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:15:43.748647+00:00
| 2023-04-19T12:34:22 |
21a6a814184cda09b1c94e4c5227eb83c7bfb371
|
{
"blob_id": "21a6a814184cda09b1c94e4c5227eb83c7bfb371",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-19T12:38:58",
"content_id": "9ed2915f845b9c090f19c4f85491053bb6bac52e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "827aaf979d1cd75d2b3cb281a98df791da072026",
"extension": "h",
"filename": "mouseclick.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 47691965,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1533,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/game/include/display/mouseclick.h",
"provenance": "stackv2-0112.json.gz:8336",
"repo_name": "tmijieux/penguins",
"revision_date": "2023-04-19T12:34:22",
"revision_id": "cf39634be2e518943cfb8a01e191d7bf26af63fa",
"snapshot_id": "d17f1c59ffe9167318c0945cf3529363b9ac231a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tmijieux/penguins/cf39634be2e518943cfb8a01e191d7bf26af63fa/game/include/display/mouseclick.h",
"visit_date": "2023-04-29T00:02:33.754985"
}
|
stackv2
|
#ifndef DISPLAY_MOUSECLICK_H
#define DISPLAY_MOUSECLICK_H
enum tile_click_outcome {
TC_SUCCESS = 0,
TC_INVALID_CLICK = -1,
TC_DISPLAY_THREAD_STOP = -2,
TC_INVALID_MOUSECLICK_STRUCT = -3,
TC_SURRENDER = -4,
};
enum mc_object_type {
MC_TILE,
MC_PENGUIN
};
struct mouseclick {
int valid_click;
enum mc_object_type object_type;
int tile_id;
int peng_id;
};
int display_mc_get(struct mouseclick *mc);
// return the id of the tile where was located the object
// that the player clicked one
// either a tile or a penguin.
void display_mc_init(int (*coord_on_tile)(double x, double z),
double z_shoes, double z_feet, double z_head);
/*
side view:
*-----------------* z_head
| |
| |
| |
| penguin |
| |
| |
| |
*-----------------* z_feet
| |
| tile |
| |
| |
*-----------------* z_shoes
top view:
tile:
*-----------------*
| X P |
| |
| X O | O is origin of the tile
| | P is any point in the world
*-----------------* pointed out by the user
coord_on_tile :
(x, z) = OP vector (projected on x and z axis)
must returns 1 if P is on tile, 0 otherwise
for an !!unscaled!! tile
*/
#endif // DISPLAY_MOUSECLICK_H
| 2.265625 | 2 |
2024-11-18T21:15:43.969519+00:00
| 2017-03-10T16:10:49 |
12b5edb54727aa8e66bf551700a4cf4919c82b60
|
{
"blob_id": "12b5edb54727aa8e66bf551700a4cf4919c82b60",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-10T16:10:49",
"content_id": "67ed33c53039b866472d872f24389ac776313221",
"detected_licenses": [
"MIT"
],
"directory_id": "08e69b0885bb3029671b28228ec33e8e78d06019",
"extension": "c",
"filename": "vfs.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": 2735,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/vfs.c",
"provenance": "stackv2-0112.json.gz:8593",
"repo_name": "metallicsoul92/mimiker",
"revision_date": "2017-03-10T16:10:49",
"revision_id": "83da55f000d4664e094bbb5de426507965de0170",
"snapshot_id": "9428a178722e533b3fd2dd92c5d722ddb97df1d1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/metallicsoul92/mimiker/83da55f000d4664e094bbb5de426507965de0170/tests/vfs.c",
"visit_date": "2020-05-21T14:18:35.829601"
}
|
stackv2
|
#include <mount.h>
#include <stdc.h>
#include <vnode.h>
#include <errno.h>
#include <vm_map.h>
#include <ktest.h>
static int test_vfs() {
vnode_t *v;
int error;
error = vfs_lookup("/dev/SPAM", &v);
ktest_assert(error == -ENOENT);
error = vfs_lookup("/usr", &v);
ktest_assert(error == -ENOENT); /* Root filesystem not implemented yet. */
error = vfs_lookup("/", &v);
ktest_assert(error == 0 && v == vfs_root_vnode);
vnode_unref(v);
error = vfs_lookup("/dev////", &v);
ktest_assert(error == 0 && v == vfs_root_dev_vnode);
vnode_unref(v);
vnode_t *dev_null, *dev_zero;
error = vfs_lookup("/dev/null", &dev_null);
ktest_assert(error == 0);
vnode_unref(dev_null);
error = vfs_lookup("/dev/zero", &dev_zero);
ktest_assert(error == 0);
vnode_unref(dev_zero);
ktest_assert(dev_zero->v_usecnt == 1);
/* Ask for the same vnode multiple times and check for correct v_usecnt. */
error = vfs_lookup("/dev/zero", &dev_zero);
ktest_assert(error == 0);
error = vfs_lookup("/dev/zero", &dev_zero);
ktest_assert(error == 0);
error = vfs_lookup("/dev/zero", &dev_zero);
ktest_assert(error == 0);
ktest_assert(dev_zero->v_usecnt == 4);
vnode_unref(dev_zero);
vnode_unref(dev_zero);
vnode_unref(dev_zero);
ktest_assert(dev_zero->v_usecnt == 1);
uio_t uio;
iovec_t iov;
int res = 0;
char buffer[100];
memset(buffer, '=', sizeof(buffer));
/* Perform a READ test on /dev/zero, cleaning buffer. */
uio.uio_op = UIO_READ;
uio.uio_vmspace = get_kernel_vm_map();
iov.iov_base = buffer;
iov.iov_len = sizeof(buffer);
uio.uio_iovcnt = 1;
uio.uio_iov = &iov;
uio.uio_offset = 0;
uio.uio_resid = sizeof(buffer);
res = VOP_READ(dev_zero, &uio);
ktest_assert(res == 0);
ktest_assert(buffer[1] == 0 && buffer[10] == 0);
ktest_assert(uio.uio_resid == 0);
/* Now write some data to /dev/null */
uio.uio_op = UIO_WRITE;
uio.uio_vmspace = get_kernel_vm_map();
iov.iov_base = buffer;
iov.iov_len = sizeof(buffer);
uio.uio_iovcnt = 1;
uio.uio_iov = &iov;
uio.uio_offset = 0;
uio.uio_resid = sizeof(buffer);
ktest_assert(dev_null != 0);
res = VOP_WRITE(dev_null, &uio);
ktest_assert(res == 0);
ktest_assert(uio.uio_resid == 0);
/* Test writing to UART */
vnode_t *dev_uart;
error = vfs_lookup("/dev/uart", &dev_uart);
ktest_assert(error == 0);
char *str = "Some string for testing UART write\n";
uio.uio_op = UIO_WRITE;
uio.uio_vmspace = get_kernel_vm_map();
iov.iov_base = str;
iov.iov_len = strlen(str);
uio.uio_iovcnt = 1;
uio.uio_iov = &iov;
uio.uio_offset = 0;
uio.uio_resid = iov.iov_len;
res = VOP_WRITE(dev_uart, &uio);
ktest_assert(res == 0);
return KTEST_SUCCESS;
}
KTEST_ADD(vfs, test_vfs, 0);
| 2.546875 | 3 |
2024-11-18T21:15:45.337456+00:00
| 2021-03-17T12:33:30 |
c18879d562b73ee236b4f3550dfff4dc324a37f9
|
{
"blob_id": "c18879d562b73ee236b4f3550dfff4dc324a37f9",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-17T12:33:30",
"content_id": "6f71a40663bdc1a318e5a1a9f15b091dbc6662e1",
"detected_licenses": [
"MIT"
],
"directory_id": "786996fa61a62f2ca06c804dec8498a9100e908c",
"extension": "c",
"filename": "gui_txt_prop.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": 9559,
"license": "MIT",
"license_type": "permissive",
"path": "/src/gui_txt_prop.c",
"provenance": "stackv2-0112.json.gz:9365",
"repo_name": "15831944/CadZinho",
"revision_date": "2021-03-17T12:33:30",
"revision_id": "86a3f1a0f6a8d21136d965e6517391d3bb3aa84e",
"snapshot_id": "31a3f1820480c902fc815dab4a83f761af083d62",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/15831944/CadZinho/86a3f1a0f6a8d21136d965e6517391d3bb3aa84e/src/gui_txt_prop.c",
"visit_date": "2023-03-20T04:39:28.764001"
}
|
stackv2
|
#include "gui_use.h"
int gui_txt_prop_interactive(gui_obj *gui){
if (gui->modal != TXT_PROP) return 0;
if (gui->step == 0) {
/* try to go to next step */
gui->step = 1;
gui->free_sel = 1;
}
/* verify if elements in selection list */
if (gui->step >= 1 && (!gui->sel_list->next || (gui->ev & EV_ADD))){
/* if selection list is empty, back to first step */
gui->step = 0;
gui->free_sel = 1;
}
if (gui->step == 0){
/* in first step, select the elements to proccess*/
gui->en_distance = 0;
gui->sel_ent_filter = DXF_TEXT | DXF_MTEXT;
gui_simple_select(gui);
/* user cancel operation */
if (gui->ev & EV_CANCEL){
gui->element = NULL;
gui_default_modal(gui);
gui->step = 0;
}
}
else if (gui->step >= 1){
gui->element = NULL;
/* user cancel operation */
if (gui->ev & EV_CANCEL){
sel_list_clear (gui);
gui_first_step(gui);
gui->step = 0;
}
}
return 1;
}
int gui_txt_prop_info (gui_obj *gui){
/* view and modify properties of TEXT entities in selection */
if (gui->modal != TXT_PROP) return 0;
static dxf_node *ent = NULL;
static char style[DXF_MAX_CHARS+1];
static int t_al_v = 0, t_al_h = 0, sty_i = 0, at_pt_i = 6;
static int en_sty = 0, en_al_v = 0, en_al_h = 0, en_h = 0, en_ang = 0, en_rec = 0;
static double txt_h, ang, rec_w;
/* alingment options */
int at_pt_h[] = {0, 1, 2, 0, 1, 2, 0, 1, 2};
int at_pt_v[] = {3, 3, 3, 2, 2, 2, 1, 1, 1};
dxf_node *tmp;
char tmp_str[DXF_MAX_CHARS+1];
int i, j, h;
nk_layout_row_dynamic(gui->ctx, 20, 1);
nk_label(gui->ctx, "Edit Text Properties", NK_TEXT_LEFT);
if (gui->step == 0){ /* get elements to edit */
nk_label(gui->ctx, "Select a element", NK_TEXT_LEFT);
}
else if (gui->step == 1){ /* init the interface */
/* get information of first element in selection list */
ent = gui->sel_list->next->data;
/* clear variables */
style[0] = 0;
t_al_v = 0;
t_al_h = 0;
txt_h = 1.0;
ang = 0.0;
at_pt_i = 6;
rec_w = 0.0;
/* try to look parameters indexes from drawing lists */
sty_i = dxf_tstyle_get(gui->drawing, ent);
if (sty_i < 0) sty_i = 0; /* error on look for style */
if(strcmp(ent->obj.name, "TEXT") == 0 ||
strcmp(ent->obj.name, "MTEXT") == 0){
/* get raw parameters directly from entity */
if(tmp = dxf_find_attr2(ent, 7))
strncpy (style, tmp->value.s_data, DXF_MAX_CHARS);
if(tmp = dxf_find_attr2(ent, 40))
txt_h = tmp->value.d_data;
if(tmp = dxf_find_attr2(ent, 50))
ang = tmp->value.d_data;
if(strcmp(ent->obj.name, "TEXT") == 0){
/* TEXT parameters */
if(tmp = dxf_find_attr2(ent, 72))
t_al_h = tmp->value.i_data;
if(tmp = dxf_find_attr2(ent, 73))
t_al_v = tmp->value.i_data;
}
else{
/* MTEXT parameters */
/* get atachment point and convert to alingment options */
if(tmp = dxf_find_attr2(ent, 71))
at_pt_i = tmp->value.i_data - 1;
if (at_pt_i > 8 || at_pt_i < 0) at_pt_i = 6;
t_al_h = at_pt_h[at_pt_i];
t_al_v = at_pt_v[at_pt_i];
/* get angle from vector */
double x = 1.0, y = 0.0;
if(tmp = dxf_find_attr2(ent, 11)){
x = tmp->value.d_data;
if (tmp = dxf_find_attr2(ent, 21))
y = tmp->value.d_data;
ang = atan2(y, x) * 180.0 / M_PI;
}
/* get rectangle width */
if(tmp = dxf_find_attr2(ent, 41))
rec_w = tmp->value.d_data;
}
}
gui->step = 2;
}
else { /* all inited */
nk_layout_row(gui->ctx, NK_STATIC, 20, 2, (float[]){60, 110});
if(strcmp(ent->obj.name, "TEXT") == 0 ||
strcmp(ent->obj.name, "MTEXT") == 0)
{ /* show entity type */
nk_label(gui->ctx, "Type:", NK_TEXT_RIGHT);
nk_label_colored(gui->ctx, ent->obj.name, NK_TEXT_LEFT, nk_rgb(255,255,0));
}
/* ---------- properties -------------*/
/* ---------- style -------------*/
nk_checkbox_label(gui->ctx, "Style:", &en_sty);
int num_tstyles = gui->drawing->num_tstyles;
dxf_tstyle *t_sty = gui->drawing->text_styles;
/* text style combo selection */
h = num_tstyles * 25 + 5;
h = (h < 200)? h : 200;
if (en_sty){ /* enable editing */
if (nk_combo_begin_label(gui->ctx, t_sty[sty_i].name, nk_vec2(220, h))){
nk_layout_row_dynamic(gui->ctx, 20, 1);
/* show available text styles in drawing */
for (j = 0; j < num_tstyles; j++){
/* skip unauthorized styles */
if (strlen(t_sty[j].name) == 0) continue;
if (nk_button_label(gui->ctx, t_sty[j].name)){
sty_i = j; /* select current style */
nk_combo_close(gui->ctx);
break;
}
}
nk_combo_end(gui->ctx);
}
}
else { /* only show information */
nk_label_colored(gui->ctx, style, NK_TEXT_LEFT, nk_rgb(255,255,0));
}
/* ----------- alignment ------------ */
/* vertical alignment */
nk_checkbox_label(gui->ctx, "Vert:", &en_al_v);
if (en_al_v){
t_al_v = nk_combo(gui->ctx, text_al_v, T_AL_V_LEN, t_al_v, 20, nk_vec2(100,105));
}
else { /* only show information */
nk_label_colored(gui->ctx, text_al_v[t_al_v], NK_TEXT_LEFT, nk_rgb(255,255,0));
}
/* horizontal alignment */
nk_checkbox_label(gui->ctx, "Horiz:", &en_al_h);
if (en_al_h){
t_al_h = nk_combo(gui->ctx, text_al_h, T_AL_H_LEN, t_al_h, 20, nk_vec2(100,105));
}
else { /* only show information */
nk_label_colored(gui->ctx, text_al_h[t_al_h], NK_TEXT_LEFT, nk_rgb(255,255,0));
}
/* ----------- text height ------------ */
nk_checkbox_label(gui->ctx, "Height:", &en_h);
if (en_h){
txt_h = nk_propertyd(gui->ctx, "#", 1.0e-9, txt_h, 1.0e9, SMART_STEP(txt_h), SMART_STEP(txt_h));
}
else {/* only show information */
snprintf(tmp_str, DXF_MAX_CHARS, "%.5g", txt_h);
nk_label_colored(gui->ctx, tmp_str, NK_TEXT_LEFT, nk_rgb(255,255,0));
}
/* ----------- angle ------------ */
nk_checkbox_label(gui->ctx, "Angle:", &en_ang);
if (en_ang){
ang = nk_propertyd(gui->ctx, "#", 0.0d, ang, 360.0d, 0.1d, 0.1d);
}
else {/* only show information */
snprintf(tmp_str, DXF_MAX_CHARS, "%.5g", ang);
nk_label_colored(gui->ctx, tmp_str, NK_TEXT_LEFT, nk_rgb(255,255,0));
}
/* ----------- rectangle width (MTEXT only) ------------ */
nk_checkbox_label(gui->ctx, "Rec W:", &en_rec);
if (en_rec){
rec_w = nk_propertyd(gui->ctx, "#", 0.0d, rec_w, 1.0e9, SMART_STEP(rec_w), SMART_STEP(rec_w));
}
else {/* only show information */
snprintf(tmp_str, DXF_MAX_CHARS, "%.5g", rec_w);
nk_label_colored(gui->ctx, tmp_str, NK_TEXT_LEFT, nk_rgb(255,255,0));
}
/* ---------------------*/
nk_layout_row_dynamic(gui->ctx, 20, 2);
if (nk_button_label(gui->ctx, "Modify") && ( en_sty || en_al_v || en_al_h || en_h || en_ang || en_rec)){
/* change selection properties according selected parameters */
if (gui->sel_list != NULL){
int ini_do = 0;
/* sweep the selection list */
list_node *current = gui->sel_list->next;
dxf_node *new_ent = NULL;
while (current != NULL){
if (current->data){
/* check type of current entity */
if(strcmp(((dxf_node *)current->data)->obj.name, "TEXT") == 0 ||
strcmp(((dxf_node *)current->data)->obj.name, "MTEXT") == 0){
/* copy current entity to preserve information to undo */
new_ent = dxf_ent_copy((dxf_node *)current->data, 0);
/* change properties according options */
if (en_sty) dxf_attr_change(new_ent, 7, gui->drawing->text_styles[sty_i].name);
if (en_ang) dxf_attr_change(new_ent, 50, &ang);
if (en_h) dxf_attr_change(new_ent, 40, &txt_h);
if(strcmp(new_ent->obj.name, "TEXT") == 0){
if (en_al_h) dxf_attr_change(new_ent, 72, &t_al_h);
if (en_al_v) dxf_attr_change(new_ent, 73, &t_al_v);
}
else {
if (en_al_h || en_al_v) {
/* alingment options to attach point */
int al_h = (t_al_h < 3 && t_al_h >= 0)? t_al_h : 0;
int al_v = (t_al_v < 4 && t_al_v > 0)? t_al_v : 1;
int attch_pt = (3 - al_v) * 3 + al_h + 1;
dxf_attr_change(new_ent, 71, &attch_pt);
}
if (en_ang){
/* angle to vector */
double x = cos(ang * M_PI / 180.0);
double y = sin(ang * M_PI / 180.0);
dxf_attr_change(new_ent, 11, &x);
dxf_attr_change(new_ent, 21, &y);
}
/* rectangle width */
if (en_rec) dxf_attr_change(new_ent, 40, &rec_w);
}
/* update in drawing */
new_ent->obj.graphics = dxf_graph_parse(gui->drawing, new_ent, 0 , DWG_LIFE);
dxf_obj_subst((dxf_node *)current->data, new_ent);
/* update undo/redo list */
if (!ini_do){
do_add_entry(&gui->list_do, "CHANGE TEXT PROPERTIES"); /* init do/undo list */
gui->step = 1;
ini_do = 1;
}
do_add_item(gui->list_do.current, (dxf_node *)current->data, new_ent);
current->data = new_ent;
}
}
current = current->next;
}
}
gui->draw = 1;
}
if (nk_button_label(gui->ctx, "Pick")){
/* get selected entity properties to match main tools (place text tools) */
if (en_sty) gui->t_sty_idx = sty_i;
if (en_h) gui->txt_h = txt_h;
if (en_al_v) gui->t_al_v = t_al_v;
if (en_al_h) gui->t_al_h = t_al_h;
if (en_ang) gui->angle = ang;
if (en_rec) gui->rect_w = rec_w;
}
}
return 1;
}
| 2.265625 | 2 |
2024-11-18T21:15:45.418905+00:00
| 2017-10-02T23:12:40 |
c8a679967a4f6f60ebf25b08a9daf18061dd4012
|
{
"blob_id": "c8a679967a4f6f60ebf25b08a9daf18061dd4012",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-02T23:12:40",
"content_id": "877af0791c7c5b29e7c624642599e7c7ad0c3d39",
"detected_licenses": [
"Zlib"
],
"directory_id": "aebf2fa2eea05024d8d843d7029107e51d5d9383",
"extension": "c",
"filename": "macro.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 34886887,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7898,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/macro.c",
"provenance": "stackv2-0112.json.gz:9493",
"repo_name": "goodpaul6/mint-lang",
"revision_date": "2017-10-02T23:12:40",
"revision_id": "138e66b786301f772387a268727a9d6489f12380",
"snapshot_id": "604331e8de5500c24758f12bcb608a3ddc24a2ee",
"src_encoding": "UTF-8",
"star_events_count": 20,
"url": "https://raw.githubusercontent.com/goodpaul6/mint-lang/138e66b786301f772387a268727a9d6489f12380/src/macro.c",
"visit_date": "2018-10-10T11:39:53.354801"
}
|
stackv2
|
// macro.c -- compile time execution module in mint
#include "lang.h"
#include "linkedlist.h"
#include "vm.h"
char CompilingMacros = 0;
struct
{
int line;
const char* file;
int varScope;
FuncDecl* funcDecl;
} Context;
// TODO: This shouldn't be global
static Expr* NextExpr;
LinkedList MacroList;
static void RecordMacro(Expr** pExp)
{
Expr* exp = *pExp;
switch(exp->type)
{
case EXP_CALL:
{
for(int i = 0; i < exp->callx.numArgs; ++i)
RecordMacro(&exp->callx.args[i]);
} break;
case EXP_MACRO_CALL:
{
// later on just replace the pointer at the address with the result of the macro
AddNode(&MacroList, pExp);
} break;
case EXP_BIN:
{
RecordMacro(&exp->binx.lhs);
RecordMacro(&exp->binx.rhs);
} break;
case EXP_PAREN:
{
RecordMacro(&exp->parenExpr);
} break;
case EXP_WHILE:
{
Expr** node = &exp->whilex.bodyHead;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
} break;
case EXP_FUNC:
{
Expr** node = &exp->funcx.bodyHead;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
} break;
case EXP_IF:
{
RecordMacro(&exp->ifx.cond);
Expr** node = &exp->ifx.bodyHead;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
if(exp->ifx.alt)
{
if(exp->ifx.alt->type == EXP_IF)
RecordMacro(&exp->ifx.alt);
else
{
node = &exp->ifx.alt;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
}
}
} break;
case EXP_RETURN:
{
RecordMacro(&exp->retx.exp);
} break;
case EXP_ARRAY_LITERAL:
{
Expr** node = &exp->arrayx.head;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
} break;
case EXP_UNARY:
{
RecordMacro(&exp->unaryx.expr);
} break;
case EXP_FOR:
{
RecordMacro(&exp->forx.init);
RecordMacro(&exp->forx.cond);
RecordMacro(&exp->forx.iter);
Expr** node = &exp->forx.bodyHead;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
} break;
case EXP_DICT_LITERAL:
{
Expr** node = &exp->dictx.pairsHead;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
} break;
case EXP_LAMBDA:
{
Expr** node = &exp->lamx.bodyHead;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
} break;
default:
break;
}
}
#define SET_CONTEXT FuncDecl* prevFunc = CurFunc; \
int prevLine = LineNumber; \
const char* prevFile = FileName; \
CurFunc = Context.funcDecl; \
LineNumber = Context.line; \
FileName = Context.file; \
VarScope = Context.varScope;
#define UNSET_CONTEXT CurFunc = prevFunc; \
LineNumber = prevLine; \
FileName = prevFile; \
VarScope = 0;
// TODO: Move these to the vm's standard library (perhaps)
static void Macro_MultiExpr(VM* vm)
{
SET_CONTEXT
Object* obj = PopArrayObject(vm);
Expr* exp = CreateExpr(EXP_MULTI);
Expr* node = NULL;
for(int i = 0; i < obj->array.length; ++i)
{
if(obj->array.members[i]->type != OBJ_NATIVE)
ErrorExitVM(vm, "Invalid expression in array argument to 'macro_multi'\n");
if(!node)
{
exp->multiHead = obj->array.members[i]->native.value;
node = exp->multiHead;
}
else
{
node->next = obj->array.members[i]->native.value;
node = node->next;
}
}
PushNative(vm, exp, NULL, NULL);
ReturnTop(vm);
UNSET_CONTEXT
}
static void Macro_NumExpr(VM* vm)
{
SET_CONTEXT
Expr* exp = CreateExpr(EXP_NUMBER);
exp->constDecl = RegisterNumber(PopNumber(vm));
PushNative(vm, exp, NULL, NULL);
ReturnTop(vm);
UNSET_CONTEXT
}
static void Macro_StrExpr(VM* vm)
{
SET_CONTEXT
Expr* exp = CreateExpr(EXP_STRING);
exp->constDecl = RegisterString(PopString(vm));
PushNative(vm, exp, NULL, NULL);
ReturnTop(vm);
UNSET_CONTEXT
}
static void Macro_DeclareVariable(VM* vm)
{
SET_CONTEXT
const char* string = PopString(vm);
VarDecl* decl = ReferenceVariable(string);
if(!decl)
decl = DeclareVariable(string);
else
ErrorExitVM(vm, "Attempted to declare previously existing variable '%s'\n", string);
printf("declared variable '%s' at scope %i\n", decl->name, decl->scope);
PushNative(vm, decl, NULL, NULL);
ReturnTop(vm);
UNSET_CONTEXT
}
static void Macro_ReferenceVariable(VM* vm)
{
SET_CONTEXT
const char* string = PopString(vm);
VarDecl* decl = ReferenceVariable(string);
if(!decl)
{
PushNull(vm);
ReturnTop(vm);
return;
}
PushNative(vm, decl, NULL, NULL);
ReturnTop(vm);
UNSET_CONTEXT
}
static void Macro_IdentExpr(VM* vm)
{
SET_CONTEXT
VarDecl* decl = PopNative(vm);
Expr* exp = CreateExpr(EXP_IDENT);
strcpy(exp->varx.name, decl->name);
exp->varx.varDecl = decl;
PushNative(vm, exp, NULL, NULL);
ReturnTop(vm);
UNSET_CONTEXT
}
static void Macro_BinExpr(VM* vm)
{
SET_CONTEXT
const char* op = PopString(vm);
Expr* lhs = PopNative(vm);
Expr* rhs = PopNative(vm);
Expr* exp = CreateExpr(EXP_BIN);
exp->binx.lhs = lhs;
exp->binx.rhs = rhs;
// TODO: add more operators
if(strcmp(op, "+") == 0) exp->binx.op = '+';
else if(strcmp(op, "-") == 0) exp->binx.op = '-';
else if(strcmp(op, "*") == 0) exp->binx.op = '*';
else if(strcmp(op, "/") == 0) exp->binx.op = '/';
else if(strcmp(op, "=") == 0) exp->binx.op = '=';
else; // TODO: Fail
PushNative(vm, exp, NULL, NULL);
ReturnTop(vm);
UNSET_CONTEXT
}
static void SetExprContext(VM* vm, Expr* exp)
{
Context.line = exp->line;
Context.file = exp->file;
Context.varScope = exp->varScope;
Context.funcDecl = exp->curFunc;
}
void ExecuteMacros(Expr** exp)
{
InitList(&MacroList);
Expr** node = exp;
while(*node)
{
RecordMacro(node);
node = &(*node)->next;
}
if(MacroList.length > 0)
{
CompilingMacros = 1;
CompileExprList(*exp);
CompilingMacros = 0;
AppendCode(OP_HALT);
VM* vm = NewVM();
FILE* tmp = tmpfile();
if(!tmp)
ErrorExitE(*exp, "Failed to create temporary file to store code for compile-time execution\n");
OutputCode(tmp);
rewind(tmp);
LoadBinaryFile(vm, tmp);
fclose(tmp);
HookStandardLibrary(vm);
HookExternNoWarn(vm, "macro_multi", Macro_MultiExpr);
HookExternNoWarn(vm, "macro_num_expr", Macro_NumExpr);
HookExternNoWarn(vm, "macro_str_expr", Macro_StrExpr);
HookExternNoWarn(vm, "macro_declare_variable", Macro_DeclareVariable);
HookExternNoWarn(vm, "macro_reference_variable", Macro_ReferenceVariable);
HookExternNoWarn(vm, "macro_ident_expr", Macro_IdentExpr);
HookExternNoWarn(vm, "macro_bin_expr", Macro_BinExpr);
for(LinkedListNode* node = MacroList.head; node != NULL; node = node->next)
{
Expr** pNodeExp = node->data;
Expr* nodeExp = *pNodeExp;
NextExpr = nodeExp->next;
// NOTE: This assumes that exp->callx.func is an EXP_IDENT
FuncDecl* decl = ReferenceFunction(nodeExp->callx.func->varx.name);
if(!decl)
ErrorExitE(nodeExp, "Attempted to call non-existent function '%s' at compile time\n", nodeExp->callx.func->varx.name);
vm->thread->pc = nodeExp->pc;
SetExprContext(vm, nodeExp);
printf("ctx line: %i\n", Context.line);
printf("ctx file: %s\n", Context.file);
printf("ctx scope: %i\n", Context.varScope);
// all macro call code ends in an OP_HALT
while(vm->thread->pc >= 0)
ExecuteCycle(vm);
if(decl->hasReturn > 0)
{
if(!vm->thread->retVal || vm->thread->retVal->type != OBJ_NATIVE)
ErrorExitE(nodeExp, "Compile-time function '%s' has invalid resulting value\n", nodeExp->callx.func->varx.name);
Expr* exp = vm->thread->retVal->native.value;
exp->next = NextExpr;
*pNodeExp = exp;
printf("'%s' generated expression of type: %s\n", decl->name, ExprNames[exp->type]);
if(exp->type == EXP_BIN)
printf("'%c'\n", exp->binx.op);
}
}
DeleteVM(vm);
}
ClearCode();
}
| 2.140625 | 2 |
2024-11-18T21:15:45.531533+00:00
| 2023-07-08T04:45:35 |
98283916d7c8860c7c200fc31e8e67d25b9cab8a
|
{
"blob_id": "98283916d7c8860c7c200fc31e8e67d25b9cab8a",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-08T04:45:35",
"content_id": "521a848071c330fc2ca22bbb58b0a6fa3089d1a5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9075cb735dbf69029840b2f8b83d17e5241fa726",
"extension": "c",
"filename": "stdio.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76154918,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2041,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/minilibc/stdio.c",
"provenance": "stackv2-0112.json.gz:9622",
"repo_name": "Grissess/tinylisp",
"revision_date": "2023-07-08T04:45:35",
"revision_id": "a077767c82b6e5eea5a6517467f587b8cdbb5c8c",
"snapshot_id": "e1bc9f07e5d302df1183be4c7a76e1eb656758cc",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Grissess/tinylisp/a077767c82b6e5eea5a6517467f587b8cdbb5c8c/minilibc/stdio.c",
"visit_date": "2023-07-09T20:20:56.447866"
}
|
stackv2
|
#include "stdio.h"
#include "string.h"
#include "arch.h"
#include <stdarg.h>
FILE *stdin = (FILE *) 1, *stdout = (FILE *) 2, *stderr = (FILE *) 3;
void fflush(FILE *f) {
arch_fflush((unsigned long) f);
}
int fputc(int c, FILE *f) {
arch_fputc((unsigned long) f, c);
return c;
}
int fgetc(FILE *f) {
return arch_fgetc((unsigned long) f);
}
int fputs(const char *s, FILE *f) {
while(*s) arch_fputc((unsigned long) f, *s++);
return 0;
}
int puts(const char *s) {
fputs(s, stdout);
putchar('\n');
return 0;
}
size_t fwrite(const void *p, size_t s, size_t n, FILE *f) {
size_t c, r = n;
const unsigned char *d = p;
while(n--) for(c = 0; c < s; c++) arch_fputc((unsigned long) f, *d++);
return r;
}
size_t fread(void *p, size_t s, size_t n, FILE *f) {
size_t c, r = n;
unsigned char *d = p;
while(n--) for(c = 0; c < s; c++) *d++ = arch_fgetc((unsigned long) f);
return r;
}
FILE *fopen(const char *name, const char *mode) {
if(!strcmp(name, "/dev/stdin") && *mode == 'r') return stdin;
if(!strcmp(name, "/dev/stdout") && *mode == 'w') return stdout;
if(!strcmp(name, "/dev/stderr") && *mode == 'w') return stderr;
return NULL;
}
int fclose(FILE *fp) { return 0; }
#define VXP_NAME vsnprintf
#define VXP_ARGS char *s, size_t sz,
/* Don't return early on fill; we're depending on an accurate cnt
* Also beware the careful unsigned comparison when sz == 0
*/
#define VXP_PUTC(c) do {\
if(cnt + 1 >= sz) {\
if(sz && s) s[cnt] = 0;\
} else if(s) s[cnt] = (c);\
} while(0)
#define VXP_DONE if(s && sz && cnt < sz) s[cnt] = 0
#include "vxprintf_impl.c"
#define VXP_NAME vfprintf
#define VXP_ARGS FILE *f,
#define VXP_PUTC(c) arch_fputc((unsigned long) f, (c))
#define VXP_DONE
#include "vxprintf_impl.c"
int snprintf(char *s, size_t sz, const char *fmt, ...) {
va_list ap;
int res;
va_start(ap, fmt);
res = vsnprintf(s, sz, fmt, ap);
va_end(ap);
return res;
}
int fprintf(FILE *f, const char *fmt, ...) {
va_list ap;
int res;
va_start(ap, fmt);
res = vfprintf(f, fmt, ap);
va_end(ap);
return res;
}
| 2.640625 | 3 |
2024-11-18T21:15:45.643964+00:00
| 2023-02-16T11:27:40 |
286dafb4e6f62aef704a2136a5b5da76d1f3f38a
|
{
"blob_id": "286dafb4e6f62aef704a2136a5b5da76d1f3f38a",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "f658bdd0bfb07b8ad09bb1a233732ae6963a6481",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "c",
"filename": "settings_store.c",
"fork_events_count": 32,
"gha_created_at": "2016-08-05T22:14:50",
"gha_event_created_at": "2022-04-05T17:14:07",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 65052293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3378,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/subsys/settings/src/settings_store.c",
"provenance": "stackv2-0112.json.gz:9752",
"repo_name": "intel/zephyr",
"revision_date": "2023-02-16T11:27:40",
"revision_id": "06d5bc51b580777079bb0b7e769e4127598ea5ee",
"snapshot_id": "819362089aa44ae378a5558f3b222197aaa811f7",
"src_encoding": "UTF-8",
"star_events_count": 32,
"url": "https://raw.githubusercontent.com/intel/zephyr/06d5bc51b580777079bb0b7e769e4127598ea5ee/subsys/settings/src/settings_store.c",
"visit_date": "2023-09-04T00:20:35.217393"
}
|
stackv2
|
/*
* Copyright (c) 2018 Nordic Semiconductor ASA
* Copyright (c) 2015 Runtime Inc
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdio.h>
#include <zephyr/types.h>
#include <stddef.h>
#include <sys/types.h>
#include <errno.h>
#include <zephyr/kernel.h>
#include <zephyr/settings/settings.h>
#include "settings_priv.h"
#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(settings, CONFIG_SETTINGS_LOG_LEVEL);
sys_slist_t settings_load_srcs;
struct settings_store *settings_save_dst;
extern struct k_mutex settings_lock;
void settings_src_register(struct settings_store *cs)
{
sys_slist_append(&settings_load_srcs, &cs->cs_next);
}
void settings_dst_register(struct settings_store *cs)
{
settings_save_dst = cs;
}
int settings_load(void)
{
return settings_load_subtree(NULL);
}
int settings_load_subtree(const char *subtree)
{
struct settings_store *cs;
int rc;
const struct settings_load_arg arg = {
.subtree = subtree
};
/*
* for every config store
* load config
* apply config
* commit all
*/
k_mutex_lock(&settings_lock, K_FOREVER);
SYS_SLIST_FOR_EACH_CONTAINER(&settings_load_srcs, cs, cs_next) {
cs->cs_itf->csi_load(cs, &arg);
}
rc = settings_commit_subtree(subtree);
k_mutex_unlock(&settings_lock);
return rc;
}
int settings_load_subtree_direct(
const char *subtree,
settings_load_direct_cb cb,
void *param)
{
struct settings_store *cs;
const struct settings_load_arg arg = {
.subtree = subtree,
.cb = cb,
.param = param
};
/*
* for every config store
* load config
* apply config
* commit all
*/
k_mutex_lock(&settings_lock, K_FOREVER);
SYS_SLIST_FOR_EACH_CONTAINER(&settings_load_srcs, cs, cs_next) {
cs->cs_itf->csi_load(cs, &arg);
}
k_mutex_unlock(&settings_lock);
return 0;
}
/*
* Append a single value to persisted config. Don't store duplicate value.
*/
int settings_save_one(const char *name, const void *value, size_t val_len)
{
int rc;
struct settings_store *cs;
cs = settings_save_dst;
if (!cs) {
return -ENOENT;
}
k_mutex_lock(&settings_lock, K_FOREVER);
rc = cs->cs_itf->csi_save(cs, name, (char *)value, val_len);
k_mutex_unlock(&settings_lock);
return rc;
}
int settings_delete(const char *name)
{
return settings_save_one(name, NULL, 0);
}
int settings_save(void)
{
struct settings_store *cs;
int rc;
int rc2;
cs = settings_save_dst;
if (!cs) {
return -ENOENT;
}
if (cs->cs_itf->csi_save_start) {
cs->cs_itf->csi_save_start(cs);
}
rc = 0;
STRUCT_SECTION_FOREACH(settings_handler_static, ch) {
if (ch->h_export) {
rc2 = ch->h_export(settings_save_one);
if (!rc) {
rc = rc2;
}
}
}
#if defined(CONFIG_SETTINGS_DYNAMIC_HANDLERS)
struct settings_handler *ch;
SYS_SLIST_FOR_EACH_CONTAINER(&settings_handlers, ch, node) {
if (ch->h_export) {
rc2 = ch->h_export(settings_save_one);
if (!rc) {
rc = rc2;
}
}
}
#endif /* CONFIG_SETTINGS_DYNAMIC_HANDLERS */
if (cs->cs_itf->csi_save_end) {
cs->cs_itf->csi_save_end(cs);
}
return rc;
}
int settings_storage_get(void **storage)
{
struct settings_store *cs = settings_save_dst;
if (!cs) {
return -ENOENT;
}
if (cs->cs_itf->csi_storage_get) {
*storage = cs->cs_itf->csi_storage_get(cs);
}
return 0;
}
void settings_store_init(void)
{
sys_slist_init(&settings_load_srcs);
}
| 2.171875 | 2 |
2024-11-18T21:15:45.742053+00:00
| 2023-09-01T22:44:04 |
8b57c90260cbd9b94297e3f614553436a035277b
|
{
"blob_id": "8b57c90260cbd9b94297e3f614553436a035277b",
"branch_name": "refs/heads/main",
"committer_date": "2023-09-01T22:44:04",
"content_id": "d8aab68b2bb4a400711725612297a6047f066635",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e7df6d41d7e04dc1c4f4ed169bf530a8a89ff17c",
"extension": "c",
"filename": "readtools.c",
"fork_events_count": 328,
"gha_created_at": "2014-06-12T16:57:56",
"gha_event_created_at": "2023-09-14T17:45:19",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 20775600,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 67649,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/OpenSim/Utilities/simmToOpenSim/readtools.c",
"provenance": "stackv2-0112.json.gz:9880",
"repo_name": "opensim-org/opensim-core",
"revision_date": "2023-09-01T22:44:04",
"revision_id": "aeaaf93b052d598247dd7d7922fdf8f2f2f4c0bb",
"snapshot_id": "2ba11c815df3072166644af2f34770162d8fc467",
"src_encoding": "UTF-8",
"star_events_count": 701,
"url": "https://raw.githubusercontent.com/opensim-org/opensim-core/aeaaf93b052d598247dd7d7922fdf8f2f2f4c0bb/OpenSim/Utilities/simmToOpenSim/readtools.c",
"visit_date": "2023-09-04T05:50:54.783630"
}
|
stackv2
|
/*******************************************************************************
READTOOLS.C
Author: Peter Loan
Date: 8-DEC-88
Copyright (c) 1992-5 MusculoGraphics, Inc.
All rights reserved.
Portions of this source code are copyrighted by MusculoGraphics, Inc.
Description: This file contains tools for reading ascii text from
input files, and for extracting numbers and strings from the text.
Routines:
preprocess_file : runs cpp on a file, then opens it
read_string : reads a string from a file
read_nonempty_line : reads a non-empty line of characters from a file
read_line : reads a possibly empty line from a file
get_groups : reads a set of muscle group names from muscle input file
getcoords : reads muscle points from the muscle input file
getdoublearray : reads an array of x-y pairs from a file
check_for_closing_paren :
get_xy_pair_from_string : reads x-y pair, format: ( 0.00 , 0.00 )
getintpair : reads a pair of integers from a file, format: ( 0 , 0 )
parse_string : parses a string using the specified format (%s, %f, ...)
get_stringpair : reads a pair of text strings from a file
name_is_gencoord : checks to see if a name is a gencoord name
*******************************************************************************/
#include <ctype.h>
#include <assert.h>
#include <stdarg.h>
#include "universal.h"
#include "globals.h"
#include "functions.h"
#include "defunctions.h"
/*************** DEFINES (for this file only) *********************************/
/*************** STATIC GLOBAL VARIABLES (for this file only) *****************/
/*************** GLOBAL VARIABLES (used in only a few files) ******************/
char natural_cubic_text[] = "_spl";
char gcv_text[] = "_gcv";
char linear_text[] = "_lin";
/*************** EXTERNED VARIABLES (declared in another file) ****************/
/*************** PROTOTYPES for STATIC FUNCTIONS (for this file only) *********/
static SBoolean string_contains_closing_paren(char str_buffer[]);
static char* get_xypair_from_string(char str_buffer[], double* x, double* y);
static char* parse_string(char str_buffer[], VariableType var_type,
void* dest_var);
static void acpp(char in_file[], const char out_file[]);
/* PREPROCESS_FILE: this routine runs the C preprocessor on the specified
* input file, putting the output in the specified output file. It then
* opens the processed file and returns a pointer to a FILE structure for it.
*/
FILE* preprocess_file(char infile[], const char outfile[])
{
FILE* fp;
if (file_exists(infile) == no)
return NULL;
acpp(infile, outfile);
#ifndef WIN32
/* Change the protections so that anyone can overwrite this temporary file.
* Technically this is not needed, because the file is deleted right after
* it is closed, but I'm leaving it here anyway in case the file is not
* deleted properly.
*/
chmod(outfile, 438);
#endif
fp = simm_fopen(outfile, "r");
if (fp == NULL)
perror("Unable to open acpp output");
return fp;
}
/* READ_STRING: this routine reads a character string from a file. It skips over
* any white space at the beginning, and returns EOF if it hits the end of
* the file before completing the string.
*/
int read_string(FILE* fp, char str_buffer[])
{
int c;
// Scan thru white space until you find the first character in the string.
while (1)
{
c = getc(fp);
if (c == EOF)
return EOF;
*str_buffer = c;
if (CHAR_IS_NOT_WHITE_SPACE(*str_buffer))
break;
}
str_buffer++;
// Now read characters until you find white space or EOF.
while (1)
{
c = getc(fp);
if (c == EOF)
return EOF;
*str_buffer = c;
if (CHAR_IS_WHITE_SPACE(*str_buffer))
break;
str_buffer++;
}
// Null-terminate the string.
*str_buffer = STRING_TERMINATOR;
// You found a valid string without hitting EOF, so return a value that you
// know will never equal EOF, no matter how EOF is defined.
return EOF + 1;
}
/* READ_LINE: reads a line (possibly empty) from a file */
int read_line(FILE* fp, char str_buffer[])
{
int c;
/* Read characters until you hit a carriage return or EOF */
while (1)
{
c = getc(fp);
if (c == EOF)
return EOF;
*str_buffer = c;
if (c == LINE_FEED)
break;
if (*str_buffer == CARRIAGE_RETURN)
break;
str_buffer++;
}
/* Null-terminate the string */
*str_buffer = STRING_TERMINATOR;
/* You found a valid line without hitting EOF, so return a value that you
* know will never equal EOF, no matter how EOF is defined.
*/
return EOF + 1;
}
/* COUNTTOKENS: returns the number of tokens in the string. */
int countTokens(char str[])
{
int count = 0, previousWasSeparator = 1;
char* p = str;
while (*p != STRING_TERMINATOR)
{
if (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
{
previousWasSeparator = 1;
}
else
{
if (previousWasSeparator)
count++;
previousWasSeparator = 0;
}
p++;
}
return count;
}
/* READ_NONEMPTY_LINE: Reads the first non-empty line from a file. */
int read_nonempty_line(FILE* fp, char str_buffer[])
{
int c;
*str_buffer = STRING_TERMINATOR;
// Scan thru the white space until you find the first character.
while (1)
{
c = getc(fp);
if (c == EOF)
return EOF;
*str_buffer = c;
if (*str_buffer != SPACE && *str_buffer != TAB &&
*str_buffer != CARRIAGE_RETURN && *str_buffer != '\r' && c != LINE_FEED)
break;
}
str_buffer++;
// Now read characters until you find a carriage return or EOF.
while (1)
{
c = getc(fp);
if (c == EOF)
{
*str_buffer = STRING_TERMINATOR;
return EOF;
}
*str_buffer = c;
if (*str_buffer == CARRIAGE_RETURN || c == LINE_FEED)
break;
str_buffer++;
}
*str_buffer = STRING_TERMINATOR;
// You found a valid line without hitting EOF, so return a value that you
// know will never equal EOF, no matter how EOF is defined.
return EOF + 1;
}
/* READ_MUSCLE_GROUPS: This routine reads names of muscle groups from a file
* until the string "endgroups" is found. For each name it reads, it enters the
* name into the group-name database for the model. It then stores the
* database-index of this name in an array of muscle-group indices for this
* muscle. When done, this routine returns the array of group indices.
*/
int* read_muscle_groups(ModelStruct* ms, FILE* fp, int* num_groups, int muscle_number)
{
int num_malloced_so_far = 50;
int* group_indices;
ReturnCode rc = code_fine;
*num_groups = 0;
group_indices = (int*)simm_malloc(num_malloced_so_far*sizeof(int));
if (group_indices == NULL)
return NULL;
while (1)
{
if (fscanf(fp, "%s", buffer) != 1)
return NULL;
if (STRINGS_ARE_EQUAL(buffer, "endgroups"))
{
// rc should be code_fine since you're reallocing a smaller size.
group_indices = (int*)simm_realloc(group_indices, (*num_groups)*sizeof(int), &rc);
return group_indices;
}
if (STRINGS_ARE_EQUAL(buffer, "all"))
{
error(none,"You cannot define a muscle group named \"all.\"");
error(none,"SIMM automatically creates a muscle group containing all muscles.");
}
else
{
int i, groupIndex = enter_muscle_group(ms, buffer, muscle_number);
if (groupIndex == -1)
return NULL;
// Make sure this group has not already been specified for this muscle.
for (i=0; i<*num_groups; i++)
{
if (groupIndex == group_indices[i])
break;
}
if (i == *num_groups)
{
if (*num_groups > num_malloced_so_far)
{
num_malloced_so_far += 50;
group_indices = (int*)simm_realloc(group_indices, num_malloced_so_far*sizeof(int), &rc);
if (rc == code_bad)
return NULL;
}
group_indices[*num_groups] = groupIndex;
(*num_groups)++;
}
}
}
return NULL;
}
/* READ_MUSCLE_PATH: this routine reads muscle attachment points
* from a file. It keeps reading from the file until the string "endpoints"
* is encountered. It initially mallocs space for some points, and if it
* fills up that space and finds more points, it reallocs the muscle point
* array so that it can add the additional points.
*/
ReturnCode read_muscle_path(ModelStruct* ms, FILE* fp, dpMusclePathStruct* path)
{
int numpoints, function_num;
dpMusclePoint* mp;
char *line;
char gencoord_name[CHARBUFFER], line2[CHARBUFFER], segment_name[CHARBUFFER], com[CHARBUFFER];
double range1, range2;
ReturnCode rc = code_fine;
// initialize the muscle path
if (initMusclePath(path) == code_bad)
return code_bad;
numpoints = 0;
while (1)
{
if (fscanf(fp, "%s", buffer) != 1)
{
error(none, "End of file reached while reading muscle attachment points");
return code_bad;
}
if (STRINGS_ARE_EQUAL(buffer, "endpoints"))
{
path->num_orig_points = numpoints;
return code_fine;
}
/* Check to see if you need to increase the size of the muscle-point
* array before reading any more points.
*/
if (numpoints >= path->mp_orig_array_size)
{
path->mp_orig_array_size += MUSCLEPOINT_ARRAY_INCREMENT;
path->mp_orig = (dpMusclePoint*)simm_realloc(path->mp_orig,
path->mp_orig_array_size*sizeof(dpMusclePoint),&rc);
if (rc == code_bad)
{
path->mp_orig_array_size -= MUSCLEPOINT_ARRAY_INCREMENT;
return rc;
}
}
mp = &path->mp_orig[numpoints];
// initialize the point
init_musclepoint(mp);
/* If the string you just read was not "endpoints" then it must
* be the start of a new point (so it's the x-coordinate), either
* a number (e.g. "0.0346"), or a function (e.g. "f2(gencoord_name)").
*/
if (sscanf(buffer,"%lg", &mp->point[XX]) != 1)
{
if (sscanf(buffer, "f%d%s", &function_num, gencoord_name) != 2)
return code_bad;
strip_brackets_from_string(gencoord_name);
mp->function[XX] = ms->function[enter_function(ms, function_num, yes)];
mp->gencoord[XX] = enter_gencoord(ms, gencoord_name, no);
mp->isMovingPoint = yes;
if (mp->gencoord[XX] == NULL)
{
(void)sprintf(errorbuffer, "Gencoord %s referenced in muscle file but not defined in joint file.", gencoord_name);
error(none,errorbuffer);
return code_bad;
}
if (mp->function[XX] == NULL)
{
(void)sprintf(errorbuffer, "Function %d referenced in muscle file but not defined in joint or muscle file.", function_num);
error(none,errorbuffer);
return code_bad;
}
}
(void)read_nonempty_line(fp,line2);
/* Read the y coordinate or function */
line = parse_string(line2,type_string,(void*)buffer);
if (sscanf(buffer,"%lg", &mp->point[YY]) != 1)
{
if (sscanf(buffer,"f%d%s", &function_num, gencoord_name) != 2)
return code_bad;
strip_brackets_from_string(gencoord_name);
mp->function[YY] = ms->function[enter_function(ms, function_num, yes)];
mp->gencoord[YY] = enter_gencoord(ms, gencoord_name, no);
mp->isMovingPoint = yes;
if (mp->gencoord[YY] == NULL)
{
(void)sprintf(errorbuffer, "Gencoord %s referenced in muscle file but not defined in joint file.", gencoord_name);
error(none,errorbuffer);
return code_bad;
}
if (mp->function[YY] == NULL)
{
(void)sprintf(errorbuffer, "Function %d referenced in muscle file but not defined in joint or muscle file.", function_num);
error(none,errorbuffer);
return code_bad;
}
}
else
{
if (mp->point[YY] == ERROR_DOUBLE)
return code_bad;
}
/* Read the z coordinate or function */
line = parse_string(line,type_string,(void*)buffer);
if (sscanf(buffer,"%lg", &mp->point[ZZ]) != 1)
{
if (sscanf(buffer,"f%d%s", &function_num, gencoord_name) != 2)
return code_bad;
strip_brackets_from_string(gencoord_name);
mp->function[ZZ] = ms->function[enter_function(ms, function_num, yes)];
mp->gencoord[ZZ] = enter_gencoord(ms, gencoord_name, no);
mp->isMovingPoint = yes;
if (mp->function[ZZ] == NULL)
{
(void)sprintf(errorbuffer, "Function %d referenced in muscle file but not defined in joint file.", function_num);
error(none,errorbuffer);
return code_bad;
}
if (mp->gencoord[ZZ] == NULL)
{
(void)sprintf(errorbuffer, "Gencoord %s referenced in muscle file but not defined in joint or muscle file.", gencoord_name);
error(none,errorbuffer);
return code_bad;
}
}
else
{
if (mp->point[ZZ] == ERROR_DOUBLE)
return code_bad;
}
/* read the keyword "segment" */
line = parse_string(line,type_string,(void*)buffer);
/* read the segment name */
line = parse_string(line,type_string,(void*)segment_name);
if (segment_name == NULL)
return code_bad;
/* read a string from the leftover part of the line. For most points,
* the leftover will be NULL. For wrapping points, the first string
* in the leftover should be "range".
*/
line = parse_string(line,type_string,(void*)com);
if (STRINGS_ARE_EQUAL(com,"range")) // new keyword
{
line = parse_string(line,type_string,(void*)gencoord_name);
if (gencoord_name == NULL || name_is_gencoord(gencoord_name, ms, NULL, NULL, NULL, no) == NULL)
{
return code_bad;
}
line = get_xypair_from_string(line, &range1, &range2);
if (line == NULL)
{
return code_bad;
}
else
{
mp->viaRange.start = _MIN(range1, range2);
mp->viaRange.end = _MAX(range1, range2);
}
mp->viaRange.gencoord = enter_gencoord(ms, gencoord_name, no);
if (mp->viaRange.gencoord == NULL)
{
(void)sprintf(errorbuffer,"Gencoord %s referenced in muscle file but not defined in joints file.", gencoord_name);
error(none,errorbuffer);
return code_bad;
}
mp->isVia = yes;
}
// support old files
if (STRINGS_ARE_EQUAL(com,"ranges"))
{
int i, temp = 0;
line = parse_string(line, type_int, (void*)&temp);
if (temp <= 0)
{
error(none,"The number of ranges must be greater than 0.");
return code_bad;
}
if (temp > 1)
{
error(none,"Multiple ranges no longer supported.");
return code_bad;
}
for (i=0; i<temp; i++)
{
line = parse_string(line,type_string,(void*)gencoord_name);
if (gencoord_name == NULL || name_is_gencoord(gencoord_name, ms, NULL, NULL, NULL, no) == NULL)
{
(void)sprintf(errorbuffer,"Gencoord %s referenced in muscle file but not defined in joints file.", gencoord_name);
error(none,errorbuffer);
return code_bad;
}
line = get_xypair_from_string(line, &range1, &range2);
if (line == NULL)
{
return code_bad;
}
if (i == 0) // only store first range
{
if (enter_gencoord(ms, gencoord_name, no) == NULL)
{
(void)sprintf(errorbuffer, "Gencoord %s referenced in muscle file but not defined in joints file.", gencoord_name);
error(none,errorbuffer);
return code_bad;
}
mp->viaRange.start = _MIN(range1, range2);
mp->viaRange.end = _MAX(range1, range2);
mp->viaRange.gencoord = enter_gencoord(ms, gencoord_name, no);
mp->isVia = yes;
}
}
}
mp->segment = enter_segment(ms, segment_name, no);
if (mp->segment == -1)
{
(void)sprintf(errorbuffer,"Segment %s referenced in muscle file but not defined in joints file.", segment_name);
error(none,errorbuffer);
return code_bad;
}
mp->undeformed_point[0] = mp->point[0];
mp->undeformed_point[1] = mp->point[1];
mp->undeformed_point[2] = mp->point[2];
numpoints++;
}
return code_fine;
}
/* ---------------------------------------------------------------------------
count_remaining_lines - scan to the end of the file, counting the number
of lines remaining.
------------------------------------------------------------------------------ */
public int count_remaining_lines (FILE* file, SBoolean countEmptyLines)
{
SBoolean lineHasContent = no;
long fpos = ftell(file);
int c, n = 0;
for (c = fgetc(file); c != EOF; c = fgetc(file))
{
if (isgraph(c))
lineHasContent = yes;
if (c == '\n')
{
if (lineHasContent || countEmptyLines)
n++;
lineHasContent = no;
}
}
if (lineHasContent)
n++;
fseek(file, fpos, SEEK_SET);
return n;
}
/* READ_DOUBLE_ARRAY: this routine reads an array of pairs-of-doubles
* (e.g. "(2.30, -0.05)"), as in the definition of a function. It keeps
* reading until it encounters the ending string (e.g. "endfunction")
* which is passed in. This routine is not trivial because it allows
* spaces to be placed liberally in the string that it extracts the
* doubles from (e.g. "( 2.30 , -0.05 )").
*/
ReturnCode read_double_array(FILE* fp, const char ending[], const char name[], dpFunction* func)
{
int new_size;
func->numpoints = 0;
while (1)
{
if (read_string(fp,buffer) == EOF)
{
(void)sprintf(errorbuffer,"Unexpected EOF reading function %s.", name);
error(abort_action,errorbuffer);
return code_bad;
}
if (STRINGS_ARE_EQUAL(buffer,ending))
break;
/* If the string just read is not the ending string (e.g. "endfunction"),
* then it must be part or all of an x-y pair "(x,y)". It cannot be more
* than one x-y pair because there must be a space between each x-y pair.
* Since there can be spaces within an x-y pair, you now want to continue
* reading strings from the file until you encounter a closing parenthesis.
*/
/* Before parsing this next string, first make sure that there is enough
* space in the function structure for the next x-y pair.
*/
if (func->numpoints == func->coefficient_array_size)
{
new_size = func->coefficient_array_size + FUNCTION_ARRAY_INCREMENT;
if (realloc_function(func,new_size) == code_bad)
return code_bad;
}
while (1)
{
if (string_contains_closing_paren(buffer) == yes)
break;
if (read_string(fp,&buffer[strlen(buffer)]) == EOF)
{
(void)sprintf(errorbuffer,"Unexpected EOF reading function %s.", name);
error(abort_action,errorbuffer);
return code_bad;
}
}
if (get_xypair_from_string(buffer,&func->x[func->numpoints],
&func->y[func->numpoints]) == NULL)
{
(void)sprintf(errorbuffer,"Error reading x-y pair in function %s.", name);
error(abort_action,errorbuffer);
return code_bad;
}
(func->numpoints)++;
}
if (func->numpoints < 2)
{
(void)sprintf(errorbuffer,"Function %s contains fewer than 2 points.", name);
error(abort_action,errorbuffer);
return code_bad;
}
return code_fine;
}
/* STRING_CONTAINS_CLOSING_PAREN: this routine scans a string to see if
* it contains a closing parenthesis.
*/
static SBoolean string_contains_closing_paren(char str_buffer[])
{
while (*str_buffer != STRING_TERMINATOR)
{
if (*(str_buffer++) == ')')
return (yes);
}
return (no);
}
/* GET_XYPAIR_FROM_STRING: this routine parses a string to extract a pair
* of doubles from it. The string should be of the form: "(x, y)".
*/
static char* get_xypair_from_string(char str_buffer[], double* x, double* y)
{
char junk;
char* buffer_ptr;
*x = *y = ERROR_DOUBLE;
buffer_ptr = parse_string(str_buffer,type_char,(void*)&junk); /* open paren */
buffer_ptr = parse_string(buffer_ptr,type_double,(void*)x); /* x coord */
buffer_ptr = parse_string(buffer_ptr,type_char,(void*)&junk); /* comma */
buffer_ptr = parse_string(buffer_ptr,type_double,(void*)y); /* y coord */
buffer_ptr = parse_string(buffer_ptr,type_char,(void*)&junk); /* close paren*/
if (*x == ERROR_DOUBLE || *y == ERROR_DOUBLE)
return (NULL);
return (buffer_ptr);
}
/* PARSE_STRING: this routine scans a string and extracts a variable from
* it. The type of variable that it extracts is specified in one of the
* arguments. It returns the unused portion of the string so that more
* variables can be extracted from it.
*/
static char* parse_string(char str_buffer[], VariableType var_type, void* dest_var)
{
char tmp_buffer[CHARBUFFER], *buffer_ptr;
if (str_buffer == NULL)
return (NULL);
buffer_ptr = tmp_buffer;
while (CHAR_IS_WHITE_SPACE(*str_buffer))
str_buffer++;
if (var_type == type_char)
{
*((char*)dest_var) = *str_buffer;
return (str_buffer+1);
}
if (var_type == type_string)
{
if (STRING_IS_NULL(str_buffer))
*((char*)dest_var) = STRING_TERMINATOR;
else
(void)sscanf(str_buffer,"%s", (char*)dest_var);
return (str_buffer + strlen((char*)dest_var));
}
if (var_type == type_double)
{
*((double*)dest_var) = ERROR_DOUBLE;
if (STRING_IS_NOT_NULL(str_buffer))
{
while (*str_buffer == '-' || *str_buffer == '.' || *str_buffer == '+' ||
*str_buffer == 'e' || *str_buffer == 'E' ||
*str_buffer == 'd' || *str_buffer == 'D' ||
(*str_buffer >= '0' && *str_buffer <= '9'))
*(buffer_ptr++) = *(str_buffer++);
*buffer_ptr = STRING_TERMINATOR;
if (sscanf(tmp_buffer,"%lg",(double*)dest_var) != 1)
*((double*)dest_var) = ERROR_DOUBLE;
}
return (str_buffer);
}
if (var_type == type_int)
{
*((int*)dest_var) = ERRORINT;
if (STRING_IS_NOT_NULL(str_buffer))
{
while (*str_buffer == '-' || (*str_buffer >= '0' && *str_buffer <= '9'))
*(buffer_ptr++) = *(str_buffer++);
*buffer_ptr = STRING_TERMINATOR;
if (sscanf(tmp_buffer,"%d",(int*)dest_var) != 1)
*((int*)dest_var) = ERRORINT;
}
return (str_buffer);
}
(void)sprintf(errorbuffer,"Unknown variable type (%d) passed to parse_string().",
(int)var_type);
error(none,errorbuffer);
return (NULL);
}
/* GET_STRING_PAIR: this routine takes a string of the form "(str1,str2)",
* which can have spaces between any of the 5 components, and returns the
* two internal strings, str1 and str2.
*/
ReturnCode get_string_pair(char str_buffer[], char str1[], char str2[])
{
/* scan past the opening parenthesis */
while (*str_buffer != '(' && *str_buffer != STRING_TERMINATOR)
str_buffer++;
str_buffer++;
if (STRING_IS_NULL(str_buffer))
return code_bad;
/* scan upto the start of str1 */
while (*str_buffer == SPACE || *str_buffer == TAB)
str_buffer++;
if (STRING_IS_NULL(str_buffer))
return code_bad;
/* copy the first string to the str1 array */
while (*str_buffer != ',' && *str_buffer != SPACE && *str_buffer != TAB)
*str1++ = *str_buffer++;
*str1 = STRING_TERMINATOR;
/* scan upto the start of str2 */
while (*str_buffer == ',' || *str_buffer == SPACE || *str_buffer == TAB)
str_buffer++;
if (STRING_IS_NULL(str_buffer))
return code_bad;
/* copy the second string to the str2 array */
while (*str_buffer != ')' && *str_buffer != SPACE && *str_buffer != TAB)
*str2++ = *str_buffer++;
*str2 = STRING_TERMINATOR;
return code_fine;
}
/* NAME_IS_GENCOORD: this function checks to see if a string is the name
* of one of the model's gencoords, with an optional suffix and also
* possibly the extra suffix "_spl" or "_gcv" (possibly followed by a cutoff
* frequency). It returns the index of the gencoord if there is a match.
* If stripEnd is yes, the optional functionType and cutoff frequency are
* removed from the name if a match is made.
*/
GeneralizedCoord* name_is_gencoord(char name[], ModelStruct* ms, char suffix[],
dpFunctionType* functionType, double* cutoffFrequency, SBoolean stripEnd)
{
int i, len, lenQ, Qnum, index, maxLen;
char *ptr, *newEnd;
len = strlen(name);
/* First check to see if the string begins with the name of a gencoord.
* To handle models which have overlapping gencoord names, like
* "q1" and "q10", check for a match with all gencoords, and take
* the longest match.
*/
for (i = 0, index = -1, maxLen = -1; i < ms->numgencoords; i++)
{
lenQ = strlen(ms->gencoord[i]->name);
if (len >= lenQ)
{
if (!strncmp(name, ms->gencoord[i]->name, lenQ))
{
if (lenQ > maxLen)
{
index = i;
maxLen = lenQ;
}
}
}
}
if (index == -1)
return NULL;
/* You've found a matching gencoord name, so move ptr past the name and
* get ready to check the suffixes.
*/
Qnum = index;
ptr = &name[maxLen];
len -= maxLen;
/* If a suffix was passed in, check to see if the name ends in that suffix.
* If it does, remove the suffix and continue on. If it does not, return NULL
* because the passed-in suffix must be in the name.
*/
if (suffix)
{
int suffix_len = strlen(suffix);
if (len >= suffix_len)
{
if (!strncmp(ptr, suffix, suffix_len))
{
ptr += suffix_len;
len -= suffix_len;
}
else
{
return NULL;
}
}
else
{
return NULL;
}
}
/* Store a pointer to the character right after the name (plus suffix, if specified).
* This will be the new end of the string if stripEnd == yes.
*/
newEnd = ptr;
/* If functionType and cutoffFrequency are not NULL, check to see if the name ends in
* natural_cubic_text or gcv_text (followed by an optional cutoff frequency). If it
* does, set *functionType to the appropriate type. If no function label is found, set
* the type to step_func.
*/
if (functionType && cutoffFrequency)
{
int matched_spl = 0, matched_lin = 0;
int lin_len = strlen(linear_text);
int spl_len = strlen(natural_cubic_text);
int gcv_len = strlen(gcv_text);
*functionType = dpStepFunction;
*cutoffFrequency = -1.0; // by default there is no smoothing
if (len >= lin_len)
{
if (!strncmp(ptr, linear_text, lin_len))
{
*functionType = dpLinearFunction;
ptr += lin_len;
len -= lin_len;
matched_lin = 1;
}
}
if (!matched_lin && len >= spl_len)
{
if (!strncmp(ptr, natural_cubic_text, spl_len))
{
*functionType = dpNaturalCubicSpline;
ptr += spl_len;
len -= spl_len;
matched_spl = 1;
}
}
if (!matched_lin && !matched_spl && len >= gcv_len)
{
if (!strncmp(ptr, gcv_text, gcv_len))
{
ptr += gcv_len;
len -= gcv_len;
*functionType = dpGCVSpline;
if (len > 0)
{
char* intPtr = buffer;
/* Move over the underscore and look for an integer. */
if (*(ptr++) != '_')
{
return NULL;
}
else
{
len--; /* for the underscore character */
while (*ptr >= '0' && *ptr <= '9')
{
*(intPtr++) = *(ptr++);
len--;
}
*intPtr = STRING_TERMINATOR;
*cutoffFrequency = atof(buffer);
}
}
}
}
}
/* If there are extra characters after the suffixes, return an error. */
if (len > 0)
return NULL;
/* Strip off the text for the function type and cutoff frequency. */
if (stripEnd == yes)
*newEnd = STRING_TERMINATOR;
return ms->gencoord[Qnum];
}
/* NAME_IS_BODY_SEGMENT: this function checks to see if a string is the name
* of one of the model's body segments. The name can be followed by the name of
* any of the model's motion objects, plus an animation component (e.g., "_px" or "_vy").
* Also, the string can contain a suffix of "_gcv" or "_spl", possibly followed
* by a cutoff frequency. It returns the index of the body segment if there is
* a match. If stripEnd is yes, the optional functionType and cutoff frequency are
* removed from the name if a match is made.
*/
int name_is_body_segment(ModelStruct* ms, char name[], int* motion_object, int* component,
dpFunctionType* functionType, double* cutoffFrequency, SBoolean stripEnd)
{
int i, index, len, lenS, maxLen, Snum;
char *ptr, *newEnd;
len = strlen(name);
/* First check to see if the string begins with the name of a segment.
* To handle models which have overlapping segment names, like
* "femur" and "femur1", check for a match with all segments, and take
* the longest match.
*/
for (i = 0, index = -1, maxLen = -1; i < ms->numsegments; i++)
{
lenS = strlen(ms->segment[i].name);
if (len >= lenS)
{
if (!strncmp(name, ms->segment[i].name, lenS))
{
if (lenS > maxLen)
{
index = i;
maxLen = lenS;
}
}
}
}
if (index == -1)
return -1;
/* You've found a matching segment name, so move ptr past the name and
* get ready to check the suffixes.
*/
Snum = index;
ptr = &name[maxLen];
len -= maxLen;
if (motion_object)
{
int lenM;
*motion_object = -1;
/* The motion object name must be preceded by an underscore. */
if (*ptr == '_')
{
/* Temporarily move past the underscore. */
ptr++;
len--;
/* Find the first motion object which matches the name.
* This suffix is optional, so do not return if there is no match.
*/
for (i = 0; i < ms->num_motion_objects; i++)
{
lenM = strlen(ms->motion_objects[i].name);
if (len >= lenM)
{
if (!strncmp(ptr, ms->motion_objects[i].name, lenM))
break;
}
}
if (i < ms->num_motion_objects)
{
*motion_object = i;
ptr += lenM;
len -= lenM;
}
else
{
/* Move backwards over the underscore. */
ptr--;
len++;
}
}
}
if (component)
{
*component = -1;
/* Check to see if a component (e.g., "_px") is next in the string.
* This suffix is optional, and independent of the motion object name suffix.
*/
if (!strncmp(ptr, "_tx", 3) || !strncmp(ptr, "_px", 3))
*component = MO_TX;
else if (!strncmp(ptr, "_ty", 3) || !strncmp(ptr, "_py", 3))
*component = MO_TY;
else if (!strncmp(ptr, "_tz", 3) || !strncmp(ptr, "_pz", 3))
*component = MO_TZ;
else if (!strncmp(ptr, "_vx", 3))
*component = MO_VX;
else if (!strncmp(ptr, "_vy", 3))
*component = MO_VY;
else if (!strncmp(ptr, "_vz", 3))
*component = MO_VZ;
else if (!strncmp(ptr, "_sx", 3))
*component = MO_SX;
else if (!strncmp(ptr, "_sy", 3))
*component = MO_SY;
else if (!strncmp(ptr, "_sz", 3))
*component = MO_SZ;
else if (!strncmp(ptr, "_cr", 3))
*component = MO_CR;
else if (!strncmp(ptr, "_cg", 3))
*component = MO_CG;
else if (!strncmp(ptr, "_cb", 3))
*component = MO_CB;
else if (!strncmp(ptr, "_x", 2))
*component = MO_X;
else if (!strncmp(ptr, "_y", 2))
*component = MO_Y;
else if (!strncmp(ptr, "_z", 2))
*component = MO_Z;
if (*component >= MO_TX && *component <= MO_CB)
{
ptr += 3;
len -= 3;
}
else if (*component >= MO_X && *component <= MO_Z)
{
ptr += 2;
len -= 2;
}
}
/* Store a pointer to the character right after the part of the name processed
* so far. This will be the new end of the string if stripEnd == yes.
*/
newEnd = ptr;
/* If functionType and cutoffFrequency are not NULL, check to see if the name ends in
* natural_cubic_text or gcv_text (followed by an optional cutoff frequency). If it
* does, set *functionType to the appropriate type. If no function label is found, set
* the type to step_func.
*/
if (functionType && cutoffFrequency)
{
int matched_spl = 0, matched_lin = 0;
int lin_len = strlen(linear_text);
int spl_len = strlen(natural_cubic_text);
int gcv_len = strlen(gcv_text);
*functionType = dpStepFunction;
*cutoffFrequency = -1.0; // by default there is no smoothing
if (len >= lin_len)
{
if (!strncmp(ptr, linear_text, lin_len))
{
*functionType = dpLinearFunction;
ptr += lin_len;
len -= lin_len;
matched_lin = 1;
}
}
if (!matched_lin && len >= spl_len)
{
if (!strncmp(ptr, natural_cubic_text, spl_len))
{
*functionType = dpNaturalCubicSpline;
ptr += spl_len;
len -= spl_len;
matched_spl = 1;
}
}
if (!matched_lin && !matched_spl && len >= gcv_len)
{
if (!strncmp(ptr, gcv_text, gcv_len))
{
ptr += gcv_len;
len -= gcv_len;
*functionType = dpGCVSpline;
if (len > 0)
{
char* intPtr = buffer;
/* Move over the underscore and look for an integer. */
if (*(ptr++) != '_')
{
return -1;
}
else
{
len--; /* for the underscore character */
while (*ptr >= '0' && *ptr <= '9')
{
*(intPtr++) = *(ptr++);
len--;
}
*intPtr = STRING_TERMINATOR;
*cutoffFrequency = atof(buffer);
}
}
}
}
}
/* If there are extra characters after the suffixes, return an error. */
if (len > 0)
return -1;
/* Strip off the text for the function type and cutoff frequency. */
if (stripEnd == yes)
*newEnd = STRING_TERMINATOR;
return Snum;
}
/* NAME_IS_MUSCLE: this function checks to see if a string is the name
* of one of the model's muscles, with an optional suffix and also
* possibly the extra suffix "_spl" or "_gcv" (possibly followed by a cutoff
* frequency). It returns the index of the muscle if there is a match.
* If stripEnd is yes, the optional functionType and cutoff frequency are
* removed from the name if a match is made.
*/
int name_is_muscle(ModelStruct* ms, char name[], char suffix[],
dpFunctionType* functionType, double* cutoffFrequency, SBoolean stripEnd)
{
int i, len, lenM, Mnum, index, maxLen;
char *ptr, *newEnd;
len = strlen(name);
/* First check to see if the string begins with the name of a muscle.
* To handle models which have overlapping muscle names, like
* "trap1" and "trap10", check for a match with all muscles, and take
* the longest match.
*/
for (i = 0, index = -1, maxLen = -1; i < ms->nummuscles; i++)
{
lenM = strlen(ms->muscle[i]->name);
if (len >= lenM)
{
if (!strncmp(name, ms->muscle[i]->name, lenM))
{
if (lenM > maxLen)
{
index = i;
maxLen = lenM;
}
}
}
}
if (index == -1)
return -1;
/* You've found a matching muscle name, so move ptr past the name and
* get ready to check the suffixes.
*/
Mnum = index;
ptr = &name[maxLen];
len -= maxLen;
/* If a suffix was passed in, check to see if the name ends in that suffix.
* If it does, remove the suffix and continue on. If it does not, return -1
* because the suffix is not optional.
*/
if (suffix)
{
int suffix_len = strlen(suffix);
if (len >= suffix_len)
{
if (!strncmp(ptr, suffix, suffix_len))
{
ptr += suffix_len;
len -= suffix_len;
}
else
{
return -1;
}
}
else
{
return -1;
}
}
/* Store a pointer to the character right after the name (plus suffix, if specified).
* This will be the new end of the string if stripEnd == yes.
*/
newEnd = ptr;
/* If functionType and cutoffFrequency are not NULL, check to see if the name ends in
* natural_cubic_text or gcv_text (followed by an optional cutoff frequency). If it
* does, set *functionType to the appropriate type. If no function label is found, set
* the type to step_func.
*/
if (functionType && cutoffFrequency)
{
int matched_spl = 0, matched_lin = 0;
int lin_len = strlen(linear_text);
int spl_len = strlen(natural_cubic_text);
int gcv_len = strlen(gcv_text);
*functionType = dpStepFunction;
*cutoffFrequency = -1.0; // by default there is no smoothing
if (len >= lin_len)
{
if (!strncmp(ptr, linear_text, lin_len))
{
*functionType = dpLinearFunction;
ptr += lin_len;
len -= lin_len;
matched_lin = 1;
}
}
if (!matched_lin && len >= spl_len)
{
if (!strncmp(ptr, natural_cubic_text, spl_len))
{
*functionType = dpNaturalCubicSpline;
ptr += spl_len;
len -= spl_len;
matched_spl = 1;
}
}
if (!matched_lin && !matched_spl && len >= gcv_len)
{
if (!strncmp(ptr, gcv_text, gcv_len))
{
ptr += gcv_len;
len -= gcv_len;
*functionType = dpGCVSpline;
if (len > 0)
{
char* intPtr = buffer;
/* Move over the underscore and look for an integer. */
if (*(ptr++) != '_')
{
return -1;
}
else
{
len--; /* for the underscore character */
while (*ptr >= '0' && *ptr <= '9')
{
*(intPtr++) = *(ptr++);
len--;
}
*intPtr = STRING_TERMINATOR;
*cutoffFrequency = atof(buffer);
}
}
}
}
}
/* If there are extra characters after the suffixes, return an error. */
if (len > 0)
return -1;
/* Strip off the text for the function type and cutoff frequency. */
if (stripEnd == yes)
*newEnd = STRING_TERMINATOR;
return Mnum;
}
SBoolean muscle_has_force_params(dpMuscleStruct* ms)
{
if (ms->optimal_fiber_length == NULL || ms->resting_tendon_length == NULL ||
ms->pennation_angle == NULL || ms->max_isometric_force == NULL ||
ms->tendon_force_len_func == NULL || ms->active_force_len_func == NULL ||
ms->passive_force_len_func == NULL || *ms->tendon_force_len_func == NULL ||
*ms->active_force_len_func == NULL || *ms->passive_force_len_func == NULL)
return no;
return yes;
}
ENUM {
NoStringMarker=0,
WhiteSpace,
SingleQuote,
DoubleQuote
} StringMarker;
StringMarker is_string_marker(char ch)
{
if (ch == '\'')
return SingleQuote;
if (ch == '\"')
return DoubleQuote;
if (CHAR_IS_WHITE_SPACE(ch) || (ch == STRING_TERMINATOR))
return WhiteSpace;
return NoStringMarker;
}
int divide_string(char string[], char* word_array[], int max_words)
{
int i, len, num_chars, word_start=0, count=0, last_one_white=1;
StringMarker marker = WhiteSpace;
if (max_words <= 0)
return 0;
len = strlen(string) + 1;
// When you hit " x", set word_start to point to the 'x'
// When you hit "x ", copy the word ending in 'x' to the next
// slot in word_array.
for (i=0; i<len; i++)
{
StringMarker m = is_string_marker(string[i]);
if (m == marker || (marker == WhiteSpace && m != NoStringMarker))
{
/* Copy the last word to word_array[] */
if (last_one_white == 0)
{
num_chars = i - word_start;
word_array[count] = (char*)simm_malloc((num_chars+1)*sizeof(char));
strncpy(word_array[count], &string[word_start], num_chars);
word_array[count][num_chars] = STRING_TERMINATOR;
if (++count == max_words)
return count;
}
last_one_white = 1;
if (m == marker)
marker = WhiteSpace;
else
marker = m;
}
else
{
if (last_one_white == 1)
word_start = i;
last_one_white = 0;
}
}
// Remove surrounding double-quotes from each word, if any.
for (i=0; i<count; i++)
{
int len = strlen(word_array[i]);
if (len > 1 && word_array[i][0] == '\"' && word_array[i][len-1] == '\"')
{
memmove(word_array[i], &word_array[i][1], len-1);
word_array[i][len-2] = STRING_TERMINATOR;
}
}
return count;
}
/* Returns the index of the last occurrence of a character in a string
* that belongs to a set of characters.
*/
int strrcspn(const char* string, const char* strCharSet)
{
int i, j, len = strlen(string);
int setLen = strlen(strCharSet);
for (i = len - 1; i >= 0; i--)
{
for (j = 0; j < setLen; j++)
{
if (string[i] == strCharSet[j])
return i;
}
}
return -1;
}
/* Extracts a name and a value (double) from a specified character string.
* The name is assumed to be at the beginning of the string, and can have
* any number of tokens in it, followed by a colon (which may or may not
* be attached to the name or the value). This function modifies the string
* by inserting a NULL character after the name.
*/
int get_name_and_value_from_string(char* string, double* value)
{
int len, pos;
char* ptr;
/* The string may have a colon in it between the name and the value,
* so search for the last colon and replace it with a space.
*/
ptr = strrchr(string, ':');
if (ptr)
*ptr = ' ';
/* Strip trailing white space, then find the position of the
* last character of white space. The value is contained in the
* characters after this last white space.
*/
strip_trailing_white_space(string);
len = strlen(string);
pos = strrcspn(string, "\r\t ");
if (pos > 0 && pos < len - 1)
{
if (sscanf(&string[pos+1], "%lg", value) != 1)
return 0;
string[pos] = STRING_TERMINATOR;
strip_trailing_white_space(string);
}
else
{
return 0;
}
return 1;
}
void strip_trailing_white_space(char string[])
{
int i;
for (i=strlen(string)-1; i>=0; i--)
{
if (CHAR_IS_WHITE_SPACE(string[i]))
string[i] = STRING_TERMINATOR;
else
break;
}
}
/* -------------------------------------------------------------------------
STATIC DATA
---------------------------------------------------------------------------- */
static int sNumDefaultAcppOptions = 2;
static int sNumTotalAcppOptions = 2;
static char* sAcppOptions[128] = { "acpp", "-P" };
/* -------------------------------------------------------------------------
clear_preprocessor_options - reset the options that are passed to acpp()
their defaults.
---------------------------------------------------------------------------- */
public void clear_preprocessor_options ()
{
int i;
for (i = sNumDefaultAcppOptions; i < sNumTotalAcppOptions; i++)
free(sAcppOptions[i]);
sNumTotalAcppOptions = sNumDefaultAcppOptions;
}
/* -------------------------------------------------------------------------
add_preprocessor_option - format and append the specified string to the
list of command-line options passed to acpp().
NOTE: "default" options must precede "non-default" option in the list,
therefore be certain to call clear_preprocessor_options() before
calling this routine with 'isDefaultOption' equal to 'yes'.
---------------------------------------------------------------------------- */
public void add_preprocessor_option (SBoolean isDefaultOption, const char* format, ...)
{
va_list ap;
va_start(ap, format);
vsprintf(buffer, format, ap);
va_end(ap);
#if MEMORY_LEAK
{
int len=strlen(buffer)+1;
sAcppOptions[sNumTotalAcppOptions] = (char*)malloc(len);
strcpy(sAcppOptions[sNumTotalAcppOptions++], buffer);
}
#else
mstrcpy(&sAcppOptions[sNumTotalAcppOptions++], buffer);
#endif
if (isDefaultOption)
sNumDefaultAcppOptions++;
}
/* -------------------------------------------------------------------------
acpp_message_proc -
---------------------------------------------------------------------------- */
static int acpp_message_proc (const char* format, ...)
{
va_list ap;
int n;
va_start(ap, format);
n = vsprintf(buffer, format, ap);
va_end(ap);
simm_printf(yes, buffer);
return n;
}
typedef int (*_msg_proc)(const char* format, ...);
int acpp_main(int argc, char** argv, _msg_proc);
/* -------------------------------------------------------------------------
acpp -
---------------------------------------------------------------------------- */
static void acpp (char in_file[], const char out_file[])
{
char* pure_path = NULL;
int argc;
/* Add the folder containing the input file to the search path
* for acpp. This is so that if the file includes other files,
* its folder is searched for them. By default, acpp will search
* only SIMM\resources and the current directory (which may not
* be the directory the input file is in).
*/
get_pure_path_from_path(in_file, &pure_path);
if (pure_path)
{
add_preprocessor_option(no, "-I%s", pure_path);
free(pure_path);
}
argc = sNumTotalAcppOptions;
sAcppOptions[argc++] = (char*) in_file;
sAcppOptions[argc++] = (char*) out_file;
#if 0
{
int i;
fprintf(stderr, "\n");
for (i = 0; i < argc; i++)
fprintf(stderr, "%s ", sAcppOptions[i]);
fprintf(stderr, "\n\n");
}
#endif
remove(out_file); /* required to work-around CodeWarrior bug */
if (acpp_main(argc, sAcppOptions, acpp_message_proc) != 0)
{
const char* infile = strrchr(in_file, DIR_SEP_CHAR);
if (infile)
infile++;
else
infile = in_file;
sprintf(errorbuffer, "Error running preproccesor on %s.", infile);
error(none, errorbuffer);
}
#if 0
/* copy the preprocessed file so we can get a look at it:
*/
{
static int sCounter = 1;
sprintf(buffer, "cp %s /suture/usr/people/simm/ACPP-OUT-%d.txt", out_file, sCounter++);
glutSystem(buffer);
}
#endif
} /* acpp */
/* -------------------------------------------------------------------------
read_deform -
---------------------------------------------------------------------------- */
ReturnCode read_deform (FILE* fp, SegmentStruct* seg, int segmentnum)
{
DeformObject* dfm = NULL;
double xyz[3];
int i = seg->num_deforms;
DMatrix m;
if (seg->num_deforms >= seg->deform_obj_array_size)
{
ReturnCode rc = code_fine;
/* expand deform object array if necessary */
seg->deform_obj_array_size += 2;
if (seg->deform == NULL)
{
seg->deform = (DeformObject*) simm_malloc(
seg->deform_obj_array_size * sizeof(DeformObject));
}
else
{
seg->deform = (DeformObject*) simm_realloc(seg->deform,
seg->deform_obj_array_size * sizeof(DeformObject), &rc);
}
if (rc == code_bad || seg->deform == NULL)
{
seg->deform_obj_array_size -= 2;
return code_bad;
}
}
seg->num_deforms++;
/* initialize the new deform */
dfm = &seg->deform[i];
init_deform(dfm);
dfm->segment = segmentnum;
if (fscanf(fp,"%s", buffer) != 1)
{
error(abort_action,"Error reading name in deform object definition");
return code_bad;
}
else
mstrcpy(&dfm->name,buffer);
while (1)
{
if (read_string(fp,buffer) == EOF)
break;
if (buffer[0] == '#')
{
read_nonempty_line(fp,buffer);
continue;
}
if (STRINGS_ARE_EQUAL(buffer,"active"))
{
if (read_string(fp,buffer) == EOF)
break;
if (STRINGS_ARE_EQUAL(buffer,"no") || STRINGS_ARE_EQUAL(buffer,"false"))
dfm->active = no;
}
else if (STRINGS_ARE_EQUAL(buffer,"visible"))
{
if (read_string(fp,buffer) == EOF)
break;
if (STRINGS_ARE_EQUAL(buffer,"no") || STRINGS_ARE_EQUAL(buffer,"false"))
dfm->visible = no;
}
else if (STRINGS_ARE_EQUAL(buffer,"autoreset"))
{
if (read_string(fp,buffer) == EOF)
break;
if (STRINGS_ARE_EQUAL(buffer,"yes") || STRINGS_ARE_EQUAL(buffer,"true"))
dfm->autoReset = yes;
}
else if (STRINGS_ARE_EQUAL(buffer,"translationonly"))
{
if (read_string(fp,buffer) == EOF)
break;
if (STRINGS_ARE_EQUAL(buffer,"yes") || STRINGS_ARE_EQUAL(buffer,"true"))
dfm->translationOnly = yes;
}
else if (STRINGS_ARE_EQUAL(buffer,"innermin"))
{
if (fscanf(fp, "%lg %lg %lg", &dfm->innerMin.xyz[0],
&dfm->innerMin.xyz[1], &dfm->innerMin.xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading \'innermin\' for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"innermax"))
{
if (fscanf(fp, "%lg %lg %lg", &dfm->innerMax.xyz[0],
&dfm->innerMax.xyz[1], &dfm->innerMax.xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading \'innermax\' for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"outermin"))
{
if (fscanf(fp, "%lg %lg %lg", &dfm->outerMin.xyz[0],
&dfm->outerMin.xyz[1], &dfm->outerMin.xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading \'outermin\' for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"outermax"))
{
if (fscanf(fp, "%lg %lg %lg", &dfm->outerMax.xyz[0],
&dfm->outerMax.xyz[1], &dfm->outerMax.xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading \'outermax\' for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"xyz_body_rotation_POSITION"))
{
if (fscanf(fp, "%lg %lg %lg", &xyz[0], &xyz[1], &xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading rotation for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
identity_matrix(m);
x_rotate_matrix_bodyfixed(m, xyz[0] * DTOR);
y_rotate_matrix_bodyfixed(m, xyz[1] * DTOR);
z_rotate_matrix_bodyfixed(m, xyz[2] * DTOR);
extract_rotation(m, &dfm->position.rotation_axis, &dfm->position.rotation_angle);
}
else if (STRINGS_ARE_EQUAL(buffer,"translation_POSITION"))
{
if (fscanf(fp,"%lg %lg %lg",
&dfm->position.translation.xyz[0],
&dfm->position.translation.xyz[1],
&dfm->position.translation.xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading translation for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"xyz_body_rotation_DEFORM_START"))
{
if (fscanf(fp, "%lg %lg %lg", &xyz[0], &xyz[1], &xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading rotation for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
identity_matrix(m);
x_rotate_matrix_bodyfixed(m, xyz[0] * DTOR);
y_rotate_matrix_bodyfixed(m, xyz[1] * DTOR);
z_rotate_matrix_bodyfixed(m, xyz[2] * DTOR);
extract_rotation(m, &dfm->deform_start.rotation_axis, &dfm->deform_start.rotation_angle);
}
else if (STRINGS_ARE_EQUAL(buffer,"translation_DEFORM_START"))
{
if (fscanf(fp,"%lg %lg %lg",
&dfm->deform_start.translation.xyz[0],
&dfm->deform_start.translation.xyz[1],
&dfm->deform_start.translation.xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading translation for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"xyz_body_rotation_DEFORM_END"))
{
if (fscanf(fp, "%lg %lg %lg", &xyz[0], &xyz[1], &xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading rotation for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
identity_matrix(m);
x_rotate_matrix_bodyfixed(m, xyz[0] * DTOR);
y_rotate_matrix_bodyfixed(m, xyz[1] * DTOR);
z_rotate_matrix_bodyfixed(m, xyz[2] * DTOR);
extract_rotation(m, &dfm->deform_end.rotation_axis, &dfm->deform_end.rotation_angle);
}
else if (STRINGS_ARE_EQUAL(buffer,"translation_DEFORM_END"))
{
if (fscanf(fp,"%lg %lg %lg",
&dfm->deform_end.translation.xyz[0],
&dfm->deform_end.translation.xyz[1],
&dfm->deform_end.translation.xyz[2]) != 3)
{
sprintf(errorbuffer, "Error reading translation for deform object %s", dfm->name);
error(abort_action,errorbuffer);
return code_bad;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"enddeform"))
break;
else
{
sprintf(errorbuffer, "Unrecognized text in deform object %s: %s", dfm->name, buffer);
error(abort_action,errorbuffer);
return code_bad;
}
}
/* Check the inner and outer boxes to see if they are well defined. */
if (dfm->innerMin.xyz[0] > dfm->innerMax.xyz[0] || dfm->innerMin.xyz[0] < dfm->outerMin.xyz[0])
{
sprintf(errorbuffer,"Error setting up deform object %s", dfm->name);
error(none, errorbuffer);
error(recover,"Inner min X must be greater than outer min X and less than inner max X");
return code_bad;
}
if (dfm->innerMin.xyz[1] > dfm->innerMax.xyz[1] || dfm->innerMin.xyz[1] < dfm->outerMin.xyz[1])
{
sprintf(errorbuffer,"Error setting up deform object %s", dfm->name);
error(none, errorbuffer);
error(recover,"Inner min Y must be greater than outer min Y and less than inner max Y");
return code_bad;
}
if (dfm->innerMin.xyz[2] > dfm->innerMax.xyz[2] || dfm->innerMin.xyz[2] < dfm->outerMin.xyz[2])
{
sprintf(errorbuffer,"Error setting up deform object %s", dfm->name);
error(none, errorbuffer);
error(recover,"Inner min Z must be greater than outer min Z and less than inner max Z");
return code_bad;
}
if (dfm->innerMax.xyz[0] > dfm->outerMax.xyz[0])
{
sprintf(errorbuffer,"Error setting up deform object %s", dfm->name);
error(none, errorbuffer);
error(recover,"Inner max X must be less than outer max X");
return code_bad;
}
if (dfm->innerMax.xyz[1] > dfm->outerMax.xyz[1])
{
sprintf(errorbuffer,"Error setting up deform object %s", dfm->name);
error(none, errorbuffer);
error(recover,"Inner max Y must be less than outer max Y");
return code_bad;
}
if (dfm->innerMax.xyz[2] > dfm->outerMax.xyz[2])
{
sprintf(errorbuffer,"Error setting up deform object %s", dfm->name);
error(none, errorbuffer);
error(recover,"Inner max Z must be less than outer max Z");
return code_bad;
}
/* NOTE: 'xyz_body_rotation_DEFORM' and 'translation_DEFORM' specify the
* *delta* transformation from the "position" frame to the "deform_start"
* frame. The code below converts this into the DeformObject's true
* "deform_start" transform which is measured relative to the parent segment's
* frame.
*/
dfm->position.xforms_valid = no;
dfm->deform_start.xforms_valid = no;
dfm->deform_end.xforms_valid = no;
recalc_deform_xforms(seg, dfm);
/* deform start */
copy_4x4matrix(dfm->deform_start.from_local_xform, m);
append_matrix(m, dfm->position.from_local_xform);
extract_rotation(m, &dfm->deform_start.rotation_axis, &dfm->deform_start.rotation_angle);
dfm->deform_start.translation.xyz[0] = m[3][0];
dfm->deform_start.translation.xyz[1] = m[3][1];
dfm->deform_start.translation.xyz[2] = m[3][2];
dfm->deform_start.xforms_valid = no;
/* deform end */
copy_4x4matrix(dfm->deform_end.from_local_xform, m);
append_matrix(m, dfm->position.from_local_xform);
extract_rotation(m, &dfm->deform_end.rotation_axis, &dfm->deform_end.rotation_angle);
dfm->deform_end.translation.xyz[0] = m[3][0];
dfm->deform_end.translation.xyz[1] = m[3][1];
dfm->deform_end.translation.xyz[2] = m[3][2];
dfm->deform_end.xforms_valid = no;
recalc_deform_xforms(seg, dfm);
#if ! ENGINE
init_deform_box_verts(dfm);
#endif
return code_fine;
} /* read_deform */
/* -------------------------------------------------------------------------
read_deformity -
---------------------------------------------------------------------------- */
ReturnCode read_deformity (ModelStruct* ms, FILE* fp)
{
ReturnCode rc = code_fine;
Deformity* dty;
if (ms->num_deformities == ms->deformity_array_size)
{
ms->deformity_array_size += DEFORMITY_ARRAY_INCREMENT;
ms->deformity = (Deformity*) simm_realloc(ms->deformity,
ms->deformity_array_size * sizeof(Deformity), &rc);
if (rc == code_bad)
{
ms->deformity_array_size -= DEFORMITY_ARRAY_INCREMENT;
return code_bad;
}
}
dty = &ms->deformity[ms->num_deformities];
init_deformity(dty);
if (fscanf(fp,"%s", buffer) != 1)
{
error(abort_action,"Error reading name in deformity definition");
return code_bad;
}
else
mstrcpy(&dty->name, buffer);
while (1)
{
if (read_string(fp, buffer) == EOF)
break;
if (buffer[0] == '#')
{
read_nonempty_line(fp,buffer);
continue;
}
if (STRINGS_ARE_EQUAL(buffer,"default_value") || STRINGS_ARE_EQUAL(buffer,"value"))
{
if (fscanf(fp, "%lg", &dty->default_value) != 1)
{
sprintf(errorbuffer, "Error reading value for deformity: %s.", dty->name);
error(none, errorbuffer);
return code_bad;
}
else
{
dty->value = dty->default_value;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"range"))
{
if (fscanf(fp, "%lg %lg", &dty->range.start, &dty->range.end) != 2)
{
sprintf(errorbuffer, "Error reading range for deformity: %s.", dty->name);
error(none, errorbuffer);
return code_bad;
}
if (dty->range.start > dty->range.end)
{
double tmp = dty->range.start;
dty->range.start = dty->range.end;
dty->range.end = tmp;
}
}
else if (STRINGS_ARE_EQUAL(buffer,"keys"))
{
int nk;
char key1[64], key2[64];
read_line(fp, buffer);
nk = sscanf(buffer,"%s %s", key1, key2);
if (nk == 1)
dty->keys[0] = dty->keys[1] = lookup_simm_key(key1);
else if (nk == 2)
{
dty->keys[0] = lookup_simm_key(key1);
dty->keys[1] = lookup_simm_key(key2);
}
else
{
sprintf(errorbuffer, "Error reading keys for deformity: %s.", dty->name);
error(recover,errorbuffer);
}
}
else if (STRINGS_ARE_EQUAL(buffer,"deform"))
{
char* dfmName = buffer;
read_line(fp, dfmName);
_strip_outer_whitespace(dfmName); /* remove any leading or trailing whitespace */
if (*dfmName)
{
rc = code_fine;
if (dty->deform == NULL)
{
dty->deform = (DeformObject**) simm_malloc(1 * sizeof(DeformObject*));
dty->deform_name = (char**) simm_malloc(1 * sizeof(char*));
}
else
{
dty->deform = (DeformObject**) simm_realloc(dty->deform,
(dty->num_deforms + 1) * sizeof(DeformObject*), &rc);
dty->deform_name = (char**) simm_realloc(dty->deform_name,
(dty->num_deforms + 1) * sizeof(char*), &rc);
}
if (dty->deform && dty->deform_name && rc == code_fine)
{
dty->deform[dty->num_deforms] = lookup_deform(ms, dfmName);
if (dty->deform[dty->num_deforms])
{
mstrcpy(&dty->deform_name[dty->num_deforms], dfmName);
dty->num_deforms++;
}
else
rc = code_bad;
}
if (rc != code_fine)
{
if (dty->deform)
free(dty->deform);
if (dty->deform_name)
free(dty->deform_name);
dty->deform = NULL;
dty->num_deforms = 0;
sprintf(errorbuffer, "Error reading deform \'%s\' for deformity: %s.",
dfmName, dty->name);
error(recover,errorbuffer);
return code_bad;
}
}
}
else if (STRINGS_ARE_EQUAL(buffer,"enddeformity"))
break;
}
/* Check the value and default_value to make sure they're in range.
* This code will also initialize them to range.start if they were not
* specified in the deformity definition.
*/
if (dty->value < dty->range.start)
dty->value = dty->range.start;
else if (dty->value > dty->range.end)
dty->value = dty->range.end;
if (dty->default_value < dty->range.start)
dty->default_value = dty->range.start;
else if (dty->default_value > dty->range.end)
dty->default_value = dty->range.end;
ms->num_deformities++;
return code_fine;
} /* read_deformity */
/* -------------------------------------------------------------------------
_read_til - read (and ignore) characters from the specified file until
the specified character 'c' is found.
---------------------------------------------------------------------------- */
SBoolean _read_til (FILE* file, int c)
{
int t = fgetc(file);
while (t != c && t != EOF)
t = fgetc(file);
return (SBoolean) (t == EOF);
}
/* -------------------------------------------------------------------------
_read_til_tokens - Read characters from 'file' into 'buf' until one of the
characters specified in 'delimiters' is encountered. Put the delimiting
character back into 'file'.
---------------------------------------------------------------------------- */
int _read_til_tokens (FILE* file, char* buf, const char* delimiters)
{
char* p = buf;
while (1)
{
char c = fgetc(file);
if (feof(file) || ferror(file))
break;
else
{
if (strchr(delimiters, c))
{
ungetc(c, file);
break;
}
else
*p++ = c;
}
}
*p = '\0';
/* remove trailing whitespace if necessary */
while (p > buf && isspace(p[-1]))
*(--p) = '\0';
/* Return 1 if the string is not empty. */
if (p > buf)
return 1;
else
return 0;
}
/* -------------------------------------------------------------------------
_strip_outer_whitespace -
---------------------------------------------------------------------------- */
void _strip_outer_whitespace (char* str)
{
/* remove exterior (but not interior) whitespace from a string.
*/
/* remove trailing whitespace */
char* p = str + strlen(str) - 1;
for ( ; p >= str && isspace(*p); p--)
*p = '\0';
/* remove leading whitespace */
for (p = str; *p; p++)
if ( ! isspace(*p))
break;
if (*p && p != str)
memmove(str, p, strlen(p) + 1);
}
void strip_brackets_from_string(char name[])
{
int i, j;
char buffer[CHARBUFFER];
// strip the () from the gencoord name
strcpy(buffer, name);
i = 0;
j = 0;
while (1)
{
if (buffer[i] == '(')
{
i++;
continue;
}
if (buffer[i] == ')')
{
name[j] = '\0';
break;
}
name[j++] = buffer[i++];
}
}
| 2.484375 | 2 |
2024-11-18T21:15:46.069736+00:00
| 2021-01-26T06:37:51 |
c5e90caa026dd1db615e98150304a6b2e9b7f5bc
|
{
"blob_id": "c5e90caa026dd1db615e98150304a6b2e9b7f5bc",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-26T06:37:51",
"content_id": "0955212dad80736fbbd395686410a5be780e0969",
"detected_licenses": [
"MIT"
],
"directory_id": "439b88ae605992cfdc0f89cf656cf6b9ba7e9049",
"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": 297996906,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2547,
"license": "MIT",
"license_type": "permissive",
"path": "/3/main.c",
"provenance": "stackv2-0112.json.gz:10395",
"repo_name": "jaisuarez/LinkedListExercises",
"revision_date": "2021-01-26T06:37:51",
"revision_id": "fa6d0eae9103caa58dab8e5f8d5d3379f16bb098",
"snapshot_id": "bf30a8519636a3af72004356d1a6479425c49488",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jaisuarez/LinkedListExercises/fa6d0eae9103caa58dab8e5f8d5d3379f16bb098/3/main.c",
"visit_date": "2023-02-21T01:42:03.739926"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data; // Data of the node
struct node *nextPtr; // Address of the next node
};
struct node *firstNode;
// Function to generate the node list
void createNodeList(int numberOfNodes);
// Function to count the total nodes in the list
int countTotalNodes();
// Function to print the node list
void displayNodeList();
int main()
{
int userInput;
int totalNodes;
printf("Input the number of nodes : ");
scanf("%d", &userInput);
createNodeList(userInput);
printf("\nData entered in the list are : \n");
displayNodeList();
totalNodes = countTotalNodes();
printf("\nTotal number of nodes = %d\n", totalNodes);
return 0;
}
void createNodeList(int numberOfNodes)
{
struct node *newNode;
struct node *tempNode;
int userInput;
int nodeId;
firstNode = (struct node *)malloc(sizeof(struct node));
// Check if the firstNode memory has been allocated
if(firstNode == NULL)
{
printf("Memory can not be allocated.");
}
else
{
printf("Input data for node 1 : ");
scanf("%d", &userInput);
firstNode->data = userInput;
firstNode->nextPtr = NULL;
tempNode = firstNode;
// Creates (numberOfNodes - 1) nodes and adds to linked list
for(nodeId = 2; nodeId <= numberOfNodes; nodeId++)
{
newNode = (struct node *)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Memory can not be allocated.");
break;
}
else
{
printf("Input data for node %d : ", nodeId);
scanf("%d", &userInput);
newNode->data = userInput;
newNode->nextPtr = NULL;
tempNode->nextPtr = newNode;
tempNode = tempNode->nextPtr;
}
}
}
}
int countTotalNodes()
{
int totalNodes = 0;
struct node *tempNode;
tempNode = firstNode;
while (tempNode != NULL)
{
totalNodes++;
tempNode = tempNode->nextPtr;
}
return totalNodes;
}
void displayNodeList()
{
struct node *tempNode;
if (firstNode == NULL)
{
printf("No data found in the list.");
}
else
{
tempNode = firstNode;
while (tempNode != NULL)
{
printf("Data = %d\n", tempNode->data);
tempNode = tempNode->nextPtr;
}
}
}
| 3.984375 | 4 |
2024-11-18T21:15:46.326094+00:00
| 2018-10-13T04:54:29 |
4ca6bbc9f0fedf3240264acc6c2963c46d0d349c
|
{
"blob_id": "4ca6bbc9f0fedf3240264acc6c2963c46d0d349c",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-13T04:54:29",
"content_id": "ee6e8f3e9747550d844ba473735ac414b5b71e90",
"detected_licenses": [
"MIT"
],
"directory_id": "3d8fd26b8f1cec26c65736ac98b7b2e80b81e4a0",
"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": 151948173,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3331,
"license": "MIT",
"license_type": "permissive",
"path": "/BTApp_Rpi/src/main.c",
"provenance": "stackv2-0112.json.gz:10652",
"repo_name": "pranav-gargeshwari/Rpi-RGB_LEDControl-AndroidApp",
"revision_date": "2018-10-13T04:54:29",
"revision_id": "83efb397c7e3ead686151d4d38e1b19742e98089",
"snapshot_id": "22d3d5fcd89a6a8733945c3de0dff88eaad97263",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/pranav-gargeshwari/Rpi-RGB_LEDControl-AndroidApp/83efb397c7e3ead686151d4d38e1b19742e98089/BTApp_Rpi/src/main.c",
"visit_date": "2020-03-31T05:29:26.701038"
}
|
stackv2
|
///-----------------------------------------------------------------
/// Description: <Description>
/// Author: <Author> Date: <DateTime>
/// Notes: <Notes>
/// Revision History:
/// Name: Date: Description:
///-----------------------------------------------------------------
#include <stdio.h>
#include <unistd.h> //Used for UART
#include <fcntl.h> //Used for UART
#include <termios.h> //Used for UART
#include <wiringPi.h>
struct termios rfcomm;
int rfcomm_fd = -1;
int openSerial(char *devName)
{
int err;
char *deviceName;
deviceName = (devName == NULL) ? "/dev/ttyUSB0" : devName;
rfcomm_fd = open(deviceName,O_RDWR | O_NONBLOCK);
if(rfcomm_fd == -1)
{
printf("Failed to open KX3 device %s, %m\n",deviceName);
return 0;
}
err = tcgetattr(rfcomm_fd,&rfcomm);
if(err != 0)
{
printf("tcgetattr failed:");
return 0;
}
cfsetospeed(&rfcomm,B9600);
rfcomm.c_cc[VMIN] = 0;
rfcomm.c_cc[VTIME] = 0;
cfmakeraw(&rfcomm);
// rfcomm.c_cflag &= ~CRTSCTS;
tcsetattr(rfcomm_fd,TCSANOW,&rfcomm);
tcflush(rfcomm_fd,TCIFLUSH);
return 1;
}
int main(void)
{
printf("\nUART test\n\n");
openSerial("/dev/rfcomm0");
char buf[] = "hello world";
int count = write(rfcomm_fd, buf,strlen(buf)+1);
printf("%i bytes transmitted...\n\n");
int led= 1;
int red = 7;
int green = 9;
int blue = 8;
if (wiringPiSetup() == -1)
exit (1);
pinMode(led, OUTPUT);
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
digitalWrite(red, 1);
digitalWrite(green, 1);
digitalWrite(blue, 1);
printf("listening...\n\n");
while(1)
{
if (rfcomm_fd != -1)
{
// Read up to 255 characters from the port if they are there
unsigned char rx_buffer[256];
int rx_length = read(rfcomm_fd, (void*)rx_buffer, 255);//Filestream, buffer to store in, number of bytes to read (max)
if (rx_length < 0)
{
//An error occured (will occur if there are no bytes)
}
else if (rx_length == 0)
{
//No data waiting
}
else
{
//Bytes received
rx_buffer[rx_length] = '\0';
printf("%i bytes read : %s\n", rx_length, rx_buffer);
if(rx_buffer[0] == 'R')
{
digitalWrite(red, 0);
digitalWrite(green, 1);
digitalWrite(blue, 1);
}
else if(rx_buffer[0] == 'G')
{
digitalWrite(red, 1);
digitalWrite(green, 0);
digitalWrite(blue, 1);
}
else if(rx_buffer[0] == 'B')
{
digitalWrite(red, 1);
digitalWrite(green, 1);
digitalWrite(blue, 0);
}
if(rx_buffer[0] == 'X')
{
digitalWrite(led, 1);
}
else if(rx_buffer[0] == 'O')
{
digitalWrite(led, 0);
}
}
}
}
}
| 2.890625 | 3 |
2024-11-18T21:15:47.204337+00:00
| 2018-03-14T12:44:12 |
6061932cbd530c40cf89011c0df6d1ad61e3cedf
|
{
"blob_id": "6061932cbd530c40cf89011c0df6d1ad61e3cedf",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-14T12:44:12",
"content_id": "f30f61d9180da1ab99c17789a8eb413b00060652",
"detected_licenses": [
"MIT"
],
"directory_id": "746d3cd0696fd3f784acf661812ef371a5ecebb7",
"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": 108884383,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 448,
"license": "MIT",
"license_type": "permissive",
"path": "/chapter10/exercises/5.c",
"provenance": "stackv2-0112.json.gz:11040",
"repo_name": "ygdm7/ProgrammingInCSolutions",
"revision_date": "2018-03-14T12:44:12",
"revision_id": "5812605683809c6517ca5eb733cfb14e2b21afa5",
"snapshot_id": "5b80e5f36c5d8f78be70a45f64809383739e087d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ygdm7/ProgrammingInCSolutions/5812605683809c6517ca5eb733cfb14e2b21afa5/chapter10/exercises/5.c",
"visit_date": "2021-09-09T08:55:36.038773"
}
|
stackv2
|
// Exercise 5 from chapter 10
// This function determines if one string exists inside another string.
int findString( char string[], char sub[] )
{
int i = 0, j = 0, count = 0;
while( string[i] )
{
if( string[i] == sub[0] )
{
while( sub[j] )
{
if( string[i + j] == sub[j] )
count++;
else
{
j = 0;
break;
}
j++;
if( sub[j] == '\0' )
return i;
}
}
i++;
}
return -1;
}
| 3.078125 | 3 |
2024-11-18T21:15:47.304385+00:00
| 2020-03-31T05:39:25 |
a771e0abf77a7f4d9bc58a88da5bfd87b203fae1
|
{
"blob_id": "a771e0abf77a7f4d9bc58a88da5bfd87b203fae1",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-31T05:39:25",
"content_id": "9287002270160306fa6233dfb5e5ca11e3a11bde",
"detected_licenses": [
"MIT"
],
"directory_id": "2d477662493d735f45b2dd48182b2d913f6af28a",
"extension": "c",
"filename": "util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 183415186,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1170,
"license": "MIT",
"license_type": "permissive",
"path": "/util.c",
"provenance": "stackv2-0112.json.gz:11170",
"repo_name": "clwgg/bsh-ref",
"revision_date": "2020-03-31T05:39:25",
"revision_id": "6e92c3e34b3b8247805b3cb0a4c4d73488f4e458",
"snapshot_id": "5af4e1a465b049cf13f667eaa8869a893b18a208",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/clwgg/bsh-ref/6e92c3e34b3b8247805b3cb0a4c4d73488f4e458/util.c",
"visit_date": "2020-05-17T01:02:28.545062"
}
|
stackv2
|
#include <stdlib.h>
#include <stdint.h>
#include <zlib.h>
#include <limits.h>
#include "util.h"
#include "htslib/htslib/kseq.h"
KSTREAM_INIT(gzFile, gzread, 16384)
int nrows(char *fn)
{
gzFile file;
kstream_t *ks;
kstring_t str = {0,0,NULL};
file = gzopen(fn, "r");
if (!file) return -1;
ks = ks_init(file);
int i = 0;
while (ks_getuntil(ks, '\n', &str, 0) >= 0) {
++i;
}
gzclose(file);
ks_destroy(ks);
free(str.s);
return i;
}
int ncols(char *fn, int offset)
{
gzFile file;
kstream_t *ks;
kstring_t str = {0,0,NULL};
file = gzopen(fn, "r");
if (!file) return -1;
ks = ks_init(file);
ks_getuntil(ks, '\n', &str, 0);
char *token;
token = strtok(str.s, " \t");
int i = 1;
while((token = strtok(NULL, " \t"))) {
++i;
}
gzclose(file);
ks_destroy(ks);
free(str.s);
return i - offset;
}
void close_outf(outf_t *outf)
{
if (outf->pfout) fclose(outf->pfout);
if (outf->adfout) fclose(outf->adfout);
if (outf->safout) fclose(outf->safout);
}
int numPlaces(int n)
{
if (n < 0) return numPlaces ((n == INT_MIN) ? INT_MAX: -n);
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
| 2.328125 | 2 |
2024-11-18T21:15:48.375488+00:00
| 2020-01-20T11:14:03 |
89d86d99c7654a7bdcf82f439a2b021f653d9312
|
{
"blob_id": "89d86d99c7654a7bdcf82f439a2b021f653d9312",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-20T11:14:03",
"content_id": "20fe2c4ec8eab246a0a70179164fb3ea9cd0df71",
"detected_licenses": [
"MIT"
],
"directory_id": "522c8a7b1b7fc6fd1adcf248a2d71caaabf7fe69",
"extension": "c",
"filename": "timer_ps.c",
"fork_events_count": 0,
"gha_created_at": "2019-09-02T03:27:57",
"gha_event_created_at": "2020-01-20T11:14:04",
"gha_language": "VHDL",
"gha_license_id": "MIT",
"github_id": 205770112,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4168,
"license": "MIT",
"license_type": "permissive",
"path": "/11-streamHDMI/c_sources/stream/timer_ps/timer_ps.c",
"provenance": "stackv2-0112.json.gz:11428",
"repo_name": "johnnv1/fpgaProjects",
"revision_date": "2020-01-20T11:14:03",
"revision_id": "82e567dbc886434a060db89a18c53a866fa678c4",
"snapshot_id": "21f103911fbabab38eee5405b33676c2ec6761fe",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/johnnv1/fpgaProjects/82e567dbc886434a060db89a18c53a866fa678c4/11-streamHDMI/c_sources/stream/timer_ps/timer_ps.c",
"visit_date": "2020-07-16T10:19:22.249039"
}
|
stackv2
|
/************************************************************************/
/* */
/* timer_ps.c -- Timer Delay for Zynq systems */
/* */
/************************************************************************/
/* Author: Sam Bobrowicz */
/* Copyright 2014, Digilent Inc. */
/************************************************************************/
/* Module Description: */
/* */
/* Implements an accurate delay function using the scu timer. */
/* Code from this module will cause conflicts with other code that */
/* requires the Zynq's scu timer. */
/* */
/* This module contains code from the Xilinx Demo titled */
/* "xscutimer_polled_example.c" */
/* */
/************************************************************************/
/* Revision History: */
/* */
/* 2/14/2014(SamB): Created */
/* */
/************************************************************************/
/* ------------------------------------------------------------ */
/* Include File Definitions */
/* ------------------------------------------------------------ */
#include "timer_ps.h"
//#include "xscutimer.h"
#include "xil_types.h"
#include "xttcps.h"
/* ------------------------------------------------------------ */
/* Global Variables */
/* ------------------------------------------------------------ */
XTtcPs Timer0Instance;
//XScuTimer TimerInstance; /* Cortex A9 Scu Private Timer Instance */
/* ------------------------------------------------------------ */
/* Procedure Definitions */
/* ------------------------------------------------------------ */
/*** TimerInitialize(u16 TimerDeviceId)
**
** Parameters:
** TimerDeviceId - The DEVICE ID of the Zynq SCU TIMER
**
** Return Value: int
** XST_SUCCESS if successful
**
** Errors:
**
** Description: Configures the global timer struct to access the
** the SCU timer. Can be called multiple times without
** error.
**
*/
int TimerInitialize(u16 TimerDeviceId)
{
int Status;
XTtcPs *timer0 = &Timer0Instance;
XTtcPs_Config *configTimer0;
//XScuTimer *TimerInstancePtr = &TimerInstance;
//XScuTimer_Config *ConfigTmrPtr;
/*
* Initialize the Scu Private Timer driver.
*/
configTimer0 = XTtcPs_LookupConfig(TimerDeviceId);
//ConfigTmrPtr = XScuTimer_LookupConfig(TimerDeviceId);
/*
* This is where the virtual address would be used, this example
* uses physical address. Note that it is not considered an error
* if the timer has already been initialized.
*/
Status = XTtcPs_CfgInitialize(timer0, configTimer0, configTimer0->BaseAddress);
//Status = XScuTimer_CfgInitialize(TimerInstancePtr, ConfigTmrPtr,ConfigTmrPtr->BaseAddr);
if (Status != XST_SUCCESS || Status != XST_DEVICE_IS_STARTED) {
return XST_FAILURE;
}
/*
* Set prescaler to 1
*/
XTtcPs_SetPrescaler(timer0, 0);
//XScuTimer_SetPrescaler(TimerInstancePtr, 0);
return Status;
}
/* ------------------------------------------------------------ */
/*** TimerDelay(u32 uSDelay)
**
** Parameters:
** uSDelay - Desired delay in micro seconds
**
** Return Value:
**
** Errors:
**
** Description: Blocks execution for the desired amount of time.
** TimerInitialize must have been called at least once
** before calling this function.
*/
/* ------------------------------------------------------------ */
void TimerDelay(u32 uSDelay)
{
u32 timerCnt;
printf("\n\n*[JGAA] - ATTENCION THIS FUNCTION DONT WORK, THE CONFIG/USE OF TCC IS WRONG*\n\n");
timerCnt = (TIMER_FREQ_HZ / 1000000) * uSDelay;
/*
XScuTimer_Stop(&TimerInstance);
XScuTimer_DisableAutoReload(&TimerInstance);
XScuTimer_LoadTimer(&TimerInstance, timerCnt);
XScuTimer_Start(&TimerInstance);
while (XScuTimer_GetCounterValue(&TimerInstance))
{}*/
XTtcPs_Stop(&Timer0Instance);
XTtcPs_ResetCounterValue(&Timer0Instance);
XTtcPs_Start(&Timer0Instance);
while(XTtcPs_GetCounterValue(&Timer0Instance) <= timerCnt){}
return;
}
/************************************************************************/
| 2.390625 | 2 |
2024-11-18T21:15:48.616123+00:00
| 2023-03-01T03:53:24 |
ce773ba7d9955515cf2c81f6d7a2a02d129287d0
|
{
"blob_id": "ce773ba7d9955515cf2c81f6d7a2a02d129287d0",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-01T03:53:24",
"content_id": "e874ff48cee74b524d540f72af940745f4c37150",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "dfa11b2384b284fa3385fdcd18c64771e3f9c18b",
"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": 88601831,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5061,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SampleCode/StdDriver/SYS_TrimIRC/main.c",
"provenance": "stackv2-0112.json.gz:11685",
"repo_name": "OpenNuvoton/Mini55BSP",
"revision_date": "2023-03-01T03:53:24",
"revision_id": "493efc58cb539cf23cc4723d3fc4288dd1948fcb",
"snapshot_id": "f00635cdca47d858c8468d9fb5c7d777d13acbc2",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/OpenNuvoton/Mini55BSP/493efc58cb539cf23cc4723d3fc4288dd1948fcb/SampleCode/StdDriver/SYS_TrimIRC/main.c",
"visit_date": "2023-03-03T20:39:03.785500"
}
|
stackv2
|
/**************************************************************************//**
* @file main.c
* @version V1.00
* $Revision: 1 $
* $Date: 15/07/03 2:55p $
* @brief Demonstrate how to use LXT to trim HIRC
*
* @note
* Copyright (C) 2015 Nuvoton Technology Corp. All rights reserved.
*****************************************************************************/
#include <stdio.h>
#include "Mini55Series.h"
/*---------------------------------------------------------------------------------------------------------*/
/* IRCTrim IRQ Handler */
/*---------------------------------------------------------------------------------------------------------*/
void HIRC_IRQHandler()
{
uint32_t status;
status=SYS_GET_IRCTRIM_INT_FLAG();
if(status & BIT1)
{
printf("Trim Failure Interrupt\n");
SYS_CLEAR_IRCTRIM_INT_FLAG(SYS_IRCTISTS_TFAILIF_Msk);
}
if(status & BIT2)
{
SYS_CLEAR_IRCTRIM_INT_FLAG(SYS_IRCTISTS_CLKERRIF_Msk);
printf("LXT Clock Error Lock\n");
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
int32_t SYS_Init(void)
{
/* Unlock protected registers */
SYS_UnlockReg();
/* Read User Config to select internal high speed RC */
if (SystemInit() < 0)
return -1;
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Enable HIRC */
CLK->PWRCTL |= CLK_PWRCTL_HIRCEN_Msk | CLK_PWRCTL_LIRCEN_Msk;
/* Waiting for clock ready */
CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk|CLK_STATUS_LIRCSTB_Msk);
/* Switch HCLK clock source to HIRC */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC,CLK_CLKDIV_HCLK(1));
/* STCLK to HIRC */
CLK_SetSysTickClockSrc(CLK_CLKSEL0_HCLKSEL_HIRC);
/* Enable IP clock */
CLK_EnableModuleClock(UART0_MODULE);
/* Select IP clock source */
CLK_SetModuleClock(UART0_MODULE,CLK_CLKSEL1_UART0SEL_HIRC,CLK_CLKDIV_UART(1));
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
/* Set P0 multi-function pins for UART RXD and TXD */
SYS->P0_MFP &= ~(SYS_MFP_P01_Msk | SYS_MFP_P00_Msk);
SYS->P0_MFP |= (SYS_MFP_P01_RXD | SYS_MFP_P00_TXD);
/* Set P3 multi-function pins for Clock Output */
SYS->P3_MFP = SYS_MFP_P36_CKO;
/* To update the variable SystemCoreClock */
SystemCoreClockUpdate();
/* Lock protected registers */
SYS_LockReg();
return 0;
}
void UART0_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init UART */
/*---------------------------------------------------------------------------------------------------------*/
/* Reset IP */
SYS_ResetModule(UART0_RST);
/* Configure UART0 and set UART0 Baudrate */
UART_Open(UART0, 115200);
}
int32_t main (void)
{
uint32_t status;
int32_t retval;
/* Init System, IP clock and multi-function I/O */
retval = SYS_Init();
/* Init UART0 for printf */
UART0_Init();
if (retval != 0)
{
printf("SYS_Init failed!\n");
while (1);
}
printf("\n\nCPU @ %dHz\n", SystemCoreClock);
printf("+----------------------------------------+\n");
printf("| Mni55 Trim IRC Sample Code |\n");
printf("+----------------------------------------+\n");
/* Enable Interrupt */
NVIC_EnableIRQ(HIRC_IRQn);
/* Enable IRC Trim, set HIRC clock to 22.1184Mhz and enable interrupt */
SYS_EnableIRCTrim(SYS_IRCTCTL_TRIM_22_1184M,SYS_IRCTIEN_CLKEIEN_Msk|SYS_IRCTIEN_TFAILIEN_Msk);
/* Waiting for HIRC Frequency Lock */
CLK_SysTickDelay(2000);
status=SYS_GET_IRCTRIM_INT_FLAG();
if(status & BIT0)
printf("HIRC Frequency Lock\n");
/* Enable CKO and output frequency = HIRC / 2 */
CLK_EnableCKO(CLK_CLKSEL2_FDIVSEL_HIRC,0,0);
printf("Press any key to disable IRC Trim Funciton\n");
getchar();
/* Disable IRC Trim */
SYS_DisableIRCTrim();
printf("Disable IRC Trim\n");
while(1);
}
/*** (C) COPYRIGHT 2015 Nuvoton Technology Corp. ***/
| 2.625 | 3 |
2024-11-18T21:15:48.748073+00:00
| 2015-07-18T22:14:30 |
7992b647228549dce16b39139ff07f0cbdbb91e5
|
{
"blob_id": "7992b647228549dce16b39139ff07f0cbdbb91e5",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-18T22:14:30",
"content_id": "b35468c5d5d390bbd976e7f999aad2f02afb0c10",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "aa37f719cdfe9d868bfec05666206e60301048a5",
"extension": "c",
"filename": "kind.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 19217148,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 428,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/type/kind.c",
"provenance": "stackv2-0112.json.gz:11814",
"repo_name": "lovasko/libctf",
"revision_date": "2015-07-18T22:14:30",
"revision_id": "6267ccf59b7c0f1111e2830fe388caf1d54cc47a",
"snapshot_id": "5ef2df497816cad5732c06a91cf4693b89e0a06a",
"src_encoding": "UTF-8",
"star_events_count": 20,
"url": "https://raw.githubusercontent.com/lovasko/libctf/6267ccf59b7c0f1111e2830fe388caf1d54cc47a/src/type/kind.c",
"visit_date": "2020-05-19T16:47:49.915934"
}
|
stackv2
|
#include "type/kind.h"
const char*
ctf_kind_to_string(ctf_kind kind)
{
static const char *translation_table[] =
{
"none",
"int",
"float",
"pointer",
"array",
"function",
"struct",
"union",
"enum",
"forward declaration",
"typedef",
"volatile",
"const",
"restrict"
};
if (kind <= CTF_KIND_MAX && kind >= CTF_KIND_MIN)
return translation_table[kind];
else
return "unresolvable";
}
| 2.078125 | 2 |
2024-11-18T21:15:49.355656+00:00
| 2020-03-06T12:46:01 |
225912f7fb44f1f80538b11318938ade28927f3f
|
{
"blob_id": "225912f7fb44f1f80538b11318938ade28927f3f",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-06T12:46:01",
"content_id": "fbd000bde91800afe898b46557ea6a74c5d26f67",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "ab8fc6dc5ec52a03d3b947eaef6e4c9bb054823c",
"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": 245389465,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12917,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/Projects/STM32L053R8-Nucleo/Applications/FreeRTOS/FreeRTOS_Mutexes/Src/main.c",
"provenance": "stackv2-0112.json.gz:12590",
"repo_name": "polya-xue/Wearable-indoor-navigation-system",
"revision_date": "2020-03-06T12:46:01",
"revision_id": "4aaaf220c9a42eba7935c708eacfee1e97a61c9c",
"snapshot_id": "4291600f0c5d267eefbadc911c089c0e2f02e265",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/polya-xue/Wearable-indoor-navigation-system/4aaaf220c9a42eba7935c708eacfee1e97a61c9c/Projects/STM32L053R8-Nucleo/Applications/FreeRTOS/FreeRTOS_Mutexes/Src/main.c",
"visit_date": "2021-02-23T01:24:17.537085"
}
|
stackv2
|
/**
******************************************************************************
* @file FreeRTOS/FreeRTOS_Mutexes/Src/main.c
* @author MCD Application Team
* @version V1.1.0
* @date 18-June-2014
* @brief Main program body
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "cmsis_os.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
#define mutexSHORT_DELAY ((uint32_t) 20)
#define mutexNO_DELAY ((uint32_t) 0)
#define mutexTWO_TICK_DELAY ((uint32_t) 2)
/* Private variables ---------------------------------------------------------*/
static osMutexId osMutex;
/* Variables used to detect and latch errors */
__IO uint32_t HighPriorityThreadCycles = 0, MediumPriorityThreadCycles = 0, LowPriorityThreadCycles = 0;
/* Handles of the two higher priority tasks, required so they can be resumed
(unsuspended) */
static osThreadId osHighPriorityThreadHandle, osMediumPriorityThreadHandle;
/* Private function prototypes -----------------------------------------------*/
static void MutexHighPriorityThread(void const *argument);
static void MutexMeduimPriorityThread(void const *argument);
static void MutexLowPriorityThread(void const *argument);
static void SystemClock_Config(void);
/* Private functions ---------------------------------------------------------*/
/**
* @brief Main program
* @param None
* @retval None
*/
int main(void)
{
/* STM32L0xx HAL library initialization:
- Configure the Flash prefetch, Flash preread and Buffer caches
- Systick timer is configured by default as source of time base, but user
can eventually implement his proper time base source (a general purpose
timer for example or other time source), keeping in mind that Time base
duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
handled in milliseconds basis.
- Low Level Initialization
*/
HAL_Init();
/* Configure the System clock to 2 MHz (Up to 32MHz possible) */
SystemClock_Config();
/* Initialize LED2 */
BSP_LED_Init(LED2);
/* Create the mutex */
osMutexDef(osMutex);
osMutex = osMutexCreate(osMutex(osMutex));
if(osMutex != NULL)
{
/* Define and create the high priority thread */
osThreadDef(MutHigh, MutexHighPriorityThread, osPriorityBelowNormal, 0, configMINIMAL_STACK_SIZE);
osHighPriorityThreadHandle = osThreadCreate(osThread(MutHigh), NULL);
/* Define and create the medium priority thread */
osThreadDef(MutMedium, MutexMeduimPriorityThread, osPriorityLow, 0, configMINIMAL_STACK_SIZE);
osMediumPriorityThreadHandle = osThreadCreate(osThread(MutMedium), NULL);
/* Define and create the low priority thread */
osThreadDef(MutLow, MutexLowPriorityThread, osPriorityIdle, 0, configMINIMAL_STACK_SIZE);
osThreadCreate(osThread(MutLow), NULL);
}
/* Start scheduler */
osKernelStart (NULL, NULL);
/* We should never get here as control is now taken by the scheduler */
for(;;);
}
/**
* @brief Mutex High Priority Thread.
* @param argument: Not used
* @retval None
*/
static void MutexHighPriorityThread(void const *argument)
{
/* Just to remove compiler warning */
(void) argument;
for(;;)
{
/* The first time through the mutex will be immediately available, on
subsequent times through the mutex will be held by the low priority thread
at this point and this Take will cause the low priority thread to inherit
the priority of this tadhr. In this case the block time must be
long enough to ensure the low priority thread will execute again before the
block time expires. If the block time does expire then the error
flag will be set here */
if(osMutexWait(osMutex, mutexTWO_TICK_DELAY) != osOK)
{
/* Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
/* Ensure the other thread attempting to access the mutex
are able to execute to ensure they either block (where a block
time is specified) or return an error (where no block time is
specified) as the mutex is held by this task */
osDelay(mutexSHORT_DELAY);
/* We should now be able to release the mutex .
When the mutex is available again the medium priority thread
should be unblocked but not run because it has a lower priority
than this thread. The low priority thread should also not run
at this point as it too has a lower priority than this thread */
if(osMutexRelease(osMutex) != osOK)
{
/* Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
/* Keep count of the number of cycles this thread has performed */
HighPriorityThreadCycles++;
/* Suspend ourselves to the medium priority thread can execute */
osThreadSuspend(NULL);
}
}
/**
* @brief Mutex Medium Priority Thread.
* @param argument: Not used
* @retval None
*/
static void MutexMeduimPriorityThread(void const *argument)
{
/* Just to remove compiler warning */
(void) argument;
for(;;)
{
/* This thread will run while the high-priority thread is blocked, and the
high-priority thread will block only once it has the mutex - therefore
this call should block until the high-priority thread has given up the
mutex, and not actually execute past this call until the high-priority
thread is suspended */
if(osMutexWait(osMutex, osWaitForever) == osOK)
{
if(osThreadIsSuspended(osHighPriorityThreadHandle) != osOK)
{
/* Did not expect to execute until the high priority thread was
suspended.
Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
else
{
/* Give the mutex back before suspending ourselves to allow
the low priority thread to obtain the mutex */
if(osMutexRelease(osMutex) != osOK)
{
/* Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
osThreadSuspend(NULL);
}
}
else
{
/* We should not leave the osMutexWait() function
until the mutex was obtained.
Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
/* The High and Medium priority threads should be in lock step */
if(HighPriorityThreadCycles != (MediumPriorityThreadCycles + 1))
{
/* Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
/* Keep count of the number of cycles this task has performed so a
stall can be detected */
MediumPriorityThreadCycles++;
}
}
/**
* @brief Mutex Low Priority Thread.
* @param argument: Not used
* @retval None
*/
static void MutexLowPriorityThread(void const *argument)
{
/* Just to remove compiler warning */
(void) argument;
for(;;)
{
/* Keep attempting to obtain the mutex. We should only obtain it when
the medium-priority thread has suspended itself, which in turn should only
happen when the high-priority thread is also suspended */
if(osMutexWait(osMutex, mutexNO_DELAY) == osOK)
{
/* Is the haigh and medium-priority threads suspended? */
if((osThreadIsSuspended(osHighPriorityThreadHandle) != osOK) || (osThreadIsSuspended(osMediumPriorityThreadHandle) != osOK))
{
/* Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
else
{
/* Keep count of the number of cycles this task has performed
so a stall can be detected */
LowPriorityThreadCycles++;
/* We can resume the other tasks here even though they have a
higher priority than the this thread. When they execute they
will attempt to obtain the mutex but fail because the low-priority
thread is still the mutex holder. this thread will then inherit
the higher priority. The medium-priority thread will block indefinitely
when it attempts to obtain the mutex, the high-priority thread will only
block for a fixed period and an error will be latched if the
high-priority thread has not returned the mutex by the time this
fixed period has expired */
osThreadResume(osMediumPriorityThreadHandle);
osThreadResume(osHighPriorityThreadHandle);
/* The other two tasks should now have executed and no longer
be suspended */
if((osThreadIsSuspended(osHighPriorityThreadHandle) == osOK) || (osThreadIsSuspended(osMediumPriorityThreadHandle) == osOK))
{
/* Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
/* Release the mutex, disinheriting the higher priority again */
if(osMutexRelease(osMutex) != osOK)
{
/* Toggle LED2 to indicate error */
BSP_LED_Toggle(LED2);
}
}
}
#if configUSE_PREEMPTION == 0
{
taskYIELD();
}
#endif
}
}
/**
* @brief System Clock Configuration
* The system Clock is configured as follow :
* System Clock source = MSI
* SYSCLK(Hz) = 2000000
* HCLK(Hz) = 2000000
* AHB Prescaler = 1
* APB1 Prescaler = 1
* APB2 Prescaler = 1
* Flash Latency(WS) = 0
* Main regulator output voltage = Scale3 mode
* @param None
* @retval None
*/
static void SystemClock_Config(void)
{
RCC_ClkInitTypeDef RCC_ClkInitStruct;
RCC_OscInitTypeDef RCC_OscInitStruct;
/* Enable Power Control clock */
__PWR_CLK_ENABLE();
/* The voltage scaling allows optimizing the power consumption when the device is
clocked below the maximum system frequency, to update the voltage scaling value
regarding system frequency refer to product datasheet. */
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);
/* Enable MSI Oscillator */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
RCC_OscInitStruct.MSIState = RCC_MSI_ON;
RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_5;
RCC_OscInitStruct.MSICalibrationValue = 0x00;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
/* Select MSI as system clock source and configure the HCLK, PCLK1 and PCLK2
clocks dividers */
RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0);
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* Infinite loop */
while (1)
{}
}
#endif
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 2.34375 | 2 |
2024-11-18T21:15:49.413929+00:00
| 2020-09-09T15:00:46 |
7428e595fa3f89ecf31500615792629ab2d5409d
|
{
"blob_id": "7428e595fa3f89ecf31500615792629ab2d5409d",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-09T15:00:46",
"content_id": "82187626314ee08c4b39264f45bfc4972e720bf8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ccc41db82e42bc370ec3c7984b1fed6b4b855667",
"extension": "c",
"filename": "thermal_sysfsread.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-21T07:46:35",
"gha_event_created_at": "2020-05-21T07:46:36",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 265787243,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7448,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/vm_thermal_utility/thermal_sysfsread.c",
"provenance": "stackv2-0112.json.gz:12719",
"repo_name": "saranyagopal1/device-intel-civ-thermal",
"revision_date": "2020-09-09T15:00:46",
"revision_id": "1415371f0835259cb9b2531904a9962ce55d6d13",
"snapshot_id": "f4994a86c40484629c5780f674e38077611cdea1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/saranyagopal1/device-intel-civ-thermal/1415371f0835259cb9b2531904a9962ce55d6d13/vm_thermal_utility/thermal_sysfsread.c",
"visit_date": "2022-12-15T09:35:43.140812"
}
|
stackv2
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include <linux/vm_sockets.h>
#include <sys/un.h>
#include "thermal_pkt.h"
#define TEST_PORT 14096
int start_connection(struct sockaddr_vm sa_listen, int listen_fd, socklen_t socklen_client);
int client_fd = 0;
int get_max_zones() {
char filename[45] = {0};
int count = 0;
while(1) {
snprintf(filename, sizeof(filename), "/sys/class/thermal/thermal_zone%d", count);
count++;
snprintf(filename + strlen(filename), sizeof(filename), "/type");
if(!access( filename, R_OK)) {
continue;
}
else
break;
}
return count-1;
}
/* read_sysfs_values: Function to read the filename sysfs value in thermal_zones
* module.
*/
void read_sysfs_values(char *base_path, char *filename, void *buf, int len, int flag)
{
char sysfs_path[120];
snprintf(sysfs_path, 120, "%s%s", base_path, "/");
snprintf(sysfs_path + strlen(sysfs_path), 120 - strlen(sysfs_path), "%s", filename);
FILE *fp = fopen(sysfs_path, "r");
if (!fp) { /* validate file open for reading */
fprintf (stderr, "Failed to open file for read.\n");
return;
}
if (flag==0)
fread(buf, len, 1, fp);
else
fscanf (fp, "%d", (int*)buf); /* read/validate value */
fclose (fp);
return;
}
/* populate_zone_info: Function to populate the zone_info struture with all
* the values for the zone number passed as variable here.
*/
void populate_zone_info (struct zone_info *zone, int zone_no) {
char base_path[120] = "/sys/class/thermal/thermal_zone";
char buf[50] = {0};
snprintf(base_path, sizeof(base_path), "/sys/class/thermal/thermal_zone%d", zone_no);
read_sysfs_values(base_path, TEMPERATURE, &zone->temperature, sizeof(zone->temperature), 1);
read_sysfs_values(base_path, TYPE, buf, 50, 0);
zone->number = zone_no;
if (strstr(buf, "x86_pkg_temp") != NULL) {
zone->type = CPU;
zone->trip_0 = CPU_TRIP_0;
zone->trip_1 = CPU_TRIP_1;
zone->trip_2 = CPU_TRIP_2;
return;
} else if (strstr(buf, "battery") != NULL) {
zone->type = BATTERY;
zone->trip_0 = zone->trip_1 = zone->trip_2 = UNKNOWN_TRIP;
return;
} else {
zone->type = UNKNOWN_TYPE;
zone->trip_0 = zone->trip_1 = zone->trip_2 = UNKNOWN_TRIP;
return;
}
return;
}
/* printf_zone_values: Print all the struture values for the
* structure variable passed
*/
void print_zone_values(struct zone_info zone) {
printf("Zone Number: %d\n", zone.number);
printf("Zone Type: %d\n", zone.type);
printf("Zone Temperature: %d\n", zone.temperature);
printf("Zone Trip Point 0: %d\n", zone.trip_0);
printf("Zone Trip Point 1: %d\n", zone.trip_1);
printf("Zone Trip Point 2: %d\n", zone.trip_2);
printf("\n");
return;
}
/* init_header_struct: Function to initialize the header struture with proper values.
* This works for both types of notification packets. (NotifyID = 1 || 2)
*/
void init_header_struct(struct header *head, uint32_t maximum_zone_no, int size_temp_type, uint16_t notifyID) {
strncpy((char *)head->intelipcid, INTELIPCID, sizeof(head->intelipcid));
head->notifyid = notifyID;
if (notifyID == 1)
head->length = maximum_zone_no * sizeof(struct zone_info);
else if (notifyID == 2)
head->length = maximum_zone_no * size_temp_type + sizeof(maximum_zone_no);
else
printf("Error: NotifyID doesn't match any known packet format\n");
return;
}
int send_pkt() {
char msgbuf[1024] = {0};
int maximum_zone_no = 0;
struct header head;
int return_value = 0;
int i = 0;
maximum_zone_no = get_max_zones();
struct zone_info zone[maximum_zone_no];
init_header_struct(&head, maximum_zone_no, 0, 1);
memcpy(msgbuf, (const unsigned char *)&head, sizeof(head));
for (i = 0; i < maximum_zone_no; i++) {
populate_zone_info(&zone[i], i);
memcpy(msgbuf + sizeof(head) + (i * sizeof(struct zone_info)), (const unsigned char *)&zone[i], sizeof(zone[i]));
}
return_value = send(client_fd, msgbuf, sizeof(msgbuf), MSG_DONTWAIT);
if (return_value == -1)
goto out;
init_header_struct(&head, maximum_zone_no, sizeof(zone[i].temperature) + sizeof(zone[i].type), 2);
char base_path[120] = "/sys/class/thermal/thermal_zone";
int size_one = sizeof(head) + sizeof(maximum_zone_no);
int size_two = sizeof(zone[0].type) + sizeof(zone[0].temperature);
while (1) {
sleep(1);
memcpy(msgbuf, (const unsigned char *)&head, sizeof(head));
/* TODO As of now we are sending the updated values for all the thermal zones
* But in future we will be sending the values of only the zones where there is
* an update in the temperature values. So below memcpy needs to be implemented
* properly with that implementation
*/
memcpy(msgbuf + sizeof(head), (const unsigned char *)&maximum_zone_no, sizeof(maximum_zone_no));
uint32_t temperature = 0;
for (i = 0; i < maximum_zone_no; i++) {
snprintf(base_path, sizeof(base_path), "/sys/class/thermal/thermal_zone%d", i);
memcpy(msgbuf + size_one + (i * size_two), (const unsigned char*)&zone[i].type, sizeof(zone[i].type));
read_sysfs_values(base_path, TEMPERATURE, &temperature, sizeof(temperature), 1);
memcpy(msgbuf + size_one + (i * size_two + sizeof(zone[i].type)), (const unsigned char*)&temperature, sizeof(temperature));
}
return_value = send(client_fd, msgbuf, sizeof(msgbuf), MSG_DONTWAIT);
if (return_value == -1)
goto out;
}
return 0;
out:
return -1;
}
int start_connection(struct sockaddr_vm sa_listen, int listen_fd, socklen_t socklen_client) {
struct sockaddr_vm sa_client;
fprintf(stderr, "Thermal utility listening on cid(%d), port(%d)\n", sa_listen.svm_cid, sa_listen.svm_port);
if (listen(listen_fd, 32) != 0) {
fprintf(stderr, "listen failed\n");
return -1;
}
client_fd = accept(listen_fd, (struct sockaddr*)&sa_client, &socklen_client);
if(client_fd < 0) {
fprintf(stderr, "accept failed\n");
return -1;
}
fprintf(stderr, "Thermal utility connected from guest(%d)\n", sa_client.svm_cid);
return 0;
}
int main()
{
int listen_fd = 0;
int ret = 0;
int return_value = 0;
struct sockaddr_vm sa_listen = {
.svm_family = AF_VSOCK,
.svm_cid = VMADDR_CID_ANY,
.svm_port = TEST_PORT,
};
socklen_t socklen_client = sizeof(struct sockaddr_vm);
listen_fd = socket(AF_VSOCK, SOCK_STREAM, 0);
if (listen_fd < 0) {
fprintf(stderr, "socket init failed\n");
ret = -1;
goto out;
}
if (bind(listen_fd, (struct sockaddr*)&sa_listen, sizeof(sa_listen)) != 0) {
perror("bind failed");
ret = -1;
goto out;
}
start:
ret = start_connection(sa_listen, listen_fd, socklen_client);
if (ret < 0)
goto out;
return_value = send_pkt();
if (return_value == -1)
goto start;
out:
if(listen_fd >= 0)
{
printf("Closing listen_fd\n");
close(listen_fd);
}
return ret;
}
| 2.15625 | 2 |
2024-11-18T21:15:51.243108+00:00
| 2023-08-27T19:14:02 |
e32f384c7fb711f984f055d6167a8a19181c95fe
|
{
"blob_id": "e32f384c7fb711f984f055d6167a8a19181c95fe",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T19:14:02",
"content_id": "7dc9e45af7b668aa4c663d91ad29f6f8472b837b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7c857119fe1505b1d80d6e62969661c06dc1a2f4",
"extension": "c",
"filename": "Ip6Driver.c",
"fork_events_count": 770,
"gha_created_at": "2019-09-02T08:22:14",
"gha_event_created_at": "2023-09-03T12:41:33",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 205810121,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 31323,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/NetworkPkg/Ip6Dxe/Ip6Driver.c",
"provenance": "stackv2-0112.json.gz:13107",
"repo_name": "CloverHackyColor/CloverBootloader",
"revision_date": "2023-08-27T19:14:02",
"revision_id": "2711170df4f60b2ae5aa20add3e00f35cf57b7e5",
"snapshot_id": "7042ca7dd6b513d22be591a295e49071ae1482ee",
"src_encoding": "UTF-8",
"star_events_count": 4734,
"url": "https://raw.githubusercontent.com/CloverHackyColor/CloverBootloader/2711170df4f60b2ae5aa20add3e00f35cf57b7e5/NetworkPkg/Ip6Dxe/Ip6Driver.c",
"visit_date": "2023-08-30T22:14:34.590134"
}
|
stackv2
|
/** @file
The driver binding and service binding protocol for IP6 driver.
Copyright (c) 2009 - 2019, Intel Corporation. All rights reserved.<BR>
(C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "Ip6Impl.h"
EFI_DRIVER_BINDING_PROTOCOL gIp6DriverBinding = {
Ip6DriverBindingSupported,
Ip6DriverBindingStart,
Ip6DriverBindingStop,
0xa,
NULL,
NULL
};
BOOLEAN mIpSec2Installed = FALSE;
/**
Callback function for IpSec2 Protocol install.
@param[in] Event Event whose notification function is being invoked
@param[in] Context Pointer to the notification function's context
**/
VOID
EFIAPI
IpSec2InstalledCallback (
IN EFI_EVENT Event,
IN VOID *Context
)
{
EFI_STATUS Status;
//
// Test if protocol was even found.
// Notification function will be called at least once.
//
Status = gBS->LocateProtocol (&gEfiIpSec2ProtocolGuid, NULL, (VOID **)&mIpSec);
if (Status == EFI_SUCCESS && mIpSec != NULL) {
//
// Close the event so it does not get called again.
//
gBS->CloseEvent (Event);
mIpSec2Installed = TRUE;
}
}
/**
This is the declaration of an EFI image entry point. This entry point is
the same for UEFI Applications, UEFI OS Loaders, and UEFI Drivers including
both device drivers and bus drivers.
The entry point for IP6 driver which installs the driver
binding and component name protocol on its image.
@param[in] ImageHandle The firmware allocated handle for the UEFI image.
@param[in] SystemTable A pointer to the EFI System Table.
@retval EFI_SUCCESS The operation completed successfully.
@retval EFI_OUT_OF_RESOURCES The request could not be completed due to a lack of resources.
**/
EFI_STATUS
EFIAPI
Ip6DriverEntryPoint (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
VOID *Registration;
EfiCreateProtocolNotifyEvent (
&gEfiIpSec2ProtocolGuid,
TPL_CALLBACK,
IpSec2InstalledCallback,
NULL,
&Registration
);
return EfiLibInstallDriverBindingComponentName2 (
ImageHandle,
SystemTable,
&gIp6DriverBinding,
ImageHandle,
&gIp6ComponentName,
&gIp6ComponentName2
);
}
/**
Test to see if this driver supports ControllerHandle.
@param[in] This Protocol instance pointer.
@param[in] ControllerHandle Handle of device to test.
@param[in] RemainingDevicePath Optional parameter use to pick a specific child
device to start.
@retval EFI_SUCCESS This driver supports this device.
@retval EFI_ALREADY_STARTED This driver is already running on this device.
@retval other This driver does not support this device.
**/
EFI_STATUS
EFIAPI
Ip6DriverBindingSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
)
{
//
// Test for the MNP service binding Protocol
//
return gBS->OpenProtocol (
ControllerHandle,
&gEfiManagedNetworkServiceBindingProtocolGuid,
NULL,
This->DriverBindingHandle,
ControllerHandle,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
}
/**
Clean up an IP6 service binding instance. It releases all
the resource allocated by the instance. The instance may be
partly initialized, or partly destroyed. If a resource is
destroyed, it is marked as that in case the destroy failed and
being called again later.
@param[in] IpSb The IP6 service binding instance to clean up.
@retval EFI_SUCCESS The resource used by the instance are cleaned up.
@retval Others Failed to clean up some of the resources.
**/
EFI_STATUS
Ip6CleanService (
IN IP6_SERVICE *IpSb
)
{
EFI_STATUS Status;
EFI_IPv6_ADDRESS AllNodes;
IP6_NEIGHBOR_ENTRY *NeighborCache;
IpSb->State = IP6_SERVICE_DESTROY;
if (IpSb->Timer != NULL) {
gBS->SetTimer (IpSb->Timer, TimerCancel, 0);
gBS->CloseEvent (IpSb->Timer);
IpSb->Timer = NULL;
}
if (IpSb->FasterTimer != NULL) {
gBS->SetTimer (IpSb->FasterTimer, TimerCancel, 0);
gBS->CloseEvent (IpSb->FasterTimer);
IpSb->FasterTimer = NULL;
}
Ip6ConfigCleanInstance (&IpSb->Ip6ConfigInstance);
if (!IpSb->LinkLocalDadFail) {
//
// Leave link-scope all-nodes multicast address (FF02::1)
//
Ip6SetToAllNodeMulticast (FALSE, IP6_LINK_LOCAL_SCOPE, &AllNodes);
Status = Ip6LeaveGroup (IpSb, &AllNodes);
if (EFI_ERROR (Status)) {
return Status;
}
}
if (IpSb->DefaultInterface != NULL) {
Ip6CleanInterface (IpSb->DefaultInterface, NULL);
IpSb->DefaultInterface = NULL;
}
Ip6CleanDefaultRouterList (IpSb);
Ip6CleanPrefixListTable (IpSb, &IpSb->OnlinkPrefix);
Ip6CleanPrefixListTable (IpSb, &IpSb->AutonomousPrefix);
if (IpSb->RouteTable != NULL) {
Ip6CleanRouteTable (IpSb->RouteTable);
IpSb->RouteTable = NULL;
}
if (IpSb->InterfaceId != NULL) {
FreePool (IpSb->InterfaceId);
}
IpSb->InterfaceId = NULL;
Ip6CleanAssembleTable (&IpSb->Assemble);
if (IpSb->MnpChildHandle != NULL) {
if (IpSb->Mnp != NULL) {
IpSb->Mnp->Cancel (IpSb->Mnp, NULL);
IpSb->Mnp->Configure (IpSb->Mnp, NULL);
gBS->CloseProtocol (
IpSb->MnpChildHandle,
&gEfiManagedNetworkProtocolGuid,
IpSb->Image,
IpSb->Controller
);
IpSb->Mnp = NULL;
}
NetLibDestroyServiceChild (
IpSb->Controller,
IpSb->Image,
&gEfiManagedNetworkServiceBindingProtocolGuid,
IpSb->MnpChildHandle
);
IpSb->MnpChildHandle = NULL;
}
if (IpSb->RecvRequest.MnpToken.Event != NULL) {
gBS->CloseEvent (IpSb->RecvRequest.MnpToken.Event);
}
//
// Free the Neighbor Discovery resources
//
while (!IsListEmpty (&IpSb->NeighborTable)) {
NeighborCache = NET_LIST_HEAD (&IpSb->NeighborTable, IP6_NEIGHBOR_ENTRY, Link);
Ip6FreeNeighborEntry (IpSb, NeighborCache, FALSE, TRUE, EFI_SUCCESS, NULL, NULL);
}
return EFI_SUCCESS;
}
/**
Create a new IP6 driver service binding protocol.
@param[in] Controller The controller that has MNP service binding
installed.
@param[in] ImageHandle The IP6 driver's image handle.
@param[out] Service The variable to receive the newly created IP6
service.
@retval EFI_OUT_OF_RESOURCES Failed to allocate some resources.
@retval EFI_SUCCESS A new IP6 service binding private is created.
**/
EFI_STATUS
Ip6CreateService (
IN EFI_HANDLE Controller,
IN EFI_HANDLE ImageHandle,
OUT IP6_SERVICE **Service
)
{
IP6_SERVICE *IpSb;
EFI_STATUS Status;
EFI_MANAGED_NETWORK_COMPLETION_TOKEN *MnpToken;
EFI_MANAGED_NETWORK_CONFIG_DATA *Config;
ASSERT (Service != NULL);
*Service = NULL;
//
// allocate a service private data then initialize all the filed to
// empty resources, so if any thing goes wrong when allocating
// resources, Ip6CleanService can be called to clean it up.
//
IpSb = AllocateZeroPool (sizeof (IP6_SERVICE));
if (IpSb == NULL) {
return EFI_OUT_OF_RESOURCES;
}
IpSb->Signature = IP6_SERVICE_SIGNATURE;
IpSb->ServiceBinding.CreateChild = Ip6ServiceBindingCreateChild;
IpSb->ServiceBinding.DestroyChild = Ip6ServiceBindingDestroyChild;
IpSb->State = IP6_SERVICE_UNSTARTED;
IpSb->NumChildren = 0;
InitializeListHead (&IpSb->Children);
InitializeListHead (&IpSb->Interfaces);
IpSb->DefaultInterface = NULL;
IpSb->RouteTable = NULL;
IpSb->RecvRequest.Signature = IP6_LINK_RX_SIGNATURE;
IpSb->RecvRequest.CallBack = NULL;
IpSb->RecvRequest.Context = NULL;
MnpToken = &IpSb->RecvRequest.MnpToken;
MnpToken->Event = NULL;
MnpToken->Status = EFI_NOT_READY;
MnpToken->Packet.RxData = NULL;
Ip6CreateAssembleTable (&IpSb->Assemble);
IpSb->MldCtrl.Mldv1QuerySeen = 0;
InitializeListHead (&IpSb->MldCtrl.Groups);
ZeroMem (&IpSb->LinkLocalAddr, sizeof (EFI_IPv6_ADDRESS));
IpSb->LinkLocalOk = FALSE;
IpSb->LinkLocalDadFail = FALSE;
IpSb->Dhcp6NeedStart = FALSE;
IpSb->Dhcp6NeedInfoRequest = FALSE;
IpSb->CurHopLimit = IP6_HOP_LIMIT;
IpSb->LinkMTU = IP6_MIN_LINK_MTU;
IpSb->BaseReachableTime = IP6_REACHABLE_TIME;
Ip6UpdateReachableTime (IpSb);
//
// RFC4861 RETRANS_TIMER: 1,000 milliseconds
//
IpSb->RetransTimer = IP6_RETRANS_TIMER;
IpSb->RoundRobin = 0;
InitializeListHead (&IpSb->NeighborTable);
InitializeListHead (&IpSb->DefaultRouterList);
InitializeListHead (&IpSb->OnlinkPrefix);
InitializeListHead (&IpSb->AutonomousPrefix);
IpSb->InterfaceIdLen = IP6_IF_ID_LEN;
IpSb->InterfaceId = NULL;
IpSb->RouterAdvertiseReceived = FALSE;
IpSb->SolicitTimer = IP6_MAX_RTR_SOLICITATIONS;
IpSb->Ticks = 0;
IpSb->Image = ImageHandle;
IpSb->Controller = Controller;
IpSb->MnpChildHandle = NULL;
IpSb->Mnp = NULL;
Config = &IpSb->MnpConfigData;
Config->ReceivedQueueTimeoutValue = 0;
Config->TransmitQueueTimeoutValue = 0;
Config->ProtocolTypeFilter = IP6_ETHER_PROTO;
Config->EnableUnicastReceive = TRUE;
Config->EnableMulticastReceive = TRUE;
Config->EnableBroadcastReceive = TRUE;
Config->EnablePromiscuousReceive = FALSE;
Config->FlushQueuesOnReset = TRUE;
Config->EnableReceiveTimestamps = FALSE;
Config->DisableBackgroundPolling = FALSE;
ZeroMem (&IpSb->SnpMode, sizeof (EFI_SIMPLE_NETWORK_MODE));
IpSb->Timer = NULL;
IpSb->FasterTimer = NULL;
ZeroMem (&IpSb->Ip6ConfigInstance, sizeof (IP6_CONFIG_INSTANCE));
IpSb->MacString = NULL;
//
// Create various resources. First create the route table, timer
// event, MNP token event and MNP child.
//
IpSb->RouteTable = Ip6CreateRouteTable ();
if (IpSb->RouteTable == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto ON_ERROR;
}
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL | EVT_TIMER,
TPL_CALLBACK,
Ip6TimerTicking,
IpSb,
&IpSb->Timer
);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL | EVT_TIMER,
TPL_CALLBACK,
Ip6NdFasterTimerTicking,
IpSb,
&IpSb->FasterTimer
);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = NetLibCreateServiceChild (
Controller,
ImageHandle,
&gEfiManagedNetworkServiceBindingProtocolGuid,
&IpSb->MnpChildHandle
);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = gBS->OpenProtocol (
IpSb->MnpChildHandle,
&gEfiManagedNetworkProtocolGuid,
(VOID **) (&IpSb->Mnp),
ImageHandle,
Controller,
EFI_OPEN_PROTOCOL_BY_DRIVER
);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = Ip6ServiceConfigMnp (IpSb, TRUE);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = IpSb->Mnp->GetModeData (IpSb->Mnp, NULL, &IpSb->SnpMode);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
IpSb->MaxPacketSize = IP6_MIN_LINK_MTU - sizeof (EFI_IP6_HEADER);
if (NetLibGetVlanId (IpSb->Controller) != 0) {
//
// This is a VLAN device, reduce MTU by VLAN tag length
//
IpSb->MaxPacketSize -= NET_VLAN_TAG_LEN;
}
IpSb->OldMaxPacketSize = IpSb->MaxPacketSize;
//
// Currently only ETHERNET is supported in IPv6 stack, since
// link local address requires an IEEE 802 48-bit MACs for
// EUI-64 format interface identifier mapping.
//
if (IpSb->SnpMode.IfType != NET_IFTYPE_ETHERNET) {
Status = EFI_UNSUPPORTED;
goto ON_ERROR;
}
Status = Ip6InitMld (IpSb);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = NetLibGetMacString (IpSb->Controller, IpSb->Image, &IpSb->MacString);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = Ip6ConfigInitInstance (&IpSb->Ip6ConfigInstance);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
IpSb->DefaultInterface = Ip6CreateInterface (IpSb, TRUE);
if (IpSb->DefaultInterface == NULL) {
Status = EFI_DEVICE_ERROR;
goto ON_ERROR;
}
Status = gBS->CreateEvent (
EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
Ip6OnFrameReceived,
&IpSb->RecvRequest,
&MnpToken->Event
);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
InsertHeadList (&IpSb->Interfaces, &IpSb->DefaultInterface->Link);
*Service = IpSb;
return EFI_SUCCESS;
ON_ERROR:
Ip6CleanService (IpSb);
FreePool (IpSb);
return Status;
}
/**
Start this driver on ControllerHandle.
@param[in] This Protocol instance pointer.
@param[in] ControllerHandle Handle of device to bind driver to.
@param[in] RemainingDevicePath Optional parameter used to pick a specific child
device to start.
@retval EFI_SUCCES This driver is added to ControllerHandle.
@retval EFI_ALREADY_STARTED This driver is already running on ControllerHandle.
@retval other This driver does not support this device.
**/
EFI_STATUS
EFIAPI
Ip6DriverBindingStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
)
{
IP6_SERVICE *IpSb;
EFI_STATUS Status;
EFI_IP6_CONFIG_PROTOCOL *Ip6Cfg;
IP6_CONFIG_DATA_ITEM *DataItem;
IpSb = NULL;
Ip6Cfg = NULL;
DataItem = NULL;
//
// Test for the Ip6 service binding protocol
//
Status = gBS->OpenProtocol (
ControllerHandle,
&gEfiIp6ServiceBindingProtocolGuid,
NULL,
This->DriverBindingHandle,
ControllerHandle,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
if (Status == EFI_SUCCESS) {
return EFI_ALREADY_STARTED;
}
Status = Ip6CreateService (ControllerHandle, This->DriverBindingHandle, &IpSb);
if (EFI_ERROR (Status)) {
return Status;
}
ASSERT (IpSb != NULL);
Ip6Cfg = &IpSb->Ip6ConfigInstance.Ip6Config;
//
// Install the Ip6ServiceBinding Protocol onto ControlerHandle
//
Status = gBS->InstallMultipleProtocolInterfaces (
&ControllerHandle,
&gEfiIp6ServiceBindingProtocolGuid,
&IpSb->ServiceBinding,
&gEfiIp6ConfigProtocolGuid,
Ip6Cfg,
NULL
);
if (EFI_ERROR (Status)) {
goto FREE_SERVICE;
}
//
// Read the config data from NV variable again.
// The default data can be changed by other drivers.
//
Status = Ip6ConfigReadConfigData (IpSb->MacString, &IpSb->Ip6ConfigInstance);
if (EFI_ERROR (Status)) {
goto UNINSTALL_PROTOCOL;
}
//
// If there is any default manual address, set it.
//
DataItem = &IpSb->Ip6ConfigInstance.DataItem[Ip6ConfigDataTypeManualAddress];
if (DataItem->Data.Ptr != NULL) {
Status = Ip6Cfg->SetData (
Ip6Cfg,
Ip6ConfigDataTypeManualAddress,
DataItem->DataSize,
DataItem->Data.Ptr
);
if (Status == EFI_INVALID_PARAMETER || Status == EFI_BAD_BUFFER_SIZE) {
//
// Clean the invalid ManualAddress configuration.
//
Status = Ip6Cfg->SetData (
Ip6Cfg,
Ip6ConfigDataTypeManualAddress,
0,
NULL
);
DEBUG ((EFI_D_WARN, "Ip6DriverBindingStart: Clean the invalid ManualAddress configuration.\n"));
}
}
//
// If there is any default gateway address, set it.
//
DataItem = &IpSb->Ip6ConfigInstance.DataItem[Ip6ConfigDataTypeGateway];
if (DataItem->Data.Ptr != NULL) {
Status = Ip6Cfg->SetData (
Ip6Cfg,
Ip6ConfigDataTypeGateway,
DataItem->DataSize,
DataItem->Data.Ptr
);
if (Status == EFI_INVALID_PARAMETER || Status == EFI_BAD_BUFFER_SIZE) {
//
// Clean the invalid Gateway configuration.
//
Status = Ip6Cfg->SetData (
Ip6Cfg,
Ip6ConfigDataTypeGateway,
0,
NULL
);
DEBUG ((EFI_D_WARN, "Ip6DriverBindingStart: Clean the invalid Gateway configuration.\n"));
}
}
//
// ready to go: start the receiving and timer
//
Status = Ip6ReceiveFrame (Ip6AcceptFrame, IpSb);
if (EFI_ERROR (Status)) {
goto UNINSTALL_PROTOCOL;
}
//
// The timer expires every 100 (IP6_TIMER_INTERVAL_IN_MS) milliseconds.
//
Status = gBS->SetTimer (
IpSb->FasterTimer,
TimerPeriodic,
TICKS_PER_MS * IP6_TIMER_INTERVAL_IN_MS
);
if (EFI_ERROR (Status)) {
goto UNINSTALL_PROTOCOL;
}
//
// The timer expires every 1000 (IP6_ONE_SECOND_IN_MS) milliseconds.
//
Status = gBS->SetTimer (
IpSb->Timer,
TimerPeriodic,
TICKS_PER_MS * IP6_ONE_SECOND_IN_MS
);
if (EFI_ERROR (Status)) {
goto UNINSTALL_PROTOCOL;
}
//
// Initialize the IP6 ID
//
mIp6Id = NET_RANDOM (NetRandomInitSeed ());
return EFI_SUCCESS;
UNINSTALL_PROTOCOL:
gBS->UninstallMultipleProtocolInterfaces (
ControllerHandle,
&gEfiIp6ServiceBindingProtocolGuid,
&IpSb->ServiceBinding,
&gEfiIp6ConfigProtocolGuid,
Ip6Cfg,
NULL
);
FREE_SERVICE:
Ip6CleanService (IpSb);
FreePool (IpSb);
return Status;
}
/**
Callback function which provided by user to remove one node in NetDestroyLinkList process.
@param[in] Entry The entry to be removed.
@param[in] Context Pointer to the callback context corresponds to the Context in NetDestroyLinkList.
@retval EFI_SUCCESS The entry has been removed successfully.
@retval Others Fail to remove the entry.
**/
EFI_STATUS
EFIAPI
Ip6DestroyChildEntryInHandleBuffer (
IN LIST_ENTRY *Entry,
IN VOID *Context
)
{
IP6_PROTOCOL *IpInstance;
EFI_SERVICE_BINDING_PROTOCOL *ServiceBinding;
UINTN NumberOfChildren;
EFI_HANDLE *ChildHandleBuffer;
if (Entry == NULL || Context == NULL) {
return EFI_INVALID_PARAMETER;
}
IpInstance = NET_LIST_USER_STRUCT_S (Entry, IP6_PROTOCOL, Link, IP6_PROTOCOL_SIGNATURE);
ServiceBinding = ((IP6_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT *) Context)->ServiceBinding;
NumberOfChildren = ((IP6_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT *) Context)->NumberOfChildren;
ChildHandleBuffer = ((IP6_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT *) Context)->ChildHandleBuffer;
if (!NetIsInHandleBuffer (IpInstance->Handle, NumberOfChildren, ChildHandleBuffer)) {
return EFI_SUCCESS;
}
return ServiceBinding->DestroyChild (ServiceBinding, IpInstance->Handle);
}
/**
Stop this driver on ControllerHandle.
@param[in] This Protocol instance pointer.
@param[in] ControllerHandle Handle of device to stop driver on.
@param[in] NumberOfChildren Number of Handles in ChildHandleBuffer. If number
of children is zero, stop the entire bus driver.
@param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
if NumberOfChildren is 0.
@retval EFI_SUCCESS The device was stopped.
@retval EFI_DEVICE_ERROR The device could not be stopped due to a device error.
**/
EFI_STATUS
EFIAPI
Ip6DriverBindingStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
)
{
EFI_SERVICE_BINDING_PROTOCOL *ServiceBinding;
IP6_SERVICE *IpSb;
EFI_HANDLE NicHandle;
EFI_STATUS Status;
LIST_ENTRY *List;
INTN State;
BOOLEAN IsDhcp6;
IP6_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT Context;
IsDhcp6 = FALSE;
NicHandle = NetLibGetNicHandle (ControllerHandle, &gEfiManagedNetworkProtocolGuid);
if (NicHandle == NULL) {
NicHandle = NetLibGetNicHandle (ControllerHandle, &gEfiDhcp6ProtocolGuid);
if (NicHandle != NULL) {
IsDhcp6 = TRUE;
} else {
return EFI_SUCCESS;
}
}
Status = gBS->OpenProtocol (
NicHandle,
&gEfiIp6ServiceBindingProtocolGuid,
(VOID **) &ServiceBinding,
This->DriverBindingHandle,
NicHandle,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
return EFI_DEVICE_ERROR;
}
IpSb = IP6_SERVICE_FROM_PROTOCOL (ServiceBinding);
if (IsDhcp6) {
Status = Ip6ConfigDestroyDhcp6 (&IpSb->Ip6ConfigInstance);
gBS->CloseEvent (IpSb->Ip6ConfigInstance.Dhcp6Event);
IpSb->Ip6ConfigInstance.Dhcp6Event = NULL;
} else if (NumberOfChildren != 0) {
//
// NumberOfChildren is not zero, destroy the IP6 children instances in ChildHandleBuffer.
//
List = &IpSb->Children;
Context.ServiceBinding = ServiceBinding;
Context.NumberOfChildren = NumberOfChildren;
Context.ChildHandleBuffer = ChildHandleBuffer;
Status = NetDestroyLinkList (
List,
Ip6DestroyChildEntryInHandleBuffer,
&Context,
NULL
);
} else if (IsListEmpty (&IpSb->Children)) {
State = IpSb->State;
Status = Ip6CleanService (IpSb);
if (EFI_ERROR (Status)) {
IpSb->State = State;
goto Exit;
}
Status = gBS->UninstallMultipleProtocolInterfaces (
NicHandle,
&gEfiIp6ServiceBindingProtocolGuid,
ServiceBinding,
&gEfiIp6ConfigProtocolGuid,
&IpSb->Ip6ConfigInstance.Ip6Config,
NULL
);
ASSERT_EFI_ERROR (Status);
FreePool (IpSb);
Status = EFI_SUCCESS;
}
Exit:
return Status;
}
/**
Creates a child handle with a set of I/O services.
@param[in] This Protocol instance pointer.
@param[in] ChildHandle Pointer to the handle of the child to create. If
it is NULL, then a new handle is created. If it
is not NULL, then the I/O services are added to
the existing child handle.
@retval EFI_SUCCES The child handle was created with the I/O services.
@retval EFI_OUT_OF_RESOURCES There are not enough resources available to create
the child.
@retval other The child handle was not created.
**/
EFI_STATUS
EFIAPI
Ip6ServiceBindingCreateChild (
IN EFI_SERVICE_BINDING_PROTOCOL *This,
IN EFI_HANDLE *ChildHandle
)
{
IP6_SERVICE *IpSb;
IP6_PROTOCOL *IpInstance;
EFI_TPL OldTpl;
EFI_STATUS Status;
VOID *Mnp;
if ((This == NULL) || (ChildHandle == NULL)) {
return EFI_INVALID_PARAMETER;
}
IpSb = IP6_SERVICE_FROM_PROTOCOL (This);
if (IpSb->LinkLocalDadFail) {
return EFI_DEVICE_ERROR;
}
IpInstance = AllocatePool (sizeof (IP6_PROTOCOL));
if (IpInstance == NULL) {
return EFI_OUT_OF_RESOURCES;
}
Ip6InitProtocol (IpSb, IpInstance);
//
// Install Ip6 onto ChildHandle
//
Status = gBS->InstallMultipleProtocolInterfaces (
ChildHandle,
&gEfiIp6ProtocolGuid,
&IpInstance->Ip6Proto,
NULL
);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
IpInstance->Handle = *ChildHandle;
//
// Open the Managed Network protocol BY_CHILD.
//
Status = gBS->OpenProtocol (
IpSb->MnpChildHandle,
&gEfiManagedNetworkProtocolGuid,
(VOID **) &Mnp,
gIp6DriverBinding.DriverBindingHandle,
IpInstance->Handle,
EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
);
if (EFI_ERROR (Status)) {
gBS->UninstallMultipleProtocolInterfaces (
ChildHandle,
&gEfiIp6ProtocolGuid,
&IpInstance->Ip6Proto,
NULL
);
goto ON_ERROR;
}
//
// Insert it into the service binding instance.
//
OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
InsertTailList (&IpSb->Children, &IpInstance->Link);
IpSb->NumChildren++;
gBS->RestoreTPL (OldTpl);
ON_ERROR:
if (EFI_ERROR (Status)) {
Ip6CleanProtocol (IpInstance);
FreePool (IpInstance);
}
return Status;
}
/**
Destroys a child handle with a set of I/O services.
@param[in] This Protocol instance pointer.
@param[in] ChildHandle Handle of the child to destroy.
@retval EFI_SUCCES The I/O services were removed from the child
handle.
@retval EFI_UNSUPPORTED The child handle does not support the I/O services
that are being removed.
@retval EFI_INVALID_PARAMETER Child handle is NULL.
@retval EFI_ACCESS_DENIED The child handle could not be destroyed because
its I/O services are being used.
@retval other The child handle was not destroyed.
**/
EFI_STATUS
EFIAPI
Ip6ServiceBindingDestroyChild (
IN EFI_SERVICE_BINDING_PROTOCOL *This,
IN EFI_HANDLE ChildHandle
)
{
EFI_STATUS Status;
IP6_SERVICE *IpSb;
IP6_PROTOCOL *IpInstance;
EFI_IP6_PROTOCOL *Ip6;
EFI_TPL OldTpl;
if ((This == NULL) || (ChildHandle == NULL)) {
return EFI_INVALID_PARAMETER;
}
//
// Retrieve the private context data structures
//
IpSb = IP6_SERVICE_FROM_PROTOCOL (This);
Status = gBS->OpenProtocol (
ChildHandle,
&gEfiIp6ProtocolGuid,
(VOID **) &Ip6,
gIp6DriverBinding.DriverBindingHandle,
ChildHandle,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
return EFI_UNSUPPORTED;
}
IpInstance = IP6_INSTANCE_FROM_PROTOCOL (Ip6);
if (IpInstance->Service != IpSb) {
return EFI_INVALID_PARAMETER;
}
OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
//
// A child can be destroyed more than once. For example,
// Ip6DriverBindingStop will destroy all of its children.
// when UDP driver is being stopped, it will destroy all
// the IP child it opens.
//
if (IpInstance->InDestroy) {
gBS->RestoreTPL (OldTpl);
return EFI_SUCCESS;
}
IpInstance->InDestroy = TRUE;
//
// Close the Managed Network protocol.
//
gBS->CloseProtocol (
IpSb->MnpChildHandle,
&gEfiManagedNetworkProtocolGuid,
gIp6DriverBinding.DriverBindingHandle,
ChildHandle
);
//
// Uninstall the IP6 protocol first. Many thing happens during
// this:
// 1. The consumer of the IP6 protocol will be stopped if it
// opens the protocol BY_DRIVER. For eaxmple, if MNP driver is
// stopped, IP driver's stop function will be called, and uninstall
// EFI_IP6_PROTOCOL will trigger the UDP's stop function. This
// makes it possible to create the network stack bottom up, and
// stop it top down.
// 2. the upper layer will recycle the received packet. The recycle
// event's TPL is higher than this function. The recycle events
// will be called back before preceeding. If any packets not recycled,
// that means there is a resource leak.
//
gBS->RestoreTPL (OldTpl);
Status = gBS->UninstallProtocolInterface (
ChildHandle,
&gEfiIp6ProtocolGuid,
&IpInstance->Ip6Proto
);
OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = Ip6CleanProtocol (IpInstance);
if (EFI_ERROR (Status)) {
gBS->InstallMultipleProtocolInterfaces (
&ChildHandle,
&gEfiIp6ProtocolGuid,
Ip6,
NULL
);
goto ON_ERROR;
}
RemoveEntryList (&IpInstance->Link);
ASSERT (IpSb->NumChildren > 0);
IpSb->NumChildren--;
gBS->RestoreTPL (OldTpl);
FreePool (IpInstance);
return EFI_SUCCESS;
ON_ERROR:
gBS->RestoreTPL (OldTpl);
return Status;
}
| 2.015625 | 2 |
2024-11-18T21:15:51.638651+00:00
| 2017-09-17T18:33:23 |
593e252f322156a2fd4bb721c0ca514223984e95
|
{
"blob_id": "593e252f322156a2fd4bb721c0ca514223984e95",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-17T18:33:23",
"content_id": "9a737eb745b3638044ec022fed745aca340c19f9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d90f66f09f71625d816d7e914a8be8691fe3b03e",
"extension": "c",
"filename": "saw_client.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 103852172,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3027,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/hw3/cl/saw_client.c",
"provenance": "stackv2-0112.json.gz:13621",
"repo_name": "leesk0502/network-homework",
"revision_date": "2017-09-17T18:33:23",
"revision_id": "c9d9c3d6e0579c6c64a1a9a93222f93510d96061",
"snapshot_id": "c4ad4c9ebbff4e724da4d9d1d04c62a2c7e50d2d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/leesk0502/network-homework/c9d9c3d6e0579c6c64a1a9a93222f93510d96061/hw3/cl/saw_client.c",
"visit_date": "2021-06-28T18:35:03.729990"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <resolv.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#define NAME_BUFF_SIZE 256
#define BUFF_SIZE 1024
#define TIMEOUT 400000
struct spacket
{
int seq;
size_t length;
char data[BUFF_SIZE];
};
int main(int argc, char **argv){
int sd,connfd,len;
ssize_t total_file_size, file_size;
FILE *fp;
int i=0;
struct spacket curpacket, ackpacket;
struct sockaddr_in servaddr,cliaddr;
struct timeval tv;
if(argc!=4){
printf("Usage : %s <IP> <PORT> <FILE_NAME>\n", argv[0]);
exit(1);
}
// File name must less then BUFF_SIZE / 2
if(strlen(argv[3]) > NAME_BUFF_SIZE / 2){
printf("File name Size cannot exceed %d", BUFF_SIZE / 2);
exit(1);
}
// create socket in client side
sd = socket( PF_INET, SOCK_DGRAM, 0 );
if(sd==-1){
printf(" socket not created in client\n");
exit(0);
}
else{
printf("socket created in client\n");
}
memset( &servaddr, 0, sizeof(servaddr) );
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr( argv[1] );
servaddr.sin_port = htons( atoi(argv[2]) );
// Open File
fp=fopen(argv[3],"rb");
if( fp == NULL ){
printf("File does not exist\n");
exit(1);
}
// Set timeout
tv.tv_sec = 0;
tv.tv_usec = TIMEOUT;
if (setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) {
perror("Error");
}
// Send data
while(1){
// Reset pakcet buffer
memset(&curpacket, 0, sizeof(curpacket));
// First Send file name to Server
if( i == 0 ){
curpacket.seq = htonl(0);
curpacket.length = htonl(strlen(argv[3]));
strcpy(curpacket.data, argv[3]);
} else {
memset(curpacket.data, 0, sizeof(curpacket.data));
file_size = fread(curpacket.data, sizeof(char), sizeof(curpacket.data), fp);
// Start at seq num 0
curpacket.seq = htonl(i);
curpacket.length = htonl(file_size);
}
sendto( sd, &curpacket, sizeof(curpacket), 0, (struct sockaddr *)&servaddr, sizeof(struct sockaddr) );
printf("send : seq(%d), file_size(%d)\n", i, file_size);
// Wait Ack Packet
while(1){
memset(&ackpacket, 0, sizeof(ackpacket));
if( recvfrom( sd, &ackpacket, sizeof(ackpacket), 0, (struct sockaddr*)&servaddr, &len) < 0 ){
// Timeout Retransmit data
sendto( sd, &curpacket, sizeof(curpacket), 0, (struct sockaddr *)&servaddr, sizeof(struct sockaddr) );
printf("resend : seq(%d), file_size(%d)\n", i, file_size);
continue;
}
ackpacket.seq = ntohl(ackpacket.seq);
printf("respond: ack(%d)\n", ackpacket.seq);
// If expected ack same with next seq number, break
if( (i+1) == ackpacket.seq ){
break;
}
}
// End of file
if( i != 0 && file_size <= 0 ){
break;
}
// Increase i
i++;
}
//close client side connection
fclose(fp);
close(sd);
return(0);
}
| 2.6875 | 3 |
2024-11-18T21:15:52.308493+00:00
| 2019-09-06T12:02:11 |
5207823aed0a712f1b110c6dcddb128eba214b15
|
{
"blob_id": "5207823aed0a712f1b110c6dcddb128eba214b15",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-06T12:02:11",
"content_id": "778bf01bb4ea49b277fd460dcff8ccb9fcd76408",
"detected_licenses": [
"MIT"
],
"directory_id": "6222824ceb034ab081d359bfd13f80773a3714b6",
"extension": "c",
"filename": "str_slice.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": 1311,
"license": "MIT",
"license_type": "permissive",
"path": "/boot/tests/functions/str_slice/str_slice.c",
"provenance": "stackv2-0112.json.gz:14520",
"repo_name": "kmizu/milone-lang",
"revision_date": "2019-09-06T12:02:11",
"revision_id": "48c3ae865a7ebd19836ebe34efd3db0c838be499",
"snapshot_id": "e9ad81ddd88d04744863693c003051a6e22164f2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kmizu/milone-lang/48c3ae865a7ebd19836ebe34efd3db0c838be499/boot/tests/functions/str_slice/str_slice.c",
"visit_date": "2020-07-21T08:03:10.923503"
}
|
stackv2
|
int main();
int main() {
struct String str_ = (struct String){.str = "Hello, John!", .len = 12};
int match_;
struct String slice_ = str_slice(str_, 0, 4);
if (!(((str_cmp(slice_, (struct String){.str = "Hello", .len = 5}) != 0) == 1))) goto next_2;
exit(1);
match_ = 0;
goto end_match_1;
next_2:;
if (!(((str_cmp(slice_, (struct String){.str = "Hello", .len = 5}) != 0) == 0))) goto next_3;
match_ = 0;
goto end_match_1;
next_3:;
exit(1);
end_match_1:;
int match_1;
struct String slice_1 = str_slice(str_, 7, 10);
if (!(((str_cmp(slice_1, (struct String){.str = "John", .len = 4}) != 0) == 1))) goto next_5;
exit(2);
match_1 = 0;
goto end_match_4;
next_5:;
if (!(((str_cmp(slice_1, (struct String){.str = "John", .len = 4}) != 0) == 0))) goto next_6;
match_1 = 0;
goto end_match_4;
next_6:;
exit(1);
end_match_4:;
int match_2;
struct String slice_2 = str_slice(str_, 11, 11);
if (!(((str_cmp(slice_2, (struct String){.str = "!", .len = 1}) != 0) == 1))) goto next_8;
exit(3);
match_2 = 0;
goto end_match_7;
next_8:;
if (!(((str_cmp(slice_2, (struct String){.str = "!", .len = 1}) != 0) == 0))) goto next_9;
match_2 = 0;
goto end_match_7;
next_9:;
exit(1);
end_match_7:;
return 0;
}
| 2.265625 | 2 |
2024-11-18T21:15:52.370299+00:00
| 2017-11-21T17:10:09 |
3d4d49125c071f62cc2fe7e65bb313e9458b17a5
|
{
"blob_id": "3d4d49125c071f62cc2fe7e65bb313e9458b17a5",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-21T17:10:09",
"content_id": "f3947b7971514141c001dda05f4f0b73234e77d8",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8f21752466b868d9e6e416e336c2553cb5e794de",
"extension": "h",
"filename": "threadsMylib.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": 2758,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/nmeth.3036-S2/src/nucleiChSvWshedPBC/threadsMylib.h",
"provenance": "stackv2-0112.json.gz:14651",
"repo_name": "treasureZoe/tgmm",
"revision_date": "2017-11-21T17:10:09",
"revision_id": "a7ca0950eb912af85002ddac3d14b1cbe2067638",
"snapshot_id": "985faf0bde43fd22b3670c721aab991bf3991d84",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/treasureZoe/tgmm/a7ca0950eb912af85002ddac3d14b1cbe2067638/nmeth.3036-S2/src/nucleiChSvWshedPBC/threadsMylib.h",
"visit_date": "2021-08-24T17:44:46.840106"
}
|
stackv2
|
//Copied from mylib::generator.c in order to have pthreads under windows visual studio
#ifndef __THREADS_MYLIB_H__
#define __THREADS_MYLIB_H__
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _MSC_VER
#pragma warning( disable:4996 )
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#ifndef __cplusplus
#define inline __inline
#include <pthread.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
// WINDOW pthreads "LIBRARY"
// Mutex macros
typedef SRWLOCK pthread_mutex_t;
#define PTHREAD_MUTEX_INITIALIZER RTL_SRWLOCK_INIT
#define pthread_mutex_lock(m) AcquireSRWLockExclusive(m)
#define pthread_mutex_unlock(m) ReleaseSRWLockExclusive(m)
// Condition variable macros
typedef CONDITION_VARIABLE pthread_cond_t;
#define PTHREAD_COND_INITIALIZER RTL_CONDITION_VARIABLE_INIT
#define pthread_cond_signal(c) WakeConditionVariable(c)
#define pthread_cond_broadcast(c) WakeAllConditionVariable(c)
#define pthread_cond_wait(c,m) SleepConditionVariableSRW(c,m,INFINITE,0)
// Simple thread support
typedef struct
{ HANDLE handle;
void *(*fct)(void *);
void *arg;
void *retval;
int id;
} Mythread;
typedef Mythread* pthread_t;
static DWORD WINAPI MyStart(void *arg)
{ Mythread *tv = (Mythread *) arg;
tv->retval = tv->fct(tv->arg);
return (0);
}
static int pthread_create(pthread_t *thread, void *attr, void *(*fct)(void *), void *arg)
{ Mythread *tv;
if (attr != NULL)
{ fprintf(stderr,"Do not support thread attributes\n");
exit (1);
}
tv = (Mythread *) malloc(sizeof(Mythread));
if (tv == NULL)
{ fprintf(stderr,"pthread_create: Out of memory.\n");
exit (1);
};
tv->fct = fct;
tv->arg = arg;
tv->handle = CreateThread(NULL,0,MyStart,tv,0,(LPDWORD) (&tv->id) );
if (tv->handle == NULL)
{
*thread = NULL;
return (EAGAIN);
}
else
{
*thread = tv;
return (0);
}
}
static int pthread_join(pthread_t t, void **ret)
{ Mythread *tv = (Mythread *) t;
WaitForSingleObject(tv->handle,INFINITE);
if (ret != NULL)
*ret = tv->retval;
CloseHandle(tv->handle);
free(tv);
return (0);
}
typedef int pthread_id;
static pthread_id pthread_tag()
{ return (GetCurrentThreadId()); }
static int pthread_is_this(pthread_id id)
{ return (GetCurrentThreadId() == id); }
#else // Small extension to pthreads!
#include <pthread.h>
typedef pthread_t pthread_id;
#define pthread_tag() pthread_self()
static inline int pthread_is_this(pthread_id id)
{ return (pthread_equal(pthread_self(),id)); }
#endif
#ifdef __cplusplus
}
#endif
#endif//__THREADS_MYLIB_H__
| 2.3125 | 2 |
2024-11-18T21:15:53.166177+00:00
| 2017-10-05T03:16:36 |
2a1a17be7020ecbc980b16027f0f7ee29fdda04b
|
{
"blob_id": "2a1a17be7020ecbc980b16027f0f7ee29fdda04b",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-05T03:16:36",
"content_id": "f0392f2dff435acec2b698f8a8320e6ae9a10000",
"detected_licenses": [
"MIT"
],
"directory_id": "1e85e53eed7f41c8af7cabf2e5b12a95eb81e4ba",
"extension": "h",
"filename": "linked-list.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 105844441,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 628,
"license": "MIT",
"license_type": "permissive",
"path": "/linked-list.h",
"provenance": "stackv2-0112.json.gz:15298",
"repo_name": "gugamm/dynamic-string",
"revision_date": "2017-10-05T03:16:36",
"revision_id": "e851607fd75829af896004efb545ebb0cb53aa43",
"snapshot_id": "673f7c872b15d10e4e30ae492d170bcacdfa81a4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gugamm/dynamic-string/e851607fd75829af896004efb545ebb0cb53aa43/linked-list.h",
"visit_date": "2021-07-07T07:11:54.492181"
}
|
stackv2
|
#ifndef _LINKED_LIST
#define _LINKED_LIST
typedef struct List List;
typedef struct Node Node;
struct Node {
Node *prev;
Node *next;
void *data;
};
struct List {
Node *head;
Node *tail;
unsigned int length;
};
List *LL_create();
void LL_destroy(List *list, void (*cb)(void *nodeData));
Node *LL_findNode(List *list, void *searchData, int (*cmp)(void *searchData, void *nodeData));
Node *LL_insertNode(List *list, void *data);
void LL_deleteNode(List *list, Node *node);
Node *LL_firstNode(List *list);
Node *LL_lastNode(List *list);
void LL_forEachNode(List *list, void (*cb)(void *nodeData));
#endif
| 2.171875 | 2 |
2024-11-18T21:15:53.861275+00:00
| 2019-10-26T13:31:08 |
e01a665cb7f4e8a10274695482c3e6c5ffa88eed
|
{
"blob_id": "e01a665cb7f4e8a10274695482c3e6c5ffa88eed",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-26T13:31:08",
"content_id": "deac0e475542691b8cdab8b9aafdb5e5043807e6",
"detected_licenses": [
"MIT"
],
"directory_id": "8c267441a659900cdc52b0aecfbc902bd36b76cd",
"extension": "c",
"filename": "C_11.c",
"fork_events_count": 0,
"gha_created_at": "2019-10-26T13:18:34",
"gha_event_created_at": "2019-10-26T13:31:09",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 217711458,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 562,
"license": "MIT",
"license_type": "permissive",
"path": "/C_11.c",
"provenance": "stackv2-0112.json.gz:15944",
"repo_name": "Yash1256/C_Programms",
"revision_date": "2019-10-26T13:31:08",
"revision_id": "f1b6d04bfe0c1a6545d63fdad2d57e7979bbfcac",
"snapshot_id": "eed65f780e203febc83a6877f21f2e95290bacf9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Yash1256/C_Programms/f1b6d04bfe0c1a6545d63fdad2d57e7979bbfcac/C_11.c",
"visit_date": "2020-08-28T13:20:09.861288"
}
|
stackv2
|
#include<stdio.h>
int main()
{
printf("The size of 978 is :: %d",sizeof(978));
printf("\nThe size of 3.142 is :: %d",sizeof(3.142));
float a=2.3543;
printf("\nThe decimal part of number is :: %f",a-(int)a);
char ch[15];
int j=0;
printf("\nInput the string :: ");
scanf("%s",ch);
for(;ch[j]!='\0';)
j++;
if(j<8)
printf("Input condition dosen't satisfied String must be minimum of 7 character's ");
else
{
printf("The first 4 Character of string :: ");
for(int i=0;i<4;i++)
printf("%c ",ch[i]);
}
return 0;
}
| 3.640625 | 4 |
2024-11-18T21:15:54.018548+00:00
| 2022-07-25T11:48:01 |
51eb3583230f2835345ada10f5813cd2159622cb
|
{
"blob_id": "51eb3583230f2835345ada10f5813cd2159622cb",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-25T11:48:01",
"content_id": "bb90f0e6d6b5ae89bfdc41ef8578eaf42a59ca46",
"detected_licenses": [
"MIT"
],
"directory_id": "76a81265e2d29de91fb65b03ce7dff00894802a0",
"extension": "c",
"filename": "checkhfe.c",
"fork_events_count": 23,
"gha_created_at": "2017-03-02T11:29:05",
"gha_event_created_at": "2021-03-03T11:10:03",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 83670462,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3487,
"license": "MIT",
"license_type": "permissive",
"path": "/tools/checkhfe.c",
"provenance": "stackv2-0112.json.gz:16074",
"repo_name": "picosonic/bbc-fdc",
"revision_date": "2022-07-25T11:48:01",
"revision_id": "b3d0b82ec4dac05753d47955da3bf300382ac51b",
"snapshot_id": "6c4f8d3fb33842d34f4aab29fff607afb82264c5",
"src_encoding": "UTF-8",
"star_events_count": 240,
"url": "https://raw.githubusercontent.com/picosonic/bbc-fdc/b3d0b82ec4dac05753d47955da3bf300382ac51b/tools/checkhfe.c",
"visit_date": "2022-08-09T18:19:03.668696"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "hfe.h"
struct hfe_header hfeheader;
struct hfe_track curtrack;
int isv3=0;
int hfe_processheader(FILE *hfefile)
{
bzero(&hfeheader, sizeof(hfeheader));
if (fread(&hfeheader, sizeof(hfeheader), 1, hfefile)==0)
return 1;
if (strncmp((char *)&hfeheader.HEADERSIGNATURE, HFE_MAGIC1, strlen(HFE_MAGIC1))!=0)
{
if (strncmp((char *)&hfeheader.HEADERSIGNATURE, HFE_MAGIC3, strlen(HFE_MAGIC3))!=0)
{
printf("Not an HFE file\n");
return 1;
}
else
{
isv3=1;
printf("HFE v3 file\n");
}
}
else
printf("HFE v1 file\n");
printf("Format revision : %d \n", hfeheader.formatrevision);
printf("Tracks : %d \n", hfeheader.number_of_track);
printf("Sides : %d \n", hfeheader.number_of_side);
printf("Track encoding : %d ", hfeheader.track_encoding);
switch (hfeheader.track_encoding)
{
case 0: printf("ISO IBM MFM"); break;
case 1: printf("AMIGA MFM"); break;
case 2: printf("ISO IBM FM"); break;
case 3: printf("EMU FM"); break;
default: printf("UNKNOWN"); break;
}
printf("\n");
printf("Bit rate : %d k bit/s \n", hfeheader.bitRate);
printf("RPM : %d \n", hfeheader.floppyRPM);
printf("Interface mode : %d ", hfeheader.floppyinterfacemode);
switch (hfeheader.floppyinterfacemode)
{
case 0: printf("IBM PC DD"); break;
case 1: printf("IBM PC HD"); break;
case 2: printf("ATARI ST DD"); break;
case 3: printf("ATARI ST HD"); break;
case 4: printf("AMIGA DD"); break;
case 5: printf("AMIGA HD"); break;
case 6: printf("CPC DD"); break;
case 7: printf("GENERIC SHUGART DD"); break;
case 8: printf("IBM PC ED"); break;
case 9: printf("MSX2 DD"); break;
case 10: printf("C64 DD"); break;
case 11: printf("EMU SHUGART"); break;
case 12: printf("S950 DD"); break;
case 13: printf("S950 HD"); break;
case 0xfe: printf("DISABLE"); break;
default: printf("UNKNOWN"); break;
}
printf("\n");
if (isv3)
printf("Write protected : %d \n", hfeheader.write_protected);
printf("Track list offset : %d \n", hfeheader.track_list_offset);
printf("Write allowed : %s \n", (hfeheader.write_allowed==HFE_TRUE)?"Yes":"No");
printf("Stepping : %s \n", (hfeheader.single_step==HFE_TRUE)?"Single":"Double");
if (hfeheader.track0s0_altencoding!=HFE_TRUE)
{
printf("Track 0 S 0 alt encoding : %d \n", hfeheader.track0s0_altencoding);
printf("Track 0 S 0 encoding : %d \n", hfeheader.track0s0_encoding);
}
if (hfeheader.track0s1_altencoding!=HFE_TRUE)
{
printf("Track 0 S 1 alt encoding : %d \n", hfeheader.track0s1_altencoding);
printf("Track 0 S 1 encoding : %d \n", hfeheader.track0s1_encoding);
}
return 0;
}
int main(int argc, char **argv)
{
FILE *fp;
uint8_t track;
if (argc!=2)
{
printf("Specify .hfe on command line\n");
return 1;
}
fp=fopen(argv[1], "rb");
if (fp==NULL)
{
printf("Unable to open file\n");
return 2;
}
if (hfe_processheader(fp)!=0)
{
fclose(fp);
return 1;
}
// Process tracks
for (track=0; track<hfeheader.number_of_track; track++)
{
fseek(fp, (hfeheader.track_list_offset*HFE_BLOCKSIZE)+(track*(sizeof(curtrack))), SEEK_SET);
if (fread(&curtrack, sizeof(curtrack), 1, fp)==0)
return 1;
printf(" Track %.2d @ block %d, %d bytes\n", track, curtrack.offset, curtrack.track_len);
}
fclose(fp);
return 0;
}
| 2.28125 | 2 |
2024-11-18T21:15:54.072520+00:00
| 2018-04-25T15:00:10 |
abfafc6967947cfeb12e14121f78bae29788288c
|
{
"blob_id": "abfafc6967947cfeb12e14121f78bae29788288c",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-25T15:00:10",
"content_id": "73172d4e0797c8b78a68731459573fc850f8cd30",
"detected_licenses": [
"MIT"
],
"directory_id": "2e89e01518ac93b453146639082026e3cbc6b1e1",
"extension": "c",
"filename": "Bcast.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 119591716,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 423,
"license": "MIT",
"license_type": "permissive",
"path": "/L09/Bcast.c",
"provenance": "stackv2-0112.json.gz:16204",
"repo_name": "dwang619/CMDA3634SP18",
"revision_date": "2018-04-25T15:00:10",
"revision_id": "61bc985a4af5f65f589eac8e7c9476977c237f6a",
"snapshot_id": "8d5e88acc59df175457f381673a41752adc1c988",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dwang619/CMDA3634SP18/61bc985a4af5f65f589eac8e7c9476977c237f6a/L09/Bcast.c",
"visit_date": "2021-05-08T19:59:14.788189"
}
|
stackv2
|
#include "mympi.h"
float main () {
float sum = val;
float recvBuffer; //space for incoming values
//start with all ranks active
int Narice = size;
while (Nactive > 1) {
if (rank >= Nactive / 2) {
//MPI_send to rank - Nactive / 2
int destRank = rank - Nactive / 2;
int tag = Nactive;
MPI_Send(&val,
1,
MPI_FLOAT,
destRank,
tag,
MPI_COMM_WORLD);
}
| 2.1875 | 2 |
2024-11-18T21:15:54.390797+00:00
| 2018-03-03T21:40:43 |
a9d11a42c632ef5c8f301601b423516a01c7bb22
|
{
"blob_id": "a9d11a42c632ef5c8f301601b423516a01c7bb22",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-03T21:40:43",
"content_id": "15463dd01a0fd7fb39fc51204ca21bdfbf44919f",
"detected_licenses": [
"Unlicense"
],
"directory_id": "31604f1719da7706aedc71b40cfae1aa207afe9f",
"extension": "c",
"filename": "boot.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44338886,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13178,
"license": "Unlicense",
"license_type": "permissive",
"path": "/boot2/boot.c",
"provenance": "stackv2-0112.json.gz:16589",
"repo_name": "jafager/beaglebone",
"revision_date": "2018-03-03T21:40:43",
"revision_id": "d204060aad311234f5a2dccaee145217d84e532a",
"snapshot_id": "119de08455e8b86638e87e7c26614c957f20dd4d",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/jafager/beaglebone/d204060aad311234f5a2dccaee145217d84e532a/boot2/boot.c",
"visit_date": "2021-01-10T10:26:55.159207"
}
|
stackv2
|
#include "stdint.h"
#include "reg.h"
#include "led.h"
#include "console.h"
#include "mmc.h"
void boot(void)
{
/* Enable clocks for the MMC0 module */
regmask32(CM_PER + CM_PER_MMC0_CLKCTRL, CM_PER_MMC0_CLKCTRL_MODULEMODE, CM_PER_MMC0_CLKCTRL_MODULEMODE_ENABLE);
console_puts("MMC0 clocks enabled.\r\n");
/* Initiate soft reset */
regwrite32(MMC0 + SD_SYSCONFIG, SD_SYSCONFIG_SOFTRESET);
console_puts("Initiating soft reset.\r\n");
/* Wait for soft reset to complete */
while (!(regread32(MMC0 + SD_SYSSTATUS) & SD_SYSSTATUS_RESETDONE));
console_puts("Soft reset complete.\r\n");
/* Set controller capabilities (1.8V and 3.0V voltage support) */
regmask32(MMC0 + SD_CAPA, SD_CAPA_VS, SD_CAPA_VS_18 | SD_CAPA_VS_30);
console_puts("Controller capabilities set.\r\n");
/* Disable idle and wakeup behavior */
regmask32(MMC0 + SD_SYSCONFIG, SD_SYSCONFIG_CLOCKACTIVITY, SD_SYSCONFIG_CLOCKACTIVITY_BOTH);
regmask32(MMC0 + SD_SYSCONFIG, SD_SYSCONFIG_SIDLEMODE, SD_SYSCONFIG_SIDLEMODE_NO_IDLE);
regmask32(MMC0 + SD_SYSCONFIG, SD_SYSCONFIG_ENAWAKEUP, SD_SYSCONFIG_ENAWAKEUP_DISABLE);
regmask32(MMC0 + SD_SYSCONFIG, SD_SYSCONFIG_AUTOIDLE, SD_SYSCONFIG_AUTOIDLE_DISABLE);
console_puts("Idle and wakeup behavior disabled.\r\n");
/* Configure bus transfer modes and bus power */
regmask32(MMC0 + SD_CON, SD_CON_DW8, SD_CON_DW8_1OR4BIT);
regmask32(MMC0 + SD_HCTL, SD_HCTL_DTW, SD_HCTL_DTW_1BIT);
regmask32(MMC0 + SD_HCTL, SD_HCTL_SDVS, SD_HCTL_SDVS_30);
regmask32(MMC0 + SD_HCTL, SD_HCTL_SDBP, SD_HCTL_SDBP);
console_puts("Bus transfer modes and bus power configured.\r\n");
/* Wait for bus power */
while (!(regread32(MMC0 + SD_HCTL) & SD_HCTL_SDBP));
console_puts("Bus power online.\r\n");
/* Enable internal clock */
regmask32(MMC0 + SD_SYSCTL, SD_SYSCTL_ICE, SD_SYSCTL_ICE);
regmask32(MMC0 + SD_SYSCTL, SD_SYSCTL_CEN, SD_SYSCTL_CEN);
regmask32(MMC0 + SD_SYSCTL, SD_SYSCTL_CLKD, SD_SYSCTL_CLKD_1023);
console_puts("Internal clock enabled.\r\n");
/* Wait for clock to stabilize */
while (!(regread32(MMC0 + SD_SYSCTL) & SD_SYSCTL_ICS));
console_puts("Internal clock stabilized.\r\n");
/* Enable internal interrupts */
regmask32(MMC0 + SD_IE, SD_IE_ENABLE_ALL, SD_IE_ENABLE_ALL);
console_puts("Internal interrupts enabled.\r\n");
/* This seems like the place where host controller */
/* configuration ends and card configuration begins */
console_puts("Press a key to continue...\r\n");
console_getc();
/* Send initialization stream */
regmask32(MMC0 + SD_CON, SD_CON_INIT, SD_CON_INIT_ENABLE);
console_puts("Sending initialization stream.\r\n");
/* Send CMD0 (I don't think this one goes to the card) */
console_puts("Sending CMD0...\r\n");
if (!mmc_send_command(0 << SD_CMD_INDX, 0))
{
mmc_dump_status();
while (1);
}
console_puts("CMD0 complete.\r\n");
/* Clear CC internal interrupt */
regmask32(MMC0 + SD_STAT, SD_STAT_CC, SD_STAT_CC);
console_puts("CC interrupt cleared.\r\n");
/* Stop sending initialization stream */
regmask32(MMC0 + SD_CON, SD_CON_INIT, SD_CON_INIT_DISABLE);
console_puts("Stopped sending initialization stream.\r\n");
/* Clear all internal interrupts */
regmask32(MMC0 + SD_STAT, SD_STAT_CLEAR_ALL, SD_STAT_CLEAR_ALL);
console_puts("Internal interrupts cleared.\r\n");
/* TODO: Change clock frequency to fit protocol */
/* Send CMD0 (this one goes to the card) */
regwrite32(MMC0 + SD_CMD, 0);
console_puts("CMD0 sent.\r\n");
/* Wait for CMD0 to complete */
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if (status & SD_STAT_ERRI)
{
console_puts("Error in CMD0: 0x");
console_hexprint(status);
console_puts("\r\n");
while (1);
}
console_puts("CMD0 complete.\r\n");
/* Clear CC internal interrupt */
regmask32(MMC0 + SD_STAT, SD_STAT_CC, SD_STAT_CC);
console_puts("CC interrupt cleared.\r\n");
/* Send CMD5 */
regwrite32(MMC0 + SD_ARG, SD_CMD5_VDD_2930 | SD_CMD5_VDD_3031);
regmask32(MMC0 + SD_CMD, SD_CMD_MASK, (5 << SD_CMD_INDX) | SD_CMD_CICE | SD_CMD_CCCE | SD_CMD_RSP_TYPE_48);
console_puts("CMD5 sent.\r\n");
/* Wait for CMD5 to complete */
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if (status & SD_STAT_CC)
{
console_puts("Card is SDIO.\r\n");
console_puts("SDIO cards are not supported.\r\n");
while (1);
}
if (!(status & SD_STAT_CTO))
{
console_puts("Error in CMD5: 0x");
console_hexprint(status);
console_puts("\r\n");
while (1);
}
console_puts("CMD5 timed out.\r\n");
console_puts("Card is not SDIO.\r\n");
/* Clear CTO internal interrupt */
regmask32(MMC0 + SD_STAT, SD_STAT_CTO, SD_STAT_CTO);
console_puts("CTO interrupt cleared.\r\n");
/* Software reset for mmc_cmd line (yes this is weird but it follows the TRM) */
regmask32(MMC0 + SD_SYSCTL, SD_SYSCTL_SRC, SD_SYSCTL_SRC);
while (!(regread32(MMC0 + SD_SYSCTL) & SD_SYSCTL_SRC));
while (regread32(MMC0 + SD_SYSCTL) & SD_SYSCTL_SRC);
console_puts("Completed software reset of mmc_cmd line.\r\n");
/* Send CMD8 */
regwrite32(MMC0 + SD_ARG, SD_CMD8_VHS_2736 | SD_CMD8_CHECK_PATTERN);
regmask32(MMC0 + SD_CMD, SD_CMD_MASK, (8 << SD_CMD_INDX) | SD_CMD_CICE | SD_CMD_CCCE | SD_CMD_RSP_TYPE_48);
console_puts("CMD8 sent.\r\n");
/* Wait for CMD8 to complete */
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if ((status & SD_STAT_ERRI) && !(status & SD_STAT_CTO))
{
console_puts("Error in CMD8: 0x");
console_hexprint(status);
console_puts("\r\n");
while (1);
}
if (status & SD_STAT_CTO)
{
console_puts("Card does not support 2.0 specification.\r\n");
console_puts("Non-2.0 cards are not supported.\r\n");
while (1);
}
if (status & SD_STAT_CC)
{
console_puts("Card supports 2.0 specification.\r\n");
uint32_t response = regread32(MMC0 + SD_RSP10);
if ((response & 0xff) != SD_CMD8_CHECK_PATTERN)
{
console_puts("CMD8 response 0x");
console_hexprint(response);
console_puts(" does not match check pattern.\r\n");
while (1);
}
console_puts("CMD8 response matches check pattern.\r\n");
}
/* Software reset for mmc_cmd line (yes this is weird but it follows the TRM) */
regmask32(MMC0 + SD_SYSCTL, SD_SYSCTL_SRC, SD_SYSCTL_SRC);
while (!(regread32(MMC0 + SD_SYSCTL) & SD_SYSCTL_SRC));
while (regread32(MMC0 + SD_SYSCTL) & SD_SYSCTL_SRC);
console_puts("Completed software reset of mmc_cmd line.\r\n");
/* NOTE: Per the TRM this resets the CC interrupt */
/* Send CMD55/ACMD41 */
uint32_t response;
do
{
/* Send CMD55 */
regwrite32(MMC0 + SD_ARG, 0);
regmask32(MMC0 + SD_CMD, SD_CMD_MASK, (55 << SD_CMD_INDX) | SD_CMD_CICE | SD_CMD_CCCE | SD_CMD_RSP_TYPE_48);
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if (status & SD_STAT_ERRI)
{
console_puts("Error in CMD55: 0x");
console_hexprint(status);
console_puts("\r\n");
while (1);
}
console_puts("CMD55 complete.\r\n");
/* Clear CC internal interrupt */
regmask32(MMC0 + SD_STAT, SD_STAT_CC, SD_STAT_CC);
console_puts("CC interrupt cleared.\r\n");
/* Send ACMD41 */
regwrite32(MMC0 + SD_ARG, SD_ACMD41_HCS | SD_ACMD41_VDD_2930 | SD_ACMD41_VDD_3031);
regmask32(MMC0 + SD_CMD, SD_CMD_MASK, (41 << SD_CMD_INDX) | SD_CMD_RSP_TYPE_48);
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if (status & SD_STAT_ERRI)
{
console_puts("Error in ACMD41: 0x");
console_hexprint(status);
console_puts("\r\n");
console_puts("ACMD41 response: 0x");
console_hexprint(regread32(MMC0 + SD_RSP10));
console_puts("\r\n");
while (1);
}
console_puts("ACMD41 complete.\r\n");
/* Clear CC internal interrupt */
regmask32(MMC0 + SD_STAT, SD_STAT_CC, SD_STAT_CC);
console_puts("CC interrupt cleared.\r\n");
/* Get response */
response = regread32(MMC0 + SD_RSP10);
}
while (!(response & SD_OCR_BUSY));
console_puts("Card powered up.\r\n");
/* Determine card capacity type */
if (response & SD_OCR_CCS)
console_puts("Card is high capacity.\r\n");
else
console_puts("Card is standard capacity.\r\n");
/* Software reset for mmc_cmd line (yes this is weird but it follows the TRM) */
regmask32(MMC0 + SD_SYSCTL, SD_SYSCTL_SRC, SD_SYSCTL_SRC);
while (!(regread32(MMC0 + SD_SYSCTL) & SD_SYSCTL_SRC));
while (regread32(MMC0 + SD_SYSCTL) & SD_SYSCTL_SRC);
console_puts("Completed software reset of mmc_cmd line.\r\n");
/* NOTE: Per the TRM this resets the CC interrupt */
/* Send CMD2 */
regwrite32(MMC0 + SD_ARG, 0);
regmask32(MMC0 + SD_CMD, SD_CMD_MASK, (2 << SD_CMD_INDX) | SD_CMD_RSP_TYPE_48);
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if (status & SD_STAT_ERRI)
{
console_puts("Error in CMD2: 0x");
console_hexprint(status);
console_puts("\r\n");
console_puts("CMD2 response: 0x");
console_hexprint(regread32(MMC0 + SD_RSP10));
console_puts("\r\n");
while (1);
}
console_puts("CMD2 complete.\r\n");
/* Clear CC internal interrupt */
regwrite32(MMC0 + SD_STAT, 0);
//regmask32(MMC0 + SD_STAT, SD_STAT_CC, SD_STAT_CC);
console_puts("CC interrupt cleared.\r\n");
/* Send CMD3 */
regwrite32(MMC0 + SD_ARG, 0);
regmask32(MMC0 + SD_CMD, SD_CMD_MASK, (3 << SD_CMD_INDX) | SD_CMD_CICE | SD_CMD_CCCE | SD_CMD_RSP_TYPE_48);
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if (status & SD_STAT_ERRI)
{
console_puts("Error in CMD3: 0x");
console_hexprint(status);
console_puts("\r\n");
console_puts("CMD3 response: 0x");
console_hexprint(regread32(MMC0 + SD_RSP10));
console_puts("\r\n");
while (1);
}
console_puts("CMD3 complete.\r\n");
/* Get relative card address from CMD3 response */
uint32_t relative_card_address = regread32(MMC0 + SD_RSP10) & 0xffff0000;
console_puts("RCA from CMD3 is ");
console_hexprint(relative_card_address);
console_puts("\r\n");
/* Clear CC internal interrupt */
regmask32(MMC0 + SD_STAT, SD_STAT_CC, SD_STAT_CC);
console_puts("CC interrupt cleared.\r\n");
/* Send CMD9 */
regwrite32(MMC0 + SD_ARG, relative_card_address);
regmask32(MMC0 + SD_CMD, SD_CMD_MASK, (9 << SD_CMD_INDX) | SD_CMD_CICE | SD_CMD_CCCE | SD_CMD_RSP_TYPE_136);
do
{
status = regread32(MMC0 + SD_STAT);
}
while (!((status & SD_STAT_CC) || (status & SD_STAT_ERRI)));
if (status & SD_STAT_ERRI)
{
console_puts("Error in CMD9: 0x");
console_hexprint(status);
console_puts("\r\n");
while (1);
}
console_puts("CMD9 complete.\r\n");
/* Get long response */
uint32_t long_response[4];
long_response[0] = regread32(MMC0 + SD_RSP10);
long_response[1] = regread32(MMC0 + SD_RSP32);
long_response[2] = regread32(MMC0 + SD_RSP54);
long_response[3] = regread32(MMC0 + SD_RSP76);
/* Calculate card capacity */
uint32_t c_size = ((long_response[1] >> 30) & 0b11) | ((long_response[2] & 0x3ff) << 2);
uint32_t c_size_mult = (long_response[1] >> 15) & 0b111;
uint32_t read_bl_len = (long_response[2] >> 16) & 0b1111;
uint32_t mult = 1 << (c_size_mult + 2);
uint32_t blocknr = (c_size + 1) * mult;
uint32_t block_len = 1 << read_bl_len;
uint32_t capacity = blocknr * block_len;
console_puts("c_size: ");
console_hexprint(c_size);
console_puts("\r\n");
console_puts("c_size_mult: ");
console_hexprint(c_size_mult);
console_puts("\r\n");
console_puts("read_bl_len: ");
console_hexprint(read_bl_len);
console_puts("\r\n");
console_puts("mult: ");
console_hexprint(mult);
console_puts("\r\n");
console_puts("blocknr: ");
console_hexprint(blocknr);
console_puts("\r\n");
console_puts("block_len: ");
console_hexprint(block_len);
console_puts("\r\n");
console_puts("capacity: ");
console_hexprint(capacity);
console_puts("\r\n");
}
| 2.1875 | 2 |
2024-11-18T21:15:54.647904+00:00
| 2017-10-25T01:47:57 |
5d595743d4410b329d2be8dda4cb6e0be67024ce
|
{
"blob_id": "5d595743d4410b329d2be8dda4cb6e0be67024ce",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-25T01:47:57",
"content_id": "0a9903153b2d4d5fd5938e1aa49770fc86529d0b",
"detected_licenses": [
"MIT"
],
"directory_id": "6dee7027bf6361194d5d2230c555121c9ed7209a",
"extension": "c",
"filename": "nthu7518.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 40413417,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1029,
"license": "MIT",
"license_type": "permissive",
"path": "/nthu/nthu7518/nthu7518.c",
"provenance": "stackv2-0112.json.gz:16979",
"repo_name": "mythnc/online-judge-solved-lists",
"revision_date": "2017-10-25T01:47:57",
"revision_id": "c8db91674298f74539312a763ff52c2ba0d9794d",
"snapshot_id": "e1838583e95a16f68387977564df01900b4d7ae0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mythnc/online-judge-solved-lists/c8db91674298f74539312a763ff52c2ba0d9794d/nthu/nthu7518/nthu7518.c",
"visit_date": "2021-01-18T15:16:36.478995"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
#define MAXC 21
#define MAXW 5000
int is_palindrome(char (*stack)[MAXC], int top);
int main(void)
{
int c, i, top;
char word[MAXC];
char stack[MAXW][MAXC];
i = top = 0;
while ((c = getchar()) != EOF) {
switch (c) {
case '\n':
word[i] = '\0';
i = 0;
strcpy(stack[top++], word);
if (is_palindrome(stack, top))
printf("YES\n");
else
printf("NO\n");
top = 0;
break;
case ' ':
word[i] = '\0';
i = 0;
strcpy(stack[top++], word);
break;
default:
word[i++] = c;
}
}
return 0;
}
int is_palindrome(char (*stack)[MAXC], int top)
{
int i, j;
for (i = 0, j = top - 1; i < j; i++, j--) {
if (strcmp(stack[i], stack[j]) != 0)
return 0;
}
return 1;
}
| 3.140625 | 3 |
2024-11-18T21:15:56.107370+00:00
| 2018-08-02T03:17:56 |
dbf0484efc205be867bb4da101eaf88e3b40fc14
|
{
"blob_id": "dbf0484efc205be867bb4da101eaf88e3b40fc14",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-02T03:17:56",
"content_id": "30044dcef5a492e97f16f5ef3193c82729f321dd",
"detected_licenses": [
"MIT"
],
"directory_id": "2bb6d7b6d5e0d29d5b725a084d35cafb0da95f9c",
"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": 111357465,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1598,
"license": "MIT",
"license_type": "permissive",
"path": "/Stack&Queue/4-CommonSuffix/4-CommonSuffix/main.c",
"provenance": "stackv2-0112.json.gz:17107",
"repo_name": "SmallElephant/C-DataStructure",
"revision_date": "2018-08-02T03:17:56",
"revision_id": "b5274de4ed23a20a4f87f1e99a565c0d76354853",
"snapshot_id": "2f4c2c20e4a325dd6e6fa970f95915be1468e3fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SmallElephant/C-DataStructure/b5274de4ed23a20a4f87f1e99a565c0d76354853/Stack&Queue/4-CommonSuffix/4-CommonSuffix/main.c",
"visit_date": "2021-09-20T01:10:43.083089"
}
|
stackv2
|
//
// main.c
// 4-CommonSuffix
//
// Created by FlyElephant on 2017/11/24.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
#include <stdio.h>
typedef struct DataNode {
struct DataNode *next;
char data;
} ListNode;
int listlen(ListNode *list) {
int len = 1;
while (list->next != NULL) {
len++;
list = list->next;
}
return len;
}
ListNode *find_listNode(ListNode *list1,ListNode *list2) {
int len1 = listlen(list1);
int len2 = listlen(list2);
if (len1 > len2) {
for (int i = 0; i < len1 - len2; i++) {
list1 = list1->next;
}
} else {
for (int i = 0; i < len2 - len1; i++) {
list2 = list2->next;
}
}
if (list1->data == list2->data) {
return list1;
} else {
while (list1->next != NULL && list1->data != list2->data) {
list1 = list1->next;
list2 = list2->next;
}
return list1->next;
}
}
int main(int argc, const char * argv[]) {
// insert code here...
ListNode node3 = { NULL, 'd'};
ListNode node2 = { &node3, 'd'};
ListNode node1 = { &node2, 'm'};
ListNode list6 = { NULL, 't'};
ListNode list5 = { &list6, 'n'};
ListNode list4 = { &list5, 'h'};
ListNode list3 = { &list4, '_'};
ListNode list2 = { &list3, 'y'};
ListNode list1 = { &list2, 'm'};
ListNode *result = find_listNode(&node1, &list1);
if (result != NULL) {
printf("起点的值:%c\n",result->data);
} else {
printf("无共同起点\n");
}
return 0;
}
| 3.109375 | 3 |
2024-11-18T21:15:56.539184+00:00
| 2021-07-29T15:01:27 |
935ab6b2e04477acb3df0be862558151c1a0f13e
|
{
"blob_id": "935ab6b2e04477acb3df0be862558151c1a0f13e",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-29T15:01:27",
"content_id": "228dd2766d886179cc8531e3a211357530858075",
"detected_licenses": [
"MIT"
],
"directory_id": "679d18988b2313e8b93db20b406a9af6d273e9a9",
"extension": "h",
"filename": "discover.h",
"fork_events_count": 15,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 256491247,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2556,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mpool/discover.h",
"provenance": "stackv2-0112.json.gz:17497",
"repo_name": "hse-project/mpool",
"revision_date": "2021-07-29T15:01:27",
"revision_id": "2942cf4cf1c6a05caa4be7337a808e23a9a8fd2a",
"snapshot_id": "91bf8f3c1d1ef32fff541ebeb50363cce35eeffb",
"src_encoding": "UTF-8",
"star_events_count": 35,
"url": "https://raw.githubusercontent.com/hse-project/mpool/2942cf4cf1c6a05caa4be7337a808e23a9a8fd2a/src/mpool/discover.h",
"visit_date": "2023-07-12T10:42:37.908256"
}
|
stackv2
|
/* SPDX-License-Identifier: MIT */
/*
* Copyright (C) 2015-2020 Micron Technology, Inc. All rights reserved.
*/
#ifndef MPOOL_DISCOVER_H
#define MPOOL_DISCOVER_H
#include <util/platform.h>
#include "mpctl.h"
struct imp_media_struct {
enum mp_media_classp mpd_classp;
char mpd_path[NAME_MAX + 1];
};
struct imp_pool {
char mp_name[MPOOL_NAMESZ_MAX];
struct mpool_uuid mp_uuid;
bool mp_activated;
int mp_media_cnt;
struct imp_media_struct *mp_media;
};
struct imp_entry {
char mp_name[MPOOL_NAMESZ_MAX];
struct mpool_uuid mp_uuid;
struct pd_prop mp_pd_prop;
char mp_path[NAME_MAX + 1];
};
/**
* imp_mpool_exists() - check if specified mpool exists
* @name: char *, name of mpool
* @flags: u32, flags
* @entry:
*
* Returns: true if mpool is named in any block device, otherwise false
*/
bool imp_mpool_exists(const char *name, u32 flags, struct imp_entry **entry);
/**
* imp_mpool_activated() - check if specified mpool is activated
* @name: char *, name of mpool
*
* imp_mpool_activated will check if the device special file for
* the named mpool exists, and return true if it does.
*
* Returns: true if mpool's special file exists
*/
bool imp_mpool_activated(const char *name);
/**
* imp_device_allocated() - Determine if a given media device is in use
* @dpath: char *, name of media device
* @flags: u32, flags
*
* imp_device_allocated() will use libblkid to see if there is a reference
* to the specified device.
*
* Returns: true if the named device is allocated to an mpool
*/
bool imp_device_allocated(const char *dpath, u32 flags);
/**
* imp_entries_get() - given a pool UUID, get data from libblkid
* @name: target mpool name
* @uuid: uuid of target mpool
* @dpath: target device name
* @flags: u32 *, flags
* @entry: pointer to array of struct imp_entry
* @entry_cnt: the count of member drives
*
* The array and its member strings will be allocated and must later be freed.
*/
merr_t
imp_entries_get(
const char *name,
struct mpool_uuid *uuid,
const char *dpath,
u32 *flags,
struct imp_entry **entry,
int *entry_cnt);
/**
* imp_entries2pd_prop() - Allocate a table of pd properties and copies
* the properties from the imp entries into that table.
*
* @entry_cnt:
* @entries:
*/
struct pd_prop *imp_entries2pd_prop(int entry_cnt, struct imp_entry *entries);
#endif
| 2.21875 | 2 |
2024-11-18T21:15:56.770809+00:00
| 2020-12-26T22:16:34 |
2fd85eab1ec4b21cb435d375dc6bf83226e1aa5c
|
{
"blob_id": "2fd85eab1ec4b21cb435d375dc6bf83226e1aa5c",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-26T22:16:34",
"content_id": "dd0e097197f75f2ada8757b339e49e16541af721",
"detected_licenses": [
"MIT"
],
"directory_id": "830e1aa8d3af295804cc84a4ae5be921d91b19a4",
"extension": "h",
"filename": "pcb.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 224050503,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1483,
"license": "MIT",
"license_type": "permissive",
"path": "/phase2/include/pcb.h",
"provenance": "stackv2-0112.json.gz:17754",
"repo_name": "notchla/OS_project",
"revision_date": "2020-12-26T22:16:34",
"revision_id": "c15879c5b22e54d24414d5402c5600eeef20219c",
"snapshot_id": "24edb6b6d6d1ddfd677dd1430205ce67aa822f83",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/notchla/OS_project/c15879c5b22e54d24414d5402c5600eeef20219c/phase2/include/pcb.h",
"visit_date": "2021-07-08T08:26:49.008932"
}
|
stackv2
|
/* functions to handle the pcb structures and the pcb list */
#ifndef PCB_H
#define PCB_H
#include <types_bikaya.h>
/* PCB handling functions */
/* PCB free list handling functions */
//initialize the static pcb array and add each block in the array to the free pcb list
void initPcbs(void);
//adds the pcb p to the free pcb list
void freePcb(pcb_t *p);
//removes a pcb from the free pcb list if possible, otherwise returns null
pcb_t *allocPcb(void);
/* PCB queue handling functions */
//initializes the list_head to a new list
void mkEmptyProcQ(struct list_head *head);
//returns true if the passed list is empty
int emptyProcQ(struct list_head *head);
//inserts the pcb p to the list pointed by head with cost O(n)
void insertProcQ(struct list_head *head, pcb_t *p);
//returns the first pcb in the list poined by head
pcb_t *headProcQ(struct list_head *head);
//removes the first pcb from the list pointed by head
pcb_t *removeProcQ(struct list_head *head);
//searches for the pcb p in the list pointed by head, removes it and returns p if p is in the list, null otherwise
pcb_t *outProcQ(struct list_head *head, pcb_t *p);
/* Tree view functions */
//returns true if p has no children
int emptyChild(pcb_t *this);
//inserts p in the end of the list of the children of prnt
void insertChild(pcb_t *prnt, pcb_t *p);
//removes and returns the first child of p
pcb_t *removeChild(pcb_t *p);
//removes p from the list of children of p->parent
pcb_t *outChild(pcb_t *p);
#endif
| 2.484375 | 2 |
2024-11-18T21:15:56.932749+00:00
| 2020-04-07T03:08:23 |
f2a06f24d41855c490b2d1f23cc54b7211413ccc
|
{
"blob_id": "f2a06f24d41855c490b2d1f23cc54b7211413ccc",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-07T03:08:23",
"content_id": "f5347e7fcc5496e6331e159b1328fd1ffbe42184",
"detected_licenses": [
"MIT"
],
"directory_id": "049388215768ffe631c1f114d451e2b2b7075d11",
"extension": "c",
"filename": "myLaplacianFoam.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": 1281,
"license": "MIT",
"license_type": "permissive",
"path": "/laplacianFoam/myLaplacianFoam.C",
"provenance": "stackv2-0112.json.gz:18011",
"repo_name": "sleepyXiwen/Cpp_OpenFOAM_Style",
"revision_date": "2020-04-07T03:08:23",
"revision_id": "57c93990abcab0ac3f16e11b4b8916a6034b795c",
"snapshot_id": "fd5fa89129d8d7f9567d20998f65e3d9c4bf3be0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sleepyXiwen/Cpp_OpenFOAM_Style/57c93990abcab0ac3f16e11b4b8916a6034b795c/laplacianFoam/myLaplacianFoam.C",
"visit_date": "2023-04-05T14:48:06.702272"
}
|
stackv2
|
/*---------------------------------------------------------------------------*\
Description
求解热传导方程
$$
\frac{\partial T}{\partial t}=\nabla\cdot{(D_T\nabla T)}
$$
\*---------------------------------------------------------------------------*/
#include "fvCFD.H"
#include "simpleControl.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
int main(int argc, char *argv[])
{
argList::addNote("求解标量场的拉普拉斯方程.");
#include "setRootCaseLists.H"
#include "createTime.H"
#include "createMesh.H"
simpleControl simple(mesh);
#include "createFields.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Info << "\n计算温度分布\n" << endl;
// SIMPLE算法循环
while (simple.loop())
{
Info << "时间 = " << runTime.timeName() << nl << endl;
// 要求解的方程
fvScalarMatrix TEqn
(
fvm::ddt(T) - fvm::laplacian(DT, T) //==0
);
TEqn.solve();
runTime.write(); // 写结果
runTime.printExecutionTime(Info);
}
Info << "计算结束\n" << endl;
return 0;
}
// ************************************************************************* //
| 2.046875 | 2 |
2024-11-18T21:15:56.999075+00:00
| 2017-01-03T20:08:37 |
351ccf6978a121a55e2c25f3a62b83f1382c7f08
|
{
"blob_id": "351ccf6978a121a55e2c25f3a62b83f1382c7f08",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-03T20:08:37",
"content_id": "2f0468da2e23f7e8a594da8095cdc4d96e0a42ac",
"detected_licenses": [
"MIT"
],
"directory_id": "1260328edbb4fb58cb2652005974ef7fd832184d",
"extension": "c",
"filename": "exo2.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": 435,
"license": "MIT",
"license_type": "permissive",
"path": "/Math et Informatique (M.I) 2015-2016/fichier/exo2.c",
"provenance": "stackv2-0112.json.gz:18139",
"repo_name": "skouliou/facebook-groups",
"revision_date": "2017-01-03T20:08:37",
"revision_id": "6f7cefef8667f545892b867489ad7c5e69790442",
"snapshot_id": "4c7e3bcc91a348376ca278690cf7fad4fe82d5d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skouliou/facebook-groups/6f7cefef8667f545892b867489ad7c5e69790442/Math et Informatique (M.I) 2015-2016/fichier/exo2.c",
"visit_date": "2021-06-12T15:25:52.142415"
}
|
stackv2
|
#include <stdio.h>
void copy(FILE* in_file, FILE* out_file) {
char cursor;
for (cursor = fgetc(in_file); cursor != EOF; cursor = fgetc(in_file)) {
cursor = (cursor == 'c') ? 'o' : cursor;
fputc(cursor, out_file);
}
}
int main() {
// code here
FILE* fst = fopen("./fst.txt", "r");
FILE* snd = fopen("./snd.txt", "w");
copy(fst, snd);
fclose(fst);
fclose(snd);
return 0;
}
| 2.71875 | 3 |
2024-11-18T21:15:57.233057+00:00
| 2021-02-09T06:30:18 |
fac092b21accb5bdbb6c72252dca0b8490d04f6a
|
{
"blob_id": "fac092b21accb5bdbb6c72252dca0b8490d04f6a",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-09T06:30:18",
"content_id": "0970e6645aab30fbbbc3df39692fd81d02f226ad",
"detected_licenses": [
"MIT"
],
"directory_id": "d87b8d396953fee653fbcbee92521395d0cec1fe",
"extension": "c",
"filename": "convey_test.c",
"fork_events_count": 0,
"gha_created_at": "2017-11-17T06:38:50",
"gha_event_created_at": "2017-11-17T06:38:51",
"gha_language": null,
"gha_license_id": null,
"github_id": 111067625,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4034,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/convey_test.c",
"provenance": "stackv2-0112.json.gz:18396",
"repo_name": "Raymond-Sun/nng",
"revision_date": "2021-02-09T06:30:18",
"revision_id": "1e125c621e2c4d60ac0daf85f3aa707adb1fd1c5",
"snapshot_id": "4f7dca95a8035002c32bde1f3071dd180160c600",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Raymond-Sun/nng/1e125c621e2c4d60ac0daf85f3aa707adb1fd1c5/tests/convey_test.c",
"visit_date": "2023-03-05T02:01:26.272742"
}
|
stackv2
|
/*
* Copyright 2017 Garrett D'Amore <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/*
* This file is intended to test the framework. It also demonstrates
* some of the capabilities.
*/
#include "convey.h"
#include <stdlib.h>
#include <string.h>
Main({
/*
* The ordering test demonstrates the execution order.
* At the end of each inner Convey, we roll back up the stack
* to the root, and then start over, bypassing Convey blocks
* that have already completed. Note that if a Convey block
* is the last thing in an enclosing Convey, we will make
* one more pass all the way through until we bypass that last
* item and can close the outer Convey.
*/
Test("Ordering", {
/*
* The buffer has to be static because don't want to clear
* it with each new pass -- that would defeat our tests!
* Note that it starts zeroed (C standard).
*/
static char buffer[32];
static int bufidx;
Convey("A runs first", { buffer[bufidx++] = 'A'; });
Printf("Bufidx is now %d", 1);
buffer[bufidx++] = '1';
Convey("B runs after A", {
So(strlen(buffer) > 0);
So(buffer[bufidx - 1] == '1');
buffer[bufidx++] = 'B';
Convey("C runs inside B", {
So(buffer[bufidx - 1] == 'B');
buffer[bufidx++] = 'C';
});
});
Convey("D runs afer A, B, C.", {
So(buffer[bufidx - 1] == '1');
buffer[bufidx++] = 'D';
});
buffer[bufidx++] = '2';
Convey("E is last", {
So(buffer[bufidx - 1] == '2');
buffer[bufidx++] = 'E';
});
So(strcmp(buffer, "A1BC1B1D12E12") == 0);
});
Test("Skipping works", {
int skipped = 0;
SkipConvey("ConveySkip works.", { So(skipped = 0); });
Convey("Assertion skipping works.", { SkipSo(skipped == 1); });
});
Test("Reset", {
static int x;
Convey("Initialize X to a non-zero value", {
So(x == 0);
x = 1;
So(x == 1);
});
Reset({ x = 20; });
Convey("Verify that reset did not get called", {
So(x == 1);
x = 5;
So(x == 5);
});
Convey("But now it did", { So(x == 20); });
});
/* save the current status so we can override */
int oldrv = convey_main_rv;
Test("Failures work", {
Convey("Assertion failure works",
{ Convey("Injected failure", { So(1 == 0); }); });
Convey("ConveyFail works", { ConveyFail("forced failure"); });
Convey("ConveyError works", { ConveyError("forced error"); });
});
/* Override the result variable to reset failure. */
convey_main_rv = oldrv;
Test("Environment works", {
Convey("PATH environment", {
So(ConveyGetEnv("PATH") != NULL);
So(strlen(ConveyGetEnv("PATH")) != 0);
});
Convey("Command line args work", {
char *v1 = ConveyGetEnv("ANOTHERNAME");
char *v2 = ConveyGetEnv("AGAIN");
if (ConveyGetEnv("NAMETEST") == NULL) {
SkipSo(v1 != NULL);
SkipSo(v2 != NULL);
SkipSo(strcmp(v1, "") == 0);
SkipSo(strcmp(v2, "YES") == 0);
} else {
So(v1 != NULL);
So(v2 != NULL);
So(strcmp(v1, "") == 0);
So(strcmp(v2, "YES") == 0);
}
})
});
})
| 2.328125 | 2 |
2024-11-18T21:15:57.639848+00:00
| 2016-04-04T19:05:44 |
ae0b73efec6971b6f171a890d131bc94b55b55dc
|
{
"blob_id": "ae0b73efec6971b6f171a890d131bc94b55b55dc",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-04T19:05:44",
"content_id": "51f44043bf71d6f13c5332b5d2a6e1d904251628",
"detected_licenses": [
"MIT"
],
"directory_id": "dfa4b89c2aece98ce221a7ab9f05957cd2cdbca1",
"extension": "c",
"filename": "l2cap_socket.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 55437126,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4612,
"license": "MIT",
"license_type": "permissive",
"path": "/src/l2cap/l2cap_socket.c",
"provenance": "stackv2-0112.json.gz:18910",
"repo_name": "SkinnerSweet/bluez_tools",
"revision_date": "2016-04-04T19:05:44",
"revision_id": "af0083d922d1ec1d470407020d1b2d4cfdb8db5b",
"snapshot_id": "9732c00b63e700b5e556de356a7ad2e03d383dbe",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/SkinnerSweet/bluez_tools/af0083d922d1ec1d470407020d1b2d4cfdb8db5b/src/l2cap/l2cap_socket.c",
"visit_date": "2021-01-10T15:42:01.029078"
}
|
stackv2
|
/* The MIT License (MIT)
Copyright (c) 2016 Thomas Bertauld <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "l2cap_socket.h"
#include "trace.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
static list_t *l2cap_socket_list = NULL;
// WARNING : this pointer always must point on the list's head.
// If controler == NULL, the first present available BT adaptator is taken.
l2cap_socket_t open_l2cap_socket(bt_address_t *adapter, uint16_t port, char to_bind) {
l2cap_socket_t result;
memset(&result, 0, sizeof(result));
(result.sockaddr).l2_family = AF_BLUETOOTH;
(result.sockaddr).l2_psm = htobs(port);
if (!adapter) {
adapter = BDADDR_ANY;
}
(result.sockaddr).l2_bdaddr = *adapter;
//result.l2_cid ???
result.sock = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
if (result.sock < 0) {
perror("opening socket");
result.sock = -1;
return result;
}
if (to_bind) {
if (bind(result.sock, (const struct sockaddr *)&(result.sockaddr), sizeof(result.sockaddr)) < 0) {
perror("binding socket");
close(result.sock);
result.sock = -1;
return result;
}
}
list_push(&l2cap_socket_list, &result, sizeof(l2cap_socket_t));
return result;
}
//------------------------------------------------------------------------------------
void close_l2cap_socket(l2cap_socket_t *l2cap_socket) {
if (l2cap_socket->sock < 0) {
print_trace(TRACE_WARNING, "close_l2cap_socket : already closed socket.\n");
return;
}
close(l2cap_socket->sock);
l2cap_socket_t *listed_socket = list_search(&l2cap_socket_list,
(const void *)l2cap_socket,
sizeof(l2cap_socket_t));
l2cap_socket->sock = -1;
if (listed_socket == NULL) {
print_trace(TRACE_WARNING, "close_l2cap_scoket : this socket wasn't referenced yet.\n");
return;
}
free(listed_socket);
return;
}
//------------------------------------------------------------------------------------
list_t *get_l2cap_socket_list(void) {
return l2cap_socket_list;
}
//------------------------------------------------------------------------------------
void close_all_l2cap_sockets(void) {
if (l2cap_socket_list == NULL) {
print_trace(TRACE_ERROR, "close_all_l2cap_sockets : no socket to close.\n");
return;
}
l2cap_socket_t *l2cap_socket = NULL;
while (l2cap_socket_list != NULL) {
l2cap_socket = (l2cap_socket_t *)list_pop(&l2cap_socket_list);
if (l2cap_socket->sock >= 0) {
close(l2cap_socket->sock);
}
free(l2cap_socket);
}
}
//------------------------------------------------------------------------------------
void display_l2cap_socket_list(void) {
list_t *tmp = l2cap_socket_list;
l2cap_socket_t val;
fprintf(stdout, "\nState of the current opened sockets list :\n");
while (tmp != NULL) {
val = *((l2cap_socket_t *)tmp->val);
char add[18];
ba2str((const bt_address_t *)&((val.sockaddr).l2_bdaddr), add);
fprintf(stdout, " -> device : %s | socket : %u \n", add, val.sock);
tmp = tmp->next;
}
fprintf(stdout, "\n");
}
//------------------------------------------------------------------------------------
#ifdef TEST_L2CAP_SOCKET
int main(int argc, char **argv) {
l2cap_socket_t test = open_l2cap_socket(NULL);
l2cap_socket_t test2 = open_l2cap_socket(NULL);
l2cap_socket_t test3 = open_l2cap_socket(NULL);
l2cap_socket_t test4 = open_l2cap_socket(NULL);
l2cap_socket_t test5 = open_l2cap_socket(NULL);
fprintf(stderr, "%i %i \n", test.sock, test.dev_id);
close_l2cap_socket(&test);
fprintf(stderr, "%i %i \n", test.sock, test.dev_id);
close_all_sockets();
}
#endif
| 2.53125 | 3 |
2024-11-18T21:15:58.415342+00:00
| 2015-11-20T00:55:05 |
1503a58736e54e42b9882a1ce7c029515e276a73
|
{
"blob_id": "1503a58736e54e42b9882a1ce7c029515e276a73",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-20T00:55:05",
"content_id": "9949ca8d78f0d99ca9e69117b5c2518fc4892baa",
"detected_licenses": [
"MIT"
],
"directory_id": "69218d822695d1a4f97fb1a35a04b630b8d12db0",
"extension": "c",
"filename": "util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 336,
"license": "MIT",
"license_type": "permissive",
"path": "/native/util.c",
"provenance": "stackv2-0112.json.gz:19172",
"repo_name": "xiangzilv123/logful-api",
"revision_date": "2015-11-20T00:55:05",
"revision_id": "05e19335d3ec1e98c94b32817a1f655e50ec480c",
"snapshot_id": "d757283661f0e36a6d27d0abf27eeeab2df332e4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xiangzilv123/logful-api/05e19335d3ec1e98c94b32817a1f655e50ec480c/native/util.c",
"visit_date": "2021-01-17T20:02:46.902915"
}
|
stackv2
|
#include "util.h"
char *str_contact(const char *str1, const char *str2) {
char *result;
result = (char *) malloc(strlen(str1) + strlen(str2) + 1);
if (!result) {
printf("Error: malloc failed in concat! \n");
exit(EXIT_FAILURE);
}
strcpy(result, str1);
strcat(result, str2);
return result;
}
| 2.484375 | 2 |
2024-11-18T21:15:58.737123+00:00
| 2021-07-05T04:37:02 |
0372f50f24210cf3a08a98d4c8449b0437d6c658
|
{
"blob_id": "0372f50f24210cf3a08a98d4c8449b0437d6c658",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-05T04:43:55",
"content_id": "c08e7b6c44776dc658d7439a1bb8bbfa81f891fd",
"detected_licenses": [
"MIT"
],
"directory_id": "c745fd8c14dcbb5d5e7e1f9cb3992b7c317c0500",
"extension": "c",
"filename": "util1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 48261248,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5208,
"license": "MIT",
"license_type": "permissive",
"path": "/gwmfe1ds/gtools/gp1/src/util1.c",
"provenance": "stackv2-0112.json.gz:19561",
"repo_name": "mfeproject/legacy-gwmfe",
"revision_date": "2021-07-05T04:37:02",
"revision_id": "ef7c1139661067165b287877f012d5664aeab85d",
"snapshot_id": "234163e4ee119cc469707c05e0bed7d75529c9fb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mfeproject/legacy-gwmfe/ef7c1139661067165b287877f012d5664aeab85d/gwmfe1ds/gtools/gp1/src/util1.c",
"visit_date": "2021-07-21T10:46:01.777061"
}
|
stackv2
|
#include <stdlib.h>
#include <sys/file.h>
#include <string.h>
#include "defs1.h"
#include "init1.h"
/*#include <unistd.h>*/
/*
Allocate n bytes of memory. Check for and exit upon error.
*/
void *emalloc(n)
unsigned n;
{
char *p;
if((p= malloc(n)) == NULL){
fprintf(stderr,"out of memory, %d bytes requested\n",n);
exit(1);
}
return(p);
}
copy_and_shift(tar,sou,n,offset)
register int n;
register float *tar,*sou,offset;
{
if(offset == 0.0)
while(n--)
*tar++ = *sou++;
else
while(n--)
*tar++ = *sou++ + offset;
}
/*
Make a copy of an array
*/
arrcpy(target,source)
short *target,*source;
{
while(*target++ = *source++)
;
}
/*
Draw the outline of the given box.
*/
boxdraw(box)
DEVICEBOX *box;
{
move(box->ll.x, box->ll.y);
cont(box->ur.x, box->ll.y);
cont(box->ur.x, box->ur.y);
cont(box->ll.x, box->ur.y);
cont(box->ll.x, box->ll.y);
}
/*
Given an x,y coordinate pair, a label 's', a linefeed size,
a quadrant code (1-4), and a character width and height,
compute the location of a string label.
*/
#define NE 1
#define SE 2
#define SW 3
#define NW 4
elabel(x,y,s,line_feed,quadrant,char_width,char_height)
int x,y,line_feed,quadrant,char_width,char_height;
char *s;
{
INTPAIR p;
int xshift = 0,yshift = 0,char_space = line_feed - char_height;
switch(quadrant){
case NE :xshift = char_width*0.6;
yshift = char_space/2;
break;
case SE :xshift = char_width*0.6;
yshift = -char_space - char_height;
break;
case SW :xshift = -strlen(s)*char_width;
yshift = -char_space - char_height;
break;
case NW :xshift = -strlen(s)*char_width ;
yshift = char_space/2;
break;
default :break;
}
p.x = x + xshift;
p.y = y + yshift;
move(p.x,p.y);
label(s);
}
/*
Check the given list of files for proper number and read accessibility.
*/
check_access(argc,argv)
int argc;
char *argv[];
{
int errstat = 0;
if(argc == 0){
errstat = 1;
fprintf(stderr,"usage: gp1 file1 ...\n");
}else if(argc > MAXFILES){
errstat = 1;
fprintf(stderr,"too many file names in argument list\n");
}
while(argc--)
if(can_access(*argv++,R_OK)){
errstat = 1;
fprintf(stderr,"can't open %s for reading\n",argv[-1]);
}
return errstat;
}
set_attribute(alist,index,ntype)
ATTRIBUTE *alist;
int index,ntype;
{
int i;
for(i=0;i<MAXATTR;i++){
if(alist[i].index == 0)
alist[i].index = index;
if(alist[i].index == index){
if((alist[i].nodetype = ntype) == DVAL) /* default */
alist[i].index = 0;
break;
}
}
}
get_attribute(alist,index)
ATTRIBUTE *alist;
int index;
{
int i;
for(i=0;i<MAXATTR;i++)
if(alist[i].index == index)
return alist[i].nodetype;
return DVAL; /* default */
}
REALPAIR
get_shift(f,c)
int f,c;
{
REALPAIR r;
extern REALPAIR fshift[],cshift[];
r.x = fshift[f].x + cshift[c].x;
r.y = fshift[f].y + cshift[c].y;
return r;
}
expand_nlist(expanded_list,nlp)
short *expanded_list,*nlp;
{
short left,right,step;
while(*nlp)
if(*nlp > ITEM_OFFSET) /* solitary entry */
*expanded_list++ = *nlp++ - ITEM_OFFSET;
else{ /* entry is left end of a range of values */
left = *nlp++;
right = *nlp++;
step = *nlp++;
for(;left<right;left += step)
*expanded_list++ = left;
*expanded_list++ = right;
}
*expanded_list = (short)0;
}
char *
print_nlist(nlp)
short *nlp;
{
static char s[80],s1[10];
*s = '\0';
while(*nlp)
if(*nlp > ITEM_OFFSET){
sprintf(s1," %d",*nlp++ - ITEM_OFFSET);
strcat(s,s1);
}else{
sprintf(s1," %d-%d",*nlp,nlp[1]);
nlp += 2;
strcat(s,s1);
if(*nlp++ != 1){
sprintf(s1,"(%d)",nlp[-1]);
strcat(s,s1);
}
}
return s;
}
collect_attributes(pic,bp)
PICTURESPEC *pic;
char *bp[];
{
int a,i = 0;
extern REALPAIR fshift[],cshift[];
static char buf[200];
short clist[MAXCOMP],*cp,flist[MAXFRAMES],*fp;
bp[0] = buf;
expand_nlist(clist,pic->cseq);
expand_nlist(flist,pic->fseq);
for(fp = flist;*fp;fp++)
if(fshift[*fp].x != 0.0 || fshift[*fp].y != 0.0){
sprintf(bp[i++],"f%d shift %.2g %.2g",*fp,fshift[*fp].x,fshift[*fp].y);
bp[i] = bp[i-1] + strlen(bp[i-1]) + 1;
}
for(cp = clist;*cp;cp++){
if((a = get_attribute(pic->attr,*cp)) != DVAL){
sprintf(bp[i++],"c%d: %s",*cp,a == SVAL ? "squares" : "triangles");
bp[i] = bp[i-1] + strlen(bp[i-1]) + 1;
}
if(cshift[*cp].x != 0.0 || cshift[*cp].y != 0.0){
sprintf(bp[i++],"c%d shift %.2g %.2g",*cp,cshift[*cp].x,cshift[*cp].y);
bp[i] = bp[i-1] + strlen(bp[i-1]) + 1;
}
}
bp[i] = NULL;
return i;
}
deallocmem(fp,n)
FRAMETYPE *fp;
int n;
{
for(;n;n--,fp++){
free((char *)fp->head->val);
free((char *)fp->head);
}
}
int emktemp(name)
char *name;
{
static char x = 'a';
char *p = name;
while(*p != '?')
++p;
*p = x++;
return mkstemp(name);
}
setviewport(vp,xp)
DEVICEBOX *vp;
int xp;
{
vp->ll.y += 4*vp->ch_size;
if(xp){ /* decrease viewport size just a little bit */
vp->ll.x += vp->ch_size;
vp->ur.x -= vp->ch_size;
vp->ur.y -= vp->ch_size;
}
}
save_argv(av,af)
char *av[],*af;
{
while(*av){
strcat(af,*av++);
if(*av)
strcat(af," ");
}
}
format(s,d,t)
char *s,t;
double d;
{
int i;
i = (int)floor(log10(d));
i = (i > 0) ? 1 : -i + 2;
sprintf(s,"%%.%d%c",i,t);
}
| 2.6875 | 3 |
2024-11-18T21:15:58.816149+00:00
| 2021-03-25T20:38:09 |
b4ba33b9b3527957917be2026492977864be909b
|
{
"blob_id": "b4ba33b9b3527957917be2026492977864be909b",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-25T20:38:09",
"content_id": "1e6d32fa02fa569a1784acec50ed59558c082d17",
"detected_licenses": [
"MIT"
],
"directory_id": "165955ca55e651777aa07e80031f094f0cfd1c33",
"extension": "h",
"filename": "EffectWaveforms.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 209388834,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1357,
"license": "MIT",
"license_type": "permissive",
"path": "/EffectcSource/include/EffectWaveforms.h",
"provenance": "stackv2-0112.json.gz:19689",
"repo_name": "Gustice/LightEffectLibrary",
"revision_date": "2021-03-25T20:38:09",
"revision_id": "208c5a53de8680de63e14aa308ce107452df8449",
"snapshot_id": "b24a212c99ea625fdc6a28384c154d45a78abde1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Gustice/LightEffectLibrary/208c5a53de8680de63e14aa308ce107452df8449/EffectcSource/include/EffectWaveforms.h",
"visit_date": "2023-04-11T14:23:46.868588"
}
|
stackv2
|
/**
* @file EffectWaveforms.h
* @author Gustice
* @brief Predefined Waveforms that can be put together to a complex Waveform
* @version 0.6
* @date 2019-10-01
*
* @copyright Copyright (c) 2019
*
*/
#pragma once
#ifdef __cplusplus
extern "C"{
#endif
#include <stdint.h>
/// Length of all subsequent Template definitions
extern const uint16_t cu16_TemplateLength;
/// Idle intensity for Slopes and Pulses
extern const uint8_t gu8_idleIntensity;
/// Idle intensity for Slopes and Pulses
extern const uint8_t gu8_fullIntensity;
/// Headrom for Effects on top of idle brightness
extern const uint8_t gu8_dynamicRange;
/// Standard cross fade steps
extern const uint8_t gu8_fadeSteps;
/// Starts from idle \ref gu8_idleIntensity and represents a gaussian impulse \ref gu8_fullIntensity
extern const uint8_t gau8_offsetPulse[];
/// Starts at zero and rises to idle intensity \ref gu8_idleIntensity
extern const uint8_t gau8_initSlope[];
/// Starts from idle \ref gu8_idleIntensity and rises up to full intensity \ref gu8_fullIntensity
extern const uint8_t gau8_offsetSlope[];
/// Starts at zero and rises to full intensity \ref gu8_fullIntensity
extern const uint8_t gau8_fullSlope[];
/// Starts at zero and represents a gaussian impulse to full intensity \ref gu8_fullIntensity
extern const uint8_t gau8_fullPulse[];
#ifdef __cplusplus
}
#endif
| 2.078125 | 2 |
2024-11-18T21:15:59.228618+00:00
| 2017-02-15T08:45:25 |
f1bbe57bf3f3e22843d19e1ae80d64e243b22006
|
{
"blob_id": "f1bbe57bf3f3e22843d19e1ae80d64e243b22006",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-15T08:45:25",
"content_id": "9711dd99f35e28a55ac1656b936603cdda590591",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "210690c7b5cb48ac965434344d69806b314e9380",
"extension": "c",
"filename": "dotproduct.c",
"fork_events_count": 0,
"gha_created_at": "2017-02-22T20:40:37",
"gha_event_created_at": "2017-02-22T20:40:37",
"gha_language": null,
"gha_license_id": null,
"github_id": 82850367,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2468,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/dotproduct.c",
"provenance": "stackv2-0112.json.gz:19945",
"repo_name": "matsjoyce/iteration_utilities",
"revision_date": "2017-02-15T08:45:25",
"revision_id": "bc8b1a52eb39ee532abd23214682ef32070089f1",
"snapshot_id": "c4a0e4f83579a9c4531547af0b0592ab59f5a975",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/matsjoyce/iteration_utilities/bc8b1a52eb39ee532abd23214682ef32070089f1/src/dotproduct.c",
"visit_date": "2021-01-21T09:03:00.772461"
}
|
stackv2
|
/******************************************************************************
* Licensed under Apache License Version 2.0 - see LICENSE.rst
*****************************************************************************/
static PyObject *
PyIU_DotProduct(PyObject *m, PyObject *args)
{
PyObject *vec1=NULL, *vec2=NULL;
PyObject *iterator1=NULL, *iterator2=NULL;
PyObject *item1=NULL, *item2=NULL;
PyObject *product=NULL;
PyObject *result=NULL;
PyObject *tmp=NULL;
if (!PyArg_ParseTuple(args, "OO", &vec1, &vec2)) {
return NULL;
}
iterator1 = PyObject_GetIter(vec1);
if (iterator1 == NULL) {
goto Fail;
}
iterator2 = PyObject_GetIter(vec2);
if (iterator2 == NULL) {
goto Fail;
}
while ( (item1 = (*Py_TYPE(iterator1)->tp_iternext)(iterator1)) &&
(item2 = (*Py_TYPE(iterator2)->tp_iternext)(iterator2))) {
product = PyNumber_Multiply(item1, item2);
if (product == NULL) {
goto Fail;
}
if (result == NULL) {
result = product;
product = NULL;
} else {
tmp = result;
result = PyNumber_Add(result, product);
Py_DECREF(product);
product = NULL;
Py_DECREF(tmp);
tmp = NULL;
if (result == NULL) {
goto Fail;
}
}
Py_DECREF(item1);
Py_DECREF(item2);
}
Py_DECREF(iterator1);
Py_DECREF(iterator2);
PYIU_CLEAR_STOPITERATION;
if (result == NULL) {
result = PyLong_FromLong((long)0);
}
return result;
Fail:
Py_XDECREF(iterator1);
Py_XDECREF(iterator2);
Py_XDECREF(item1);
Py_XDECREF(item2);
Py_XDECREF(product);
Py_XDECREF(result);
return NULL;
}
/******************************************************************************
* Docstring
*****************************************************************************/
PyDoc_STRVAR(PyIU_DotProduct_doc, "dotproduct(vec1, vec2)\n\
--\n\
\n\
Dot product (matrix multiplication) of two vectors.\n\
\n\
Parameters\n\
----------\n\
vec1, vec2 : iterable\n\
Any `iterables` to calculate the dot product.\n\
\n\
Returns\n\
-------\n\
dotproduct : number\n\
The dot product - the sum of the element-wise multiplication.\n\
\n\
Examples\n\
--------\n\
>>> from iteration_utilities import dotproduct\n\
>>> dotproduct([1,2,3,4], [1,2,3,4])\n\
30");
| 2.703125 | 3 |
2024-11-18T21:15:59.307260+00:00
| 2019-08-14T23:33:21 |
ff02933ae2238d9c8ac8c30f2c46348a2be8ed4b
|
{
"blob_id": "ff02933ae2238d9c8ac8c30f2c46348a2be8ed4b",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-14T23:33:21",
"content_id": "6c1aa3012617a1ac6e3fad3cfbec8c51aa41045a",
"detected_licenses": [
"MIT"
],
"directory_id": "dd1b1c4bb086b123ceeaa4d32bfb1d26bbe38f3a",
"extension": "c",
"filename": "lpg_integer_set.c",
"fork_events_count": 2,
"gha_created_at": "2017-01-02T17:29:42",
"gha_event_created_at": "2022-05-24T23:14:46",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 77850241,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2043,
"license": "MIT",
"license_type": "permissive",
"path": "/generic/lpg_integer_set.c",
"provenance": "stackv2-0112.json.gz:20073",
"repo_name": "TyRoXx/Lpg",
"revision_date": "2019-08-14T23:33:21",
"revision_id": "cbee7e6cceba239dd3832d393d047b4204897fdc",
"snapshot_id": "79d5eaa39a08d3885c710ad3e48ff70f7188c45a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/TyRoXx/Lpg/cbee7e6cceba239dd3832d393d047b4204897fdc/generic/lpg_integer_set.c",
"visit_date": "2021-12-12T10:51:54.256363"
}
|
stackv2
|
#include "lpg_integer_set.h"
#include "lpg_allocate.h"
integer_set integer_set_from_range(integer_range const range)
{
integer const size = integer_range_size(range);
if (!integer_less_or_equals(size, integer_create(0, SIZE_MAX)))
{
LPG_TO_DO();
}
integer_set const result = {allocate_array((size_t)size.low, sizeof(*result.elements)), (size_t)size.low};
for (uint64_t i = 0; i < size.low; ++i)
{
result.elements[i] = range.minimum;
ASSERT(integer_add(result.elements + i, integer_create(0, i)));
}
return result;
}
void integer_set_free(integer_set const freed)
{
if (freed.elements)
{
deallocate(freed.elements);
}
}
bool integer_set_contains_range(integer_set const set, integer_range const range)
{
bool added = true;
for (integer i = range.minimum; integer_less_or_equals(i, range.maximum);
added = integer_add(&i, integer_create(0, 1)))
{
ASSUME(added);
if (!integer_set_contains(set, i))
{
return false;
}
}
return true;
}
bool integer_set_contains(integer_set const set, integer const element)
{
for (size_t i = 0; i < set.used; ++i)
{
if (integer_equal(set.elements[i], element))
{
return true;
}
}
return false;
}
void integer_set_remove_range(integer_set *const set, integer_range const range)
{
bool added = true;
for (integer i = range.minimum; integer_less_or_equals(i, range.maximum);
added = integer_add(&i, integer_create(0, 1)))
{
ASSUME(added);
integer_set_remove(set, i);
}
}
void integer_set_remove(integer_set *const set, integer const element)
{
for (size_t i = 0; i < set->used; ++i)
{
if (integer_equal(set->elements[i], element))
{
set->elements[i] = set->elements[set->used - 1];
set->used -= 1;
return;
}
}
}
bool integer_set_is_empty(integer_set const set)
{
return (set.used == 0);
}
| 2.953125 | 3 |
2024-11-18T21:15:59.389605+00:00
| 2014-11-23T16:56:37 |
01ed9eadc7f45c218483c5eb940249371b4fa022
|
{
"blob_id": "01ed9eadc7f45c218483c5eb940249371b4fa022",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-23T16:56:37",
"content_id": "49153abf5b63b62826c1deaf39faa893e614dbb7",
"detected_licenses": [
"MIT"
],
"directory_id": "c17a721bb4158486820f7ea8695b578413961ced",
"extension": "h",
"filename": "scene.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": 4813,
"license": "MIT",
"license_type": "permissive",
"path": "/src/scene.h",
"provenance": "stackv2-0112.json.gz:20202",
"repo_name": "jtheoof/bina",
"revision_date": "2014-11-23T16:56:37",
"revision_id": "577a38336c96a5c4e05cd08e20548228fd5fd3f5",
"snapshot_id": "e678af6b0ac1627b02a2d97be3eca37d5c4d5963",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jtheoof/bina/577a38336c96a5c4e05cd08e20548228fd5fd3f5/src/scene.h",
"visit_date": "2020-05-26T19:59:23.579597"
}
|
stackv2
|
/**
* Contains all the necessary structs and functions to deal with a scene.
*
* A scene, for now, is composed of the background image and an associated
* scale map which serves to compute the scale of object depending on its
* position on the image. The scale map is, of course, not visible on the
* screen. It is simply used to scale an object according to the pixel color.
*/
/**
* @file scene.h
* @author Jeremy Attali, Johan Attali
* @date August 10, 2013
*/
#pragma once
#include "sprite.h"
/* TODO Remove this if unsused. */
typedef struct scene_char_t
{
float minsize;
float maxsize;
sprite_t* sprite;
} scene_char_t;
typedef struct scene_t
{
/**
* The background of the scene.
*
* For now we do not support scenes than spans past the viewport (scenes
* too large for the camera).
*/
sprite_t* background;
/**
* The scale map.
*
* A white pixel corresponds to #maxsize for character. A black pixel
* corresponds to #minsize for character. This does not need to be
* a sprite because it will not be drawn on the screen. It will just be
* used to compute the final size of a sprite (ex: the main character).
*/
texture_t* smap;
/**
* Background program id.
*
* Obtained via #shader_create_program.
*/
unsigned int bg_prog;
/**
* Character program id.
*
* Obtained via #shader_create_program.
*/
unsigned int ch_prog;
/**
* Minimum scale of the character.
*
* This is a normalized value. For example 0.5f will mean that the minimum
* size of the character will be half of the original one.
*/
float scale_min;
/**
* Maximum scale of the character.
*
* This is a normalized value. For example 1.0f will mean that the maximum
* size of the character will be the original one.
*/
float scale_max;
/**
* The difference between #scale_max and #scale_min.
*
* This is used in order to avoid doing it many times.
*/
float scale_dif;
/**
* The character that moves around the scene.
*/
sprite_t* character;
/**
* The width of the scene.
*
* Used to render the viewport and the background for example.
*/
unsigned int width;
/*
* The height of the scene.
*
* Used to render the viewport and the background for example.
*/
unsigned int height;
/**
* Time since the character has been idle (no animation applied to it).
*/
float time_idle;
/**
* A simple flag to indicate that the scene has been loaded and is ready
* to be rendered.
*/
short is_ready;
#define DEMO_SPRITES 0
sprite_t** demo_sprites;
texture_t** demo_textures;
} scene_t;
/**
* Loads a scene with a name.
*
* The scene also specifies the minimum scale and maximum scale of the
* character.
*
* Later we can imagine having a real manifest for a scene. With all
* objects presents, their positions, sizes, scales, ...
*
* @param name The name of the scene. Must be the name of the folder present
* in 'scenes' assets. The folder must contain a 'background.png' and
* 'scaleMap.png' file.
* @param minsize The minimum scaling ratio of the character.
* @param maxsize The maximum scaling ratio of the character.
* @return The scene created.
*/
scene_t* scene_load(const char* name,
const float minsize, const float maxsize);
/**
* The scene is responsible for releasing memory of the texture object it has
* created for background and scale map sprites.
*
* @param scene The scene to delete.
*/
void scene_unload(scene_t** scene);
/**
* Animates the scene.
*
* @param scene The scene to animate.
* @param elapsed Time elapsed since last frame.
*/
void scene_animate(scene_t* scene, float elapsed);
/**
* Renders the scene.
*
* @param scene The scene to render.
*/
void scene_render(scene_t* scene);
/**
* Moves the character in the scene.
*
* @param scene The scene where the character is present.
* @param screen The destination where the character should go in screen
* coordinates.
* @param speed The speed we want to set it to.
*/
void scene_move_character_to(scene_t* scene, vec2_t screen, float speed);
/**
* Computes the size of the character based on its position thanks to the
* scale map.
*
* @param scene The scene where the character is.
* @param norm A normalized point (0 to 1) that represents the coordinate we
* are looking for in the scale map.
* @return A ratio between 0 and 1 that corresponds to the pixel size.
* 0 stands for minimum size in the scene. 1 stands for maximum size in the
* scene.
*/
float scene_compute_character_size(scene_t* scene, const vec2_t norm);
| 2.859375 | 3 |
2024-11-18T21:15:59.863109+00:00
| 2014-12-05T00:16:12 |
f78bb4bd019babb6740701859861cc5aca70332c
|
{
"blob_id": "f78bb4bd019babb6740701859861cc5aca70332c",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-05T00:16:12",
"content_id": "fe7f51d7bc48ba84728a17e3324bfb26fa9a4861",
"detected_licenses": [
"MIT"
],
"directory_id": "7760b60252c09677e9ff566016a922159a17e28a",
"extension": "c",
"filename": "load_average.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": 766,
"license": "MIT",
"license_type": "permissive",
"path": "/load_average.c",
"provenance": "stackv2-0112.json.gz:20460",
"repo_name": "sousa-lucas/ec8top",
"revision_date": "2014-12-05T00:16:12",
"revision_id": "7337e360cea48f6f444997e061889e22300c6d8d",
"snapshot_id": "4048928c0b8cea1af8bfd838db59a2c0ef89c660",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sousa-lucas/ec8top/7337e360cea48f6f444997e061889e22300c6d8d/load_average.c",
"visit_date": "2021-01-09T06:49:53.614700"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
#include <sys/sysinfo.h>//biblioteca para obter informação direto do sistema (proc)
#include "load_average.h"
int load_average(char *b, size_t s) {
/*cria a struct que irá obtem informções do sistema*/
struct sysinfo Sinfo;
char buffer[500];
buffer[0] = '\x0';
if(sysinfo(&Sinfo) != -1)
/* Impressão do Load Averages de 1, 5 and 15 minutos
* necessário a divisão por 65536 = (2¹⁶), para igualar a escalar do que é entregue pelo proc*/
snprintf(buffer,500, "<b>Load Average:</b> (%.2f), (%.2f), (%.2f)<br>\n",
((Sinfo.loads[0])/65536.0), ((Sinfo.loads[1])/65536.0), ((Sinfo.loads[2])/65536.0));
//coloca as informacoes no buffer do projeto
strncat(b, buffer, s);
return 0;
}
| 2.90625 | 3 |
2024-11-18T21:16:00.755316+00:00
| 2015-03-28T08:21:39 |
5f9a850faa72d933faff46274c798d7ec5550c49
|
{
"blob_id": "5f9a850faa72d933faff46274c798d7ec5550c49",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-28T08:21:52",
"content_id": "cdc844d3f7f86048c05606487407bcc3d6a4cf0f",
"detected_licenses": [
"MIT"
],
"directory_id": "d0a4af187e11d82715de8dc51f39bc3ab8f2abbe",
"extension": "c",
"filename": "code.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": 2259,
"license": "MIT",
"license_type": "permissive",
"path": "/src/SCC-core/code.c",
"provenance": "stackv2-0112.json.gz:21102",
"repo_name": "shihyu/SCC",
"revision_date": "2015-03-28T08:21:39",
"revision_id": "1b67d88f42ccf8e9eb123380f8aec1ddb7f5abf6",
"snapshot_id": "b3807fda07c20367a26dff897963dd760bacc9b1",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shihyu/SCC/1b67d88f42ccf8e9eb123380f8aec1ddb7f5abf6/src/SCC-core/code.c",
"visit_date": "2021-01-22T16:44:53.301236"
}
|
stackv2
|
#include "code.h"
#include <windows.h>
static IdentSym symTab[MAX_SYM_NUM];
static ConstSym constTab[MAX_SYM_NUM];
static int pos_id = 0;
static int pos_const = 0;
void symTab_insert(sym_e type, char* value){
/// 2014-7-9 添加重复定义提示出错
if(symTab_lookup(value)!=NULL){
_Error_print("redefined IDENT symbol %s",value);
return; // 不再插入符号表
}
/// 2014-7-9 添加重复定义提示出错
symTab[pos_id].type = type;
ASSERT(value!=0);
symTab[pos_id].value = value;
ASSERT(pos_id<MAX_SYM_NUM);
pos_id ++;
}
IdentSym* symTab_lookup(char* value){
int i;
for(i=0;i<pos_id;i++){
if(0==strcmp(symTab[i].value,value)){
return symTab+i;
}
}
return NULL;
}
ConstSym* constTab_lookInt(char* value){
int i;
for(i=0;i<pos_const;i++){
if(0==strcmp(constTab[i].value,value)){
return constTab+i;
}
}
if(i==pos_const){
constTab[pos_const].value = value;
ASSERT(pos_const<MAX_SYM_NUM);
pos_const ++;
}
return constTab+pos_const;
}
//函数用来产生临时变量, 如产生临时变量t1 :
static int tempNum=0;
char* newTemp(){
//N=N+1;
//“t”|| ITOS(N) ;
tempNum ++ ;
char* tempName = (char*) malloc(8*sizeof(char));
*tempName='t';
strcpy(tempName+1,itos(tempNum) );
return tempName;
}
static int labelNum=0;
char* getLabel(){
//N=N+1;
//“t”|| ITOS(N) ;
labelNum ++ ;
char* labelName = (char*) malloc(8*sizeof(char));
strcpy(labelName,"label");
strcpy(labelName+5,itos(labelNum) );
return labelName;
}
char* itos(int n) {
char* str= (char*)malloc(10*sizeof(char));
int radix=10;
int i = 0;
int m = n;
int f = 0;
if (n == 0) { //如果是0,直接赋值
str[0] = '0';
str[1] = '\0';
return str;
}
else if (n < 0){
str[0] = '-';
n = -n;
f = 1;
}
while (m){
m /= radix;
i++;
}
str[i + f] = '\0';
i--;
while (n){
str[i + f] = n % radix;
if (str[i + f] < 10){
str[i + f] += '0';
}
else{
str[i + f] += ('a' - 10);
}
n /= radix;
i--;
}
return str;
}
| 2.6875 | 3 |
2024-11-18T21:16:00.891225+00:00
| 2020-04-01T17:45:22 |
2b6dd0cd7d9283e89bf3aa2d5827fc38c71f9e3f
|
{
"blob_id": "2b6dd0cd7d9283e89bf3aa2d5827fc38c71f9e3f",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-01T17:45:22",
"content_id": "a392ba36b30add6cfede60bb0ff6420ec5299a7c",
"detected_licenses": [
"MIT"
],
"directory_id": "3d384fe7def1cf54ec3b6db6c461f063f0fa149a",
"extension": "c",
"filename": "main_19.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 252246499,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1427,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/main_19.c",
"provenance": "stackv2-0112.json.gz:21360",
"repo_name": "rolfwr/pmcc",
"revision_date": "2020-04-01T17:45:22",
"revision_id": "b26a3408884ad309181d9a98711a57dabbf7cd37",
"snapshot_id": "041637992a820e7b26630266aec4827fcc68130d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rolfwr/pmcc/b26a3408884ad309181d9a98711a57dabbf7cd37/tests/main_19.c",
"visit_date": "2021-05-20T10:21:47.705675"
}
|
stackv2
|
char number;
char outnum;
char huns;
char tens;
char ones;
char needtens;
char fizz;
char buzz;
char neednum;
int main() {
number = 0;
fizz = 3;
buzz = 5;
while (number - 100) {
number = number + 1;
fizz = fizz - 1;
buzz = buzz - 1;
neednum = 1;
if (!fizz) {
fizz = 3;
putchar('F');
putchar('i');
putchar('z');
putchar('z');
neednum = 0;
}
if (!buzz) {
buzz = 5;
putchar('B');
putchar('u');
putchar('z');
putchar('z');
neednum = 0;
}
if (neednum) {
outnum = number;
huns = 0;
tens = 0;
ones = 0;
while (outnum) {
outnum = outnum - 1;
ones = ones + 1 ;
if (!(ones - 10)) {
ones = 0;
tens = tens + 1;
}
if (!(tens - 10)) {
tens = 0;
huns = huns + 1;
}
}
needtens = tens;
if (huns) {
putchar('0' + huns);
needtens = 1;
}
if (needtens) {
putchar('0' + tens);
}
putchar('0' + ones);
}
putchar('\n');
}
}
| 2.375 | 2 |
2024-11-18T21:16:01.267472+00:00
| 2018-05-16T21:44:18 |
7fde3efebafc4e7894f705c2533594908bfc6ee5
|
{
"blob_id": "7fde3efebafc4e7894f705c2533594908bfc6ee5",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-16T21:44:18",
"content_id": "112d9f323939c529772f4a12d9f99130f5793475",
"detected_licenses": [
"ISC"
],
"directory_id": "6c00ab8c0b21f487a9bbaadd57e8f390a7a0ba0e",
"extension": "h",
"filename": "riscv.h",
"fork_events_count": 0,
"gha_created_at": "2019-02-28T15:01:42",
"gha_event_created_at": "2019-02-28T15:01:43",
"gha_language": null,
"gha_license_id": "ISC",
"github_id": 173132430,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1175,
"license": "ISC",
"license_type": "permissive",
"path": "/macsim/src/arch/riscv.h",
"provenance": "stackv2-0112.json.gz:21745",
"repo_name": "domso/rcmc",
"revision_date": "2018-05-16T21:44:18",
"revision_id": "e442772bfcc9607fadfbfc5a4f02af2d330dd8d4",
"snapshot_id": "0ad73ff096a6591bbe869d97c2a8354187fde590",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/domso/rcmc/e442772bfcc9607fadfbfc5a4f02af2d330dd8d4/macsim/src/arch/riscv.h",
"visit_date": "2020-04-25T23:04:40.052472"
}
|
stackv2
|
/**
* riscv.h
* RISC-V ISA
*
* MacSim project
*/
#ifndef _RISCV_H
#define _RISCV_H
#include "node.h"
// Init the memory
void riscv_init_context(node_t *node);
// Remove context from memory and free memory blocks
void riscv_finish_context(node_t *node);
// Print a register dump
void riscv_print_context(node_t *node);
// Dump the current context to file.
void riscv_dump_context(const char *file, node_t *node);
// Disassemble one instruction
int riscv_disasm(node_t *node, addr_t pc, char *dstr);
// internal use, only in riscv.c and rvmpb.c
bool riscv_instruction_uses_reg_s(uint_fast32_t iw);
bool riscv_instruction_uses_reg_t(uint_fast32_t iw);
instruction_class_t riscv_execute_iw(node_t *node, uint_fast32_t iw,
uint_fast32_t next_iw);
#define RISCV_CANONICAL_NAN_FLOAT 0x7FC00000
static inline float unboxing_float(double d)
{
uf64_t x;
uf32_t y;
x.f = d;
if ((x.i>>32) != -1) {
y.u = RISCV_CANONICAL_NAN_FLOAT;
} else {
y.u = x.u;
}
return y.f;
}
static inline double boxing_float(float f)
{
uf32_t x;
uf64_t y;
x.f = f;
y.u = 0xffffffff00000000 | x.u;
return y.f;
}
#endif
| 2.3125 | 2 |
2024-11-18T21:16:01.714745+00:00
| 2023-08-01T11:26:10 |
3e615bfb758bb46213bfc1097bdd344b27dc256d
|
{
"blob_id": "3e615bfb758bb46213bfc1097bdd344b27dc256d",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T08:22:52",
"content_id": "e40b907bd9fb404a1d50d89994c246391bf1c41b",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "eff786582e50538f7146a04aa40b632c891c9828",
"extension": "c",
"filename": "lis2de12_reg.c",
"fork_events_count": 27,
"gha_created_at": "2019-04-05T02:46:38",
"gha_event_created_at": "2023-09-04T07:37:33",
"gha_language": "C",
"gha_license_id": null,
"github_id": 179609736,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 67182,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/sensor/stmemsc/lis2de12_STdC/driver/lis2de12_reg.c",
"provenance": "stackv2-0112.json.gz:22132",
"repo_name": "zephyrproject-rtos/hal_st",
"revision_date": "2023-08-01T11:26:10",
"revision_id": "9b128caf3e7b2e750169b880e83f210ea2213473",
"snapshot_id": "19d338b979d27e552a1601d4d29153e559f9951f",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/zephyrproject-rtos/hal_st/9b128caf3e7b2e750169b880e83f210ea2213473/sensor/stmemsc/lis2de12_STdC/driver/lis2de12_reg.c",
"visit_date": "2023-09-01T17:02:01.724005"
}
|
stackv2
|
/**
******************************************************************************
* @file lis2de12_reg.c
* @author Sensors Software Solution Team
* @brief LIS2DE12 driver file
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2021 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
#include "lis2de12_reg.h"
/**
* @defgroup LIS2DE12
* @brief This file provides a set of functions needed to drive the
* lis2de12 enanced inertial module.
* @{
*
*/
/**
* @defgroup LIS2DE12_Interfaces_Functions
* @brief This section provide a set of functions used to read and
* write a generic register of the device.
* MANDATORY: return 0 -> no Error.
* @{
*
*/
/**
* @brief Read generic device register
*
* @param ctx read / write interface definitions(ptr)
* @param reg register to read
* @param data pointer to buffer that store the data read(ptr)
* @param len number of consecutive register to read
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t __weak lis2de12_read_reg(stmdev_ctx_t *ctx, uint8_t reg,
uint8_t *data,
uint16_t len)
{
int32_t ret;
ret = ctx->read_reg(ctx->handle, reg, data, len);
return ret;
}
/**
* @brief Write generic device register
*
* @param ctx read / write interface definitions(ptr)
* @param reg register to write
* @param data pointer to data to write in register reg(ptr)
* @param len number of consecutive register to write
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t __weak lis2de12_write_reg(stmdev_ctx_t *ctx, uint8_t reg,
uint8_t *data,
uint16_t len)
{
int32_t ret;
ret = ctx->write_reg(ctx->handle, reg, data, len);
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Sensitivity
* @brief These functions convert raw-data into engineering units.
* @{
*
*/
float_t lis2de12_from_fs2_to_mg(int16_t lsb)
{
return ((float_t)lsb / 256.0f) * 15.6f;
}
float_t lis2de12_from_fs4_to_mg(int16_t lsb)
{
return ((float_t)lsb / 256.0f) * 31.2f;
}
float_t lis2de12_from_fs8_to_mg(int16_t lsb)
{
return ((float_t)lsb / 256.0f) * 62.5f;
}
float_t lis2de12_from_fs16_to_mg(int16_t lsb)
{
return ((float_t)lsb / 256.0f) * 187.5f;
}
float_t lis2de12_from_lsb_to_celsius(int16_t lsb)
{
return (((float_t)lsb / 256.0f) * 1.0f) + 25.0f;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Data_generation
* @brief This section group all the functions concerning data generation.
* @{
*
*/
/**
* @brief Temperature status register.[get]
*
* @param ctx read / write interface definitions
* @param buff buffer that stores data read
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_temp_status_reg_get(stmdev_ctx_t *ctx, uint8_t *buff)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_STATUS_REG_AUX, buff, 1);
return ret;
}
/**
* @brief Temperature data available.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of tda in reg STATUS_REG_AUX
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_temp_data_ready_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_status_reg_aux_t status_reg_aux;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_STATUS_REG_AUX,
(uint8_t *)&status_reg_aux, 1);
*val = status_reg_aux.tda;
return ret;
}
/**
* @brief Temperature data overrun.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of tor in reg STATUS_REG_AUX
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_temp_data_ovr_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_status_reg_aux_t status_reg_aux;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_STATUS_REG_AUX,
(uint8_t *)&status_reg_aux, 1);
*val = status_reg_aux.tor;
return ret;
}
/**
* @brief Temperature output value.[get]
*
* @param ctx read / write interface definitions
* @param buff buffer that stores data read
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_temperature_raw_get(stmdev_ctx_t *ctx, int16_t *val)
{
uint8_t buff[2];
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_OUT_TEMP_L, buff, 2);
*val = (int16_t)buff[1];
*val = (*val * 256) + (int16_t)buff[0];
return ret;
}
/**
* @brief Temperature sensor enable.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of temp_en in reg TEMP_CFG_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_temperature_meas_set(stmdev_ctx_t *ctx,
lis2de12_temp_en_t val)
{
lis2de12_temp_cfg_reg_t temp_cfg_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TEMP_CFG_REG,
(uint8_t *)&temp_cfg_reg, 1);
if (ret == 0)
{
temp_cfg_reg.temp_en = (uint8_t) val;
ret = lis2de12_write_reg(ctx, LIS2DE12_TEMP_CFG_REG,
(uint8_t *)&temp_cfg_reg, 1);
}
return ret;
}
/**
* @brief Temperature sensor enable.[get]
*
* @param ctx read / write interface definitions
* @param val get the values of temp_en in reg TEMP_CFG_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_temperature_meas_get(stmdev_ctx_t *ctx,
lis2de12_temp_en_t *val)
{
lis2de12_temp_cfg_reg_t temp_cfg_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TEMP_CFG_REG,
(uint8_t *)&temp_cfg_reg, 1);
switch (temp_cfg_reg.temp_en)
{
case LIS2DE12_TEMP_DISABLE:
*val = LIS2DE12_TEMP_DISABLE;
break;
case LIS2DE12_TEMP_ENABLE:
*val = LIS2DE12_TEMP_ENABLE;
break;
default:
*val = LIS2DE12_TEMP_DISABLE;
break;
}
return ret;
}
/**
* @brief Output data rate selection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of odr in reg CTRL_REG1
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_data_rate_set(stmdev_ctx_t *ctx, lis2de12_odr_t val)
{
lis2de12_ctrl_reg1_t ctrl_reg1;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG1,
(uint8_t *)&ctrl_reg1, 1);
if (ret == 0)
{
ctrl_reg1.lpen = PROPERTY_ENABLE;
ctrl_reg1.odr = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG1,
(uint8_t *)&ctrl_reg1, 1);
}
return ret;
}
/**
* @brief Output data rate selection.[get]
*
* @param ctx read / write interface definitions
* @param val get the values of odr in reg CTRL_REG1
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_data_rate_get(stmdev_ctx_t *ctx, lis2de12_odr_t *val)
{
lis2de12_ctrl_reg1_t ctrl_reg1;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG1,
(uint8_t *)&ctrl_reg1, 1);
switch (ctrl_reg1.odr)
{
case LIS2DE12_POWER_DOWN:
*val = LIS2DE12_POWER_DOWN;
break;
case LIS2DE12_ODR_1Hz:
*val = LIS2DE12_ODR_1Hz;
break;
case LIS2DE12_ODR_10Hz:
*val = LIS2DE12_ODR_10Hz;
break;
case LIS2DE12_ODR_25Hz:
*val = LIS2DE12_ODR_25Hz;
break;
case LIS2DE12_ODR_50Hz:
*val = LIS2DE12_ODR_50Hz;
break;
case LIS2DE12_ODR_100Hz:
*val = LIS2DE12_ODR_100Hz;
break;
case LIS2DE12_ODR_200Hz:
*val = LIS2DE12_ODR_200Hz;
break;
case LIS2DE12_ODR_400Hz:
*val = LIS2DE12_ODR_400Hz;
break;
case LIS2DE12_ODR_1kHz620_LP:
*val = LIS2DE12_ODR_1kHz620_LP;
break;
case LIS2DE12_ODR_5kHz376_LP_1kHz344_NM_HP:
*val = LIS2DE12_ODR_5kHz376_LP_1kHz344_NM_HP;
break;
default:
*val = LIS2DE12_POWER_DOWN;
break;
}
return ret;
}
/**
* @brief High pass data from internal filter sent to output register
* and FIFO.
*
* @param ctx read / write interface definitions
* @param val change the values of fds in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_on_outputs_set(stmdev_ctx_t *ctx,
uint8_t val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
if (ret == 0)
{
ctrl_reg2.fds = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
}
return ret;
}
/**
* @brief High pass data from internal filter sent to output register
* and FIFO.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of fds in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_on_outputs_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
*val = (uint8_t)ctrl_reg2.fds;
return ret;
}
/**
* @brief High-pass filter cutoff frequency selection.[set]
*
* HPCF[2:1]\ft @1Hz @10Hz @25Hz @50Hz @100Hz @200Hz @400Hz @1kHz6 ft@5kHz
* AGGRESSIVE 0.02Hz 0.2Hz 0.5Hz 1Hz 2Hz 4Hz 8Hz 32Hz 100Hz
* STRONG 0.008Hz 0.08Hz 0.2Hz 0.5Hz 1Hz 2Hz 4Hz 16Hz 50Hz
* MEDIUM 0.004Hz 0.04Hz 0.1Hz 0.2Hz 0.5Hz 1Hz 2Hz 8Hz 25Hz
* LIGHT 0.002Hz 0.02Hz 0.05Hz 0.1Hz 0.2Hz 0.5Hz 1Hz 4Hz 12Hz
*
* @param ctx read / write interface definitions
* @param val change the values of hpcf in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_bandwidth_set(stmdev_ctx_t *ctx,
lis2de12_hpcf_t val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
if (ret == 0)
{
ctrl_reg2.hpcf = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
}
return ret;
}
/**
* @brief High-pass filter cutoff frequency selection.[get]
*
* HPCF[2:1]\ft @1Hz @10Hz @25Hz @50Hz @100Hz @200Hz @400Hz @1kHz6 ft@5kHz
* AGGRESSIVE 0.02Hz 0.2Hz 0.5Hz 1Hz 2Hz 4Hz 8Hz 32Hz 100Hz
* STRONG 0.008Hz 0.08Hz 0.2Hz 0.5Hz 1Hz 2Hz 4Hz 16Hz 50Hz
* MEDIUM 0.004Hz 0.04Hz 0.1Hz 0.2Hz 0.5Hz 1Hz 2Hz 8Hz 25Hz
* LIGHT 0.002Hz 0.02Hz 0.05Hz 0.1Hz 0.2Hz 0.5Hz 1Hz 4Hz 12Hz
*
* @param ctx read / write interface definitions
* @param val get the values of hpcf in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_bandwidth_get(stmdev_ctx_t *ctx,
lis2de12_hpcf_t *val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
switch (ctrl_reg2.hpcf)
{
case LIS2DE12_AGGRESSIVE:
*val = LIS2DE12_AGGRESSIVE;
break;
case LIS2DE12_STRONG:
*val = LIS2DE12_STRONG;
break;
case LIS2DE12_MEDIUM:
*val = LIS2DE12_MEDIUM;
break;
case LIS2DE12_LIGHT:
*val = LIS2DE12_LIGHT;
break;
default:
*val = LIS2DE12_LIGHT;
break;
}
return ret;
}
/**
* @brief High-pass filter mode selection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of hpm in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_mode_set(stmdev_ctx_t *ctx,
lis2de12_hpm_t val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
if (ret == 0)
{
ctrl_reg2.hpm = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
}
return ret;
}
/**
* @brief High-pass filter mode selection.[get]
*
* @param ctx read / write interface definitions
* @param val get the values of hpm in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_mode_get(stmdev_ctx_t *ctx,
lis2de12_hpm_t *val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
switch (ctrl_reg2.hpm)
{
case LIS2DE12_NORMAL_WITH_RST:
*val = LIS2DE12_NORMAL_WITH_RST;
break;
case LIS2DE12_REFERENCE_MODE:
*val = LIS2DE12_REFERENCE_MODE;
break;
case LIS2DE12_NORMAL:
*val = LIS2DE12_NORMAL;
break;
case LIS2DE12_AUTORST_ON_INT:
*val = LIS2DE12_AUTORST_ON_INT;
break;
default:
*val = LIS2DE12_NORMAL_WITH_RST;
break;
}
return ret;
}
/**
* @brief Full-scale configuration.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of fs in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_full_scale_set(stmdev_ctx_t *ctx, lis2de12_fs_t val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
if (ret == 0)
{
ctrl_reg4.fs = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
}
return ret;
}
/**
* @brief Full-scale configuration.[get]
*
* @param ctx read / write interface definitions
* @param val get the values of fs in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_full_scale_get(stmdev_ctx_t *ctx, lis2de12_fs_t *val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
switch (ctrl_reg4.fs)
{
case LIS2DE12_2g:
*val = LIS2DE12_2g;
break;
case LIS2DE12_4g:
*val = LIS2DE12_4g;
break;
case LIS2DE12_8g:
*val = LIS2DE12_8g;
break;
case LIS2DE12_16g:
*val = LIS2DE12_16g;
break;
default:
*val = LIS2DE12_2g;
break;
}
return ret;
}
/**
* @brief Block Data Update.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of bdu in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_block_data_update_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
if (ret == 0)
{
ctrl_reg4.bdu = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
}
return ret;
}
/**
* @brief Block Data Update.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of bdu in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_block_data_update_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
*val = (uint8_t)ctrl_reg4.bdu;
return ret;
}
/**
* @brief Reference value for interrupt generation.[set]
* LSB = ~16@2g / ~31@4g / ~63@8g / ~127@16g
*
* @param ctx read / write interface definitions
* @param buff buffer that contains data to write
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_filter_reference_set(stmdev_ctx_t *ctx,
uint8_t *buff)
{
int32_t ret;
ret = lis2de12_write_reg(ctx, LIS2DE12_REFERENCE, buff, 1);
return ret;
}
/**
* @brief Reference value for interrupt generation.[get]
* LSB = ~16@2g / ~31@4g / ~63@8g / ~127@16g
*
* @param ctx read / write interface definitions
* @param buff buffer that stores data read
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_filter_reference_get(stmdev_ctx_t *ctx,
uint8_t *buff)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_REFERENCE, buff, 1);
return ret;
}
/**
* @brief Acceleration set of data available.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of zyxda in reg STATUS_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_xl_data_ready_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_status_reg_t status_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_STATUS_REG,
(uint8_t *)&status_reg, 1);
*val = status_reg.zyxda;
return ret;
}
/**
* @brief Acceleration set of data overrun.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of zyxor in reg STATUS_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_xl_data_ovr_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_status_reg_t status_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_STATUS_REG,
(uint8_t *)&status_reg, 1);
*val = status_reg.zyxor;
return ret;
}
/**
* @brief Acceleration output value.[get]
*
* @param ctx read / write interface definitions
* @param buff buffer that stores data read
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_acceleration_raw_get(stmdev_ctx_t *ctx, int16_t *val)
{
uint8_t buff[6];
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_READ_START, buff, 6);
val[0] = (int16_t)buff[1];
val[0] = (val[0] * 256) + (int16_t)buff[0];
val[1] = (int16_t)buff[3];
val[1] = (val[1] * 256) + (int16_t)buff[2];
val[2] = (int16_t)buff[5];
val[2] = (val[2] * 256) + (int16_t)buff[4];
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Common
* @brief This section group common useful functions
* @{
*
*/
/**
* @brief DeviceWhoamI .[get]
*
* @param ctx read / write interface definitions
* @param buff buffer that stores data read
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_device_id_get(stmdev_ctx_t *ctx, uint8_t *buff)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_WHO_AM_I, buff, 1);
return ret;
}
/**
* @brief Self Test.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of st in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_self_test_set(stmdev_ctx_t *ctx, lis2de12_st_t val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
if (ret == 0)
{
ctrl_reg4.st = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
}
return ret;
}
/**
* @brief Self Test.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of st in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_self_test_get(stmdev_ctx_t *ctx, lis2de12_st_t *val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
switch (ctrl_reg4.st)
{
case LIS2DE12_ST_DISABLE:
*val = LIS2DE12_ST_DISABLE;
break;
case LIS2DE12_ST_POSITIVE:
*val = LIS2DE12_ST_POSITIVE;
break;
case LIS2DE12_ST_NEGATIVE:
*val = LIS2DE12_ST_NEGATIVE;
break;
default:
*val = LIS2DE12_ST_DISABLE;
break;
}
return ret;
}
/**
* @brief Reboot memory content. Reload the calibration parameters.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of boot in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_boot_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
if (ret == 0)
{
ctrl_reg5.boot = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
}
return ret;
}
/**
* @brief Reboot memory content. Reload the calibration parameters.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of boot in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_boot_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
*val = (uint8_t)ctrl_reg5.boot;
return ret;
}
/**
* @brief Info about device status.[get]
*
* @param ctx read / write interface definitions
* @param val register STATUS_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_status_get(stmdev_ctx_t *ctx,
lis2de12_status_reg_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_STATUS_REG, (uint8_t *) val, 1);
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Interrupts_generator_1
* @brief This section group all the functions that manage the first
* interrupts generator
* @{
*
*/
/**
* @brief Interrupt generator 1 configuration register.[set]
*
* @param ctx read / write interface definitions
* @param val register INT1_CFG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_gen_conf_set(stmdev_ctx_t *ctx,
lis2de12_int1_cfg_t *val)
{
int32_t ret;
ret = lis2de12_write_reg(ctx, LIS2DE12_INT1_CFG, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Interrupt generator 1 configuration register.[get]
*
* @param ctx read / write interface definitions
* @param val register INT1_CFG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_gen_conf_get(stmdev_ctx_t *ctx,
lis2de12_int1_cfg_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT1_CFG, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Interrupt generator 1 source register.[get]
*
* @param ctx read / write interface definitions
* @param val Registers INT1_SRC
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_gen_source_get(stmdev_ctx_t *ctx,
lis2de12_int1_src_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT1_SRC, (uint8_t *) val, 1);
return ret;
}
/**
* @brief User-defined threshold value for xl interrupt event on
* generator 1.[set]
* LSb = 16mg@2g / 32mg@4g / 62mg@8g / 186mg@16g
*
* @param ctx read / write interface definitions
* @param val change the values of ths in reg INT1_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_gen_threshold_set(stmdev_ctx_t *ctx,
uint8_t val)
{
lis2de12_int1_ths_t int1_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT1_THS, (uint8_t *)&int1_ths, 1);
if (ret == 0)
{
int1_ths.ths = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_INT1_THS, (uint8_t *)&int1_ths, 1);
}
return ret;
}
/**
* @brief User-defined threshold value for xl interrupt event on
* generator 1.[get]
* LSb = 16mg@2g / 32mg@4g / 62mg@8g / 186mg@16g
*
* @param ctx read / write interface definitions
* @param val change the values of ths in reg INT1_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_gen_threshold_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_int1_ths_t int1_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT1_THS, (uint8_t *)&int1_ths, 1);
*val = (uint8_t)int1_ths.ths;
return ret;
}
/**
* @brief The minimum duration (LSb = 1/ODR) of the Interrupt 1 event to be
* recognized.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of d in reg INT1_DURATION
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_gen_duration_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_int1_duration_t int1_duration;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT1_DURATION,
(uint8_t *)&int1_duration, 1);
if (ret == 0)
{
int1_duration.d = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_INT1_DURATION,
(uint8_t *)&int1_duration, 1);
}
return ret;
}
/**
* @brief The minimum duration (LSb = 1/ODR) of the Interrupt 1 event to be
* recognized.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of d in reg INT1_DURATION
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_gen_duration_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_int1_duration_t int1_duration;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT1_DURATION,
(uint8_t *)&int1_duration, 1);
*val = (uint8_t)int1_duration.d;
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Interrupts_generator_2
* @brief This section group all the functions that manage the second
* interrupts generator
* @{
*
*/
/**
* @brief Interrupt generator 2 configuration register.[set]
*
* @param ctx read / write interface definitions
* @param val registers INT2_CFG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_gen_conf_set(stmdev_ctx_t *ctx,
lis2de12_int2_cfg_t *val)
{
int32_t ret;
ret = lis2de12_write_reg(ctx, LIS2DE12_INT2_CFG, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Interrupt generator 2 configuration register.[get]
*
* @param ctx read / write interface definitions
* @param val registers INT2_CFG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_gen_conf_get(stmdev_ctx_t *ctx,
lis2de12_int2_cfg_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT2_CFG, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Interrupt generator 2 source register.[get]
*
* @param ctx read / write interface definitions
* @param val registers INT2_SRC
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_gen_source_get(stmdev_ctx_t *ctx,
lis2de12_int2_src_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT2_SRC, (uint8_t *) val, 1);
return ret;
}
/**
* @brief User-defined threshold value for xl interrupt event on
* generator 2.[set]
* LSb = 16mg@2g / 32mg@4g / 62mg@8g / 186mg@16g
*
* @param ctx read / write interface definitions
* @param val change the values of ths in reg INT2_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_gen_threshold_set(stmdev_ctx_t *ctx,
uint8_t val)
{
lis2de12_int2_ths_t int2_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT2_THS, (uint8_t *)&int2_ths, 1);
if (ret == 0)
{
int2_ths.ths = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_INT2_THS, (uint8_t *)&int2_ths, 1);
}
return ret;
}
/**
* @brief User-defined threshold value for xl interrupt event on
* generator 2.[get]
* LSb = 16mg@2g / 32mg@4g / 62mg@8g / 186mg@16g
*
* @param ctx read / write interface definitions
* @param val change the values of ths in reg INT2_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_gen_threshold_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_int2_ths_t int2_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT2_THS, (uint8_t *)&int2_ths, 1);
*val = (uint8_t)int2_ths.ths;
return ret;
}
/**
* @brief The minimum duration (LSb = 1/ODR) of the Interrupt 1 event to be
* recognized .[set]
*
* @param ctx read / write interface definitions
* @param val change the values of d in reg INT2_DURATION
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_gen_duration_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_int2_duration_t int2_duration;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT2_DURATION,
(uint8_t *)&int2_duration, 1);
if (ret == 0)
{
int2_duration.d = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_INT2_DURATION,
(uint8_t *)&int2_duration, 1);
}
return ret;
}
/**
* @brief The minimum duration (LSb = 1/ODR) of the Interrupt 1 event to be
* recognized.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of d in reg INT2_DURATION
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_gen_duration_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_int2_duration_t int2_duration;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_INT2_DURATION,
(uint8_t *)&int2_duration, 1);
*val = (uint8_t)int2_duration.d;
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Interrupt_pins
* @brief This section group all the functions that manage interrupt pins
* @{
*
*/
/**
* @brief High-pass filter on interrupts/tap generator.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of hp in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_int_conf_set(stmdev_ctx_t *ctx,
lis2de12_hp_t val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
if (ret == 0)
{
ctrl_reg2.hp = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
}
return ret;
}
/**
* @brief High-pass filter on interrupts/tap generator.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of hp in reg CTRL_REG2
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_high_pass_int_conf_get(stmdev_ctx_t *ctx,
lis2de12_hp_t *val)
{
lis2de12_ctrl_reg2_t ctrl_reg2;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG2,
(uint8_t *)&ctrl_reg2, 1);
switch (ctrl_reg2.hp)
{
case LIS2DE12_DISC_FROM_INT_GENERATOR:
*val = LIS2DE12_DISC_FROM_INT_GENERATOR;
break;
case LIS2DE12_ON_INT1_GEN:
*val = LIS2DE12_ON_INT1_GEN;
break;
case LIS2DE12_ON_INT2_GEN:
*val = LIS2DE12_ON_INT2_GEN;
break;
case LIS2DE12_ON_TAP_GEN:
*val = LIS2DE12_ON_TAP_GEN;
break;
case LIS2DE12_ON_INT1_INT2_GEN:
*val = LIS2DE12_ON_INT1_INT2_GEN;
break;
case LIS2DE12_ON_INT1_TAP_GEN:
*val = LIS2DE12_ON_INT1_TAP_GEN;
break;
case LIS2DE12_ON_INT2_TAP_GEN:
*val = LIS2DE12_ON_INT2_TAP_GEN;
break;
case LIS2DE12_ON_INT1_INT2_TAP_GEN:
*val = LIS2DE12_ON_INT1_INT2_TAP_GEN;
break;
default:
*val = LIS2DE12_DISC_FROM_INT_GENERATOR;
break;
}
return ret;
}
/**
* @brief Int1 pin routing configuration register.[set]
*
* @param ctx read / write interface definitions
* @param val registers CTRL_REG3
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_pin_int1_config_set(stmdev_ctx_t *ctx,
lis2de12_ctrl_reg3_t *val)
{
int32_t ret;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG3, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Int1 pin routing configuration register.[get]
*
* @param ctx read / write interface definitions
* @param val registers CTRL_REG3
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_pin_int1_config_get(stmdev_ctx_t *ctx,
lis2de12_ctrl_reg3_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG3, (uint8_t *) val, 1);
return ret;
}
/**
* @brief int2_pin_detect_4d: [set] 4D enable: 4D detection is enabled
* on INT2 pin when 6D bit on
* INT2_CFG (34h) is set to 1.
*
* @param ctx read / write interface definitions
* @param val change the values of d4d_int2 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_pin_detect_4d_set(stmdev_ctx_t *ctx,
uint8_t val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
if (ret == 0)
{
ctrl_reg5.d4d_int2 = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
}
return ret;
}
/**
* @brief 4D enable: 4D detection is enabled on INT2 pin when 6D bit on
* INT2_CFG (34h) is set to 1.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of d4d_int2 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_pin_detect_4d_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
*val = (uint8_t)ctrl_reg5.d4d_int2;
return ret;
}
/**
* @brief Latch interrupt request on INT2_SRC (35h) register, with
* INT2_SRC (35h) register cleared by reading INT2_SRC(35h)
* itself.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of lir_int2 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_pin_notification_mode_set(stmdev_ctx_t *ctx,
lis2de12_lir_int2_t val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
if (ret == 0)
{
ctrl_reg5.lir_int2 = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
}
return ret;
}
/**
* @brief Latch interrupt request on INT2_SRC (35h) register, with
* INT2_SRC (35h) register cleared by reading INT2_SRC(35h)
* itself.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of lir_int2 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int2_pin_notification_mode_get(stmdev_ctx_t *ctx,
lis2de12_lir_int2_t *val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
switch (ctrl_reg5.lir_int2)
{
case LIS2DE12_INT2_PULSED:
*val = LIS2DE12_INT2_PULSED;
break;
case LIS2DE12_INT2_LATCHED:
*val = LIS2DE12_INT2_LATCHED;
break;
default:
*val = LIS2DE12_INT2_PULSED;
break;
}
return ret;
}
/**
* @brief 4D enable: 4D detection is enabled on INT1 pin when 6D bit
* on INT1_CFG(30h) is set to 1.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of d4d_int1 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_pin_detect_4d_set(stmdev_ctx_t *ctx,
uint8_t val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
if (ret == 0)
{
ctrl_reg5.d4d_int1 = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
}
return ret;
}
/**
* @brief 4D enable: 4D detection is enabled on INT1 pin when 6D bit on
* INT1_CFG(30h) is set to 1.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of d4d_int1 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_pin_detect_4d_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
*val = (uint8_t)ctrl_reg5.d4d_int1;
return ret;
}
/**
* @brief Latch interrupt request on INT1_SRC (31h), with INT1_SRC(31h)
* register cleared by reading INT1_SRC (31h) itself.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of lir_int1 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_pin_notification_mode_set(stmdev_ctx_t *ctx,
lis2de12_lir_int1_t val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
if (ret == 0)
{
ctrl_reg5.lir_int1 = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
}
return ret;
}
/**
* @brief Latch interrupt request on INT1_SRC (31h), with INT1_SRC(31h)
* register cleared by reading INT1_SRC (31h) itself.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of lir_int1 in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_int1_pin_notification_mode_get(stmdev_ctx_t *ctx,
lis2de12_lir_int1_t *val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
switch (ctrl_reg5.lir_int1)
{
case LIS2DE12_INT1_PULSED:
*val = LIS2DE12_INT1_PULSED;
break;
case LIS2DE12_INT1_LATCHED:
*val = LIS2DE12_INT1_LATCHED;
break;
default:
*val = LIS2DE12_INT1_PULSED;
break;
}
return ret;
}
/**
* @brief Int2 pin routing configuration register.[set]
*
* @param ctx read / write interface definitions
* @param val registers CTRL_REG6
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_pin_int2_config_set(stmdev_ctx_t *ctx,
lis2de12_ctrl_reg6_t *val)
{
int32_t ret;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG6, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Int2 pin routing configuration register.[get]
*
* @param ctx read / write interface definitions
* @param val registers CTRL_REG6
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_pin_int2_config_get(stmdev_ctx_t *ctx,
lis2de12_ctrl_reg6_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG6, (uint8_t *) val, 1);
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Fifo
* @brief This section group all the functions concerning the fifo usage
* @{
*
*/
/**
* @brief FIFO enable.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of fifo_en in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
if (ret == 0)
{
ctrl_reg5.fifo_en = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
}
return ret;
}
/**
* @brief FIFO enable.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of fifo_en in reg CTRL_REG5
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_ctrl_reg5_t ctrl_reg5;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG5,
(uint8_t *)&ctrl_reg5, 1);
*val = (uint8_t)ctrl_reg5.fifo_en;
return ret;
}
/**
* @brief FIFO watermark level selection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of fth in reg FIFO_CTRL_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_watermark_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_fifo_ctrl_reg_t fifo_ctrl_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
if (ret == 0)
{
fifo_ctrl_reg.fth = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
}
return ret;
}
/**
* @brief FIFO watermark level selection.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of fth in reg FIFO_CTRL_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_watermark_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_fifo_ctrl_reg_t fifo_ctrl_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
*val = (uint8_t)fifo_ctrl_reg.fth;
return ret;
}
/**
* @brief Trigger FIFO selection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of tr in reg FIFO_CTRL_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_trigger_event_set(stmdev_ctx_t *ctx,
lis2de12_tr_t val)
{
lis2de12_fifo_ctrl_reg_t fifo_ctrl_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
if (ret == 0)
{
fifo_ctrl_reg.tr = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
}
return ret;
}
/**
* @brief Trigger FIFO selection.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of tr in reg FIFO_CTRL_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_trigger_event_get(stmdev_ctx_t *ctx,
lis2de12_tr_t *val)
{
lis2de12_fifo_ctrl_reg_t fifo_ctrl_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
switch (fifo_ctrl_reg.tr)
{
case LIS2DE12_INT1_GEN:
*val = LIS2DE12_INT1_GEN;
break;
case LIS2DE12_INT2_GEN:
*val = LIS2DE12_INT2_GEN;
break;
default:
*val = LIS2DE12_INT1_GEN;
break;
}
return ret;
}
/**
* @brief FIFO mode selection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of fm in reg FIFO_CTRL_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_mode_set(stmdev_ctx_t *ctx, lis2de12_fm_t val)
{
lis2de12_fifo_ctrl_reg_t fifo_ctrl_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
if (ret == 0)
{
fifo_ctrl_reg.fm = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
}
return ret;
}
/**
* @brief FIFO mode selection.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of fm in reg FIFO_CTRL_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_mode_get(stmdev_ctx_t *ctx, lis2de12_fm_t *val)
{
lis2de12_fifo_ctrl_reg_t fifo_ctrl_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_CTRL_REG,
(uint8_t *)&fifo_ctrl_reg, 1);
switch (fifo_ctrl_reg.fm)
{
case LIS2DE12_BYPASS_MODE:
*val = LIS2DE12_BYPASS_MODE;
break;
case LIS2DE12_FIFO_MODE:
*val = LIS2DE12_FIFO_MODE;
break;
case LIS2DE12_DYNAMIC_STREAM_MODE:
*val = LIS2DE12_DYNAMIC_STREAM_MODE;
break;
case LIS2DE12_STREAM_TO_FIFO_MODE:
*val = LIS2DE12_STREAM_TO_FIFO_MODE;
break;
default:
*val = LIS2DE12_BYPASS_MODE;
break;
}
return ret;
}
/**
* @brief FIFO status register.[get]
*
* @param ctx read / write interface definitions
* @param val registers FIFO_SRC_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_status_get(stmdev_ctx_t *ctx,
lis2de12_fifo_src_reg_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_SRC_REG, (uint8_t *) val, 1);
return ret;
}
/**
* @brief FIFO stored data level.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of fss in reg FIFO_SRC_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_data_level_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_fifo_src_reg_t fifo_src_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_SRC_REG,
(uint8_t *)&fifo_src_reg, 1);
*val = (uint8_t)fifo_src_reg.fss;
return ret;
}
/**
* @brief Empty FIFO status flag.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of empty in reg FIFO_SRC_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_empty_flag_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_fifo_src_reg_t fifo_src_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_SRC_REG,
(uint8_t *)&fifo_src_reg, 1);
*val = (uint8_t)fifo_src_reg.empty;
return ret;
}
/**
* @brief FIFO overrun status flag.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of ovrn_fifo in reg FIFO_SRC_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_ovr_flag_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_fifo_src_reg_t fifo_src_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_SRC_REG,
(uint8_t *)&fifo_src_reg, 1);
*val = (uint8_t)fifo_src_reg.ovrn_fifo;
return ret;
}
/**
* @brief FIFO watermark status.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of wtm in reg FIFO_SRC_REG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_fifo_fth_flag_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_fifo_src_reg_t fifo_src_reg;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_FIFO_SRC_REG,
(uint8_t *)&fifo_src_reg, 1);
*val = (uint8_t)fifo_src_reg.wtm;
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Tap_generator
* @brief This section group all the functions that manage the tap and
* double tap event generation
* @{
*
*/
/**
* @brief Tap/Double Tap generator configuration register.[set]
*
* @param ctx read / write interface definitions
* @param val registers CLICK_CFG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_tap_conf_set(stmdev_ctx_t *ctx,
lis2de12_click_cfg_t *val)
{
int32_t ret;
ret = lis2de12_write_reg(ctx, LIS2DE12_CLICK_CFG, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Tap/Double Tap generator configuration register.[get]
*
* @param ctx read / write interface definitions
* @param val registers CLICK_CFG
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_tap_conf_get(stmdev_ctx_t *ctx,
lis2de12_click_cfg_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CLICK_CFG, (uint8_t *) val, 1);
return ret;
}
/**
* @brief Tap/Double Tap generator source register.[get]
*
* @param ctx read / write interface definitions
* @param val registers CLICK_SRC
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_tap_source_get(stmdev_ctx_t *ctx,
lis2de12_click_src_t *val)
{
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CLICK_SRC, (uint8_t *) val, 1);
return ret;
}
/**
* @brief User-defined threshold value for Tap/Double Tap event.[set]
* 1 LSB = full scale/128
*
* @param ctx read / write interface definitions
* @param val change the values of ths in reg CLICK_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_tap_threshold_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_click_ths_t click_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CLICK_THS,
(uint8_t *)&click_ths, 1);
if (ret == 0)
{
click_ths.ths = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CLICK_THS,
(uint8_t *)&click_ths, 1);
}
return ret;
}
/**
* @brief User-defined threshold value for Tap/Double Tap event.[get]
* 1 LSB = full scale/128
*
* @param ctx read / write interface definitions
* @param val change the values of ths in reg CLICK_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_tap_threshold_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_click_ths_t click_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CLICK_THS,
(uint8_t *)&click_ths, 1);
*val = (uint8_t)click_ths.ths;
return ret;
}
/**
* @brief If the LIR_Click bit is not set, the interrupt is kept high
* for the duration of the latency window.
* If the LIR_Click bit is set, the interrupt is kept high until the
* CLICK_SRC(39h) register is read.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of lir_click in reg CLICK_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_tap_notification_mode_set(stmdev_ctx_t *ctx,
lis2de12_lir_click_t val)
{
lis2de12_click_ths_t click_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CLICK_THS,
(uint8_t *)&click_ths, 1);
if (ret == 0)
{
click_ths.lir_click = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CLICK_THS,
(uint8_t *)&click_ths, 1);
}
return ret;
}
/**
* @brief If the LIR_Click bit is not set, the interrupt is kept high
* for the duration of the latency window.
* If the LIR_Click bit is set, the interrupt is kept high until the
* CLICK_SRC(39h) register is read.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of lir_click in reg CLICK_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_tap_notification_mode_get(stmdev_ctx_t *ctx,
lis2de12_lir_click_t *val)
{
lis2de12_click_ths_t click_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CLICK_THS,
(uint8_t *)&click_ths, 1);
switch (click_ths.lir_click)
{
case LIS2DE12_TAP_PULSED:
*val = LIS2DE12_TAP_PULSED;
break;
case LIS2DE12_TAP_LATCHED:
*val = LIS2DE12_TAP_LATCHED;
break;
default:
*val = LIS2DE12_TAP_PULSED;
break;
}
return ret;
}
/**
* @brief The maximum time (1 LSB = 1/ODR) interval that can elapse
* between the start of the click-detection procedure and when the
* acceleration falls back below the threshold.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of tli in reg TIME_LIMIT
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_shock_dur_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_time_limit_t time_limit;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TIME_LIMIT,
(uint8_t *)&time_limit, 1);
if (ret == 0)
{
time_limit.tli = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_TIME_LIMIT,
(uint8_t *)&time_limit, 1);
}
return ret;
}
/**
* @brief The maximum time (1 LSB = 1/ODR) interval that can elapse between
* the start of the click-detection procedure and when the
* acceleration falls back below the threshold.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of tli in reg TIME_LIMIT
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_shock_dur_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_time_limit_t time_limit;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TIME_LIMIT,
(uint8_t *)&time_limit, 1);
*val = (uint8_t)time_limit.tli;
return ret;
}
/**
* @brief The time (1 LSB = 1/ODR) interval that starts after the first
* click detection where the click-detection procedure is
* disabled, in cases where the device is configured for
* double-click detection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of tla in reg TIME_LATENCY
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_quiet_dur_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_time_latency_t time_latency;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TIME_LATENCY,
(uint8_t *)&time_latency, 1);
if (ret == 0)
{
time_latency.tla = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_TIME_LATENCY,
(uint8_t *)&time_latency, 1);
}
return ret;
}
/**
* @brief The time (1 LSB = 1/ODR) interval that starts after the first
* click detection where the click-detection procedure is
* disabled, in cases where the device is configured for
* double-click detection.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of tla in reg TIME_LATENCY
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_quiet_dur_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_time_latency_t time_latency;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TIME_LATENCY,
(uint8_t *)&time_latency, 1);
*val = (uint8_t)time_latency.tla;
return ret;
}
/**
* @brief The maximum interval of time (1 LSB = 1/ODR) that can elapse
* after the end of the latency interval in which the click-detection
* procedure can start, in cases where the device is configured
* for double-click detection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of tw in reg TIME_WINDOW
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_double_tap_timeout_set(stmdev_ctx_t *ctx,
uint8_t val)
{
lis2de12_time_window_t time_window;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TIME_WINDOW,
(uint8_t *)&time_window, 1);
if (ret == 0)
{
time_window.tw = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_TIME_WINDOW,
(uint8_t *)&time_window, 1);
}
return ret;
}
/**
* @brief The maximum interval of time (1 LSB = 1/ODR) that can elapse
* after the end of the latency interval in which the
* click-detection procedure can start, in cases where the device
* is configured for double-click detection.[get]
*
* @param ctx read / write interface definitions
* @param val change the values of tw in reg TIME_WINDOW
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_double_tap_timeout_get(stmdev_ctx_t *ctx,
uint8_t *val)
{
lis2de12_time_window_t time_window;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_TIME_WINDOW,
(uint8_t *)&time_window, 1);
*val = (uint8_t)time_window.tw;
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Activity_inactivity
* @brief This section group all the functions concerning activity
* inactivity functionality
* @{
*
*/
/**
* @brief Sleep-to-wake, return-to-sleep activation threshold in
* low-power mode.[set]
* 1 LSb = 16mg@2g / 32mg@4g / 62mg@8g / 186mg@16g
*
* @param ctx read / write interface definitions
* @param val change the values of acth in reg ACT_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_act_threshold_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_act_ths_t act_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_ACT_THS, (uint8_t *)&act_ths, 1);
if (ret == 0)
{
act_ths.acth = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_ACT_THS, (uint8_t *)&act_ths, 1);
}
return ret;
}
/**
* @brief Sleep-to-wake, return-to-sleep activation threshold in low-power
* mode.[get]
* 1 LSb = 16mg@2g / 32mg@4g / 62mg@8g / 186mg@16g
*
* @param ctx read / write interface definitions
* @param val change the values of acth in reg ACT_THS
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_act_threshold_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_act_ths_t act_ths;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_ACT_THS, (uint8_t *)&act_ths, 1);
*val = (uint8_t)act_ths.acth;
return ret;
}
/**
* @brief Sleep-to-wake, return-to-sleep.[set]
* duration = (8*1[LSb]+1)/ODR
*
* @param ctx read / write interface definitions
* @param val change the values of actd in reg ACT_DUR
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_act_timeout_set(stmdev_ctx_t *ctx, uint8_t val)
{
lis2de12_act_dur_t act_dur;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_ACT_DUR, (uint8_t *)&act_dur, 1);
if (ret == 0)
{
act_dur.actd = val;
ret = lis2de12_write_reg(ctx, LIS2DE12_ACT_DUR, (uint8_t *)&act_dur, 1);
}
return ret;
}
/**
* @brief Sleep-to-wake, return-to-sleep.[get]
* duration = (8*1[LSb]+1)/ODR
*
* @param ctx read / write interface definitions
* @param val change the values of actd in reg ACT_DUR
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_act_timeout_get(stmdev_ctx_t *ctx, uint8_t *val)
{
lis2de12_act_dur_t act_dur;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_ACT_DUR, (uint8_t *)&act_dur, 1);
*val = (uint8_t)act_dur.actd;
return ret;
}
/**
* @}
*
*/
/**
* @defgroup LIS2DE12_Serial_interface
* @brief This section group all the functions concerning serial
* interface management
* @{
*
*/
/**
* @brief Connect/Disconnect SDO/SA0 internal pull-up.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of sdo_pu_disc in reg CTRL_REG0
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_pin_sdo_sa0_mode_set(stmdev_ctx_t *ctx,
lis2de12_sdo_pu_disc_t val)
{
lis2de12_ctrl_reg0_t ctrl_reg0;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG0,
(uint8_t *)&ctrl_reg0, 1);
if (ret == 0)
{
ctrl_reg0.sdo_pu_disc = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG0,
(uint8_t *)&ctrl_reg0, 1);
}
return ret;
}
/**
* @brief Connect/Disconnect SDO/SA0 internal pull-up.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of sdo_pu_disc in reg CTRL_REG0
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_pin_sdo_sa0_mode_get(stmdev_ctx_t *ctx,
lis2de12_sdo_pu_disc_t *val)
{
lis2de12_ctrl_reg0_t ctrl_reg0;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG0,
(uint8_t *)&ctrl_reg0, 1);
switch (ctrl_reg0.sdo_pu_disc)
{
case LIS2DE12_PULL_UP_DISCONNECT:
*val = LIS2DE12_PULL_UP_DISCONNECT;
break;
case LIS2DE12_PULL_UP_CONNECT:
*val = LIS2DE12_PULL_UP_CONNECT;
break;
default:
*val = LIS2DE12_PULL_UP_DISCONNECT;
break;
}
return ret;
}
/**
* @brief SPI Serial Interface Mode selection.[set]
*
* @param ctx read / write interface definitions
* @param val change the values of sim in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_spi_mode_set(stmdev_ctx_t *ctx, lis2de12_sim_t val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
if (ret == 0)
{
ctrl_reg4.sim = (uint8_t)val;
ret = lis2de12_write_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
}
return ret;
}
/**
* @brief SPI Serial Interface Mode selection.[get]
*
* @param ctx read / write interface definitions
* @param val Get the values of sim in reg CTRL_REG4
* @retval interface status (MANDATORY: return 0 -> no Error)
*
*/
int32_t lis2de12_spi_mode_get(stmdev_ctx_t *ctx, lis2de12_sim_t *val)
{
lis2de12_ctrl_reg4_t ctrl_reg4;
int32_t ret;
ret = lis2de12_read_reg(ctx, LIS2DE12_CTRL_REG4,
(uint8_t *)&ctrl_reg4, 1);
switch (ctrl_reg4.sim)
{
case LIS2DE12_SPI_4_WIRE:
*val = LIS2DE12_SPI_4_WIRE;
break;
case LIS2DE12_SPI_3_WIRE:
*val = LIS2DE12_SPI_3_WIRE;
break;
default:
*val = LIS2DE12_SPI_4_WIRE;
break;
}
return ret;
}
/**
* @}
*
*/
/**
* @}
*
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 2.296875 | 2 |
2024-11-18T21:16:02.945211+00:00
| 2021-01-02T02:11:39 |
f2429782ca7d6534504072b4d24a026c07180e7d
|
{
"blob_id": "f2429782ca7d6534504072b4d24a026c07180e7d",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-02T02:11:39",
"content_id": "c9d29ce9be20f7dc331500b8772d453460130241",
"detected_licenses": [
"MIT"
],
"directory_id": "abf432d562312760cfd28a97c43b9e1f97ab64f4",
"extension": "c",
"filename": "12.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 154999333,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 358,
"license": "MIT",
"license_type": "permissive",
"path": "/C/12.c",
"provenance": "stackv2-0112.json.gz:22775",
"repo_name": "MilenaCarecho/LogicaDeProgramacao",
"revision_date": "2021-01-02T02:11:39",
"revision_id": "d48ec002a788b2032845a0dd8e7e88f06e46ac17",
"snapshot_id": "8e46dae6e74d21397df9878ad06ff2c2c4dce7d2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MilenaCarecho/LogicaDeProgramacao/d48ec002a788b2032845a0dd8e7e88f06e46ac17/C/12.c",
"visit_date": "2023-02-10T05:31:51.486842"
}
|
stackv2
|
/** Sejam 𝑎 e 𝑏 os catetos de um triângulo, onde a hipotenusa é obtida pela equação:
ℎ𝑖𝑝𝑜𝑡𝑒𝑛𝑢𝑠𝑎 = √𝑎
2 + 𝑏
2. Faça um programa que receba os valores de 𝑎 e 𝑏 e encontre o
valor da hipotenusa através da equação. Imprima no final o resultado dessa operação. **/
#include <stdio.h>
int main () {
}
| 2.609375 | 3 |
2024-11-18T21:29:37.174150+00:00
| 2018-08-04T15:57:25 |
467ef3364e4c363448b4ef8568dcc5680f26b456
|
{
"blob_id": "467ef3364e4c363448b4ef8568dcc5680f26b456",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-04T15:57:25",
"content_id": "5da36ae1b0471f0c98cdbee83e8c1d3db23665ec",
"detected_licenses": [
"MIT"
],
"directory_id": "7e8742deb51479d56c61b1e4d1b60adf2b134423",
"extension": "c",
"filename": "example.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 135796483,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3353,
"license": "MIT",
"license_type": "permissive",
"path": "/example.c",
"provenance": "stackv2-0112.json.gz:174621",
"repo_name": "polycone/rtems-i2c-max961x-driver",
"revision_date": "2018-08-04T15:57:25",
"revision_id": "e7bc77329e0730cf52bf6641b3afbe2f9b86cc66",
"snapshot_id": "b094581022c3a7fd7815aaafe99d7d5d5a21d55a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/polycone/rtems-i2c-max961x-driver/e7bc77329e0730cf52bf6641b3afbe2f9b86cc66/example.c",
"visit_date": "2020-03-19T04:07:06.526509"
}
|
stackv2
|
#include <rtems.h>
#define CONFIGURE_INIT
#include <bsp.h>
rtems_task Init( rtems_task_argument argument);
#define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER
#define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER
#define CONFIGURE_APPLICATION_NEEDS_NULL_DRIVER
#define CONFIGURE_MAXIMUM_TASKS 8
#define CONFIGURE_RTEMS_INIT_TASKS_TABLE
#define CONFIGURE_EXTRA_TASK_STACKS (3 * RTEMS_MINIMUM_STACK_SIZE)
#define CONFIGURE_LIBIO_MAXIMUM_FILE_DESCRIPTORS 16
#define CONFIGURE_INIT_TASK_PRIORITY 100
#define CONFIGURE_USE_IMFS_AS_BASE_FILESYSTEM
#include <rtems/confdefs.h>
#define CONFIGURE_DRIVER_AMBAPP_GAISLER_GPTIMER
#define CONFIGURE_DRIVER_AMBAPP_GAISLER_APBUART
#define CONFIGURE_DRIVER_AMBAPP_GAISLER_I2CMST
#include <drvmgr/drvmgr_confdefs.h>
#include <rtems/libi2c.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <i2cmst.h>
#include "config.c"
#include "i2c-max961x.h"
#define CIRCUIT_BRIDGE_RESISTANCE 0.02
#define MAX961X_DEVICE_PATH "/dev/i2c1.max961x"
rtems_task measure_current(rtems_task_argument argument);
rtems_id task_id;
rtems_name task_name;
rtems_task Init(rtems_task_argument arg)
{
int status = 0;
system_init();
printf("******** Starting MAX9611 Current Measurement ********\n");
status = rtems_libi2c_register_drv("max961x", i2c_max961x_driver_descriptor, 0, MAX961X_ADDRESS);
if (status < 0) {
printf("ERROR: Could not register MAX961x driver\n");
exit(0);
}
printf("driver registered successfully\n");
task_name = rtems_build_name('C', 'U', 'R', 'M');
rtems_task_create(task_name, 1, RTEMS_MINIMUM_STACK_SIZE * 2,
RTEMS_DEFAULT_MODES, RTEMS_DEFAULT_ATTRIBUTES, &task_id);
rtems_task_start(task_id, measure_current, 1);
rtems_task_delete(RTEMS_SELF);
}
int verbose_open(const char *path, int flags)
{
int fd = open(path, flags);
if (fd < 0)
printf("Could not open %s: %s\n", path, strerror(errno));
return fd;
}
float get_circuit_current(int fd)
{
int csa_level = ioctl(fd, IOCTL_MAX961X_CSA_DATA);
return csa_level * MAX961X_LSB_STEP_1X_GAIN / CIRCUIT_BRIDGE_RESISTANCE;
}
float get_circuit_voltage(int fd)
{
int rsp_level = ioctl(fd, IOCTL_MAX961X_RSP_DATA);
return rsp_level * MAX961X_VOLTAGE_LSB_STEP;
}
float get_circuit_temp(int fd)
{
int temp_level = ioctl(fd, IOCTL_MAX961X_TEMP_DATA);
float temp = (temp_level & 0xFF) * MAX961X_TEMP_ACCURACY;
if (temp_level & 0x100)
temp = -temp;
return temp;
}
rtems_task measure_current(rtems_task_argument unused)
{
int max961x_device;
float current, voltage, temp;
printf("[measure_current] Started\n");
max961x_device = verbose_open(MAX961X_DEVICE_PATH, O_RDWR);
if (max961x_device < 0)
exit(1);
ioctl(max961x_device, IOCTL_MAX961X_CONTROL, 0x0700);
printf("\tCurrent\t\tVoltage\t\tTemp\n");
while (true)
{
current = get_circuit_current(max961x_device);
voltage = get_circuit_voltage(max961x_device);
temp = get_circuit_temp(max961x_device);
usleep(1000000);
printf("\t%.3f A\t\t%.3f V\t\t%.3f %cC\n", current, voltage, temp, 248);
}
}
| 2.1875 | 2 |
2024-11-18T21:29:38.160425+00:00
| 2020-12-10T17:50:07 |
8b3f1a53194f0fda4f119b0d9e67e5808e3e94bf
|
{
"blob_id": "8b3f1a53194f0fda4f119b0d9e67e5808e3e94bf",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-10T17:50:07",
"content_id": "8b6840cf2894371318aa7292faf37e6f7916ed63",
"detected_licenses": [
"MIT"
],
"directory_id": "a7ab63234bd218d38956dced06f71c0d3defd7ab",
"extension": "c",
"filename": "solution.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 293273460,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 177,
"license": "MIT",
"license_type": "permissive",
"path": "/problems/number_of_steps_to_reduce_a_number_to_zero/solution.c",
"provenance": "stackv2-0112.json.gz:175139",
"repo_name": "yogeshsingh01/LeetCode",
"revision_date": "2020-12-10T17:50:07",
"revision_id": "606b608fccae81fc1dfd7a0283e1739c1e6dfed1",
"snapshot_id": "69fd7f4a5449b4b84d84d347c3ae7541acd1c4b6",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/yogeshsingh01/LeetCode/606b608fccae81fc1dfd7a0283e1739c1e6dfed1/problems/number_of_steps_to_reduce_a_number_to_zero/solution.c",
"visit_date": "2023-02-03T07:24:26.567259"
}
|
stackv2
|
int numberOfSteps (int num){
int steps = 0;
while(num)
{
num = (num%2) ? num -1 : num / 2;
steps++;
}
return steps;
}
| 3.078125 | 3 |
2024-11-18T21:29:38.343510+00:00
| 2019-05-02T20:45:46 |
8ebf94e0d7cf28529c6d7eb20e60c04c51b86fab
|
{
"blob_id": "8ebf94e0d7cf28529c6d7eb20e60c04c51b86fab",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-02T20:45:46",
"content_id": "83e5eba6f210789bf453176482288c8571c1dba9",
"detected_licenses": [
"MIT"
],
"directory_id": "2f898bb332097d11f321186207e94f6d156587f3",
"extension": "c",
"filename": "img.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 102375690,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1479,
"license": "MIT",
"license_type": "permissive",
"path": "/informatica/class8/img.c",
"provenance": "stackv2-0112.json.gz:175397",
"repo_name": "miltonsarria/teaching",
"revision_date": "2019-05-02T20:45:46",
"revision_id": "7a2b4e6c74d9f11562dfe34722e607ca081c1681",
"snapshot_id": "ad2d07e9cfbfcf272c4b2fbef47321eae765a605",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/miltonsarria/teaching/7a2b4e6c74d9f11562dfe34722e607ca081c1681/informatica/class8/img.c",
"visit_date": "2022-01-05T05:58:13.163155"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "bmp_milton.h"
#define ext ".bmp"
#define ext2 ".txt"
int main()
{
int fc[3],s,c,op,c1,l1,tm;
float fil[13][13];
int brillo,contraste,i,j;
char nombre1[12],nombre2[12],nombrea[12];
//-----------------memoria dinamica
// filas y columnas
int m = 1000,n = 1000;
//long int **mat; //matriz para la imagen
int **mat = NULL;
mat = Matrix_Alloc(mat, m, n);
//-----------------------------------
printf("ingrese archivo:");
scanf("%s",nombre1);
//juntar(nombre1,ext);
strcat(nombre1,ext);
c=bmp256(nombre1,mat,fc); //fc[fil,col,numero de ceros]
if(c==0)
{
printf("no se pudo abrir el archivo!! \n");
getchar();
return 0;
}
///
printf("ingrese archivo destino: ");
scanf("%s",nombre2);
//modificar para que nombre 1 sea diferente de nombre2
//operaciones a relizar
printf("ingrese el umbral: ");
int umbral;
scanf("%d",&umbral);
for (i=0;i<fc[0];i++)
{
for(j=0;j<fc[1];j++)
{
if(mat[i][j]>umbral) mat[i][j]=255;
else mat[i][j]=0;
}
}
///////////////////////////////////////////////////////////////////////////////
l1=strlen(nombre2);
for(i=0;i<l1;i++)
nombrea[i]=nombre2[i];
strcat(nombre2,ext);
//juntar(nombre2,ext);
s=salvar(nombre1,nombre2,mat,fc);
printf("Finalizado, press. ENTER.....");
getchar();
Matrix_Free(mat,m);
return 1;
}
| 2.625 | 3 |
2024-11-18T21:29:39.258595+00:00
| 2019-09-07T09:49:53 |
b7b8c02d26fa013dbeb675d89a85d56281358003
|
{
"blob_id": "b7b8c02d26fa013dbeb675d89a85d56281358003",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-07T09:49:53",
"content_id": "159077ca1d25bbd1c7d5488c476fb0e48c96e95c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6474aec132c5511fb7b47e2a8d077d67dfa92aa5",
"extension": "c",
"filename": "lianbiao.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 189165195,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2908,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lianbiao.c",
"provenance": "stackv2-0112.json.gz:175783",
"repo_name": "seeways/DataStructureDemo",
"revision_date": "2019-09-07T09:49:53",
"revision_id": "acaf9a386293dab363d88feaeeea44a16b061f80",
"snapshot_id": "4f2d1201ab518bfe7ea8555dab3d759aadfaede0",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/seeways/DataStructureDemo/acaf9a386293dab363d88feaeeea44a16b061f80/lianbiao.c",
"visit_date": "2020-05-29T13:30:30.009240"
}
|
stackv2
|
#include "lianbiao.h"
/*
链表
*/
link* lianbiaoInitLink() {
// no head pointer
//link* p = NULL; // create head pointer
//link* temp = (link*)malloc(sizeof(link));// create firstNode
//// init firstNode
//temp->elem = 1;
//temp->next = NULL;
//p = temp;
//// create other node
//for (int i = 2; i < 6; i++)
//{
// link* a = (link*)malloc(sizeof(link));
// a->elem = i;
// a->next = NULL;
// // create logical relationships using temp node and a node
// temp->next = a;
// // temp pointer's last node to new link every time, that is the 'a' node , so temp=a also right.
// temp = temp->next;
//}
// have head pointer
link* p = (link*)malloc(sizeof(link));// create a head node
link* temp = p;// state a pointer to head node
for (int i = 1; i < 5; i++) {
link* a = (link*)malloc(sizeof(link));
a->elem = i;
a->next = NULL;
temp->next = a;
temp = temp->next;
}
return p;
}
//p为原链表,elem表示新数据元素,pos表示新元素要插入的位置
link* lianbiaoInsertElem(link* p, int elem, int pos) {
link* temp = p;//创建临时结点temp
//首先找到要插入位置的上一个结点
for (int i = 0; i < pos; i++) {
if (temp == NULL) {
printf("插入位置无效\n");
return p;
}
temp = temp->next;
}
//创建插入结点c
link* c = (link*)malloc(sizeof(link));
c->elem = elem;
//向链表中插入结点
c->next = temp->next;
temp->next = c;
return p;
}
//p为原链表,pos为要删除元素的值
link* lianbiaoDelElem(link* p, int pos) {
link* temp = p;
//temp指向被删除结点的上一个结点
for (int i = 0; i < pos; i++) {
temp = temp->next;
}
link* del = temp->next;//单独设置一个指针指向被删除结点,以防丢失
temp->next = temp->next->next;//删除某个结点的方法就是更改前一个结点的指针域
free(del);//手动释放该结点,防止内存泄漏
return p;
}
//p为原链表,elem表示被查找元素、
int lianbiaoSelectElem(link* p, int elem) {
//新建一个指针t,初始化为头指针 p
link* t = p;
int i = 0;
//由于头节点的存在,因此while中的判断为t->next
while (t->next) {
t = t->next;
if (t->elem == elem) {
return i;
}
i++;
}
//程序执行至此处,表示查找失败
return -1;
}
//更新函数,其中,add 表示更改结点在链表中的位置,newElem 为新的数据域的值
link* lianbiaoAmendElem(link* p, int pos, int newElem) {
link* temp = p;
temp = temp->next;//在遍历之前,temp指向首元结点
//遍历到被删除结点
for (int i = 0; i < pos; i++) {
temp = temp->next;
}
temp->elem = newElem;
return p;
}
void lianbiaoDisplay(link* p) {
link* temp = p;//将temp指针重新指向头结点
//只要temp指针指向的结点的next不是Null,就执行输出语句。
while (temp->next) {
temp = temp->next;
printf("%d ", temp->elem);
}
printf("\n");
}
| 3.71875 | 4 |
2024-11-18T21:29:43.748885+00:00
| 2019-08-29T12:30:16 |
e5a2ab74abb6eeb87789dcd2d87759c875d047da
|
{
"blob_id": "e5a2ab74abb6eeb87789dcd2d87759c875d047da",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-29T12:30:16",
"content_id": "271bfadb5847530a561731a2d6ebf7ee1a938bcb",
"detected_licenses": [
"MIT"
],
"directory_id": "f422b464dd2c63a90c05b9936ae4800159d304b9",
"extension": "h",
"filename": "po.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 204589545,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3774,
"license": "MIT",
"license_type": "permissive",
"path": "/firmware/msp430g2553/po.h",
"provenance": "stackv2-0112.json.gz:176300",
"repo_name": "danilodsp/Home-Automation",
"revision_date": "2019-08-29T12:30:16",
"revision_id": "f5e66fba4622c39e604e14e736d378ceed7fad78",
"snapshot_id": "f258be6e5cbc6023a4c055684f0ff7dac0826d53",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/danilodsp/Home-Automation/f5e66fba4622c39e604e14e736d378ceed7fad78/firmware/msp430g2553/po.h",
"visit_date": "2020-07-11T15:55:29.419635"
}
|
stackv2
|
/*
* po.h
*
* Created on: 05/06/2012
* Author: Danilo
*/
#ifndef PO_H_
#define PO_H_
// Parâmetros fixos
#define tipoSensor 0x01 // Categoria do sensor
#define tipoAtuador 0x00 // Categoria do atuador
#define timeout 5000 // Timeout de espera dos estados de RX
#define initTime 5000 // Delay para inciar os estados (ms)
#define nSample 64 // Número de amostras para cálculo da média (valor máximo recomendado = 64)
// Flags
#define flagDebug (0x0001)
#define flagReceived (0x0002)
#define flagPeriodo (0x0004)
#define flagConfigSensor (0x0008)
#define flagConfigAtuador (0x0010)
#define flagError (0x0020)
#define flagAlarme (0x0040)
#define flagChecksum (0x0080)
#define flagConfig (0x0100)
// Verificar flags
#define fDebug (flags&flagDebug)
#define fReceived (flags&flagReceived)
#define fPeriodo (flags&flagPeriodo)
#define fConfigSensor (flags&flagConfigSensor)
#define fConfigAtuador (flags&flagConfigAtuador)
#define fError (flags&flagError)
#define fAlarme (flags&flagAlarme)
#define fChecksum (flags&flagChecksum)
#define fConfig (flags&flagConfig)
// LEDs
#define LED1 P1OUT|=BIT0
#define LED2 P1OUT|=BIT6
#define xLED1 P1OUT^=BIT0
#define xLED2 P1OUT^=BIT6
#define dLED1 P1OUT&=~BIT0
#define dLED2 P1OUT&=~BIT6
// Error
#define ERROR_SEM_TIPO (0x0001) // Firmware sem tipoSensor nem tipoAtuador cadastrado
#define ADDRESS_NOT_FOUND (0x0002) // Address Not Found Status de um frame type 8B
#define ERROR_FRAME (0x0003) // Erro no frame recebido
#define ERROR_COMMAND (0x0004) // Erro por receber comando errado (Ex: um comando 0x02 quando deveria ser um 0x04)
#include "halatuador.h"
#include "MdE.h"
#include "config.h" // Arquivos de configuração da camada HAL !!
#include <msp430g2553.h>
void init(); // Inicialização das variaveis
void lerMem(); // Ler memória flash
char configurarAddress(); // Envia frame configurarAddress do protocolo, retorna 0 se obter um verificarStatusEnvio com sucesso
char armazenandoID(); // Armazena o ID sensor e ID atuador recebido do módulo central, retorna diferente de 0 caso o checksum do frame recebido esteja errado
char configurarIS();
void configurarSensor(); // Configura os parâmetros do sensor
void configurarPeriodo(); // Configurar o periodo do xBee para sleep mode
void medicaoPeriodica(); // Envia as medições em um certo período
char enviarMedicao(int valorMedido); // Envia por UART resultado das medicoes
void calcularMedia(); // Calcula media dos resultados das medicoes
char verificarStatusEnvio(unsigned int comando); // Verifica os frames de status de envio (8B), retorna 0 se houve sucesso no envio
unsigned char checksum(unsigned char *frameT); // Calcula o checksum de um frame (frameT) com número de bytes igual a qtd
unsigned char checksumP(unsigned char *frameT, int posIni, int posFin); // Calcula o checksum com a POsição do byte inicial e final
void debug(unsigned char *frameT); // Envia um frame (frameT) para a UART
void timer(int ms); // Esse timer também desliga a CPU, somente retornando ao acabar o valor ms
void timer_us(int us); // Timer em microsegundos
void configurarAtuador(); // Configura os parâmetros do atuador
void atuar(); // Comando atuar
char waitReceive(); // Esperar o flagReceived, retorna 1 se recebeu dados na serial e 0 se não recebeu nada
void receive(); // Recebe dados da UART (frameRx)
void send(); // Envia dados pela UART (frameTx)
char verificarChecksum(); // Verifica o checksum, retornando 0 se houve sucesso
void waitTimeout();
void erro(int erroValor); // Atribuir erro
//void PO_emitirErro(); // Emite por um LED o erro
#endif /* PO_H_ */
| 2.25 | 2 |
2024-11-18T21:29:44.119538+00:00
| 2021-03-22T18:20:25 |
83101f43af429dcd525d615924a807d0ecd822d4
|
{
"blob_id": "83101f43af429dcd525d615924a807d0ecd822d4",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-22T20:05:11",
"content_id": "2cc57f4132a07260aa5af13ae0465170f7b3c98d",
"detected_licenses": [
"MIT"
],
"directory_id": "84aae6f97f520e1d9161c6d3c0b46c6049cbbe1e",
"extension": "h",
"filename": "text.h",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 43848100,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1840,
"license": "MIT",
"license_type": "permissive",
"path": "/SNES_Jukebox/text.h",
"provenance": "stackv2-0112.json.gz:176429",
"repo_name": "Moonspine/snes-jukebox",
"revision_date": "2021-03-22T18:20:25",
"revision_id": "b3c2f79bc12d43202076783ea713d6c91c86d71f",
"snapshot_id": "3a137b47e568d23146626e53d9791e89a8ab62da",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/Moonspine/snes-jukebox/b3c2f79bc12d43202076783ea713d6c91c86d71f/SNES_Jukebox/text.h",
"visit_date": "2022-07-24T13:36:32.885463"
}
|
stackv2
|
#ifndef TEXT_H
#define TEXT_H
#define MAX_PGM_TEXT_LENGTH 21
// BRR Streaming
static PROGMEM const char TEXT_UPLOADING_LOADER[] = "Upoading loader...";
static PROGMEM const char TEXT_LOADER_UPLOADED[] = "Loader uploaded!";
static PROGMEM const char TEXT_STREAMING[] = "Streaming:";
static PROGMEM const char TEXT_PRESS_B_TO_STOP[] = "Press 'B' to stop";
static PROGMEM const char TEXT_PRESS_A_TO_PAUSE[] = "Press 'A' to pause";
static PROGMEM const char TEXT_PRESS_A_TO_UNPAUSE[] = "Press 'A' to unpause";
static PROGMEM const char TEXT_PRESS_X_TO_TOGGLE_LOOP[] = "'X' to toggle loop";
static PROGMEM const char TEXT_PRESS_LEFT_RIGHT_TO_SEEK[] = "Press < or > to seek";
static PROGMEM const char TEXT_MONO[] = "Monaural";
static PROGMEM const char TEXT_STEREO[] = "Stereo";
// SPC loading
static PROGMEM const char TEXT_SELECT_FILE[] = "-- Select SPC, BRR --";
static PROGMEM const char TEXT_LOADING_SPC[] = "Loading SPC:";
static PROGMEM const char TEXT_SONG[] = "Song:";
static PROGMEM const char TEXT_GAME[] = "Game:";
static PROGMEM const char TEXT_COMPOSER[] = "Composer:";
static PROGMEM const char TEXT_UNKNOWN[] = "Unknown:";
// Port write menu
static PROGMEM const char TEXT_PORT_WRITE_MENU[] = "- Port write menu -";
static PROGMEM const char TEXT_PORT_NUMBERS[] = "Port# 0 1 2 3";
static PROGMEM const char TEXT_CURRENTLY_READING[] = "Currently reading";
static PROGMEM const char TEXT_CURRENTLY_WRITTEN[] = "Currently written";
static PROGMEM const char TEXT_CURRENTLY_ORIGINAL[] = "Orig:";
static PROGMEM const char TEXT_CURRENTLY_LAST[] = "Last:";
static PROGMEM const char TEXT_CURRENTLY_WRITE[] = "Write:";
void copyPgmString(const char *source, byte *dest, word charLimit) {
word index = 0;
while ((dest[index++] = pgm_read_byte(source++)) != 0 && index < charLimit) {}
dest[charLimit - 1] = 0;
}
#endif
| 2.234375 | 2 |
2024-11-18T21:29:44.568052+00:00
| 2020-03-23T11:06:13 |
1552a73a245893777d34db991dee04ec55223100
|
{
"blob_id": "1552a73a245893777d34db991dee04ec55223100",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-23T11:06:13",
"content_id": "23531879295cda04534259cf3dcd8ffba57b8385",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e6a9a1fe1c93fd7a465f1f86a669152822840ee3",
"extension": "c",
"filename": "list_pop_front.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 6031189,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 522,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/srcs/list_pop_front.c",
"provenance": "stackv2-0112.json.gz:176818",
"repo_name": "Sbastien/Double-chained-linked-list",
"revision_date": "2020-03-23T11:06:13",
"revision_id": "ff81fce6bdd2655c12ccd8ad00545ade1c2fd710",
"snapshot_id": "c50abf328cc2dc3bfa8ec1b37989260a4fe52186",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Sbastien/Double-chained-linked-list/ff81fce6bdd2655c12ccd8ad00545ade1c2fd710/srcs/list_pop_front.c",
"visit_date": "2020-04-06T04:09:10.426190"
}
|
stackv2
|
#include "linkedlist.h"
#include <stdlib.h>
void list_pop_front(t_list *list) {
t_node *tmp;
tmp = NULL;
if (list && list->size > 0) {
if (list->size == 1) {
tmp = list->tail;
list->head = NULL;
list->tail = NULL;
} else {
tmp = list->head;
list->head->next->prev = list->head->prev;
list->head->prev->next = list->head->next;
list->head = list->head->next;
}
list->size -= 1;
if (list->del_data)
list->del_data(&tmp->data);
free(tmp);
}
}
| 2.484375 | 2 |
2024-11-18T21:29:44.729568+00:00
| 2022-06-09T19:43:13 |
d4102d755e56dec7a96af9acbb6612bb7b24e2c7
|
{
"blob_id": "d4102d755e56dec7a96af9acbb6612bb7b24e2c7",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-09T19:43:13",
"content_id": "c487633bb1f52e65d84437e41dc5a8ca6a4f78e3",
"detected_licenses": [
"MIT"
],
"directory_id": "64014c6a817eae339ee272067922c4c26a6d1459",
"extension": "c",
"filename": "sort_list.c",
"fork_events_count": 10,
"gha_created_at": "2020-09-27T21:43:17",
"gha_event_created_at": "2022-06-04T01:47:38",
"gha_language": "C++",
"gha_license_id": "NOASSERTION",
"github_id": 299124547,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4689,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/mod-single-repo/nvm_malloc/ulib-svn/src/base/sort_list.c",
"provenance": "stackv2-0112.json.gz:177076",
"repo_name": "urcs-sync/Montage",
"revision_date": "2022-06-09T19:43:13",
"revision_id": "3384e50105348fab6d80e897bfb4a0efdd8aa825",
"snapshot_id": "c91dbf3abd0f82c2f84ad40f152d992787fbdbd6",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/urcs-sync/Montage/3384e50105348fab6d80e897bfb4a0efdd8aa825/ext/mod-single-repo/nvm_malloc/ulib-svn/src/base/sort_list.c",
"visit_date": "2023-07-06T15:26:36.356064"
}
|
stackv2
|
/* The MIT License
Copyright (C) 2011 Zilong Tan ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* This implementation was ported from Linux kernel. */
#include <string.h>
#include "sort_list.h"
#define MAX_LIST_LENGTH_BITS 64
/*
* Returns a list organized in an intermediate format suited
* to chaining of merge() calls: null-terminated, no reserved or
* sentinel head node, "prev" links not maintained.
*/
static struct list_head *merge(void *priv,
int (*cmp)(void *priv, const void *, const void *),
struct list_head *a, struct list_head *b)
{
struct list_head head, *tail = &head;
while (a && b) {
/* if equal, take 'a' -- important for sort stability */
if ((*cmp)(priv, a, b) <= 0) {
tail->next = a;
a = a->next;
} else {
tail->next = b;
b = b->next;
}
tail = tail->next;
}
tail->next = a?:b;
return head.next;
}
/*
* Combine final list merge with restoration of standard doubly-linked
* list structure. This approach duplicates code from merge(), but
* runs faster than the tidier alternatives of either a separate final
* prev-link restoration pass, or maintaining the prev links
* throughout.
*/
static void merge_and_restore_back_links(void *priv,
int (*cmp)(void *priv, const void *, const void *),
struct list_head *head,
struct list_head *a, struct list_head *b)
{
struct list_head *tail = head;
while (a && b) {
/* if equal, take 'a' -- important for sort stability */
if ((*cmp)(priv, a, b) <= 0) {
tail->next = a;
a->prev = tail;
a = a->next;
} else {
tail->next = b;
b->prev = tail;
b = b->next;
}
tail = tail->next;
}
tail->next = a ? : b;
do {
tail->next->prev = tail;
tail = tail->next;
} while (tail->next);
tail->next = head;
head->prev = tail;
}
void list_sort(void *priv, struct list_head *head,
int (*cmp)(void *priv, const void *, const void *))
{
struct list_head *part[MAX_LIST_LENGTH_BITS + 1]; /* sorted partial lists
-- last slot is a sentinel */
int lev; /* index into part[] */
int max_lev = 0;
struct list_head *list;
if (list_empty(head))
return;
memset(part, 0, sizeof(part));
head->prev->next = NULL;
list = head->next;
while (list) {
struct list_head *cur = list;
list = list->next;
cur->next = NULL;
for (lev = 0; part[lev]; lev++) {
cur = merge(priv, cmp, part[lev], cur);
part[lev] = NULL;
}
if (lev > max_lev)
max_lev = lev;
part[lev] = cur;
}
for (lev = 0; lev < max_lev; lev++)
if (part[lev])
list = merge(priv, cmp, part[lev], list);
merge_and_restore_back_links(priv, cmp, head, part[max_lev], list);
}
void list_sort_forward(void *priv, struct list_head_forward *head,
int (*cmp)(void *priv, const void *, const void *))
{
struct list_head_forward *part[MAX_LIST_LENGTH_BITS + 1]; /* sorted partial lists
-- last slot is a sentinel */
int lev; /* index into part[] */
int max_lev = 0;
struct list_head_forward *list;
if (head->next == NULL)
return;
memset(part, 0, sizeof(part));
list = head->next;
while (list) {
struct list_head_forward *cur = list;
list = list->next;
cur->next = NULL;
for (lev = 0; part[lev]; lev++) {
cur = (struct list_head_forward *)
merge(priv, cmp, (struct list_head *)part[lev],
(struct list_head *)cur);
part[lev] = NULL;
}
if (lev > max_lev)
max_lev = lev;
part[lev] = cur;
}
for (lev = 0; lev <= max_lev; lev++)
if (part[lev])
list = (struct list_head_forward *)
merge(priv, cmp, (struct list_head *)part[lev],
(struct list_head *)list);
head->next = list;
}
| 2.671875 | 3 |
2024-11-18T21:29:44.962270+00:00
| 2022-05-10T18:56:48 |
49db77085850427bc6329617336a91e60b81a305
|
{
"blob_id": "49db77085850427bc6329617336a91e60b81a305",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-10T19:12:56",
"content_id": "5e276232a9260d3463814b50afdd47533ebdb9bb",
"detected_licenses": [
"Zlib"
],
"directory_id": "782af7bfc133bd8335b7c78d69a5e885b67b9043",
"extension": "c",
"filename": "model.c",
"fork_events_count": 48,
"gha_created_at": "2016-07-11T04:11:31",
"gha_event_created_at": "2021-10-13T03:30:04",
"gha_language": "HTML",
"gha_license_id": null,
"github_id": 63035773,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18026,
"license": "Zlib",
"license_type": "permissive",
"path": "/model.c",
"provenance": "stackv2-0112.json.gz:177336",
"repo_name": "madler/crcany",
"revision_date": "2022-05-10T18:56:48",
"revision_id": "2493dc60762066a0d2644f92a0903a8af7a10d27",
"snapshot_id": "c13b42466cab9cb58c1e7c957c820eff66484a25",
"src_encoding": "UTF-8",
"star_events_count": 245,
"url": "https://raw.githubusercontent.com/madler/crcany/2493dc60762066a0d2644f92a0903a8af7a10d27/model.c",
"visit_date": "2023-09-03T14:18:19.984955"
}
|
stackv2
|
/* model.c -- Generic CRC parameter model routines
* Copyright (C) 2014, 2016, 2017, 2020 Mark Adler
* For conditions of distribution and use, see copyright notice in crcany.c.
*/
#include "model.h"
/* --- Parameter processing routines --- */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Read one variable name and value from a string. The format is name=value,
// possibly preceded by white space, with the value ended by white space or the
// end of the string. White space is not permitted in the name, value, or
// around the = sign. Except that value can contain white space if it starts
// with a double quote. In that case, the value is taken from after the
// initial double-quote to before the closing double quote. A double-quote can
// be included in the value with two adjacent double-quotes. A double-quote in
// a name or in a value when the first character isn't a double-quote is
// treated like any other non-white-space character. On return *str points
// after the value, name is the zero-terminated name and value is the
// zero-terminated value. *str is modified to contain the zero-terminated name
// and value. read_vars() returns 1 on success, 0 on end of string, or -1 if
// there was an error, such as no name, no "=", no value, or no closing quote.
// If -1, *str is not modified, though *next and *value may be modified.
static int read_var(char **str, char **name, char **value) {
// Skip any leading white space, check for end of string.
char *next = *str;
while (isspace(*next))
next++;
if (*next == 0)
return 0;
// Get name.
*name = next;
while (*next && !isspace(*next) && *next != '=')
next++;
if (*next != '=' || next == *name)
return -1;
*next++ = 0;
// Get value.
if (*next == '"') {
// Get quoted value.
*value = ++next;
next = strchr(next, '"');
if (next == NULL)
return -1;
// Handle embedded quotes.
char *copy = next;
while (next[1] == '"') {
next++;
do {
*copy++ = *next++;
if (*next == 0)
return -1;
} while (*next != '"');
*copy = 0;
}
}
else {
// Get non-quoted value.
*value = next;
while (*next && !isspace(*next))
next++;
if (next == *value)
return -1;
}
// Skip terminating character if not end of string, terminate value.
if (*next)
*next++ = 0;
// Return updated string location.
*str = next;
return 1;
}
// Shift left a double-word quantity by n bits: r = a << n, 0 < n < WORDBITS.
// Return NULL from the enclosing function on overflow. rh and rl must be
// word_t lvalues. It is allowed for a to be r, shifting in place. ah and al
// are each used twice in this macro, so beware of side effects. WORDBITS is
// the number of bits in a word_t, which must be an unsigned integer type.
#define SHLO(rh, rl, ah, al, n) \
do { \
if ((word_t)(ah) >> (WORDBITS - (n))) \
return NULL; \
rh = ((word_t)(ah) << (n)) | ((word_t)(al) >> (WORDBITS - (n))); \
rl = (word_t)(al) << (n); \
} while (0)
// Add two double-word quantities: r += a. Return NULL from the enclosing
// function on overflow. rh and rl must be word_t lvalues. Note that rh and
// rl are referenced more than once, so beware of side effects.
#define ADDO(rh, rl, ah, al) \
do { \
word_t t = rh; \
rh += (ah); \
if (rh < t) \
return NULL; \
t = rl; \
rl += (al); \
if (rl < t && ++(rh) == 0) \
return NULL; \
} while (0)
// Convert a string of digits to a double-word unsigned integer, that is, two
// word_t unsigned integers making up a single unsigned integer with twice as
// many bits. If the string starts with "0x" or "0X", consider the string to
// be hexadecimal. If it starts with "0", consider it to be octal. Otherwise
// consider it to be decimal. If the string starts with "-", return the two's
// complement of the number that follows. Return a pointer to the first
// character in the string that is not a valid digit, or the end of the string
// if all were valid. If the provided digits result in an overflow of the
// double-length integer, then NULL is returned. If NULL is returned, *high
// and *low are unaltered.
static char *strtobig(char *str, word_t *high, word_t *low) {
unsigned neg = 0; // true if "-" prefix
word_t nh, nl; // double-length number accumulated
word_t th, tl; // temporary double-length number
// Look for minus sign.
if (*str == '-') {
str++;
neg = 1;
}
// Determine base from prefix.
unsigned k = 10;
if (*str == '0') {
str++;
k = 8;
if (*str == 'x' || *str == 'X') {
str++;
k = 16;
}
}
// Accumulate digits until a non-digit.
nh = nl = 0;
switch (k) {
case 8:
while (*str >= '0' && *str <= '7') {
k = *str++ - '0';
SHLO(nh, nl, nh, nl, 3);
nl |= k;
}
break;
case 10:
while (*str >= '0' && *str <= '9') {
k = *str++ - '0';
SHLO(nh, nl, nh, nl, 1); // n <<= 1
SHLO(th, tl, nh, nl, 2); // t = n << 2
ADDO(nh, nl, th, tl); // n += t
ADDO(nh, nl, 0, k); // n += k
}
break;
case 16:
while ((k = *str >= '0' && *str <= '9' ? *str++ - '0' :
*str >= 'A' && *str <= 'F' ? *str++ - 'A' + 10 :
*str >= 'a' && *str <= 'f' ? *str++ - 'a' + 10 :
16) != 16) {
SHLO(nh, nl, nh, nl, 4);
nl |= k;
}
}
// If negative, negate.
if (neg) {
nl = ~nl + 1;
nh = ~nh + (nl == 0 ? 1 : 0);
}
// Return result and string position after number.
*high = nh;
*low = nl;
return str;
}
// Check that high:low bits above width bits are either all zeros or all ones.
// If they are all ones, make them all zeros. Return true if those bits were
// not all zeros or all ones.
static int normal_big(word_t *low, word_t *high, unsigned width) {
const word_t ones = (word_t)0 - 1;
word_t mask_lo = width < WORDBITS ? ones << width : 0;
word_t mask_hi = width <= WORDBITS ? ones :
width < WORDBITS*2 ? ones << (width - WORDBITS) : 0;
if ((*low & mask_lo) == mask_lo && (*high & mask_hi) == mask_hi) {
*low &= ~mask_lo;
*high &= ~mask_hi;
return 0;
}
return (*low & mask_lo) != 0 || (*high & mask_hi) != 0;
}
/* --- Model input routines --- */
#include <stdio.h>
#include <stdlib.h>
// Masks for parameters.
#define WIDTH 1
#define POLY 2
#define INIT 4
#define REFIN 8
#define REFOUT 16
#define XOROUT 32
#define CHECK 64
#define RES 128
#define NAME 256
#define ALL (WIDTH|POLY|INIT|REFIN|REFOUT|XOROUT|CHECK|RES|NAME)
// A strncmp() that ignores case, like POSIX strncasecmp().
static int strncmpi(char const *s1, char const *s2, size_t n) {
unsigned char const *a = (unsigned char const *)s1,
*b = (unsigned char const *)s2;
for (size_t i = 0; i < n; i++) {
int diff = tolower(a[i]) - tolower(b[i]);
if (diff != 0)
return diff;
if (a[i] == 0)
break;
}
return 0;
}
// See model.h.
int read_model(model_t *model, char *str, int lenient) {
// Read name=value pairs from line.
unsigned got = 0, bad = 0, rep = 0;
char *unk = NULL;
model->name = NULL;
int ret;
char *name, *value;
while ((ret = read_var(&str, &name, &value)) == 1) {
size_t n = strlen(name);
size_t k = strlen(value);
word_t hi, lo;
char *end;
if (strncmpi(name, "width", n) == 0) {
if (got & WIDTH) {
rep |= WIDTH;
continue;
}
if ((end = strtobig(value, &hi, &lo)) == NULL || *end || hi) {
bad |= WIDTH;
continue;
}
model->width = lo;
got |= WIDTH;
}
else if (strncmpi(name, "poly", n) == 0) {
if (got & POLY) {
rep |= POLY;
continue;
}
if ((end = strtobig(value, &hi, &lo)) == NULL || *end) {
bad |= POLY;
continue;
}
model->poly = lo;
model->poly_hi = hi;
got |= POLY;
}
else if (strncmpi(name, "init", n) == 0) {
if (got & INIT) {
rep |= INIT;
continue;
}
if ((end = strtobig(value, &hi, &lo)) == NULL || *end) {
bad |= POLY;
continue;
}
model->init = lo;
model->init_hi = hi;
got |= INIT;
}
else if (strncmpi(name, "refin", n) == 0) {
if (got & REFIN) {
rep |= REFIN;
continue;
}
if (strncmpi(value, "true", k) &&
strncmpi(value, "false", k)) {
bad |= REFIN;
continue;
}
model->ref = *value == 't' ? 1 : 0;
got |= REFIN;
}
else if (strncmpi(name, "refout", n < 4 ? 4 : n) == 0) {
if (got & REFOUT) {
rep |= REFOUT;
continue;
}
if (strncmpi(value, "true", k) &&
strncmpi(value, "false", k)) {
bad |= REFOUT;
continue;
}
model->rev = *value == 't' ? 1 : 0;
got |= REFOUT;
}
else if (strncmpi(name, "xorout", n) == 0) {
if (got & XOROUT) {
rep |= XOROUT;
continue;
}
if ((end = strtobig(value, &hi, &lo)) == NULL || *end) {
bad |= XOROUT;
continue;
}
model->xorout = lo;
model->xorout_hi = hi;
got |= XOROUT;
}
else if (strncmpi(name, "check", n) == 0) {
if (got & CHECK) {
rep |= CHECK;
continue;
}
if ((end = strtobig(value, &hi, &lo)) == NULL || *end) {
bad |= CHECK;
continue;
}
model->check = lo;
model->check_hi = hi;
got |= CHECK;
}
else if (strncmpi(name, "residue", n < 3 ? 3 : n) == 0) {
if (got & RES) {
rep |= RES;
continue;
}
if ((end = strtobig(value, &hi, &lo)) == NULL || *end) {
bad |= RES;
continue;
}
model->res = lo;
model->res_hi = hi;
got |= RES;
}
else if (strncmpi(name, "name", n) == 0) {
if (got & NAME) {
rep |= NAME;
continue;
}
model->name = malloc(strlen(value) + 1);
if (model->name == NULL)
return 2;
strcpy(model->name, value);
got |= NAME;
}
else
unk = name;
}
// Provide defaults for some parameters.
if ((got & INIT) == 0) {
model->init = 0;
model->init_hi = 0;
got |= INIT;
}
if ((got & (REFIN|REFOUT)) == REFIN) {
model->rev = model->ref;
got |= REFOUT;
}
else if ((got & (REFIN|REFOUT)) == REFOUT) {
model->ref = model->rev;
got |= REFIN;
}
if ((got & XOROUT) == 0) {
model->xorout = 0;
model->xorout_hi = 0;
got |= XOROUT;
}
if ((got & RES) == 0) {
model->res = 0;
model->res_hi = 0;
got |= RES;
}
if (lenient && (got & CHECK) == 0) {
model->check = 0;
got |= CHECK;
}
// Check for parameter values out of range.
if (got & WIDTH) {
if (model->width < 1 || model->width > WORDBITS*2)
bad |= WIDTH;
else {
if ((got & POLY) &&
(normal_big(&model->poly, &model->poly_hi, model->width) ||
(model->poly & 1) != 1))
bad |= POLY;
if (normal_big(&model->init, &model->init_hi, model->width))
bad |= INIT;
if (normal_big(&model->xorout, &model->xorout_hi, model->width))
bad |= XOROUT;
if ((got & CHECK) &&
normal_big(&model->check, &model->check_hi, model->width))
bad |= CHECK;
if ((got & RES) &&
normal_big(&model->res, &model->res_hi, model->width))
bad |= RES;
}
}
// Issue error messages for noted problems (this section can be safely
// removed if error messages are not desired).
if (ret == -1)
fprintf(stderr, "bad syntax (not 'parm=value') at: '%s'\n", str);
else {
const char *parm[] = {"width", "poly", "init", "refin", "refout",
"xorout", "check", "residue", "name"};
name = model->name == NULL ? "<no name>" : model->name;
if (unk != NULL)
fprintf(stderr, "%s: unknown parameter %s\n", name, unk);
for (size_t n = rep, k = 0; n; n >>= 1, k++)
if (n & 1)
fprintf(stderr, "%s: %s repeated\n", name, parm[k]);
for (size_t n = bad, k = 0; n; n >>= 1, k++)
if (n & 1)
fprintf(stderr, "%s: %s out of range\n", name, parm[k]);
for (size_t n = (got ^ ALL) & ~bad, k = 0; n; n >>= 1, k++)
if (n & 1)
fprintf(stderr, "%s: %s missing\n", name, parm[k]);
}
// Return error if model not fully specified and valid.
if (ret == -1 || unk != NULL || rep || bad || got != ALL)
return 1;
// All good.
return 0;
}
// See model.h.
word_t reverse(word_t x, unsigned n) {
if (n == 1)
return x & 1;
if (n == 2)
return ((x >> 1) & 1) + ((x << 1) & 2);
if (n <= 4) {
x = ((x >> 2) & 3) + ((x << 2) & 0xc);
x = ((x >> 1) & 5) + ((x << 1) & 0xa);
return x >> (4 - n);
}
if (n <= 8) {
x = ((x >> 4) & 0xf) + ((x << 4) & 0xf0);
x = ((x >> 2) & 0x33) + ((x << 2) & 0xcc);
x = ((x >> 1) & 0x55) + ((x << 1) & 0xaa);
return x >> (8 - n);
}
if (n <= 16) {
x = ((x >> 8) & 0xff) + ((x << 8) & 0xff00);
x = ((x >> 4) & 0xf0f) + ((x << 4) & 0xf0f0);
x = ((x >> 2) & 0x3333) + ((x << 2) & 0xcccc);
x = ((x >> 1) & 0x5555) + ((x << 1) & 0xaaaa);
return x >> (16 - n);
}
#if WORDBITS >= 32
if (n <= 32) {
x = ((x >> 16) & 0xffff) + ((x << 16) & 0xffff0000);
x = ((x >> 8) & 0xff00ff) + ((x << 8) & 0xff00ff00);
x = ((x >> 4) & 0xf0f0f0f) + ((x << 4) & 0xf0f0f0f0);
x = ((x >> 2) & 0x33333333) + ((x << 2) & 0xcccccccc);
x = ((x >> 1) & 0x55555555) + ((x << 1) & 0xaaaaaaaa);
return x >> (32 - n);
}
# if WORDBITS >= 64
if (n <= 64) {
x = ((x >> 32) & 0xffffffff) + ((x << 32) & 0xffffffff00000000);
x = ((x >> 16) & 0xffff0000ffff) + ((x << 16) & 0xffff0000ffff0000);
x = ((x >> 8) & 0xff00ff00ff00ff) + ((x << 8) & 0xff00ff00ff00ff00);
x = ((x >> 4) & 0xf0f0f0f0f0f0f0f) + ((x << 4) & 0xf0f0f0f0f0f0f0f0);
x = ((x >> 2) & 0x3333333333333333) + ((x << 2) & 0xcccccccccccccccc);
x = ((x >> 1) & 0x5555555555555555) + ((x << 1) & 0xaaaaaaaaaaaaaaaa);
return x >> (64 - n);
}
# endif
#endif
return n < 2*WORDBITS ? reverse(x, WORDBITS) << (n - WORDBITS) : 0;
}
// See model.h.
void reverse_dbl(word_t *hi, word_t *lo, unsigned n) {
if (n <= WORDBITS) {
*lo = reverse(*lo, n);
*hi = 0;
}
else {
word_t tmp = reverse(*lo, WORDBITS);
*lo = reverse(*hi, n - WORDBITS);
if (n < WORDBITS*2) {
*lo |= tmp << (n - WORDBITS);
*hi = tmp >> (WORDBITS*2 - n);
}
else
*hi = tmp;
}
}
// See model.h.
void process_model(model_t *model) {
if (model->ref)
reverse_dbl(&model->poly_hi, &model->poly, model->width);
if (model->rev)
reverse_dbl(&model->init_hi, &model->init, model->width);
model->init ^= model->xorout;
model->init_hi ^= model->xorout_hi;
model->rev ^= model->ref;
}
// Like POSIX getline().
ptrdiff_t fgetline(char **line, size_t *size, FILE *in) {
if (*line == NULL || *size == 0) {
free(*line);
*line = malloc(1);
if (*line == NULL)
return -1;
*size = 1;
}
int ch;
size_t len = 0;
while ((ch = getc(in)) != EOF) {
if (len + 1 >= *size) {
size_t more = *size << 1;
void *mem = realloc(*line, more);
if (mem == NULL)
return -1;
*line = mem;
*size = more;
}
(*line)[len++] = ch;
if (ch == '\n')
break;
}
(*line)[len] = 0;
ptrdiff_t ret = len;
return ret < 1 ? -1 : ret;
}
// See model.h.
ptrdiff_t getcleanline(char **line, size_t *size, FILE *in) {
// Get a line, return -1 on EOF or error.
ptrdiff_t len = fgetline(line, size, in);
if (len == -1)
return -1;
// Delete any embedded nulls.
char *ln = *line;
ptrdiff_t n = 0;
while (n < len && ln[n])
n++;
ptrdiff_t k = n;
while (++n < len)
if (ln[n])
ln[k++] = ln[n];
// Delete any trailing space.
while (k && isspace(ln[k - 1]))
k--;
ln[k] = 0;
return k;
}
| 2.671875 | 3 |
2024-11-18T21:29:45.034579+00:00
| 2023-08-30T22:00:02 |
a2a6ad33490fcac2eeb04b23ed16809eb11d1254
|
{
"blob_id": "a2a6ad33490fcac2eeb04b23ed16809eb11d1254",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T22:00:02",
"content_id": "837660f3f6b73c727e2f98ebe239e1954bcd662f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "113854f799ea342b2b2986d40256c9164b5759b4",
"extension": "c",
"filename": "5_ex_shm_test_filesize_mmapsize.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147092799,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1266,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/B.操作系统/Linux/Application/3.进程通信/7.共享内存区/Examples/5_ex_shm_test_filesize_mmapsize.c",
"provenance": "stackv2-0112.json.gz:177468",
"repo_name": "isshe/coding-life",
"revision_date": "2023-08-30T22:00:02",
"revision_id": "f93ecaee587474446d51a0be6bce54176292fd97",
"snapshot_id": "5710ad135bf91ab9c6caf2f29a91215f03bba120",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/isshe/coding-life/f93ecaee587474446d51a0be6bce54176292fd97/B.操作系统/Linux/Application/3.进程通信/7.共享内存区/Examples/5_ex_shm_test_filesize_mmapsize.c",
"visit_date": "2023-08-31T20:43:23.967162"
}
|
stackv2
|
#include "isshe_common.h"
#include "isshe_error.h"
#include "isshe_ipc.h"
#include "isshe_process.h"
#include "isshe_unistd.h"
#include "isshe_file.h"
#define SEM_NAME "mysem"
int main(int argc, char *argv[])
{
int fd, i;
char *ptr; // 注意这里的类型!!!写成int,找了半天。
size_t filesize, mmapsize, pagesize;
if (argc != 4) {
isshe_error_exit("Usage: test1 <pathname> <filesize> <mmapsize>");
}
filesize = atoi(argv[2]);
mmapsize = atoi(argv[3]);
printf("filesize = %ld, mmapsize = %ld\n", (long)filesize, (long)mmapsize);
fd = isshe_open(argv[1], O_RDWR | O_CREAT | O_TRUNC, ISSHE_FILE_MODE);
isshe_lseek(fd, filesize - 1, SEEK_SET);
isshe_write(fd, "", 1);
ptr = isshe_mmap(NULL, mmapsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
isshe_close(fd);
pagesize = isshe_sysconf(_SC_PAGESIZE);
printf("PAGESIZE = %ld\n", (long)pagesize);
for (i = 0; i < max(filesize, mmapsize); i += pagesize) {
ptr[i] = 1;
printf("1: ptr[%d] = %d\n", i, ptr[i]);
ptr[i + pagesize - 1] = 1;
printf("2: ptr[%d] = %d\n", (int)(i + pagesize - 1), ptr[i + pagesize - 1]);
}
printf("ptr[%d] = %d\n", i, ptr[i]);
exit(0);
}
| 2.796875 | 3 |
2024-11-18T21:29:45.241739+00:00
| 2021-03-12T16:26:31 |
1b99276d4b726ed0ba1378fe4a19590dcc699838
|
{
"blob_id": "1b99276d4b726ed0ba1378fe4a19590dcc699838",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-12T16:26:31",
"content_id": "332b9ecc14880be57b71530d1adfa1dca917bb9a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "53185d37d7de545e4ed54433303c50ce18dfcc10",
"extension": "c",
"filename": "LD4_1_20CY20031.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 336060167,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 938,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/LD4_1_20CY20031.c",
"provenance": "stackv2-0112.json.gz:177861",
"repo_name": "shubhamsnehil/Lab-Day-Assignment-codes",
"revision_date": "2021-03-12T16:26:31",
"revision_id": "6e01da9219ad9cdb8b2ec87dca72a5022a044bb7",
"snapshot_id": "24095f6979794827a183195c989ddb28be1bcb9e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/shubhamsnehil/Lab-Day-Assignment-codes/6e01da9219ad9cdb8b2ec87dca72a5022a044bb7/LD4_1_20CY20031.c",
"visit_date": "2023-03-22T21:53:07.281491"
}
|
stackv2
|
//Roll No.:20CY20031
//Name:Shubham Snehil
#include <stdio.h>
int main()
{
int a,temp;
printf("\nEnter an integer:");
scanf("%d",&a);
while(a!=0)
{
temp=a%10;
switch(temp)
{
case 0:
printf("Zero ");
break;
case 1:
printf("One ");
break;
case 2:
printf("Two ");
break;
case 3:
printf("Three ");
break;
case 4:
printf("Four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("Six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("Eight ");
break;
case 9:
printf("nine ");
break;
}
a/=10;
}
}
| 3.40625 | 3 |
2024-11-18T21:29:45.708411+00:00
| 2020-07-19T09:51:14 |
4793c9bc776c4001f8def995d67ad8d3a4e5a576
|
{
"blob_id": "4793c9bc776c4001f8def995d67ad8d3a4e5a576",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-19T09:51:14",
"content_id": "6b17a75e006cd12df4c05dcaaf03d09988a4bd38",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a1cae92e3015bdde25509af429316d01764469b4",
"extension": "c",
"filename": "testcase10.c",
"fork_events_count": 0,
"gha_created_at": "2019-02-21T01:46:05",
"gha_event_created_at": "2019-03-08T01:27:41",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 171780132,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 658,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/C/ubuntu/testcase/testcase10.c",
"provenance": "stackv2-0112.json.gz:177990",
"repo_name": "kaka555/KAKAOS",
"revision_date": "2020-07-19T09:51:14",
"revision_id": "67426c8dfd9010b92831113728e109fbb1613615",
"snapshot_id": "d0c88c6e1837b5b4ac91e1e9ef1cf94e27fb730d",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/kaka555/KAKAOS/67426c8dfd9010b92831113728e109fbb1613615/C/ubuntu/testcase/testcase10.c",
"visit_date": "2021-07-10T15:41:42.350012"
}
|
stackv2
|
//test new memory management
#include <user.h>
#include <osinit.h>
#include <os_delay.h>
extern volatile TCB *OSTCBCurPtr;
extern volatile TCB *OSTCBHighRdyPtr;
void three(void *para)
{
void *ptr[31];
int i;
_get_os_buddy_ptr_head();
ka_printf("%p\n", _alloc_power2_page());
ka_printf("%p\n", _alloc_power3_page());
ka_printf("%p\n", _alloc_power4_page());
ka_printf("%p\n", _alloc_power6_page());
while (1)
{
for (i = 0; i < 31; ++i)
{
ptr[i] = ka_malloc(500);
ka_printf("ptr[%d] is %p\n", i, ptr[i]);
}
sleep(200 * HZ);
for (i = 0; i < 31; ++i)
{
ka_free(ptr[i]);
}
ka_printf("free complete\n");
sleep(500 * HZ);
}
}
| 2.40625 | 2 |
2024-11-18T21:29:45.991549+00:00
| 2019-01-28T00:36:12 |
21a73b791a01c41d272a88a3d196dbc6027c934d
|
{
"blob_id": "21a73b791a01c41d272a88a3d196dbc6027c934d",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-28T00:36:12",
"content_id": "4aa1e6db85ed848f32035a903c8f8a7d7a4ecbb5",
"detected_licenses": [
"MIT"
],
"directory_id": "1c5311bc12010954398e91d7b1b71ad3edd8c0fb",
"extension": "c",
"filename": "boot.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 26934718,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4464,
"license": "MIT",
"license_type": "permissive",
"path": "/stage2/src/boot.c",
"provenance": "stackv2-0112.json.gz:178121",
"repo_name": "cjsmeele/havik",
"revision_date": "2019-01-28T00:36:12",
"revision_id": "bc7b58ceca06fdde846edaaf9a048a3813577d35",
"snapshot_id": "428513a6f7f78626311f1e5b25ee76072f73a7e2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/cjsmeele/havik/bc7b58ceca06fdde846edaaf9a048a3813577d35/stage2/src/boot.c",
"visit_date": "2020-05-04T11:14:08.383578"
}
|
stackv2
|
/**
* \file
* \brief Functions used to boot the system.
* \author Chris Smeele
* \copyright Copyright (c) 2015, Chris Smeele. All rights reserved.
* \license MIT. See LICENSE for the full license text.
*/
#include "boot.h"
#include "console.h"
#include "fs/fs.h"
#include "elf.h"
#include "config.h"
#include "vbe.h"
#include "multiboot.h"
#include "stage2.h"
void boot(BootOption *bootOption) {
Partition *kernelPartition = bootOption->kernel.partition;
if (!kernelPartition->fsDriver) {
printf("error: Kernel partition has no FS driver\n");
return;
}
FileInfo fileInfo;
memset(&fileInfo, 0, sizeof(FileInfo));
int ret = kernelPartition->fsDriver->getFile(
kernelPartition,
&fileInfo,
bootOption->kernel.path
);
if (ret == FS_SUCCESS && fileInfo.type == FILE_TYPE_REGULAR) {
ConfigOption *videoWidth = getConfigOption("video-width");
ConfigOption *videoHeight = getConfigOption("video-height");
ConfigOption *videoBpp = getConfigOption("video-bbp");
ConfigOption *videoMode = getConfigOption("video-mode");
bool modeSet = false;
if (videoMode->value.valInt32) {
modeSet = !vbeSetMode(videoMode->value.valInt32);
} else if (videoWidth->value.valInt32 && videoHeight->value.valInt32) {
uint16_t mode = vbeGetModeFromModeInfo(
videoWidth->value.valInt32,
videoHeight->value.valInt32,
videoBpp->value.valInt32
);
if (mode != 0xffff)
modeSet = !vbeSetMode(mode);
}
// Note: We do not read the kernel's multiboot header; We simply assume that
// the kernel will be an ELF image and supply a memory map.
// Any video mode switching must be specified in the loader.rc file.
generateMultibootInfo(kernelPartition);
loadElf(&fileInfo);
// Boot failed. :(
if (modeSet) {
// Reset display to 80x25 text mode.
msleep(3000);
setVideoMode(3);
}
} else if (ret == FS_FILE_NOT_FOUND || fileInfo.type != FILE_TYPE_REGULAR) {
printf(
"error: Kernel binary not found at hd%u:%u:%s\n",
kernelPartition->disk->diskNo,
kernelPartition->partitionNo,
bootOption->kernel.path
);
} else {
printf("An error occurred while locating the kernel binary on disk\n");
}
}
int parseBootPathString(BootFilePath *bootFile, char *str) {
if (strneq(str, "hd", 2)) {
str += 2;
uint32_t numLen = strchr(str, ':') - str;
if (!numLen || !str[numLen+1])
goto invalidFormat;
str[numLen] = '\0';
uint32_t diskNo = atoi(str);
str += numLen + 1;
numLen = strchr(str, ':') - str;
if (!numLen || !str[numLen+1])
goto invalidFormat;
str[numLen] = '\0';
uint32_t partNo = atoi(str);
str += numLen + 1;
if (diskNo >= diskCount || partNo >= disks[diskNo].partitionCount) {
printf("error: Boot file path disk/partition number out of range\n");
return 1;
}
bootFile->path = str;
bootFile->partition = &disks[diskNo].partitions[partNo];
printf("Selected boot file path: hd%u:%u, <%s>\n", diskNo, partNo, str);
} else if (strneq(str, "FSID=", 5)) {
str += 5;
uint32_t idLen = strchr(str, ':') - str;
if (!idLen || !str[idLen+1])
goto invalidFormat;
str[idLen] = '\0';
if (idLen < 1 || idLen > 16)
goto invalidFormat;
toLowerCase(str);
uint64_t id = 0;
for (uint32_t i=0; i<idLen; i++) {
if (
(str[i] >= '0' && str[i] <= '9')
|| (str[i] >= 'a' && str[i] <= 'f')
) {
id |= (uint64_t)(
str[i] >= '0' && str[i] <= '9'
? str[i] - '0'
: str[i] - 'a' + 10
) << ((idLen - (i+1)) * 4);
}
}
bootFile->partition = getPartitionByFsId(id);
if (!bootFile->partition) {
printf("error: No filesystem with id %08x-%08x was found\n", (uint32_t)(id >> 32), (uint32_t)id);
return 1;
}
bootFile->path = str + idLen + 1;
} else if (strneq(str, "FSLABEL=", 8)) {
str += 8;
uint32_t labelLen = strchr(str, ':') - str;
if (!labelLen || !str[labelLen+1])
goto invalidFormat;
str[labelLen] = '\0';
bootFile->partition = getPartitionByFsLabel(str);
if (!bootFile->partition) {
printf("error: No filesystem with label '%s' was found\n", str);
return 1;
}
bootFile->path = str + labelLen + 1;
} else if (str[0] == '/') {
if (loaderPart) {
bootFile->path = str;
bootFile->partition = loaderPart;
} else {
printf("error: Boot file path is incomplete\n");
return 1;
}
} else {
goto invalidFormat;
}
return 0;
invalidFormat:
printf("error: Invalid boot file path format\n");
return 1;
}
| 2.484375 | 2 |
2024-11-18T21:29:47.093819+00:00
| 2020-01-25T18:56:19 |
c8a3b2efb7d81145edb2d94adf71ea60c52b35a1
|
{
"blob_id": "c8a3b2efb7d81145edb2d94adf71ea60c52b35a1",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-25T18:56:19",
"content_id": "22154994f0423891020b4b80846f84a0314c18ce",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d4438b0b2bdc56ea127ea7df65b0e8cb33a71451",
"extension": "c",
"filename": "notification.c",
"fork_events_count": 1,
"gha_created_at": "2019-11-13T20:33:01",
"gha_event_created_at": "2019-11-13T20:33:02",
"gha_language": null,
"gha_license_id": "BSD-3-Clause",
"github_id": 221546266,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9023,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/libs/notification/notification.c",
"provenance": "stackv2-0112.json.gz:179163",
"repo_name": "ulrikeschaefer/libelektra",
"revision_date": "2020-01-25T18:56:19",
"revision_id": "0213cd13c5dc05d7827d39b089b6cb657a898e84",
"snapshot_id": "973176fc7b9df222f6c9491a5716ed256d14a439",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ulrikeschaefer/libelektra/0213cd13c5dc05d7827d39b089b6cb657a898e84/src/libs/notification/notification.c",
"visit_date": "2022-04-06T20:31:37.720706"
}
|
stackv2
|
/**
* @file
*
* @brief Implementation of notification functions as defined in
* kdbnotification.h
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include <kdbassert.h>
#include <kdbease.h>
#include <kdbhelper.h>
#include <kdbinvoke.h>
#include <kdbioprivate.h>
#include <kdblogger.h>
#include <kdbnotification.h>
#include <kdbnotificationinternal.h>
#include <kdbplugin.h>
#include <kdbprivate.h> // for elektraGetPluginFunction, elektraPluginFindGlobal, kdb->globalPlugins and plugin->config
#include <stdio.h>
static void pluginsOpenNotification (KDB * kdb, ElektraNotificationCallback callback, ElektraNotificationCallbackContext * context)
{
ELEKTRA_NOT_NULL (kdb);
ELEKTRA_NOT_NULL (callback);
KeySet * parameters = ksNew (2, keyNew ("/callback", KEY_FUNC, callback, KEY_END),
keyNew ("/context", KEY_BINARY, KEY_SIZE, sizeof (context), KEY_VALUE, &context, KEY_END), KS_END);
// iterate over global plugins
for (int positionIndex = 0; positionIndex < NR_GLOBAL_POSITIONS; positionIndex++)
{
for (int subPositionIndex = 0; subPositionIndex < NR_GLOBAL_SUBPOSITIONS; subPositionIndex++)
{
Plugin * plugin = kdb->globalPlugins[positionIndex][subPositionIndex];
if (!plugin)
{
continue;
}
elektraDeferredCall (plugin, "openNotification", parameters);
}
}
ksDel (parameters);
}
static void pluginsCloseNotification (KDB * kdb)
{
ELEKTRA_NOT_NULL (kdb);
// iterate over global plugins
for (int positionIndex = 0; positionIndex < NR_GLOBAL_POSITIONS; positionIndex++)
{
for (int subPositionIndex = 0; subPositionIndex < NR_GLOBAL_SUBPOSITIONS; subPositionIndex++)
{
Plugin * plugin = kdb->globalPlugins[positionIndex][subPositionIndex];
if (!plugin)
{
continue;
}
elektraDeferredCall (plugin, "closeNotification", NULL);
}
}
}
/**
* @see kdbnotificationinternal.h ::ElektraNotificationKdbUpdate
*/
static void elektraNotificationKdbUpdate (KDB * kdb, Key * changedKey)
{
KeySet * ks = ksNew (0, KS_END);
kdbGet (kdb, ks, changedKey);
ksDel (ks);
}
int elektraNotificationOpen (KDB * kdb)
{
// Make sure kdb is not null
if (!kdb)
{
ELEKTRA_LOG_WARNING ("kdb was not set");
return 0;
}
Plugin * notificationPlugin = elektraPluginFindGlobal (kdb, "internalnotification");
// Allow open only once
if (notificationPlugin)
{
ELEKTRA_LOG_WARNING ("elektraNotificationOpen already called for kdb");
return 0;
}
// Create context for notification callback
ElektraNotificationCallbackContext * context = elektraMalloc (sizeof (*context));
if (context == NULL)
{
return 0;
}
context->kdb = kdb;
context->kdbUpdate = &elektraNotificationKdbUpdate;
Key * parent = keyNew ("", KEY_END);
KeySet * contract = ksNew (2, keyNew ("system/elektra/ensure/plugins/global/internalnotification", KEY_VALUE, "mounted", KEY_END),
keyNew ("system/elektra/ensure/plugins/global/internalnotification/config/context", KEY_BINARY, KEY_SIZE,
sizeof (context), KEY_VALUE, &context, KEY_END),
KS_END);
if (kdbEnsure (kdb, contract, parent) != 0)
{
keyDel (parent);
ELEKTRA_LOG_WARNING ("kdbEnsure failed");
return 0;
}
notificationPlugin = elektraPluginFindGlobal (kdb, "internalnotification");
if (notificationPlugin == NULL)
{
ELEKTRA_LOG_WARNING ("kdbEnsure failed");
return 0;
}
context->notificationPlugin = notificationPlugin;
// Get notification callback from notification plugin
size_t func = elektraPluginGetFunction (notificationPlugin, "notificationCallback");
if (!func)
{
// remove notification plugin again
contract = ksNew (1, keyNew ("system/elektra/ensure/plugins/global/internalnotification", KEY_VALUE, "unmounted", KEY_END),
KS_END);
if (kdbEnsure (kdb, contract, parent) != 0)
{
ELEKTRA_LOG_WARNING ("kdbEnsure failed");
}
keyDel (parent);
return 0;
}
ElektraNotificationCallback notificationCallback = (ElektraNotificationCallback) func;
keyDel (parent);
// Open notification for plugins
pluginsOpenNotification (kdb, notificationCallback, context);
return 1;
}
int elektraNotificationClose (KDB * kdb)
{
// Make sure kdb is not null
if (!kdb)
{
ELEKTRA_LOG_WARNING ("kdb was not set");
return 0;
}
Plugin * notificationPlugin = elektraPluginFindGlobal (kdb, "internalnotification");
// Make sure open was called
if (notificationPlugin == NULL)
{
ELEKTRA_LOG_WARNING ("elektraNotificationOpen not called before elektraPluginClose");
return 0;
}
Key * contextKey = ksLookupByName (notificationPlugin->config, "user/context", 0);
ElektraNotificationCallbackContext * context = *(ElektraNotificationCallbackContext **) keyValue (contextKey);
elektraFree (context);
// Unmount the plugin
Key * parent = keyNew ("", KEY_END);
KeySet * contract =
ksNew (1, keyNew ("system/elektra/ensure/plugins/global/internalnotification", KEY_VALUE, "unmounted", KEY_END), KS_END);
if (kdbEnsure (kdb, contract, parent) != 0)
{
ELEKTRA_LOG_WARNING ("kdbEnsure failed");
}
keyDel (parent);
// Close notification for plugins
pluginsCloseNotification (kdb);
return 1;
}
/**
* @internal
* Get notification plugin from kdb.
*
* @param kdb KDB handle
* @return Notification plugin handle or NULL if not present
*/
static Plugin * getNotificationPlugin (KDB * kdb)
{
ELEKTRA_NOT_NULL (kdb);
Plugin * notificationPlugin = elektraPluginFindGlobal (kdb, "internalnotification");
if (notificationPlugin)
{
return notificationPlugin;
}
else
{
ELEKTRA_LOG_WARNING (
"notificationPlugin not set. use "
"elektraNotificationOpen before calling other "
"elektraNotification-functions");
return NULL;
}
}
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (int, Int)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (unsigned int, UnsignedInt)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (long, Long)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (unsigned long, UnsignedLong)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (float, Float)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (double, Double)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_boolean_t, KdbBoolean)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_char_t, KdbChar)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_octet_t, KdbOctet)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_short_t, KdbShort)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_unsigned_short_t, KdbUnsignedShort)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_long_t, KdbLong)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_unsigned_long_t, KdbUnsignedLong)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_long_long_t, KdbLongLong)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_unsigned_long_long_t, KdbUnsignedLongLong)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_float_t, KdbFloat)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_double_t, KdbDouble)
ELEKTRA_NOTIFICATION_TYPE_DEFINITION (kdb_long_double_t, KdbLongDouble)
int elektraNotificationRegisterCallback (KDB * kdb, Key * key, ElektraNotificationChangeCallback callback, void * context)
{
if (!kdb || !key || !callback)
{
ELEKTRA_LOG_WARNING ("null pointer passed");
return 0;
}
// Find notification plugin
Plugin * notificationPlugin = getNotificationPlugin (kdb);
if (!notificationPlugin)
{
return 0;
}
// Get register function from plugin
size_t func = elektraPluginGetFunction (notificationPlugin, "registerCallback");
if (!func)
{
return 0;
}
// Call register function
ElektraNotificationPluginRegisterCallback registerFunc = (ElektraNotificationPluginRegisterCallback) func;
return registerFunc (notificationPlugin, key, callback, context);
}
int elektraNotificationRegisterCallbackSameOrBelow (KDB * kdb, Key * key, ElektraNotificationChangeCallback callback, void * context)
{
if (!kdb || !key || !callback)
{
ELEKTRA_LOG_WARNING ("null pointer passed");
return 0;
}
// Find notification plugin
Plugin * notificationPlugin = getNotificationPlugin (kdb);
if (!notificationPlugin)
{
return 0;
}
// Get register function from plugin
size_t func = elektraPluginGetFunction (notificationPlugin, "registerCallbackSameOrBelow");
if (!func)
{
return 0;
}
// Call register function
ElektraNotificationPluginRegisterCallbackSameOrBelow registerFunc = (ElektraNotificationPluginRegisterCallbackSameOrBelow) func;
return registerFunc (notificationPlugin, key, callback, context);
}
int elektraNotificationSetConversionErrorCallback (KDB * kdb, ElektraNotificationConversionErrorCallback callback, void * context)
{
if (!kdb || !callback)
{
ELEKTRA_LOG_WARNING ("null pointer passed");
return 0;
}
// Find notification plugin
Plugin * notificationPlugin = getNotificationPlugin (kdb);
if (!notificationPlugin)
{
return 0;
}
// Get register function from plugin
size_t func = elektraPluginGetFunction (notificationPlugin, "setConversionErrorCallback");
if (!func)
{
return 0;
}
// Call register function
ElektraNotificationSetConversionErrorCallback setCallbackFunc = (ElektraNotificationSetConversionErrorCallback) func;
setCallbackFunc (notificationPlugin, callback, context);
return 1;
}
| 2.109375 | 2 |
2024-11-18T21:29:47.201432+00:00
| 2019-04-12T08:38:26 |
285bf46d387d95088d391270fde3d3eabf8f7df3
|
{
"blob_id": "285bf46d387d95088d391270fde3d3eabf8f7df3",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-12T08:38:26",
"content_id": "f365f0484d8dd4d3db1f6d5577848a8e7ce8835e",
"detected_licenses": [
"MIT"
],
"directory_id": "8df77479804e9a9aa25cc1175d081cee2ebd4ff5",
"extension": "c",
"filename": "i2c.c",
"fork_events_count": 6,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14828043,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5105,
"license": "MIT",
"license_type": "permissive",
"path": "/drivers/i2c.c",
"provenance": "stackv2-0112.json.gz:179292",
"repo_name": "raphui/rnk",
"revision_date": "2019-04-12T08:38:26",
"revision_id": "b77186afcebe95ad5efb53684fef113abdec273f",
"snapshot_id": "afa853498f597019ba3b54d2874d0b0aa8aec02e",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/raphui/rnk/b77186afcebe95ad5efb53684fef113abdec273f/drivers/i2c.c",
"visit_date": "2021-06-08T09:13:54.923012"
}
|
stackv2
|
#include <kernel/printk.h>
#include <drv/i2c.h>
#include <mm/mm.h>
#include <errno.h>
#include <string.h>
#include <utils.h>
#include <init.h>
#include <fdtparse.h>
static int dev_count = 0;
static int master_count = 0;
static struct list_node i2c_device_list;
static struct list_node i2c_master_list;
static int i2c_write(struct device *dev, unsigned char *buff, unsigned int size)
{
int ret;
struct i2c_device *i2c = container_of(dev, struct i2c_device, dev);
verbose_printk("writing from i2c !\n");
kmutex_lock(&i2c->master->i2c_mutex);
ret = i2c->master->i2c_ops->write(i2c, buff, size);
kmutex_unlock(&i2c->master->i2c_mutex);
return ret;
}
static int i2c_read(struct device *dev, unsigned char *buff, unsigned int size)
{
int ret;
struct i2c_device *i2c = container_of(dev, struct i2c_device, dev);
verbose_printk("reading from i2c !\n");
kmutex_lock(&i2c->master->i2c_mutex);
ret = i2c->master->i2c_ops->read(i2c, buff, size);
kmutex_unlock(&i2c->master->i2c_mutex);
return ret;
}
int i2c_transfer(struct i2c_device *i2c, unsigned char *buff, unsigned int size, int direction)
{
int ret = 0;
verbose_printk("i2c %s transfer\n", (direction == I2C_TRANSFER_READ) ? "read" : "write");
kmutex_lock(&i2c->master->i2c_mutex);
if (direction == I2C_TRANSFER_READ)
ret = i2c_read(&i2c->dev, buff, size);
else if (direction == I2C_TRANSFER_WRITE)
ret = i2c_write(&i2c->dev, buff, size);
else {
error_printk("invalid i2c transfer direction\n");
ret = -EINVAL;
}
kmutex_unlock(&i2c->master->i2c_mutex);
return ret;
}
struct i2c_device *i2c_new_device(void)
{
struct i2c_device *i2cdev = NULL;
i2cdev = (struct i2c_device *)kmalloc(sizeof(struct i2c_device));
if (!i2cdev) {
error_printk("cannot allocate i2c device\n");
return NULL;
}
memset(i2cdev, 0, sizeof(struct i2c_device));
dev_count++;
return i2cdev;
}
struct i2c_device *i2c_new_device_with_master(int fdt_offset)
{
int ret;
int parent_offset;
char fdt_path[64];
struct device *dev;
struct i2c_master *i2c;
struct i2c_device *i2cdev = NULL;
const void *fdt_blob = fdtparse_get_blob();
i2cdev = (struct i2c_device *)kmalloc(sizeof(struct i2c_device));
if (!i2cdev) {
error_printk("cannot allocate i2c device\n");
goto err;
}
memset(i2cdev, 0, sizeof(struct i2c_device));
parent_offset = fdt_parent_offset(fdt_blob, fdt_offset);
if (parent_offset < 0) {
error_printk("failed to retrive i2c master for this i2c device\n");
goto err;
}
memset(fdt_path, 0, 64 * sizeof(char));
ret = fdt_get_path(fdt_blob, parent_offset, fdt_path, 64);
if (ret < 0) {
error_printk("failed to fdt path of i2c device parent node\n");
goto err;
}
dev = device_from_of_path((const char *)fdt_path);
if (!dev) {
error_printk("failed to find device with fdt path: %s\n", fdt_path);
goto err;
}
i2c = container_of(dev, struct i2c_master, dev);
i2cdev->master = i2c;
dev_count++;
return i2cdev;
err:
return NULL;
}
int i2c_remove_device(struct i2c_device *i2c)
{
int ret = 0;
struct i2c_device *i2cdev = NULL;
ret = device_unregister(&i2c->dev);
if (ret < 0) {
error_printk("failed to unregister i2c device");
return ret;
}
list_for_every_entry(&i2c_device_list, i2cdev, struct i2c_device, node)
if (i2cdev == i2c)
break;
if (i2cdev) {
list_delete(&i2cdev->node);
kfree(i2cdev);
}
else
ret = -ENOENT;
dev_count--;
return ret;
}
int i2c_register_device(struct i2c_device *i2c)
{
int ret = 0;
snprintf(i2c->dev.name, sizeof(i2c->dev.name), "/dev/i2c%d", dev_count);
i2c->dev.read = i2c_read;
i2c->dev.write = i2c_write;
list_add_tail(&i2c_device_list, &i2c->node);
ret = device_register(&i2c->dev);
if (ret < 0)
error_printk("failed to register i2c device\n");
return ret;
}
struct i2c_master *i2c_new_master(void)
{
struct i2c_master *i2c = NULL;
i2c = (struct i2c_master *)kmalloc(sizeof(struct i2c_master));
if (!i2c) {
error_printk("cannot allocate i2c master\n");
return NULL;
}
memset(i2c, 0, sizeof(struct i2c_master));
master_count++;
return i2c;
}
int i2c_remove_master(struct i2c_master *i2c)
{
int ret = 0;
struct i2c_master *i2cdev = NULL;
ret = device_unregister(&i2c->dev);
if (ret < 0) {
error_printk("failed to unregister i2c master");
return ret;
}
list_for_every_entry(&i2c_master_list, i2cdev, struct i2c_master, node)
if (i2cdev == i2c)
break;
if (i2cdev) {
list_delete(&i2cdev->node);
kfree(i2cdev);
}
else
ret = -ENOENT;
master_count--;
return ret;
}
int i2c_register_master(struct i2c_master *i2c)
{
int ret = 0;
char tmp[10] = {0};
memcpy(tmp, dev_prefix, sizeof(dev_prefix));
/* XXX: ascii 0 start at 0x30 */
tmp[8] = 0x30 + master_count;
memcpy(i2c->dev.name, tmp, sizeof(tmp));
kmutex_init(&i2c->i2c_mutex);
list_add_tail(&i2c_master_list, &i2c->node);
ret = device_register(&i2c->dev);
if (ret < 0)
error_printk("failed to register i2c device\n");
return ret;
}
int i2c_init(void)
{
int ret = 0;
list_initialize(&i2c_device_list);
list_initialize(&i2c_master_list);
return ret;
}
postcore_initcall(i2c_init);
| 2.296875 | 2 |
2024-11-18T21:29:47.401526+00:00
| 2016-05-28T22:16:14 |
b459a65585f3527b935c0f0bd6b6f6de5cd00817
|
{
"blob_id": "b459a65585f3527b935c0f0bd6b6f6de5cd00817",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-28T22:16:14",
"content_id": "cff5cc151974cb59c2a66ebd213ae091846d4030",
"detected_licenses": [
"MIT"
],
"directory_id": "20d7b5ab63d638295652e87af6ec82d1fc923af3",
"extension": "h",
"filename": "esp8266_debug.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 58876971,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 796,
"license": "MIT",
"license_type": "permissive",
"path": "/src/esp8266_debug.h",
"provenance": "stackv2-0112.json.gz:179421",
"repo_name": "monkey-jsun/arduino-esp8266-atcmd",
"revision_date": "2016-05-28T22:16:14",
"revision_id": "e1e55ab3c24904761bc2639b298cc6c94f8f3769",
"snapshot_id": "16c387032c564a82eef8bd0aaf49b2edbb94077f",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/monkey-jsun/arduino-esp8266-atcmd/e1e55ab3c24904761bc2639b298cc6c94f8f3769/src/esp8266_debug.h",
"visit_date": "2020-12-31T07:19:47.350569"
}
|
stackv2
|
#ifndef __esp8266_debug_h__
#define __esp8266_debug_h__
#define ESP8266_DEBUG
//#define ESP8266_DEBUG_VERBOSE
#ifdef ESP8266_DEBUG
#define ASSERT(x) if (!(x)) { \
Serial.print(F("assert failed at ")); \
Serial.print(__func__); \
Serial.print(F("()@")); \
Serial.println(__LINE__); \
for(;;); }
#define WARN(x) if (!(x)) { \
Serial.print(F("warning at ")); \
Serial.print(__func__); \
Serial.print(F("()@")); \
Serial.println(__LINE__);}
#define VERIFY(x, y) ASSERT(x y)
#define DEBUG(x) do { x; } while (0)
#ifdef ESP8266_DEBUG_VERBOSE
#define DEBUG_VERBOSE(x) DEBUG(x)
#else
#define DEBUG_VERBOSE(x)
#endif
#else
#define ASSERT(x)
#define WARN(x)
#define VERIFY(x, y) x
#define DEBUG(x)
#define DEBUG_VERBOSE(x)
#endif
#endif /* __esp8266_debug_h__ */
| 2.03125 | 2 |
2024-11-18T21:29:47.478583+00:00
| 2020-08-25T08:11:02 |
6122d04cfdcae24eb166e326bf3cb4a104797711
|
{
"blob_id": "6122d04cfdcae24eb166e326bf3cb4a104797711",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-25T08:11:02",
"content_id": "ed37639f6fdf9d251d1bc921767baf4b27d88f68",
"detected_licenses": [
"MIT"
],
"directory_id": "044decc68a8d4e32b5226bc70448dc30edaba347",
"extension": "c",
"filename": "motorpoll.c",
"fork_events_count": 0,
"gha_created_at": "2020-07-03T15:20:27",
"gha_event_created_at": "2020-07-03T15:20:28",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 276929909,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3528,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/pbio/src/motorpoll.c",
"provenance": "stackv2-0112.json.gz:179549",
"repo_name": "GianCann/pybricks-micropython",
"revision_date": "2020-08-25T08:11:02",
"revision_id": "f23cdf7fdf9abd068e7e84ca54d6162b4fc5f72a",
"snapshot_id": "9f63ea42882505f76f80cdf1e648c786cc85abd3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GianCann/pybricks-micropython/f23cdf7fdf9abd068e7e84ca54d6162b4fc5f72a/lib/pbio/src/motorpoll.c",
"visit_date": "2022-12-04T16:43:36.335580"
}
|
stackv2
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2018-2020 The Pybricks Authors
#include <pbio/control.h>
#include <pbio/drivebase.h>
#include <pbio/motorpoll.h>
#include <pbio/servo.h>
#if PBDRV_CONFIG_NUM_MOTOR_CONTROLLER != 0
static pbio_servo_t servo[PBDRV_CONFIG_NUM_MOTOR_CONTROLLER];
static pbio_error_t servo_err[PBDRV_CONFIG_NUM_MOTOR_CONTROLLER];
static pbio_drivebase_t drivebase;
static pbio_error_t drivebase_err;
// Get pointer to servo by port index
pbio_error_t pbio_motorpoll_get_servo(pbio_port_t port, pbio_servo_t **srv) {
for (uint8_t i = 0; i < PBDRV_CONFIG_NUM_MOTOR_CONTROLLER; i++) {
if (servo[i].port == port) {
*srv = &servo[i];
return PBIO_SUCCESS;
}
}
return PBIO_ERROR_INVALID_PORT;
}
// Set status of the servo, which tells us whether to poll or not
pbio_error_t pbio_motorpoll_set_servo_status(pbio_servo_t *srv, pbio_error_t err) {
for (int i = 0; i < PBDRV_CONFIG_NUM_MOTOR_CONTROLLER; i++) {
if (srv == &servo[i]) {
servo_err[i] = err;
return PBIO_SUCCESS;
}
}
return PBIO_ERROR_INVALID_ARG;
}
// get status of the servo, which tells us whether to poll or not
pbio_error_t pbio_motorpoll_get_servo_status(pbio_servo_t *srv) {
for (int i = 0; i < PBDRV_CONFIG_NUM_MOTOR_CONTROLLER; i++) {
if (srv == &servo[i]) {
return servo_err[i];
}
}
return PBIO_ERROR_INVALID_ARG;
}
// Get pointer to drivebase
pbio_error_t pbio_motorpoll_get_drivebase(pbio_drivebase_t **db) {
// Get pointer to device (at the moment, there is only one drivebase)
*db = &drivebase;
return PBIO_SUCCESS;
}
// Set status of the drivebase, which tells us whether to poll or not
pbio_error_t pbio_motorpoll_set_drivebase_status(pbio_drivebase_t *db, pbio_error_t err) {
if (db != &drivebase) {
return PBIO_ERROR_INVALID_ARG;
}
drivebase_err = err;
return PBIO_SUCCESS;
}
// Get status of the drivebase, which tells us whether to poll or not
pbio_error_t pbio_motorpoll_get_drivebase_status(pbio_drivebase_t *db) {
if (db != &drivebase) {
return PBIO_ERROR_INVALID_ARG;
}
return drivebase_err;
}
void _pbio_motorpoll_reset_all(void) {
// Set ports for all servos on init
for (int i = 0; i < PBDRV_CONFIG_NUM_MOTOR_CONTROLLER; i++) {
servo[i].port = PBIO_PORT_A + i;
}
pbio_error_t err;
// Force stop the drivebase
err = pbio_drivebase_stop_force(&drivebase);
if (err != PBIO_SUCCESS) {
drivebase_err = err;
}
// Force stop the servos
for (int i = 0; i < PBDRV_CONFIG_NUM_MOTOR_CONTROLLER; i++) {
err = pbio_servo_stop_force(&servo[i]);
if (err != PBIO_SUCCESS) {
servo_err[i] = err;
}
}
}
void _pbio_motorpoll_poll(void) {
pbio_error_t err;
// Poll servos
for (int i = 0; i < PBDRV_CONFIG_NUM_MOTOR_CONTROLLER; i++) {
// Poll servo again if it says so, and save error if encountered
if (servo_err[i] == PBIO_ERROR_AGAIN) {
err = pbio_servo_control_update(&servo[i]);
if (err != PBIO_SUCCESS) {
servo_err[i] = err;
}
}
}
// Poll drivebase again if it says so, and save error if encountered
if (drivebase_err == PBIO_ERROR_AGAIN) {
err = pbio_drivebase_update(&drivebase);
if (err != PBIO_SUCCESS) {
drivebase_err = err;
}
}
}
#endif // PBDRV_CONFIG_NUM_MOTOR_CONTROLLER
| 2.453125 | 2 |
2024-11-18T21:29:53.756218+00:00
| 2023-08-25T04:46:28 |
ca923936045192791ebaa9e59321eecf0c43d155
|
{
"blob_id": "ca923936045192791ebaa9e59321eecf0c43d155",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-25T07:17:19",
"content_id": "1bc45b38830febf4fdfcd10522e4f3df75d7aa17",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dc7631ad46c850ad3b491c261c2da42edffabc4e",
"extension": "c",
"filename": "bmi260.c",
"fork_events_count": 58,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50835018,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 76621,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/zephyr/test/drivers/default/src/bmi260.c",
"provenance": "stackv2-0112.json.gz:179810",
"repo_name": "coreboot/chrome-ec",
"revision_date": "2023-08-25T04:46:28",
"revision_id": "0bbd46a5aa22eb824b21365f21f4811c9343ca1e",
"snapshot_id": "6eab032c65da77f16a7de81da85921c2ca872ee2",
"src_encoding": "UTF-8",
"star_events_count": 66,
"url": "https://raw.githubusercontent.com/coreboot/chrome-ec/0bbd46a5aa22eb824b21365f21f4811c9343ca1e/zephyr/test/drivers/default/src/bmi260.c",
"visit_date": "2023-08-25T08:30:03.833636"
}
|
stackv2
|
/* Copyright 2021 The ChromiumOS Authors
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "common.h"
#include "driver/accelgyro_bmi260.h"
#include "driver/accelgyro_bmi_common.h"
#include "emul/emul_bmi.h"
#include "emul/emul_common_i2c.h"
#include "i2c.h"
#include "motion_sense_fifo.h"
#include "test/drivers/test_mocks.h"
#include "test/drivers/test_state.h"
#include <zephyr/fff.h>
#include <zephyr/kernel.h>
#include <zephyr/ztest.h>
#define BMI_NODE DT_NODELABEL(accel_bmi260)
#define BMI_ACC_SENSOR_ID SENSOR_ID(DT_NODELABEL(ms_bmi260_accel))
#define BMI_GYR_SENSOR_ID SENSOR_ID(DT_NODELABEL(ms_bmi260_gyro))
#define BMI_INT_EVENT \
TASK_EVENT_MOTION_SENSOR_INTERRUPT(SENSOR_ID(DT_ALIAS(bmi260_int)))
/** How accurate comparision of vectors should be */
#define V_EPS 8
/** Convert from one type of vector to another */
#define convert_int3v_int16(v, r) \
do { \
r[0] = v[0]; \
r[1] = v[1]; \
r[2] = v[2]; \
} while (0)
/** Rotation used in some tests */
static const mat33_fp_t test_rotation = { { 0, FLOAT_TO_FP(1), 0 },
{ FLOAT_TO_FP(-1), 0, 0 },
{ 0, 0, FLOAT_TO_FP(-1) } };
/** Rotate given vector by test rotation */
static void rotate_int3v_by_test_rotation(intv3_t v)
{
int16_t t;
t = v[0];
v[0] = -v[1];
v[1] = t;
v[2] = -v[2];
}
/** Set emulator accelerometer offset values to intv3_t vector */
static void set_emul_acc_offset(const struct emul *emul, intv3_t offset)
{
bmi_emul_set_off(emul, BMI_EMUL_ACC_X, offset[0]);
bmi_emul_set_off(emul, BMI_EMUL_ACC_Y, offset[1]);
bmi_emul_set_off(emul, BMI_EMUL_ACC_Z, offset[2]);
}
/** Save emulator accelerometer offset values to intv3_t vector */
static void get_emul_acc_offset(const struct emul *emul, intv3_t offset)
{
offset[0] = bmi_emul_get_off(emul, BMI_EMUL_ACC_X);
offset[1] = bmi_emul_get_off(emul, BMI_EMUL_ACC_Y);
offset[2] = bmi_emul_get_off(emul, BMI_EMUL_ACC_Z);
}
/** Set emulator accelerometer values to intv3_t vector */
static void set_emul_acc(const struct emul *emul, intv3_t acc)
{
bmi_emul_set_value(emul, BMI_EMUL_ACC_X, acc[0]);
bmi_emul_set_value(emul, BMI_EMUL_ACC_Y, acc[1]);
bmi_emul_set_value(emul, BMI_EMUL_ACC_Z, acc[2]);
}
/** Set emulator gyroscope offset values to intv3_t vector */
static void set_emul_gyr_offset(const struct emul *emul, intv3_t offset)
{
bmi_emul_set_off(emul, BMI_EMUL_GYR_X, offset[0]);
bmi_emul_set_off(emul, BMI_EMUL_GYR_Y, offset[1]);
bmi_emul_set_off(emul, BMI_EMUL_GYR_Z, offset[2]);
}
/** Save emulator gyroscope offset values to intv3_t vector */
static void get_emul_gyr_offset(const struct emul *emul, intv3_t offset)
{
offset[0] = bmi_emul_get_off(emul, BMI_EMUL_GYR_X);
offset[1] = bmi_emul_get_off(emul, BMI_EMUL_GYR_Y);
offset[2] = bmi_emul_get_off(emul, BMI_EMUL_GYR_Z);
}
/** Set emulator gyroscope values to vector of three int16_t */
static void set_emul_gyr(const struct emul *emul, intv3_t gyr)
{
bmi_emul_set_value(emul, BMI_EMUL_GYR_X, gyr[0]);
bmi_emul_set_value(emul, BMI_EMUL_GYR_Y, gyr[1]);
bmi_emul_set_value(emul, BMI_EMUL_GYR_Z, gyr[2]);
}
/** Convert accelerometer read to units used by emulator */
static void drv_acc_to_emul(intv3_t drv, int range, intv3_t out)
{
const int scale = MOTION_SCALING_FACTOR / BMI_EMUL_1G;
out[0] = drv[0] * range / scale;
out[1] = drv[1] * range / scale;
out[2] = drv[2] * range / scale;
}
/** Convert gyroscope read to units used by emulator */
static void drv_gyr_to_emul(intv3_t drv, int range, intv3_t out)
{
const int scale = MOTION_SCALING_FACTOR / BMI_EMUL_125_DEG_S;
range /= 125;
out[0] = drv[0] * range / scale;
out[1] = drv[1] * range / scale;
out[2] = drv[2] * range / scale;
}
/** Compare two vectors of intv3_t type */
static void compare_int3v_f(intv3_t exp_v, intv3_t v, int eps, int line)
{
int i;
for (i = 0; i < 3; i++) {
zassert_within(
exp_v[i], v[i], eps,
"Expected [%d; %d; %d], got [%d; %d; %d]; line: %d",
exp_v[0], exp_v[1], exp_v[2], v[0], v[1], v[2], line);
}
}
#define compare_int3v_eps(exp_v, v, e) compare_int3v_f(exp_v, v, e, __LINE__)
#define compare_int3v(exp_v, v) compare_int3v_eps(exp_v, v, V_EPS)
/**
* Custom emulator read function which always return INIT OK status in
* INTERNAL STATUS register. Used in init test.
*/
static int emul_init_ok(const struct emul *emul, int reg, uint8_t *val,
int byte, void *data)
{
bmi_emul_set_reg(emul, BMI260_INTERNAL_STATUS, BMI260_INIT_OK);
return 1;
}
/** Init BMI260 before test */
static void bmi_init_emul(void)
{
struct motion_sensor_t *ms_acc;
struct motion_sensor_t *ms_gyr;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int ret;
common_data = emul_bmi_get_i2c_common_data(emul);
ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
ms_gyr = &motion_sensors[BMI_GYR_SENSOR_ID];
/*
* Init BMI before test. It is needed custom function to set value of
* BMI260_INTERNAL_STATUS register, because init function triggers reset
* which clears value set in this register before test.
*/
i2c_common_emul_set_read_func(common_data, emul_init_ok, NULL);
ret = ms_acc->drv->init(ms_acc);
zassert_equal(EC_RES_SUCCESS, ret, "Got accel init error %d", ret);
ret = ms_gyr->drv->init(ms_gyr);
zassert_equal(EC_RES_SUCCESS, ret, "Got gyro init error %d", ret);
/* Remove custom emulator read function */
i2c_common_emul_set_read_func(common_data, NULL, NULL);
}
/** Test get accelerometer offset with and without rotation */
ZTEST_USER(bmi260, test_bmi_acc_get_offset)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int16_t ret[3];
intv3_t ret_v;
intv3_t exp_v;
int16_t temp;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
/* Set emulator offset */
exp_v[0] = BMI_EMUL_1G / 10;
exp_v[1] = BMI_EMUL_1G / 20;
exp_v[2] = -(int)BMI_EMUL_1G / 30;
set_emul_acc_offset(emul, exp_v);
/* BMI driver returns value in mg units */
exp_v[0] = 1000 / 10;
exp_v[1] = 1000 / 20;
exp_v[2] = -1000 / 30;
/* Test fail on offset read */
i2c_common_emul_set_read_fail_reg(common_data, BMI160_OFFSET_ACC70);
zassert_equal(EC_ERROR_INVAL, ms->drv->get_offset(ms, ret, &temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data, BMI160_OFFSET_ACC70 + 1);
zassert_equal(EC_ERROR_INVAL, ms->drv->get_offset(ms, ret, &temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data, BMI160_OFFSET_ACC70 + 2);
zassert_equal(EC_ERROR_INVAL, ms->drv->get_offset(ms, ret, &temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Disable rotation */
ms->rot_standard_ref = NULL;
/* Test get offset without rotation */
zassert_equal(EC_SUCCESS, ms->drv->get_offset(ms, ret, &temp));
zassert_equal(temp, (int16_t)EC_MOTION_SENSE_INVALID_CALIB_TEMP);
convert_int3v_int16(ret, ret_v);
compare_int3v(exp_v, ret_v);
/* Setup rotation and rotate expected offset */
ms->rot_standard_ref = &test_rotation;
rotate_int3v_by_test_rotation(exp_v);
/* Test get offset with rotation */
zassert_equal(EC_SUCCESS, ms->drv->get_offset(ms, ret, &temp));
zassert_equal(temp, (int16_t)EC_MOTION_SENSE_INVALID_CALIB_TEMP);
convert_int3v_int16(ret, ret_v);
compare_int3v(exp_v, ret_v);
}
/** Test get gyroscope offset with and without rotation */
ZTEST_USER(bmi260, test_bmi_gyr_get_offset)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int16_t ret[3];
intv3_t ret_v;
intv3_t exp_v;
int16_t temp;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Do not fail on read */
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Set emulator offset */
exp_v[0] = BMI_EMUL_125_DEG_S / 100;
exp_v[1] = BMI_EMUL_125_DEG_S / 200;
exp_v[2] = -(int)BMI_EMUL_125_DEG_S / 300;
set_emul_gyr_offset(emul, exp_v);
/* BMI driver returns value in mdeg/s units */
exp_v[0] = 125000 / 100;
exp_v[1] = 125000 / 200;
exp_v[2] = -125000 / 300;
/* Test fail on offset read */
i2c_common_emul_set_read_fail_reg(common_data, BMI160_OFFSET_GYR70);
zassert_equal(EC_ERROR_INVAL, ms->drv->get_offset(ms, ret, &temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data, BMI160_OFFSET_GYR70 + 1);
zassert_equal(EC_ERROR_INVAL, ms->drv->get_offset(ms, ret, &temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data, BMI160_OFFSET_GYR70 + 2);
zassert_equal(EC_ERROR_INVAL, ms->drv->get_offset(ms, ret, &temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data, BMI160_OFFSET_EN_GYR98);
zassert_equal(EC_ERROR_INVAL, ms->drv->get_offset(ms, ret, &temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Disable rotation */
ms->rot_standard_ref = NULL;
/* Test get offset without rotation */
zassert_equal(EC_SUCCESS, ms->drv->get_offset(ms, ret, &temp));
zassert_equal(temp, (int16_t)EC_MOTION_SENSE_INVALID_CALIB_TEMP);
convert_int3v_int16(ret, ret_v);
compare_int3v_eps(exp_v, ret_v, 64);
/* Setup rotation and rotate expected offset */
ms->rot_standard_ref = &test_rotation;
rotate_int3v_by_test_rotation(exp_v);
/* Test get offset with rotation */
zassert_equal(EC_SUCCESS, ms->drv->get_offset(ms, ret, &temp));
zassert_equal(temp, (int16_t)EC_MOTION_SENSE_INVALID_CALIB_TEMP);
convert_int3v_int16(ret, ret_v);
compare_int3v_eps(exp_v, ret_v, 64);
}
/**
* Test set accelerometer offset with and without rotation. Also test behaviour
* on I2C error.
*/
ZTEST_USER(bmi260, test_bmi_acc_set_offset)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int16_t input_v[3] = { 0, 0, 0 };
int16_t temp = 0;
intv3_t ret_v;
intv3_t exp_v;
uint8_t nv_c;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
/* Test fail on NV CONF register read and write */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_NV_CONF);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
i2c_common_emul_set_write_fail_reg(common_data, BMI260_NV_CONF);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test fail on offset write */
i2c_common_emul_set_write_fail_reg(common_data, BMI160_OFFSET_ACC70);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
BMI160_OFFSET_ACC70 + 1);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
BMI160_OFFSET_ACC70 + 2);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Setup NV_CONF register value */
bmi_emul_set_reg(emul, BMI260_NV_CONF, 0x7);
/* Set input offset */
exp_v[0] = BMI_EMUL_1G / 10;
exp_v[1] = BMI_EMUL_1G / 20;
exp_v[2] = -(int)BMI_EMUL_1G / 30;
/* BMI driver accept value in mg units */
input_v[0] = 1000 / 10;
input_v[1] = 1000 / 20;
input_v[2] = -1000 / 30;
/* Disable rotation */
ms->rot_standard_ref = NULL;
/* Test set offset without rotation */
zassert_equal(EC_SUCCESS, ms->drv->set_offset(ms, input_v, temp));
get_emul_acc_offset(emul, ret_v);
/*
* Depending on used range, accelerometer values may be up to 6 bits
* more accurate then offset value resolution.
*/
compare_int3v_eps(exp_v, ret_v, 64);
nv_c = bmi_emul_get_reg(emul, BMI260_NV_CONF);
/* Only ACC_OFFSET_EN bit should be changed */
zassert_equal(0x7 | BMI260_ACC_OFFSET_EN, nv_c,
"Expected 0x%x, got 0x%x", 0x7 | BMI260_ACC_OFFSET_EN,
nv_c);
/* Setup NV_CONF register value */
bmi_emul_set_reg(emul, BMI260_NV_CONF, 0);
/* Setup rotation and rotate input for set_offset function */
ms->rot_standard_ref = &test_rotation;
convert_int3v_int16(input_v, ret_v);
rotate_int3v_by_test_rotation(ret_v);
convert_int3v_int16(ret_v, input_v);
/* Test set offset with rotation */
zassert_equal(EC_SUCCESS, ms->drv->set_offset(ms, input_v, temp));
get_emul_acc_offset(emul, ret_v);
compare_int3v_eps(exp_v, ret_v, 64);
nv_c = bmi_emul_get_reg(emul, BMI260_NV_CONF);
/* Only ACC_OFFSET_EN bit should be changed */
zassert_equal(BMI260_ACC_OFFSET_EN, nv_c, "Expected 0x%x, got 0x%x",
BMI260_ACC_OFFSET_EN, nv_c);
}
/**
* Test set gyroscope offset with and without rotation. Also test behaviour
* on I2C error.
*/
ZTEST_USER(bmi260, test_bmi_gyr_set_offset)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int16_t input_v[3];
int16_t temp = 0;
intv3_t ret_v;
intv3_t exp_v;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Test fail on OFFSET EN GYR98 register read and write */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_OFFSET_EN_GYR98);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
i2c_common_emul_set_write_fail_reg(common_data, BMI260_OFFSET_EN_GYR98);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test fail on offset write */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_OFFSET_GYR70);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
BMI260_OFFSET_GYR70 + 1);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
BMI260_OFFSET_GYR70 + 2);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_offset(ms, input_v, temp),
NULL);
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Set input offset */
exp_v[0] = BMI_EMUL_125_DEG_S / 100;
exp_v[1] = BMI_EMUL_125_DEG_S / 200;
exp_v[2] = -(int)BMI_EMUL_125_DEG_S / 300;
/* BMI driver accept value in mdeg/s units */
input_v[0] = 125000 / 100;
input_v[1] = 125000 / 200;
input_v[2] = -125000 / 300;
/* Disable rotation */
ms->rot_standard_ref = NULL;
/* Test set offset without rotation */
zassert_equal(EC_SUCCESS, ms->drv->set_offset(ms, input_v, temp));
get_emul_gyr_offset(emul, ret_v);
/*
* Depending on used range, gyroscope values may be up to 4 bits
* more accurate then offset value resolution.
*/
compare_int3v_eps(exp_v, ret_v, 32);
/* Gyroscope offset should be enabled */
zassert_true(bmi_emul_get_reg(emul, BMI260_OFFSET_EN_GYR98) &
BMI260_OFFSET_GYRO_EN,
NULL);
/* Setup rotation and rotate input for set_offset function */
ms->rot_standard_ref = &test_rotation;
convert_int3v_int16(input_v, ret_v);
rotate_int3v_by_test_rotation(ret_v);
convert_int3v_int16(ret_v, input_v);
/* Test set offset with rotation */
zassert_equal(EC_SUCCESS, ms->drv->set_offset(ms, input_v, temp));
get_emul_gyr_offset(emul, ret_v);
compare_int3v_eps(exp_v, ret_v, 32);
zassert_true(bmi_emul_get_reg(emul, BMI260_OFFSET_EN_GYR98) &
BMI260_OFFSET_GYRO_EN,
NULL);
}
/**
* Try to set accelerometer range and check if expected range was set
* in driver and in emulator.
*/
static void check_set_acc_range_f(const struct emul *emul,
struct motion_sensor_t *ms, int range,
int rnd, int exp_range, int line)
{
uint8_t exp_range_reg;
uint8_t range_reg;
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, range, rnd),
"set_range failed; line: %d", line);
zassert_equal(exp_range, ms->current_range,
"Expected range %d, got %d; line %d", exp_range,
ms->current_range, line);
range_reg = bmi_emul_get_reg(emul, BMI260_ACC_RANGE);
switch (exp_range) {
case 2:
exp_range_reg = BMI260_GSEL_2G;
break;
case 4:
exp_range_reg = BMI260_GSEL_4G;
break;
case 8:
exp_range_reg = BMI260_GSEL_8G;
break;
case 16:
exp_range_reg = BMI260_GSEL_16G;
break;
default:
/* Unknown expected range */
zassert_unreachable(
"Expected range %d not supported by device; line %d",
exp_range, line);
return;
}
zassert_equal(exp_range_reg, range_reg,
"Expected range reg 0x%x, got 0x%x; line %d",
exp_range_reg, range_reg, line);
}
#define check_set_acc_range(emul, ms, range, rnd, exp_range) \
check_set_acc_range_f(emul, ms, range, rnd, exp_range, __LINE__)
/** Test set accelerometer range with and without I2C errors */
ZTEST_USER(bmi260, test_bmi_acc_set_range)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int start_range;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
/* Setup starting range, shouldn't be changed on error */
start_range = 2;
ms->current_range = start_range;
bmi_emul_set_reg(emul, BMI260_ACC_RANGE, BMI260_GSEL_2G);
/* Setup emulator fail on write */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_ACC_RANGE);
/* Test fail on write */
zassert_equal(EC_ERROR_INVAL, ms->drv->set_range(ms, 12, 0));
zassert_equal(start_range, ms->current_range);
zassert_equal(BMI260_GSEL_2G, bmi_emul_get_reg(emul, BMI260_ACC_RANGE),
NULL);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_range(ms, 12, 1));
zassert_equal(start_range, ms->current_range);
zassert_equal(BMI260_GSEL_2G, bmi_emul_get_reg(emul, BMI260_ACC_RANGE),
NULL);
/* Do not fail on write */
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test setting range with rounding down */
check_set_acc_range(emul, ms, 1, 0, 2);
check_set_acc_range(emul, ms, 2, 0, 2);
check_set_acc_range(emul, ms, 3, 0, 2);
check_set_acc_range(emul, ms, 4, 0, 4);
check_set_acc_range(emul, ms, 5, 0, 4);
check_set_acc_range(emul, ms, 6, 0, 4);
check_set_acc_range(emul, ms, 7, 0, 4);
check_set_acc_range(emul, ms, 8, 0, 8);
check_set_acc_range(emul, ms, 9, 0, 8);
check_set_acc_range(emul, ms, 15, 0, 8);
check_set_acc_range(emul, ms, 16, 0, 16);
check_set_acc_range(emul, ms, 17, 0, 16);
/* Test setting range with rounding up */
check_set_acc_range(emul, ms, 1, 1, 2);
check_set_acc_range(emul, ms, 2, 1, 2);
check_set_acc_range(emul, ms, 3, 1, 4);
check_set_acc_range(emul, ms, 4, 1, 4);
check_set_acc_range(emul, ms, 5, 1, 8);
check_set_acc_range(emul, ms, 6, 1, 8);
check_set_acc_range(emul, ms, 7, 1, 8);
check_set_acc_range(emul, ms, 8, 1, 8);
check_set_acc_range(emul, ms, 9, 1, 16);
check_set_acc_range(emul, ms, 15, 1, 16);
check_set_acc_range(emul, ms, 16, 1, 16);
check_set_acc_range(emul, ms, 17, 1, 16);
}
/**
* Try to set gyroscope range and check if expected range was set in driver and
* in emulator.
*/
static void check_set_gyr_range_f(const struct emul *emul,
struct motion_sensor_t *ms, int range,
int rnd, int exp_range, int line)
{
uint8_t exp_range_reg;
uint8_t range_reg;
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, range, rnd),
"set_range failed; line: %d", line);
zassert_equal(exp_range, ms->current_range,
"Expected range %d, got %d; line %d", exp_range,
ms->current_range, line);
range_reg = bmi_emul_get_reg(emul, BMI260_GYR_RANGE);
switch (exp_range) {
case 125:
exp_range_reg = BMI260_DPS_SEL_125;
break;
case 250:
exp_range_reg = BMI260_DPS_SEL_250;
break;
case 500:
exp_range_reg = BMI260_DPS_SEL_500;
break;
case 1000:
exp_range_reg = BMI260_DPS_SEL_1000;
break;
case 2000:
exp_range_reg = BMI260_DPS_SEL_2000;
break;
default:
/* Unknown expected range */
zassert_unreachable(
"Expected range %d not supported by device; line %d",
exp_range, line);
return;
}
zassert_equal(exp_range_reg, range_reg,
"Expected range reg 0x%x, got 0x%x; line %d",
exp_range_reg, range_reg, line);
}
#define check_set_gyr_range(emul, ms, range, rnd, exp_range) \
check_set_gyr_range_f(emul, ms, range, rnd, exp_range, __LINE__)
/** Test set gyroscope range with and without I2C errors */
ZTEST_USER(bmi260, test_bmi_gyr_set_range)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int start_range;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Setup starting range, shouldn't be changed on error */
start_range = 250;
ms->current_range = start_range;
bmi_emul_set_reg(emul, BMI260_GYR_RANGE, BMI260_DPS_SEL_250);
/* Setup emulator fail on write */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_GYR_RANGE);
/* Test fail on write */
zassert_equal(EC_ERROR_INVAL, ms->drv->set_range(ms, 125, 0));
zassert_equal(start_range, ms->current_range);
zassert_equal(BMI260_DPS_SEL_250,
bmi_emul_get_reg(emul, BMI260_GYR_RANGE), NULL);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_range(ms, 125, 1));
zassert_equal(start_range, ms->current_range);
zassert_equal(BMI260_DPS_SEL_250,
bmi_emul_get_reg(emul, BMI260_GYR_RANGE), NULL);
/* Do not fail on write */
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test setting range with rounding down */
check_set_gyr_range(emul, ms, 1, 0, 125);
check_set_gyr_range(emul, ms, 124, 0, 125);
check_set_gyr_range(emul, ms, 125, 0, 125);
check_set_gyr_range(emul, ms, 126, 0, 125);
check_set_gyr_range(emul, ms, 249, 0, 125);
check_set_gyr_range(emul, ms, 250, 0, 250);
check_set_gyr_range(emul, ms, 251, 0, 250);
check_set_gyr_range(emul, ms, 499, 0, 250);
check_set_gyr_range(emul, ms, 500, 0, 500);
check_set_gyr_range(emul, ms, 501, 0, 500);
check_set_gyr_range(emul, ms, 999, 0, 500);
check_set_gyr_range(emul, ms, 1000, 0, 1000);
check_set_gyr_range(emul, ms, 1001, 0, 1000);
check_set_gyr_range(emul, ms, 1999, 0, 1000);
check_set_gyr_range(emul, ms, 2000, 0, 2000);
check_set_gyr_range(emul, ms, 2001, 0, 2000);
/* Test setting range with rounding up */
check_set_gyr_range(emul, ms, 1, 1, 125);
check_set_gyr_range(emul, ms, 124, 1, 125);
check_set_gyr_range(emul, ms, 125, 1, 125);
check_set_gyr_range(emul, ms, 126, 1, 250);
check_set_gyr_range(emul, ms, 249, 1, 250);
check_set_gyr_range(emul, ms, 250, 1, 250);
check_set_gyr_range(emul, ms, 251, 1, 500);
check_set_gyr_range(emul, ms, 499, 1, 500);
check_set_gyr_range(emul, ms, 500, 1, 500);
check_set_gyr_range(emul, ms, 501, 1, 1000);
check_set_gyr_range(emul, ms, 999, 1, 1000);
check_set_gyr_range(emul, ms, 1000, 1, 1000);
check_set_gyr_range(emul, ms, 1001, 1, 2000);
check_set_gyr_range(emul, ms, 1999, 1, 2000);
check_set_gyr_range(emul, ms, 2000, 1, 2000);
check_set_gyr_range(emul, ms, 2001, 1, 2000);
}
/** Test get resolution of acclerometer and gyroscope sensor */
ZTEST_USER(bmi260, test_bmi_get_resolution)
{
struct motion_sensor_t *ms;
/* Test accelerometer */
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
/* Resolution should be always 16 bits */
zassert_equal(16, ms->drv->get_resolution(ms));
/* Test gyroscope */
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Resolution should be always 16 bits */
zassert_equal(16, ms->drv->get_resolution(ms));
}
/**
* Try to set accelerometer data rate and check if expected rate was set
* in driver and in emulator.
*/
static void check_set_acc_rate_f(const struct emul *emul,
struct motion_sensor_t *ms, int rate, int rnd,
int exp_rate, int line)
{
uint8_t exp_rate_reg;
uint8_t rate_reg;
int drv_rate;
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, rate, rnd),
"set_data_rate failed; line: %d", line);
drv_rate = ms->drv->get_data_rate(ms);
zassert_equal(exp_rate, drv_rate, "Expected rate %d, got %d; line %d",
exp_rate, drv_rate, line);
rate_reg = bmi_emul_get_reg(emul, BMI260_ACC_CONF);
rate_reg &= BMI_ODR_MASK;
switch (exp_rate) {
case 12500:
exp_rate_reg = 0x5;
break;
case 25000:
exp_rate_reg = 0x6;
break;
case 50000:
exp_rate_reg = 0x7;
break;
case 100000:
exp_rate_reg = 0x8;
break;
case 200000:
exp_rate_reg = 0x9;
break;
case 400000:
exp_rate_reg = 0xa;
break;
case 800000:
exp_rate_reg = 0xb;
break;
case 1600000:
exp_rate_reg = 0xc;
break;
default:
/* Unknown expected rate */
zassert_unreachable(
"Expected rate %d not supported by device; line %d",
exp_rate, line);
return;
}
zassert_equal(exp_rate_reg, rate_reg,
"Expected rate reg 0x%x, got 0x%x; line %d", exp_rate_reg,
rate_reg, line);
}
#define check_set_acc_rate(emul, ms, rate, rnd, exp_rate) \
check_set_acc_rate_f(emul, ms, rate, rnd, exp_rate, __LINE__)
/** Test set and get accelerometer rate with and without I2C errors */
ZTEST_USER(bmi260, test_bmi_acc_rate)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
uint8_t reg_rate;
uint8_t pwr_ctrl;
int drv_rate;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
/* Test setting rate with rounding down */
check_set_acc_rate(emul, ms, 12500, 0, 12500);
check_set_acc_rate(emul, ms, 12501, 0, 12500);
check_set_acc_rate(emul, ms, 24999, 0, 12500);
check_set_acc_rate(emul, ms, 25000, 0, 25000);
check_set_acc_rate(emul, ms, 25001, 0, 25000);
check_set_acc_rate(emul, ms, 49999, 0, 25000);
check_set_acc_rate(emul, ms, 50000, 0, 50000);
check_set_acc_rate(emul, ms, 50001, 0, 50000);
check_set_acc_rate(emul, ms, 99999, 0, 50000);
check_set_acc_rate(emul, ms, 100000, 0, 100000);
check_set_acc_rate(emul, ms, 100001, 0, 100000);
check_set_acc_rate(emul, ms, 199999, 0, 100000);
check_set_acc_rate(emul, ms, 200000, 0, 200000);
check_set_acc_rate(emul, ms, 200001, 0, 200000);
check_set_acc_rate(emul, ms, 399999, 0, 200000);
/*
* We cannot test frequencies from 400000 to 1600000 because
* CONFIG_EC_MAX_SENSOR_FREQ_MILLIHZ is set to 250000
*/
/* Test setting rate with rounding up */
check_set_acc_rate(emul, ms, 6251, 1, 12500);
check_set_acc_rate(emul, ms, 12499, 1, 12500);
check_set_acc_rate(emul, ms, 12500, 1, 12500);
check_set_acc_rate(emul, ms, 12501, 1, 25000);
check_set_acc_rate(emul, ms, 24999, 1, 25000);
check_set_acc_rate(emul, ms, 25000, 1, 25000);
check_set_acc_rate(emul, ms, 25001, 1, 50000);
check_set_acc_rate(emul, ms, 49999, 1, 50000);
check_set_acc_rate(emul, ms, 50000, 1, 50000);
check_set_acc_rate(emul, ms, 50001, 1, 100000);
check_set_acc_rate(emul, ms, 99999, 1, 100000);
check_set_acc_rate(emul, ms, 100000, 1, 100000);
check_set_acc_rate(emul, ms, 100001, 1, 200000);
check_set_acc_rate(emul, ms, 199999, 1, 200000);
check_set_acc_rate(emul, ms, 200000, 1, 200000);
/* Test out of range rate with rounding down */
zassert_equal(EC_RES_INVALID_PARAM, ms->drv->set_data_rate(ms, 1, 0),
NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 12499, 0), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 400000, 0), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 2000000, 0), NULL);
/* Test out of range rate with rounding up */
zassert_equal(EC_RES_INVALID_PARAM, ms->drv->set_data_rate(ms, 1, 1),
NULL);
zassert_equal(EC_RES_INVALID_PARAM, ms->drv->set_data_rate(ms, 6250, 1),
NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 200001, 1), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 400000, 1), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 2000000, 1), NULL);
/* Current rate shouldn't be changed on error */
drv_rate = ms->drv->get_data_rate(ms);
reg_rate = bmi_emul_get_reg(emul, BMI260_ACC_CONF);
/* Setup emulator fail on read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_CONF);
/* Test fail on read */
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 0),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_ACC_CONF));
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 1),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_ACC_CONF));
/* Do not fail on read */
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Setup emulator fail on write */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_ACC_CONF);
/* Test fail on write */
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 0),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_ACC_CONF));
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 1),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_ACC_CONF));
/* Do not fail on write */
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test disabling sensor */
bmi_emul_set_reg(emul, BMI260_PWR_CTRL,
BMI260_AUX_EN | BMI260_GYR_EN | BMI260_ACC_EN);
bmi_emul_set_reg(emul, BMI260_ACC_CONF, BMI260_FILTER_PERF);
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, 0, 0));
pwr_ctrl = bmi_emul_get_reg(emul, BMI260_PWR_CTRL);
reg_rate = bmi_emul_get_reg(emul, BMI260_ACC_CONF);
zassert_equal(BMI260_AUX_EN | BMI260_GYR_EN, pwr_ctrl);
zassert_true(!(reg_rate & BMI260_FILTER_PERF));
/* Test enabling sensor */
bmi_emul_set_reg(emul, BMI260_PWR_CTRL, 0);
bmi_emul_set_reg(emul, BMI260_ACC_CONF, 0);
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, 50000, 0));
pwr_ctrl = bmi_emul_get_reg(emul, BMI260_PWR_CTRL);
reg_rate = bmi_emul_get_reg(emul, BMI260_ACC_CONF);
zassert_equal(BMI260_ACC_EN, pwr_ctrl);
zassert_true(reg_rate & BMI260_FILTER_PERF);
/* Test disabling sensor (by setting rate to 0) but failing. */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_PWR_CTRL);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 0, 0),
"Did not properly handle failed power down.");
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test enabling sensor but failing. (after first disabling it) */
ms->drv->set_data_rate(ms, 0, 0);
i2c_common_emul_set_write_fail_reg(common_data, BMI260_PWR_CTRL);
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 0),
"Did not properly handle failed power up.");
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
}
/**
* Try to set gyroscope data rate and check if expected rate was set
* in driver and in emulator.
*/
static void check_set_gyr_rate_f(const struct emul *emul,
struct motion_sensor_t *ms, int rate, int rnd,
int exp_rate, int line)
{
uint8_t exp_rate_reg;
uint8_t rate_reg;
int drv_rate;
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, rate, rnd),
"set_data_rate failed; line: %d", line);
drv_rate = ms->drv->get_data_rate(ms);
zassert_equal(exp_rate, drv_rate, "Expected rate %d, got %d; line %d",
exp_rate, drv_rate, line);
rate_reg = bmi_emul_get_reg(emul, BMI260_GYR_CONF);
rate_reg &= BMI_ODR_MASK;
switch (exp_rate) {
case 25000:
exp_rate_reg = 0x6;
break;
case 50000:
exp_rate_reg = 0x7;
break;
case 100000:
exp_rate_reg = 0x8;
break;
case 200000:
exp_rate_reg = 0x9;
break;
case 400000:
exp_rate_reg = 0xa;
break;
case 800000:
exp_rate_reg = 0xb;
break;
case 1600000:
exp_rate_reg = 0xc;
break;
case 3200000:
exp_rate_reg = 0xc;
break;
default:
/* Unknown expected rate */
zassert_unreachable(
"Expected rate %d not supported by device; line %d",
exp_rate, line);
return;
}
zassert_equal(exp_rate_reg, rate_reg,
"Expected rate reg 0x%x, got 0x%x; line %d", exp_rate_reg,
rate_reg, line);
}
#define check_set_gyr_rate(emul, ms, rate, rnd, exp_rate) \
check_set_gyr_rate_f(emul, ms, rate, rnd, exp_rate, __LINE__)
/** Test set and get gyroscope rate with and without I2C errors */
ZTEST_USER(bmi260, test_bmi_gyr_rate)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
uint8_t reg_rate;
uint8_t pwr_ctrl;
int drv_rate;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Test setting rate with rounding down */
check_set_gyr_rate(emul, ms, 25000, 0, 25000);
check_set_gyr_rate(emul, ms, 25001, 0, 25000);
check_set_gyr_rate(emul, ms, 49999, 0, 25000);
check_set_gyr_rate(emul, ms, 50000, 0, 50000);
check_set_gyr_rate(emul, ms, 50001, 0, 50000);
check_set_gyr_rate(emul, ms, 99999, 0, 50000);
check_set_gyr_rate(emul, ms, 100000, 0, 100000);
check_set_gyr_rate(emul, ms, 100001, 0, 100000);
check_set_gyr_rate(emul, ms, 199999, 0, 100000);
check_set_gyr_rate(emul, ms, 200000, 0, 200000);
check_set_gyr_rate(emul, ms, 200001, 0, 200000);
check_set_gyr_rate(emul, ms, 399999, 0, 200000);
/*
* We cannot test frequencies from 400000 to 3200000 because
* CONFIG_EC_MAX_SENSOR_FREQ_MILLIHZ is set to 250000
*/
/* Test setting rate with rounding up */
check_set_gyr_rate(emul, ms, 12501, 1, 25000);
check_set_gyr_rate(emul, ms, 24999, 1, 25000);
check_set_gyr_rate(emul, ms, 25000, 1, 25000);
check_set_gyr_rate(emul, ms, 25001, 1, 50000);
check_set_gyr_rate(emul, ms, 49999, 1, 50000);
check_set_gyr_rate(emul, ms, 50000, 1, 50000);
check_set_gyr_rate(emul, ms, 50001, 1, 100000);
check_set_gyr_rate(emul, ms, 99999, 1, 100000);
check_set_gyr_rate(emul, ms, 100000, 1, 100000);
check_set_gyr_rate(emul, ms, 100001, 1, 200000);
check_set_gyr_rate(emul, ms, 199999, 1, 200000);
check_set_gyr_rate(emul, ms, 200000, 1, 200000);
/* Test out of range rate with rounding down */
zassert_equal(EC_RES_INVALID_PARAM, ms->drv->set_data_rate(ms, 1, 0),
NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 24999, 0), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 400000, 0), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 4000000, 0), NULL);
/* Test out of range rate with rounding up */
zassert_equal(EC_RES_INVALID_PARAM, ms->drv->set_data_rate(ms, 1, 1),
NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 12499, 1), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 200001, 1), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 400000, 1), NULL);
zassert_equal(EC_RES_INVALID_PARAM,
ms->drv->set_data_rate(ms, 4000000, 1), NULL);
/* Current rate shouldn't be changed on error */
drv_rate = ms->drv->get_data_rate(ms);
reg_rate = bmi_emul_get_reg(emul, BMI260_GYR_CONF);
/* Setup emulator fail on read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_CONF);
/* Test fail on read */
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 0),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_GYR_CONF));
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 1),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_GYR_CONF));
/* Do not fail on read */
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Setup emulator fail on write */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_GYR_CONF);
/* Test fail on write */
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 0),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_GYR_CONF));
zassert_equal(EC_ERROR_INVAL, ms->drv->set_data_rate(ms, 50000, 1),
NULL);
zassert_equal(drv_rate, ms->drv->get_data_rate(ms));
zassert_equal(reg_rate, bmi_emul_get_reg(emul, BMI260_GYR_CONF));
/* Do not fail on write */
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test disabling sensor */
bmi_emul_set_reg(emul, BMI260_PWR_CTRL,
BMI260_AUX_EN | BMI260_GYR_EN | BMI260_ACC_EN);
bmi_emul_set_reg(emul, BMI260_GYR_CONF,
BMI260_FILTER_PERF | BMI260_GYR_NOISE_PERF);
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, 0, 0));
pwr_ctrl = bmi_emul_get_reg(emul, BMI260_PWR_CTRL);
reg_rate = bmi_emul_get_reg(emul, BMI260_GYR_CONF);
zassert_equal(BMI260_AUX_EN | BMI260_ACC_EN, pwr_ctrl);
zassert_true(!(reg_rate & (BMI260_FILTER_PERF | BMI260_GYR_NOISE_PERF)),
NULL);
/* Test enabling sensor */
bmi_emul_set_reg(emul, BMI260_PWR_CTRL, 0);
bmi_emul_set_reg(emul, BMI260_GYR_CONF, 0);
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, 50000, 0));
pwr_ctrl = bmi_emul_get_reg(emul, BMI260_PWR_CTRL);
reg_rate = bmi_emul_get_reg(emul, BMI260_GYR_CONF);
zassert_equal(BMI260_GYR_EN, pwr_ctrl);
zassert_true(reg_rate & (BMI260_FILTER_PERF | BMI260_GYR_NOISE_PERF),
NULL);
}
/**
* Test setting and getting scale in accelerometer and gyroscope sensors.
* Correct appling scale to results is checked in "read" test.
*/
ZTEST_USER(bmi260, test_bmi_scale)
{
struct motion_sensor_t *ms;
int16_t ret_scale[3];
int16_t exp_scale[3] = { 100, 231, 421 };
int16_t t;
/* Test accelerometer */
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
zassert_equal(EC_SUCCESS, ms->drv->set_scale(ms, exp_scale, 0));
zassert_equal(EC_SUCCESS, ms->drv->get_scale(ms, ret_scale, &t));
zassert_equal(t, (int16_t)EC_MOTION_SENSE_INVALID_CALIB_TEMP);
zassert_equal(exp_scale[0], ret_scale[0]);
zassert_equal(exp_scale[1], ret_scale[1]);
zassert_equal(exp_scale[2], ret_scale[2]);
/* Test gyroscope */
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
zassert_equal(EC_SUCCESS, ms->drv->set_scale(ms, exp_scale, 0));
zassert_equal(EC_SUCCESS, ms->drv->get_scale(ms, ret_scale, &t));
zassert_equal(t, (int16_t)EC_MOTION_SENSE_INVALID_CALIB_TEMP);
zassert_equal(exp_scale[0], ret_scale[0]);
zassert_equal(exp_scale[1], ret_scale[1]);
zassert_equal(exp_scale[2], ret_scale[2]);
}
/** Test reading temperature using accelerometer and gyroscope sensors */
ZTEST_USER(bmi260, test_bmi_read_temp)
{
struct motion_sensor_t *ms_acc, *ms_gyr;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int ret_temp;
int exp_temp;
common_data = emul_bmi_get_i2c_common_data(emul);
ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
ms_gyr = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Setup emulator fail on read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_TEMPERATURE_0);
zassert_equal(EC_ERROR_NOT_POWERED,
ms_acc->drv->read_temp(ms_acc, &ret_temp), NULL);
zassert_equal(EC_ERROR_NOT_POWERED,
ms_gyr->drv->read_temp(ms_gyr, &ret_temp), NULL);
i2c_common_emul_set_read_fail_reg(common_data, BMI260_TEMPERATURE_1);
zassert_equal(EC_ERROR_NOT_POWERED,
ms_acc->drv->read_temp(ms_acc, &ret_temp), NULL);
zassert_equal(EC_ERROR_NOT_POWERED,
ms_gyr->drv->read_temp(ms_gyr, &ret_temp), NULL);
/* Do not fail on read */
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Fail on invalid temperature */
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_0, 0x00);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_1, 0x80);
zassert_equal(EC_ERROR_NOT_POWERED,
ms_acc->drv->read_temp(ms_acc, &ret_temp), NULL);
zassert_equal(EC_ERROR_NOT_POWERED,
ms_gyr->drv->read_temp(ms_gyr, &ret_temp), NULL);
/*
* Test correct values. Both motion sensors should return the same
* temperature.
*/
exp_temp = C_TO_K(23);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_0, 0x00);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_1, 0x00);
zassert_equal(EC_SUCCESS, ms_acc->drv->read_temp(ms_acc, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
zassert_equal(EC_SUCCESS, ms_gyr->drv->read_temp(ms_gyr, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
exp_temp = C_TO_K(87);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_0, 0xff);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_1, 0x7f);
zassert_equal(EC_SUCCESS, ms_acc->drv->read_temp(ms_acc, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
zassert_equal(EC_SUCCESS, ms_gyr->drv->read_temp(ms_gyr, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
exp_temp = C_TO_K(-41);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_0, 0x01);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_1, 0x80);
zassert_equal(EC_SUCCESS, ms_acc->drv->read_temp(ms_acc, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
zassert_equal(EC_SUCCESS, ms_gyr->drv->read_temp(ms_gyr, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
exp_temp = C_TO_K(47);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_0, 0x00);
bmi_emul_set_reg(emul, BMI260_TEMPERATURE_1, 0x30);
zassert_equal(EC_SUCCESS, ms_acc->drv->read_temp(ms_acc, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
zassert_equal(EC_SUCCESS, ms_gyr->drv->read_temp(ms_gyr, &ret_temp),
NULL);
zassert_equal(exp_temp, ret_temp);
}
/** Test reading accelerometer sensor data */
ZTEST_USER(bmi260, test_bmi_acc_read)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
intv3_t ret_v;
intv3_t exp_v;
int16_t scale[3] = { MOTION_SENSE_DEFAULT_SCALE,
MOTION_SENSE_DEFAULT_SCALE,
MOTION_SENSE_DEFAULT_SCALE };
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
/* Set offset 0 to simplify test */
bmi_emul_set_off(emul, BMI_EMUL_ACC_X, 0);
bmi_emul_set_off(emul, BMI_EMUL_ACC_Y, 0);
bmi_emul_set_off(emul, BMI_EMUL_ACC_Z, 0);
/* Fail on read status */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_STATUS);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* When not ready, driver should return saved raw value */
exp_v[0] = 100;
exp_v[1] = 200;
exp_v[2] = 300;
ms->raw_xyz[0] = exp_v[0];
ms->raw_xyz[1] = exp_v[1];
ms->raw_xyz[2] = exp_v[2];
/* Status not ready */
bmi_emul_set_reg(emul, BMI260_STATUS, 0);
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
compare_int3v(exp_v, ret_v);
/* Status only GYR ready */
bmi_emul_set_reg(emul, BMI260_STATUS, BMI260_DRDY_GYR);
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
compare_int3v(exp_v, ret_v);
/* Status ACC ready */
bmi_emul_set_reg(emul, BMI260_STATUS, BMI260_DRDY_ACC);
/* Set input accelerometer values */
exp_v[0] = BMI_EMUL_1G / 10;
exp_v[1] = BMI_EMUL_1G / 20;
exp_v[2] = -(int)BMI_EMUL_1G / 30;
set_emul_acc(emul, exp_v);
/* Disable rotation */
ms->rot_standard_ref = NULL;
/* Set scale */
zassert_equal(EC_SUCCESS, ms->drv->set_scale(ms, scale, 0));
/* Set range to 2G */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 2, 0));
/* Test read without rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_acc_to_emul(ret_v, 2, ret_v);
compare_int3v(exp_v, ret_v);
/* Set range to 4G */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 4, 0));
/* Test read without rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_acc_to_emul(ret_v, 4, ret_v);
compare_int3v(exp_v, ret_v);
/* Setup rotation and rotate expected vector */
ms->rot_standard_ref = &test_rotation;
rotate_int3v_by_test_rotation(exp_v);
/* Set range to 2G */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 2, 0));
/* Test read with rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_acc_to_emul(ret_v, 2, ret_v);
compare_int3v(exp_v, ret_v);
/* Set range to 4G */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 4, 0));
/* Test read with rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_acc_to_emul(ret_v, 4, ret_v);
compare_int3v(exp_v, ret_v);
/* Fail on read of data registers */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_X_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_X_H_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_Y_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_Y_H_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_Z_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_Z_H_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
ms->rot_standard_ref = NULL;
}
/** Test reading gyroscope sensor data */
ZTEST_USER(bmi260, test_bmi_gyr_read)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
intv3_t ret_v;
intv3_t exp_v;
int16_t scale[3] = { MOTION_SENSE_DEFAULT_SCALE,
MOTION_SENSE_DEFAULT_SCALE,
MOTION_SENSE_DEFAULT_SCALE };
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Set offset 0 to simplify test */
bmi_emul_set_off(emul, BMI_EMUL_GYR_X, 0);
bmi_emul_set_off(emul, BMI_EMUL_GYR_Y, 0);
bmi_emul_set_off(emul, BMI_EMUL_GYR_Z, 0);
/* Fail on read status */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_STATUS);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* When not ready, driver should return saved raw value */
exp_v[0] = 100;
exp_v[1] = 200;
exp_v[2] = 300;
ms->raw_xyz[0] = exp_v[0];
ms->raw_xyz[1] = exp_v[1];
ms->raw_xyz[2] = exp_v[2];
/* Status not ready */
bmi_emul_set_reg(emul, BMI260_STATUS, 0);
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
compare_int3v(exp_v, ret_v);
/* Status only ACC ready */
bmi_emul_set_reg(emul, BMI260_STATUS, BMI260_DRDY_ACC);
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
compare_int3v(exp_v, ret_v);
/* Status GYR ready */
bmi_emul_set_reg(emul, BMI260_STATUS, BMI260_DRDY_GYR);
/* Set input accelerometer values */
exp_v[0] = BMI_EMUL_125_DEG_S / 10;
exp_v[1] = BMI_EMUL_125_DEG_S / 20;
exp_v[2] = -(int)BMI_EMUL_125_DEG_S / 30;
set_emul_gyr(emul, exp_v);
/* Disable rotation */
ms->rot_standard_ref = NULL;
/* Set scale */
zassert_equal(EC_SUCCESS, ms->drv->set_scale(ms, scale, 0));
/* Set range to 125°/s */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 125, 0));
/* Test read without rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_gyr_to_emul(ret_v, 125, ret_v);
compare_int3v(exp_v, ret_v);
/* Set range to 1000°/s */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 1000, 0));
/* Test read without rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_gyr_to_emul(ret_v, 1000, ret_v);
compare_int3v(exp_v, ret_v);
/* Setup rotation and rotate expected vector */
ms->rot_standard_ref = &test_rotation;
rotate_int3v_by_test_rotation(exp_v);
/* Set range to 125°/s */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 125, 0));
/* Test read with rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_gyr_to_emul(ret_v, 125, ret_v);
compare_int3v(exp_v, ret_v);
/* Set range to 1000°/s */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, 1000, 0));
/* Test read with rotation */
zassert_equal(EC_SUCCESS, ms->drv->read(ms, ret_v));
drv_gyr_to_emul(ret_v, 1000, ret_v);
compare_int3v(exp_v, ret_v);
/* Fail on read of data registers */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_X_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_X_H_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_Y_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_Y_H_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_Z_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_Z_H_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->read(ms, ret_v));
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
ms->rot_standard_ref = NULL;
}
/** Test accelerometer calibration */
ZTEST_USER(bmi260, test_bmi_acc_perform_calib)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
intv3_t start_off;
intv3_t exp_off;
intv3_t ret_off;
int range;
int rate;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
bmi_init_emul();
/* Disable rotation */
ms->rot_standard_ref = NULL;
/* Range and rate cannot change after calibration */
range = 4;
rate = 50000;
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, range, 0));
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, rate, 0));
/* Set offset 0 */
start_off[0] = 0;
start_off[1] = 0;
start_off[2] = 0;
set_emul_acc_offset(emul, start_off);
/* Set input accelerometer values */
exp_off[0] = BMI_EMUL_1G / 10;
exp_off[1] = BMI_EMUL_1G / 20;
exp_off[2] = BMI_EMUL_1G - (int)BMI_EMUL_1G / 30;
set_emul_acc(emul, exp_off);
/* Expected offset is [-X, -Y, 1G - Z] */
exp_off[0] = -exp_off[0];
exp_off[1] = -exp_off[1];
exp_off[2] = BMI_EMUL_1G - exp_off[2];
/* Test success on disabling calibration */
zassert_equal(EC_SUCCESS, ms->drv->perform_calib(ms, 0));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on rate read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_CONF);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on status read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_STATUS);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on data not ready */
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
bmi_emul_set_reg(emul, BMI260_STATUS, 0);
zassert_equal(EC_ERROR_TIMEOUT, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Setup data status ready for rest of the test */
bmi_emul_set_reg(emul, BMI260_STATUS, BMI260_DRDY_ACC);
/* Test fail on data read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_ACC_X_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on setting offset */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_NV_CONF);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test successful offset compenastion */
zassert_equal(EC_SUCCESS, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
get_emul_acc_offset(emul, ret_off);
/*
* Depending on used range, accelerometer values may be up to 6 bits
* more accurate then offset value resolution.
*/
compare_int3v_eps(exp_off, ret_off, 64);
}
/** Test gyroscope calibration */
ZTEST_USER(bmi260, test_bmi_gyr_perform_calib)
{
struct motion_sensor_t *ms;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
intv3_t start_off;
intv3_t exp_off;
intv3_t ret_off;
int range;
int rate;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
bmi_init_emul();
/* Range and rate cannot change after calibration */
range = 125;
rate = 50000;
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, range, 0));
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, rate, 0));
/* Set offset 0 */
start_off[0] = 0;
start_off[1] = 0;
start_off[2] = 0;
set_emul_gyr_offset(emul, start_off);
/* Set input accelerometer values */
exp_off[0] = BMI_EMUL_125_DEG_S / 100;
exp_off[1] = BMI_EMUL_125_DEG_S / 200;
exp_off[2] = -(int)BMI_EMUL_125_DEG_S / 300;
set_emul_gyr(emul, exp_off);
/* Expected offset is [-X, -Y, -Z] */
exp_off[0] = -exp_off[0];
exp_off[1] = -exp_off[1];
exp_off[2] = -exp_off[2];
/* Test success on disabling calibration */
zassert_equal(EC_SUCCESS, ms->drv->perform_calib(ms, 0));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on rate read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_CONF);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on status read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_STATUS);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on data not ready */
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
bmi_emul_set_reg(emul, BMI260_STATUS, 0);
zassert_equal(EC_ERROR_TIMEOUT, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/*
* Setup data status ready for rest of the test. Gyroscope calibration
* should check DRDY_GYR bit, but current driver check only for ACC.
*/
bmi_emul_set_reg(emul, BMI260_STATUS,
BMI260_DRDY_ACC | BMI260_DRDY_GYR);
/* Test fail on data read */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_GYR_X_L_G);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
/* Test fail on setting offset */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_OFFSET_EN_GYR98);
zassert_equal(EC_ERROR_INVAL, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test successful offset compenastion */
zassert_equal(EC_SUCCESS, ms->drv->perform_calib(ms, 1));
zassert_equal(range, ms->current_range);
zassert_equal(rate, ms->drv->get_data_rate(ms));
get_emul_gyr_offset(emul, ret_off);
/*
* Depending on used range, gyroscope values may be up to 4 bits
* more accurate then offset value resolution.
*/
compare_int3v_eps(exp_off, ret_off, 32);
}
/**
* A custom fake to use with the `init_rom_map` mock that returns the
* value of `addr`
*/
static const void *init_rom_map_addr_passthru(const void *addr, int size)
{
return addr;
}
/** Test init function of BMI260 accelerometer and gyroscope sensors */
ZTEST_USER(bmi260, test_bmi_init)
{
struct motion_sensor_t *ms_acc, *ms_gyr;
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
common_data = emul_bmi_get_i2c_common_data(emul);
ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
ms_gyr = &motion_sensors[BMI_GYR_SENSOR_ID];
/* The mock should return whatever is passed in to its addr param */
RESET_FAKE(init_rom_map);
init_rom_map_fake.custom_fake = init_rom_map_addr_passthru;
bmi_init_emul();
}
/** Data for custom emulator read function used in FIFO test */
struct fifo_func_data {
uint16_t interrupts;
};
/**
* Custom emulator read function used in FIFO test. It sets interrupt registers
* to value passed as additional data. It sets interrupt registers to 0 after
* access.
*/
static int emul_fifo_func(const struct emul *emul, int reg, uint8_t *val,
int byte, void *data)
{
struct fifo_func_data *d = data;
if (reg + byte == BMI260_INT_STATUS_0) {
bmi_emul_set_reg(emul, BMI260_INT_STATUS_0,
d->interrupts & 0xff);
d->interrupts &= 0xff00;
} else if (reg + byte == BMI260_INT_STATUS_1) {
bmi_emul_set_reg(emul, BMI260_INT_STATUS_1,
(d->interrupts >> 8) & 0xff);
d->interrupts &= 0xff;
}
return 1;
}
/**
* Run irq handler on accelerometer sensor and check if committed data in FIFO
* match what was set in FIFO frames in emulator.
*/
static void check_fifo_f(struct motion_sensor_t *ms_acc,
struct motion_sensor_t *ms_gyr,
struct bmi_emul_frame *frame, int acc_range,
int gyr_range, int line)
{
struct ec_response_motion_sensor_data vector;
struct bmi_emul_frame *f_acc, *f_gyr;
uint32_t event = BMI_INT_EVENT;
uint16_t size;
intv3_t exp_v;
intv3_t ret_v;
/* Find first frame of acc and gyr type */
f_acc = frame;
while (f_acc != NULL && !(f_acc->type & BMI_EMUL_FRAME_ACC)) {
f_acc = f_acc->next;
}
f_gyr = frame;
while (f_gyr != NULL && !(f_gyr->type & BMI_EMUL_FRAME_GYR)) {
f_gyr = f_gyr->next;
}
/* Read FIFO in driver */
zassert_equal(EC_SUCCESS, ms_acc->drv->irq_handler(ms_acc, &event),
"Failed to read FIFO in irq handler, line %d", line);
/* Read all data committed to FIFO */
while (motion_sense_fifo_read(sizeof(vector), 1, &vector, &size)) {
/* Ignore timestamp frames */
if (vector.flags == MOTIONSENSE_SENSOR_FLAG_TIMESTAMP) {
continue;
}
/* Check acclerometer frames */
if (ms_acc - motion_sensors == vector.sensor_num) {
if (f_acc == NULL) {
zassert_unreachable(
"Not expected acclerometer data in FIFO, line %d",
line);
}
convert_int3v_int16(vector.data, ret_v);
drv_acc_to_emul(ret_v, acc_range, ret_v);
exp_v[0] = f_acc->acc_x;
exp_v[1] = f_acc->acc_y;
exp_v[2] = f_acc->acc_z;
compare_int3v_f(exp_v, ret_v, V_EPS, line);
f_acc = f_acc->next;
}
/* Check gyroscope frames */
if (ms_gyr - motion_sensors == vector.sensor_num) {
if (f_gyr == NULL) {
zassert_unreachable(
"Not expected gyroscope data in FIFO, line %d",
line);
}
convert_int3v_int16(vector.data, ret_v);
drv_gyr_to_emul(ret_v, gyr_range, ret_v);
exp_v[0] = f_gyr->gyr_x;
exp_v[1] = f_gyr->gyr_y;
exp_v[2] = f_gyr->gyr_z;
compare_int3v_f(exp_v, ret_v, V_EPS, line);
f_gyr = f_gyr->next;
}
}
/* Skip frames of different type at the end */
while (f_acc != NULL && !(f_acc->type & BMI_EMUL_FRAME_ACC)) {
f_acc = f_acc->next;
}
while (f_gyr != NULL && !(f_gyr->type & BMI_EMUL_FRAME_GYR)) {
f_gyr = f_gyr->next;
}
/* All frames are readed */
zassert_is_null(f_acc, "Not all accelerometer frames are read, line %d",
line);
zassert_is_null(f_gyr, "Not all gyroscope frames are read, line %d",
line);
}
#define check_fifo(ms_acc, ms_gyr, frame, acc_range, gyr_range) \
check_fifo_f(ms_acc, ms_gyr, frame, acc_range, gyr_range, __LINE__)
/** Test irq handler of accelerometer sensor */
ZTEST_USER(bmi260, test_bmi_acc_fifo)
{
struct motion_sensor_t *ms, *ms_gyr;
struct fifo_func_data func_data;
struct bmi_emul_frame f[3];
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
int gyr_range = 125;
int acc_range = 2;
int event;
common_data = emul_bmi_get_i2c_common_data(emul);
ms = &motion_sensors[BMI_ACC_SENSOR_ID];
ms_gyr = &motion_sensors[BMI_GYR_SENSOR_ID];
bmi_init_emul();
/* Need to be set to collect all data in FIFO */
ms->oversampling_ratio = 1;
ms_gyr->oversampling_ratio = 1;
/* Only BMI event should be handled */
event = 0x1234 & ~BMI_INT_EVENT;
zassert_equal(EC_ERROR_NOT_HANDLED, ms->drv->irq_handler(ms, &event),
NULL);
event = BMI_INT_EVENT;
/* Test fail to read interrupt status registers */
i2c_common_emul_set_read_fail_reg(common_data, BMI260_INT_STATUS_0);
zassert_equal(EC_ERROR_INVAL, ms->drv->irq_handler(ms, &event));
i2c_common_emul_set_read_fail_reg(common_data, BMI260_INT_STATUS_1);
zassert_equal(EC_ERROR_INVAL, ms->drv->irq_handler(ms, &event));
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Test no interrupt */
bmi_emul_set_reg(emul, BMI260_INT_STATUS_0, 0);
bmi_emul_set_reg(emul, BMI260_INT_STATUS_1, 0);
/* Enable sensor FIFO */
zassert_equal(EC_SUCCESS, ms->drv->set_data_rate(ms, 50000, 0));
/* Trigger irq handler and check results */
check_fifo(ms, ms_gyr, NULL, acc_range, gyr_range);
/* Set custom function for FIFO test */
i2c_common_emul_set_read_func(common_data, emul_fifo_func, &func_data);
/* Set range */
zassert_equal(EC_SUCCESS, ms->drv->set_range(ms, acc_range, 0));
zassert_equal(EC_SUCCESS, ms_gyr->drv->set_range(ms_gyr, gyr_range, 0),
NULL);
/* Setup single accelerometer frame */
f[0].type = BMI_EMUL_FRAME_ACC;
f[0].acc_x = BMI_EMUL_1G / 10;
f[0].acc_y = BMI_EMUL_1G / 20;
f[0].acc_z = -(int)BMI_EMUL_1G / 30;
f[0].next = NULL;
bmi_emul_append_frame(emul, f);
/* Setup interrupts register */
func_data.interrupts = BMI260_FWM_INT;
/* Trigger irq handler and check results */
check_fifo(ms, ms_gyr, f, acc_range, gyr_range);
/* Setup second accelerometer frame */
f[1].type = BMI_EMUL_FRAME_ACC;
f[1].acc_x = -(int)BMI_EMUL_1G / 40;
f[1].acc_y = BMI_EMUL_1G / 50;
f[1].acc_z = BMI_EMUL_1G / 60;
f[0].next = &(f[1]);
f[1].next = NULL;
bmi_emul_append_frame(emul, f);
/* Setup interrupts register */
func_data.interrupts = BMI260_FWM_INT;
/* Trigger irq handler and check results */
check_fifo(ms, ms_gyr, f, acc_range, gyr_range);
/* Enable sensor FIFO */
zassert_equal(EC_SUCCESS, ms_gyr->drv->set_data_rate(ms_gyr, 50000, 0),
NULL);
/* Setup first gyroscope frame (after two accelerometer frames) */
f[2].type = BMI_EMUL_FRAME_GYR;
f[2].gyr_x = -(int)BMI_EMUL_125_DEG_S / 100;
f[2].gyr_y = BMI_EMUL_125_DEG_S / 200;
f[2].gyr_z = BMI_EMUL_125_DEG_S / 300;
f[1].next = &(f[2]);
f[2].next = NULL;
bmi_emul_append_frame(emul, f);
/* Setup interrupts register */
func_data.interrupts = BMI260_FWM_INT;
/* Trigger irq handler and check results */
check_fifo(ms, ms_gyr, f, acc_range, gyr_range);
/* Setup second accelerometer frame to by gyroscope frame too */
f[1].type |= BMI_EMUL_FRAME_GYR;
f[1].gyr_x = -(int)BMI_EMUL_125_DEG_S / 300;
f[1].gyr_y = BMI_EMUL_125_DEG_S / 400;
f[1].gyr_z = BMI_EMUL_125_DEG_S / 500;
bmi_emul_append_frame(emul, f);
/* Setup interrupts register */
func_data.interrupts = BMI260_FWM_INT;
/* Trigger irq handler and check results */
check_fifo(ms, ms_gyr, f, acc_range, gyr_range);
/* Skip frame should be ignored by driver */
bmi_emul_set_skipped_frames(emul, 8);
bmi_emul_append_frame(emul, f);
/* Setup interrupts register */
func_data.interrupts = BMI260_FWM_INT;
/* Trigger irq handler and check results */
check_fifo(ms, ms_gyr, f, acc_range, gyr_range);
/* Setup second frame as an config frame */
f[1].type = BMI_EMUL_FRAME_CONFIG;
/* Indicate that accelerometer range changed */
f[1].config = 0x1;
bmi_emul_append_frame(emul, f);
/* Setup interrupts register */
func_data.interrupts = BMI260_FWM_INT;
/* Trigger irq handler and check results */
check_fifo(ms, ms_gyr, f, acc_range, gyr_range);
/* Remove custom emulator read function */
i2c_common_emul_set_read_func(common_data, NULL, NULL);
}
/** Test irq handler of gyroscope sensor */
ZTEST_USER(bmi260, test_bmi_gyr_fifo)
{
struct motion_sensor_t *ms;
uint32_t event;
ms = &motion_sensors[BMI_GYR_SENSOR_ID];
/* Interrupt shuldn't be triggered for gyroscope motion sense */
event = BMI_INT_EVENT;
zassert_equal(EC_ERROR_NOT_HANDLED, ms->drv->irq_handler(ms, &event),
NULL);
}
ZTEST_USER(bmi260, test_unsupported_configs)
{
/*
* This test checks that we properly handle passing in invalid sensor
* types or attempting unsupported operations on certain sensor types.
*/
struct motion_sensor_t ms_fake;
/* Part 1:
* Setting offset on anything that is not an accel or gyro is an error.
* Make a copy of the accelerometer motion sensor struct and modify its
* type to magnetometer for this test.
*/
memcpy(&ms_fake, &motion_sensors[BMI_ACC_SENSOR_ID], sizeof(ms_fake));
ms_fake.type = MOTIONSENSE_TYPE_MAG;
int16_t offset[3] = { 0 };
int ret =
ms_fake.drv->set_offset(&ms_fake, (const int16_t *)&offset, 0);
zassert_equal(
ret, EC_RES_INVALID_PARAM,
"Expected a return code of %d (EC_RES_INVALID_PARAM) but got %d",
EC_RES_INVALID_PARAM, ret);
/* Part 2:
* Running a calibration on a magnetometer is also not supported.
*/
memcpy(&ms_fake, &motion_sensors[BMI_ACC_SENSOR_ID], sizeof(ms_fake));
ms_fake.type = MOTIONSENSE_TYPE_MAG;
ret = ms_fake.drv->perform_calib(&ms_fake, 1);
zassert_equal(
ret, EC_RES_INVALID_PARAM,
"Expected a return code of %d (EC_RES_INVALID_PARAM) but got %d",
EC_RES_INVALID_PARAM, ret);
}
ZTEST_USER(bmi260, test_interrupt_handler)
{
/* The accelerometer interrupt handler simply sets an event flag for the
* motion sensing task. Make sure that flag starts cleared, fire the
* interrupt, and ensure the flag is set.
*/
atomic_t *mask;
mask = task_get_event_bitmap(TASK_ID_MOTIONSENSE);
zassert_true(mask != NULL,
"Got a null pointer when getting event bitmap.");
zassert_true((*mask & CONFIG_ACCELGYRO_BMI260_INT_EVENT) == 0,
"Event flag is set before firing interrupt");
bmi260_interrupt(0);
mask = task_get_event_bitmap(TASK_ID_MOTIONSENSE);
zassert_true(mask != NULL,
"Got a null pointer when getting event bitmap.");
zassert_true(*mask & CONFIG_ACCELGYRO_BMI260_INT_EVENT,
"Event flag is not set after firing interrupt");
}
ZTEST_USER(bmi260, test_bmi_init_chip_id)
{
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data =
emul_bmi_get_i2c_common_data(emul);
struct motion_sensor_t *ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
/* Part 1:
* Error occurs while reading the chip ID
*/
i2c_common_emul_set_read_fail_reg(common_data, BMI260_CHIP_ID);
int ret = ms_acc->drv->init(ms_acc);
zassert_equal(ret, EC_ERROR_UNKNOWN,
"Expected %d (EC_ERROR_UNKNOWN) but got %d",
EC_ERROR_UNKNOWN, ret);
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Part 2:
* Test cases where the returned chip ID does not match what is
* expected. This involves overriding values in the motion_sensor
* struct, so make a copy first.
*/
struct motion_sensor_t ms_fake;
memcpy(&ms_fake, ms_acc, sizeof(ms_fake));
/* Part 2a: expecting MOTIONSENSE_CHIP_BMI220 but get BMI260's chip ID!
*/
bmi_emul_set_reg(emul, BMI260_CHIP_ID, BMI260_CHIP_ID_MAJOR);
ms_fake.chip = MOTIONSENSE_CHIP_BMI220;
ret = ms_fake.drv->init(&ms_fake);
zassert_equal(ret, EC_ERROR_ACCESS_DENIED,
"Expected %d (EC_ERROR_ACCESS_DENIED) but got %d",
EC_ERROR_ACCESS_DENIED, ret);
/* Part 2b: expecting MOTIONSENSE_CHIP_BMI260 but get BMI220's chip ID!
*/
bmi_emul_set_reg(emul, BMI260_CHIP_ID, BMI220_CHIP_ID_MAJOR);
ms_fake.chip = MOTIONSENSE_CHIP_BMI260;
ret = ms_fake.drv->init(&ms_fake);
zassert_equal(ret, EC_ERROR_ACCESS_DENIED,
"Expected %d (EC_ERROR_ACCESS_DENIED) but got %d",
EC_ERROR_ACCESS_DENIED, ret);
/* Part 2c: use an invalid expected chip */
ms_fake.chip = MOTIONSENSE_CHIP_MAX;
ret = ms_fake.drv->init(&ms_fake);
zassert_equal(ret, EC_ERROR_ACCESS_DENIED,
"Expected %d (EC_ERROR_ACCESS_DENIED) but got %d",
EC_ERROR_ACCESS_DENIED, ret);
}
/* Make an I2C emulator mock wrapped in FFF */
FAKE_VALUE_FUNC(int, bmi_config_load_no_mapped_flash_mock_read_fn,
const struct emul *, int, uint8_t *, int, void *);
struct i2c_common_emul_data *common_data;
static int bmi_config_load_no_mapped_flash_mock_read_fn_helper(
const struct emul *emul, int reg, uint8_t *val, int bytes, void *data)
{
if (reg == BMI260_INTERNAL_STATUS && val) {
/* We want to force-return a status of 'initialized' when this
* is read.
*/
*val = BMI260_INIT_OK;
return 0;
}
/* For other registers, go through the normal emulator route */
return 1;
}
ZTEST_USER(bmi260, test_bmi_config_load_no_mapped_flash)
{
/* Tests the situation where we load BMI config data when flash memory
* is not mapped (basically what occurs when `init_rom_map()` in
* `bmi_config_load()` returns NULL)
*/
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
struct motion_sensor_t *ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
int ret, num_status_reg_reads;
common_data = emul_bmi_get_i2c_common_data(emul);
/* Force bmi_config_load() to have to manually copy from memory */
RESET_FAKE(init_rom_map);
init_rom_map_fake.return_val = NULL;
/* Force init_rom_copy() to succeed */
RESET_FAKE(init_rom_copy);
init_rom_copy_fake.return_val = 0;
/* Set proper chip ID and raise the INIT_OK flag to signal that config
* succeeded.
*/
bmi_emul_set_reg(emul, BMI260_CHIP_ID, BMI260_CHIP_ID_MAJOR);
i2c_common_emul_set_read_func(
common_data, bmi_config_load_no_mapped_flash_mock_read_fn,
NULL);
RESET_FAKE(bmi_config_load_no_mapped_flash_mock_read_fn);
bmi_config_load_no_mapped_flash_mock_read_fn_fake.custom_fake =
bmi_config_load_no_mapped_flash_mock_read_fn_helper;
/* Part 1: successful path */
ret = ms_acc->drv->init(ms_acc);
zassert_equal(ret, EC_RES_SUCCESS, "Got %d but expected %d", ret,
EC_RES_SUCCESS);
/* Check the number of times we accessed BMI260_INTERNAL_STATUS */
num_status_reg_reads = MOCK_COUNT_CALLS_WITH_ARG_VALUE(
bmi_config_load_no_mapped_flash_mock_read_fn_fake, 1,
BMI260_INTERNAL_STATUS);
zassert_equal(1, num_status_reg_reads,
"Accessed status reg %d times but expected %d.",
num_status_reg_reads, 1);
/* Part 2: write to `BMI260_INIT_ADDR_0` fails */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_INIT_ADDR_0);
ret = ms_acc->drv->init(ms_acc);
zassert_equal(ret, EC_ERROR_INVALID_CONFIG, "Got %d but expected %d",
ret, EC_ERROR_INVALID_CONFIG);
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Part 3: init_rom_copy() fails w/ a non-zero return code of 255. */
init_rom_copy_fake.return_val = 255;
ret = ms_acc->drv->init(ms_acc);
zassert_equal(ret, EC_ERROR_INVALID_CONFIG, "Got %d but expected %d",
ret, EC_ERROR_INVALID_CONFIG);
init_rom_copy_fake.return_val = 0;
/* Part 4: write to `BMI260_INIT_DATA` fails */
i2c_common_emul_set_write_fail_reg(common_data, BMI260_INIT_DATA);
ret = ms_acc->drv->init(ms_acc);
zassert_equal(ret, EC_ERROR_INVALID_CONFIG, "Got %d but expected %d",
ret, EC_ERROR_INVALID_CONFIG);
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
/* Cleanup */
i2c_common_emul_set_read_func(common_data, NULL, NULL);
}
ZTEST_USER(bmi260, test_bmi_config_unsupported_chip)
{
/* Test what occurs when we try to configure a chip that is
* turned off in Kconfig (BMI220). This test assumes that
* CONFIG_ACCELGYRO_BMI220 is NOT defined.
*/
#if defined(CONFIG_ACCELGYRO_BMI220)
#error "Test test_bmi_config_unsupported_chip will not work properly with " \
"CONFIG_ACCELGYRO_BMI220 defined."
#endif
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
struct motion_sensor_t ms_fake;
common_data = emul_bmi_get_i2c_common_data(emul);
/* Set up struct and emaulator to be a BMI220 chip, which
* `bmi_config_load()` does not support in the current configuration
*/
memcpy(&ms_fake, &motion_sensors[BMI_ACC_SENSOR_ID], sizeof(ms_fake));
ms_fake.chip = MOTIONSENSE_CHIP_BMI220;
bmi_emul_set_reg(emul, BMI260_CHIP_ID, BMI220_CHIP_ID_MAJOR);
int ret = ms_fake.drv->init(&ms_fake);
zassert_equal(ret, EC_ERROR_INVALID_CONFIG, "Expected %d but got %d",
EC_ERROR_INVALID_CONFIG, ret);
}
ZTEST_USER(bmi260, test_init_config_read_failure)
{
/* Test proper response to a failed read from the register
* BMI260_INTERNAL_STATUS.
*/
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
struct motion_sensor_t *ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
int ret;
common_data = emul_bmi_get_i2c_common_data(emul);
/* Set up i2c emulator and mocks */
bmi_emul_set_reg(emul, BMI260_CHIP_ID, BMI260_CHIP_ID_MAJOR);
i2c_common_emul_set_read_fail_reg(common_data, BMI260_INTERNAL_STATUS);
RESET_FAKE(init_rom_map);
init_rom_map_fake.custom_fake = init_rom_map_addr_passthru;
ret = ms_acc->drv->init(ms_acc);
zassert_equal(ret, EC_ERROR_INVALID_CONFIG, "Expected %d but got %d",
EC_ERROR_INVALID_CONFIG, ret);
}
/* Mock read function and counter used to test the timeout when
* waiting for the chip to initialize
*/
static int timeout_test_status_reg_access_count;
static int status_timeout_mock_read_fn(const struct emul *emul, int reg,
uint8_t *val, int bytes, void *data)
{
if (reg == BMI260_INTERNAL_STATUS && val) {
/* We want to force-return a non-OK status each time */
timeout_test_status_reg_access_count++;
*val = BMI260_INIT_ERR;
return 0;
} else {
return 1;
}
}
ZTEST_USER(bmi260, test_init_config_status_timeout)
{
/* We allow up to 15 tries to get a successful BMI260_INIT_OK
* value from the BMI260_INTERNAL_STATUS register. Make sure
* we properly handle the case where the chip is not initialized
* before the timeout.
*/
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
struct motion_sensor_t *ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
int ret;
common_data = emul_bmi_get_i2c_common_data(emul);
/* Set up i2c emulator and mocks */
bmi_emul_set_reg(emul, BMI260_CHIP_ID, BMI260_CHIP_ID_MAJOR);
timeout_test_status_reg_access_count = 0;
i2c_common_emul_set_read_func(common_data, status_timeout_mock_read_fn,
NULL);
RESET_FAKE(init_rom_map);
init_rom_map_fake.custom_fake = init_rom_map_addr_passthru;
ret = ms_acc->drv->init(ms_acc);
zassert_equal(timeout_test_status_reg_access_count, 15,
"Expected %d attempts but counted %d", 15,
timeout_test_status_reg_access_count);
zassert_equal(ret, EC_ERROR_INVALID_CONFIG, "Expected %d but got %d",
EC_ERROR_INVALID_CONFIG, ret);
}
/**
* @brief Put the driver and emulator in to a consistent state before each test.
*
* @param arg Test fixture (unused)
*/
static void bmi260_test_before(void *arg)
{
ARG_UNUSED(arg);
const struct emul *emul = EMUL_DT_GET(BMI_NODE);
struct i2c_common_emul_data *common_data;
struct motion_sensor_t *ms_acc = &motion_sensors[BMI_ACC_SENSOR_ID];
struct motion_sensor_t *ms_gyr = &motion_sensors[BMI_GYR_SENSOR_ID];
common_data = emul_bmi_get_i2c_common_data(emul);
/* Reset I2C */
i2c_common_emul_set_read_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
i2c_common_emul_set_write_fail_reg(common_data,
I2C_COMMON_EMUL_NO_FAIL_REG);
i2c_common_emul_set_read_func(common_data, NULL, NULL);
i2c_common_emul_set_write_func(common_data, NULL, NULL);
/* Reset local fakes(s) */
RESET_FAKE(bmi_config_load_no_mapped_flash_mock_read_fn);
/* Clear rotation matrices */
ms_acc->rot_standard_ref = NULL;
ms_gyr->rot_standard_ref = NULL;
/* Set Chip ID register to BMI260 (required for init() to succeed) */
bmi_emul_set_reg(emul, BMI260_CHIP_ID, BMI260_CHIP_ID_MAJOR);
}
ZTEST_SUITE(bmi260, drivers_predicate_pre_main, NULL, bmi260_test_before, NULL,
NULL);
| 2.140625 | 2 |
2024-11-18T21:29:54.237160+00:00
| 2018-09-12T01:12:20 |
bf55a06d7690437eebcb6fd79776dc9e3638a536
|
{
"blob_id": "bf55a06d7690437eebcb6fd79776dc9e3638a536",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-12T01:12:20",
"content_id": "8deecc824294d2747e429101f8ec90c66a5ddf21",
"detected_licenses": [
"MIT"
],
"directory_id": "0b9c1df516012cee1cee852d3cc62f9f79b664d0",
"extension": "c",
"filename": "http_client.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 120667683,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4942,
"license": "MIT",
"license_type": "permissive",
"path": "/src/code_snipet/http_client.c",
"provenance": "stackv2-0112.json.gz:180456",
"repo_name": "97xuzy/http_server",
"revision_date": "2018-09-12T01:12:20",
"revision_id": "5dbf15f5788dfecbcb1a0f519fce095cfb58ec4b",
"snapshot_id": "bcb8da09effeb3e38e751dc90ad562863ece3dba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/97xuzy/http_server/5dbf15f5788dfecbcb1a0f519fce095cfb58ec4b/src/code_snipet/http_client.c",
"visit_date": "2018-12-09T16:36:44.610308"
}
|
stackv2
|
/*!
https://www.geeksforgeeks.org/socket-programming-cc/
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <pthread.h>
#include <time.h>
#define MAX_CLIENT_THREAD 10000
const char request_string[] = "GET /index.html HTTP/1.1\r\n"
"Host: localhost:8080\r\n"
"User-Agent: Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: en-US,en;q=0.5\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"DNT: 1\r\n"
"Connection: keep-alive\r\n"
"Upgrade-Insecure-Requests: 1\r\n\r\n";
typedef struct thread_init_data
{
char *ip_addr;
int port;
int num_req;
} thread_init_data_t;
int parse_cmd_arg(int argc, char *argv[], int *num_client, int *request_per_client, char *ip_addr, int *port);
void* thread_func(void *data_ptr);
int send_request(int sock);
char *read_response_string(int sock);
int main(int argc, char* argv[])
{
char ip_addr[64] = {0};
int port = 0;
int num_client = 0;
int request_per_client = 0;
parse_cmd_arg(argc, argv, &num_client, &request_per_client, ip_addr, &port);
pthread_t threads[MAX_CLIENT_THREAD];
thread_init_data_t data = {ip_addr, port, request_per_client};
for(int i = 0; i < num_client; i++)
{
if(pthread_create(&(threads[i]), NULL, thread_func, &data))
{
fprintf(stderr, "Error creating thread\n");
return 1;
}
}
for(int i = 0; i < num_client; i++)
{
// Wait for request thread to finish
if(pthread_join(threads[i], NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
}
return 0;
}
void* thread_func(void *data_ptr)
{
const thread_init_data_t data = *((thread_init_data_t*)data_ptr);
const char *ip_addr = data.ip_addr;
const int port = data.port;
const int num_req = data.num_req;
int sock = 0;
struct sockaddr_in serv_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
pthread_exit(NULL);
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, ip_addr, &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
pthread_exit(NULL);
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
pthread_exit(NULL);
}
for(int i = 0; i < num_req; i++)
{
send_request(sock);
int milliseconds = 100;
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, NULL);
//read_response_string(sock);
}
return NULL;
}
int parse_cmd_arg(int argc, char *argv[], int *num_client, int *request_per_client, char *ip_addr, int *port)
{
if(argc < 5)
{
fprintf(stderr, "Too few arg\n");
fprintf(stderr, "./http_client num_client req_per_client ip_addr port\n");
exit(-1);
}
int temp1 = atoi(argv[1]);
if(temp1 <= 0 || temp1 > MAX_CLIENT_THREAD)
{
fprintf(stderr, "Number of clients out of range, 1 ~ %d\n", MAX_CLIENT_THREAD);
exit(-1);
}
int temp2 = atoi(argv[2]);
if(temp2 <= 0 || temp1 > MAX_CLIENT_THREAD)
{
fprintf(stderr, "Number of clients out of range, 1 ~ %d\n", MAX_CLIENT_THREAD);
exit(-1);
}
int temp3 = atoi(argv[4]);
if(temp3 <= 0)
{
fprintf(stderr, "Unable to parse port number\n");
exit(-1);
}
*num_client = temp1;
*request_per_client = temp2;
strcpy(ip_addr, argv[3]);
*port = temp3;
return 0;
}
int send_request(int sock)
{
send(sock , request_string , strlen(request_string) + 1 , 0 );
printf("request sent\n");
return 0;
}
char *read_response_string(int sock)
{
// Read Request
char buffer[1024];
char *request_str = malloc(1024 * sizeof(*request_str));
int request_str_len = 0;
int byte_read = 0;
do
{
byte_read = read(sock, buffer, sizeof(buffer));
if(byte_read < 0) return NULL;
memcpy(request_str + request_str_len, buffer, byte_read);
request_str_len += byte_read;
request_str = realloc(request_str, request_str_len);
printf("read %d byte\n", byte_read);
}
while(byte_read == 1024);
//printf("\"%s\"\n", request_str);
printf("response is %ld bytes\n", strlen(request_str));
free(request_str);
return request_str;
}
| 2.890625 | 3 |
2024-11-18T21:29:54.448593+00:00
| 2023-01-05T12:40:03 |
4ae1fb936c9d9f2fc1e4f9444322fda66821e1fd
|
{
"blob_id": "4ae1fb936c9d9f2fc1e4f9444322fda66821e1fd",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-05T12:40:03",
"content_id": "f2197ec29749dca9efcb198f438241a207a9b6b1",
"detected_licenses": [
"MIT"
],
"directory_id": "d200264ee92369d376ba00f6fd5f6d50d9936026",
"extension": "c",
"filename": "idt.c",
"fork_events_count": 21,
"gha_created_at": "2021-04-25T14:27:55",
"gha_event_created_at": "2021-04-27T21:04:53",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 361450561,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 876,
"license": "MIT",
"license_type": "permissive",
"path": "/src/idt.c",
"provenance": "stackv2-0112.json.gz:180587",
"repo_name": "zment4/tetris-os",
"revision_date": "2023-01-05T12:40:03",
"revision_id": "4ff18f6275a28dc51c1f864bda116530c9ba4c54",
"snapshot_id": "f95b377e5e9d4656d8e4c027f9f5fc1ab424ade9",
"src_encoding": "UTF-8",
"star_events_count": 38,
"url": "https://raw.githubusercontent.com/zment4/tetris-os/4ff18f6275a28dc51c1f864bda116530c9ba4c54/src/idt.c",
"visit_date": "2023-08-17T05:24:25.183083"
}
|
stackv2
|
#include "idt.h"
struct IDTEntry {
u16 offset_low;
u16 selector;
u8 __ignored;
u8 type;
u16 offset_high;
} PACKED;
struct IDTPointer {
u16 limit;
uintptr_t base;
} PACKED;
static struct {
struct IDTEntry entries[256];
struct IDTPointer pointer;
} idt;
// in start.S
extern void idt_load();
void idt_set(u8 index, void (*base)(struct Registers*), u16 selector, u8 flags) {
idt.entries[index] = (struct IDTEntry) {
.offset_low = ((uintptr_t) base) & 0xFFFF,
.offset_high = (((uintptr_t) base) >> 16) & 0xFFFF,
.selector = selector,
.type = flags | 0x60,
.__ignored = 0
};
}
void idt_init() {
idt.pointer.limit = sizeof(idt.entries) - 1;
idt.pointer.base = (uintptr_t) &idt.entries[0];
memset(&idt.entries[0], 0, sizeof(idt.entries));
idt_load((uintptr_t) &idt.pointer);
}
| 2.171875 | 2 |
2024-11-18T21:29:54.579578+00:00
| 2022-03-20T17:53:25 |
df49e633b6b3ae0f0bc9167a017bc8ed42ed593e
|
{
"blob_id": "df49e633b6b3ae0f0bc9167a017bc8ed42ed593e",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-20T17:53:25",
"content_id": "76e57b39acc90a7a1ec88efea7031587e08af009",
"detected_licenses": [
"MIT"
],
"directory_id": "15fbb35cb68bd707f6a1eee9485e2ee37fc52876",
"extension": "c",
"filename": "bootloader_config.c",
"fork_events_count": 23,
"gha_created_at": "2016-09-19T19:00:32",
"gha_event_created_at": "2023-07-06T21:24:19",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 68636610,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 794,
"license": "MIT",
"license_type": "permissive",
"path": "/can-io-firmware/src/bootloader_config.c",
"provenance": "stackv2-0112.json.gz:180850",
"repo_name": "cvra/robot-software",
"revision_date": "2022-03-20T17:53:25",
"revision_id": "dcbfa7a99c452145e53142c182ae909079a63962",
"snapshot_id": "f922ec80a5d24f6d7904c1586a9d5f5aa7c1b4bf",
"src_encoding": "UTF-8",
"star_events_count": 42,
"url": "https://raw.githubusercontent.com/cvra/robot-software/dcbfa7a99c452145e53142c182ae909079a63962/can-io-firmware/src/bootloader_config.c",
"visit_date": "2023-07-20T09:58:30.975456"
}
|
stackv2
|
#include <string.h>
#include "bootloader_config.h"
bool config_get(bootloader_config_t* cfg)
{
#if !defined(CONFIG_ADDR)
// not compiled for bootloader, use default config
cfg->ID = 1;
strcpy(cfg->board_name, "dummy-config");
strcpy(cfg->device_class, "can-io-board");
cfg->application_crc = 0;
cfg->application_size = 0;
cfg->update_count = 0;
return true;
#else
uint8_t* p = (uint8_t*)CONFIG_ADDR;
// first config page
if (config_is_valid(p, CONFIG_PAGE_SIZE)) {
*cfg = config_read(p, CONFIG_PAGE_SIZE);
return true;
}
// try second config page
p += CONFIG_PAGE_SIZE;
if (config_is_valid(p, CONFIG_PAGE_SIZE)) {
*cfg = config_read(p, CONFIG_PAGE_SIZE);
return true;
}
return false;
#endif
}
| 2.375 | 2 |
2024-11-18T21:29:57.116830+00:00
| 2018-06-10T10:46:45 |
06ea24a2ac3a1fc3754448de0450f80e0f893027
|
{
"blob_id": "06ea24a2ac3a1fc3754448de0450f80e0f893027",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-10T10:46:45",
"content_id": "104c0a63cc2e01ddda61844475ae6b8c9e9f17f7",
"detected_licenses": [
"Unlicense"
],
"directory_id": "20d049a342605808473e16f2b081a54a3f420a11",
"extension": "c",
"filename": "main.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 113150090,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3747,
"license": "Unlicense",
"license_type": "permissive",
"path": "/fourth_semester/Sysopy/Zadanie4/zad3/main.c",
"provenance": "stackv2-0112.json.gz:180979",
"repo_name": "MajronMan/agh_stuff",
"revision_date": "2018-06-10T10:46:45",
"revision_id": "d045e3bd47ac17880526203d9993d9b2389a9ffe",
"snapshot_id": "1ebd5d04319428c8d9b7c1d56ba67d4c92365eb8",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/MajronMan/agh_stuff/d045e3bd47ac17880526203d9993d9b2389a9ffe/fourth_semester/Sysopy/Zadanie4/zad3/main.c",
"visit_date": "2021-09-15T20:23:37.017420"
}
|
stackv2
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#define CHECK(FUN, VAL, COMP, ERR) if((VAL) == COMP) {\
char msg[100];\
sprintf(msg, "%s: %s\n", FUN, ERR);\
perror(msg);\
exit(-1);\
}
#define CHECK_NEGATIVE_ONE(FUN, VAL, ERR) CHECK(FUN, VAL, -1, ERR)
#define CHECK_SIG_ERR(FUN, VAL, ERR) CHECK(FUN, VAL, SIG_ERR, ERR)
#define HELP printf("Usage: ./main.out signals_count Type\n");
#define RED "\x1b[31m"
#define GREEN "\x1b[32m"
#define BLUE "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN "\x1b[36m"
#define RESET "\x1b[0m"
typedef struct timespec timespec;
typedef struct timeval timeval;
void do_child_stuff();
void do_parent_stuff();
int send_signal(pid_t pid, int sig);
int select_rt_signal(int sig);
void prepare_set(sigset_t *set);
void SIGINT_handler(int sig);
int L;
int Type;
pid_t child_pid;
pid_t parent_pid;
int main(int argc, char **argv) {
if (argc != 3) {
HELP
exit(-1);
}
L = atoi(argv[1]);
Type = atoi(argv[2]);
parent_pid = getpid();
CHECK_SIG_ERR("main", signal(SIGINT, SIGINT_handler), "SIGINT install error");
CHECK_NEGATIVE_ONE("main", child_pid = fork(), "Failed to fork")
if (child_pid == 0) {
do_child_stuff();
} else {
do_parent_stuff();
}
return 0;
}
char *get_child_msg(){
char *what;
switch(Type){
case 1:
what = "kill";
break;
case 2:
what = "add some sigqueue to";
break;
case 3:
what = "do some realtime to";
break;
default:
what = "WHAT";
break;
}
return what;
}
void do_child_stuff() {
int received = 0;
int received_sig = 0;
while(received_sig != select_rt_signal(SIGUSR2)) {
sigset_t set;
prepare_set(&set);
CHECK_NEGATIVE_ONE("do_child_stuff", sigwait(&set, &received_sig), "waiting for signal failed")
printf(GREEN"CHILD RECEIVED SIGNAL %d"RESET"\n", received_sig);
received += received_sig == select_rt_signal(SIGUSR1);
}
printf(MAGENTA"Time has come to %s the parent %d times"RESET"\n", get_child_msg(), received);
for(int i=0; i<received; i++) {
send_signal(parent_pid, SIGUSR1);
sleep(1);
}
}
void do_parent_stuff() {
sleep(1);
int sent = 0, received = 0;
for(int i=0; i<L; i++) {
sent++;
send_signal(child_pid, SIGUSR1);
sleep(1);
}
char *sig1 = Type == 3? "SIGRTMIN": "SIGUSR1";
char *sig2 = Type == 3? "SIGRTMAX": "SIGUSR2";
printf(BLUE"Parent sent %d %s, time for some juicy %s"RESET"\n", sent, sig1, sig2);
send_signal(child_pid, SIGUSR2);
while(received < L) {
int received_sig;
sigset_t set;
prepare_set(&set);
CHECK_NEGATIVE_ONE("do_parent_stuff", sigwait(&set, &received_sig), "waiting for signal failed")
printf(GREEN"PARENT RECEIVED SIGNAL %d"RESET"\n", received_sig);
received++;
}
sleep(1);
printf(CYAN"Parent received %d signals"RESET"\n", received);
}
int select_rt_signal(int sig){
if(Type != 3) return sig;
if(sig == SIGUSR1) return SIGRTMIN;
else return SIGRTMAX;
}
int send_signal(pid_t pid, int sig){
union sigval s={0};
if(Type == 2) return sigqueue(pid, sig, s);
return kill(pid, select_rt_signal(sig));
}
void prepare_set(sigset_t *set) {
sigemptyset(set);
sigaddset(set, SIGUSR2);
sigaddset(set, SIGUSR1);
sigaddset(set, SIGRTMIN);
sigaddset(set, SIGRTMAX);
sigprocmask(SIG_BLOCK, set, NULL);
}
void SIGINT_handler(int sig) {
printf(RED"INTERRUPTED BY %d"RESET"\n", sig);
kill(child_pid, SIGKILL);
exit(1);
}
| 2.71875 | 3 |
2024-11-18T21:29:57.784989+00:00
| 2019-04-12T08:38:26 |
2790a2c1dc7a2eac4945b5425561a50bbec30b1a
|
{
"blob_id": "2790a2c1dc7a2eac4945b5425561a50bbec30b1a",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-12T08:38:26",
"content_id": "62acc88ce681f03b81170946ce8e38023545ba2c",
"detected_licenses": [
"MIT"
],
"directory_id": "8df77479804e9a9aa25cc1175d081cee2ebd4ff5",
"extension": "c",
"filename": "flash-stm32f4xx.c",
"fork_events_count": 6,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14828043,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2767,
"license": "MIT",
"license_type": "permissive",
"path": "/boards/mach-stm32/flash-stm32f4xx.c",
"provenance": "stackv2-0112.json.gz:181757",
"repo_name": "raphui/rnk",
"revision_date": "2019-04-12T08:38:26",
"revision_id": "b77186afcebe95ad5efb53684fef113abdec273f",
"snapshot_id": "afa853498f597019ba3b54d2874d0b0aa8aec02e",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/raphui/rnk/b77186afcebe95ad5efb53684fef113abdec273f/boards/mach-stm32/flash-stm32f4xx.c",
"visit_date": "2021-06-08T09:13:54.923012"
}
|
stackv2
|
#include <board.h>
#include <errno.h>
#include <kernel/printk.h>
#include <mm/mm.h>
#include <string.h>
#include <init.h>
#include <drv/device.h>
#include <fdtparse.h>
#include <drv/mtd.h>
#include <sizes.h>
#include <mach/flash-stm32.h>
#define FLASH_PSIZE_BYTE (0 << 8)
#define FLASH_PSIZE_WORD (2 << 8)
#define FLASH_PSIZE_MASK (3 << 8)
#define CR_PSIZE_MASK 0xFFFFFCFF
#define SR_ERR_MASK 0xF3
#define FLASH_KEY1 0x45670123
#define FLASH_KEY2 0xCDEF89AB
#define SECTOR_MASK 0xFFFFFF07
static int stm32_flash_erase_needed(unsigned char *addr, unsigned char *buff, unsigned int size)
{
int ret = 0;
while (size--) {
if (((*addr ^ *buff) & *buff) != 0) {
ret = 1;
break;
}
addr++;
buff++;
}
return ret;
}
int stm32_flash_erase(struct mtd *mtd, unsigned int sector)
{
int ret = 0;
stm32_flash_unlock();
ret = stm32_flash_wait_operation();
if (ret < 0) {
error_printk("last operation did not success\n");
return ret;
}
FLASH->CR &= CR_PSIZE_MASK;
FLASH->CR |= FLASH_PSIZE_BYTE;
FLASH->CR &= SECTOR_MASK;
FLASH->CR |= FLASH_CR_SER | (sector << 3);
FLASH->CR |= FLASH_CR_STRT;
ret = stm32_flash_wait_operation();
if (ret < 0) {
error_printk("failed to erase sector\n");
return ret;
}
FLASH->CR &= (~FLASH_CR_SER);
FLASH->CR &= SECTOR_MASK;
stm32_flash_lock();
return ret;
}
int stm32_flash_write_byte(unsigned int address, void *data, int byte_access)
{
int ret = 0;
ret = stm32_flash_wait_operation();
if (ret < 0) {
error_printk("last operation did not success\n");
return ret;
}
FLASH->CR &= CR_PSIZE_MASK;
if (!byte_access)
FLASH->CR |= FLASH_PSIZE_WORD;
FLASH->CR |= FLASH_CR_PG;
if (byte_access)
*(volatile unsigned char *)address = *(unsigned char *)data;
else
*(volatile unsigned int *)address = *(unsigned int *)data;
ret = stm32_flash_wait_operation();
if (ret < 0) {
error_printk("failed to write 0x%x at 0x%x\n", data, address);
return ret;
}
FLASH->CR &= (~FLASH_CR_PG);
return ret;
}
int stm32_flash_write(struct mtd *mtd, unsigned char *buff, unsigned int size, struct mtd_page *page)
{
int ret = 0;
int i;
int step;
int byte_access = size % sizeof(unsigned int);
unsigned int addr = mtd->base_addr + mtd->curr_off;
FLASH->ACR &= ~FLASH_ACR_DCEN;
ret = stm32_flash_erase_needed((unsigned char *)addr, buff, size);
if (ret) {
ret = stm32_flash_erase(mtd, page->index);
if (ret < 0)
goto err;
}
stm32_flash_unlock();
if (byte_access)
step = 1;
else
step = 4;
for (i = 0; i < size; i += step) {
ret = stm32_flash_write_byte(addr, &buff[i], byte_access);
if (ret < 0)
break;
if (byte_access)
addr += step;
}
stm32_flash_lock();
FLASH->ACR |= FLASH_ACR_DCRST;
FLASH->ACR |= FLASH_ACR_DCEN;
err:
return ret;
}
| 2.53125 | 3 |
2024-11-18T21:29:57.951672+00:00
| 2019-10-29T23:22:40 |
8c84beda053ebe1fef87e1ea428b66265c8db7aa
|
{
"blob_id": "8c84beda053ebe1fef87e1ea428b66265c8db7aa",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-29T23:22:40",
"content_id": "4f262aee3aa1bc37e862e8b766184c59e917e336",
"detected_licenses": [
"MIT"
],
"directory_id": "1aeb367578f7719775a4c418d71ab6e3f9d0589d",
"extension": "c",
"filename": "filesystem_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": 3023,
"license": "MIT",
"license_type": "permissive",
"path": "/Practicas/Practica2/Ejercicio4/filesystem_client.c",
"provenance": "stackv2-0112.json.gz:182017",
"repo_name": "cirano-eusebi/pdytr2018",
"revision_date": "2019-10-29T23:22:40",
"revision_id": "1f27c532dab779ffaf9122c684384b214e4a24e3",
"snapshot_id": "8348b0286fd5983972bcc8a5b6f789ee4749897d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cirano-eusebi/pdytr2018/1f27c532dab779ffaf9122c684384b214e4a24e3/Practicas/Practica2/Ejercicio4/filesystem_client.c",
"visit_date": "2022-03-15T20:18:11.239862"
}
|
stackv2
|
#include <stdio.h>
#include "filesystem.h"
void parse_args(int argc, char* argv[], char** host, char** filename)
{
if (argc < 3) {
printf ("usage: %s hostname filename\n", argv[0]);
exit (1);
}
*host = argv[1];
*filename = argv[2];
}
// Open file to append data
FILE* createOrOpenFile(char* filename) {
return fopen(filename, "a");
}
void closeFile(FILE* fileD) {
fclose(fileD);
}
int updateFile(FILE* fileD, char* buffer, int size) {
return fwrite(buffer, sizeof(char), size, fileD);
}
void sentFileToServer(char* newFilename, CLIENT* client, int buffer_size) {
FILE* fileD = fopen(newFilename, "r");
printf ("newFilename: %s\n", newFilename);
fseek(fileD, 0L, SEEK_END);
int file_size = ftell(fileD);
char* buffer = calloc(buffer_size, sizeof(char));
int currentReadBytes = 0;
enum clnt_stat status;
printf ("currentReadBytes: %d \t file_size: %d\n", currentReadBytes, file_size);
do {
int readSize = buffer_size;
if (readSize > (file_size - currentReadBytes)) {
readSize = file_size - currentReadBytes;
}
//read to buffer.
fseek(fileD, currentReadBytes, SEEK_SET);
int readBytes = fread(buffer, sizeof(char), readSize, fileD);
write_request w_request;
w_request.name = newFilename;
w_request.size = readBytes;
w_request.buffer = buffer;
int serverReadSize = 0;
status = pdytr_write_1(w_request, &serverReadSize, client);
if (status != RPC_SUCCESS) {
clnt_perror (client, "call failed");
}
currentReadBytes += serverReadSize;
printf ("currentReadBytes: %d \t serverReadSize: %d\t readBytes: %d\n", currentReadBytes, serverReadSize, readBytes);
} while (currentReadBytes < file_size);
free(buffer);
closeFile(fileD);
}
int main (int argc, char* argv[])
{
char* host;
char* filename;
parse_args(argc, argv, &host, &filename);
CLIENT* client = clnt_create (host, FS_PROG, FS_VERSION, "udp");
if (client == NULL) {
clnt_pcreateerror (host);
exit (1);
}
int file_size = 0;
enum clnt_stat status = pdytr_file_size_1(filename, &file_size, client);
if (status != RPC_SUCCESS) {
clnt_perror (client, "call failed");
}
int buffer_size = 255;
read_request request;
request.name = filename;
request.offset = 0;
request.size = buffer_size;
read_response* response = malloc(sizeof(read_response));
response->buffer = calloc(buffer_size, sizeof(char));
int currentBytes = 0;
char* newFilename = calloc(strlen(filename)+7, sizeof(char));
newFilename = strcat(newFilename, "client-");
newFilename = strcat(newFilename, filename);
FILE* fileD = createOrOpenFile(newFilename);
do {
status = pdytr_read_1(request, response, client);
if (status != RPC_SUCCESS) {
clnt_perror (client, "call failed");
}
currentBytes+= response->size;
request.offset = currentBytes;
updateFile(fileD, response->buffer, response->size);
} while (currentBytes < file_size);
closeFile(fileD);
free(response->buffer);
free(response);
sentFileToServer(newFilename, client, buffer_size);
clnt_destroy (client);
exit (0);
}
| 2.859375 | 3 |
2024-11-18T21:29:58.021239+00:00
| 2019-09-24T02:33:20 |
3e54b8a1a0755c11cbf1ee0231e8ac3c03ba249d
|
{
"blob_id": "3e54b8a1a0755c11cbf1ee0231e8ac3c03ba249d",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-24T02:33:20",
"content_id": "c0237cb158bb11f9f146931ab9f15db2b5df3059",
"detected_licenses": [
"MIT"
],
"directory_id": "8b90166a4a69d7a841f05518dfae60633d689176",
"extension": "c",
"filename": "6-4.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 205683202,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 375,
"license": "MIT",
"license_type": "permissive",
"path": "/ch6/6-4.c",
"provenance": "stackv2-0112.json.gz:182148",
"repo_name": "kentywang/kr-solns",
"revision_date": "2019-09-24T02:33:20",
"revision_id": "db6d8e1ae7404fef7036b2406d7b016f1aa58c6c",
"snapshot_id": "cd13950532c3d29ed84c839c951f4e78ab7c070d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kentywang/kr-solns/db6d8e1ae7404fef7036b2406d7b016f1aa58c6c/ch6/6-4.c",
"visit_date": "2020-07-16T00:36:54.785274"
}
|
stackv2
|
/*
Basic idea is to go back to using and fixed-size array of structs (instead of
a tree) and then create a array of pointers to them. We sort this pointer
array instead of the struct array and then print. Printing is O(n), sorting
O(log n), updating/inserting a word is O(n).
Book keeps update/insert using tree (while still constructing pointer array),
so it's O(log n).
*/
| 3.328125 | 3 |
2024-11-18T21:29:58.669090+00:00
| 2022-01-27T05:46:54 |
d894516a077f14824e0feda92453a888b537223c
|
{
"blob_id": "d894516a077f14824e0feda92453a888b537223c",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-27T05:46:54",
"content_id": "49c23cedf1d6127904acbce3fc5692b724c31968",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "45c62ef608be0c1d8e18eca66169899545fc8a17",
"extension": "c",
"filename": "grib_list.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236273554,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3091,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Sources_Eccodes/eccodes-2.15.0-Source/examples/C/grib_list.c",
"provenance": "stackv2-0112.json.gz:182793",
"repo_name": "jpmacveigh/python_grib",
"revision_date": "2022-01-27T05:46:54",
"revision_id": "c0bc1c5bc6d40c7294443ad2b0e3cb7726428584",
"snapshot_id": "22b81342fa8e4dfeb3b5fec5e2946fd6856bb022",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jpmacveigh/python_grib/c0bc1c5bc6d40c7294443ad2b0e3cb7726428584/Sources_Eccodes/eccodes-2.15.0-Source/examples/C/grib_list.c",
"visit_date": "2022-02-02T05:11:39.253063"
}
|
stackv2
|
/*
* Copyright 2005-2019 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
/*
* C Implementation: grib_list
*
* Description: how to get values using keys.
*
*/
#include <stdio.h>
#include <assert.h>
#include "eccodes.h"
int main(int argc, char** argv)
{
int err = 0;
size_t i = 0;
size_t count;
size_t size;
long numberOfContributingSpectralBands;
long values[1024];
long new_values[1024];
FILE* in = NULL;
const char* filename = "../../data/satellite.grib";
codes_handle *h = NULL;
in = fopen(filename,"rb");
if(!in) {
printf("ERROR: unable to open input file %s\n",filename);
return 1;
}
/* create new handle from a message in a file*/
h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);
if (h == NULL) {
printf("Error: unable to create handle from file %s\n",filename);
}
CODES_CHECK(codes_get_long(h,"numberOfContributingSpectralBands",&numberOfContributingSpectralBands),0);
assert(numberOfContributingSpectralBands == 3);
/* Shrink NB to 2 */
numberOfContributingSpectralBands = 2;
CODES_CHECK(codes_set_long(h,"numberOfContributingSpectralBands",numberOfContributingSpectralBands),0);
/* Expand NB to 9 */
numberOfContributingSpectralBands = 9;
CODES_CHECK(codes_set_long(h,"numberOfContributingSpectralBands",numberOfContributingSpectralBands),0);
/* get as a long*/
CODES_CHECK(codes_get_long(h,"numberOfContributingSpectralBands",&numberOfContributingSpectralBands),0);
printf("numberOfContributingSpectralBands=%ld\n",numberOfContributingSpectralBands);
/* get as a long*/
CODES_CHECK(codes_get_size(h,"scaledValueOfCentralWaveNumber",&count),0);
printf("count=%ld\n",(long)count);
assert(count < sizeof(values)/sizeof(values[0]));
size = count;
CODES_CHECK(codes_get_long_array(h,"scaledValueOfCentralWaveNumber",values,&size),0);
assert(size == count);
for(i=0;i<count;i++) {
printf("scaledValueOfCentralWaveNumber %lu = %ld\n",(unsigned long)i,values[i]);
if (i == 0) assert( values[i] == 26870 );
if (i == 1) assert( values[i] == 9272 );
}
for(i=0;i<count;i++)
values[i] = i+1000;
size = count;
/* size--; */
CODES_CHECK(codes_set_long_array(h,"scaledValueOfCentralWaveNumber",values,size),0);
assert(size == count);
/* check what we set */
CODES_CHECK(codes_get_long_array(h,"scaledValueOfCentralWaveNumber",new_values,&size),0);
assert(size == count);
for(i=0;i<count;i++) {
printf("Now scaledValueOfCentralWaveNumber %lu = %ld\n",(unsigned long)i,new_values[i]);
assert( new_values[i] == (i+1000) );
}
codes_handle_delete(h);
fclose(in);
return 0;
}
| 2.5 | 2 |
2024-11-18T21:29:58.773895+00:00
| 2014-08-19T06:54:36 |
0bcb98dbb4f4b4fec4fa080dbc82a29d11fb1f1d
|
{
"blob_id": "0bcb98dbb4f4b4fec4fa080dbc82a29d11fb1f1d",
"branch_name": "refs/heads/master",
"committer_date": "2014-08-19T06:54:36",
"content_id": "55b5afec02df91ac1c628d2d6692a28fad34234b",
"detected_licenses": [
"MIT"
],
"directory_id": "71e0f23ee6b27c813875edfa16e30d21da14a363",
"extension": "c",
"filename": "pocl_image_util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6933,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/CL/pocl_image_util.c",
"provenance": "stackv2-0112.json.gz:182922",
"repo_name": "easonwang27/pocl-1",
"revision_date": "2014-08-19T06:54:36",
"revision_id": "61617baf530012ddf2e4437e6c589867838c9a3f",
"snapshot_id": "b303c34285787f898ea3560f7fc3125475be9902",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/easonwang27/pocl-1/61617baf530012ddf2e4437e6c589867838c9a3f/lib/CL/pocl_image_util.c",
"visit_date": "2021-06-02T06:38:14.983392"
}
|
stackv2
|
/* OpenCL runtime library: pocl_image_util image utility functions
Copyright (c) 2012 Timo Viitanen / Tampere University of Technology
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "pocl_cl.h"
#include "pocl_image_util.h"
#include "assert.h"
extern cl_int
pocl_check_image_origin_region (const cl_mem image,
const size_t *origin,
const size_t *region)
{
if (image == NULL)
return CL_INVALID_MEM_OBJECT;
if (origin == NULL || region == NULL)
return CL_INVALID_VALUE;
/* check if origin + region in each dimension is with in image bounds */
if (((origin[0] + region[0]) > image->image_row_pitch) ||
(image->image_height > 0 &&
((origin[1] + region[1]) > image->image_height)) ||
(image->image_depth > 0 && (origin[2] + region[2]) > image->image_depth))
return CL_INVALID_VALUE;
return CL_SUCCESS;
}
extern void
pocl_get_image_information (cl_channel_order ch_order,
cl_channel_type ch_type,
int* channels_out,
int* elem_size_out)
{
if (ch_type == CL_SNORM_INT8 || ch_type == CL_UNORM_INT8 ||
ch_type == CL_SIGNED_INT8 || ch_type == CL_UNSIGNED_INT8)
{
*elem_size_out = 1; /* 1 byte */
}
else if (ch_type == CL_UNSIGNED_INT32 || ch_type == CL_SIGNED_INT32 ||
ch_type == CL_FLOAT || ch_type == CL_UNORM_INT_101010)
{
*elem_size_out = 4; /* 32bit -> 4 bytes */
}
else if (ch_type == CL_SNORM_INT16 || ch_type == CL_UNORM_INT16 ||
ch_type == CL_SIGNED_INT16 || ch_type == CL_UNSIGNED_INT16 ||
ch_type == CL_UNORM_SHORT_555 || ch_type == CL_UNORM_SHORT_565 ||
ch_type == CL_HALF_FLOAT)
{
*elem_size_out = 2; /* 16bit -> 2 bytes */
}
/* channels TODO: verify num of channels*/
if (ch_order == CL_RGB || ch_order == CL_RGBx || ch_order == CL_R ||
ch_order == CL_Rx || ch_order == CL_A)
{
*channels_out = 1;
}
else
{
*channels_out = 4;
}
}
cl_int
pocl_write_image(cl_mem image,
cl_device_id device_id,
const size_t * origin, /*[3]*/
const size_t * region, /*[3]*/
size_t host_row_pitch,
size_t host_slice_pitch,
const void * ptr)
{
if (image == NULL)
return CL_INVALID_MEM_OBJECT;
if ((ptr == NULL) || (region == NULL) || origin == NULL)
return CL_INVALID_VALUE;
size_t dev_elem_size = sizeof(cl_float);
int dev_channels = 4;
int host_elem_size;
int host_channels;
pocl_get_image_information (image->image_channel_order,
image->image_channel_data_type,
&host_channels, &host_elem_size);
size_t tuned_origin[3] = {origin[0]*dev_elem_size*dev_channels, origin[1],
origin[2]};
size_t tuned_region[3] = {region[0]*dev_elem_size*dev_channels, region[1],
region[2]};
size_t image_row_pitch = image->image_width*dev_elem_size*dev_channels;
size_t image_slice_pitch = 0;
if ((tuned_region[0]*tuned_region[1]*tuned_region[2] > 0) &&
(tuned_region[0]-1 +
image_row_pitch * (tuned_region[1]-1) +
image_slice_pitch * (tuned_region[2]-1) >= image->size))
return CL_INVALID_VALUE;
device_id->ops->write_rect (device_id->data, ptr,
image->device_ptrs[device_id->dev_id].mem_ptr,
tuned_origin, tuned_origin, tuned_region,
image_row_pitch, image_slice_pitch,
image_row_pitch, image_slice_pitch);
return CL_SUCCESS;
}
extern cl_int
pocl_read_image(cl_mem image,
cl_device_id device_id,
const size_t * origin, /*[3]*/
const size_t * region, /*[3]*/
size_t host_row_pitch,
size_t host_slice_pitch,
void * ptr)
{
if (image == NULL)
return CL_INVALID_MEM_OBJECT;
if ((ptr == NULL) || (region == NULL) || origin == NULL)
return CL_INVALID_VALUE;
int width = image->image_width;
int height = image->image_height;
int host_channels, host_elem_size;
pocl_get_image_information(image->image_channel_order,
image->image_channel_data_type,
&host_channels, &host_elem_size);
/* dev imagetype = host imagetype, in current implementation */
int dev_elem_size = host_elem_size;
int dev_channels = host_channels;
size_t tuned_origin[3] = {origin[0]*dev_elem_size*dev_channels, origin[1],
origin[2]};
size_t tuned_region[3] = {region[0]*dev_elem_size*dev_channels, region[1],
region[2]};
size_t image_row_pitch = width*dev_elem_size*dev_channels;
size_t image_slice_pitch = height*image_row_pitch;
if ((tuned_origin[0] + tuned_region[0] > image_row_pitch) ||
(tuned_origin[1] + tuned_region[1] > height))
return CL_INVALID_VALUE;
if ((image->type == CL_MEM_OBJECT_IMAGE3D &&
(tuned_origin[2] + tuned_region[2] > image->image_depth)))
return CL_INVALID_VALUE;
if (image->type != CL_MEM_OBJECT_IMAGE3D && region[2] != 1)
return CL_INVALID_VALUE;
device_id->ops->read_rect(device_id->data, ptr,
image->device_ptrs[device_id->dev_id].mem_ptr,
tuned_origin, tuned_origin, tuned_region,
image_row_pitch, image_slice_pitch,
image_row_pitch, image_slice_pitch);
return CL_SUCCESS;
}
| 2.1875 | 2 |
2024-11-18T21:29:58.936565+00:00
| 2022-11-28T14:34:00 |
29d356fda8eb43247f72b26d21e5635bbc148199
|
{
"blob_id": "29d356fda8eb43247f72b26d21e5635bbc148199",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-28T14:34:00",
"content_id": "02e2948b9e566356e2451b928efef55ab77e0fba",
"detected_licenses": [],
"directory_id": "e3e940b2324da6e88f076b8a7f7fd3f20e076b81",
"extension": "h",
"filename": "column.h",
"fork_events_count": 38,
"gha_created_at": "2014-07-02T22:09:06",
"gha_event_created_at": "2022-11-28T14:34:01",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 21441956,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2214,
"license": "",
"license_type": "permissive",
"path": "/include/chisql/column.h",
"provenance": "stackv2-0112.json.gz:183051",
"repo_name": "uchicago-cs/chidb",
"revision_date": "2022-11-28T14:34:00",
"revision_id": "57001a72b92f8a2cd95da11b894541ea48a4f87f",
"snapshot_id": "bc49640181b47e61e061e35ff480b4a123684114",
"src_encoding": "UTF-8",
"star_events_count": 51,
"url": "https://raw.githubusercontent.com/uchicago-cs/chidb/57001a72b92f8a2cd95da11b894541ea48a4f87f/include/chisql/column.h",
"visit_date": "2022-12-10T18:34:36.319636"
}
|
stackv2
|
#ifndef __COLUMN_H_
#define __COLUMN_H_
#include "common.h"
#include "literal.h"
enum constraint_type {
CONS_NOT_NULL,
CONS_UNIQUE,
CONS_PRIMARY_KEY,
CONS_FOREIGN_KEY,
CONS_DEFAULT,
CONS_AUTO_INCREMENT,
CONS_CHECK,
CONS_SIZE
};
typedef struct ForeignKeyRef_t {
const char *col_name, *table_name, *table_col_name;
} ForeignKeyRef_t;
typedef struct Constraint_t {
enum constraint_type t;
union {
ForeignKeyRef_t ref;
Literal_t *default_val;
unsigned size;
Condition_t *check;
} constraint;
struct Constraint_t *next;
} Constraint_t;
typedef struct Column_t {
char *name;
enum data_type type;
Constraint_t *constraints;
size_t offset; /* offset in bytes from the beginning of the row */
struct Column_t *next;
} Column_t;
typedef struct ColumnReference_t {
char *tableName, *columnName, *columnAlias;
} ColumnReference_t;
/* constraints on single columns */
ForeignKeyRef_t ForeignKeyRef_makeFull(const char *cname, ForeignKeyRef_t fkey);
ForeignKeyRef_t ForeignKeyRef_make(const char *foreign_tname,
const char *foreign_cname);
Constraint_t *NotNull(void);
Constraint_t *AutoIncrement(void);
Constraint_t *PrimaryKey(void);
Constraint_t *ForeignKey(ForeignKeyRef_t fkr);
Constraint_t *Default(Literal_t *val);
Constraint_t *Unique(void);
Constraint_t *Check(Condition_t *cond);
Constraint_t *ColumnSize(unsigned size);
Constraint_t *Constraint_append(Constraint_t *constraints, Constraint_t *constraint);
Column_t *Column_addConstraint(Column_t *column, Constraint_t *constraints);
Column_t *Column(const char *name, enum data_type type, Constraint_t *constraints);
Column_t *Column_append(Column_t *columns, Column_t *column);
ColumnReference_t *ColumnReference_make(const char *, const char *);
int Column_compareByName(const void *col1, const void *col2);
void *Column_copy(void *col);
void Column_getOffsets(Column_t *cols);
size_t Column_getSize(Column_t *col);
void Constraint_print(void *constraint);
void Constraint_printList(Constraint_t *constraints);
void Column_freeList(Column_t *column);
/* sets the size of the next column */
void Column_setSize(ssize_t size);
#endif
| 2.6875 | 3 |
2024-11-18T21:29:59.042652+00:00
| 2018-12-02T01:49:26 |
cb061677e83d1c3937b39ae4bd938bc268decef4
|
{
"blob_id": "cb061677e83d1c3937b39ae4bd938bc268decef4",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-02T01:49:26",
"content_id": "61ae9dc841954a3e23d5f87372cbfcbf157ad413",
"detected_licenses": [
"MIT"
],
"directory_id": "887a1a5b20d640ea920f523a825994901094e198",
"extension": "h",
"filename": "assignment_3.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 159011901,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15135,
"license": "MIT",
"license_type": "permissive",
"path": "/Day3/assignment_3.h",
"provenance": "stackv2-0112.json.gz:183181",
"repo_name": "rafi007akhtar/compiler-lab-assignments",
"revision_date": "2018-12-02T01:49:26",
"revision_id": "aeb15edd8c46608a9afe6c93619b028560f9cc37",
"snapshot_id": "a5728345ed060d8b57324928ef02146588a1e2cb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rafi007akhtar/compiler-lab-assignments/aeb15edd8c46608a9afe6c93619b028560f9cc37/Day3/assignment_3.h",
"visit_date": "2020-04-08T04:18:59.756285"
}
|
stackv2
|
/** The following assignments were given on Day 2. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define allo (char *) malloc(sizeof(char) * 100)
typedef enum boolean {false, true} bool;
// UTILITY FUNCTIONS
char *removeSpaces(char *str)
{
// Remove all spaces from a string
char *trimmed = allo;
int pos = -1;
int trimI = 0;
while(str[++pos])
{
if ((int) str[pos] == 32 || str[pos] == '\t')
continue;
trimmed[trimI++] = str[pos];
}
trimmed[trimI] = '\0';
return trimmed;
}
int indexOf(char *str, char ch)
{
// Return the first index of character `ch` in string `str`
// Return -1 if not found
int pos = -1;
while(str[++pos])
{
if (str[pos] == ch)
return pos;
}
return -1;
}
char *unindentLine(char *line)
{
// Remove indentation (extra spaces in the prefix) of a line
char *unindented = allo;
int pos = -1;
int newPos = 0;
while(line[++pos])
{
if ((int) line[pos] != 32 || line[pos] != '\t')
unindented[newPos++] = line[pos];
}
unindented[newPos] = '\0';
return unindented;
}
bool typeCheck(char *val, char *datatype)
{
// Returns true if `val` is a valid value for datatype `type`
// Returns false otherwise
// Does NOT check for void types
int pos;
if (!strcmp(datatype, "short") || !strcmp(datatype, "int") || !strcmp(datatype, "long"))
{
// check for all ints
pos = -1;
while(val[++pos])
{
// it can be expression with numbers, +, -, /, *, % and spaces only
if (val[pos] == '*' || val[pos] == '/' || val[pos] == '/' || val[pos] == '%')
{
// this cannot happen in the beginning
if (pos == 0)
return false;
continue;
}
if (val[pos] != '+' && val[pos] != '-' && val[pos] && (int) val[pos]!=32
&& !((int)val[pos] >= 48 && (int)val[pos] <= 57)
)
return false;
}
return true;
}
if (!strcmp(datatype, "float") || !strcmp(datatype, "double"))
{
pos = -1;
while(val[++pos])
{
if (val[pos] == '.')
{
// periods can't appear at the end
if (val[pos+1] == '\0') return false;
continue;
}
if (val[pos] == '*' || val[pos] == '/' || val[pos] == '/' || val[pos] == '%')
{
// this cannot happen in the beginning
if (pos == 0)
return false;
continue;
}
if (val[pos] != '+' && val[pos] != '-' && val[pos] && (int) val[pos]!=32
&& !((int)val[pos] >= 48 && (int)val[pos] <= 57)
)
return false;
}
return true;
}
if (! strcmp(datatype, "char"))
{
// chars can be only one letter long, plus the surrounding quotes ''
if (val[0] != '\'' || val[2] != '\'' || val[3] != '\0')
return false;
return true;
}
return false;
}
bool in(char *word, char *list[], int len)
{
// check if word exists in list
int i;
for (i = 0; i < len; i++)
{
if (! strcmp(list[i], word))
return true;
}
return false;
}
// ### Assignment questions begin from here ###
// Q1: Write a C program to check if another C file has the necessary prerequisites for executing a C program(such as #include<stdio.h>, int main(){},return 0;)
bool checkPrerequisites(char *filename)
{
FILE *f;
f = fopen(filename, "r");
size_t len = 0;
char *line;
int result;
bool checkMain, checkReturn, openBrace, closeBrace, checkHeader;
checkMain = checkReturn = checkHeader = closeBrace = false;
while(1)
{
result = getline(&line, &len, f);
if (result == -1)
break;
// check header
if (line[0] == '#')
{
if (!strcmp("#include<stdio.h>\n", removeSpaces(line)))
{
checkHeader = true;
continue;
}
}
// check main
if (! strcmp("int main()\n", line) ||
! strcmp("int main(void)\n", line) ||
! strcmp("int main(int argc, char *argv[])\n", line)
)
{
checkMain = true;
continue;
}
// check open brace
if (!strcmp("{\n", line) && checkMain == true)
{
openBrace = true;
continue;
}
// check close brace
if (!strcmp("}\n", line) && openBrace == true)
{
closeBrace = true;
continue;
}
// check return
if (checkReturn == false)
{
if (
(!strcmp("return0;\n", removeSpaces(line)) &&
strcmp("return0;\n", line)) ||
(!strcmp("return(0);\n", removeSpaces(line)) &&
strcmp("return(0);\n", line))
)
checkReturn = true;
continue;
}
// if already encountered all these, don't check anymore
if (checkMain && checkReturn && openBrace && closeBrace && checkHeader)
return true;
}
fclose(f);
return (checkHeader && checkMain && openBrace && closeBrace && checkReturn);
}
// Q2: Write a C program that will replace a calloc() function to malloc() function with appropriate parameters.
// E.g.-
// Input: calloc(5,sizeof(float)),
// Output: malloc(5* sizeof(float))
char* calToMal(char *str)
{
char *test = allo;
int pos = -1;
int testI = 0;
while(str[++pos])
{
// change the 'c' in "calloc" to 'm' for "malloc"
if (pos == 0)
test[testI++] = 'm';
// change the comma to multiply
else if (str[pos] == ',')
test[testI++] = '*';
else test[testI++] = str[pos];
}
test[testI] = '\0';
return test;
}
// Q3: Write a C program which will take a C file as input and
// find out the total memory space required for allocating
// all the variables and check if it exceeds a certain limit
// (which is taken as user input).
int varSize(char *filename)
{
size_t len = 0;
char *line;
int result;
int pos;
char *type;
size_t size = 0;
int intCount, floatCount, longCount, doubleCount, charCount;
intCount = floatCount = longCount = doubleCount = charCount = 0;
FILE *f = fopen(filename, "r");
while(1)
{
result = getline(&line, &len, f);
if (result == -1) break;
pos = -1;
while(line[++pos])
{
type = allo;
if(pos + 3 < len)
{
memcpy(type, &line[pos], 3);
type[3] = '\0';
if (! strcmp("int", type))
intCount++;
}
if(pos + 4 < len)
{
memcpy(type, &line[pos], 4);
type[4] = '\0';
if (! strcmp("long", type))
longCount++;
if (! strcmp("char", type))
charCount++;
}
if (pos + 5 < len)
{
memcpy(type, &line[pos], 5);
type[5] = '\0';
if (! strcmp("float", type))
floatCount++;
if (! strcmp("double", type))
doubleCount++;
}
if (pos + 6 < len)
{
memcpy(type, &line[pos], 6);
type[6] = '\0';
if (! strcmp("double", type))
doubleCount++;
}
free(type);
}
}
fclose(f);
intCount--; // subtracting an int for int main
// printf("Ints: %d \nFloats: %d \nLongs: %d \nChars: %d \nDoubles: %d\n", intCount, floatCount, longCount, charCount, doubleCount);
int totalSize = (
(intCount*sizeof(int)) +
(floatCount*sizeof(float)) +
(charCount*sizeof(char)) +
(longCount*sizeof(long)) +
(doubleCount*sizeof(double))
);
return totalSize;
}
// Q4: Write a C program that takes another C file as input and check if all the functions are having proper return types.
void checkReturn(char *filename)
{
char* line;
size_t len = 0;
int result;
char *type = "none so far";
char *temp;
int spaceIndex;
bool hasError = false;
FILE *f = fopen(filename, "r");
int lineNumber = 0;
while(1)
{
result = getline(&line, &len, f);
if (result == -1) break;
lineNumber++;
// get the return type if this line is a function decl.
len = strlen(line);
if (line[len-2] == ')')
{
type = allo;
spaceIndex = indexOf(line, (char)32);
memcpy(type, &line[0], spaceIndex);
type[spaceIndex] = '\0';
// you don't need anything else from this line, so move on to the next
continue;
}
// once you have the return type, check for the closest return statement
if (strcmp(type, "none so far"))
{
line = removeSpaces(line);
// a return statement would atleast need 6 characters
len = strlen(line);
if (len < 6) continue;
// printf("Line '%s' with length %ld will be processed\n", line, len);
temp = allo;
memcpy(temp, &line[0], 6); // 'return' is 6 characters long
temp[6] = '\0';
// check if the statement is a return statement
if (! strcmp(temp, "return"))
{
if (! strcmp(type, "void"))
{
hasError = true;
printf("Error in line %d: return statement in void\n", lineNumber);
}
else // return statement in a non-void function
{
// now get the return value
temp = allo;
int ind = indexOf(line, ';');
memcpy(temp, &line[6], ind-6);
temp[ind-6] = '\0';
// printf("Return value: '%s' in type '%s'\n", temp, type);
// now check if you have the proper value wrt the type
if (! typeCheck(temp, type))
{
hasError = true;
printf("Error in line %d: '%s' is not a valid return value for type '%s'\n", lineNumber, temp, type);
}
free(temp);
}
free(type);
type = "none so far";
}
}
}
fclose(f);
if (! hasError) printf("There are no errors in the return types of this file\n");
}
// Q5: Write a C program that should check if all the members of the \
structures are having a defined data type. If not, print an error.
void checkStruct(char *filename)
{
// ASSUMPTION: The file contains only struct members
char *line;
size_t len = 0;
int lineNumber = 0;
int result;
char *first5;
char *types[] = {"int", "short", "float", "long", "double", "char"};
char *type;
int spaceIndex;
FILE *f = fopen(filename, "r");
while(1)
{
result = getline(&line, &len, f);
if (result == -1) break;
lineNumber++;
if (! strcmp(line, "\n"))
continue;
// skip for lines with "struct", "{", "}"
len = strlen(line);
if (len >= 6)
{
first5 = allo;
memcpy(first5, &line[0], 6);
first5[6] = '\0';
if (!strcmp("struct", first5) || !strcmp("typede", first5))
continue;
free(first5);
}
if (line[0] == '{' || line[0] == '}')
continue;
// assuming the rest are struct members, check if they have valid datatypes
spaceIndex = indexOf(line, (char)32);
line = removeSpaces(line);
type = allo;
memcpy(type, &line[0], spaceIndex-1);
type[spaceIndex-1] = '\0';
// printf("Type of this member: '%s'\n", type);
if (! in(type, types, 6))
printf("Error in line %d: %s is not a valid type \n", lineNumber, type);
free(type);
}
fclose(f);
}
// Q6: Write a C program that will check whether the input string is containing “Monday” in it.
bool hasMonday(char *str)
{
char *temp = allo;
char *word = "Monday";
int pos, tPos;
pos = tPos = -1;
while(str[++pos])
{
// when you reach the end
if (str[pos+1] == '\0')
{
temp[++tPos] = str[pos];
temp[++tPos] = '\0';
if (! strcmp(temp, word))
{
free(temp);
return true;
}
free(temp);
return false;
}
// when you are anywhere but the end
if ((int) str[pos] == 32)
{
temp[++tPos] = '\0';
if (! strcmp(temp, word))
return true;
free(temp);
temp = allo;
tPos = -1;
continue;
}
temp[++tPos] = str[pos];
}
}
// Q7: Write a C program that will check whether all the variables declared in an input file are initialized or not.
// If not, initialize them with 0.
void initialize(char *filename)
{
char *line;
int result;
size_t len = 0;
int pos;
FILE *f = fopen(filename, "r");
char *assinged;
bool isAssigned;
// copy the results to an intermediate temp file
FILE *temp = fopen("temp.c", "w+");
fclose(temp);
while(1)
{
result = getline(&line, &len, f);
if (result == -1) break;
pos = -1;
isAssigned = false;
while(line[++pos])
{
if (line[pos] == '=')
{
isAssigned = true;
break;
}
}
if (! isAssigned)
{
temp = fopen("temp.c", "a+");
assinged = allo;
len = strlen(line);
memcpy(assinged, &line[0], len-2);
assinged[len-2] = '=';
assinged[len-1] = '0';
assinged[len] = ';';
assinged[len+1] = '\n';
assinged[len+2] = '\0';
fprintf(temp, "%s", assinged);
free(assinged);
fclose(temp);
}
else
{
temp = fopen("temp.c", "a+");
fprintf(temp, "%s", line);
fclose(temp);
}
}
fclose(f);
// now copy the results of temp to the program file freshened-up
f = fopen(filename, "w+"); // clear its contents
temp = fopen("temp.c", "r"); // copy this file's contents
while(1)
{
result = getline(&line, &len, temp);
if (result == -1) break;
fprintf(f, "%s", line);
}
fclose(f);
fclose(temp);
// now delete temp
remove("temp.c");
}
| 3.421875 | 3 |
2024-11-18T21:29:59.280329+00:00
| 2020-09-22T06:40:20 |
7fc716f5e6968972b1c1acc51ad62fa25f0d418f
|
{
"blob_id": "7fc716f5e6968972b1c1acc51ad62fa25f0d418f",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-22T06:40:20",
"content_id": "218c596e751d4ce4e785e17c31062afdd5c809f5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d4d1fd4d11cd4860b9299c4fd1034b7c491e2cfb",
"extension": "c",
"filename": "TwoStrings.c",
"fork_events_count": 1,
"gha_created_at": "2018-07-18T06:05:54",
"gha_event_created_at": "2020-10-01T06:36:11",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 141388402,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1587,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/CompetitiveProgramming/HackerEarth/basicInput/ex/TwoStrings.c",
"provenance": "stackv2-0112.json.gz:183438",
"repo_name": "send2manoo/Data-Structure",
"revision_date": "2020-09-22T06:40:20",
"revision_id": "c9763ec9709421a558a8dee5e3d811dd8e343960",
"snapshot_id": "264168c6310f64d96960c89e805fc9e206d75e45",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/send2manoo/Data-Structure/c9763ec9709421a558a8dee5e3d811dd8e343960/CompetitiveProgramming/HackerEarth/basicInput/ex/TwoStrings.c",
"visit_date": "2021-06-26T12:01:32.344639"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
// HASHING IS NOT A ACCURATE SOLUTION TO COMPARE TWO STRINGS. SO WE GO FOR TRADITIOAL METHOD.
int hashFunction(char S1[])
{
unsigned short int count = 0;
int hash = 0, i = 0;
while(S1[i] != '\0'){
count++;
i++;
}
for (i = 0; i < count; i++)
hash = hash + (int)S1[i];
return hash;
}
void compare(char str1[], char str2[]){
int flag;
for(int i=0;i<strlen(str1);i++) //first for loop for browsing elements of string 1
{
flag=0;
for(int j=0;j<strlen(str2);j++) //second for loop for elements of string 2
{
if(str1[i]==str2[j]) //if element of string 1 is equal string 2 break out of second loop
{ //flag variable is used to check is control reaches if block
flag = 1; //i have made elements of string 2 =0 ,so that it does not match with any other element of string 1 more than 1 time ,you can use any other logic also.
str2[j] = '0';
break;
}
}
if(flag==0) //this means control does not reach if block or the two strings are not equal.
break;
}
flag==1?printf("YES\n"):printf("NO\n");
}
int main()
{
char S1[100000], S2[100000];
unsigned int T, hash_1, hash_2, count;
scanf("%u", &T);
for (int i = 0; i < T; i++){
scanf("%s %s", S1, S2);
// hash_1 = hashFunction(S1);
// hash_2 = hashFunction(S2);
// if(hash_1 == hash_2) printf("YES\n");
// else printf("NO\n");
// OR
compare(S1, S2);
}
return 0;
}
| 3.609375 | 4 |
2024-11-18T21:29:59.724171+00:00
| 2020-12-15T03:14:29 |
b6b90ada9a610625bf24b3241a3a961f9acf8e7f
|
{
"blob_id": "b6b90ada9a610625bf24b3241a3a961f9acf8e7f",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-15T03:14:29",
"content_id": "c31e5f812c206837e77d75ba0264495b39941e06",
"detected_licenses": [
"MIT"
],
"directory_id": "c349a18d12a6ee89d3b4835beb9b4dd2c352a5b5",
"extension": "c",
"filename": "interrupt.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": 3913,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/interrupt.c",
"provenance": "stackv2-0112.json.gz:183570",
"repo_name": "evgeni-skk/SparX-III_Unmanaged",
"revision_date": "2020-12-15T03:14:29",
"revision_id": "7d85d2b0dc765e22a5c7ce1348edc91d766f7f41",
"snapshot_id": "614acb8f3dfb34a89caf8d2cc50a16fac897185f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/evgeni-skk/SparX-III_Unmanaged/7d85d2b0dc765e22a5c7ce1348edc91d766f7f41/src/main/interrupt.c",
"visit_date": "2023-05-30T22:34:05.227945"
}
|
stackv2
|
//Copyright (c) 2004-2020 Microchip Technology Inc. and its subsidiaries.
//SPDX-License-Identifier: MIT
#include "common.h" /* Always include common.h at the first place of user-defined herder files */
#include "vtss_luton26_regs.h"
#include "h2io.h"
#include "timer.h"
#include "uartdrv.h"
#include "misc2.h"
/*****************************************************************************
*
*
* Public data
*
*
*
****************************************************************************/
/*****************************************************************************
*
*
* Defines
*
*
*
****************************************************************************/
/*****************************************************************************
*
*
* Typedefs and enums
*
*
*
****************************************************************************/
/*****************************************************************************
*
*
* Prototypes for local functions
*
*
*
****************************************************************************/
/*****************************************************************************
*
*
* Local data
*
*
*
****************************************************************************/
/* ************************************************************************ */
void ext_interrupt_init (void) small
/* ------------------------------------------------------------------------ --
* Purpose : Enable external interrupts. Ext0 with low priority
* and Ext1 with high priority
* Remarks :
* Restrictions:
* See also :
* Example :
****************************************************************************/
{
/* Enable interrupt output to 8051 */
h2_write_masked(VTSS_ICPU_CFG_INTR_ICPU_IRQ1_ENA,
VTSS_F_ICPU_CFG_INTR_ICPU_IRQ1_ENA_ICPU_IRQ1_ENA,
VTSS_F_ICPU_CFG_INTR_ICPU_IRQ1_ENA_ICPU_IRQ1_ENA);
h2_write_masked(VTSS_ICPU_CFG_INTR_ICPU_IRQ0_ENA,
VTSS_F_ICPU_CFG_INTR_ICPU_IRQ0_ENA_ICPU_IRQ0_ENA,
VTSS_F_ICPU_CFG_INTR_ICPU_IRQ0_ENA_ICPU_IRQ0_ENA);
/* Enable 8051 interrupt */
PX1 = 1; /* Set high priority for ext 1 */
EX1 = 1; /* Enable ext 1 interrupt */
PX0 = 0; /* Set low priority for ext 0 */
EX0 = 1; /* Enable ext 0 interrupt */
}
/* ************************************************************************ */
void ext_1_interrupt (void) small interrupt 2 using 2
/* ------------------------------------------------------------------------ --
* Purpose : Handle UART interrupts with high priority
* Remarks : ISR could only call H2_READ, H2_WRITE, H2_WRITE_MASKED, no
* other function is shared with main
* Restrictions:
* See also :
* Example :
****************************************************************************/
{
ulong ident;
H2_READ(VTSS_ICPU_CFG_INTR_ICPU_IRQ1_IDENT, ident);
#ifndef NO_DEBUG_IF
if(test_bit_32(6, &ident)) {
// UART interrupt
uart_interrupt();
H2_WRITE(VTSS_ICPU_CFG_INTR_INTR, VTSS_F_ICPU_CFG_INTR_INTR_UART_INTR);
}
#endif
}
/* ************************************************************************ */
void ext_0_interrupt (void) small interrupt 0 using 1
/* ------------------------------------------------------------------------ --
* Purpose : Handle timer and exteral interrupts with low priority
* Remarks : ISR could only call H2_READ, H2_WRITE, H2_WRITE_MASKED, no
* other function is shared with main
* Restrictions:
* See also :
* Example :
****************************************************************************/
{
ulong ident;
H2_READ(VTSS_ICPU_CFG_INTR_ICPU_IRQ0_IDENT, ident);
if(test_bit_32(8, &ident)) {
// Timer 1 interrupt
timer_1_interrupt();
H2_WRITE(VTSS_ICPU_CFG_INTR_INTR, VTSS_F_ICPU_CFG_INTR_INTR_TIMER1_INTR);
}
}
| 2.015625 | 2 |
2024-11-18T21:29:59.848662+00:00
| 2017-12-05T21:55:58 |
99d199110a627f6f6c9b9d0445aeb3d6d3af2073
|
{
"blob_id": "99d199110a627f6f6c9b9d0445aeb3d6d3af2073",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-05T21:55:58",
"content_id": "3c3d6a3467418ff7bba9171ca6ece3a318b5dbf0",
"detected_licenses": [
"MIT"
],
"directory_id": "769f8dc0d8e4703a3beb1b95c4fe441eaa12d9cf",
"extension": "h",
"filename": "estruturas.h",
"fork_events_count": 0,
"gha_created_at": "2017-11-08T12:34:26",
"gha_event_created_at": "2017-12-05T21:55:59",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 109973691,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5831,
"license": "MIT",
"license_type": "permissive",
"path": "/include/estruturas.h",
"provenance": "stackv2-0112.json.gz:183700",
"repo_name": "LSantos06/ProxyServer",
"revision_date": "2017-12-05T21:55:58",
"revision_id": "08025eb7fdbf263d8f9ad21e4ace2f26efbee1a1",
"snapshot_id": "ba980f70801005bd17e8fc3df3abe063768f2fa1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/LSantos06/ProxyServer/08025eb7fdbf263d8f9ad21e4ace2f26efbee1a1/include/estruturas.h",
"visit_date": "2021-08-23T17:27:22.996985"
}
|
stackv2
|
/**
* @file estruturas.h
* @brief Arquivo principal com a funcao main com servico de proxy.
*/
#ifndef estruturas_h
#define estruturas_h
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <setjmp.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <math.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BACKLOG 20 // How many pending connections queue will hold
#define BUFFER 32768 // Buffer size, máx message size
// Header line list structure
typedef struct headerList
{
char *headerFieldName; /**< String para armazenar o "campo" */
char *value; /**< String para armazenar o valor do "campo" */
struct headerList *next;
} HeaderList;
// Request/Response message structure
typedef struct requestORresponse
{
char *methodORversion; /**< Se for request:method,se for response:version */
char *urlORstatusCode; /**< Se for request:url, se for response:statusCode */
char *versionORphrase; /**< Se for request:version, se for response:phrase */
HeaderList *headers;
char *body; /**< Corpo da requisicao */
} RequestORResponse;
/**
* @fn int main(int argc, char *argv[]);
* @brief Funcao principal do programa.
* @param argc Quantidade de argumentos passados pela linha de comando.
* @param argv[] Argumentos passados pela linha de comando.
* @return Status de execucao.
*/
int main(int argc, char *argv[]);
// Thread that handles pairs request/reponse
/**
* @fn void *connectionHandler(void *);
* @brief Atraves de thread maneja pares requesicoes e respostas.
* @param c_pNewSocketFD descritor da socket do servidor.
*/
void *connectionHandler(void * c_pNewSocketFD);
// General functions headers
/**
* @fn RequestORResponse* getRequestORResponseFields(char *buffer)
* @brief Parse da string buffer guarda os campos de HTTP em uma struct.
* @param buffer -> string que tem os dados enviados pelo browser.
* @return RequestORResponse estrutura que armazena as strings do cabecalho e formato HTTP.
*/
RequestORResponse* getRequestORResponseFields(char *buffer);
/**
* @fn char* getRequestORResponseMessage(RequestORResponse *requestORresponse)
* @brief Pega estrutura que tem os campos separados e monta uma string de requisicao.
* @param requestORresponse estrutura que sera usada para montar a requisicao ou mensagem de resposta.
* @return String no formato correto para envio de requisicao.
*/
char* getRequestORResponseMessage(RequestORResponse *requestORresponse);
/**
* @fn void freeRequestORResponseFiedls(RequestORResponse *requestORresponse);
* @brief Libera a memoria da estrutura que foi passada com parametro.
* @param requestORresponse estrutura que sera liberada.
*/
void freeRequestORResponseFiedls(RequestORResponse *requestORresponse);
/**
* @fn char * search_host(RequestORResponse * c_request);
* @brief Ṕrocura o valor de host dado a estrutura.
* @param c_request estrutura que sera usada para procurar o valor do host.
* @return String com o valor do host ou NULL.
*/
char * search_host(RequestORResponse * c_request);
/**
* @fn void handle_client(int c_newSocketFD);
* @brief Maneja a conexao especifica de um cliente.
* @param c_newSocketFD descritor da socket do cliente.
*/
void handle_client(int c_newSocketFD);
// HeaderList function headers
/**
* @fn HeaderList* createHeaderList();
* @brief Aloca um ponteiro de estutura HeaderList.
* @return Ponteiro para HeaderList ja inicializada.
*/
HeaderList* createHeaderList();
/**
* @fn HeaderList* insertHeaderList(HeaderList *list, char *headerFieldName, char *value)
* @brief Insere na lista de cabecalho de acordo com o headerFieldName e a string value.
* @param list ponteiro para estrutura que contem os cabecalhos e seus valores.
* @param headerFieldName String com o nome do campo do cabecalho.
* @param value valor do campo.
* @return Ponteiro para HeaderList que contem o novo elemento inserido.
*/
HeaderList* insertHeaderList(HeaderList *list, char *headerFieldName, char *value);
/**
* @fn int emptyHeaderList(HeaderList *list);
* @brief Verificia se a lista de cabecalho esta vazia.
* @param list ponteiro para estrutura que contem os cabecalhos e seus valores.
* @return 1 se estiver vazio, 0 se estiver com elementos.
*/
int emptyHeaderList(HeaderList *list);
/**
* @fn void freeHeaderList(HeaderList *list);
* @brief Libera memoria da estrutura.
* @param list ponteiro para estrutura que contem os cabecalhos e seus valores.
*/
void freeHeaderList(HeaderList *list);
/**
* @fn void printHeaderList(HeaderList *list);
* @brief Printa tudo que esta na lista de cabecalho.
* @param list ponteiro para estrutura que contem os cabecalhos e seus valores.
*/
void printHeaderList(HeaderList *list);
/**
* @fn void get_1_line(char * first_l, char * buffer);
* @brief Pega a primeira linha de uma requisicao.
* @param first_l String que ter apenas o valor da primeira linha.
* @param buffer String que tem todo conteudo do buffer.
*/
void get_1_line(char * first_l, char * buffer);
/**
* @fn void get_status(char * status, char * buffer);
* @brief Pega o status da primeira linha de uma requisicao.
* @param status String que ter apenas o valor do codigo de status.
* @param buffer String que tem todo conteudo do buffer.
*/
void get_status(char * status, char * buffer);
/**
* @fn int verify_status(char * status);
* @brief Verifica o status esta OK (2xx).
* @param status String que tem o codigo de status.
* @return 1 se comeca com 2 e 0 caso contrario.
*/
int verify_status(char * status);
#endif
| 2.484375 | 2 |
2024-11-18T21:29:59.908185+00:00
| 2018-08-06T00:26:34 |
c0af36dccfcc92497904af6465e5b037ed8be011
|
{
"blob_id": "c0af36dccfcc92497904af6465e5b037ed8be011",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-06T00:26:34",
"content_id": "168851438d016639f198f0fb38e21a2912a7953e",
"detected_licenses": [
"ISC"
],
"directory_id": "53d2d2596e793844a69a9b812406237395096fe9",
"extension": "c",
"filename": "sort.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 123381299,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3481,
"license": "ISC",
"license_type": "permissive",
"path": "/code/C/sort1/sort.c",
"provenance": "stackv2-0112.json.gz:183831",
"repo_name": "roflcopter4/random",
"revision_date": "2018-08-06T00:26:34",
"revision_id": "186e676f24a86196083d80a2eabd2e6814baaa71",
"snapshot_id": "5d569e3cac4b9d4a6ed464b7871cfcc17481a161",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/roflcopter4/random/186e676f24a86196083d80a2eabd2e6814baaa71/code/C/sort1/sort.c",
"visit_date": "2021-01-25T11:02:58.305458"
}
|
stackv2
|
#include "sort.h"
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
static int compare(const void *a, const void *b);
static void lazysort(uint32_t *list, int size);
static uint32_t * getlist();
static uint32_t * cpylist(uint32_t *list);
static inline int numdigits(int number);
#define NUM 10000
#define MAX 999999
int num_qsort_ops;
int
main(int argc, char **argv)
{
program_name = argv[0];
opt_flag_ind = num_qsort_ops = verbose = loud = 0;
numitems = NUM;
maxsize = MAX;
decode_switches(argc, argv);
intlen = numdigits(maxsize);
int i;
if ((i = sodium_init()) != 0) {
eprintf("WTF\n");
exit(i);
}
struct timeval tv1, tv2;
uint32_t *list = getlist();
for (i = 0; i < opt_flag_ind; ++i) {
uint32_t *list_copy = cpylist(list);
gettimeofday(&tv1, NULL);
if (loud)
print_intlist(list_copy, numitems);
switch (optflags[i]) {
case 'Q':
puts("Running C's 'qsort'.");
lazysort(list_copy, numitems);
break;
case 'b':
puts("Running braindead bubblesort.");
bubble_sort(list_copy, numitems);
break;
case 's':
puts("Running selection sort.");
selection_sort(list_copy, numitems);
break;
case 'r':
puts("Running recursive selection sort.");
recursive_ss(list_copy, numitems);
break;
}
if (verbose) {
print_intlist(list_copy, numitems);
puts("");
}
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
free(list_copy);
}
free(list);
return 0;
}
void
print_intlist(uint32_t *intlist, int size)
{
for (int i = 0; i < size; ++i) {
if (i < (size - 1))
printf("%*u, ", intlen, intlist[i]);
else
printf("%*u\n", intlen, intlist[i]);
}
if (numitems > 40)
printf("\n\n");
}
static uint32_t *
getlist()
{
uint32_t *list = die_malloc(numitems * sizeof(uint32_t));
for (int i = 0; i < numitems; ++i)
list[i] = randombytes_uniform(maxsize);
return list;
}
static uint32_t *
cpylist(uint32_t *list)
{
uint32_t *list_copy = die_malloc(numitems * sizeof(uint32_t));
memcpy(list_copy, list, numitems * sizeof(uint32_t));
return list_copy;
}
static inline int
numdigits(int number)
{
char tmp[BUFSIZ];
snprintf(tmp, BUFSIZ, "%d", number);
return strlen(tmp);
}
static int
compare(const void *a, const void *b)
{
/*++num_qsort_ops;*/
return (*(const uint32_t *)a > *(const uint32_t *)b);
}
static void
lazysort(uint32_t *list, int size)
{
qsort(list, size, sizeof(uint32_t), compare);
/*printf("Number of steps taken: %d\n", num_qsort_ops);*/
}
| 2.890625 | 3 |
2024-11-18T21:30:00.464368+00:00
| 2017-01-08T07:42:14 |
e16fe0c23fe5516785ee394bc81f9051e7dcdd18
|
{
"blob_id": "e16fe0c23fe5516785ee394bc81f9051e7dcdd18",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-08T07:42:14",
"content_id": "96c06c6459600cbde2e79ed9955b602c25c5f0ae",
"detected_licenses": [
"Unlicense"
],
"directory_id": "cb4b662f85b653d22be91eb857ddcdb664ab898d",
"extension": "h",
"filename": "record_mgr.h",
"fork_events_count": 1,
"gha_created_at": "2017-01-08T07:40:12",
"gha_event_created_at": "2018-04-26T20:02:13",
"gha_language": "C",
"gha_license_id": "Unlicense",
"github_id": 78328674,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1839,
"license": "Unlicense",
"license_type": "permissive",
"path": "/assign4/record_mgr.h",
"provenance": "stackv2-0112.json.gz:184218",
"repo_name": "etushar89/rdbms-core",
"revision_date": "2017-01-08T07:42:14",
"revision_id": "bd8466d42a71ec44c70e474e0d34173c2fd9085e",
"snapshot_id": "0f8a5a107fea5c289364774419c661d45a09a00c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/etushar89/rdbms-core/bd8466d42a71ec44c70e474e0d34173c2fd9085e/assign4/record_mgr.h",
"visit_date": "2021-01-12T00:58:54.245023"
}
|
stackv2
|
#ifndef RECORD_MGR_H
#define RECORD_MGR_H
#include "dberror.h"
#include "expr.h"
#include "tables.h"
// Bookkeeping for scans
typedef struct RM_ScanHandle {
RM_TableData *rel;
void *mgmtData;
} RM_ScanHandle;
typedef struct RM_ScanIterator {
int totalRecords;
int lastRecordRead;
Record** records;
} RM_ScanIterator;
// table and manager
extern RC initRecordManager(void *mgmtData);
extern RC shutdownRecordManager();
extern RC createTable(char *name, Schema *schema);
extern RC openTable(RM_TableData *rel, char *name);
extern RC closeTable(RM_TableData *rel);
extern RC deleteTable(char *name);
extern int getNumTuples(RM_TableData *rel);
extern RC deleteIndex(char *name);
// handling records in a table
extern RC insertRecord(RM_TableData *rel, Record *record);
extern RC deleteRecord(RM_TableData *rel, RID id);
extern RC updateRecord(RM_TableData *rel, Record *record);
extern RC updateScan(RM_TableData *rel, Expr *cond,
void (*op)(Schema*, Record *));
extern RC getRecord(RM_TableData *rel, RID id, Record *record);
// scans
extern RC startScan(RM_TableData *rel, RM_ScanHandle *scan, Expr *cond);
extern RC next(RM_ScanHandle *scan, Record *record);
extern RC closeScan(RM_ScanHandle *scan);
// dealing with schemas
extern int getRecordSize(Schema *schema);
extern Schema *createSchema(int numAttr, char **attrNames, DataType *dataTypes,
int *typeLength, int keySize, int *keys);
extern RC freeSchema(Schema *schema);
// dealing with records and attribute values
extern RC createRecord(Record **record, Schema *schema);
extern RC freeRecord(Record *record);
extern RC getAttr(Record *record, Schema *schema, int attrNum, Value **value);
extern RC setAttr(Record *record, Schema *schema, int attrNum, Value *value);
extern bool isNULLAttr(RM_TableData *rel, Record *record, int attrNum);
#endif // RECORD_MGR_H
| 2.015625 | 2 |
2024-11-18T21:30:00.788447+00:00
| 2019-04-12T20:19:04 |
39aa6d6a2556e8e8847a22a576bc2acda19c9408
|
{
"blob_id": "39aa6d6a2556e8e8847a22a576bc2acda19c9408",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-12T20:19:04",
"content_id": "0a33bbcc3b8125ddb28dd7598b65982f3d18cf57",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "862788954150ebc0ee04cb21ab7182672028eda6",
"extension": "h",
"filename": "entrySearch.h",
"fork_events_count": 14,
"gha_created_at": "2014-09-25T18:51:02",
"gha_event_created_at": "2017-03-17T19:52:22",
"gha_language": "Cuda",
"gha_license_id": null,
"github_id": 24470875,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6417,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/entrySearch.h",
"provenance": "stackv2-0112.json.gz:184612",
"repo_name": "groundcherry/bluebottle",
"revision_date": "2019-04-12T20:19:04",
"revision_id": "5ab46c235c6809f167be22685909fb917e13a282",
"snapshot_id": "4eb5d9bf5961c7a3579c4d0435605c6718c631cc",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/groundcherry/bluebottle/5ab46c235c6809f167be22685909fb917e13a282/src/entrySearch.h",
"visit_date": "2020-12-24T08:23:09.249758"
}
|
stackv2
|
/*******************************************************************************
********************************* BLUEBOTTLE **********************************
*******************************************************************************
*
* Copyright 2012 - 2016 Adam Sierakowski, The Johns Hopkins University
*
* 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.
*
* Please contact the Johns Hopkins University to use Bluebottle for
* commercial and/or for-profit applications.
******************************************************************************/
/* entrySearch
*
* An algorithm to find the minimum or maximum value of an array using a GPU.
* This program searches an array of reals of arbitrary length and returns the
* minimum or maximum value of the array.
*
* Adam J. Sierakowski, JHU/APL 2011
*/
/****h* Bluebottle/entrySearch
* NAME
* entrySearch
* FUNCTION
* An algorithm to find the minimum or maximum value of an array using a GPU.
* This program searches an array of reals of arbitrary length and returns the
* minimum or maximum value of the array.
******
*/
/****h* Bluebottle/entrySearch_kernel
* NAME
* entrySearch_kernel
* FUNCTION
* EntrySearch CUDA kernel functions.
******
*/
#ifndef __ENTRYSEARCH_H__
#define __ENTRYSEARCH_H__
extern "C"
{
#include "bluebottle.h"
}
/****f* entrySearch/find_min()
* NAME
* find_min()
* USAGE
*/
real find_min(int size, real *d_iarr);
/*
* FUNCTION
* Return the minimum value of array d_iarr. Note that d_iarr will be
* destroyed by the reduction algorithm.
* ARGUMENTS
* * size -- the size of the array
* * d_iarr -- the array to search (must be allocated on the device); it will
* be destroyed by the reduction algorithm
******
*/
/****f* entrySearch/find_max()
* NAME
* find_max()
* USAGE
*/
real find_max(int size, real *d_iarr);
/*
* FUNCTION
* Return the maximum value of array d_iarr. Note that d_iarr will be
* destroyed by the reduction algorithm.
* ARGUMENTS
* * size -- the size of the array
* * d_iarr -- the array to search (must be allocated on the device); it will
* be destroyed by the reduction algorithm
******
*/
/****f* entrySearch/find_max_int()
* NAME
* find_max_int()
* USAGE
*/
int find_max_int(int size, int *d_iarr);
/*
* FUNCTION
* Return the maximum value of array d_iarr. Note that d_iarr will be
* destroyed by the reduction algorithm.
* ARGUMENTS
* * size -- the size of the array
* * d_iarr -- the array to search (must be allocated on the device); it will
* be destroyed by the reduction algorithm
******
*/
/****f* entrySearch/find_max_mag()
* NAME
* find_max_mag()
* USAGE
*/
real find_max_mag(int size, real *d_iarr);
/*
* FUNCTION
* Return the maximum magnitude value of array d_iarr. Note that d_iarr will
* be destroyed by the reduction algorithm.
* ARGUMENTS
* * size -- the size of the array
* * d_iarr -- the array to search (must be allocated on the device); it will
* be destroyed by the reduction algorithm
******
*/
/****f* entrySearch/avg_entries()
* NAME
* avg_entries()
* USAGE
*/
real avg_entries(int size, real *d_iarr);
/*
* FUNCTION
* Return the average of the entries of array d_iarr. Note that d_iarr will
* be destroyed by the reduction algorithm.
* ARGUMENTS
* * size -- the size of the array
* * d_iarr -- the array to average (must be allocated on the device); it will
* be destroyed by the reduction algorithm
******
*/
/****f* entrySearch/sum_entries()
* NAME
* sum_entries()
* USAGE
*/
real sum_entries(int size, real *d_iarr);
/*
* FUNCTION
* Return the sum of the entries of array d_iarr. Note that d_iarr will
* be destroyed by the reduction algorithm.
* ARGUMENTS
* * size -- the size of the array
* * d_iarr -- the array to average (must be allocated on the device); it will
* be destroyed by the reduction algorithm
******
*/
/****f* entrySearch_kernel/entrySearch_min_kernel<<<>>>()
* NAME
* entrySearch_min_kernel<<<>>>()
* USAGE
*/
__global__ void entrySearch_min_kernel(real *iarr, real *minarr,
int size);
/*
* FUNCTION
* Kernel function called by find_min().
* ARGUMENTS
* * iarr -- the input array
* * minarr -- the ouput array
* * size -- the size of the input array
******
*/
/****f* entrySearch_kernel/entrySearch_max_kernel<<<>>>()
* NAME
* entrySearch_max_kernel<<<>>>()
* USAGE
*/
__global__ void entrySearch_max_kernel(real *iarr, real *maxarr,
int size);
/*
* FUNCTION
* Kernel function called by find_max().
* ARGUMENTS
* * iarr -- the input array
* * maxarr -- the ouput array
* * size -- the size of the input array
******
*/
/****f* entrySearch_kernel/entrySearch_max_int_kernel<<<>>>()
* NAME
* entrySearch_max_int_kernel<<<>>>()
* USAGE
*/
__global__ void entrySearch_max_int_kernel(int *iarr, int *maxarr,
int size);
/*
* FUNCTION
* Kernel function called by find_max().
* ARGUMENTS
* * iarr -- the input array
* * maxarr -- the ouput array
* * size -- the size of the input array
******
*/
/****f* entrySearch_kernel/entrySearch_max_mag_kernel<<<>>>()
* NAME
* entrySearch_max_mag_kernel<<<>>>()
* USAGE
*/
__global__ void entrySearch_max_mag_kernel(real *iarr, real *maxarr,
int size);
/*
* FUNCTION
* Kernel function called by find_max_mag().
* ARGUMENTS
* * iarr -- the input array
* * maxarr -- the ouput array
* * size -- the size of the input array
******
*/
/****f* entrySearch_kernel/entrySearch_avg_entries_kernel<<<>>>()
* NAME
* entrySearch_avg_entries_kernel<<<>>>()
* USAGE
*/
__global__ void entrySearch_avg_entries_kernel(real *iarr, real *maxarr,
int size);
/*
* FUNCTION
* Kernel function called by avg_entries().
* ARGUMENTS
* * iarr -- the input array
* * maxarr -- the ouput array
* * size -- the size of the input array
******
*/
#endif
| 2.359375 | 2 |
2024-11-18T21:30:00.862042+00:00
| 2017-05-24T21:20:45 |
ff169edf7ea9dc420c3ea8f467b7fcc7e5105057
|
{
"blob_id": "ff169edf7ea9dc420c3ea8f467b7fcc7e5105057",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-24T21:20:45",
"content_id": "5ff687c716f759cc79445e7f75c1902fbfed3967",
"detected_licenses": [
"MIT"
],
"directory_id": "054295d551faaf2e02ba4a2816cc1d597cce0820",
"extension": "c",
"filename": "pruebas_alumno.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": 15557,
"license": "MIT",
"license_type": "permissive",
"path": "/pruebas_alumno.c",
"provenance": "stackv2-0112.json.gz:184744",
"repo_name": "GonzaDiz/abb",
"revision_date": "2017-05-24T21:20:45",
"revision_id": "b9b157dacfffa97b1c475e74fa8edc978c8a7142",
"snapshot_id": "cac4802c094146ffd0ee93960df1dc2878b70f65",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GonzaDiz/abb/b9b157dacfffa97b1c475e74fa8edc978c8a7142/pruebas_alumno.c",
"visit_date": "2020-07-11T17:28:23.558024"
}
|
stackv2
|
#include "abb.h"
#include "testing.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
/* ******************************************************************
* PRUEBAS UNITARIAS
* *****************************************************************/
static void prueba_crear_abb_vacio(){
printf("---------------------------PRUEBAS CREAR ABB VACIO---------------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* str = "test";
print_test("Prueba crear abb vacio", abb);
print_test("Prueba la cantidad de nodos en el abb es igual a 0", abb_cantidad(abb) == 0);
print_test("Prueba buscar una clave en un abb vacio devuelve NULL",!abb_obtener(abb,str));
print_test("Prueba ver si un valor esta en el abb y la clave no existe devuelve NULL",!abb_pertenece(abb,str));
abb_destruir(abb);
print_test("El arbol se destruyo correctamente",true);
}
static void pruebas_abb_guardar(){
printf("---------------------------PRUEBAS ABB GUARDAR---------------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* claves[] = {"f","z","d","a"};
char* datos[] = {"f","z","d","a"};
print_test("Prueba crear abb vacio", abb);
print_test("Prueba la cantidad de nodos en el abb es igual a 0", abb_cantidad(abb) == 0);
// Prueba guardar el primer elemento
print_test("Prueba guardar un nodo de raiz",abb_guardar(abb,claves[0],datos[0]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 1", abb_cantidad(abb) == 1);
print_test("Prueba abb obtener devuelve f",abb_obtener(abb,claves[0]) == datos[0]);
print_test("Prueba abb pertenece devuelve true con clave f", abb_pertenece(abb,claves[0]) == true);
// Prueba guardar un segundo elemento el cual es mayor, hijo derecho
print_test("Prueba abb pertenee devuelve false con clave z", abb_pertenece(abb,claves[1]) == false);
print_test("Prueba guardar un nodo con clave z", abb_guardar(abb,claves[1],datos[1]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 2", abb_cantidad(abb) == 2);
print_test("Prueba abb obtener de clave z devuelve z", abb_obtener(abb,claves[1]) == datos[1]);
print_test("Prueba abb pertence devuelve true con clave z", abb_pertenece(abb,claves[1]) == true);
// Prueba guardar un tercer elemento el cual es menor, hijo izquierdo
print_test("Prueba guardar un nodo con clave d", abb_guardar(abb,claves[2],datos[2]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 3", abb_cantidad(abb) == 3);
print_test("Prueba abb obtener de clave d devuelve d", abb_obtener(abb,claves[2]) == datos[2]);
print_test("Prueba abb pertence devuelve true con clave d", abb_pertenece(abb,claves[2]) == true);
print_test("Prueba guardar un nodo con clave a", abb_guardar(abb,claves[3],datos[3]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 4", abb_cantidad(abb) == 4);
print_test("Prueba abb obtener de clave a devuelve a", abb_obtener(abb,claves[3]) == datos[3]);
print_test("Prueba abb pertence devuelve true con clave a", abb_pertenece(abb,claves[3]) == true);
abb_destruir(abb);
print_test("El arbol se destruyo correctamente",true);
}
static void pruebas_abb_guardar_claves_iguales(){
printf("---------------------------PRUEBAS ABB GUARDAR CLAVES IGUALES---------------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* claves[] = {"f","a","f","a"};
char* datos[] = {"f","a","f2","a2"};
print_test("Prueba crear abb vacio", abb);
print_test("Prueba la cantidad de nodos en el abb es igual a 0", abb_cantidad(abb) == 0);
// Prueba guardar el primer elemento
print_test("Prueba guardar un nodo de raiz",abb_guardar(abb,claves[0],datos[0]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 1", abb_cantidad(abb) == 1);
print_test("Prueba abb obtener devuelve f",abb_obtener(abb,claves[0]) == datos[0]);
print_test("Prueba abb pertenece devuelve true con clave f", abb_pertenece(abb,claves[0]) == true);
print_test("Prueba abb pertenee devuelve false con clave a", abb_pertenece(abb,claves[1]) == false);
print_test("Prueba guardar un nodo con clave a", abb_guardar(abb,claves[1],datos[1]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 2", abb_cantidad(abb) == 2);
print_test("Prueba abb obtener de clave a devuelve a", abb_obtener(abb,claves[1]) == datos[1]);
print_test("Prueba abb pertence devuelve true con clave a", abb_pertenece(abb,claves[1]) == true);
// Prueba guardar un tercer elemento el cual es menor, hijo izquierdo
print_test("Prueba guardar un nodo con clave f", abb_guardar(abb,claves[2],datos[2]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 2", abb_cantidad(abb) == 2);
print_test("Prueba abb obtener de clave f devuelve f", abb_obtener(abb,claves[2]) == datos[2]);
print_test("Prueba abb pertence devuelve true con clave d", abb_pertenece(abb,claves[2]) == true);
print_test("Prueba guardar un nodo con clave a", abb_guardar(abb,claves[3],datos[3]) == true);
print_test("Prueba la cantidad de nodos en el abb es igual a 2", abb_cantidad(abb) == 2);
print_test("Prueba abb obtener de clave a devuelve a", abb_obtener(abb,claves[3]) == datos[3]);
print_test("Prueba abb pertence devuelve true con clave a", abb_pertenece(abb,claves[3]) == true);
abb_destruir(abb);
print_test("El arbol se destruyo correctamente",true);
}
static void pruebas_abb_borrar_hojas(){
printf("---------------------------PRUEBAS ABB BORRAR---------------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* claves[] = {"f","z","d","a"};
char* datos[] = {"f","z","d","a"};
print_test("Guardar clave f en el abb",abb_guardar(abb,claves[0],datos[0]) == true);
print_test("Guardar clave z en el abb",abb_guardar(abb,claves[1],datos[1]) == true);
print_test("Guardar clave d en el abb",abb_guardar(abb,claves[2],datos[2]) == true);
print_test("Guardar clave a en el abb",abb_guardar(abb,claves[3],datos[3]) == true);
print_test("Prueba cantidad es igual a 4", abb_cantidad(abb) == 4);
print_test("Intento borrar una clave que no existe es NULL", abb_borrar(abb,"i") == NULL);
print_test("Prueba cantidad es igual a 4", abb_cantidad(abb) == 4);
print_test("Prueba borrar hoja a", abb_borrar(abb,claves[3]) == claves[3]);
print_test("Prueba a ya no pertenece al arbol", abb_pertenece(abb,claves[3]) == false);
print_test("Prueba cantidad es igual a 3", abb_cantidad(abb) == 3);
print_test("Prueba borrar hoja z", abb_borrar(abb,claves[1]) == claves[1]);
print_test("Prueba z ya no pertenece al arbol", abb_pertenece(abb,claves[1]) == false);
print_test("Prueba cantidad es igual a 2", abb_cantidad(abb) == 2);
print_test("Prueba borrar hoja d", abb_borrar(abb,claves[2]) == claves[2]);
print_test("Prueba d ya no pertenece al arbol", abb_pertenece(abb,claves[2]) == false);
print_test("Prueba cantidad es igual a 1", abb_cantidad(abb) == 1);
print_test("Prueba borrar raiz/hoja f", abb_borrar(abb,claves[0]) == claves[0]);
print_test("Prueba f ya no pertenece al arbol", abb_pertenece(abb,claves[0]) == false);
print_test("Prueba cantidad es igual a 0", abb_cantidad(abb) == 0);
abb_destruir(abb);
print_test("El arbol se destruyo correctamente",true);
}
static void pruebas_abb_borrar_nodo_con_un_hijo(){
printf("-------------------PRUEBAS ABB BORRAR UN HIJO---------------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* claves[] = {"f","x","d","a","z"};
char* datos[] = {"f","x","d","a","z"};
print_test("Guardar clave f en el abb",abb_guardar(abb,claves[0],datos[0]) == true);
print_test("Guardar clave x en el abb",abb_guardar(abb,claves[1],datos[1]) == true);
print_test("Guardar clave d en el abb",abb_guardar(abb,claves[2],datos[2]) == true);
print_test("Guardar clave a en el abb",abb_guardar(abb,claves[3],datos[3]) == true);
print_test("Guardar clave z en el abb",abb_guardar(abb,claves[4],datos[4]) == true);
print_test("Prueba cantidad es igual a 5", abb_cantidad(abb) == 5);
print_test("Prueba borrar nodo con un hijo y devuelve d", abb_borrar(abb,claves[2]) == datos[2]);
print_test("Comprobar que d ya no pertenece al arbol", abb_pertenece(abb,claves[2]) == false);
print_test("Comprobar que a pertenece al arbol", abb_pertenece(abb,claves[3]) == true);
print_test("Prueba cantidad es igual a 4", abb_cantidad(abb) == 4);
print_test("Prueba borrar nodo con un hijo x", abb_borrar(abb,claves[1]) == datos[1]);
print_test("Prueba cantidad es igual a 3", abb_cantidad(abb) == 3);
print_test("Prueba borrar hoja z", abb_borrar(abb,claves[4]) == datos[4]);
print_test("Prueba z no pertenece al arbol", abb_pertenece(abb,claves[4]) == false);
print_test("Prueba borrar raiz f", abb_borrar(abb,claves[0]) == datos[0]);
print_test("Prueba cantidad es igual a 1", abb_cantidad(abb) == 1);
abb_destruir(abb);
print_test("El arbol se destruyo correctamente",true);
}
static void pruebas_abb_borrar_nodo_con_dos_hijos(){
printf("-------------------PRUEBAS ABB BORRAR NODO CON DOS HIJOS------------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* claves[] = {"40","30","50","15","35","60","10","20","38"};
char* datos[] = {"40","30","50","15","35","60","10","20","38"};
bool ok = true;
for (int i = 0; i<9; i++){
ok = abb_guardar(abb,claves[i],datos[i]);
if (!ok) break;
}
print_test("Prueba almacenar elementos", ok);
print_test("Prueba cantidad es igual a 9", abb_cantidad(abb) == 9);
print_test("Prueba borrar nodo 30 con dos hijos", abb_borrar(abb,claves[1]) == datos[1]);
print_test("Prueba cantidad es igual a 8", abb_cantidad(abb) == 8);
print_test("Pruebo que el nodo 30 ya no existe", abb_pertenece(abb,claves[1]) == false);
print_test("Prueba borrar nodo 35 con dos hijos", abb_borrar(abb,claves[4]) == datos[4]);
print_test("Prueba cantidad es igual a 7", abb_cantidad(abb) == 7);
print_test("Pruebo que el nodo 35 ya no pertenece", abb_pertenece(abb,claves[4]) == false);
print_test("Pruebo borrar nodo 15 con dos hijos", abb_borrar(abb,claves[3]) == datos[3]);
print_test("Prueba cantidad es igual a 6",abb_cantidad(abb) == 6);
print_test("Pruebo que 15 ya no pertenece", abb_pertenece(abb,claves[3]) == false);
abb_destruir(abb);
print_test("El arbol se destruyo correctamente",true);
}
static void pruebas_abb_volumen(size_t largo){
printf("-------------------PRUEBAS ABB VOLUMEN ------------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
const size_t largo_clave = 10;
char (*claves)[largo_clave] = malloc (largo * largo_clave);
char (*datos)[largo_clave] = malloc (largo * largo_clave);
time_t t;
srand((unsigned) time(&t));
bool ok = true;
for (int i = 0;i <largo;i++){
sprintf(claves[i], "%08d",(rand() % 500000));
//Me aseguro que no haya claves repetidas asi puedo probar pertenece y obtener sin tantos problemas
while (abb_pertenece(abb,claves[i])){
sprintf(claves[i], "%08d", (rand() % 500000));
}
strcpy(datos[i],claves[i]);
//sprintf(datos[i],"%08d", claves[i]);
ok = abb_guardar(abb,claves[i],datos[i]);
if (!ok) break;
//printf("%08d\n",rand() % i);
}
print_test("Prueba abb guardar muchos elementos", ok);
print_test("Prueba abb cantidad",abb_cantidad(abb) == largo);
for (int i = 0;i < largo; i++){
ok = abb_pertenece(abb,claves[i]);
if (!ok) break;
ok = abb_obtener(abb,claves[i]) == datos[i];
if (!ok) break;
}
print_test("Las claves y los datos pertenecen al abb",ok);
for (int i=0; i<(largo/2);i++){
ok = abb_borrar(abb,claves[i]) == datos[i];
if (!ok) break;
}
print_test("Borrar la mitad del abb es ok",ok);
abb_destruir(abb);
free(claves);
free(datos);
}
bool buscar_dato(const char* clave, void* datos, void* extra){
if(datos == extra) return false;
return true;
}
static void pruebas_abb_iterador_interno(){
printf("-------------------PRUEBAS ABB ITERARDOR INTERNO-----------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* claves[] = {"40","30","50","15","35","60","10","20","38"};
char* datos[] = {"40","30","50","15","35","60","10","20","38"};
bool ok = true;
for (int i = 0; i<9; i++){
ok = abb_guardar(abb,claves[i],datos[i]);
if (!ok) break;
}
print_test("Prueba almacenar elementos", ok);
abb_in_order(abb,buscar_dato,datos[4]);
print_test("No se modifico la posicion inicial de abb",abb_obtener(abb,claves[0]) == datos[0]);
abb_destruir(abb);
print_test("El arbol se destruyo correctamente",true);
}
static void pruebas_abb_iterador_externo(){
printf("-------------------PRUEBAS ABB ITERARDOR EXTERNO-----------------------\n");
abb_t* abb = abb_crear(strcmp,NULL);
char* claves[] = {"40","30","50","15","35","60","10","20","38"};
char* datos[] = {"40","30","50","15","35","60","10","20","38"};
bool ok = true;
for (int i = 0; i<9; i++){
ok = abb_guardar(abb,claves[i],datos[i]);
if (!ok) break;
}
print_test("Prueba almacenar elementos", ok);
abb_iter_t* iter = abb_iter_in_crear(abb);
print_test("El iterador ha sido creado",true);
print_test("El actual del iterador es 10",strcmp(abb_iter_in_ver_actual(iter),claves[6]) == 0);
print_test("Avanzo en el iterador es verdadero",abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 15",strcmp(abb_iter_in_ver_actual(iter),claves[3]) == 0);
print_test("El iterador no esta al final",abb_iter_in_al_final(iter) == false);
print_test("Avanzo en el iterador es verdadero",abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 20",strcmp(abb_iter_in_ver_actual(iter),claves[7]) == 0);
print_test("Avanzo en el iterador es verdadero",abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 30",strcmp(abb_iter_in_ver_actual(iter),claves[1]) == 0);
print_test("Avanzo en el iterador es verdadero", abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 35",strcmp(abb_iter_in_ver_actual(iter),claves[4]) == 0);
print_test("Avanzo en el iterador es verdadero", abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 38",strcmp(abb_iter_in_ver_actual(iter),claves[8]) == 0);
print_test("Avanzo en el iterador es verdadero", abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 40",strcmp(abb_iter_in_ver_actual(iter),claves[0]) == 0);
print_test("Avanzo en el iterador es verdadero", abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 50",strcmp(abb_iter_in_ver_actual(iter),claves[2]) == 0);
print_test("Avanzo en el iterador es verdadero", abb_iter_in_avanzar(iter) == true);
print_test("El actual del iterador es 60",strcmp(abb_iter_in_ver_actual(iter),claves[5]) == 0);
print_test("Avanzo en el iterador es falso", abb_iter_in_avanzar(iter) == false);
print_test("Iterador esta al final es verdadero", abb_iter_in_al_final(iter) == true);
abb_destruir(abb);
print_test("ABB destruido",true);
abb_iter_in_destruir(iter);
print_test("Iterador destruido", true);
}
/* ******************************************************************
* FUNCIÓN PRINCIPAL
* ******************************************************************/
void pruebas_abb_alumno()
{
/* Ejecuta todas las pruebas unitarias. */
prueba_crear_abb_vacio();
pruebas_abb_guardar();
pruebas_abb_guardar_claves_iguales();
pruebas_abb_borrar_hojas();
pruebas_abb_borrar_nodo_con_un_hijo();
pruebas_abb_borrar_nodo_con_dos_hijos();
pruebas_abb_volumen(5000);
pruebas_abb_iterador_interno();
pruebas_abb_iterador_externo();
}
| 3.1875 | 3 |
2024-11-18T21:30:00.937143+00:00
| 2015-09-19T11:42:51 |
35053dd99435b5dca35d0b4c07633b9b736a104e
|
{
"blob_id": "35053dd99435b5dca35d0b4c07633b9b736a104e",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-19T11:42:51",
"content_id": "6645f303188ab538966aaa896d36b0d76e9f2436",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d7d3e71895c02a7a9af0960a0c7f16d9e804a816",
"extension": "c",
"filename": "trie.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": 11050,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/experiments/tries/second_trie/trie.c",
"provenance": "stackv2-0112.json.gz:184874",
"repo_name": "pombredanne/pulp_db",
"revision_date": "2015-09-19T11:42:51",
"revision_id": "97f4af562901167a6fc05c9cc4fd4a86f01b97d8",
"snapshot_id": "318c41a30c59d124c20a299c8e058f700e56f44a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pombredanne/pulp_db/97f4af562901167a6fc05c9cc4fd4a86f01b97d8/experiments/tries/second_trie/trie.c",
"visit_date": "2020-04-06T06:22:04.225972"
}
|
stackv2
|
/*
// This feels like the same problem with storing the refs
// bit vs diff vs encoded vs plain
// We need to store offsets of keys.
// Say every first letter, 256 possibilities. Say only 3 first letters are used. But maybe 200 are used.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "trie.h"
static int goto_node_zero(struct trie__view *t);
static int goto_node_zero(struct trie__view *t)
{
// -1 just temp value. We re-evaluate it.
//first child of every node all the way down
struct trie__node *n = t->root;
struct trie__frame tmp = {-1, n};
t->stack_index = 0;
t->stack[t->stack_index] = tmp;
while (n->children != NULL)
{
t->stack[t->stack_index].stack_child_index = 0;
n = n->children + 0; // Get first child
struct trie__frame tmp = {-1, n};
t->stack_index++;
t->stack[t->stack_index] = tmp;
}
return 0;
}
static struct trie__node *next_node(struct trie__view *t);
static struct trie__node *next_node(struct trie__view *t)
{
//printf("stack index =%d \n", t->stack_index);
struct trie__node *n = t->stack[t->stack_index].node;
//printf("Is it here?\n");
// printf("t->stack_index %d\n", t->stack_index);
//printf("t->children %p\n", n->children);
if (t->stack_index < 0)
{
//printf("1?\n");
return NULL;
}
else if (n->children == NULL)
{
//printf("!!!\n");
return t->stack[t->stack_index--].node; //yield node then move back one
}
else if (t->stack[t->stack_index].stack_child_index == -1) // -1 when children not null equals unexplored set of chieldren.
{
//printf("coring here\n");
t->stack[t->stack_index].stack_child_index = 0; // Going into the first child
t->stack_index++;
t->stack[t->stack_index].stack_child_index = -1;
t->stack[t->stack_index].node = t->stack[t->stack_index-1].node->children + 0;
return next_node(t);
}
else
{
//printf("key = %c\n", t->stack[t->stack_index].node->children[t->stack[t->stack_index].stack_child_index].key);
//printf("things %d %d\n", t->stack_index, t->stack[t->stack_index].stack_child_index);
if (t->stack[t->stack_index].stack_child_index < t->stack[t->stack_index].node->last_i)
{
//printf("or here %d %d\n", t->stack[t->stack_index].stack_child_index, t->stack[t->stack_index].node->last_i);
(t->stack[t->stack_index].stack_child_index)++; // Moving on to next child
t->stack_index++;
//printf("mmmkey = %c\n", t->stack[t->stack_index].node->children[t->stack[t->stack_index].stack_child_index].key);
//printf("things %d %d\n", t->stack_index, t->stack[t->stack_index].stack_child_index);
t->stack[t->stack_index].stack_child_index = -1;
t->stack[t->stack_index].node = t->stack[t->stack_index-1].node->children + (t->stack[t->stack_index-1].stack_child_index); // This addition >0 as in this clause.
//printf("moving on to next node\n");
return next_node(t);
//printf("post next node\n");
}
else
{
// Yield current and move up one
//printf("???\n");
return t->stack[t->stack_index--].node;
}
}
return NULL;
}
static bool power_of_two(unsigned char i);
static bool power_of_two(unsigned char i)
{
if (((i) & (i - 1)) == 0) // See exercise 2.9 K&R
{
return true;
}
else
{
return false;
}
}
static void trie__init_node(struct trie__node *new_node);
static void trie__init_node(struct trie__node *new_node)
{
new_node->keys = NULL;
new_node->children = NULL;
new_node->last_i = 0;
new_node->has_value = false;
new_node->result = 0;
}
static struct trie__node *new_child_node(struct trie__node *n, char key, unsigned char position);
static struct trie__node *new_child_node(struct trie__node *n, char key, unsigned char position)
{
if (n->children == NULL)
{
assert(position==0);
n->last_i = 0;
n->children = malloc(sizeof(struct trie__node[1]));
n->keys = malloc(sizeof(char));
trie__init_node(n->children + 0);
n->keys[0] = key;
return n->children + 0;
}
else if (n->last_i == 255)
{
printf("Is not possible to add to a full node\n");
exit(EXIT_FAILURE);
}
if (power_of_two(n->last_i + 1))
{
unsigned char old_size = n->last_i + 1;
unsigned char new_size = old_size << 1;
n->keys = realloc(n->keys, sizeof(char [new_size]));
n->children = realloc(n->children, sizeof(struct trie__node [new_size]));
}
n->last_i++;
bool append = (position == n->last_i);
bool error = (position > n->last_i);
if (append)
{
assert(position==n->last_i);
}
else if (error)
{
printf("ERROR: can only use this to append or inplace insertion\n");
exit(EXIT_FAILURE);
}
else // inplace
{
int ksize = sizeof(n->keys[position])*(n->last_i-position); //inclusive last_i is now cur len due to ++
memmove(n->keys+position+1, n->keys+position, ksize);
int size = sizeof(n->children[position])*(n->last_i-position); //inclusive last_i is now cur len due to ++
memmove(n->children+position+1, n->children+position, size); // Shift over by one
}
struct trie__node *new_child = n->children + position;
trie__init_node(new_child);
n->keys[position] = key;
return new_child;
}
static unsigned char bisect_children(const struct trie__node *n, const char letter);
static unsigned char bisect_children(const struct trie__node *n, const char letter)
{
/* Will return position where letter equals
or the position where that letter should be placed.
*/
unsigned char last_i = n->last_i;
int low = 0;
int high = last_i;
char c;
unsigned char p = 0;
while (low <= high)
{
p = (high+low)/2;
c = n->keys[p];
//printf("fkeys %c\n", c);
if (letter > c)
{
low = p + 1;
p++; //If we break straight after this is the position.
}
else if (letter < c)
{
high = p - 1;
}
else
{
return p; // returning matching p allows us to use above as a binary search as well.
}
}
return p;
}
static struct trie__node *trie__setdefault(struct trie__view *t, unsigned char *key, unsigned int len, bool not_found_init);
static struct trie__node *trie__setdefault(struct trie__view *t, unsigned char *key, unsigned int len, bool not_found_init)
{
struct trie__node *n = t->root;
char letter;
bool found = false;
unsigned int letter_index;
for (letter_index=0; letter_index<len; ++letter_index)
{
letter = key[letter_index];
//printf("fletter='%u'\n", field[letter_index]);
found = false;
if (n->children == NULL)
break; // n has no children
// binary search here? Better if children split into nodes[] and keys[]??? Cache?
int position = bisect_children(n, letter);
if (position > n->last_i)
{
}
else if (n->keys[position] == letter)
{
//printf("Found %c %d\n", letter, position);
n = n->children + position;
found = true;
}
else
{
//printf("Not Found %c %d\n", letter, position);
}
if (!found)
break;
}
if (not_found_init && !found)
{
while (letter_index<len)
{
letter = key[letter_index];
//printf("iletter='%u'\n", field[letter_index]);
int position;
if (n->children == NULL)
{
position = 0;
}
else
{
position = bisect_children(n, letter);
}
//printf("Adding node %c %d %d\n", letter, letter_index, position);
n = new_child_node(n, letter, position);
if (n==NULL)
{
printf("Couldn't make child node");
return NULL;
}
++letter_index;
}
n->has_value = true;
n->result = 0;
found = true;
t->len++;
}
if (found)
{
return n;
}
else
{
return NULL;
}
}
/*---
GLOBAL METHODS
---*/
int trie__open(struct trie__view *t, char *trie_name)
{
strncpy(t->trie_name, trie_name, TRIE_NAME_SIZE);
t->len = 0;
t->stack_index = -1;
//t->stack[0] = NULL;
t->root = malloc(sizeof(struct trie__node));
trie__init_node(t->root);
return 0;
}
struct trie__node *trie__get(struct trie__view *t, void *key, unsigned int len)
{
return trie__setdefault(t, key, len, false);
}
struct trie__node *trie__add(struct trie__view *t, void *key, unsigned int len)
{
return trie__setdefault(t, key, len, true);
}
unsigned long long trie__len(struct trie__view *t)
{
return t->len;
}
bool trie__has_value(struct trie__node *n)
{
return (n->has_value);
}
int trie__has_children(struct trie__node *n)
{
if (n->children == NULL)
{
return 0;
}
else
return n->last_i + 1;
}
int trie__close(struct trie__view *t)
{
printf("Pre goto_node_zero \n");
goto_node_zero(t);
printf("Post goto_node_zero \n");
while (true)
{
//printf("pre next \n");
struct trie__node *n = next_node(t);
//unsigned char tmp[256];
//unsigned int len = 0;
//trie__fullkey(t, tmp, &len);
//tmp[len] = '\0';
//printf("full_key='%s'\n", tmp);
//printf("foobar %lld\n", n->result);
//printf("post next \n");
if (n == NULL)
break;
if (n->children != NULL)
{
//printf("childrern = '%.*s'\n", n->last_i+1, n->keys);
//printf("Freeing children array \n");
free(n->children);
n->children = NULL;
free(n->keys);
n->keys = NULL;
}
}
printf("freeing root\n");
free(t->root);
t->root = NULL;
return 0;
}
int trie__iter(struct trie__view *t)
{
return goto_node_zero(t);
}
struct trie__node *trie__next(struct trie__view *t)
{
struct trie__node *node = NULL;
while (true)
{
node = next_node(t);
if (node == NULL)
break;
if (node->has_value)
{
break;
}
}
return node;
}
int trie__fullkey(struct trie__view *t, unsigned char *dest, unsigned int *len)
{
unsigned int i;
for (i = 0; i <= t->stack_index; ++i)
{
int c_i = t->stack[i].stack_child_index;
dest[i] = t->stack[i].node->keys[c_i];
}
*len = i;
return 0;
}
| 3.359375 | 3 |
2024-11-18T21:30:05.995471+00:00
| 2021-03-08T02:53:53 |
c6b1eb8b174e7e157ddf921a9aaeca1a9a33c783
|
{
"blob_id": "c6b1eb8b174e7e157ddf921a9aaeca1a9a33c783",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-08T02:53:53",
"content_id": "1ee43ec9589f6d93ab9976d28f0d1644e7d38b80",
"detected_licenses": [
"MIT"
],
"directory_id": "d638632476dab44ffe49dbc736730679d784c85f",
"extension": "c",
"filename": "heap_ops.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 302788186,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1541,
"license": "MIT",
"license_type": "permissive",
"path": "/0x02-huffman_coding/heap/heap_ops.c",
"provenance": "stackv2-0112.json.gz:185395",
"repo_name": "gogomillan/holbertonschool-system_algorithms",
"revision_date": "2021-03-08T02:53:53",
"revision_id": "62d3da4a8b2dfbd00ba2e38322d19598b259076e",
"snapshot_id": "5e9010e481cb37ac516aee9217c71854aa0eb796",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gogomillan/holbertonschool-system_algorithms/62d3da4a8b2dfbd00ba2e38322d19598b259076e/0x02-huffman_coding/heap/heap_ops.c",
"visit_date": "2023-03-18T15:43:16.500256"
}
|
stackv2
|
#include "heap.h"
#define RIGHT 1
#define LEFT 0
#define FLOOR(n) (n - (n % 1))
#define CEILING_POS(X) ((X - (int)(X)) > 0 ? (int)(X + 1) : (int)(X))
#define CEILING_NEG(X) ((X - (int)(X)) < 0 ? (int)(X - 1) : (int)(X))
#define CEIL(X) (((X) > 0) ? CEILING_POS(X) : CEILING_NEG(X))
/**
* power - compute @n to the power of @e
*
* @n: number
* @e: exponent
*
* Return: n^e
*/
int power(int n, int e)
{
int new_n;
if (e == 0)
return (1);
new_n = power(n, e / 2);
if (e % 2 == 0)
return (new_n * new_n);
else
return (n * new_n * new_n);
}
/**
* logarithm2 - compute the log2 of @n
*
* @n: number to log
*
* Return: 2nd logarithm of @n
*/
int logarithm2(int n)
{
return ((n > 1) ? 1 + logarithm2(n / 2) : 0);
}
/**
* push - push node onto stack
*
* @stack: pointer to first stack pointer
* @direction: direction data
*
* Return: node pushed or NULL on failure
*/
stack_t *push(stack_t **stack, int direction)
{
stack_t *node;
node = malloc(sizeof(stack_t));
if (node == NULL)
return (NULL);
if (*stack != NULL)
(*stack)->prev = node;
node->prev = NULL;
node->next = *stack;
node->direction = direction;
*stack = node;
return (node);
}
/**
* pop - pop a node from stack
*
* @stack: stack to pop from
*
* Return: next direction in stack, or -1 on failure
*/
int pop(stack_t **stack)
{
stack_t *tmp;
int dir;
if (*stack == NULL)
return (-1);
dir = (*stack)->direction;
tmp = *stack;
*stack = (*stack)->next;
free(tmp);
if (*stack)
(*stack)->prev = NULL;
return (dir);
}
| 3.28125 | 3 |
2024-11-18T21:30:07.631571+00:00
| 2020-05-04T23:07:57 |
7651cdaace11ef812c765a5b7d57b8879ca4cad1
|
{
"blob_id": "7651cdaace11ef812c765a5b7d57b8879ca4cad1",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-04T23:07:57",
"content_id": "841c93a19bb88996daec1b73108c7ee09e4b7d69",
"detected_licenses": [
"MIT"
],
"directory_id": "7b8880f3ec5f7b6d5d621becf326803670ab51ea",
"extension": "h",
"filename": "HCPath.h",
"fork_events_count": 1,
"gha_created_at": "2020-03-27T00:30:03",
"gha_event_created_at": "2020-03-27T00:30:04",
"gha_language": null,
"gha_license_id": null,
"github_id": 250403984,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5994,
"license": "MIT",
"license_type": "permissive",
"path": "/Source/Graphic/HCPath.h",
"provenance": "stackv2-0112.json.gz:185653",
"repo_name": "dstoker-cricut/HollowCore",
"revision_date": "2020-05-04T23:07:57",
"revision_id": "87ecdd0640fa4504c42394ffc3039cfd809c81a9",
"snapshot_id": "466c212809899996d2e3f9cdf573b6af3bbb735f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dstoker-cricut/HollowCore/87ecdd0640fa4504c42394ffc3039cfd809c81a9/Source/Graphic/HCPath.h",
"visit_date": "2022-06-04T22:44:32.269878"
}
|
stackv2
|
//
// HCPath.h
// HollowCore
//
// Created by Matt Stoker on 12/28/19.
// Copyright © 2019 HollowCore. All rights reserved.
//
#ifndef HCPath_h
#define HCPath_h
#include "../Core/HCObject.h"
#include "../Geometry/HCRectangle.h"
#include "../Data/HCData.h"
#include "../Container/HCList.h"
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Object Type
//----------------------------------------------------------------------------------------------------------------------------------
extern HCType HCPathType;
typedef struct HCPath* HCPathRef;
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Definitions
//----------------------------------------------------------------------------------------------------------------------------------
typedef enum HCPathCommand {
HCPathCommandMove,
HCPathCommandAddLine,
HCPathCommandAddQuadraticCurve,
HCPathCommandAddCubicCurve,
HCPathCommandCloseSubpath,
} HCPathCommand;
typedef struct HCPathElement {
HCPathCommand command;
HCPoint* points;
} HCPathElement;
typedef void (*HCPathIntersectionFunction)(void* context, HCBoolean* continueSearching, HCPathRef path, HCPathRef otherPath, HCPoint point);
#define HCPathFlatnessCoarse 1.001
#define HCPathFlatnessNormal 1.0001
#define HCPathFlatnessFine 1.00001
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Construction
//----------------------------------------------------------------------------------------------------------------------------------
HCPathRef HCPathCreateEmpty(void);
HCPathRef HCPathCreateWithElements(HCPathElement* elements, HCInteger elementCount);
HCPathRef HCPathCreateWithSubpaths(HCListRef subpaths);
HCPathRef HCPathCreateRectangle(HCRectangle rectangle);
HCPathRef HCPathCreateEllipse(HCRectangle ellipseBounds);
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Object Polymorphic Functions
//----------------------------------------------------------------------------------------------------------------------------------
HCBoolean HCPathIsEqual(HCPathRef self, HCPathRef other);
HCInteger HCPathHashValue(HCPathRef self);
void HCPathPrint(HCPathRef self, FILE* stream);
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Attributes
//----------------------------------------------------------------------------------------------------------------------------------
HCInteger HCPathElementCount(HCPathRef self);
HCPathElement HCPathElementAt(HCPathRef self, HCInteger elementIndex);
HCDataRef HCPathElementPolylineData(HCPathRef self, HCInteger elementIndex);
HCInteger HCPathElementPolylinePointCount(HCPathRef self, HCInteger elementIndex);
HCPoint HCPathElementPolylinePointAt(HCPathRef self, HCInteger elementIndex, HCInteger pointIndex);
HCPoint HCPathCurrentPoint(HCPathRef self);
HCRectangle HCPathBounds(HCPathRef self);
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Path Manipulation
//----------------------------------------------------------------------------------------------------------------------------------
void HCPathMove(HCPathRef self, HCReal x, HCReal y);
void HCPathAddLine(HCPathRef self, HCReal x, HCReal y);
void HCPathAddQuadraticCurve(HCPathRef self, HCReal cx, HCReal cy, HCReal x, HCReal y);
void HCPathAddCubicCurve(HCPathRef self, HCReal cx0, HCReal cy0, HCReal cx1, HCReal cy1, HCReal x, HCReal y);
void HCPathClose(HCPathRef self);
void HCPathAddElement(HCPathRef self, HCPathCommand command, const HCPoint* points);
void HCPathRemoveLastElement(HCPathRef self);
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Path Conversion
//----------------------------------------------------------------------------------------------------------------------------------
void HCPathPrintData(HCPathRef self, FILE* stream);
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Subpaths
//----------------------------------------------------------------------------------------------------------------------------------
HCBoolean HCPathSubpathContainingElementIsOpen(HCPathRef self, HCInteger elementIndex, HCInteger* startIndex, HCInteger* endIndex);
HCBoolean HCPathSubpathContainingElementIsClosed(HCPathRef self, HCInteger elementIndex, HCInteger* startIndex, HCInteger* endIndex);
HCPathRef HCPathSubpathContaingElementRetained(HCPathRef self, HCInteger elementIndex, HCInteger* startIndex, HCInteger* endIndex, HCBoolean* isOpen);
HCListRef HCPathSubpathsRetained(HCPathRef self);
HCListRef HCPathOpenSubpathsRetained(HCPathRef self);
HCListRef HCPathClosedSubpathsRetained(HCPathRef self);
HCPathRef HCPathOpenSubpathsAsPathRetained(HCPathRef self);
HCPathRef HCPathClosedSubpathsAsPathRetained(HCPathRef self);
//----------------------------------------------------------------------------------------------------------------------------------
// MARK: - Path Intersection
//----------------------------------------------------------------------------------------------------------------------------------
HCBoolean HCPathContainsPoint(HCPathRef self, HCPoint point);
HCBoolean HCPathContainsPointNonZero(HCPathRef self, HCPoint point);
HCBoolean HCPathIntersectsPath(HCPathRef self, HCPathRef other);
void HCPathIntersections(HCPathRef self, HCPathRef other, HCPathIntersectionFunction intersection, void* context);
#endif /* HCPath_h */
| 2.203125 | 2 |
2024-11-18T21:30:07.796612+00:00
| 2019-03-15T19:33:08 |
d39e80765659fc0bfcee8c0e6ab91c3f17936f6a
|
{
"blob_id": "d39e80765659fc0bfcee8c0e6ab91c3f17936f6a",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-15T19:33:08",
"content_id": "617718ef6feb1e473164c70271f73749b4502869",
"detected_licenses": [
"MIT"
],
"directory_id": "1ee90dfe125294c8a50fcf2bf1312c35c523a934",
"extension": "c",
"filename": "referenceMedianProblemTest2.c",
"fork_events_count": 0,
"gha_created_at": "2019-03-12T17:28:42",
"gha_event_created_at": "2019-03-12T17:28:42",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 175264281,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4488,
"license": "MIT",
"license_type": "permissive",
"path": "/submodules/matchingAndOrdering/tests/testBin/referenceMedianProblemTest2.c",
"provenance": "stackv2-0112.json.gz:185916",
"repo_name": "pbasting/cactus",
"revision_date": "2019-03-15T19:33:08",
"revision_id": "833d8ca015deecdfa5d0aca01211632cdaca9e58",
"snapshot_id": "8262d0e946bb6c28373f2bbe588f90c2bc964b52",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pbasting/cactus/833d8ca015deecdfa5d0aca01211632cdaca9e58/submodules/matchingAndOrdering/tests/testBin/referenceMedianProblemTest2.c",
"visit_date": "2020-04-28T12:04:32.019316"
}
|
stackv2
|
/*
* Copyright (C) 2009-2011 by Benedict Paten ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include "sonLib.h"
#include "stReferenceProblem.h"
#include "stReferenceProblem2.h"
#include "stMatchingAlgorithms.h"
/*
* These two functions convert from one version of the coordinates to another.
*/
int64_t convertN(int64_t n, int64_t stubNumber, int64_t nodeNumber) {
assert(n >= 0 && n < nodeNumber);
if(n <= stubNumber) {
return n + 1;
}
if(n % 2 != 0) {
return -(n/2 + stubNumber/2 + 1);
}
return n/2 + stubNumber/2 + 1;
}
int64_t convertIN(int64_t n, int64_t stubNumber, int64_t nodeNumber) {
assert(n != 0 && n <= nodeNumber && n >= -nodeNumber);
if(n > 0 && n <= stubNumber) {
return n - 1;
}
if(n > 0) {
return 2*n - stubNumber - 2;
}
return -2*n - stubNumber - 1;
}
static stList *convertReferenceToAdjacencyEdges2(reference *ref) {
stList *edges = stList_construct3(0, (void(*)(void *)) stIntTuple_destruct);
for(int64_t i=0; i<reference_getIntervalNumber(ref); i++) {
int64_t n = reference_getFirstOfInterval(ref, i);
while(reference_getNext(ref, n) != INT64_MAX) {
stList_append(edges, constructEdge(n, reference_getNext(ref, n)));
n = -reference_getNext(ref, n);
}
}
return edges;
}
int main(int argc, char *argv[]) {
/*
* Parse in the chain number
*/
int64_t permutationNumber;
int i = scanf("%" PRIi64 "", &permutationNumber);
assert(i == 1);
int64_t nodeNumber, stubNumber;
i = scanf("%" PRIi64 "", &nodeNumber);
assert(i == 1);
i = scanf("%" PRIi64 "", &stubNumber);
assert(i == 1);
assert(stubNumber >= 0 && stubNumber % 2 == 0);
assert(nodeNumber >= stubNumber && nodeNumber % 2 == 0);
reference *ref = reference_construct(nodeNumber / 2 + stubNumber/2);
for(int64_t j=1; j<=stubNumber; j+=2) {
reference_makeNewInterval(ref, j, j+1);
}
/*
* Parse in the chain weights as a list
* of the form end1, end2, weight
*/
refAdjList *aL = refAdjList_construct(nodeNumber / 2 + stubNumber/2);
int64_t weightNumber;
i = scanf("%" PRIi64 "", &weightNumber);
assert(i == 1);
for(int64_t j=0; j<weightNumber; j++) {
int64_t node1, node2;
float weight;
i = scanf("%" PRIi64 " %" PRIi64 " %f", &node1, &node2, &weight);
assert(i == 3);
assert(node1 != node2);
assert(node1 >= 0 && node1 < nodeNumber);
assert(node2 >= 0 && node2 < nodeNumber);
refAdjList_addToWeight(aL, convertN(node1, stubNumber, nodeNumber), convertN(node2, stubNumber, nodeNumber), weight);
}
/*
* Compute the ordering
*/
makeReferenceGreedily2(aL, aL, ref, 0.99);
updateReferenceGreedily(aL, aL, ref, permutationNumber);
/*
* Print out the median genome,
* as a list.
*/
stList *adjacencyEdges = convertReferenceToAdjacencyEdges2(ref);
assert(stList_length(adjacencyEdges) == nodeNumber/2);
int64_t adjacencies[nodeNumber];
for(int64_t j=0; j<nodeNumber; j++) {
adjacencies[j] = INT64_MAX;
}
for(int64_t j=0; j<stList_length(adjacencyEdges); j++) {
stIntTuple *edge = stList_get(adjacencyEdges, j);
int64_t node1 = convertIN(stIntTuple_get(edge, 0), stubNumber, nodeNumber);
int64_t node2 = convertIN(stIntTuple_get(edge, 1), stubNumber, nodeNumber);
assert(node1 >= 0 && node1 <= nodeNumber);
assert(node2 >= 0 && node2 <= nodeNumber);
adjacencies[node1] = node2;
adjacencies[node2] = node1;
}
for(int64_t j=0; j<nodeNumber; j++) {
assert(adjacencies[j] != INT64_MAX);
assert(adjacencies[j] >= 0 && adjacencies[j] < nodeNumber);
}
//Now print out the median
int64_t nodesCovered = 0;
for(int64_t j=0; j<stubNumber; j+=2) {
int64_t node = adjacencies[j];
assert(node >= 0 && node < nodeNumber);
while(node != j+1) {
nodesCovered+=2;
printf("%" PRIi64 "\t", node);
node += node % 2 == 0 ? 1 : -1;
assert(node >= 0 && node < nodeNumber);
node = adjacencies[node];
assert(node >= 0 && node < nodeNumber);
if(nodesCovered > nodeNumber) {
assert(0);
}
}
}
printf("\n");
assert(nodeNumber - stubNumber == nodesCovered);
}
| 2.6875 | 3 |
2024-11-18T21:30:08.308593+00:00
| 2020-02-17T09:35:14 |
cfef8141092e4f55b03ef6a5f6370e845557d260
|
{
"blob_id": "cfef8141092e4f55b03ef6a5f6370e845557d260",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-17T09:35:14",
"content_id": "7b290e13b32b8b8b142c2cb536b7e2469c8413f7",
"detected_licenses": [
"MIT"
],
"directory_id": "b6cd08e111ef200fe739c9bae4383088ff1fe2bb",
"extension": "h",
"filename": "MK60_i2c.h",
"fork_events_count": 0,
"gha_created_at": "2019-11-07T11:04:48",
"gha_event_created_at": "2020-02-15T03:15:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 220216897,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1253,
"license": "MIT",
"license_type": "permissive",
"path": "/作业/PWM/Chip/inc/MK60_i2c.h",
"provenance": "stackv2-0112.json.gz:186304",
"repo_name": "yirrk/BJTUwh-dlqx-Intelligent-Car",
"revision_date": "2020-02-17T09:35:14",
"revision_id": "e37ec4e181cc63ddd2472fa34395ddab1312245f",
"snapshot_id": "93fe2b5875970d7680297c2dfffb7013af271b3c",
"src_encoding": "GB18030",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/yirrk/BJTUwh-dlqx-Intelligent-Car/e37ec4e181cc63ddd2472fa34395ddab1312245f/作业/PWM/Chip/inc/MK60_i2c.h",
"visit_date": "2020-09-05T21:23:22.001104"
}
|
stackv2
|
/*!
* COPYRIGHT NOTICE
* Copyright (c) 2013,山外科技
* All rights reserved.
* 技术讨论:山外论坛 http://www.vcan123.com
*
* 除注明出处外,以下所有内容版权均属山外科技所有,未经允许,不得用于商业用途,
* 修改内容时必须保留山外科技的版权声明。
*
* @file MK60_i2c.h
* @brief i2c驱动头文件
* @author 山外科技
* @version v5.0
* @date 2013-07-12
* @note 目前仅实现主机读写寄存器功能,其他功能待实现
*/
#ifndef __MK60_I2C_H__
#define __MK60_I2C_H__
/**
* @brief I2C模块编号
*/
typedef enum
{
I2C0 = 0,
I2C1 = 1
} I2Cn_e;
/**
* @brief 主机读写模式选择
*/
typedef enum MSmode
{
MWSR = 0x00, /* 主机写模式 */
MRSW = 0x01 /* 主机读模式 */
} MSmode;
//目前代码仅支持 I2C主机模式
extern uint32 i2c_init(I2Cn_e i2cn, uint32 baud); //初始化I2C
extern void i2c_write_reg(I2Cn_e, uint8 SlaveID, uint8 reg, uint8 Data); //写入数据到寄存器
extern uint8 i2c_read_reg (I2Cn_e, uint8 SlaveID, uint8 reg); //读取寄存器的数据
#endif //__MK60_I2C_H__
| 2.15625 | 2 |
2024-11-18T21:30:09.705928+00:00
| 2020-02-27T18:27:43 |
4b35e99946321dbcfb40f209f19eb3d76bc72c73
|
{
"blob_id": "4b35e99946321dbcfb40f209f19eb3d76bc72c73",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-27T18:27:43",
"content_id": "7d86a051f5809c7d9ea3194e4843dcaf0d59072a",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "da87c3c4568baf73eafba3bdd0398b721c14fa83",
"extension": "c",
"filename": "trasheol.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 111293783,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 386,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/lib/sbr/misc/trasheol.c",
"provenance": "stackv2-0112.json.gz:187076",
"repo_name": "gonter/hyx-tools",
"revision_date": "2020-02-27T18:27:43",
"revision_id": "4fefb2d99454f859e7ed452a8d8113aff068aefc",
"snapshot_id": "d8b42fc1fb8a296924208838a8fcc196060d884f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gonter/hyx-tools/4fefb2d99454f859e7ed452a8d8113aff068aefc/lib/sbr/misc/trasheol.c",
"visit_date": "2022-04-08T15:24:52.144996"
}
|
stackv2
|
/*
* FILE ~/usr/sbr/trasheol.c
*
* overread until end of line
*
* written: 1992 07 20
* latest update: 1994-08-14
*
*/
#include <stdio.h>
#include <gg/sbr.h>
/* ------------------------------------------------------------------------ */
long trash_until_eol (FILE *fi)
{
long ctr= 0L;
while (!feof (fi) && (fgetc (fi) & 0x00FF) != 0x0A) ctr++;
return ctr;
}
| 2.203125 | 2 |
2024-11-18T21:30:10.381687+00:00
| 2012-06-14T12:33:12 |
604fe5dedd83996135fefc3140164342e0990080
|
{
"blob_id": "604fe5dedd83996135fefc3140164342e0990080",
"branch_name": "refs/heads/master",
"committer_date": "2012-06-14T12:33:12",
"content_id": "e2251bec2b8a661bdc05a263f1b3de10e25a4ce8",
"detected_licenses": [
"Artistic-2.0"
],
"directory_id": "b339d662d16f1fdd3897576bcbc477cce9968063",
"extension": "h",
"filename": "ast.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": 12382,
"license": "Artistic-2.0",
"license_type": "permissive",
"path": "/src/ast.h",
"provenance": "stackv2-0112.json.gz:187594",
"repo_name": "crab2313/m1",
"revision_date": "2012-06-14T12:33:12",
"revision_id": "d86e4a36a6841f2842e27c827719d7d0f73883d7",
"snapshot_id": "db900570bee13af89990dade59a86d03f6920359",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/crab2313/m1/d86e4a36a6841f2842e27c827719d7d0f73883d7/src/ast.h",
"visit_date": "2021-01-18T08:00:52.443961"
}
|
stackv2
|
#ifndef __M1_AST_H__
#define __M1_AST_H__
#include "symtab.h"
#include "decl.h"
#include "instr.h"
#include "compiler.h"
#include "ann.h"
typedef struct m1_block {
struct m1_expression *stats;
struct m1_symboltable locals;
} m1_block;
/* structure to represent a function. */
typedef struct m1_chunk {
char *rettype; /* return type of chunk */
char *name; /* name of this chunk */
struct m1_chunk *next; /* chunks are stored in a list. */
struct m1_block *block; /* list of statements. */
struct m1_var *parameters; /* list of parameters */
unsigned num_params; /* parameter count. */
unsigned line; /* line of function declaration. */
struct m1_symboltable constants; /* constants used in this chunk */
} m1_chunk;
/* Struct to represent each struct field. */
typedef struct m1_structfield {
char *name; /* name of struct member. */
char *type; /* type of struct member. */
unsigned offset; /* memory offset of this member in the struct */
struct m1_structfield *next; /* fields are stored as a list. */
} m1_structfield;
/* structure that holds an M1 struct definition */
typedef struct m1_struct {
char *name; /* name of this struct. */
unsigned size; /* total size of this struct; can calculate from fields but
better keep a "cached" value */
struct m1_structfield *fields; /* list of fields in this struct. */
} m1_struct;
typedef struct m1_pmc {
char *name;
unsigned size;
struct m1_chunk *methods;
struct m1_structfield *fields;
} m1_pmc;
/* To represent "lhs = rhs" statements. */
typedef struct m1_assignment {
struct m1_object *lhs;
struct m1_expression *rhs;
} m1_assignment;
/* To represent function call statements. */
typedef struct m1_funcall {
char *name;
struct m1_expression *arguments;
struct m1_decl *typedecl;
} m1_funcall;
/* To represent new expressions (new Object(x, y, z) ). */
typedef struct m1_newexpr {
char *type; /* name of new type to instantiate. */
struct m1_decl *typedecl; /* pointer to declaration of type. */
struct m1_expression *args; /* arguments passed on to type's constructor. */
} m1_newexpr;
typedef enum m1_expr_type {
EXPR_ADDRESS, /* &x */
EXPR_ASSIGN,
EXPR_BINARY,
EXPR_BLOCK,
EXPR_BREAK,
EXPR_CONTINUE,
EXPR_CAST,
EXPR_CHAR,
EXPR_CONSTDECL,
EXPR_DEREF, /* *x */
EXPR_DOWHILE,
EXPR_FALSE,
EXPR_FOR,
EXPR_FUNCALL,
EXPR_IF,
EXPR_INT,
EXPR_M0BLOCK,
EXPR_NEW,
EXPR_NULL,
EXPR_NUMBER,
EXPR_OBJECT,
EXPR_PRINT, /* temporary? */
EXPR_RETURN,
EXPR_STRING,
EXPR_SWITCH,
EXPR_TRUE,
EXPR_UNARY,
EXPR_VARDECL,
EXPR_WHILE
} m1_expr_type;
typedef enum m1_binop {
OP_ASSIGN,
OP_PLUS,
OP_MINUS,
OP_MUL,
OP_DIV,
OP_MOD,
OP_XOR,
OP_GT,
OP_GE,
OP_LT,
OP_LE,
OP_EQ,
OP_NE,
OP_AND,
OP_OR,
OP_BAND,
OP_BOR,
OP_RSH,
OP_LSH
} m1_binop;
/* To represent binary expressions, like a + b. */
typedef struct m1_binexpr {
struct m1_expression *left;
struct m1_expression *right;
m1_binop op;
} m1_binexpr;
typedef enum m1_unop {
UNOP_POSTINC, /* a++ */
UNOP_POSTDEC, /* a-- */
UNOP_PREINC, /* ++a */
UNOP_PREDEC, /* --a */
UNOP_NOT /* !a */
/* There is no UNOP_NEG: unary minus is handled by multiplying by -1 */
} m1_unop;
/* for unary expressions, like -x, and !y. */
typedef struct m1_unexpr {
struct m1_expression *expr;
m1_unop op;
} m1_unexpr;
typedef struct m1_castexpr {
struct m1_expression *expr;
char *type;
m1_valuetype targettype;
} m1_castexpr;
/* object types. */
typedef enum m1_object_type {
OBJECT_LINK, /* node linking a and b in a.b */
OBJECT_MAIN, /* a in a.b */
OBJECT_FIELD, /* b in a.b */
OBJECT_INDEX, /* b in a[b] */
OBJECT_DEREF, /* b in a->b */
OBJECT_SCOPE, /* b in a::b */
OBJECT_SELF, /* "self" */
OBJECT_SUPER /* "super" */
} m1_object_type;
/* struct to represent an element or link between two elements
in aggregates. In a.b.c, each element (a, b, c) is represented
by one m1_object node. Links, between a and b, and b and c are ALSO
represented by a m1_object node. Yes, that's a lot of nodes for
an expression like "a.b.c" (5 in total).
*/
typedef struct m1_object {
union {
char *name; /* for name, field or deref access, in a.b.c for instance. */
struct m1_expression *index; /* for array index (a[42]) */
struct m1_object *field; /* if this is a linking node (OBJECT_LINK) representing "a.b" as a whole. */
} obj;
enum m1_object_type type; /* selector for union */
struct m1_symbol *sym; /* pointer to this object's declaration. */
struct m1_object *parent; /* pointer to its parent (in a.b.c, a is b's parent) */
} m1_object;
/* for while and do-while statements */
typedef struct m1_whileexpr {
struct m1_expression *cond;
struct m1_expression *block;
} m1_whileexpr;
/* for if statements */
typedef struct m1_ifexpr {
struct m1_expression *cond;
struct m1_expression *ifblock;
struct m1_expression *elseblock;
} m1_ifexpr;
/* for for-statements */
typedef struct m1_forexpr {
struct m1_expression *init;
struct m1_expression *cond;
struct m1_expression *step;
struct m1_expression *block;
} m1_forexpr;
/* const declarations */
typedef struct m1_const {
char *type;
char *name;
struct m1_expression *value;
} m1_const;
/* variable declarations */
typedef struct m1_var {
char *name;
char *type; /* store type name; type may not have been parsed yet; check in type checker. */
struct m1_expression *init; /* to handle: int x = 42; */
unsigned num_elems; /* 1 for non-arrays, larger for arrays */
struct m1_symbol *sym; /* pointer to symbol in symboltable */
struct m1_var *next; /* var nodes are stored as a list. */
} m1_var;
/* structure to represent a single case of a switch statement. */
typedef struct m1_case {
int selector;
struct m1_expression *block;
struct m1_case *next;
} m1_case;
/* structure to represent a switch statement. */
typedef struct m1_switch {
struct m1_expression *selector;
struct m1_case *cases;
struct m1_expression *defaultstat;
} m1_switch;
/* for representing literal constants, i.e., int, float and strings */
typedef struct m1_literal {
union m1_value value; /* the value */
enum m1_valuetype type; /* selector for the union value */
struct m1_symbol *sym; /* pointer to a symboltable entry. */
} m1_literal;
typedef struct m0_block {
struct m0_instr *instr;
} m0_block;
typedef struct m1_enumconst {
char *name; /* name of this constant */
int value; /* value of this constant */
struct m1_enumconst *next;
} m1_enumconst;
typedef struct m1_enum {
char *enumname;
m1_enumconst *enums;
} m1_enum;
/* to represent statements */
typedef struct m1_expression {
union {
struct m1_unexpr *u;
struct m1_binexpr *b;
struct m1_funcall *f;
struct m1_assignment *a;
struct m1_whileexpr *w;
struct m1_forexpr *o;
struct m1_ifexpr *i;
struct m1_expression *e;
struct m1_object *t;
struct m1_const *c;
struct m1_var *v;
struct m0_block *m0;
struct m1_switch *s;
struct m1_newexpr *n;
struct m1_literal *l;
struct m1_castexpr *cast;
struct m1_block *blck;
} expr;
m1_expr_type type; /* selector for union */
unsigned line; /* line number */
struct m1_expression *next;
} m1_expression;
extern int yyget_lineno(yyscan_t yyscanner);
//extern m1_chunk *chunk(M1_compiler *comp, char *rettype, char *name);
extern m1_chunk *chunk(ARGIN_NOTNULL(M1_compiler * const comp), ARGIN(char *rettype), ARGIN_NOTNULL(char *name));
//extern m1_expression *block(M1_compiler *comp);
extern m1_block *block(ARGIN_NOTNULL(M1_compiler *comp));
extern m1_expression *expression(M1_compiler *comp, m1_expr_type type);
extern m1_expression *funcall(M1_compiler *comp, m1_object *fun, m1_expression *args);
extern m1_object *object(M1_compiler *comp, m1_object_type type);
extern void obj_set_ident(m1_object *node, char *ident);
extern m1_structfield *structfield(M1_compiler *comp, char *name, char *type);
extern m1_struct *newstruct(M1_compiler *comp, char *name, m1_structfield *fields);
extern m1_pmc *newpmc(M1_compiler *comp, char *name, m1_structfield *fields, m1_chunk *methods);
extern m1_expression *ifexpr(M1_compiler *comp, m1_expression *cond, m1_expression *ifblock, m1_expression *elseblock);
extern m1_expression *whileexpr(M1_compiler *comp, m1_expression *cond, m1_expression *block);
extern m1_expression *dowhileexpr(M1_compiler *comp, m1_expression *cond, m1_expression *block);
extern m1_expression *forexpr(M1_compiler *comp, m1_expression *init, m1_expression *cond, m1_expression *step, m1_expression *stat);
extern m1_expression *inc_or_dec(M1_compiler *comp, m1_expression *obj, m1_unop optype);
extern m1_expression *returnexpr(M1_compiler *comp, m1_expression *retexp);
extern m1_expression *assignexpr(M1_compiler *comp, m1_expression *lhs, int assignop, m1_expression *rhs);
extern m1_expression *objectexpr(M1_compiler *comp, m1_object *obj, m1_expr_type type);
extern m1_expression *binexpr(M1_compiler *comp, m1_expression *e1, int op, m1_expression *e2);
extern m1_expression *number(M1_compiler *comp, double value);
extern m1_expression *integer(M1_compiler *comp, int value);
extern m1_expression *character(M1_compiler *comp, char ch);
extern m1_expression *string(M1_compiler *comp, char *str);
extern m1_expression *unaryexpr(M1_compiler *comp, m1_unop op, m1_expression *e);
extern m1_object *arrayindex(M1_compiler *comp, m1_expression *index);
extern m1_object *objectfield(M1_compiler *comp, char *field);
extern m1_object *objectderef(M1_compiler *comp, char *field);
extern m1_expression *printexpr(M1_compiler *comp, m1_expression *e);
extern m1_expression *constdecl(M1_compiler *comp, char *type, char *name, m1_expression *expr);
extern m1_expression *vardecl(M1_compiler *comp, char *type, m1_var *v);
extern m1_var *var(M1_compiler *comp, char *name, m1_expression *init);
extern m1_var *array(M1_compiler *comp, char *name, unsigned size, m1_expression *init);
extern unsigned field_size(struct m1_structfield *field);
extern m1_expression *switchexpr(M1_compiler *comp, m1_expression *expr, m1_case *cases, m1_expression *defaultstat);
extern m1_case *switchcase(M1_compiler *comp, int selector, m1_expression *block);
extern m1_expression *newexpr(M1_compiler *copm, char *type, m1_expression *args);
extern m1_object *lhsobj(M1_compiler *comp, m1_object *parent, m1_object *field);
extern m1_expression *castexpr(M1_compiler *comp, char *type, m1_expression *castedexpr);
extern m1_structfield *struct_find_field(M1_compiler *comp, m1_struct *structdef, char *fieldname);
extern m1_enumconst *enumconst(M1_compiler *comp, char *enumitem, int enumvalue);
extern m1_enum *newenum(M1_compiler *comp, char *name, m1_enumconst *enumconstants);
extern m1_var *parameter(M1_compiler *comp, char *type, char *name);
extern void block_set_stat(m1_block *block, m1_expression *stat);
extern struct m1_block *open_scope(M1_compiler *comp);
extern void close_scope(M1_compiler *comp);
extern void enter_param(M1_compiler *comp, m1_var *parameter);
#endif
| 2.140625 | 2 |
2024-11-18T21:30:10.442441+00:00
| 2011-03-09T23:19:05 |
c1c73ea1fb202b4c15b30fadc3939a1ccb42c08d
|
{
"blob_id": "c1c73ea1fb202b4c15b30fadc3939a1ccb42c08d",
"branch_name": "refs/heads/master",
"committer_date": "2011-03-09T23:19:05",
"content_id": "5fd9d0d5a8ce9f1f7b6d153597ad75e53f90e173",
"detected_licenses": [
"MIT"
],
"directory_id": "f7f31b85a7d3a72c10926913eac3221d578ee046",
"extension": "c",
"filename": "lev.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 727600,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 950,
"license": "MIT",
"license_type": "permissive",
"path": "/algorithms/c/levenshtein/lev.c",
"provenance": "stackv2-0112.json.gz:187722",
"repo_name": "rik0/rk-exempla",
"revision_date": "2011-03-09T23:19:05",
"revision_id": "811f859a0980b0636bbafa2656893d988c4d0e32",
"snapshot_id": "28732167bb20694e3ea711ad6229080d6db0f395",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rik0/rk-exempla/811f859a0980b0636bbafa2656893d988c4d0e32/algorithms/c/levenshtein/lev.c",
"visit_date": "2021-01-10T20:00:48.508817"
}
|
stackv2
|
#include <stdlib.h>
#include "lev.h"
/* just to try the algorithm, substitute with
* unsigned int *buffer;
* unsigned int **distance;
* initialized and destructed at the beginning and end of lev.
*/
unsigned int distance[24][24];
static inline
unsigned int min(unsigned int a, unsigned int b) {
return (a < b) ? a : b;
}
static inline
unsigned int minimum(unsigned int a, unsigned int b, unsigned int c) {
return min(min(a, b), c);
}
unsigned int levenshtein(const char* u, const size_t n, const char* v, const size_t m) {
for(int i = 0; i <= n; ++i) {
distance[i][0] = i;
}
for(int j = 0; j <= m; ++j) {
distance[0][j] = j;
}
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
if(u[i-1] == v[j-1]) {
distance[i][j] = distance[i-1][j-1];
} else {
distance[i][j] = 1 + minimum(
distance[i-1][j],
distance[i][j-1],
distance[i-1][j-1]
);
}
}
}
return distance[n][m];
}
| 3 | 3 |
2024-11-18T21:30:10.648958+00:00
| 2023-08-27T05:12:43 |
52bdf50d24291b52301af8a69746c317ee6045dd
|
{
"blob_id": "52bdf50d24291b52301af8a69746c317ee6045dd",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T05:12:43",
"content_id": "57168b1d9d99bfd045ebf6556ebc71c4cda60969",
"detected_licenses": [
"MIT"
],
"directory_id": "c8785278ccc04221bc4f618acfb6a639b452d13f",
"extension": "c",
"filename": "xterm_mouse.c",
"fork_events_count": 15,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14258504,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11185,
"license": "MIT",
"license_type": "permissive",
"path": "/linux/xterm_mouse.c",
"provenance": "stackv2-0112.json.gz:187981",
"repo_name": "fishilico/shared",
"revision_date": "2023-08-27T05:12:43",
"revision_id": "a846ce38894f749082405d9a86fcf13d0bf5b992",
"snapshot_id": "14edd274df12057ae1dc294fe10715ddc969e796",
"src_encoding": "UTF-8",
"star_events_count": 35,
"url": "https://raw.githubusercontent.com/fishilico/shared/a846ce38894f749082405d9a86fcf13d0bf5b992/linux/xterm_mouse.c",
"visit_date": "2023-08-31T15:58:35.327197"
}
|
stackv2
|
/**
* Use the mouse in a X11 terminal
*
* Some terminfo sequences:
* * smcup = \E[?1049h enter alternate screen (enter_ca_mode)
* * rmcup = \E[?1049l exit alternate screen (exit_ca_mode)
* * cup 1 2 = \E[2;3H set cursor pos to 2nd column, 3rd line (x=1, y=2)
* * civis = \E[?25l make cursor invisible
* * cnorm = \E[?12l\E[?25h make cursor normal
* * cvvis = \E[?12;25h make cursor very visible
* * el = \E[K clear to end of line
* * ed = \E[J clear to end to screen
* * clear = \E[H\E[2J clear screen and home cursor
* * XM 1 = \E[?1002h enable "any event" mouse mode (xterm-1002)
* * XM 0 = \E[?1002l disable "any event" mouse mode (xterm-1002)
* * \E[?1006h enable mouse protocol
* * \E[?1006l disable mouse protocol
*
* Note: the escape sequences can be obtained with something like:
* strace -ewrite -o/proc/self/fd/3 -s500 tput -T$TERM smcup 3>&1 >/dev/null 2>&1
*
* Some documentation:
* * terminfo sequences related to mouse are "XM" and "xm" in
* http://invisible-island.net/ncurses/terminfo.src.html
* * ncurses implements a mouse interface in ncurses/base/lib_mouse.c:
* http://fossies.org/dox/ncurses-5.9/lib__mouse_8c_source.html
* * ... the associated man page is curs_mouse(3x):
* http://www.manpagez.com/man/3/curs_mouse/
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE /* for sigaction, sigemptyset, snprintf */
#endif
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
/**
* Global variables
*/
static int tty_fd = -1;
static volatile unsigned int win_cols;
static volatile unsigned int win_rows;
static struct termios tty_attr_orig;
/**
* Callback to update win_cols and win_rows according to the size of tty_fd
*/
static int update_winsize(void)
{
struct winsize window_size;
if (tty_fd < 0) {
return 0;
}
if (ioctl(tty_fd, TIOCGWINSZ, &window_size) < 0) {
perror("ioctl(tty, TIOCGWINSZ)");
return 0;
}
win_cols = window_size.ws_col;
win_rows = window_size.ws_row;
return 1;
}
/**
* Write every byte to the tty
*/
static int tty_write(const char *buffer, size_t count)
{
if (tty_fd < 0) {
return 0;
}
while (count > 0) {
ssize_t ret = write(tty_fd, buffer, count);
if (ret >= 0) {
buffer += ret;
count -= (size_t)ret;
} else if (errno != EINTR) {
perror("write(tty)");
return 0;
}
}
return 1;
}
static int tty_print(const char *string)
{
return tty_write(string, strlen(string));
}
/**
* Initialize the tty
*/
static int tty_init(void)
{
const char *tty_name = "/dev/tty";
struct termios tty_attr;
/* Open a RW file descriptor to the current tty, using stdout or /dev/tty */
if (isatty(STDOUT_FILENO)) {
tty_name = ttyname(STDOUT_FILENO);
if (!tty_name) {
perror("ttyname");
return 0;
}
}
tty_fd = open(tty_name, O_RDWR | O_CLOEXEC);
if (tty_fd == -1) {
perror("open(tty)");
return 0;
}
/* Setup terminal attributes */
if (tcgetattr(tty_fd, &tty_attr) == -1) {
perror("tcgetattr");
close(tty_fd);
tty_fd = -1;
return 0;
}
tty_attr_orig = tty_attr;
tty_attr.c_lflag &= ~(unsigned)ICANON; /* Disable canonical mode */
tty_attr.c_lflag &= ~(unsigned)ECHO; /* Don't echo input characters */
tty_attr.c_lflag |= ISIG; /* Convert INT and QUIT chars to signal */
if (tcsetattr(tty_fd, TCSAFLUSH, &tty_attr) == -1) {
perror("tcsetattr");
return 0;
}
/* Get the window size */
if (!update_winsize()) {
return 0;
}
/* Enter alternate screen, make cursor invisible and enable mouse protocol */
if (!tty_print("\033[?1049h\033[?25l\033[?1002;1006h")) {
return 0;
}
return 1;
}
/**
* Revert everything tty_init did
*/
static void tty_reset(void)
{
if (tty_fd == -1) {
return;
}
/* Exit alternate screen, make cursor normal and disable mouse protocol */
tty_print("\033[?1049l\033[?12l\033[?25h\033[?1002;1006l");
/* Restore initial terminal attributes and drop unread input */
if (tcsetattr(tty_fd, TCSAFLUSH, &tty_attr_orig) == -1) {
perror("tcsetattr");
}
close(tty_fd);
tty_fd = -1;
}
/**
* Quit nicely when handling the interrupt signal
*/
static void __attribute__ ((noreturn)) handle_sigterm(int signum)
{
assert(signum == SIGINT || signum == SIGQUIT || signum == SIGTERM);
tty_reset();
exit(0);
}
/**
* Handle window change signal
*/
static void handle_sigwinch(int signum)
{
assert(signum == SIGWINCH);
update_winsize();
}
int main(void)
{
struct sigaction sa;
unsigned char buffer[1024];
char textbuf[200];
ssize_t count;
size_t i, curpos, textbufpos;
int saved_errno;
unsigned int mouse_buttons, mouse_x, mouse_y;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handle_sigterm;
if (sigaction(SIGINT, &sa, NULL) == -1) {
perror("sigaction(SIGINT)");
return 1;
}
if (sigaction(SIGQUIT, &sa, NULL) == -1) {
perror("sigaction(SIGQUIT)");
return 1;
}
if (sigaction(SIGTERM, &sa, NULL) == -1) {
perror("sigaction(SIGTERM)");
return 1;
}
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handle_sigwinch;
if (sigaction(SIGWINCH, &sa, NULL) == -1) {
perror("sigaction(SIGWINCH)");
return 1;
}
if (!tty_init()) {
tty_reset();
return 1;
}
snprintf(textbuf, sizeof(textbuf),
"Window size: %u x %u\n",
win_cols, win_rows);
tty_print(textbuf);
curpos = 0;
for (;;) {
assert(curpos < sizeof(buffer));
count = read(tty_fd, buffer + curpos, (size_t)(sizeof(buffer) - curpos));
if (count == -1) {
if (errno == EINTR) {
/* display current window size */
snprintf(textbuf, sizeof(textbuf),
"\033[HWindow size: %u x %u\033[K\n",
win_cols, win_rows);
tty_print(textbuf);
continue;
}
saved_errno = errno;
tty_reset();
errno = saved_errno;
perror("read");
return 1;
}
/* There are curpos+count available bytes in the buffer */
count += curpos;
curpos = 0;
for (i = 0; i < (size_t)count; i++) {
if (buffer[i] == '\003' || buffer[i] == 'q' || buffer[i] == 'Q') {
/* Quit if Received ^C, q or Q from the terminal */
tty_reset();
return 0;
} else if (buffer[i] == 'c' || buffer[i] == 'C') {
/* Clear screen */
tty_print("\033[H\033[2J");
continue;
} else if (buffer[i] != '\033') {
/* Received something else than escape sequence, continue */
continue;
}
/* Mouse is \e[M and 3 characters */
if (i + 6 > (size_t)count) {
/* The sequence has not been completely read, keep its beginning */
curpos = ((size_t)count) - i;
memmove(buffer, buffer + i, curpos);
break;
}
if (buffer[i + 1] != '[' && buffer[i + 2] != 'M') {
continue;
}
/* Retrieve mouse state from buffer */
mouse_buttons = (unsigned int)(buffer[i + 3] - ' ');
mouse_x = (unsigned int)(buffer[i + 4] - ' ' - 1) & 0xff;
mouse_y = (unsigned int)(buffer[i + 5] - ' ' - 1) & 0xff;
/* Display a pattern */
textbuf[0] = '\0';
/* Change the color depending on the button state */
switch (mouse_buttons) {
case 0:
/* Left button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[31m");
break;
case 1:
/* Middle button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[32m");
break;
case 2:
/* Right button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[34m");
break;
case 3:
/* Button released */
snprintf(textbuf, sizeof(textbuf), "\033[37m");
break;
case 0x20:
/* Move with left button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[41m");
break;
case 0x21:
/* Move with middle button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[42m");
break;
case 0x22:
/* Move with right button pressed */
snprintf(textbuf, sizeof(textbuf), "\033[44m");
break;
case 0x40:
/* Mouse wheel up */
snprintf(textbuf, sizeof(textbuf), "\033[43m");
break;
case 0x41:
/* Mouse wheel down */
snprintf(textbuf, sizeof(textbuf), "\033[46m");
}
textbufpos = strlen(textbuf);
/* Show a cross on cursor position */
if (mouse_y >= 1) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH|", mouse_y, mouse_x + 1);
textbufpos += strlen(textbuf + textbufpos);
}
if (mouse_x == 0) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;1HX-", mouse_y + 1);
} else if (mouse_x + 1 >= win_cols) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH-X", mouse_y + 1, mouse_x);
} else {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH-X-", mouse_y + 1, mouse_x);
}
textbufpos += strlen(textbuf + textbufpos);
if (mouse_y + 1 < win_rows) {
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos,
"\033[%u;%uH|", mouse_y + 2, mouse_x + 1);
textbufpos += strlen(textbuf + textbufpos);
}
assert(textbufpos + 3 < sizeof(textbuf));
snprintf(textbuf + textbufpos, sizeof(textbuf) - textbufpos, "\033[m");
tty_print(textbuf);
/* printf("\033[H0x%02x, %u, %u\033[K\n", mouse_buttons, mouse_x, mouse_y); */
i += 5;
}
}
}
| 2.5625 | 3 |
2024-11-18T21:30:10.870281+00:00
| 2021-07-19T10:45:54 |
b097c84809743337ef147899ad279e6301417793
|
{
"blob_id": "b097c84809743337ef147899ad279e6301417793",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-19T10:45:54",
"content_id": "3d64492230d2088fcfe85ec24450b8d4f8e7c886",
"detected_licenses": [
"Unlicense"
],
"directory_id": "dbc423eef9dd026fa59f5b4fd532068275a97205",
"extension": "c",
"filename": "geohash.py.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 383990319,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4216,
"license": "Unlicense",
"license_type": "permissive",
"path": "/etc/geohash.py.c",
"provenance": "stackv2-0112.json.gz:188243",
"repo_name": "skeeto/geohash",
"revision_date": "2021-07-19T10:45:54",
"revision_id": "f434f17882c5e234730bafec275d9030ca630326",
"snapshot_id": "59863fbeb326f84b6f74b5843985beb68fc15d1f",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/skeeto/geohash/f434f17882c5e234730bafec275d9030ca630326/etc/geohash.py.c",
"visit_date": "2023-06-06T16:45:12.286424"
}
|
stackv2
|
// Binary geohash module for Python 3.7+
//
// Linux build:
// $ cc -shared $(python-config --includes) -fPIC -DNDEBUG \
// -O3 -s -ffreestanding -nostdlib -o geohash.so geohash.py.c
//
// Windows build (w64devkit):
// $ cc -shared -I"$PYTHONHOME/include" -L"$PYTHONHOME/libs" -DNDEBUG \
// -O3 -s -ffreestanding -nostdlib -o geohash.pyd geohash.py.c -lpython3
//
// This is free and unencumbered software released into the public domain.
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "../geohash.c"
PyDoc_STRVAR(encode_doc,
"encode(latitude, longitude, /)\n--\n\n"
"Encode (latitude, longitude) degrees into a geohash.\n\n"
"Latitude must be in [-90, 90) and longitude must be in [-180, 180).");
static PyObject *
encode(PyObject *self, PyObject **args, Py_ssize_t nargs)
{
(void)self;
double lat, lon;
if (nargs != 2) {
PyErr_SetString(PyExc_TypeError, "takes exactly two arguments");
return 0;
}
lat = PyFloat_AsDouble(args[0]);
if (PyErr_Occurred()) {
return 0;
}
lon = PyFloat_AsDouble(args[1]);
if (PyErr_Occurred()) {
return 0;
}
if (!(lat >= -90.0 && lat < 90.0)) {
PyErr_SetString(PyExc_ValueError, "latitude must be in [-90, 90)");
return 0;
}
if (!(lon >= -180.0 && lon < 180.0)) {
PyErr_SetString(PyExc_ValueError, "longitude must be in [-180, 180)");
return 0;
}
char buf[21];
geohash_encode(buf, lat, lon);
return Py_BuildValue("s#", buf, (int)sizeof(buf));
}
PyDoc_STRVAR(decode_doc,
"decode(geohash, /)\n--\n\n"
"Decode a geohash into (latitude, longitude) degrees, as pair.\n\n"
"The geohash must be either bytes or a string.");
static PyObject *
decode(PyObject *self, PyObject **args, Py_ssize_t nargs)
{
(void)self;
(void)nargs;
if (nargs != 1) {
PyErr_SetString(PyExc_TypeError, "takes exactly one argument");
return 0;
}
int len;
char tmp[22];
char *buf = tmp;
if (Py_TYPE(args[0]) == &PyUnicode_Type) {
Py_ssize_t slen;
wchar_t *u = PyUnicode_AsWideCharString(args[0], &slen);
len = slen > (Py_ssize_t)sizeof(tmp) ? (int)sizeof(tmp) : (int)slen;
for (int i = 0; i < len; i++) {
tmp[i] = u[i] > 127 ? 0 : u[i];
}
} else if (Py_TYPE(args[0]) == &PyBytes_Type) {
Py_ssize_t slen = PyBytes_GET_SIZE(args[0]);
buf = PyBytes_AsString(args[0]);
len = slen > (Py_ssize_t)sizeof(buf) ? (int)sizeof(buf) : (int)slen;
} else {
PyErr_SetString(PyExc_TypeError, "must be bytes or str");
return 0;
}
double lat, lon;
if (!geohash_decode(&lat, &lon, buf, len)) {
PyErr_SetString(PyExc_ValueError, "invalid geohash");
return 0;
}
return Py_BuildValue("ff", lat, lon);
}
PyDoc_STRVAR(maxerr_doc,
"maxerr(length, /)\n--\n\n"
"Compute the maximum error in degrees for a given geohash byte length,\n"
"as pair (latitude_maxerr, longitude_maxerr).\n\n");
static PyObject *
maxerr(PyObject *self, PyObject **args, Py_ssize_t nargs)
{
(void)self;
if (nargs != 1) {
PyErr_SetString(PyExc_TypeError, "takes exactly one argument");
return 0;
}
long n = PyLong_AsLong(args[0]);
if (PyErr_Occurred()) {
return 0;
}
if (n < 0) {
PyErr_SetString(PyExc_ValueError, "length must be non-negative");
return 0;
}
if (n > 21) {
n = 21;
}
double laterr = 90.0 / (1LL << ((5*n + 0) / 2));
double lonerr = 180.0 / (1LL << ((5*n + 1) / 2));
return Py_BuildValue("ff", laterr, lonerr);
}
static PyMethodDef methods[] = {
{"encode", (PyCFunction)encode, METH_FASTCALL, encode_doc},
{"decode", (PyCFunction)decode, METH_FASTCALL, decode_doc},
{"maxerr", (PyCFunction)maxerr, METH_FASTCALL, maxerr_doc},
{0, 0, 0, 0}
};
static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT,
.m_name = "geohash",
.m_doc = "Encoder and decoder for geohash",
.m_methods = methods,
};
PyMODINIT_FUNC
PyInit_geohash(void)
{
return PyModule_Create(&module);
}
#if defined(_WIN32) && __STDC_HOSTED__ == 0
int DllMainCRTStartup(void) { return 1; }
#endif
| 2.328125 | 2 |
2024-11-18T21:30:11.061824+00:00
| 2020-01-01T04:06:33 |
ba463f17450e3eacbf78c9565555ad700b0b8b99
|
{
"blob_id": "ba463f17450e3eacbf78c9565555ad700b0b8b99",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-01T04:06:33",
"content_id": "c5f3bb7896370fdff0a9c3e8b1965641c928345b",
"detected_licenses": [
"MIT"
],
"directory_id": "33ee597da61f29260dbd1230c83bc4b780362de2",
"extension": "c",
"filename": "main.c",
"fork_events_count": 4,
"gha_created_at": "2019-08-25T11:25:30",
"gha_event_created_at": "2019-11-02T15:07:05",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 204284704,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 863,
"license": "MIT",
"license_type": "permissive",
"path": "/os/06-file-lock/main.c",
"provenance": "stackv2-0112.json.gz:188634",
"repo_name": "chrisvrose/sem3labs",
"revision_date": "2020-01-01T04:06:33",
"revision_id": "cb53ad708ded643d389a47102d316fff25016d01",
"snapshot_id": "fe12e77bcea270d0c20614858069c077f6423c46",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/chrisvrose/sem3labs/cb53ad708ded643d389a47102d316fff25016d01/os/06-file-lock/main.c",
"visit_date": "2020-07-10T14:25:17.945418"
}
|
stackv2
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main(int argc,char* argv[]){
int fd;
char buffer[255];
struct flock fvar;
if(argc==1){
printf("Usage: %s <filename>\n",argv[0]);return 1;
}
if((fd = open(argv[1],O_RDWR) )==-1){
fprintf(stderr,"Error opening\n");return 1;
}
fvar.l_type = F_WRLCK;
fvar.l_whence = SEEK_SET;
fvar.l_start = 0;
fvar.l_len = 100;
if((fcntl(fd,F_SETLK,&fvar))==0){
sleep(20);
}else{
fcntl(fd,F_GETLK,&fvar);
printf("File already claimed by (%d)\n",fvar.l_pid);
return 1;
}
printf("Press any key to remove lock\n");
getchar();
if((fcntl(fd,F_UNLCK,&fvar))==-1){
fprintf(stderr,"Error unlocking\n");
return 1;
}
printf("Unlocked\n");
close(fd);
return 0;
}
| 2.8125 | 3 |
2024-11-18T21:30:11.361821+00:00
| 2020-03-08T16:22:54 |
4ffc0ad0f37555797288cac644c5bd96956e626e
|
{
"blob_id": "4ffc0ad0f37555797288cac644c5bd96956e626e",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-08T16:22:54",
"content_id": "bd5745774f0e1476f88035112df2d4fda43bc2ee",
"detected_licenses": [
"MIT"
],
"directory_id": "24fc2132f5cfe01dae1f38f954c6e1c10c144e27",
"extension": "h",
"filename": "utils.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1568,
"license": "MIT",
"license_type": "permissive",
"path": "/include/macros/utils.h",
"provenance": "stackv2-0112.json.gz:188764",
"repo_name": "BooshSource/AlphaTools",
"revision_date": "2020-03-08T16:22:54",
"revision_id": "70ff9cd4ec4184f67d7e8b779538ef88f1e88682",
"snapshot_id": "ad612d09b4f554f5b2e6835a8ace5926d8ac60de",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BooshSource/AlphaTools/70ff9cd4ec4184f67d7e8b779538ef88f1e88682/include/macros/utils.h",
"visit_date": "2022-04-26T15:44:57.929480"
}
|
stackv2
|
#pragma once
/**
* \file utils.h
* \brief Common utility macros
*
* Various utility macros, for common operations at the pre-processing step.
* Includes stuff like concatenation, unique identifiers, and token operations.
*/
/**
* \brief Concatenate two tokens unexpanded
*
* Macro to concatenate two tokens, without expanding them. Generally not useful on its own
*/
#define AT_CONCATENATE(a, b) a##b
/**
* \brief Expand then concatenate two tokens
*
* Macro to expand and then concatenate two tokens. Internally, just calls concatenate.
* This ensures expansion due to C macro evaluation rules.
*/
#define AT_EXPAND_CONCAT(a, b) AT_CONCATENATE(a, b)
/**
* \brief Generate a unique variable/function name
*
* Macro to generate a unique identifier. It's not impossible to generate a collision, so
* make sure to choose uncommon prefixes.
* Should work across compilers.
*/
#ifdef __COUNTER__
#define AT_UNIQUE_IDENT(prefix) AT_EXPAND_CONCAT(prefix, __COUNTER__)
#else
#define AT_UNIQUE_IDENT(prefix) AT_EXPAND_CONCAT(prefix, __LINE__)
#endif
/**
* \internal
*
* Actually stringifies the token
*/
#define _AT_STRINGIFY(token) #token
/**
* \brief Converts macro expansion to a string
*
* Convert a token to a string, including the result of another macro expansion
*/
#define AT_STRINGIFY(token) _AT_STRINGIFY(token)
/**
* \brief Force expansion
*
* Expands the contained values before the next step of macro resolution,
* useful for forcing __VA_ARGS__ in MSVC to work more like you would expect
*/
#define AT_EXPAND(token) token
| 2.125 | 2 |
2024-11-18T21:30:11.766297+00:00
| 2019-09-25T17:41:09 |
1203e1d98a635ea4175c0baf095e164d668db030
|
{
"blob_id": "1203e1d98a635ea4175c0baf095e164d668db030",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-25T17:41:09",
"content_id": "9019a1f7aa9c5f8a3ef49153c7febcc72cf1d5aa",
"detected_licenses": [
"MIT"
],
"directory_id": "3a46bf71fb10d8b61fd02f756af54c58564058cb",
"extension": "c",
"filename": "ipset.c",
"fork_events_count": 1,
"gha_created_at": "2018-12-06T16:43:39",
"gha_event_created_at": "2018-12-06T16:43:41",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 160703618,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1000,
"license": "MIT",
"license_type": "permissive",
"path": "/ipset.c",
"provenance": "stackv2-0112.json.gz:189155",
"repo_name": "inverse-inc/go-ipset",
"revision_date": "2019-09-25T17:41:09",
"revision_id": "4d5749cc4aa698edb249f95cc48a0960830dc81e",
"snapshot_id": "f066e70fb9d5c81fa98954841d2f951f28a6ce05",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/inverse-inc/go-ipset/4d5749cc4aa698edb249f95cc48a0960830dc81e/ipset.c",
"visit_date": "2021-06-12T17:10:13.848721"
}
|
stackv2
|
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "ipset.h"
#include "_cgo_export.h"
int writebuf( const char* format, ... ) {
va_list args;
va_start(args, format);
outfn(va_arg(args, char *));
va_end(args);
return 0;
}
// Initializes a session with a write buffer for XML
struct ipset_session *session_init_xml() {
struct ipset_session *session = ipset_session_init(writebuf);
if (session) {
ipset_session_output(session, IPSET_LIST_XML);
}
return session;
}
// Returns the ipset_arg with the given name
const struct ipset_arg*
get_ipset_arg(struct ipset_type *type, const char *argname){
const struct ipset_arg *arg;
#ifdef IPSET_OPTARG_MAX
int k;
for (k = 0; type->cmd[IPSET_ADD].args[k] != IPSET_ARG_NONE; k++) {
arg = ipset_keyword(type->cmd[IPSET_ADD].args[k]);
#else
for (arg = type->args[IPSET_ADD]; arg->opt; arg++) {
#endif
if (strcmp(argname, arg->name[0]) == 0){
return arg;
}
}
return NULL;
}
| 2.28125 | 2 |
2024-11-18T21:30:11.837727+00:00
| 2020-05-12T02:21:37 |
13a2a01c301f6c991ee6289c6380ad1e2d7b106e
|
{
"blob_id": "13a2a01c301f6c991ee6289c6380ad1e2d7b106e",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-12T02:21:37",
"content_id": "9f8ddf80b1e135edaf6159ee22dff3dcb0aae731",
"detected_licenses": [
"MIT"
],
"directory_id": "8a8d0139f50144f6a1b4be4789f7a2962eadbad5",
"extension": "c",
"filename": "list.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 196894319,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4306,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lib/list.c",
"provenance": "stackv2-0112.json.gz:189285",
"repo_name": "waterproofpatch/c_list",
"revision_date": "2020-05-12T02:21:37",
"revision_id": "3a1f4b1e3e23780e963258e1edd6cd3c90c99178",
"snapshot_id": "58f0f12d7156f3fa2c74c77cebdc2de269f64512",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/waterproofpatch/c_list/3a1f4b1e3e23780e963258e1edd6cd3c90c99178/src/lib/list.c",
"visit_date": "2022-04-29T03:33:34.694254"
}
|
stackv2
|
/**
* @author waterproofpatch
* @file list.c
* @brief List implementation.
*/
#include <stdlib.h>
/* Foreard declarations for this file */
#include "list.h"
list_t *list_init(void *(*list_malloc)(size_t), void (*list_free)(void *))
{
/* Validate args */
if (list_malloc == NULL || list_free == NULL)
{
return NULL;
}
/* Create a new list structure and initialize its members */
list_t *list = (list_t *)list_malloc(sizeof(list_t));
if (list == NULL)
{
return NULL;
}
list->head = list->tail = NULL;
list->count = 0;
list->list_malloc = list_malloc;
list->list_free = list_free;
return list;
}
void list_destroy(list_t *list)
{
/* Validate args */
if (list == NULL)
{
return;
}
/* Release resources for each list_node_t */
list_node_t *cur = list->head;
list_node_t *next = NULL;
while (cur)
{
next = cur->next;
list->list_free(cur);
cur = next;
}
/* .. and then finally for the list itself */
list->list_free(list);
}
int list_add(list_t *list, void *element)
{
/* Validate args */
if (list == NULL || element == NULL)
{
return 0;
}
/* Create a new entry to hold a reference to the data */
list_node_t *new_node =
(list_node_t *)list->list_malloc(sizeof(list_node_t));
if (new_node == NULL)
{
return 0;
}
new_node->next = NULL;
new_node->element = element;
/* Case where new element is the first element */
if (list->head == NULL)
{
list->head = new_node;
list->tail = new_node;
list->count++;
return 1;
}
/* Case where new element is not the first element */
list->tail->next = new_node;
list->tail = new_node;
list->count++;
return 1;
}
int list_remove(list_t *list, void *element)
{
/* Validate args */
if (list == NULL || element == NULL)
{
return 0;
}
list_node_t *cur = list->head;
list_node_t *prev = NULL;
/* Compare pointers until we find a matching entry */
while (cur && cur->element != element)
{
prev = cur;
cur = cur->next;
}
/* Not found */
if (!cur)
{
return 0;
}
/* If we're removing the tail, move the tail back */
if (cur == list->tail)
{
list->tail = prev;
}
/* Skip entry about to be removed */
if (prev)
{
prev->next = cur->next;
}
/* Case where head is removed */
else
{
list->head = cur->next;
}
list->list_free(cur);
list->count--;
return 1;
}
void list_foreach(list_t *list,
void (*process_func)(void *, void *),
void *context)
{
/* Validate args */
if (list == NULL || process_func == NULL)
{
return;
}
/* Starting with the head, move through each element
* in the list invoking the process func on it */
list_node_t *cur = list->head;
while (cur)
{
process_func(cur->element, context);
cur = cur->next;
}
}
void *list_get_at_index(list_t *list, unsigned int index)
{
/* Validate args */
if (list == NULL)
{
return NULL;
}
/* Move through the list until the requested index is found or we are out of
* elements */
unsigned int i = 0;
list_node_t *cur = list->head;
while (cur && i++ < index)
{
cur = cur->next;
}
return cur != NULL ? cur->element : NULL;
}
void *list_search(list_t *list,
char (*key_comparator)(void *, void *),
void *key)
{
/* Validate args */
if (list == NULL || key_comparator == NULL || key == NULL)
{
return NULL;
}
/* Starting with the head, move through each element in the list
* and invoke the key_comparator on it with the supplied key
* until we have a match or we exhaust the list. */
list_node_t *cur = list->head;
while (cur)
{
if (key_comparator(cur->element, key) == 1)
{
return cur->element;
}
cur = cur->next;
}
return NULL;
}
inline size_t list_count(list_t *list)
{
return list == NULL ? 0 : list->count;
}
| 3.28125 | 3 |
2024-11-18T21:30:11.918407+00:00
| 2021-04-12T14:56:13 |
d2a0f67e4e72e6b2e40930608b83126d53f89548
|
{
"blob_id": "d2a0f67e4e72e6b2e40930608b83126d53f89548",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-12T14:56:13",
"content_id": "331ea924b6f613045f96a0b6c16dea236f01f932",
"detected_licenses": [
"MIT"
],
"directory_id": "7ceb425e73d16e119202f4dc57be22023f72ec7b",
"extension": "h",
"filename": "ufm_rw_utils.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4944,
"license": "MIT",
"license_type": "permissive",
"path": "/fw/code/inc/ufm_rw_utils.h",
"provenance": "stackv2-0112.json.gz:189414",
"repo_name": "lobster1989/pfr-wilson-city",
"revision_date": "2021-04-12T14:56:13",
"revision_id": "6b85ec3895653210110e20412e4e686d318e65d7",
"snapshot_id": "2204520565ddc4122f4a7ca3e6bf7b28fbcd20af",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lobster1989/pfr-wilson-city/6b85ec3895653210110e20412e4e686d318e65d7/fw/code/inc/ufm_rw_utils.h",
"visit_date": "2023-04-06T23:29:30.566829"
}
|
stackv2
|
/******************************************************************************
* Copyright (c) 2021 Intel Corporation
*
* 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.
******************************************************************************/
/**
* @file ufm_rw_utils.h
* @brief Responsible for read & write access to the UFM flash.
*/
#ifndef WHITLEY_INC_UFM_RW_UTILS_H_
#define WHITLEY_INC_UFM_RW_UTILS_H_
// Always include pfr_sys.h first
#include "pfr_sys.h"
#include "pfr_pointers.h"
#define U_UFM_CSR_ADDR __IO_CALC_ADDRESS_NATIVE_ALT_U32(U_UFM_CSR_BASE, 0)
#define UFM_CSR_STATUS_REG U_UFM_CSR_ADDR
#define UFM_CSR_CTRL_REG U_UFM_CSR_ADDR + 1
//default value of the control register when all sectors have write enabled and the sector erase and page erase bits are set to all 1s
#define UFM_CTRL_REG_DEFAULT_VAL 0xf07fffff
//The lower 20 bits hold the page erase address
#define UFM_PAGE_ERASE_MASK 0xfff00000
// bits 22-20 hold the sector erase info
#define UFM_SECTOR_ERASE_MASK 0xff8fffff
// busy bits are bits[1:0]
#define UFM_BUSY_BITS_MASK 0b11
// write success is bit[3]
#define UFM_WRITE_SUCCESS_MASK 0b1000
static PFR_ALT_INLINE void PFR_ALT_ALWAYS_INLINE ufm_enable_write()
{
IOWR(UFM_CSR_CTRL_REG, 0, UFM_CTRL_REG_DEFAULT_VAL);
}
/**
* @brief Check if UFM is busy processing erase/write command.
*
* @return 1 if busy is busy; 0, otherwise.
*/
static alt_u32 is_ufm_busy()
{
#ifdef USE_SYSTEM_MOCK
// Assume never busy in system mock
return 0;
#endif
return (IORD(UFM_CSR_STATUS_REG, 0) & UFM_BUSY_BITS_MASK) != 0;
}
/**
* @brief Erase the page where the address is pointing at.
*
* @param addr An address within the UFM flash.
*/
static void ufm_erase_page(alt_u32 addr)
{
#ifdef USE_SYSTEM_MOCK
// Call system mock's UFM page erase function.
SYSTEM_MOCK::get()->erase_ufm_page(addr);
return;
#endif
IOWR(UFM_CSR_CTRL_REG, 0, UFM_CTRL_REG_DEFAULT_VAL & ( (addr) | UFM_PAGE_ERASE_MASK));
// Poll until erase is finished
while (is_ufm_busy()) {}
}
/**
* @brief Perform Sector Erase in UFM for the given sector
*/
static void ufm_erase_sector(alt_u32 sector_id)
{
#ifdef USE_SYSTEM_MOCK
// Call system mock's UFM sector erase function.
SYSTEM_MOCK::get()->erase_ufm_sector(sector_id);
return;
#endif
IOWR(UFM_CSR_CTRL_REG, 0, (UFM_CTRL_REG_DEFAULT_VAL & UFM_SECTOR_ERASE_MASK) | (sector_id << 20));
while (is_ufm_busy()) {}
}
/**
* @brief Read data from the Mailbox fifo and write to specific location in UFM.
* There's a statically allocated buffer to store the read data. The largest block
* of data that Nios is expecting to read from the mailbox FIFO is the root key hash.
* The size of root key hash is defined by PFR_CRYPTO_LENGTH macro.
*
* The mailbox FIFO is flushed after read.
*
* @param ufm_addr pointer to the destination address in UFM
* @param nbytes number of bytes to read/write
*/
static void write_ufm_from_mb_fifo(alt_u32* ufm_addr, alt_u32 nbytes)
{
// The largest block of data to read from mailbox fifo is PFR_CRYPTO_LENGTH bytes.
alt_u8 read_data_buffer[PFR_CRYPTO_LENGTH];
// Read the data a byte by a byte
for (alt_u32 i = 0; i < nbytes; i++)
{
read_data_buffer[i] = read_from_mailbox_fifo();
}
// Upon completion, flush the FIFO
flush_mailbox_fifo();
// Commit write data to UFM
alt_u32_memcpy(ufm_addr, (alt_u32*) read_data_buffer, nbytes);
}
/**
* @brief Read data from the UFM and write to the mailbox fifo
*
* @param ufm_addr pointer to the destination address in UFM
* @param nbytes number of bytes to read/write
*/
static void write_mb_fifo_from_ufm(alt_u8* ufm_addr, alt_u32 nbytes)
{
// flush the FIFO prior to write for sanity
flush_mailbox_fifo();
for (alt_u32 i = 0; i < nbytes; i++)
{
write_to_mailbox_fifo(ufm_addr[i]);
}
}
#endif /* WHITLEY_INC_UFM_RW_UTILS_H_ */
| 2.109375 | 2 |
2024-11-18T21:30:12.138687+00:00
| 2013-10-01T08:51:29 |
b7854df3c2e198cda4973fd26cfa996e350989bc
|
{
"blob_id": "b7854df3c2e198cda4973fd26cfa996e350989bc",
"branch_name": "refs/heads/master",
"committer_date": "2013-10-01T08:51:29",
"content_id": "be1950f0e2c8af26997cb00f88aa69a2b90a2f56",
"detected_licenses": [
"MIT-enna"
],
"directory_id": "596c31b047ca731e4908aaf9f056b6ec39623380",
"extension": "c",
"filename": "irc.c",
"fork_events_count": 7,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2317070,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18451,
"license": "MIT-enna",
"license_type": "permissive",
"path": "/PROTO/emote/src/lib/protocols/irc/irc.c",
"provenance": "stackv2-0112.json.gz:189802",
"repo_name": "kakaroto/e17",
"revision_date": "2013-10-01T08:51:29",
"revision_id": "93aef5b89a5e845d90fba2c209b548c1c1f553cf",
"snapshot_id": "0762d641749774371739852a3969f0859ddce99b",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/kakaroto/e17/93aef5b89a5e845d90fba2c209b548c1c1f553cf/PROTO/emote/src/lib/protocols/irc/irc.c",
"visit_date": "2020-06-04T18:17:12.959338"
}
|
stackv2
|
#include "irc.h"
#include "irc_parse.h"
#include "emote_private.h"
#include <Ecore_Con.h>
#include <unistd.h>
EMAPI Emote_Protocol_Api protocol_api =
{
/* version, name, label */
EMOTE_PROTOCOL_API_VERSION, "irc", "IRC"
};
typedef struct _IRC_Server_Params IRC_Server_Params;
static Eina_Bool _irc_cb_server_add(void *data, int type __UNUSED__, void *event __UNUSED__);
static Eina_Bool _irc_cb_server_del(void *data, int type __UNUSED__, void *event __UNUSED__);
static Eina_Bool _irc_cb_server_data(void *data, int type __UNUSED__, void *event);
static Eina_Bool _irc_event_handler(void *data __UNUSED__, int type, void *event);
static Emote_Protocol *m;
static Eina_Hash *_irc_servers = NULL;
static Emote_Event_Type _em_events[] =
{
EMOTE_EVENT_SERVER_CONNECT,
EMOTE_EVENT_SERVER_DISCONNECT,
EMOTE_EVENT_CHAT_JOIN,
EMOTE_EVENT_CHAT_MESSAGE_SEND,
EMOTE_EVENT_SERVER_MESSAGE_SEND
};
struct _IRC_Server_Params
{
const char *name;
int port;
const char *nick;
const char *user;
const char *pass;
};
EMAPI int
protocol_init(Emote_Protocol *p)
{
unsigned int i;
m = p;
ecore_con_init();
_irc_servers = eina_hash_string_superfast_new(NULL);
for (i = 0; i < (sizeof(_em_events)/sizeof(Emote_Event_Type)); ++i)
emote_event_handler_add(_em_events[i], _irc_event_handler, NULL);
return 1;
}
EMAPI int
protocol_shutdown(void)
{
ecore_con_shutdown();
if (_irc_servers)
eina_hash_free(_irc_servers);
return 1;
}
int
protocol_irc_connect(const char *server, int port, const char *nick, const char *user, const char *pass)
{
Ecore_Con_Server *serv = NULL;
IRC_Server_Params *params;
if (!server) return 0;
if (!(serv = eina_hash_find(_irc_servers, server)))
{
if (port <= 0) port = 6667;
if (!user)
user = getlogin();
if (!nick)
nick = user;
if (!pass)
pass = user;
// Create params
params = EMOTE_NEW(IRC_Server_Params, 1);
params->name = ((server != NULL) ? eina_stringshare_add(server) : NULL);
params->nick = ((nick != NULL) ? eina_stringshare_add(nick) : NULL);
params->user = ((user != NULL) ? eina_stringshare_add(user) : NULL);
params->pass = ((pass != NULL) ? eina_stringshare_add(pass) : NULL);
params->port = port;
serv = ecore_con_server_connect(ECORE_CON_REMOTE_SYSTEM,
server, port, params);
ecore_event_handler_add(ECORE_CON_EVENT_SERVER_ADD,
_irc_cb_server_add, NULL);
ecore_event_handler_add(ECORE_CON_EVENT_SERVER_DEL,
_irc_cb_server_del, NULL);
ecore_event_handler_add(ECORE_CON_EVENT_SERVER_DATA,
_irc_cb_server_data, NULL);
eina_hash_add(_irc_servers, server, serv);
protocol_irc_pass(server, pass);
protocol_irc_user(server, user);
protocol_irc_nick(server, nick);
}
return 1;
}
int
protocol_irc_disconnect(const char *server)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if (!server) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "QUIT\r\n");
ecore_con_server_send(serv, buf, len);
ecore_con_server_flush(serv);
ecore_con_server_del(serv);
return 1;
}
int
protocol_irc_pass(const char *server, const char *pass)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!pass)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "PASS %s\r\n", pass);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_nick(const char *server, const char *nick)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!nick)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "NICK %s\r\n", nick);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_user(const char *server, const char *nick)
{
Ecore_Con_Server *serv = NULL;
char buf[512], host[64];
int len = 0;
if ((!server) || (!nick)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
gethostname(host, 63);
len = snprintf(buf, sizeof(buf), "USER %s %s %s :%s\r\n",
nick, host, server, "Emote Tester");
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_join(const char *server, const char *chan)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!chan)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "JOIN %s\r\n", chan);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_command(const char *server, const char *message)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!message)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "%s\r\n", message);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_message(const char *server, const char *chan, const char *message)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!chan) || (!message)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "PRIVMSG %s :%s\r\n", chan, message);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_identify(const char *server, const char *pass)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!pass)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "IDENTIFY %s\r\n", pass);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_ghost(const char *server, const char *nick, const char *pass)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!nick) || (!pass)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "GHOST %s %s\r\n", nick, pass);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_part(const char *server, const char *channel, const char *reason)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
if (reason[0])
len = snprintf(buf, sizeof(buf), "PART %s :%s\r\n", channel, reason);
else
len = snprintf(buf, sizeof(buf), "PART %s\r\n", channel);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_back(const char *server)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if (!server) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "AWAY\r\n");
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_away(const char *server, const char *reason)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if (!server) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
if (reason)
{
if (!reason[0]) reason = " ";
}
else
reason = " ";
len = snprintf(buf, sizeof(buf), "AWAY :%s\r\n", reason);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_away_status(const char *server, const char *channel)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "WHO %s\r\n", channel);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_kick(const char *server, const char *channel, const char *nick, const char *reason)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel) || (!nick)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
if (reason[0])
len = snprintf(buf, sizeof(buf), "KICK %s %s :%s\r\n",
channel, nick, reason);
else
len = snprintf(buf, sizeof(buf), "KICK %s %s\r\n", channel, nick);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_invite(const char *server, const char *channel, const char *nick)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel) || (!nick)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "INVITE %s %s\r\n", nick, channel);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_mode(const char *server, const char *channel, const char *mode)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel) || (!mode)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "MODE %s %s\r\n", channel, mode);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_user_list(const char *server, const char *channel)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "WHO %s\r\n", channel);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_user_host(const char *server, const char *nick)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!nick)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "USERHOST %s\r\n", nick);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_user_whois(const char *server, const char *nick)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!nick)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "WHOIS %s\r\n", nick);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_action(const char *server, const char *channel, const char *action)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel) || (!action)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf),
"PRIVMSG %s :\001ACTION %s\001\r\n", channel, action);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_notice(const char *server, const char *channel, const char *notice)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel) || (!notice)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "NOTICE %s :%s\r\n", channel, notice);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_topic(const char *server, const char *channel, const char *topic)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
if (!topic)
len = snprintf(buf, sizeof(buf), "TOPIC %s :\r\n", channel);
else if (topic[0])
len = snprintf(buf, sizeof(buf), "TOPIC %s :%s\r\n", channel, topic);
else
len = snprintf(buf, sizeof(buf), "TOPIC %s\r\n", channel);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_channels_list(const char *server, const char *arg)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if (!server) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
if (arg[0])
len = snprintf(buf, sizeof(buf), "LIST %s\r\n", arg);
else
len = snprintf(buf, sizeof(buf), "LIST\r\n");
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_names(const char *server, const char *channel)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!channel)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "NAMES %s\r\n", channel);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_ping(const char *server, const char *to, const char *timestring)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!timestring)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
if ((to) && (to[0]))
len = snprintf(buf, sizeof(buf),
"PRIVMSG %s :\001PING %s\001\r\n", to, timestring);
else
len = snprintf(buf, sizeof(buf), "PING %s\r\n", timestring);
ecore_con_server_send(serv, buf, len);
return 1;
}
int
protocol_irc_pong(const char *server, const char *msg)
{
Ecore_Con_Server *serv = NULL;
char buf[512];
int len = 0;
if ((!server) || (!msg)) return 0;
if (!(serv = eina_hash_find(_irc_servers, server))) return 0;
if (!ecore_con_server_connected_get(serv)) return 0;
len = snprintf(buf, sizeof(buf), "PONG %s\n", msg);
ecore_con_server_send(serv, buf, len);
return 1;
}
static Eina_Bool
_irc_cb_server_add(void *data __UNUSED__, int type __UNUSED__, void *event)
{
Ecore_Con_Event_Server_Data *ev;
Emote_Event *d;
IRC_Server_Params *params;
ev = event;
if (!ev->server) return EINA_FALSE;
params = ecore_con_server_data_get(ev->server);
d = emote_event_new
(
m,
EMOTE_EVENT_SERVER_CONNECTED,
params->name,
params->port,
params->nick,
params->user,
params->pass
);
emote_event_send(d);
return EINA_FALSE;
}
static Eina_Bool
_irc_cb_server_del(void *data __UNUSED__, int type __UNUSED__, void *event)
{
Ecore_Con_Event_Server_Data *ev;
Emote_Event *d;
IRC_Server_Params *params;
ev = event;
if (!ev->server) return EINA_FALSE;
d = emote_event_new(m, EMOTE_EVENT_SERVER_DISCONNECTED, ecore_con_server_name_get(ev->server));
emote_event_send(d);
params = ecore_con_server_data_get(ev->server);
eina_hash_del_by_key(_irc_servers, params->name);
if (params->name) eina_stringshare_del(params->name);
if (params->nick) eina_stringshare_del(params->name);
if (params->user) eina_stringshare_del(params->name);
if (params->pass) eina_stringshare_del(params->name);
EMOTE_FREE(params);
return EINA_FALSE;
}
static Eina_Bool
_irc_cb_server_data(void *data __UNUSED__, int type __UNUSED__, void *event)
{
Ecore_Con_Event_Server_Data *ev;
char *msg;
ev = event;
if(!ev->server) return EINA_FALSE;
msg = calloc((ev->size + 1), sizeof(char));
strncpy(msg, ev->data, ev->size);
irc_parse_input(msg, ecore_con_server_name_get(ev->server), m);
free(msg);
return EINA_FALSE;
}
static Eina_Bool
_irc_event_handler(void *data __UNUSED__, int type __UNUSED__, void *event)
{
if (EMOTE_EVENT_T(event)->protocol != m)
return EINA_FALSE;
switch(EMOTE_EVENT_T(event)->type)
{
case EMOTE_EVENT_SERVER_CONNECT:
{
Emote_Event_Server_Connect *d;
d = event;
protocol_irc_connect(
EMOTE_EVENT_SERVER_T(d)->server,
d->port,
d->nick,
d->username,
d->password
);
break;
}
case EMOTE_EVENT_SERVER_DISCONNECT:
{
Emote_Event_Server *d;
d = event;
protocol_irc_disconnect(d->server);
break;
}
case EMOTE_EVENT_CHAT_JOIN:
{
Emote_Event_Chat *d;
d = event;
protocol_irc_join(EMOTE_EVENT_SERVER_T(d)->server, d->channel);
break;
}
case EMOTE_EVENT_CHAT_MESSAGE_SEND:
{
Emote_Event_Chat_Message *d;
d = event;
protocol_irc_message(EMOTE_EVENT_SERVER_T(d)->server,
EMOTE_EVENT_CHAT_T(d)->channel,
((d->message[0] == '/') ? &(d->message[1]) : d->message));
break;
}
case EMOTE_EVENT_SERVER_MESSAGE_SEND:
{
Emote_Event_Server_Message *d;
d = event;
protocol_irc_command(EMOTE_EVENT_SERVER_T(d)->server, &(d->message[1]));
break;
}
default:
printf("Unhandled Event (%u)!\n", EMOTE_EVENT_T(event)->type);
return EINA_FALSE;
}
return EINA_TRUE;
}
| 2.1875 | 2 |
2024-11-18T21:30:12.316537+00:00
| 2016-12-30T20:45:54 |
1f1f257ed24e60319a064bf3690be2afd23d6490
|
{
"blob_id": "1f1f257ed24e60319a064bf3690be2afd23d6490",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-30T20:45:54",
"content_id": "9dafb60161ecf8402012e2c220e1c8834f3776d0",
"detected_licenses": [
"Zlib"
],
"directory_id": "4d1b273e7bfda3a5c9fce2274778a4274c3eddfa",
"extension": "c",
"filename": "virtualpath.c",
"fork_events_count": 24,
"gha_created_at": "2016-02-29T21:34:50",
"gha_event_created_at": "2018-10-05T21:55:12",
"gha_language": "C",
"gha_license_id": "Zlib",
"github_id": 52826445,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2941,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/virtualpath.c",
"provenance": "stackv2-0112.json.gz:189932",
"repo_name": "dimok789/ftpiiu",
"revision_date": "2016-12-30T20:45:54",
"revision_id": "dfbb117c4509b9bb7ccfdc76f632a2a777cfb293",
"snapshot_id": "9d2601196db5bdc63d1bd53f5052b76203ed6999",
"src_encoding": "UTF-8",
"star_events_count": 69,
"url": "https://raw.githubusercontent.com/dimok789/ftpiiu/dfbb117c4509b9bb7ccfdc76f632a2a777cfb293/src/virtualpath.c",
"visit_date": "2021-05-04T11:28:40.200322"
}
|
stackv2
|
/****************************************************************************
* Copyright (C) 2008
* Joseph Jordan <[email protected]>
*
* Copyright (C) 2010
* by Dimok
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, and to alter it and
* redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you
* must not claim that you wrote the original software. If you use
* this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and
* must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* for WiiXplorer 2010
***************************************************************************/
#include <malloc.h>
#include <string.h>
#include "virtualpath.h"
u8 MAX_VIRTUAL_PARTITIONS = 0;
VIRTUAL_PARTITION * VIRTUAL_PARTITIONS = NULL;
void VirtualMountDevice(const char * path)
{
if(!path)
return;
int i = 0;
char name[255];
char alias[255];
char prefix[255];
bool namestop = false;
alias[0] = '/';
do
{
if(path[i] == ':')
namestop = true;
if(!namestop)
{
name[i] = path[i];
name[i+1] = '\0';
alias[i+1] = path[i];
alias[i+2] = '\0';
}
prefix[i] = path[i];
prefix[i+1] = '\0';
i++;
}
while(path[i-1] != '/');
AddVirtualPath(name, alias, prefix);
}
void AddVirtualPath(const char *name, const char *alias, const char *prefix)
{
if(!VIRTUAL_PARTITIONS)
VIRTUAL_PARTITIONS = (VIRTUAL_PARTITION *) malloc(sizeof(VIRTUAL_PARTITION));
VIRTUAL_PARTITION * tmp = realloc(VIRTUAL_PARTITIONS, sizeof(VIRTUAL_PARTITION)*(MAX_VIRTUAL_PARTITIONS+1));
if(!tmp)
{
free(VIRTUAL_PARTITIONS);
MAX_VIRTUAL_PARTITIONS = 0;
return;
}
VIRTUAL_PARTITIONS = tmp;
VIRTUAL_PARTITIONS[MAX_VIRTUAL_PARTITIONS].name = strdup(name);
VIRTUAL_PARTITIONS[MAX_VIRTUAL_PARTITIONS].alias = strdup(alias);
VIRTUAL_PARTITIONS[MAX_VIRTUAL_PARTITIONS].prefix = strdup(prefix);
VIRTUAL_PARTITIONS[MAX_VIRTUAL_PARTITIONS].inserted = true;
MAX_VIRTUAL_PARTITIONS++;
}
void MountVirtualDevices()
{
VirtualMountDevice("sd:/");
}
void UnmountVirtualPaths()
{
u32 i = 0;
for(i = 0; i < MAX_VIRTUAL_PARTITIONS; i++)
{
if(VIRTUAL_PARTITIONS[i].name)
free(VIRTUAL_PARTITIONS[i].name);
if(VIRTUAL_PARTITIONS[i].alias)
free(VIRTUAL_PARTITIONS[i].alias);
if(VIRTUAL_PARTITIONS[i].prefix)
free(VIRTUAL_PARTITIONS[i].prefix);
}
if(VIRTUAL_PARTITIONS)
free(VIRTUAL_PARTITIONS);
VIRTUAL_PARTITIONS = NULL;
MAX_VIRTUAL_PARTITIONS = 0;
}
| 2.203125 | 2 |
2024-11-18T21:30:12.423843+00:00
| 2018-05-25T08:41:01 |
26a423cc205f0216c2002e0e748a25d3d4c2a817
|
{
"blob_id": "26a423cc205f0216c2002e0e748a25d3d4c2a817",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-25T08:41:01",
"content_id": "42072b382a9893296767126aa6449dc5c89e34b6",
"detected_licenses": [
"MIT"
],
"directory_id": "a9e6fc2474cdf4a2369acaecd5a8a4f835154846",
"extension": "c",
"filename": "emplace_float_suite.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": 1330,
"license": "MIT",
"license_type": "permissive",
"path": "/test/c/emplace_float_suite.c",
"provenance": "stackv2-0112.json.gz:190062",
"repo_name": "joeloliaragao/Telemetry",
"revision_date": "2018-05-25T08:41:01",
"revision_id": "76de42fcf6585c3124cea3f441e3e780671cd147",
"snapshot_id": "128cef0adf206fba867be3efc28013b94ad2375f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/joeloliaragao/Telemetry/76de42fcf6585c3124cea3f441e3e780671cd147/test/c/emplace_float_suite.c",
"visit_date": "2020-04-18T04:36:10.023080"
}
|
stackv2
|
#include "test.h"
TEST emplace_float32()
{
TM_msg dummy;
float buf = 64;
dummy.type = TM_float32;
dummy.buffer = (void *)&buf;
dummy.size = 1;
float destination;
if(!emplace_f32(&dummy, &destination))
{
FAIL();
}
ASSERT_EQ_FMT(buf, destination,"%f");
PASS();
}
TEST emplace_float32_neg()
{
TM_msg dummy;
float buf = -64;
dummy.type = TM_float32;
dummy.buffer = (void *)&buf;
dummy.size = 1;
float destination;
if(!emplace_f32(&dummy, &destination))
{
FAIL();
}
ASSERT_EQ_FMT(buf, destination,"%f");
PASS();
}
TEST emplace_float32_decimals()
{
TM_msg dummy;
float buf = 64.123456;
dummy.type = TM_float32;
dummy.buffer = (void *)&buf;
dummy.size = 1;
float destination;
if(!emplace_f32(&dummy, &destination))
{
FAIL();
}
ASSERT_EQ_FMT(buf, destination,"%f");
PASS();
}
TEST emplace_float32_decimals_neg()
{
TM_msg dummy;
float buf = -64.123456;
dummy.type = TM_float32;
dummy.buffer = (void *)&buf;
dummy.size = 1;
float destination;
if(!emplace_f32(&dummy, &destination))
{
FAIL();
}
ASSERT_EQ_FMT(buf, destination,"%f");
PASS();
}
SUITE(emplace_float_suite) {
RUN_TEST(emplace_float32);
RUN_TEST(emplace_float32_neg);
RUN_TEST(emplace_float32_decimals);
RUN_TEST(emplace_float32_decimals_neg);
}
| 2.5625 | 3 |
2024-11-18T21:30:12.792252+00:00
| 2022-06-11T10:43:35 |
fd79363970a654fd55167c30fb001bc3186b53ef
|
{
"blob_id": "fd79363970a654fd55167c30fb001bc3186b53ef",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-11T10:48:44",
"content_id": "27e3117dcaa9896a585942d229ebbb2af0cdc1ee",
"detected_licenses": [
"MIT"
],
"directory_id": "ebff7c39d1746127e502d201c0ed5b79e619e0a6",
"extension": "c",
"filename": "base.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 193844325,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6793,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ip/ip6/base.c",
"provenance": "stackv2-0112.json.gz:190581",
"repo_name": "dywisor/ip-dedup",
"revision_date": "2022-06-11T10:43:35",
"revision_id": "6ecacda0c660e2b19e2df8840ac73a7ec7c8ea94",
"snapshot_id": "80742e12c78b79dbdf0d0a675d05ee2b1234d96b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dywisor/ip-dedup/6ecacda0c660e2b19e2df8840ac73a7ec7c8ea94/src/ip/ip6/base.c",
"visit_date": "2022-06-14T14:50:22.189611"
}
|
stackv2
|
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>
#include <stdio.h> /* snprintf() */
#include "base.h"
#include "../base.h"
static void ip6_addr_data_copy_to_blocks (
const struct ip6_addr_data* const restrict bits,
uint16_t* const restrict blocks
);
static void ip6_addr_data_find_longest_zero_seq (
const uint16_t* const restrict blocks,
size_t* const restrict zseq_start,
size_t* const restrict zseq_len
);
static int ip6_addr_data_build_addr_str (
const uint16_t* const restrict blocks,
char* const restrict sbuf,
const size_t fill_zero_start,
const size_t fill_zero_len
);
static ip_bitpos_t ip6_calc_bitpos ( const ip_prefixlen_t prefixpos ) {
return ( IP6_MAX_PREFIXLEN - prefixpos );
}
static void ip6_calc_ro_bitpos_in (
const ip6_addr_data_t* const restrict src,
const ip_prefixlen_t prefixpos,
ip6_addr_data_chunk_t* const restrict chunk_out,
ip_bitpos_t* const restrict bitpos_out,
bool* const restrict high_out
) {
ip_bitpos_t bpos;
bpos = ip6_calc_bitpos(prefixpos);
if ( bpos < 64 ) {
*chunk_out = src->low;
*bitpos_out = bpos;
*high_out = false;
} else {
*chunk_out = src->high;
*bitpos_out = bpos - 64;
*high_out = true;
}
}
static ip6_addr_data_chunk_t ip6_calc_bit ( const ip_bitpos_t bpos ) {
ip6_addr_data_chunk_t ret;
ret = 0x1;
ret <<= bpos;
return ret;
}
bool ip6_calc_bit_is_set_at_prefixpos (
const ip6_addr_data_t* const restrict bits,
const ip_prefixlen_t prefixpos
) {
ip6_addr_data_chunk_t chunk;
ip_bitpos_t bpos;
bool is_high;
ip6_calc_ro_bitpos_in ( bits, prefixpos, &chunk, &bpos, &is_high );
return ( (chunk & ip6_calc_bit(bpos)) != 0 ) ? true : false;
}
void ip6_calc_flip_bit_at_prefixpos (
const ip6_addr_data_t* const restrict bits,
const ip_prefixlen_t prefixpos,
ip6_addr_data_t* const restrict dst
) {
ip6_addr_data_chunk_t src_chunk;
ip6_addr_data_chunk_t flipped;
ip6_addr_data_chunk_t new_chunk;
ip_bitpos_t bpos;
bool is_high;
ip6_calc_ro_bitpos_in ( bits, prefixpos, &src_chunk, &bpos, &is_high );
flipped = ip6_calc_bit(bpos);
new_chunk = (src_chunk ^ flipped);
if ( is_high ) {
dst->low = bits->low;
dst->high = new_chunk;
} else {
dst->low = new_chunk;
dst->high = bits->high;
}
}
void ip6_calc_set_bit_at_prefixpos (
const ip6_addr_data_t* const restrict bits,
const ip_prefixlen_t prefixpos,
bool bit_set,
ip6_addr_data_t* const restrict dst
) {
ip6_addr_data_chunk_t src_chunk;
ip6_addr_data_chunk_t bit_mask;
ip6_addr_data_chunk_t new_chunk;
ip_bitpos_t bpos;
bool is_high;
ip6_calc_ro_bitpos_in ( bits, prefixpos, &src_chunk, &bpos, &is_high );
bit_mask = ip6_calc_bit(bpos);
new_chunk = ( bit_set ? (src_chunk | bit_mask) : (src_chunk & ~bit_mask) );
if ( is_high ) {
dst->low = bits->low;
dst->high = new_chunk;
} else {
dst->low = new_chunk;
dst->high = bits->high;
}
}
void ip6_calc_netmask (
const ip_prefixlen_t prefixlen,
ip6_addr_data_t* const restrict dst
) {
if ( prefixlen >= IP6_DATA_CHUNK_SIZE ) {
dst->high = IP6_DATA_CHUNK_MAX;
if ( prefixlen >= IP6_MAX_PREFIXLEN ) {
dst->low = IP6_DATA_CHUNK_MAX;
} else {
const ip_prefixlen_t rem = (prefixlen - IP6_DATA_CHUNK_SIZE);
dst->low = (
IP6_DATA_CHUNK_MAX & (
IP6_DATA_CHUNK_MAX << (IP6_DATA_CHUNK_SIZE - rem)
)
);
}
} else {
dst->high = (
IP6_DATA_CHUNK_MAX & (
IP6_DATA_CHUNK_MAX << (IP6_DATA_CHUNK_SIZE - prefixlen)
)
);
dst->low = 0x0;
}
}
static void ip6_addr_data_copy_to_blocks (
const struct ip6_addr_data* const restrict bits,
uint16_t* const restrict blocks
) {
unsigned k;
k = 0;
for ( ; k < 4; k++ ) {
blocks[k] = (bits->high >> (16 * (4 - k - 1))) & 0xffff;
}
for ( ; k < 8; k++ ) {
blocks[k] = (bits->low >> (16 * (8 - k - 1))) & 0xffff;
}
}
static void ip6_addr_data_find_longest_zero_seq (
const uint16_t* const restrict blocks,
size_t* const restrict zseq_start,
size_t* const restrict zseq_len
) {
unsigned k;
size_t cur_zseq_start;
size_t cur_zseq_len;
*zseq_start = 0;
*zseq_len = 0;
cur_zseq_start = 0;
cur_zseq_len = 0;
for ( k = 0; k < 8; k++ ) {
if ( blocks[k] != 0 ) {
if ( cur_zseq_len > *zseq_len ) {
*zseq_start = cur_zseq_start;
*zseq_len = cur_zseq_len;
}
cur_zseq_start = k + 1;
cur_zseq_len = 0;
} else if ( cur_zseq_len == 0 ) {
cur_zseq_start = k;
cur_zseq_len = 1;
} else {
cur_zseq_len++;
}
}
if ( cur_zseq_len > *zseq_len ) {
*zseq_start = cur_zseq_start;
*zseq_len = cur_zseq_len;
}
}
static int ip6_addr_data_build_addr_str (
const uint16_t* const restrict blocks,
char* const restrict sbuf,
const size_t fill_zero_start,
const size_t fill_zero_len
) {
unsigned k;
int ret;
char* s;
s = sbuf;
*s = '\0';
for ( k = 0; k < 8; k++ ) {
/* Insert fill-empty-blocks sequence "::",
* but only if there actually is an empty block.
* */
if ( (fill_zero_len > 0) && (k == fill_zero_start) ) {
if ( k == 0 ) { *s++ = ':'; }
*s++ = ':';
k += fill_zero_len - 1; /* k++ */
} else if ( blocks[k] == 0 ) {
*s++ = '0';
if ( k < 7 ) { *s++ = ':'; }
} else {
ret = snprintf ( s, 5, ("%" PRIx16), blocks[k] );
if ( (ret <= 0) || (ret >= 5) ) { return -1; }
s += ret;
if ( k < 7 ) { *s++ = ':'; }
}
}
*s = '\0';
return 0;
}
const char* ip6_addr_data_into_str (
const struct ip6_addr_data* const restrict bits,
char* const restrict dst
) {
uint16_t blocks[8];
size_t fill_zero_start;
size_t fill_zero_len;
if ( dst == NULL ) { return NULL; }
/* create blocks */
ip6_addr_data_copy_to_blocks ( bits, blocks );
/* find longest zero sequence */
ip6_addr_data_find_longest_zero_seq (
blocks, &fill_zero_start, &fill_zero_len
);
/* create output string */
if (
ip6_addr_data_build_addr_str (
blocks, dst, fill_zero_start, fill_zero_len
) != 0
) {
return NULL;
}
return dst;
}
| 2.375 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.