added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:25:11.662833+00:00 | 2013-04-17T18:42:40 | eece52e16e2a231a35f3285494fa0eb8824d7101 | {
"blob_id": "eece52e16e2a231a35f3285494fa0eb8824d7101",
"branch_name": "refs/heads/master",
"committer_date": "2013-04-17T18:42:40",
"content_id": "5077a39e799f58114f1c696019c98366f211df2a",
"detected_licenses": [
"MIT"
],
"directory_id": "bb108c3ea7d235e6fee0575181b5988e6b6a64ef",
"extension": "c",
"filename": "i386ops.c",
"fork_events_count": 8,
"gha_created_at": "2012-03-23T04:23:01",
"gha_event_created_at": "2013-04-17T18:42:41",
"gha_language": "C",
"gha_license_id": null,
"github_id": 3805274,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 60473,
"license": "MIT",
"license_type": "permissive",
"path": "/mame/src/emu/cpu/i386/i386ops.c",
"provenance": "stackv2-0115.json.gz:111362",
"repo_name": "clobber/MAME-OS-X",
"revision_date": "2013-04-17T18:42:40",
"revision_id": "ca11d0e946636bda042b6db55c82113e5722fc08",
"snapshot_id": "3c5e6058b2814754176f3c6dcf1b2963ca804fc3",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/clobber/MAME-OS-X/ca11d0e946636bda042b6db55c82113e5722fc08/mame/src/emu/cpu/i386/i386ops.c",
"visit_date": "2021-01-20T05:31:15.086981"
} | stackv2 | static UINT8 I386OP(shift_rotate8)(i386_state *cpustate, UINT8 modrm, UINT32 value, UINT8 shift)
{
UINT8 src = value;
UINT8 dst = value;
if( shift == 0 ) {
CYCLES_RM(cpustate,modrm, 3, 7);
} else if( shift == 1 ) {
switch( (modrm >> 3) & 0x7 )
{
case 0: /* ROL rm8, 1 */
cpustate->CF = (src & 0x80) ? 1 : 0;
dst = (src << 1) + cpustate->CF;
cpustate->OF = ((src ^ dst) & 0x80) ? 1 : 0;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 1: /* ROR rm8, 1 */
cpustate->CF = (src & 0x1) ? 1 : 0;
dst = (cpustate->CF << 7) | (src >> 1);
cpustate->OF = ((src ^ dst) & 0x80) ? 1 : 0;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 2: /* RCL rm8, 1 */
dst = (src << 1) + cpustate->CF;
cpustate->CF = (src & 0x80) ? 1 : 0;
cpustate->OF = ((src ^ dst) & 0x80) ? 1 : 0;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_CARRY_REG, CYCLES_ROTATE_CARRY_MEM);
break;
case 3: /* RCR rm8, 1 */
dst = (cpustate->CF << 7) | (src >> 1);
cpustate->CF = src & 0x1;
cpustate->OF = ((src ^ dst) & 0x80) ? 1 : 0;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_CARRY_REG, CYCLES_ROTATE_CARRY_MEM);
break;
case 4: /* SHL/SAL rm8, 1 */
case 6:
dst = src << 1;
cpustate->CF = (src & 0x80) ? 1 : 0;
cpustate->OF = (((cpustate->CF << 7) ^ dst) & 0x80) ? 1 : 0;
SetSZPF8(dst);
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 5: /* SHR rm8, 1 */
dst = src >> 1;
cpustate->CF = src & 0x1;
cpustate->OF = (dst & 0x80) ? 1 : 0;
SetSZPF8(dst);
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 7: /* SAR rm8, 1 */
dst = (INT8)(src) >> 1;
cpustate->CF = src & 0x1;
cpustate->OF = 0;
SetSZPF8(dst);
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
}
} else {
switch( (modrm >> 3) & 0x7 )
{
case 0: /* ROL rm8, i8 */
dst = ((src & ((UINT8)0xff >> shift)) << shift) |
((src & ((UINT8)0xff << (8-shift))) >> (8-shift));
cpustate->CF = (src >> (8-shift)) & 0x1;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 1: /* ROR rm8, i8 */
dst = ((src & ((UINT8)0xff << shift)) >> shift) |
((src & ((UINT8)0xff >> (8-shift))) << (8-shift));
cpustate->CF = (src >> (shift-1)) & 0x1;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 2: /* RCL rm8, i8 */
dst = ((src & ((UINT8)0xff >> shift)) << shift) |
((src & ((UINT8)0xff << (9-shift))) >> (9-shift)) |
(cpustate->CF << (shift-1));
cpustate->CF = (src >> (8-shift)) & 0x1;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_CARRY_REG, CYCLES_ROTATE_CARRY_MEM);
break;
case 3: /* RCR rm8, i8 */
dst = ((src & ((UINT8)0xff << shift)) >> shift) |
((src & ((UINT8)0xff >> (8-shift))) << (9-shift)) |
(cpustate->CF << (8-shift));
cpustate->CF = (src >> (shift-1)) & 0x1;
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_CARRY_REG, CYCLES_ROTATE_CARRY_MEM);
break;
case 4: /* SHL/SAL rm8, i8 */
case 6:
dst = src << shift;
cpustate->CF = (src & (1 << (8-shift))) ? 1 : 0;
SetSZPF8(dst);
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 5: /* SHR rm8, i8 */
dst = src >> shift;
cpustate->CF = (src & (1 << (shift-1))) ? 1 : 0;
SetSZPF8(dst);
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
case 7: /* SAR rm8, i8 */
dst = (INT8)src >> shift;
cpustate->CF = (src & (1 << (shift-1))) ? 1 : 0;
SetSZPF8(dst);
CYCLES_RM(cpustate,modrm, CYCLES_ROTATE_REG, CYCLES_ROTATE_MEM);
break;
}
}
return dst;
}
static void I386OP(adc_rm8_r8)(i386_state *cpustate) // Opcode 0x10
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = ADC8(cpustate, dst, src, cpustate->CF);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = ADC8(cpustate, dst, src, cpustate->CF);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
}
static void I386OP(adc_r8_rm8)(i386_state *cpustate) // Opcode 0x12
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
dst = ADC8(cpustate, dst, src, cpustate->CF);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
dst = ADC8(cpustate, dst, src, cpustate->CF);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_MEM_REG);
}
}
static void I386OP(adc_al_i8)(i386_state *cpustate) // Opcode 0x14
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(AL);
dst = ADC8(cpustate, dst, src, cpustate->CF);
REG8(AL) = dst;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(add_rm8_r8)(i386_state *cpustate) // Opcode 0x00
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = ADD8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = ADD8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
}
static void I386OP(add_r8_rm8)(i386_state *cpustate) // Opcode 0x02
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
dst = ADD8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
dst = ADD8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_MEM_REG);
}
}
static void I386OP(add_al_i8)(i386_state *cpustate) // Opcode 0x04
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(AL);
dst = ADD8(cpustate,dst, src);
REG8(AL) = dst;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(and_rm8_r8)(i386_state *cpustate) // Opcode 0x20
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = AND8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = AND8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
}
static void I386OP(and_r8_rm8)(i386_state *cpustate) // Opcode 0x22
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
dst = AND8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
dst = AND8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_MEM_REG);
}
}
static void I386OP(and_al_i8)(i386_state *cpustate) // Opcode 0x24
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(AL);
dst = AND8(cpustate,dst, src);
REG8(AL) = dst;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(clc)(i386_state *cpustate) // Opcode 0xf8
{
cpustate->CF = 0;
CYCLES(cpustate,CYCLES_CLC);
}
static void I386OP(cld)(i386_state *cpustate) // Opcode 0xfc
{
cpustate->DF = 0;
CYCLES(cpustate,CYCLES_CLD);
}
static void I386OP(cli)(i386_state *cpustate) // Opcode 0xfa
{
cpustate->IF = 0;
CYCLES(cpustate,CYCLES_CLI);
}
static void I386OP(cmc)(i386_state *cpustate) // Opcode 0xf5
{
cpustate->CF ^= 1;
CYCLES(cpustate,CYCLES_CMC);
}
static void I386OP(cmp_rm8_r8)(i386_state *cpustate) // Opcode 0x38
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
SUB8(cpustate,dst, src);
CYCLES(cpustate,CYCLES_CMP_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
SUB8(cpustate,dst, src);
CYCLES(cpustate,CYCLES_CMP_REG_MEM);
}
}
static void I386OP(cmp_r8_rm8)(i386_state *cpustate) // Opcode 0x3a
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
SUB8(cpustate,dst, src);
CYCLES(cpustate,CYCLES_CMP_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
SUB8(cpustate,dst, src);
CYCLES(cpustate,CYCLES_CMP_MEM_REG);
}
}
static void I386OP(cmp_al_i8)(i386_state *cpustate) // Opcode 0x3c
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(AL);
SUB8(cpustate,dst, src);
CYCLES(cpustate,CYCLES_CMP_IMM_ACC);
}
static void I386OP(cmpsb)(i386_state *cpustate) // Opcode 0xa6
{
UINT32 eas, ead;
UINT8 src, dst;
if( cpustate->segment_prefix ) {
eas = i386_translate(cpustate, cpustate->segment_override, cpustate->address_size ? REG32(ESI) : REG16(SI) );
} else {
eas = i386_translate(cpustate, DS, cpustate->address_size ? REG32(ESI) : REG16(SI) );
}
ead = i386_translate(cpustate, ES, cpustate->address_size ? REG32(EDI) : REG16(DI) );
src = READ8(cpustate,eas);
dst = READ8(cpustate,ead);
SUB8(cpustate,dst, src);
BUMP_SI(cpustate,1);
BUMP_DI(cpustate,1);
CYCLES(cpustate,CYCLES_CMPS);
}
static void I386OP(in_al_i8)(i386_state *cpustate) // Opcode 0xe4
{
UINT16 port = FETCH(cpustate);
UINT8 data = READPORT8(cpustate, port);
REG8(AL) = data;
CYCLES(cpustate,CYCLES_IN_VAR);
}
static void I386OP(in_al_dx)(i386_state *cpustate) // Opcode 0xec
{
UINT16 port = REG16(DX);
UINT8 data = READPORT8(cpustate, port);
REG8(AL) = data;
CYCLES(cpustate,CYCLES_IN);
}
static void I386OP(ja_rel8)(i386_state *cpustate) // Opcode 0x77
{
INT8 disp = FETCH(cpustate);
if( cpustate->CF == 0 && cpustate->ZF == 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jbe_rel8)(i386_state *cpustate) // Opcode 0x76
{
INT8 disp = FETCH(cpustate);
if( cpustate->CF != 0 || cpustate->ZF != 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jc_rel8)(i386_state *cpustate) // Opcode 0x72
{
INT8 disp = FETCH(cpustate);
if( cpustate->CF != 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jg_rel8)(i386_state *cpustate) // Opcode 0x7f
{
INT8 disp = FETCH(cpustate);
if( cpustate->ZF == 0 && (cpustate->SF == cpustate->OF) ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jge_rel8)(i386_state *cpustate) // Opcode 0x7d
{
INT8 disp = FETCH(cpustate);
if( (cpustate->SF == cpustate->OF) ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jl_rel8)(i386_state *cpustate) // Opcode 0x7c
{
INT8 disp = FETCH(cpustate);
if( (cpustate->SF != cpustate->OF) ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jle_rel8)(i386_state *cpustate) // Opcode 0x7e
{
INT8 disp = FETCH(cpustate);
if( cpustate->ZF != 0 || (cpustate->SF != cpustate->OF) ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jnc_rel8)(i386_state *cpustate) // Opcode 0x73
{
INT8 disp = FETCH(cpustate);
if( cpustate->CF == 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jno_rel8)(i386_state *cpustate) // Opcode 0x71
{
INT8 disp = FETCH(cpustate);
if( cpustate->OF == 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jnp_rel8)(i386_state *cpustate) // Opcode 0x7b
{
INT8 disp = FETCH(cpustate);
if( cpustate->PF == 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jns_rel8)(i386_state *cpustate) // Opcode 0x79
{
INT8 disp = FETCH(cpustate);
if( cpustate->SF == 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jnz_rel8)(i386_state *cpustate) // Opcode 0x75
{
INT8 disp = FETCH(cpustate);
if( cpustate->ZF == 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jo_rel8)(i386_state *cpustate) // Opcode 0x70
{
INT8 disp = FETCH(cpustate);
if( cpustate->OF != 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jp_rel8)(i386_state *cpustate) // Opcode 0x7a
{
INT8 disp = FETCH(cpustate);
if( cpustate->PF != 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(js_rel8)(i386_state *cpustate) // Opcode 0x78
{
INT8 disp = FETCH(cpustate);
if( cpustate->SF != 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jz_rel8)(i386_state *cpustate) // Opcode 0x74
{
INT8 disp = FETCH(cpustate);
if( cpustate->ZF != 0 ) {
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JCC_DISP8); /* TODO: Timing = 7 + m */
} else {
CYCLES(cpustate,CYCLES_JCC_DISP8_NOBRANCH);
}
}
static void I386OP(jmp_rel8)(i386_state *cpustate) // Opcode 0xeb
{
INT8 disp = FETCH(cpustate);
NEAR_BRANCH(cpustate,disp);
CYCLES(cpustate,CYCLES_JMP_SHORT); /* TODO: Timing = 7 + m */
}
static void I386OP(lahf)(i386_state *cpustate) // Opcode 0x9f
{
REG8(AH) = get_flags(cpustate) & 0xd7;
CYCLES(cpustate,CYCLES_LAHF);
}
static void I386OP(lodsb)(i386_state *cpustate) // Opcode 0xac
{
UINT32 eas;
if( cpustate->segment_prefix ) {
eas = i386_translate(cpustate, cpustate->segment_override, cpustate->address_size ? REG32(ESI) : REG16(SI) );
} else {
eas = i386_translate(cpustate, DS, cpustate->address_size ? REG32(ESI) : REG16(SI) );
}
REG8(AL) = READ8(cpustate,eas);
BUMP_SI(cpustate,1);
CYCLES(cpustate,CYCLES_LODS);
}
static void I386OP(mov_rm8_r8)(i386_state *cpustate) // Opcode 0x88
{
UINT8 src;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
STORE_RM8(modrm, src);
CYCLES(cpustate,CYCLES_MOV_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
WRITE8(cpustate,ea, src);
CYCLES(cpustate,CYCLES_MOV_REG_MEM);
}
}
static void I386OP(mov_r8_rm8)(i386_state *cpustate) // Opcode 0x8a
{
UINT8 src;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
STORE_REG8(modrm, src);
CYCLES(cpustate,CYCLES_MOV_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
STORE_REG8(modrm, src);
CYCLES(cpustate,CYCLES_MOV_MEM_REG);
}
}
static void I386OP(mov_rm8_i8)(i386_state *cpustate) // Opcode 0xc6
{
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
UINT8 value = FETCH(cpustate);
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
UINT8 value = FETCH(cpustate);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_MOV_IMM_MEM);
}
}
static void I386OP(mov_r32_cr)(i386_state *cpustate) // Opcode 0x0f 20
{
UINT8 modrm = FETCH(cpustate);
UINT8 cr = (modrm >> 3) & 0x7;
STORE_RM32(modrm, cpustate->cr[cr]);
CYCLES(cpustate,CYCLES_MOV_CR_REG);
}
static void I386OP(mov_r32_dr)(i386_state *cpustate) // Opcode 0x0f 21
{
UINT8 modrm = FETCH(cpustate);
UINT8 dr = (modrm >> 3) & 0x7;
STORE_RM32(modrm, cpustate->dr[dr]);
switch(dr)
{
case 0:
case 1:
case 2:
case 3:
CYCLES(cpustate,CYCLES_MOV_REG_DR0_3);
break;
case 6:
case 7:
CYCLES(cpustate,CYCLES_MOV_REG_DR6_7);
break;
}
}
static void I386OP(mov_cr_r32)(i386_state *cpustate) // Opcode 0x0f 22
{
UINT8 modrm = FETCH(cpustate);
UINT8 cr = (modrm >> 3) & 0x7;
cpustate->cr[cr] = LOAD_RM32(modrm);
switch(cr)
{
case 0: CYCLES(cpustate,CYCLES_MOV_REG_CR0); break;
case 2: CYCLES(cpustate,CYCLES_MOV_REG_CR2); break;
case 3: CYCLES(cpustate,CYCLES_MOV_REG_CR3); break;
case 4: CYCLES(cpustate,1); break; // TODO
default:
fatalerror("i386: mov_cr_r32 CR%d !", cr);
break;
}
}
static void I386OP(mov_dr_r32)(i386_state *cpustate) // Opcode 0x0f 23
{
UINT8 modrm = FETCH(cpustate);
UINT8 dr = (modrm >> 3) & 0x7;
cpustate->dr[dr] = LOAD_RM32(modrm);
switch(dr)
{
case 0:
case 1:
case 2:
case 3:
CYCLES(cpustate,CYCLES_MOV_DR0_3_REG);
break;
case 6:
case 7:
CYCLES(cpustate,CYCLES_MOV_DR6_7_REG);
break;
default:
fatalerror("i386: mov_dr_r32 DR%d !", dr);
break;
}
}
static void I386OP(mov_al_m8)(i386_state *cpustate) // Opcode 0xa0
{
UINT32 offset, ea;
if( cpustate->address_size ) {
offset = FETCH32(cpustate);
} else {
offset = FETCH16(cpustate);
}
/* TODO: Not sure if this is correct... */
if( cpustate->segment_prefix ) {
ea = i386_translate(cpustate, cpustate->segment_override, offset );
} else {
ea = i386_translate(cpustate, DS, offset );
}
REG8(AL) = READ8(cpustate,ea);
CYCLES(cpustate,CYCLES_MOV_IMM_MEM);
}
static void I386OP(mov_m8_al)(i386_state *cpustate) // Opcode 0xa2
{
UINT32 offset, ea;
if( cpustate->address_size ) {
offset = FETCH32(cpustate);
} else {
offset = FETCH16(cpustate);
}
/* TODO: Not sure if this is correct... */
if( cpustate->segment_prefix ) {
ea = i386_translate(cpustate, cpustate->segment_override, offset );
} else {
ea = i386_translate(cpustate, DS, offset );
}
WRITE8(cpustate, ea, REG8(AL) );
CYCLES(cpustate,CYCLES_MOV_MEM_ACC);
}
static void I386OP(mov_rm16_sreg)(i386_state *cpustate) // Opcode 0x8c
{
UINT8 modrm = FETCH(cpustate);
int s = (modrm >> 3) & 0x7;
if( modrm >= 0xc0 ) {
STORE_RM16(modrm, cpustate->sreg[s].selector);
CYCLES(cpustate,CYCLES_MOV_SREG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE16(cpustate,ea, cpustate->sreg[s].selector);
CYCLES(cpustate,CYCLES_MOV_SREG_MEM);
}
}
static void I386OP(mov_sreg_rm16)(i386_state *cpustate) // Opcode 0x8e
{
UINT16 selector;
UINT8 modrm = FETCH(cpustate);
int s = (modrm >> 3) & 0x7;
if( modrm >= 0xc0 ) {
selector = LOAD_RM16(modrm);
CYCLES(cpustate,CYCLES_MOV_REG_SREG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
selector = READ16(cpustate,ea);
CYCLES(cpustate,CYCLES_MOV_MEM_SREG);
}
cpustate->sreg[s].selector = selector;
i386_load_segment_descriptor(cpustate, s );
}
static void I386OP(mov_al_i8)(i386_state *cpustate) // Opcode 0xb0
{
REG8(AL) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(mov_cl_i8)(i386_state *cpustate) // Opcode 0xb1
{
REG8(CL) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(mov_dl_i8)(i386_state *cpustate) // Opcode 0xb2
{
REG8(DL) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(mov_bl_i8)(i386_state *cpustate) // Opcode 0xb3
{
REG8(BL) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(mov_ah_i8)(i386_state *cpustate) // Opcode 0xb4
{
REG8(AH) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(mov_ch_i8)(i386_state *cpustate) // Opcode 0xb5
{
REG8(CH) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(mov_dh_i8)(i386_state *cpustate) // Opcode 0xb6
{
REG8(DH) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(mov_bh_i8)(i386_state *cpustate) // Opcode 0xb7
{
REG8(BH) = FETCH(cpustate);
CYCLES(cpustate,CYCLES_MOV_IMM_REG);
}
static void I386OP(movsb)(i386_state *cpustate) // Opcode 0xa4
{
UINT32 eas, ead;
UINT8 v;
if( cpustate->segment_prefix ) {
eas = i386_translate(cpustate, cpustate->segment_override, cpustate->address_size ? REG32(ESI) : REG16(SI) );
} else {
eas = i386_translate(cpustate, DS, cpustate->address_size ? REG32(ESI) : REG16(SI) );
}
ead = i386_translate(cpustate, ES, cpustate->address_size ? REG32(EDI) : REG16(DI) );
v = READ8(cpustate,eas);
WRITE8(cpustate,ead, v);
BUMP_SI(cpustate,1);
BUMP_DI(cpustate,1);
CYCLES(cpustate,CYCLES_MOVS);
}
static void I386OP(or_rm8_r8)(i386_state *cpustate) // Opcode 0x08
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = OR8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = OR8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
}
static void I386OP(or_r8_rm8)(i386_state *cpustate) // Opcode 0x0a
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
dst = OR8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
dst = OR8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_MEM_REG);
}
}
static void I386OP(or_al_i8)(i386_state *cpustate) // Opcode 0x0c
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(AL);
dst = OR8(cpustate,dst, src);
REG8(EAX) = dst;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(out_al_i8)(i386_state *cpustate) // Opcode 0xe6
{
UINT16 port = FETCH(cpustate);
UINT8 data = REG8(AL);
WRITEPORT8(cpustate, port, data);
CYCLES(cpustate,CYCLES_OUT_VAR);
}
static void I386OP(out_al_dx)(i386_state *cpustate) // Opcode 0xee
{
UINT16 port = REG16(DX);
UINT8 data = REG8(AL);
WRITEPORT8(cpustate, port, data);
CYCLES(cpustate,CYCLES_OUT);
}
static void I386OP(arpl)(i386_state *cpustate) // Opcode 0x63
{
UINT16 src, dst;
UINT8 modrm = FETCH(cpustate);
UINT8 flag = 0;
if( modrm >= 0xc0 ) {
src = LOAD_REG16(modrm);
dst = LOAD_RM16(modrm);
if( (dst&0x3) < (src&0x3) ) {
dst = (dst&0xfffc) | (src&0x3);
flag = 1;
STORE_RM16(modrm, dst);
}
} else {
UINT32 ea = GetEA(cpustate, modrm);
src = LOAD_REG16(modrm);
dst = READ16(cpustate, ea);
if( (dst&0x3) < (src&0x3) ) {
dst = (dst&0xfffc) | (src&0x3);
flag = 1;
WRITE16(cpustate, ea, dst);
}
}
SetZF(flag);
}
static void I386OP(push_i8)(i386_state *cpustate) // Opcode 0x6a
{
UINT8 value = FETCH(cpustate);
PUSH8(cpustate,value);
CYCLES(cpustate,CYCLES_PUSH_IMM);
}
static void I386OP(ins_generic)(i386_state *cpustate, int size)
{
UINT32 ead;
UINT8 vb;
UINT16 vw;
UINT32 vd;
ead = i386_translate(cpustate, ES, cpustate->address_size ? REG32(EDI) : REG16(DI) );
switch(size) {
case 1:
vb = READPORT8(cpustate, REG16(DX));
WRITE8(cpustate,ead, vb);
break;
case 2:
vw = READPORT16(cpustate, REG16(DX));
WRITE16(cpustate,ead, vw);
break;
case 4:
vd = READPORT32(cpustate, REG16(DX));
WRITE32(cpustate,ead, vd);
break;
}
REG32(EDI) += ((cpustate->DF) ? -1 : 1) * size;
CYCLES(cpustate,CYCLES_INS); // TODO: Confirm this value
}
static void I386OP(insb)(i386_state *cpustate) // Opcode 0x6c
{
I386OP(ins_generic)(cpustate, 1);
}
static void I386OP(insw)(i386_state *cpustate) // Opcode 0x6d
{
I386OP(ins_generic)(cpustate, 2);
}
static void I386OP(insd)(i386_state *cpustate) // Opcode 0x6d
{
I386OP(ins_generic)(cpustate, 4);
}
static void I386OP(outs_generic)(i386_state *cpustate, int size)
{
UINT32 eas;
UINT8 vb;
UINT16 vw;
UINT32 vd;
if( cpustate->segment_prefix ) {
eas = i386_translate(cpustate, cpustate->segment_override, cpustate->address_size ? REG32(ESI) : REG16(SI) );
} else {
eas = i386_translate(cpustate, DS, cpustate->address_size ? REG32(ESI) : REG16(SI) );
}
switch(size) {
case 1:
vb = READ8(cpustate,eas);
WRITEPORT8(cpustate, REG16(DX), vb);
break;
case 2:
vw = READ16(cpustate,eas);
WRITEPORT16(cpustate, REG16(DX), vw);
break;
case 4:
vd = READ32(cpustate,eas);
WRITEPORT32(cpustate, REG16(DX), vd);
break;
}
REG32(ESI) += ((cpustate->DF) ? -1 : 1) * size;
CYCLES(cpustate,CYCLES_OUTS); // TODO: Confirm this value
}
static void I386OP(outsb)(i386_state *cpustate) // Opcode 0x6e
{
I386OP(outs_generic)(cpustate, 1);
}
static void I386OP(outsw)(i386_state *cpustate) // Opcode 0x6f
{
I386OP(outs_generic)(cpustate, 2);
}
static void I386OP(outsd)(i386_state *cpustate) // Opcode 0x6f
{
I386OP(outs_generic)(cpustate, 4);
}
static void I386OP(repeat)(i386_state *cpustate, int invert_flag)
{
UINT32 repeated_eip = cpustate->eip;
UINT32 repeated_pc = cpustate->pc;
UINT8 opcode; // = FETCH(cpustate);
// UINT32 eas, ead;
UINT32 count;
INT32 cycle_base = 0, cycle_adjustment = 0;
UINT8 prefix_flag=1;
UINT8 *flag = NULL;
do {
repeated_eip = cpustate->eip;
repeated_pc = cpustate->pc;
opcode = FETCH(cpustate);
switch(opcode) {
case 0x26:
cpustate->segment_override=ES;
cpustate->segment_prefix=1;
break;
case 0x2e:
cpustate->segment_override=CS;
cpustate->segment_prefix=1;
break;
case 0x36:
cpustate->segment_override=SS;
cpustate->segment_prefix=1;
break;
case 0x3e:
cpustate->segment_override=DS;
cpustate->segment_prefix=1;
break;
case 0x64:
cpustate->segment_override=FS;
cpustate->segment_prefix=1;
break;
case 0x65:
cpustate->segment_override=GS;
cpustate->segment_prefix=1;
break;
case 0x66:
cpustate->operand_size ^= 1;
break;
case 0x67:
cpustate->address_size ^= 1;
break;
default:
prefix_flag=0;
}
} while (prefix_flag);
if( cpustate->segment_prefix ) {
// FIXME: the following does not work if both address override and segment override are used
i386_translate(cpustate, cpustate->segment_override, cpustate->sreg[cpustate->segment_prefix].d ? REG32(ESI) : REG16(SI) );
} else {
//eas =
i386_translate(cpustate, DS, cpustate->address_size ? REG32(ESI) : REG16(SI) );
}
i386_translate(cpustate, ES, cpustate->address_size ? REG32(EDI) : REG16(DI) );
switch(opcode)
{
case 0x6c:
case 0x6d:
/* INSB, INSW, INSD */
// TODO: cycle count
cycle_base = 8;
cycle_adjustment = -4;
flag = NULL;
break;
case 0x6e:
case 0x6f:
/* OUTSB, OUTSW, OUTSD */
// TODO: cycle count
cycle_base = 8;
cycle_adjustment = -4;
flag = NULL;
break;
case 0xa4:
case 0xa5:
/* MOVSB, MOVSW, MOVSD */
cycle_base = 8;
cycle_adjustment = -4;
flag = NULL;
break;
case 0xa6:
case 0xa7:
/* CMPSB, CMPSW, CMPSD */
cycle_base = 5;
cycle_adjustment = -1;
flag = &cpustate->ZF;
break;
case 0xac:
case 0xad:
/* LODSB, LODSW, LODSD */
cycle_base = 5;
cycle_adjustment = 1;
flag = NULL;
break;
case 0xaa:
case 0xab:
/* STOSB, STOSW, STOSD */
cycle_base = 5;
cycle_adjustment = 0;
flag = NULL;
break;
case 0xae:
case 0xaf:
/* SCASB, SCASW, SCASD */
cycle_base = 5;
cycle_adjustment = 0;
flag = &cpustate->ZF;
break;
default:
fatalerror("i386: Invalid REP/opcode %02X combination",opcode);
break;
}
if( cpustate->address_size ) {
if( REG32(ECX) == 0 )
return;
} else {
if( REG16(CX) == 0 )
return;
}
/* now actually perform the repeat */
CYCLES_NUM(cycle_base);
do
{
cpustate->eip = repeated_eip;
cpustate->pc = repeated_pc;
I386OP(decode_opcode)(cpustate);
CYCLES_NUM(cycle_adjustment);
if (cpustate->address_size)
count = --REG32(ECX);
else
count = --REG16(CX);
if (cpustate->cycles <= 0)
goto outofcycles;
}
while( count && (!flag || (invert_flag ? !*flag : *flag)) );
return;
outofcycles:
/* if we run out of cycles to execute, and we are still in the repeat, we need
* to exit this instruction in such a way to go right back into it when we have
* time to execute cycles */
cpustate->eip = cpustate->prev_eip;
CHANGE_PC(cpustate,cpustate->eip);
CYCLES_NUM(-cycle_base);
}
static void I386OP(rep)(i386_state *cpustate) // Opcode 0xf3
{
I386OP(repeat)(cpustate, 0);
}
static void I386OP(repne)(i386_state *cpustate) // Opcode 0xf2
{
I386OP(repeat)(cpustate, 1);
}
static void I386OP(sahf)(i386_state *cpustate) // Opcode 0x9e
{
set_flags(cpustate, (get_flags(cpustate) & 0xffffff00) | (REG8(AH) & 0xd7) );
CYCLES(cpustate,CYCLES_SAHF);
}
static void I386OP(sbb_rm8_r8)(i386_state *cpustate) // Opcode 0x18
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = SBB8(cpustate, dst, src, cpustate->CF);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = SBB8(cpustate, dst, src, cpustate->CF);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
}
static void I386OP(sbb_r8_rm8)(i386_state *cpustate) // Opcode 0x1a
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
dst = SBB8(cpustate, dst, src, cpustate->CF);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
dst = SBB8(cpustate, dst, src, cpustate->CF);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_MEM_REG);
}
}
static void I386OP(sbb_al_i8)(i386_state *cpustate) // Opcode 0x1c
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(AL);
dst = SBB8(cpustate, dst, src, cpustate->CF);
REG8(EAX) = dst;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(scasb)(i386_state *cpustate) // Opcode 0xae
{
UINT32 eas;
UINT8 src, dst;
eas = i386_translate(cpustate, ES, cpustate->address_size ? REG32(EDI) : REG16(DI) );
src = READ8(cpustate,eas);
dst = REG8(AL);
SUB8(cpustate,dst, src);
BUMP_DI(cpustate,1);
CYCLES(cpustate,CYCLES_SCAS);
}
static void I386OP(setalc)(i386_state *cpustate) // Opcode 0xd6 (undocumented)
{
if( cpustate->CF ) {
REG8(AL) = 0xff;
} else {
REG8(AL) = 0;
}
CYCLES(cpustate,3);
}
static void I386OP(seta_rm8)(i386_state *cpustate) // Opcode 0x0f 97
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->CF == 0 && cpustate->ZF == 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setbe_rm8)(i386_state *cpustate) // Opcode 0x0f 96
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->CF != 0 || cpustate->ZF != 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setc_rm8)(i386_state *cpustate) // Opcode 0x0f 92
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->CF != 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setg_rm8)(i386_state *cpustate) // Opcode 0x0f 9f
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->ZF == 0 && (cpustate->SF == cpustate->OF) ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setge_rm8)(i386_state *cpustate) // Opcode 0x0f 9d
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( (cpustate->SF == cpustate->OF) ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setl_rm8)(i386_state *cpustate) // Opcode 0x0f 9c
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->SF != cpustate->OF ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setle_rm8)(i386_state *cpustate) // Opcode 0x0f 9e
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->ZF != 0 || (cpustate->SF != cpustate->OF) ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setnc_rm8)(i386_state *cpustate) // Opcode 0x0f 93
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->CF == 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setno_rm8)(i386_state *cpustate) // Opcode 0x0f 91
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->OF == 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setnp_rm8)(i386_state *cpustate) // Opcode 0x0f 9b
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->PF == 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setns_rm8)(i386_state *cpustate) // Opcode 0x0f 99
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->SF == 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setnz_rm8)(i386_state *cpustate) // Opcode 0x0f 95
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->ZF == 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(seto_rm8)(i386_state *cpustate) // Opcode 0x0f 90
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->OF != 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setp_rm8)(i386_state *cpustate) // Opcode 0x0f 9a
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->PF != 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(sets_rm8)(i386_state *cpustate) // Opcode 0x0f 98
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->SF != 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(setz_rm8)(i386_state *cpustate) // Opcode 0x0f 94
{
UINT8 modrm = FETCH(cpustate);
UINT8 value = 0;
if( cpustate->ZF != 0 ) {
value = 1;
}
if( modrm >= 0xc0 ) {
STORE_RM8(modrm, value);
CYCLES(cpustate,CYCLES_SETCC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
WRITE8(cpustate,ea, value);
CYCLES(cpustate,CYCLES_SETCC_MEM);
}
}
static void I386OP(stc)(i386_state *cpustate) // Opcode 0xf9
{
cpustate->CF = 1;
CYCLES(cpustate,CYCLES_STC);
}
static void I386OP(std)(i386_state *cpustate) // Opcode 0xfd
{
cpustate->DF = 1;
CYCLES(cpustate,CYCLES_STD);
}
static void I386OP(sti)(i386_state *cpustate) // Opcode 0xfb
{
cpustate->IF = 1;
CYCLES(cpustate,CYCLES_STI);
}
static void I386OP(stosb)(i386_state *cpustate) // Opcode 0xaa
{
UINT32 ead;
ead = i386_translate(cpustate, ES, cpustate->address_size ? REG32(EDI) : REG16(DI) );
WRITE8(cpustate,ead, REG8(AL));
BUMP_DI(cpustate,1);
CYCLES(cpustate,CYCLES_STOS);
}
static void I386OP(sub_rm8_r8)(i386_state *cpustate) // Opcode 0x28
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = SUB8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = SUB8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
}
static void I386OP(sub_r8_rm8)(i386_state *cpustate) // Opcode 0x2a
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
dst = SUB8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
dst = SUB8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_MEM_REG);
}
}
static void I386OP(sub_al_i8)(i386_state *cpustate) // Opcode 0x2c
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(EAX);
dst = SUB8(cpustate,dst, src);
REG8(EAX) = dst;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(test_al_i8)(i386_state *cpustate) // Opcode 0xa8
{
UINT8 src = FETCH(cpustate);
UINT8 dst = REG8(AL);
dst = src & dst;
SetSZPF8(dst);
cpustate->CF = 0;
cpustate->OF = 0;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(test_rm8_r8)(i386_state *cpustate) // Opcode 0x84
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = src & dst;
SetSZPF8(dst);
cpustate->CF = 0;
cpustate->OF = 0;
CYCLES(cpustate,CYCLES_TEST_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = src & dst;
SetSZPF8(dst);
cpustate->CF = 0;
cpustate->OF = 0;
CYCLES(cpustate,CYCLES_TEST_REG_MEM);
}
}
static void I386OP(xchg_r8_rm8)(i386_state *cpustate) // Opcode 0x86
{
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
UINT8 src = LOAD_RM8(modrm);
UINT8 dst = LOAD_REG8(modrm);
STORE_REG8(modrm, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_XCHG_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
UINT8 src = READ8(cpustate,ea);
UINT8 dst = LOAD_REG8(modrm);
STORE_REG8(modrm, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_XCHG_REG_MEM);
}
}
static void I386OP(xor_rm8_r8)(i386_state *cpustate) // Opcode 0x30
{
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_REG8(modrm);
dst = LOAD_RM8(modrm);
dst = XOR8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = LOAD_REG8(modrm);
dst = READ8(cpustate,ea);
dst = XOR8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
}
static void I386OP(xor_r8_rm8)(i386_state *cpustate) // Opcode 0x32
{
UINT32 src, dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
dst = LOAD_REG8(modrm);
dst = XOR8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
dst = LOAD_REG8(modrm);
dst = XOR8(cpustate,dst, src);
STORE_REG8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_MEM_REG);
}
}
static void I386OP(xor_al_i8)(i386_state *cpustate) // Opcode 0x34
{
UINT8 src, dst;
src = FETCH(cpustate);
dst = REG8(AL);
dst = XOR8(cpustate,dst, src);
REG8(AL) = dst;
CYCLES(cpustate,CYCLES_ALU_IMM_ACC);
}
static void I386OP(group80_8)(i386_state *cpustate) // Opcode 0x80
{
UINT32 ea;
UINT8 src, dst;
UINT8 modrm = FETCH(cpustate);
switch( (modrm >> 3) & 0x7 )
{
case 0: // ADD Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
dst = ADD8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
dst = ADD8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
break;
case 1: // OR Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
dst = OR8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
dst = OR8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
break;
case 2: // ADC Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
dst = ADC8(cpustate, dst, src, cpustate->CF);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
dst = ADC8(cpustate, dst, src, cpustate->CF);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
break;
case 3: // SBB Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
dst = SBB8(cpustate, dst, src, cpustate->CF);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
dst = SBB8(cpustate, dst, src, cpustate->CF);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
break;
case 4: // AND Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
dst = AND8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
dst = AND8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
break;
case 5: // SUB Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
dst = SUB8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
dst = SUB8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
break;
case 6: // XOR Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
dst = XOR8(cpustate,dst, src);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_ALU_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
dst = XOR8(cpustate,dst, src);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_ALU_REG_MEM);
}
break;
case 7: // CMP Rm8, i8
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
src = FETCH(cpustate);
SUB8(cpustate,dst, src);
CYCLES(cpustate,CYCLES_CMP_REG_REG);
} else {
ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
src = FETCH(cpustate);
SUB8(cpustate,dst, src);
CYCLES(cpustate,CYCLES_CMP_REG_MEM);
}
break;
}
}
static void I386OP(groupC0_8)(i386_state *cpustate) // Opcode 0xc0
{
UINT8 dst;
UINT8 modrm = FETCH(cpustate);
UINT8 shift;
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
shift = FETCH(cpustate) & 0x1f;
dst = i386_shift_rotate8(cpustate, modrm, dst, shift);
STORE_RM8(modrm, dst);
} else {
UINT32 ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
shift = FETCH(cpustate) & 0x1f;
dst = i386_shift_rotate8(cpustate, modrm, dst, shift);
WRITE8(cpustate,ea, dst);
}
}
static void I386OP(groupD0_8)(i386_state *cpustate) // Opcode 0xd0
{
UINT8 dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
dst = i386_shift_rotate8(cpustate, modrm, dst, 1);
STORE_RM8(modrm, dst);
} else {
UINT32 ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
dst = i386_shift_rotate8(cpustate, modrm, dst, 1);
WRITE8(cpustate,ea, dst);
}
}
static void I386OP(groupD2_8)(i386_state *cpustate) // Opcode 0xd2
{
UINT8 dst;
UINT8 modrm = FETCH(cpustate);
if( modrm >= 0xc0 ) {
dst = LOAD_RM8(modrm);
dst = i386_shift_rotate8(cpustate, modrm, dst, REG8(CL));
STORE_RM8(modrm, dst);
} else {
UINT32 ea = GetEA(cpustate,modrm);
dst = READ8(cpustate,ea);
dst = i386_shift_rotate8(cpustate, modrm, dst, REG8(CL));
WRITE8(cpustate,ea, dst);
}
}
static void I386OP(groupF6_8)(i386_state *cpustate) // Opcode 0xf6
{
UINT8 modrm = FETCH(cpustate);
switch( (modrm >> 3) & 0x7 )
{
case 0: /* TEST Rm8, i8 */
if( modrm >= 0xc0 ) {
UINT8 dst = LOAD_RM8(modrm);
UINT8 src = FETCH(cpustate);
dst &= src;
cpustate->CF = cpustate->OF = cpustate->AF = 0;
SetSZPF8(dst);
CYCLES(cpustate,CYCLES_TEST_IMM_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
UINT8 dst = READ8(cpustate,ea);
UINT8 src = FETCH(cpustate);
dst &= src;
cpustate->CF = cpustate->OF = cpustate->AF = 0;
SetSZPF8(dst);
CYCLES(cpustate,CYCLES_TEST_IMM_MEM);
}
break;
case 2: /* NOT Rm8 */
if( modrm >= 0xc0 ) {
UINT8 dst = LOAD_RM8(modrm);
dst = ~dst;
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_NOT_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
UINT8 dst = READ8(cpustate,ea);
dst = ~dst;
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_NOT_MEM);
}
break;
case 3: /* NEG Rm8 */
if( modrm >= 0xc0 ) {
UINT8 dst = LOAD_RM8(modrm);
dst = SUB8(cpustate, 0, dst );
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_NEG_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
UINT8 dst = READ8(cpustate,ea);
dst = SUB8(cpustate, 0, dst );
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_NEG_MEM);
}
break;
case 4: /* MUL AL, Rm8 */
{
UINT16 result;
UINT8 src, dst;
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
CYCLES(cpustate,CYCLES_MUL8_ACC_REG); /* TODO: Correct multiply timing */
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
CYCLES(cpustate,CYCLES_MUL8_ACC_MEM); /* TODO: Correct multiply timing */
}
dst = REG8(AL);
result = (UINT16)src * (UINT16)dst;
REG16(AX) = (UINT16)result;
cpustate->CF = cpustate->OF = (REG16(AX) > 0xff);
}
break;
case 5: /* IMUL AL, Rm8 */
{
INT16 result;
INT16 src, dst;
if( modrm >= 0xc0 ) {
src = (INT16)(INT8)LOAD_RM8(modrm);
CYCLES(cpustate,CYCLES_IMUL8_ACC_REG); /* TODO: Correct multiply timing */
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = (INT16)(INT8)READ8(cpustate,ea);
CYCLES(cpustate,CYCLES_IMUL8_ACC_MEM); /* TODO: Correct multiply timing */
}
dst = (INT16)(INT8)REG8(AL);
result = src * dst;
REG16(AX) = (UINT16)result;
cpustate->CF = cpustate->OF = !(result == (INT16)(INT8)result);
}
break;
case 6: /* DIV AL, Rm8 */
{
UINT16 quotient, remainder, result;
UINT8 src;
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
CYCLES(cpustate,CYCLES_DIV8_ACC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
CYCLES(cpustate,CYCLES_DIV8_ACC_MEM);
}
quotient = (UINT16)REG16(AX);
if( src ) {
remainder = quotient % (UINT16)src;
result = quotient / (UINT16)src;
if( result > 0xff ) {
/* TODO: Divide error */
} else {
REG8(AH) = (UINT8)remainder & 0xff;
REG8(AL) = (UINT8)result & 0xff;
// this flag is actually undefined, enable on non-cyrix
if (cpustate->cpuid_id0 != 0x69727943)
cpustate->CF = 1;
}
} else {
/* TODO: Divide by zero */
}
}
break;
case 7: /* IDIV AL, Rm8 */
{
INT16 quotient, remainder, result;
UINT8 src;
if( modrm >= 0xc0 ) {
src = LOAD_RM8(modrm);
CYCLES(cpustate,CYCLES_IDIV8_ACC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
src = READ8(cpustate,ea);
CYCLES(cpustate,CYCLES_IDIV8_ACC_MEM);
}
quotient = (INT16)REG16(AX);
if( src ) {
remainder = quotient % (INT16)(INT8)src;
result = quotient / (INT16)(INT8)src;
if( result > 0xff ) {
/* TODO: Divide error */
} else {
REG8(AH) = (UINT8)remainder & 0xff;
REG8(AL) = (UINT8)result & 0xff;
// this flag is actually undefined, enable on non-cyrix
if (cpustate->cpuid_id0 != 0x69727943)
cpustate->CF = 1;
}
} else {
/* TODO: Divide by zero */
}
}
break;
}
}
static void I386OP(groupFE_8)(i386_state *cpustate) // Opcode 0xfe
{
UINT8 modrm = FETCH(cpustate);
switch( (modrm >> 3) & 0x7 )
{
case 0: /* INC Rm8 */
if( modrm >= 0xc0 ) {
UINT8 dst = LOAD_RM8(modrm);
dst = INC8(cpustate,dst);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_INC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
UINT8 dst = READ8(cpustate,ea);
dst = INC8(cpustate,dst);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_INC_MEM);
}
break;
case 1: /* DEC Rm8 */
if( modrm >= 0xc0 ) {
UINT8 dst = LOAD_RM8(modrm);
dst = DEC8(cpustate,dst);
STORE_RM8(modrm, dst);
CYCLES(cpustate,CYCLES_DEC_REG);
} else {
UINT32 ea = GetEA(cpustate,modrm);
UINT8 dst = READ8(cpustate,ea);
dst = DEC8(cpustate,dst);
WRITE8(cpustate,ea, dst);
CYCLES(cpustate,CYCLES_DEC_MEM);
}
break;
case 6: /* PUSH Rm8 */
{
UINT8 value;
if( modrm >= 0xc0 ) {
value = LOAD_RM8(modrm);
} else {
UINT32 ea = GetEA(cpustate,modrm);
value = READ8(cpustate,ea);
}
if( cpustate->operand_size ) {
PUSH32(cpustate,value);
} else {
PUSH16(cpustate,value);
}
CYCLES(cpustate,CYCLES_PUSH_RM);
}
break;
default:
fatalerror("i386: groupFE_8 /%d unimplemented", (modrm >> 3) & 0x7);
break;
}
}
static void I386OP(segment_CS)(i386_state *cpustate) // Opcode 0x2e
{
cpustate->segment_prefix = 1;
cpustate->segment_override = CS;
I386OP(decode_opcode)(cpustate);
}
static void I386OP(segment_DS)(i386_state *cpustate) // Opcode 0x3e
{
cpustate->segment_prefix = 1;
cpustate->segment_override = DS;
CYCLES(cpustate,0); // TODO: Specify cycle count
I386OP(decode_opcode)(cpustate);
}
static void I386OP(segment_ES)(i386_state *cpustate) // Opcode 0x26
{
cpustate->segment_prefix = 1;
cpustate->segment_override = ES;
CYCLES(cpustate,0); // TODO: Specify cycle count
I386OP(decode_opcode)(cpustate);
}
static void I386OP(segment_FS)(i386_state *cpustate) // Opcode 0x64
{
cpustate->segment_prefix = 1;
cpustate->segment_override = FS;
CYCLES(cpustate,1); // TODO: Specify cycle count
I386OP(decode_opcode)(cpustate);
}
static void I386OP(segment_GS)(i386_state *cpustate) // Opcode 0x65
{
cpustate->segment_prefix = 1;
cpustate->segment_override = GS;
CYCLES(cpustate,1); // TODO: Specify cycle count
I386OP(decode_opcode)(cpustate);
}
static void I386OP(segment_SS)(i386_state *cpustate) // Opcode 0x36
{
cpustate->segment_prefix = 1;
cpustate->segment_override = SS;
CYCLES(cpustate,0); // TODO: Specify cycle count
I386OP(decode_opcode)(cpustate);
}
static void I386OP(operand_size)(i386_state *cpustate) // Opcode 0x66
{
cpustate->operand_size ^= 1;
I386OP(decode_opcode)(cpustate);
}
static void I386OP(address_size)(i386_state *cpustate) // Opcode 0x67
{
cpustate->address_size ^= 1;
I386OP(decode_opcode)(cpustate);
}
static void I386OP(nop)(i386_state *cpustate) // Opcode 0x90
{
CYCLES(cpustate,CYCLES_NOP);
}
static void I386OP(int3)(i386_state *cpustate) // Opcode 0xcc
{
CYCLES(cpustate,CYCLES_INT3);
i386_trap(cpustate,3, 1, 0);
}
static void I386OP(int)(i386_state *cpustate) // Opcode 0xcd
{
int interrupt = FETCH(cpustate);
CYCLES(cpustate,CYCLES_INT);
i386_trap(cpustate,interrupt, 1, 0);
}
static void I386OP(into)(i386_state *cpustate) // Opcode 0xce
{
if( cpustate->OF ) {
i386_trap(cpustate,4, 1, 0);
CYCLES(cpustate,CYCLES_INTO_OF1);
}
else
{
CYCLES(cpustate,CYCLES_INTO_OF0);
}
}
static UINT32 i386_escape_ea; // hack around GCC 4.6 error because we need the side effects of GetEA()
static void I386OP(escape)(i386_state *cpustate) // Opcodes 0xd8 - 0xdf
{
UINT8 modrm = FETCH(cpustate);
if(modrm < 0xc0)
{
i386_escape_ea = GetEA(cpustate,modrm);
}
CYCLES(cpustate,3); // TODO: confirm this
(void) LOAD_RM8(modrm);
}
static void I386OP(hlt)(i386_state *cpustate) // Opcode 0xf4
{
// TODO: We need to raise an exception in protected mode and when
// the current privilege level is not zero
cpustate->halted = 1;
CYCLES(cpustate,CYCLES_HLT);
if (cpustate->cycles > 0)
cpustate->cycles = 0;
}
static void I386OP(decimal_adjust)(i386_state *cpustate, int direction)
{
UINT8 tmpAL = REG8(AL);
UINT8 tmpCF = cpustate->CF;
if (cpustate->AF || ((REG8(AL) & 0xf) > 9))
{
UINT16 t= (UINT16)REG8(AL) + (direction * 0x06);
REG8(AL) = (UINT8)t&0xff;
cpustate->AF = 1;
if (t & 0x100)
cpustate->CF = 1;
if (direction > 0)
tmpAL = REG8(AL);
}
if (tmpCF || (tmpAL > 0x99))
{
REG8(AL) += (direction * 0x60);
cpustate->CF = 1;
}
SetSZPF8(REG8(AL));
}
static void I386OP(daa)(i386_state *cpustate) // Opcode 0x27
{
I386OP(decimal_adjust)(cpustate, +1);
CYCLES(cpustate,CYCLES_DAA);
}
static void I386OP(das)(i386_state *cpustate) // Opcode 0x2f
{
I386OP(decimal_adjust)(cpustate, -1);
CYCLES(cpustate,CYCLES_DAS);
}
static void I386OP(aaa)(i386_state *cpustate) // Opcode 0x37
{
if( ( (REG8(AL) & 0x0f) > 9) || (cpustate->AF != 0) ) {
REG16(AX) = REG16(AX) + 6;
REG8(AH) = REG8(AH) + 1;
cpustate->AF = 1;
cpustate->CF = 1;
} else {
cpustate->AF = 0;
cpustate->CF = 0;
}
REG8(AL) = REG8(AL) & 0x0f;
CYCLES(cpustate,CYCLES_AAA);
}
static void I386OP(aas)(i386_state *cpustate) // Opcode 0x3f
{
if (cpustate->AF || ((REG8(AL) & 0xf) > 9))
{
REG16(AX) -= 6;
REG8(AH) -= 1;
cpustate->AF = 1;
cpustate->CF = 1;
}
else
{
cpustate->AF = 0;
cpustate->CF = 0;
}
REG8(AL) &= 0x0f;
CYCLES(cpustate,CYCLES_AAS);
}
static void I386OP(aad)(i386_state *cpustate) // Opcode 0xd5
{
UINT8 tempAL = REG8(AL);
UINT8 tempAH = REG8(AH);
UINT8 i = FETCH(cpustate);
REG8(AL) = (tempAL + (tempAH * i)) & 0xff;
REG8(AH) = 0;
SetSZPF8( REG8(AL) );
CYCLES(cpustate,CYCLES_AAD);
}
static void I386OP(aam)(i386_state *cpustate) // Opcode 0xd4
{
UINT8 tempAL = REG8(AL);
UINT8 i = FETCH(cpustate);
REG8(AH) = tempAL / i;
REG8(AL) = tempAL % i;
SetSZPF8( REG8(AL) );
CYCLES(cpustate,CYCLES_AAM);
}
static void I386OP(clts)(i386_state *cpustate) // Opcode 0x0f 0x06
{
// TODO: #GP(0) is executed
cpustate->cr[0] &= ~0x08; /* clear TS bit */
CYCLES(cpustate,CYCLES_CLTS);
}
static void I386OP(wait)(i386_state *cpustate) // Opcode 0x9B
{
// TODO
}
static void I386OP(lock)(i386_state *cpustate) // Opcode 0xf0
{
CYCLES(cpustate,CYCLES_LOCK); // TODO: Determine correct cycle count
I386OP(decode_opcode)(cpustate);
}
static void I386OP(mov_r32_tr)(i386_state *cpustate) // Opcode 0x0f 24
{
FETCH(cpustate);
CYCLES(cpustate,1); // TODO: correct cycle count
}
static void I386OP(mov_tr_r32)(i386_state *cpustate) // Opcode 0x0f 26
{
FETCH(cpustate);
CYCLES(cpustate,1); // TODO: correct cycle count
}
static void I386OP(unimplemented)(i386_state *cpustate)
{
fatalerror("i386: Unimplemented opcode %02X at %08X", cpustate->opcode, cpustate->pc - 1 );
}
static void I386OP(invalid)(i386_state *cpustate)
{
logerror("i386: Invalid opcode %02X at %08X\n", cpustate->opcode, cpustate->pc - 1);
i386_trap(cpustate, 6, 0, 0);
}
| 2.15625 | 2 |
2024-11-18T22:25:11.888741+00:00 | 2018-07-10T22:21:36 | b47554b68ab04a32bb818444ebe7089a4388cdae | {
"blob_id": "b47554b68ab04a32bb818444ebe7089a4388cdae",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-10T22:21:36",
"content_id": "d793977f0beb78fef0225ae81723b8ceb15cd5e1",
"detected_licenses": [
"MIT"
],
"directory_id": "c52fe0ec977a650aa80afbccc58bd5674d7e5d70",
"extension": "c",
"filename": "dgs_gauss_mp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 114688036,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19680,
"license": "MIT",
"license_type": "permissive",
"path": "/My Implementations/Key Exchanges in C/src/dgs_gauss_mp.c",
"provenance": "stackv2-0115.json.gz:111618",
"repo_name": "Afraz496/fypafraz",
"revision_date": "2018-07-10T22:21:36",
"revision_id": "e2b5c6d1797ccf7a4882003306507ca00e648ea8",
"snapshot_id": "adc9e00aec9abf8842515e14934c9b53c10c6be8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Afraz496/fypafraz/e2b5c6d1797ccf7a4882003306507ca00e648ea8/My Implementations/Key Exchanges in C/src/dgs_gauss_mp.c",
"visit_date": "2023-03-09T16:46:59.234570"
} | stackv2 | /******************************************************************************
*
* DGS - Discrete Gaussian Samplers
*
* Copyright (c) 2014, Martin Albrecht <martinralbrecht+dgs@googlemail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
******************************************************************************/
#include "dgs.h"
#include <assert.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
/** SIGMA2 **/
static void sigma2_init(mpfr_t sigma2, int prec) {
mpfr_init2(sigma2, prec);
mpfr_set_ui(sigma2, 2, MPFR_RNDN); // 2
mpfr_log(sigma2, sigma2, MPFR_RNDN); //log₂ 2
mpfr_mul_ui(sigma2, sigma2, 2, MPFR_RNDN); //2·log₂ 2
mpfr_ui_div(sigma2, 1, sigma2, MPFR_RNDN); //1/(2·log₂ 2)
mpfr_sqrt(sigma2, sigma2, MPFR_RNDN); //σ₂ = sqrt(1/(2·log₂ 2))
}
static inline void _dgs_disc_gauss_mp_init_rho(dgs_disc_gauss_mp_t *self, const mpfr_prec_t prec) {
self->rho = (mpfr_t*)malloc(sizeof(mpfr_t)*mpz_get_ui(self->two_upper_bound_minus_one));
if (!self->rho){
dgs_disc_gauss_mp_clear(self);
dgs_die("out of memory");
}
mpfr_t x_;
mpfr_init2(x_, prec);
long absmax = mpz_get_ui(self->upper_bound) - 1;
for(long x=-absmax; x<=absmax; x++) {
mpfr_set_si(x_, x, MPFR_RNDN);
mpfr_sub(x_, x_, self->c_r, MPFR_RNDN);
mpfr_sqr(x_, x_, MPFR_RNDN);
mpfr_mul(x_, x_, self->f, MPFR_RNDN);
mpfr_exp(x_, x_, MPFR_RNDN);
mpfr_init2(self->rho[x+absmax], prec);
mpfr_set(self->rho[x+absmax], x_, MPFR_RNDN);
}
mpfr_clear(x_);
}
static inline long _dgs_disc_gauss_mp_min_in_rho(dgs_disc_gauss_mp_t *self, long range) {
long mi = 0;
mpfr_t* m = &(self->rho[mi]);
for (long x = 1; x < range;++x) {
if (mpfr_cmp(self->rho[x], *m) < 0) {
mi = x;
m = &(self->rho[mi]);
}
}
return mi;
}
static inline long _dgs_disc_gauss_mp_max_in_rho(dgs_disc_gauss_mp_t *self, long range) {
long mi = 0;
mpfr_t* m = &(self->rho[mi]);
for (long x = 1; x < range;++x) {
if (mpfr_cmp(self->rho[x], *m) > 0) {
mi = x;
m = &(self->rho[mi]);
}
}
return mi;
}
dgs_disc_gauss_sigma2p_t *dgs_disc_gauss_sigma2p_init() {
dgs_disc_gauss_sigma2p_t *self = (dgs_disc_gauss_sigma2p_t*)calloc(sizeof(dgs_disc_gauss_sigma2p_t),1);
if (!self) dgs_die("out of memory");
self->B = dgs_bern_uniform_init(0);
return self;
}
void dgs_disc_gauss_sigma2p_mp_call(mpz_t rop, dgs_disc_gauss_sigma2p_t *self, gmp_randstate_t state) {
while(1) {
if (!dgs_bern_uniform_call(self->B, state)) {
mpz_set_ui(rop, 0);
return;
}
int dobreak = 0;
for(unsigned long i=1; ;i++) {
for(size_t j=0; j<2*i-2; j++) {
if(dgs_bern_uniform_call(self->B, state)) {
dobreak = 1;
break;
}
}
if (__DGS_LIKELY(dobreak))
break;
if (!dgs_bern_uniform_call(self->B, state)) {
mpz_set_ui(rop, i);
return;
}
}
}
}
long dgs_disc_gauss_sigma2p_dp_call(dgs_disc_gauss_sigma2p_t *self) {
while(1) {
if (!dgs_bern_uniform_call_libc(self->B)) {
return 0;
}
int dobreak = 0;
for(unsigned long i=1; ;i++) {
for(size_t j=0; j<2*i-2; j++) {
if(dgs_bern_uniform_call_libc(self->B)) {
dobreak = 1;
break;
}
}
if (__DGS_LIKELY(dobreak))
break;
if (!dgs_bern_uniform_call_libc(self->B)) {
return i;
}
}
}
}
void dgs_disc_gauss_sigma2p_clear(dgs_disc_gauss_sigma2p_t *self) {
assert(self != NULL);
if (self->B) dgs_bern_uniform_clear(self->B);
free(self);
}
/** GENERAL SIGMA :: INIT **/
static inline void _dgs_disc_gauss_mp_init_f(mpfr_t f, const mpfr_t sigma) {
mpfr_init2(f, mpfr_get_prec(sigma));
mpfr_set(f, sigma, MPFR_RNDN);
mpfr_sqr(f, f, MPFR_RNDN); // f = σ²
mpfr_mul_ui(f, f, 2, MPFR_RNDN); // f = 2 σ²
mpfr_ui_div(f, 1, f, MPFR_RNDN); // f = 1/(2 σ²)
mpfr_neg(f, f, MPFR_RNDN); // f = -1/(2 σ²)
}
static inline void _dgs_disc_gauss_mp_init_upper_bound(mpz_t upper_bound,
mpz_t upper_bound_minus_one,
mpz_t two_upper_bound_minus_one,
mpfr_t sigma, size_t tailcut) {
mpfr_t tmp;
mpfr_init2(tmp, mpfr_get_prec(sigma));
mpz_init(upper_bound);
mpz_init(upper_bound_minus_one);
mpz_init(two_upper_bound_minus_one);
mpfr_mul_ui(tmp, sigma, tailcut, MPFR_RNDN); // tmp = σ·τ
mpfr_add_ui(tmp, tmp, 1, MPFR_RNDN); // tmp = σ·τ + 1
mpfr_get_z(upper_bound, tmp, MPFR_RNDU); // upper_bound = ⌈σ·τ + 1⌉
mpz_sub_ui(upper_bound_minus_one, upper_bound, 1); // upper_bound - 1 = ⌈σ·τ⌉
mpz_mul_ui(two_upper_bound_minus_one, upper_bound, 2);
mpz_sub_ui(two_upper_bound_minus_one, two_upper_bound_minus_one, 1); // 2·upper_bound - 1
mpfr_clear(tmp);
}
static inline void _dgs_disc_gauss_mp_init_bexp(dgs_disc_gauss_mp_t *self, mpfr_t sigma, mpz_t upper_bound) {
mpfr_init2(self->f, mpfr_get_prec(sigma));
mpfr_set(self->f, sigma, MPFR_RNDN); // f = σ
mpfr_sqr(self->f, self->f, MPFR_RNDN); // f = σ²
mpfr_mul_ui(self->f, self->f, 2, MPFR_RNDN); // f = 2 σ²
size_t l = 2*mpz_sizeinbase(upper_bound, 2);
self->Bexp = dgs_bern_exp_mp_init(self->f, l);
}
dgs_disc_gauss_mp_t *dgs_disc_gauss_mp_init(const mpfr_t sigma, const mpfr_t c, size_t tau, dgs_disc_gauss_alg_t algorithm) {
if (mpfr_cmp_ui(sigma,0)<= 0)
dgs_die("sigma must be > 0");
if (tau == 0)
dgs_die("tau must be > 0");
mpfr_prec_t prec = mpfr_get_prec(sigma);
if (mpfr_get_prec(c) > prec)
prec = mpfr_get_prec(c);
dgs_disc_gauss_mp_t *self = (dgs_disc_gauss_mp_t*)calloc(sizeof(dgs_disc_gauss_mp_t),1);
if (!self) dgs_die("out of memory");
mpz_init(self->x);
mpz_init(self->x2);
mpz_init(self->k);
mpfr_init2(self->y, prec);
mpfr_init2(self->z, prec);
mpfr_init2(self->sigma, prec);
mpfr_set(self->sigma, sigma, MPFR_RNDN);
mpfr_init2(self->c, prec);
mpfr_set(self->c, c, MPFR_RNDN);
mpz_init(self->c_z);
mpfr_get_z(self->c_z, c, MPFR_RNDN);
mpfr_init2(self->c_r, prec);
mpfr_sub_z(self->c_r, self->c, self->c_z, MPFR_RNDN);
self->tau = tau;
if (algorithm == DGS_DISC_GAUSS_DEFAULT) {
mpfr_t k; mpfr_init(k);
mpfr_t sigma2; sigma2_init(sigma2, prec);
mpfr_div(k, self->sigma, sigma2, MPFR_RNDN);
double k_ = mpfr_get_d(k, MPFR_RNDN);
mpfr_clear(sigma2);
mpfr_clear(k);
double sigma_ = mpfr_get_d(self->sigma, MPFR_RNDN);
/* 1. try the uniform algorithm */
if (2*ceil(sigma_*self->tau) * sizeof(double) <= DGS_DISC_GAUSS_MAX_TABLE_SIZE_BYTES) {
algorithm = DGS_DISC_GAUSS_UNIFORM_TABLE;
/* 2. see if sigma2 is close enough */
} else if(abs(round(k_)-k_) < DGS_DISC_GAUSS_EQUAL_DIFF) {
algorithm = DGS_DISC_GAUSS_SIGMA2_LOGTABLE;
/* 3. do logtables */
} else {
algorithm = DGS_DISC_GAUSS_UNIFORM_LOGTABLE;
}
}
self->algorithm = algorithm;
switch(algorithm) {
case DGS_DISC_GAUSS_UNIFORM_ONLINE: {
_dgs_disc_gauss_mp_init_upper_bound(self->upper_bound,
self->upper_bound_minus_one,
self->two_upper_bound_minus_one,
self->sigma, self->tau);
self->call = dgs_disc_gauss_mp_call_uniform_online;
_dgs_disc_gauss_mp_init_f(self->f, self->sigma);
break;
}
case DGS_DISC_GAUSS_UNIFORM_TABLE: {
_dgs_disc_gauss_mp_init_upper_bound(self->upper_bound,
self->upper_bound_minus_one,
self->two_upper_bound_minus_one,
self->sigma, self->tau);
self->B = dgs_bern_uniform_init(0);
_dgs_disc_gauss_mp_init_f(self->f, sigma);
if (mpfr_zero_p(self->c_r)) { /* c is an integer */
self->call = dgs_disc_gauss_mp_call_uniform_table;
if (mpz_cmp_ui(self->upper_bound, ULONG_MAX/sizeof(mpfr_t))>0){
dgs_disc_gauss_mp_clear(self);
dgs_die("integer overflow");
}
self->rho = (mpfr_t*)malloc(sizeof(mpfr_t)*mpz_get_ui(self->upper_bound));
if (!self->rho){
dgs_disc_gauss_mp_clear(self);
dgs_die("out of memory");
}
mpfr_t x_;
mpfr_init2(x_, prec);
for(unsigned long x=0; x<mpz_get_ui(self->upper_bound); x++) {
mpfr_set_ui(x_, x, MPFR_RNDN);
mpfr_sqr(x_, x_, MPFR_RNDN);
mpfr_mul(x_, x_, self->f, MPFR_RNDN);
mpfr_exp(x_, x_, MPFR_RNDN);
mpfr_init2(self->rho[x], prec);
mpfr_set(self->rho[x], x_, MPFR_RNDN);
}
mpfr_div_ui(self->rho[0],self->rho[0], 2, MPFR_RNDN);
mpfr_clear(x_);
} else { /* c is not an integer, we need a bigger table as our nice symmetry is lost */
self->call = dgs_disc_gauss_mp_call_uniform_table_offset;
if (mpz_cmp_ui(self->two_upper_bound_minus_one, ULONG_MAX/sizeof(mpfr_t)) > 0){
dgs_disc_gauss_mp_clear(self);
dgs_die("integer overflow");
}
// we need a bigger table
_dgs_disc_gauss_mp_init_rho(self, prec);
}
break;
}
case DGS_DISC_GAUSS_UNIFORM_LOGTABLE: {
self->call = dgs_disc_gauss_mp_call_uniform_logtable;
_dgs_disc_gauss_mp_init_upper_bound(self->upper_bound,
self->upper_bound_minus_one,
self->two_upper_bound_minus_one,
self->sigma, self->tau);
if (!mpfr_zero_p(self->c_r)) {
dgs_disc_gauss_mp_clear(self);
dgs_die("algorithm DGS_DISC_GAUSS_UNIFORM_LOGTABLE requires c%1 == 0");
}
_dgs_disc_gauss_mp_init_bexp(self, self->sigma, self->upper_bound);
break;
}
case DGS_DISC_GAUSS_SIGMA2_LOGTABLE: {
self->call = dgs_disc_gauss_mp_call_sigma2_logtable;
if (!mpfr_zero_p(self->c_r)) {
dgs_disc_gauss_mp_clear(self);
dgs_die("algorithm DGS_DISC_GAUSS_SIGMA2_LOGTABLE requires c%1 == 0");
}
mpfr_t k;
mpfr_init2(k, prec);
mpfr_t sigma2;
sigma2_init(sigma2, prec);
mpfr_div(k, sigma, sigma2, MPFR_RNDN);
mpfr_get_z(self->k, k, MPFR_RNDN);
mpfr_mul_z(self->sigma, sigma2, self->k, MPFR_RNDN); //k·σ₂
mpfr_clear(sigma2);
mpfr_clear(k);
_dgs_disc_gauss_mp_init_upper_bound(self->upper_bound,
self->upper_bound_minus_one,
self->two_upper_bound_minus_one,
self->sigma, self->tau);
_dgs_disc_gauss_mp_init_bexp(self, self->sigma, self->upper_bound);
self->B = dgs_bern_uniform_init(0);
self->D2 = dgs_disc_gauss_sigma2p_init();
break;
}
case DGS_DISC_GAUSS_ALIAS: {
_dgs_disc_gauss_mp_init_upper_bound(self->upper_bound,
self->upper_bound_minus_one,
self->two_upper_bound_minus_one,
self->sigma, self->tau);
_dgs_disc_gauss_mp_init_f(self->f, sigma);
self->call = dgs_disc_gauss_mp_call_alias;
if (mpz_cmp_ui(self->two_upper_bound_minus_one, ULONG_MAX/sizeof(mpfr_t)) > 0){
dgs_disc_gauss_mp_clear(self);
dgs_die("integer overflow");
}
// we'll use the big table
_dgs_disc_gauss_mp_init_rho(self, prec);
// convert rho to probabilities
mpfr_set_d(self->y, 0.0, MPFR_RNDN);
mpfr_set_d(self->z, 1.0, MPFR_RNDN);
long range = mpz_get_ui(self->two_upper_bound_minus_one);
for(long x=0; x<range; x++) {
mpfr_add(self->y, self->y,self->rho[x], MPFR_RNDN);
}
mpfr_div(self->y, self->z, self->y, MPFR_RNDN);
for(long x=0; x<range; x++) {
mpfr_mul(self->rho[x], self->rho[x], self->y, MPFR_RNDN);
}
// compute bias and alias
self->alias = (mpz_t*)calloc(range, sizeof(mpz_t));
if (!self->alias){
dgs_disc_gauss_mp_clear(self);
dgs_die("out of memory");
}
self->bias = (dgs_bern_mp_t**)calloc(range, sizeof(dgs_bern_mp_t*));
if (!self->bias){
dgs_disc_gauss_mp_clear(self);
dgs_die("out of memory");
}
//~ // simple robin hood strategy approximates good alias
//~ // this precomputation takes ~n^2, but could be reduced by
//~ // using better data structures to compute min and max
//~ // (instead of just linear search each time)
mpfr_set_d(self->y, (double)range, MPFR_RNDN);
mpfr_div(self->y, self->z, self->y, MPFR_RNDD); // self->y = avg
long low = _dgs_disc_gauss_mp_min_in_rho(self, range);
long high;
mpfr_sub(self->z, self->y, self->rho[low], MPFR_RNDD); // z = avg - rho[low]
mpfr_t p;
mpfr_init2(p, prec);
while(mpfr_cmp_d(self->z,0) > 0) {
high = _dgs_disc_gauss_mp_max_in_rho(self, range);
mpfr_mul_z(p, self->rho[low], self->two_upper_bound_minus_one, MPFR_RNDN);
self->bias[low] = dgs_bern_mp_init(p);
mpz_init(self->alias[low]);
mpz_set_ui(self->alias[low], high);
mpfr_sub(self->rho[high], self->rho[high], self->z, MPFR_RNDU);
mpfr_set(self->rho[low], self->y, MPFR_RNDU);
low = _dgs_disc_gauss_mp_min_in_rho(self, range);
mpfr_sub(self->z, self->y, self->rho[low], MPFR_RNDD); // z = avg - rho[low]
}
mpfr_clear(p);
break;
}
default:
free(self);
dgs_die("unknown algorithm %d", algorithm);
}
return self;
}
/** GENERAL SIGMA :: CALL **/
void dgs_disc_gauss_mp_call_uniform_table(mpz_t rop, dgs_disc_gauss_mp_t *self, gmp_randstate_t state) {
unsigned long x;
do {
mpz_urandomm(self->x, state, self->upper_bound);
x = mpz_get_ui(self->x);
mpfr_urandomb(self->y, state);
} while (mpfr_cmp(self->y, self->rho[x]) >= 0);
mpz_set_ui(rop, x);
if(dgs_bern_uniform_call(self->B, state))
mpz_neg(rop, rop);
mpz_add(rop, rop, self->c_z);
}
void dgs_disc_gauss_mp_call_uniform_table_offset(mpz_t rop, dgs_disc_gauss_mp_t *self, gmp_randstate_t state) {
unsigned long x;
do {
mpz_urandomm(self->x, state, self->two_upper_bound_minus_one);
x = mpz_get_ui(self->x);
mpfr_urandomb(self->y, state);
} while (mpfr_cmp(self->y, self->rho[x]) >= 0);
mpz_set_ui(rop, x);
mpz_sub(rop, rop, self->upper_bound_minus_one);
mpz_add(rop, rop, self->c_z);
}
void dgs_disc_gauss_mp_call_alias(mpz_t rop, dgs_disc_gauss_mp_t *self, gmp_randstate_t state) {
mpz_urandomm(rop, state, self->two_upper_bound_minus_one);
unsigned long x = mpz_get_ui(rop);
if (self->bias[x]) {
if (!dgs_bern_mp_call(self->bias[x], state)) {
if (!self->alias[x]) {
free(self);
dgs_die("bias initialized but no alias!");
}
mpz_set(rop, self->alias[x]);
}
}
mpz_sub(rop, rop, self->upper_bound_minus_one);
mpz_add(rop, rop, self->c_z);
}
void dgs_disc_gauss_mp_call_uniform_online(mpz_t rop, dgs_disc_gauss_mp_t *self, gmp_randstate_t state) {
do {
mpz_urandomm(self->x, state, self->two_upper_bound_minus_one);
mpz_sub(self->x, self->x, self->upper_bound_minus_one);
mpfr_set_z(self->z, self->x, MPFR_RNDN);
mpfr_sub(self->z, self->z, self->c_r, MPFR_RNDN);
mpfr_mul(self->z, self->z, self->z, MPFR_RNDN);
mpfr_mul(self->z, self->z, self->f, MPFR_RNDN);
mpfr_exp(self->z, self->z, MPFR_RNDN);
mpfr_urandomb(self->y, state);
} while (mpfr_cmp(self->y, self->z) >= 0);
mpz_set(rop, self->x);
mpz_add(rop, rop, self->c_z);
}
void dgs_disc_gauss_mp_call_uniform_logtable(mpz_t rop, dgs_disc_gauss_mp_t *self, gmp_randstate_t state) {
do {
mpz_urandomm(self->x, state, self->two_upper_bound_minus_one);
mpz_sub(self->x, self->x, self->upper_bound_minus_one);
mpz_mul(self->x2, self->x, self->x);
} while (dgs_bern_exp_mp_call(self->Bexp, self->x2, state) == 0);
mpz_set(rop, self->x);
mpz_add(rop, rop, self->c_z);
}
void dgs_disc_gauss_mp_call_sigma2_logtable(mpz_t rop, dgs_disc_gauss_mp_t *self, gmp_randstate_t state) {
do {
do {
dgs_disc_gauss_sigma2p_mp_call(self->x, self->D2, state);
mpz_urandomm(self->y_z, state, self->k);
mpz_mul(self->x2, self->k, self->x);
mpz_mul_ui(self->x2, self->x2, 2);
mpz_add(self->x2, self->x2, self->y_z);
mpz_mul(self->x2, self->x2, self->y_z);
} while (dgs_bern_exp_mp_call(self->Bexp, self->x2, state) == 0);
mpz_mul(rop, self->k, self->x);
mpz_add(rop, rop, self->y_z);
if (mpz_sgn(rop) == 0) {
if (dgs_bern_uniform_call(self->B, state))
break;
} else {
break;
}
} while (1);
if(dgs_bern_uniform_call(self->B, state))
mpz_neg(rop, rop);
mpz_add(rop, rop, self->c_z);
}
/** GENERAL SIGMA :: CLEAR **/
void dgs_disc_gauss_mp_clear(dgs_disc_gauss_mp_t *self) {
mpfr_clear(self->sigma);
if (self->B) dgs_bern_uniform_clear(self->B);
if (self->Bexp) dgs_bern_exp_mp_clear(self->Bexp);
if (self->D2) dgs_disc_gauss_sigma2p_clear(self->D2);
mpz_clear(self->x);
mpz_clear(self->x2);
mpz_clear(self->k);
mpfr_clear(self->y);
mpfr_clear(self->f);
mpfr_clear(self->z);
mpfr_clear(self->c);
mpfr_clear(self->c_r);
mpz_clear(self->y_z);
mpz_clear(self->c_z);
if (self->rho) {
unsigned long range = mpz_get_ui(self->two_upper_bound_minus_one);
if (self->call == dgs_disc_gauss_mp_call_uniform_table)
range = mpz_get_ui(self->upper_bound);
for(unsigned long x=0; x<range; x++) {
mpfr_clear(self->rho[x]);
}
free(self->rho);
}
if (self->alias) {
for(unsigned long x=0; x<mpz_get_ui(self->two_upper_bound_minus_one); x++) {
if (self->alias[x])
mpz_clear(self->alias[x]);
}
free(self->alias);
}
if (self->bias) {
for(unsigned long x=0; x<mpz_get_ui(self->two_upper_bound_minus_one); x++) {
if (self->bias[x])
dgs_bern_mp_clear(self->bias[x]);
}
free(self->bias);
}
if (self->upper_bound)
mpz_clear(self->upper_bound);
if (self->upper_bound_minus_one)
mpz_clear(self->upper_bound_minus_one);
if (self->two_upper_bound_minus_one)
mpz_clear(self->two_upper_bound_minus_one);
free(self);
}
| 2.03125 | 2 |
2024-11-18T22:25:12.300241+00:00 | 2023-08-08T16:53:06 | 4c45a875eb6436e38bc57472c310a7b3b2b99a18 | {
"blob_id": "4c45a875eb6436e38bc57472c310a7b3b2b99a18",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-08T16:53:06",
"content_id": "130e421e0aff5c5d06b12b853f6f3c91bb203516",
"detected_licenses": [
"MIT"
],
"directory_id": "f514484749e0bb1840f644d6ee4a7ac733f028de",
"extension": "c",
"filename": "lc749.c",
"fork_events_count": 0,
"gha_created_at": "2017-11-19T12:10:06",
"gha_event_created_at": "2023-02-28T15:27:21",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 111291583,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8840,
"license": "MIT",
"license_type": "permissive",
"path": "/leetcode/C/lc749.c",
"provenance": "stackv2-0115.json.gz:112008",
"repo_name": "frank-deng/experimental-works",
"revision_date": "2023-08-08T16:53:06",
"revision_id": "bc3296c701145f6a3e37d7a228569f6937e41be0",
"snapshot_id": "5d7e81a726667206712a6e71c75941de880844bf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/frank-deng/experimental-works/bc3296c701145f6a3e37d7a228569f6937e41be0/leetcode/C/lc749.c",
"visit_date": "2023-08-22T17:47:17.164559"
} | stackv2 | #include "test.h"
typedef struct {
uint16_t x;
uint16_t y;
} getRegionQueueItem_t;
typedef struct {
size_t start;
size_t end;
size_t size;
getRegionQueueItem_t *data;
} getRegionQueue_t;
int getRegionQueueInit(getRegionQueue_t *queue, size_t size)
{
queue->start = 0;
queue->end = 0;
queue->size = size;
queue->data = (getRegionQueueItem_t*)malloc(sizeof(getRegionQueueItem_t) * size);
if (queue->data == NULL) {
return 0;
}
return 1;
}
void getRegionQueueFree(getRegionQueue_t *queue)
{
queue->start = 0;
queue->end = 0;
queue->size = 0;
if (queue->data != NULL) {
free(queue->data);
queue->data = NULL;
}
}
int getRegionQueuePush(getRegionQueue_t *queue, uint16_t x, uint16_t y)
{
if ((queue->start != queue->end) &&
(queue->start % queue->size == queue->end % queue->size)) {
return 0;
}
size_t offset = (queue->start % queue->size);
getRegionQueueItem_t *item = queue->data + offset;
item->x = x;
item->y = y;
(queue->start)++;
return 1;
}
int getRegionQueuePop(getRegionQueue_t *queue, uint16_t *x, uint16_t *y)
{
if (queue->start == queue->end) {
return 0;
}
size_t offset = queue->end % queue->size;
getRegionQueueItem_t *item = queue->data + offset;
*x = item->x;
*y = item->y;
(queue->end)++;
return 1;
}
typedef struct {
uint16_t width;
uint16_t height;
uint8_t *data;
} map_t;
void mapClear(const map_t *map);
int mapCreate(map_t *target, int width, int height)
{
target->width = width;
target->height = height;
target->data = (uint8_t*)malloc(sizeof(uint8_t) * width * height);
if (target->data == NULL) {
return 0;
}
mapClear(target);
return 1;
}
void mapClear(const map_t *map)
{
memset(map->data, 0, sizeof(uint8_t) * map->width * map->height);
}
int mapCopy(const map_t *dest, const map_t* const src){
if (dest->width != src->width || dest->height != src->height) {
return 0;
}
memcpy(dest->data, src->data, sizeof(uint8_t) * src->width * src->height);
return 1;
}
int mapClone(map_t *dest, const map_t* const src)
{
if (!mapCreate(dest, src->width, src->height)) {
return 0;
}
return mapCopy(dest, src);
}
void mapFree(map_t *map)
{
if (map->data != NULL) {
free(map->data);
}
map->data = NULL;
map->width = 0;
map->height = 0;
}
#define BIT_PROCESSED 0x80
#define BIT_INFECTED 0x1
#define BIT_INFECT_NEXT 0x2
#define CELL_INFECTED_ACTIVE(n) (((n) & BIT_INFECTED) && !((n) & BIT_PROCESSED))
int findNextPos(map_t *map, uint16_t *x, uint16_t *y)
{
//找到下一个有毒块
while (*y < map->height) {
uint8_t block = map->data[map->width * (*y) + (*x)];
if (CELL_INFECTED_ACTIVE(block)) {
break;
}
(*x)++;
if (*x >= map->width) {
*x = 0;
(*y)++;
}
}
if (*y >= map->height) {
*x = *y = 0;
return 0;
}
return 1;
}
typedef struct __region_t_list{
map_t map;
int infectNextCount;
int wallCount;
} region_t;
region_t *getNextRegion(map_t *map, uint16_t *x0, uint16_t *y0)
{
if (!findNextPos(map, x0, y0)) {
return NULL;
}
region_t* region = (region_t*)malloc(sizeof(region_t));
region->infectNextCount = region->wallCount = 0;
if (!mapCreate(&(region->map), map->width, map->height)){
free(region);
return NULL;
}
getRegionQueue_t queue;
if (!getRegionQueueInit(&queue, map->width * map->height)){
return NULL;
}
getRegionQueuePush(&queue, *x0, *y0);
uint16_t x, y;
while (getRegionQueuePop(&queue, &x, &y)) {
size_t offset = map->width * y + x;
uint8_t cell = map->data[offset];
if (cell & BIT_PROCESSED) {
continue;
}
map->data[offset] |= BIT_PROCESSED;
if (!(cell & BIT_INFECTED)) {
if (!(region->map.data[offset] & BIT_INFECT_NEXT)) {
region->map.data[offset] |= BIT_INFECT_NEXT;
(region->infectNextCount)++;
}
continue;
}
region->map.data[offset] |= BIT_INFECTED;
// Left cell
if (x > 0) {
getRegionQueuePush(&queue, x - 1, y);
}
// Right cell
if (x < map->width - 1) {
getRegionQueuePush(&queue, x + 1, y);
}
// Top cell
if (y > 0) {
getRegionQueuePush(&queue, x, y - 1);
}
// Bottom cell
if (y < map->height - 1) {
getRegionQueuePush(&queue, x, y + 1);
}
}
getRegionQueueFree(&queue);
return region;
}
void freeRegion(region_t *region)
{
mapFree(&(region->map));
free(region);
}
uint32_t countWalls(const map_t* const map, const map_t* const ref)
{
uint32_t result = 0;
for (uint16_t y = 0; y < map->height; y++) {
for (uint16_t x = 0; x < map->width; x++) {
size_t offset = map->width * y + x;
if (ref->data[offset] & BIT_PROCESSED) {
continue;
}
uint8_t block = map->data[offset];
//左边的墙
if (x > 0) {
size_t offsetLeft = map->width * y + (x - 1);
uint8_t blockLeft = map->data[offsetLeft];
if (!(ref->data[offsetLeft] & BIT_PROCESSED) &&
(blockLeft & BIT_INFECTED) != (block & BIT_INFECTED)) {
result++;
}
}
//上边的墙
if (y > 0) {
size_t offsetTop = map->width * (y - 1) + x;
uint8_t blockTop = map->data[offsetTop];
if (!(ref->data[offsetTop] & BIT_PROCESSED) &&
(blockTop & BIT_INFECTED) != (block & BIT_INFECTED)) {
result++;
}
}
}
}
return result;
}
void freezeMap(const map_t* map, const map_t* const ref)
{
for (uint16_t y = 0; y < map->height; y++) {
for (uint16_t x = 0; x < map->width; x++) {
size_t offset = map->width * y + x;
if (ref->data[offset] & BIT_INFECTED) {
map->data[offset] |= BIT_PROCESSED;
}
}
}
}
void infectMapNext(const map_t* map)
{
map_t mapOrig;
mapClone(&mapOrig, map);
for (uint16_t y = 0; y < map->height; y++) {
for (uint16_t x = 0; x < map->width; x++) {
size_t offset = map->width * y + x;
uint8_t block = mapOrig.data[offset];
if (x > 0) {
size_t offsetLeft = map->width * y + (x - 1);
uint8_t blockLeft = mapOrig.data[offsetLeft];
if (CELL_INFECTED_ACTIVE(block) ||
CELL_INFECTED_ACTIVE(blockLeft)) {
map->data[offsetLeft] |= BIT_INFECTED;
map->data[offset] |= BIT_INFECTED;
}
}
if (y > 0) {
size_t offsetTop = map->width * (y - 1) + x;
uint8_t blockTop = mapOrig.data[offsetTop];
if (CELL_INFECTED_ACTIVE(block) ||
CELL_INFECTED_ACTIVE(blockTop)) {
map->data[offsetTop] |= BIT_INFECTED;
map->data[offset] |= BIT_INFECTED;
}
}
}
}
mapFree(&mapOrig);
}
int processMap(const map_t* mapSrc, uint32_t *wallsAdded)
{
map_t map;
region_t *region = NULL, *regionUse = NULL;
if (!mapClone(&map, mapSrc)){
return 0;
}
uint16_t x = 0, y = 0;
do{
region = getNextRegion(&map, &x, &y);
if (region == NULL) {
break;
} else if (regionUse == NULL) {
regionUse = region;
} else if (region->infectNextCount > regionUse->infectNextCount) {
freeRegion(regionUse);
regionUse = region;
} else {
freeRegion(region);
region = NULL;
}
} while (region != NULL);
mapFree(&map);
if (regionUse == NULL) {
return 0;
}
*wallsAdded = countWalls(&(regionUse->map), mapSrc);
freezeMap(mapSrc, &(regionUse->map));
infectMapNext(mapSrc);
freeRegion(regionUse);
return 1;
}
int containVirus(int **mapSrc, int rows, int *colSize)
{
map_t map;
int walls = 0;
uint32_t wallsAdded;
if (!mapCreate(&map, colSize[0], rows)){
return 0;
}
for (uint16_t y = 0; y < map.height; y++) {
for (uint16_t x = 0; x < map.width; x++) {
map.data[map.width * y + x] = (mapSrc[y][x] ? 1 : 0);
}
}
while(processMap(&map, &wallsAdded)){
walls += wallsAdded;
}
mapFree(&map);
return walls;
}
| 2.765625 | 3 |
2024-11-18T22:25:12.372889+00:00 | 2020-07-31T20:48:43 | 708051336f1f10a71d1197e3a3efb8d57e6a1eea | {
"blob_id": "708051336f1f10a71d1197e3a3efb8d57e6a1eea",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-31T20:48:43",
"content_id": "b1886defde4a6942be9b8fda527f5baacc5ba271",
"detected_licenses": [
"MIT"
],
"directory_id": "b717e07cee4466f2ca2c5281d731960ab0618cb7",
"extension": "h",
"filename": "DynamicTrees.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 251497218,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5490,
"license": "MIT",
"license_type": "permissive",
"path": "/include/ift/segm/DynamicTrees.h",
"provenance": "stackv2-0115.json.gz:112137",
"repo_name": "italosestilon/MO815-tasks",
"revision_date": "2020-07-31T20:48:43",
"revision_id": "03fd83e60b7e2065fe932447e743f3cb8cda3891",
"snapshot_id": "0cf973319ade729e08acaa00cacf157ef9b1b153",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/italosestilon/MO815-tasks/03fd83e60b7e2065fe932447e743f3cb8cda3891/include/ift/segm/DynamicTrees.h",
"visit_date": "2023-04-29T15:21:55.681739"
} | stackv2 | //
// Created by jordao on 05/06/18.
//
#ifndef IFT_IFTDYNAMICSET_H
#define IFT_IFTDYNAMICSET_H
#ifdef __cplusplus
extern "C" {
#endif
#include "iftImage.h"
#include "ift/core/dtypes/LabeledSet.h"
#include "iftMImage.h"
#include "iftDataSet.h"
#include "iftMetrics.h"
//! swig(extend = iftDynamicSetExt.i, destroyer = iftDestroyDynamicSet)
typedef struct ift_dynamic_set
{
double *mean;
iftSet *begin;
iftSet *end;
int dim;
int size;
} iftDynamicSet;
//! swig(extend = iftDTForestExt.i, destroyer = iftDestroyDTForest)
typedef struct ift_dt_forest
{
iftImage *label;
iftFImage *cost;
iftImage *root;
iftImage *pred;
iftImage *order;
iftImage *delay;
iftDynamicSet **dyn_trees;
} iftDTForest;
static inline void iftInsertDynamicSet(iftDynamicSet *S, const iftMImage *mimg, int p)
{
if (S->size) {
iftSet *a = (iftSet*) iftAlloc(1, sizeof *a);
if (!a)
iftError(MSG_MEMORY_ALLOC_ERROR, "iftInsertDynamicSet");
a->elem = p;
S->end->next = a;
S->end = a;
} else {
S->begin = (iftSet*) iftAlloc(1, sizeof *S->begin);
S->begin->elem = p;
S->end = S->begin;
}
S->size += 1;
for (int i = 0; i < S->dim; i++) {
S->mean[i] += (mimg->val[p][i] - S->mean[i]) / S->size;
}
}
iftDynamicSet *iftCreateDynamicSet(int dim);
//! swig(newobject)
iftDTForest *iftCreateDTForest(const iftMImage *mimg, const iftAdjRel *A, const iftLabeledSet *seeds,
float delta, float gamma);
void iftDestroyDynamicSet(iftDynamicSet **S);
void iftDestroyDTForest(iftDTForest **forest);
static inline double iftDistDynamicSetMImage(const iftDynamicSet *S, const iftMImage *mimg, int p)
{
double dist = 0;
for (int i = 0; i < S->dim; i++) {
dist += (S->mean[i] - mimg->val[p][i]) * (S->mean[i] - mimg->val[p][i]);
}
return dist;
}
//! swig(newobject)
iftImage *iftDynamicSetObjectPolicy(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, bool use_dist);
//! swig(newobject)
iftImage *iftDynamicSetRootPolicy(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, int h, bool use_dist);
//! swig(newobject)
iftImage *iftDynamicSetMinRootPolicy(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, int h, bool use_dist);
//! swig(newobject)
iftImage *iftDynamicSetWithCluster(iftMImage *mimg, iftImage *cluster, iftAdjRel *A, iftLabeledSet *seeds, int h, bool use_dist);
//! swig(newobject)
iftImage *iftDynamicSetRootEnhanced(iftMImage *mimg, iftImage *objmap, iftAdjRel *A, iftLabeledSet *seeds, int h, float alpha, bool use_dist);
//! swig(newobject)
iftImage *iftDynamicSetMinRootEnhanced(iftMImage *mimg, iftImage *objmap, iftAdjRel *A, iftLabeledSet *seeds, int h, float alpha, bool use_dist);
/**
* @param mimg multi-band original image
* @param A adjacency relation
* @param seeds labeled seeds nodes
* @param delta plato penalization height
* @param gamma neighbor distance scaling parameter, must be > 0.0
* @param objmap (optional) saliency image
* @param alpha (optional) saliency weight, is set to 1.0 if objmap is not given
* @return label mapping
*/
//! swig(newobject, stable)
iftImage *iftDynTreeRoot(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, int delta,
float gamma, iftImage *objmap, float alpha);
/**
* @param mimg multi-band original image
* @param A adjacency relation
* @param seeds labeled seeds nodes
* @param delta plato penalization height
* @param gamma neighbor distance scaling parameter, must be > 0.0
* @param objmap (optional) saliency image
* @param alpha (optional) saliency weight, is set to 1.0 if objmap is not given
* @return label mapping
*/
//! swig(newobject, stable)
iftImage *iftDynTreeClosestRoot(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, int delta,
float gamma, iftImage *objmap, float alpha);
iftImage *iftDynTreeLearned(iftMImage *mimg, iftMatrix *M, iftAdjRel *A, iftLabeledSet *seeds,
int delta, float gamma);
typedef struct ift_dynamic_set_CIARP
{
double *mean;
int size;
} iftDynamicSet_CIARP;
static inline void iftInsertDynamicSet_CIARP(iftDynamicSet_CIARP *S, iftMImage *mimg, int p)
{
S->mean[0] += (mimg->val[p][0] - S->mean[0]) / (S->size + 1);
S->mean[1] += (mimg->val[p][1] - S->mean[1]) / (S->size + 1);
S->mean[2] += (mimg->val[p][2] - S->mean[2]) / (S->size + 1);
++S->size;
}
static inline double iftDistDynamicSetMImage_CIARP(iftDynamicSet_CIARP *S, iftMImage *mimg, int p)
{
double dist = (S->mean[0] - mimg->val[p][0]) * (S->mean[0] - mimg->val[p][0]) +
(S->mean[1] - mimg->val[p][1]) * (S->mean[1] - mimg->val[p][1]) +
(S->mean[2] - mimg->val[p][2]) * (S->mean[2] - mimg->val[p][2]);
return dist;
}
iftDynamicSet_CIARP *iftCreateDynamicSet_CIARP(void);
void iftDestroyDynamicSet_CIARP(iftDynamicSet_CIARP **S);
iftImage *iftDynamicSetObjectPolicy_CIARP(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, bool use_dist);
iftImage *iftDynamicSetRootPolicy_CIARP(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, bool use_dist);
iftImage *iftDynamicSetMinRootPolicy_CIARP(iftMImage *mimg, iftAdjRel *A, iftLabeledSet *seeds, bool use_dist);
#ifdef __cplusplus
}
#endif
#endif //IFT_IFTDYNAMICSET_H
| 2.078125 | 2 |
2024-11-18T22:25:12.553719+00:00 | 2014-06-13T16:06:07 | 3fb46d1c31fc14ed4b8cfaf21ec065e79bfabfd3 | {
"blob_id": "3fb46d1c31fc14ed4b8cfaf21ec065e79bfabfd3",
"branch_name": "refs/heads/master",
"committer_date": "2014-06-13T16:06:07",
"content_id": "b80ec9cde24587746ae349e306035ec5d22fe240",
"detected_licenses": [
"Unlicense"
],
"directory_id": "1324b0aeebb652fe449738cf5819a9c2e2321c4f",
"extension": "c",
"filename": "utils.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 20756311,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1562,
"license": "Unlicense",
"license_type": "permissive",
"path": "/source/utils.c",
"provenance": "stackv2-0115.json.gz:112267",
"repo_name": "iamn1ck/3048",
"revision_date": "2014-06-13T16:06:07",
"revision_id": "60e4659ff9b328e984fbdccfeb8149efef13ed23",
"snapshot_id": "99cad1efde0e0a26e07fa25e21919045566e59ee",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/iamn1ck/3048/60e4659ff9b328e984fbdccfeb8149efef13ed23/source/utils.c",
"visit_date": "2016-09-05T11:05:48.372785"
} | stackv2 | #include "utils.h"
#include "memory.h"
void write_word(int address, int word){
int *a = (int*) address;
*a = word;
}
void write_byte(int address, char byte){
char *a = (char*) address;
*a = byte;
}
int read_word(int address){
int *a = (int*) address;
return *a;
}
void* find_byte_sequence(char* sequence, int num, int base_address){
char* c = (char*)base_address;
while (1){
if (*c == sequence[0]){
int i;
for (i = 1; i < num; i++){
if(*(c+i) == sequence[i]){
} else {
break;
}
return (void*)c;
}
}
c++;
}
}
int strlen(char* string){
int i;
for (i = 0; ; i++){
if (string[i] == 0x00){
return i;
}
}
}
void strconcat(char* dest, char* src){
while(*dest != '\0') dest++;
while(*src != 0x00){
*dest = *src;
dest++;
src++;
}
*dest = 0x00;
}
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
| 3.125 | 3 |
2024-11-18T22:25:12.935173+00:00 | 2020-02-09T20:44:13 | f73956cfef8db14a47b149291111592d72687bac | {
"blob_id": "f73956cfef8db14a47b149291111592d72687bac",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-09T20:44:13",
"content_id": "fa653795da3433e0b3aba939409502f82d4e875d",
"detected_licenses": [
"MIT"
],
"directory_id": "960b99785babf45c9194c9d2e5bacc2bfdbef451",
"extension": "h",
"filename": "atmel_start_pins.h",
"fork_events_count": 0,
"gha_created_at": "2019-11-20T14:07:59",
"gha_event_created_at": "2019-11-20T14:08:00",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 222951695,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14223,
"license": "MIT",
"license_type": "permissive",
"path": "/rev_a/firmware/LoFence/include/atmel_start_pins.h",
"provenance": "stackv2-0115.json.gz:112655",
"repo_name": "kevinkngo/lofence",
"revision_date": "2020-02-09T20:44:13",
"revision_id": "24fd53311371a786a307ccebee5830c5f7d7a260",
"snapshot_id": "08daec141537c4eb0c8040db3abffdc759ae337c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kevinkngo/lofence/24fd53311371a786a307ccebee5830c5f7d7a260/rev_a/firmware/LoFence/include/atmel_start_pins.h",
"visit_date": "2020-09-14T00:22:58.327371"
} | stackv2 | /*
* Code generated from Atmel Start.
*
* This file will be overwritten when reconfiguring your Atmel Start project.
* Please copy examples or other code you want to keep to a separate file
* to avoid losing it when reconfiguring.
*/
#ifndef ATMEL_START_PINS_H_INCLUDED
#define ATMEL_START_PINS_H_INCLUDED
#include <port.h>
/**
* \brief Set RN_RESET pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void RN_RESET_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTB_set_pin_pull_mode(1, pull_mode);
}
/**
* \brief Set RN_RESET data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void RN_RESET_set_dir(const enum port_dir dir)
{
PORTB_set_pin_dir(1, dir);
}
/**
* \brief Set RN_RESET level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void RN_RESET_set_level(const bool level)
{
PORTB_set_pin_level(1, level);
}
/**
* \brief Toggle output level on RN_RESET
*
* Toggle the pin level
*/
static inline void RN_RESET_toggle_level()
{
PORTB_toggle_pin_level(1);
}
/**
* \brief Get level on RN_RESET
*
* Reads the level on a pin
*/
static inline bool RN_RESET_get_level()
{
return PORTB_get_pin_level(1);
}
/**
* \brief Set DBG_TX pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void DBG_TX_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTB_set_pin_pull_mode(3, pull_mode);
}
/**
* \brief Set DBG_TX data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void DBG_TX_set_dir(const enum port_dir dir)
{
PORTB_set_pin_dir(3, dir);
}
/**
* \brief Set DBG_TX level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void DBG_TX_set_level(const bool level)
{
PORTB_set_pin_level(3, level);
}
/**
* \brief Toggle output level on DBG_TX
*
* Toggle the pin level
*/
static inline void DBG_TX_toggle_level()
{
PORTB_toggle_pin_level(3);
}
/**
* \brief Get level on DBG_TX
*
* Reads the level on a pin
*/
static inline bool DBG_TX_get_level()
{
return PORTB_get_pin_level(3);
}
/**
* \brief Set DBG_RX pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void DBG_RX_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTB_set_pin_pull_mode(4, pull_mode);
}
/**
* \brief Set DBG_RX data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void DBG_RX_set_dir(const enum port_dir dir)
{
PORTB_set_pin_dir(4, dir);
}
/**
* \brief Set DBG_RX level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void DBG_RX_set_level(const bool level)
{
PORTB_set_pin_level(4, level);
}
/**
* \brief Toggle output level on DBG_RX
*
* Toggle the pin level
*/
static inline void DBG_RX_toggle_level()
{
PORTB_toggle_pin_level(4);
}
/**
* \brief Get level on DBG_RX
*
* Reads the level on a pin
*/
static inline bool DBG_RX_get_level()
{
return PORTB_get_pin_level(4);
}
/**
* \brief Set ADC_PLUS pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void ADC_PLUS_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTC_set_pin_pull_mode(0, pull_mode);
}
/**
* \brief Set ADC_PLUS data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void ADC_PLUS_set_dir(const enum port_dir dir)
{
PORTC_set_pin_dir(0, dir);
}
/**
* \brief Set ADC_PLUS level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void ADC_PLUS_set_level(const bool level)
{
PORTC_set_pin_level(0, level);
}
/**
* \brief Toggle output level on ADC_PLUS
*
* Toggle the pin level
*/
static inline void ADC_PLUS_toggle_level()
{
PORTC_toggle_pin_level(0);
}
/**
* \brief Get level on ADC_PLUS
*
* Reads the level on a pin
*/
static inline bool ADC_PLUS_get_level()
{
return PORTC_get_pin_level(0);
}
/**
* \brief Set ADC_POWER pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void ADC_POWER_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTC_set_pin_pull_mode(1, pull_mode);
}
/**
* \brief Set ADC_POWER data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void ADC_POWER_set_dir(const enum port_dir dir)
{
PORTC_set_pin_dir(1, dir);
}
/**
* \brief Set ADC_POWER level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void ADC_POWER_set_level(const bool level)
{
PORTC_set_pin_level(1, level);
}
/**
* \brief Toggle output level on ADC_POWER
*
* Toggle the pin level
*/
static inline void ADC_POWER_toggle_level()
{
PORTC_toggle_pin_level(1);
}
/**
* \brief Get level on ADC_POWER
*
* Reads the level on a pin
*/
static inline bool ADC_POWER_get_level()
{
return PORTC_get_pin_level(1);
}
/**
* \brief Set ADC_MINUS pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void ADC_MINUS_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTC_set_pin_pull_mode(2, pull_mode);
}
/**
* \brief Set ADC_MINUS data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void ADC_MINUS_set_dir(const enum port_dir dir)
{
PORTC_set_pin_dir(2, dir);
}
/**
* \brief Set ADC_MINUS level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void ADC_MINUS_set_level(const bool level)
{
PORTC_set_pin_level(2, level);
}
/**
* \brief Toggle output level on ADC_MINUS
*
* Toggle the pin level
*/
static inline void ADC_MINUS_toggle_level()
{
PORTC_toggle_pin_level(2);
}
/**
* \brief Get level on ADC_MINUS
*
* Reads the level on a pin
*/
static inline bool ADC_MINUS_get_level()
{
return PORTC_get_pin_level(2);
}
/**
* \brief Set BAT_ADC pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void BAT_ADC_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTC_set_pin_pull_mode(4, pull_mode);
}
/**
* \brief Set BAT_ADC data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void BAT_ADC_set_dir(const enum port_dir dir)
{
PORTC_set_pin_dir(4, dir);
}
/**
* \brief Set BAT_ADC level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void BAT_ADC_set_level(const bool level)
{
PORTC_set_pin_level(4, level);
}
/**
* \brief Toggle output level on BAT_ADC
*
* Toggle the pin level
*/
static inline void BAT_ADC_toggle_level()
{
PORTC_toggle_pin_level(4);
}
/**
* \brief Get level on BAT_ADC
*
* Reads the level on a pin
*/
static inline bool BAT_ADC_get_level()
{
return PORTC_get_pin_level(4);
}
/**
* \brief Set BAT_GND pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void BAT_GND_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTC_set_pin_pull_mode(5, pull_mode);
}
/**
* \brief Set BAT_GND data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void BAT_GND_set_dir(const enum port_dir dir)
{
PORTC_set_pin_dir(5, dir);
}
/**
* \brief Set BAT_GND level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void BAT_GND_set_level(const bool level)
{
PORTC_set_pin_level(5, level);
}
/**
* \brief Toggle output level on BAT_GND
*
* Toggle the pin level
*/
static inline void BAT_GND_toggle_level()
{
PORTC_toggle_pin_level(5);
}
/**
* \brief Get level on BAT_GND
*
* Reads the level on a pin
*/
static inline bool BAT_GND_get_level()
{
return PORTC_get_pin_level(5);
}
/**
* \brief Set MCU_RX pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void MCU_RX_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTD_set_pin_pull_mode(0, pull_mode);
}
/**
* \brief Set MCU_RX data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void MCU_RX_set_dir(const enum port_dir dir)
{
PORTD_set_pin_dir(0, dir);
}
/**
* \brief Set MCU_RX level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void MCU_RX_set_level(const bool level)
{
PORTD_set_pin_level(0, level);
}
/**
* \brief Toggle output level on MCU_RX
*
* Toggle the pin level
*/
static inline void MCU_RX_toggle_level()
{
PORTD_toggle_pin_level(0);
}
/**
* \brief Get level on MCU_RX
*
* Reads the level on a pin
*/
static inline bool MCU_RX_get_level()
{
return PORTD_get_pin_level(0);
}
/**
* \brief Set MCU_TX pull mode
*
* Configure pin to pull up, down or disable pull mode, supported pull
* modes are defined by device used
*
* \param[in] pull_mode Pin pull mode
*/
static inline void MCU_TX_set_pull_mode(const enum port_pull_mode pull_mode)
{
PORTD_set_pin_pull_mode(1, pull_mode);
}
/**
* \brief Set MCU_TX data direction
*
* Select if the pin data direction is input, output or disabled.
* If disabled state is not possible, this function throws an assert.
*
* \param[in] direction PORT_DIR_IN = Data direction in
* PORT_DIR_OUT = Data direction out
* PORT_DIR_OFF = Disables the pin
* (low power state)
*/
static inline void MCU_TX_set_dir(const enum port_dir dir)
{
PORTD_set_pin_dir(1, dir);
}
/**
* \brief Set MCU_TX level
*
* Sets output level on a pin
*
* \param[in] level true = Pin level set to "high" state
* false = Pin level set to "low" state
*/
static inline void MCU_TX_set_level(const bool level)
{
PORTD_set_pin_level(1, level);
}
/**
* \brief Toggle output level on MCU_TX
*
* Toggle the pin level
*/
static inline void MCU_TX_toggle_level()
{
PORTD_toggle_pin_level(1);
}
/**
* \brief Get level on MCU_TX
*
* Reads the level on a pin
*/
static inline bool MCU_TX_get_level()
{
return PORTD_get_pin_level(1);
}
#endif /* ATMEL_START_PINS_H_INCLUDED */
| 2.5 | 2 |
2024-11-18T22:25:13.072639+00:00 | 2023-08-13T07:00:15 | 7f25bc768f7bdac662bd2209180238ee0e4103f7 | {
"blob_id": "7f25bc768f7bdac662bd2209180238ee0e4103f7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-13T07:00:15",
"content_id": "de0f98a04e9b6a2f3389a8897cfd95b02d9290ab",
"detected_licenses": [
"MIT"
],
"directory_id": "2266eb133fc3121daf0aa7f4560626b46b94afe0",
"extension": "c",
"filename": "dao-xiang2.c",
"fork_events_count": 49,
"gha_created_at": "2017-11-28T03:05:14",
"gha_event_created_at": "2023-02-01T03:42:14",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 112278568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2625,
"license": "MIT",
"license_type": "permissive",
"path": "/kungfu/class/shaolin/dao-xiang2.c",
"provenance": "stackv2-0115.json.gz:112785",
"repo_name": "oiuv/mud",
"revision_date": "2023-08-13T07:00:15",
"revision_id": "e9ff076724472256b9b4bd88c148d6bf71dc3c02",
"snapshot_id": "6fbabebc7b784279fdfae06d164f5aecaa44ad90",
"src_encoding": "UTF-8",
"star_events_count": 99,
"url": "https://raw.githubusercontent.com/oiuv/mud/e9ff076724472256b9b4bd88c148d6bf71dc3c02/kungfu/class/shaolin/dao-xiang2.c",
"visit_date": "2023-08-18T20:18:37.848801"
} | stackv2 | // Npc: /kungfu/class/shaolin/dao-xiang2.c
// Date: YZC 96/01/19
inherit NPC;
inherit F_MASTER;
string ask_me_1();
#include "dao.h"
void create()
{
set_name("道象禅师", ({
"daoxiang chanshi",
"daoxiang",
"chanshi",
}));
set("long",
"他是一位身材高大的中年僧人,两臂粗壮,膀阔腰圆。他手持兵\n"
"刃,身穿一袭灰布镶边袈裟,似乎有一身武艺。\n"
);
set("gender", "男性");
set("attitude", "friendly");
set("class", "bonze");
set("age", 40);
set("shen_type", 1);
set("str", 20);
set("int", 20);
set("con", 20);
set("dex", 20);
set("max_qi", 400);
set("max_jing", 300);
set("neili", 450);
set("max_neili", 450);
set("jiali", 40);
set("combat_exp", 10000);
set("score", 100);
set_skill("force", 50);
set_skill("hunyuan-yiqi", 50);
set_skill("shaolin-xinfa", 50);
set_skill("dodge", 50);
set_skill("shaolin-shenfa", 50);
set_skill("strike", 50);
set_skill("banruo-zhang", 50);
set_skill("damo-jian", 50);
set_skill("buddhism", 50);
set_skill("literate", 50);
map_skill("force", "hunyuan-yiqi");
map_skill("dodge", "shaolin-shenfa");
map_skill("strike", "banruo-zhang");
map_skill("parry", "banruo-zhang");
prepare_skill("strike", "banruo-zhang");
create_family("少林派", 39, "弟子");
set("inquiry", ([
"金创药" : (: ask_me_1 :),
]));
set("jin_count", 20);
setup();
carry_object("/d/shaolin/obj/dao-cloth")->wear();
}
string ask_me_1()
{
mapping fam;
object ob;
if (!(fam = this_player()->query("family")) || fam["family_name"] != "少林派")
return RANK_D->query_respect(this_player()) +
"与本派素无来往,不知此话从何谈起?";
if ( (int)this_player()->query_condition("bonze_drug" ) > 0 )
return RANK_D->query_respect(this_player()) +
"你是不是刚吃过药,怎麽又来要了? 灵药多吃有害无宜,过段时间再来吧。";
if ( present("jin chuangyao", this_player()) )
return RANK_D->query_respect(this_player()) +
"你现在身上不是有颗药丸吗,怎麽又来要了? 真是贪得无餍!";
if (query("jin_count") < 1) return "对不起,金创药已经发完了";
ob = new("/d/shaolin/obj/jinchuang-yao");
ob->move(this_player());
add("jin_count", -1);
message_vision("$N获得一包金创药。\n",this_player());
return "好吧,记住,不到危急关头不要轻易使用此药。";
}
| 2.21875 | 2 |
2024-11-18T22:25:13.350483+00:00 | 2017-12-06T10:12:22 | 2ea7b7ad2ed9bb76a576d06e56964514451d6deb | {
"blob_id": "2ea7b7ad2ed9bb76a576d06e56964514451d6deb",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-06T10:12:22",
"content_id": "bc6987105fd5875301f84d6aef893349c4f1a470",
"detected_licenses": [
"MIT"
],
"directory_id": "f2fa92487f63d2e11723960ae59c10048769fd43",
"extension": "c",
"filename": "moto.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 113300358,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1596,
"license": "MIT",
"license_type": "permissive",
"path": "/C/14/moto.c",
"provenance": "stackv2-0115.json.gz:112915",
"repo_name": "Pantoofle/Language-Practice",
"revision_date": "2017-12-06T10:12:22",
"revision_id": "f5d4b3f5eb745f0e9abf50f2ddb08fd902225f07",
"snapshot_id": "d611c1d29786891a5ed2b48ffa71c95e8d28f4f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Pantoofle/Language-Practice/f5d4b3f5eb745f0e9abf50f2ddb08fd902225f07/C/14/moto.c",
"visit_date": "2021-08-23T20:06:07.101866"
} | stackv2 | #include<stdio.h>
#include<stdlib.h>
/* On prépare les entrées des différentes motos*/
#define X_MOTO \
X(Suzuki, Gsxf, 5000, bleu)\
X(HarleyDavidson, VRod, 16500, noir)\
X(Kawasaki, Ninja300, 6000, vert)
#define X(marque, modele, prix, couleur) marque ## _ ## modele, /* X est maintenant un "accesseur"*/
enum index_e{ /* Si on appelle X(...) il sera remplacé par la marque, suivie du modèle de la moto*/
X_MOTO /*On recopie ici la définition de toutes les motos.*/
/* Or dans cette def, il y a X, qui est donc remplacé par marque_modele pour chaque moto*/
NOMBRE_MOTOS
};
#undef X // on a plus besoin de X. on l'oublie
#define X(marque, modele, prix, couleur) #marque, // Maintenant, X est juste remplaçée par la marque
char const * const marque_a [] = {
X_MOTO // On créé un tableau contenant toutes les marques
};
#undef X
#define X(marque, modele, prix, couleur) #modele, // Maintenant, X est juste remplaçée par le modele
char const * const modele_a [] = {
X_MOTO // On créé un tableau contenant touts les modeles
};
#undef X
#define X(marque, modele, prix, couleur) prix, //Ici, pas besoin de #, l'expression est deja un int
const int prix_a [] = {
X_MOTO
};
#undef X
#define X(marque, modele, prix, couleur) #couleur,
char const * const couleur_a [] = {
X_MOTO
};
#undef X
int main(void){
int i;
printf("%lu", sizeof(marque_a));
for(i=0; i<NOMBRE_MOTOS; i++)
printf("Marque : %s −Modele : %s − Prix : %d − Couleur : %s \n",
marque_a [i], modele_a[i], prix_a[i] ,couleur_a[i]);
return EXIT_SUCCESS;
}
| 2.8125 | 3 |
2024-11-18T22:25:13.425235+00:00 | 2021-03-12T12:15:05 | a66120962b6ae49fc3ed09afc7c3f40b615d3946 | {
"blob_id": "a66120962b6ae49fc3ed09afc7c3f40b615d3946",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-12T12:15:05",
"content_id": "6acc2e7e8a435a9e436563cfe7c805e7965d1975",
"detected_licenses": [
"MIT"
],
"directory_id": "d0dafe2f324f488ac02debf15b0d8f7c00bc9af2",
"extension": "c",
"filename": "06.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 311907305,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 280,
"license": "MIT",
"license_type": "permissive",
"path": "/01/06.c",
"provenance": "stackv2-0115.json.gz:113046",
"repo_name": "BasePractice/mirea.c.cyber.labs",
"revision_date": "2021-03-12T12:15:05",
"revision_id": "bb3f422fb830f9054cd9ba6c5593323b57399959",
"snapshot_id": "3469fa8a7261447585e9727c9125e28e0f0eef74",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/BasePractice/mirea.c.cyber.labs/bb3f422fb830f9054cd9ba6c5593323b57399959/01/06.c",
"visit_date": "2023-03-21T05:51:37.585398"
} | stackv2 | #include "base.h"
/**
* y = sh(2 * x) + x
* x = 1
*/
double CALL(task)(double x, double eps, bool *divergent) {
return x_shn(2 * x, eps, divergent) + x;
}
double CALL(base)(double x, double _) {
return sinh(2 * x) + x;
}
double CALL(initiate_x)() {
return 1;
}
| 2.21875 | 2 |
2024-11-18T22:25:13.496275+00:00 | 2015-04-21T22:15:33 | f418c08d9430dc5d2a92c639dd426b25c3d086ff | {
"blob_id": "f418c08d9430dc5d2a92c639dd426b25c3d086ff",
"branch_name": "HEAD",
"committer_date": "2015-04-21T22:15:33",
"content_id": "1478c23350f664771e82cdd6dc268430d32fba07",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "433ce53f5e6a30143599a116546d392d5bbb71a9",
"extension": "c",
"filename": "AmqpHashTable.c",
"fork_events_count": 8,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1619242,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3757,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/LibAmqp/AmqpTypes/AmqpHashTable.c",
"provenance": "stackv2-0115.json.gz:113174",
"repo_name": "libamqp/libamqp",
"revision_date": "2015-04-21T22:15:33",
"revision_id": "af404f8412a940059fa54af0b25160bc94c8dd4b",
"snapshot_id": "856a4b9ccad80aaad610a76d015ac0aae0b454e6",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/libamqp/libamqp/af404f8412a940059fa54af0b25160bc94c8dd4b/src/LibAmqp/AmqpTypes/AmqpHashTable.c",
"visit_date": "2016-09-03T06:44:13.553357"
} | stackv2 | /*
Copyright 2011-2012 StormMQ Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <assert.h>
#include <string.h>
#include "Misc/Bits.h"
#include "Context/Context.h"
#include "AmqpTypes/AmqpHashTable.h"
#include "debug_helper.h"
void amqp_hash_table_initialize(amqp_context_t *context, amqp_hash_table_t *map, int initial_capacity, amqp_hash_fn_t hash, amqp_compare_fn_t compare)
{
map->capacity = amqp_next_power_two(initial_capacity);
assert(map->capacity > 0);
map->count = 0;
map->buckets = AMQP_MALLOC_ARRAY(context, amqp_entry_t *, map->capacity);
map->entry_list = 0;
map->hash = hash;
map->compare = compare;
map->on_heap = 0;
}
amqp_hash_table_t *amqp_hash_table_create(amqp_context_t *context, int initial_capacity, amqp_hash_fn_t hash, amqp_compare_fn_t compare)
{
amqp_hash_table_t *result = AMQP_MALLOC(context, amqp_hash_table_t);
amqp_hash_table_initialize(context, result, initial_capacity, hash, compare);
result->on_heap = 1;
return result;
}
void amqp_hash_table_cleanup(amqp_context_t *context, amqp_hash_table_t *map, amqp_free_callback_t callback)
{
if (map)
{
amqp_entry_t *list = map->entry_list;
while (list)
{
amqp_entry_t *entry = list;
list = list->entry_list.next;
if (callback)
{
callback(context, entry->key, entry->data);
}
AMQP_FREE(context, entry);
}
AMQP_FREE(context, map->buckets);
map->buckets = 0;
map->entry_list = 0;
if (map->on_heap)
{
AMQP_FREE(context, map);
}
}
}
static amqp_entry_t *add_entry(amqp_context_t *context, amqp_hash_table_t *map, int index, const void *key, const void *data)
{
amqp_entry_t *entry = AMQP_MALLOC(context, amqp_entry_t);
entry->key = key;
entry->data = data;
entry->collision_list.next = map->buckets[index];
entry->collision_list.prev = &map->buckets[index];
map->buckets[index] = entry;
entry->entry_list.next = map->entry_list;
entry->entry_list.prev = &map->entry_list;
map->entry_list = entry;
map->count++;
return entry;
}
static amqp_entry_t *search_chain(amqp_hash_table_t *map, amqp_entry_t *chain, const void *key)
{
while (chain && map->compare(chain->key, key) != 0)
{
chain = chain->collision_list.next;
}
return chain;
}
static int calculate_index(amqp_hash_table_t *map, const void *key)
{
uint32_t hash = map->hash(key);
uint32_t mask = map->capacity - 1;
return hash & mask;
}
int amqp_hash_table_put(amqp_context_t *context, amqp_hash_table_t *map, const void *key, const void *data)
{
int index;
assert(map && map->hash && map->compare);
index = calculate_index(map, key);
if (map->buckets[index] != 0 && search_chain(map, map->buckets[index], key))
{
return false;
}
add_entry(context, map, index, key, data);
return true;
}
const void *amqp_hash_table_get(amqp_hash_table_t *map, const void *key)
{
int index = calculate_index(map, key);
amqp_entry_t *entry = search_chain(map, map->buckets[index], key);
return entry ? entry->data : 0;
}
| 2.375 | 2 |
2024-11-18T22:25:13.807758+00:00 | 2019-08-07T01:16:48 | 66078a5b31e73087cd47cdcac0a2567f6d277d4f | {
"blob_id": "66078a5b31e73087cd47cdcac0a2567f6d277d4f",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-07T01:16:48",
"content_id": "b7bbab2e393af61f3baf70083fd9889803e157c1",
"detected_licenses": [
"MIT"
],
"directory_id": "63a54bc72b5860fa51117334b80c4e8e027258dd",
"extension": "c",
"filename": "tests-my_macroABS.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": 401,
"license": "MIT",
"license_type": "permissive",
"path": "/CPool/CPool_Day09/tests/tests-my_macroABS.c",
"provenance": "stackv2-0115.json.gz:113302",
"repo_name": "Epitech-Strasbourg-CT/Epitech-Computer-Science-School-Projects",
"revision_date": "2019-08-07T01:16:48",
"revision_id": "43065b7230534a8ba08793dadbf99ce07ac9af3a",
"snapshot_id": "b90e12137b56902e2862f956844a64b85164e724",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Epitech-Strasbourg-CT/Epitech-Computer-Science-School-Projects/43065b7230534a8ba08793dadbf99ce07ac9af3a/CPool/CPool_Day09/tests/tests-my_macroABS.c",
"visit_date": "2022-02-11T21:59:20.801001"
} | stackv2 | /*
** tests-my_macroABS.c for tests-my_macroABS in /home/RODRIG_1/rendu/Piscine_C_J09
**
** Made by rodriguez gwendoline
** Login <RODRIG_1@epitech.net>
**
** Started on Thu Oct 9 14:34:11 2014 rodriguez gwendoline
** Last update Tue Nov 4 11:44:08 2014 rodriguez gwendoline
*/
#include "./../ex_01/my_macroABS.h"
int main()
{
int i;
i = -2;
i = ABS(i);
my_putchar(i + '0');
}
| 2.046875 | 2 |
2024-11-18T22:25:13.912662+00:00 | 2018-07-20T17:12:35 | a6e567c6e1f0beea79e48cdc15b41f2dcbf00eda | {
"blob_id": "a6e567c6e1f0beea79e48cdc15b41f2dcbf00eda",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-20T17:12:35",
"content_id": "77b257dae4de6452f0acbd1f8100753b694fe669",
"detected_licenses": [
"MIT"
],
"directory_id": "e70da0b17cfc6214756513829ee019daacfd8583",
"extension": "c",
"filename": "histograma.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 105811853,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2527,
"license": "MIT",
"license_type": "permissive",
"path": "/activities/histograma/histograma.c",
"provenance": "stackv2-0115.json.gz:113431",
"repo_name": "alessandrojean/PE-2017.3",
"revision_date": "2018-07-20T17:12:35",
"revision_id": "f29d467e7e53921420117bdef181132e3e2d00bc",
"snapshot_id": "2ec4a03dd4580fb644bbdf23e9f5beb3de68819f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alessandrojean/PE-2017.3/f29d467e7e53921420117bdef181132e3e2d00bc/activities/histograma/histograma.c",
"visit_date": "2018-10-20T17:10:34.422518"
} | stackv2 | #include <stdio.h>
#define N 20000
void bubble_sort(double t[], int n);
double media_acima_media(double media, double t[], int n);
void popular_aux(int aux[20], double t[], int n);
double histograma(int aux[20], double t[], int n);
void histograma_vertical(double max_aux, int aux[20]);
int main() {
int n = 0;
double t[N], med, min = 100, max = -100, soma = 0;;
while(n < N && scanf("%lf", &t[n]) > 0) {
if(t[n] > max)
max = t[n];
else if(t[n] < min)
min = t[n];
soma += t[n++];
}
med = soma / n;
printf("med = %.3lf, min = %.3lf, max = %.3lf\n", med, min, max);
bubble_sort(t, n);
printf("Média das temperaturas acima da média: %.3lf\n", media_acima_media(med, t, n));
int aux[20];
popular_aux(aux, t, n);
double max_aux = histograma(aux, t, n);
histograma_vertical(max_aux, aux);
/* escreva a maior parte de seu código aqui */
return 0;
}
void bubble_sort(double t[], int n){
double aux = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (t[j] > t[j + 1]) {
aux = t[j];
t[j] = t[j + 1];
t[j + 1] = aux;
}
}
}
}
double media_acima_media(double med, double t[], int n){
double soma = 0;
int c = 0;
for(int i = 0; i < n; i++){
if(t[i] > med){
soma += t[i];
c++;
}
}
return soma / c;
}
void popular_aux(int aux[20], double t[], int n){
double passo = (t[n - 1] - t[0]) / 20, min = t[0];
int j = 0;
for(int i = 0; i < 20; i++){
double max = min + passo * (i + 1);
while(t[j] < max){
aux[i]++;
j++;
}
printf("aux[%d] = %d\n", i, aux[i]);
}
}
double histograma(int aux[20], double t[], int n){
double passo = (t[n - 1] - t[0]) / 20, min = t[0], max_aux = 0;
for(int j = 0; j < 20; j++){
double ast = aux[j] / 122.0;
double max = min + passo;
if(ast > max_aux)
max_aux = ast;
printf("Temperaturas entre %06.3lf e %06.3lf: ", min, max);
while(ast-- > 0)
printf("*");
printf("\n");
min = max;
}
return max_aux;
}
void histograma_vertical(double max_aux, int aux[20]){
printf("Histograma na vertical:\n");
for(double j = max_aux; j > 0; j--){
for(int i = 0; i < 20; i++){
printf(j <= (aux[i] + 121) / 122 ? "*" : " ");
}
printf("\n");
}
}
| 3.46875 | 3 |
2024-11-18T22:25:14.025123+00:00 | 2017-04-17T10:06:51 | 728e6cf3846478b994ecdc98291cd15e6901e8a2 | {
"blob_id": "728e6cf3846478b994ecdc98291cd15e6901e8a2",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-17T10:06:51",
"content_id": "fd3e812956cd0bb249d98eb6c362dd39819a53d9",
"detected_licenses": [
"MIT"
],
"directory_id": "bd71a5b18673a7ec58d6d50113539781f4de31a5",
"extension": "c",
"filename": "user_main.c",
"fork_events_count": 0,
"gha_created_at": "2017-04-17T10:06:51",
"gha_event_created_at": "2017-04-17T10:06:52",
"gha_language": null,
"gha_license_id": null,
"github_id": 88496231,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4050,
"license": "MIT",
"license_type": "permissive",
"path": "/user/user_main.c",
"provenance": "stackv2-0115.json.gz:113559",
"repo_name": "bryant1410/ws2812esp8266",
"revision_date": "2017-04-17T10:06:51",
"revision_id": "57710f48f21a50bc9bdc8d9ff0f73c2132ab8743",
"snapshot_id": "c2b9834845687a8705dc8d620fc4747498f8666e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/bryant1410/ws2812esp8266/57710f48f21a50bc9bdc8d9ff0f73c2132ab8743/user/user_main.c",
"visit_date": "2021-01-19T20:12:31.516997"
} | stackv2 | #include "mem.h"
#include "c_types.h"
#include "user_interface.h"
#include "ets_sys.h"
#include "driver/uart.h"
#include "osapi.h"
#include "espconn.h"
#include "mystuff.h"
#define PORT 7777
#define SERVER_TIMEOUT 1500
#define MAX_CONNS 5
#define MAX_FRAME 2000
#define procTaskPrio 0
#define procTaskQueueLen 1
static volatile os_timer_t some_timer;
static struct espconn *pUdpServer;
void user_rf_pre_init(void)
{
//nothing.
}
char * strcat( char * dest, char * src )
{
return strcat(dest, src );
}
//Tasks that happen all the time.
os_event_t procTaskQueue[procTaskQueueLen];
static uint8_t printed_ip = 0;
static void ICACHE_FLASH_ATTR
procTask(os_event_t *events)
{
system_os_post(procTaskPrio, 0, 0 );
if( events->sig == 0 && events->par == 0 )
{
//Idle Event.
struct station_config wcfg;
char stret[256];
char *stt = &stret[0];
struct ip_info ipi;
int stat = wifi_station_get_connect_status();
// printf( "STAT: %d\n", stat );
if( stat == STATION_WRONG_PASSWORD || stat == STATION_NO_AP_FOUND || stat == STATION_CONNECT_FAIL )
{
wifi_set_opmode_current( 2 );
stt += ets_sprintf( stt, "Connection failed: %d\n", stat );
uart0_sendStr(stret);
}
if( stat == STATION_GOT_IP && !printed_ip )
{
wifi_station_get_config( &wcfg );
wifi_get_ip_info(0, &ipi);
stt += ets_sprintf( stt, "STAT: %d\n", stat );
stt += ets_sprintf( stt, "IP: %d.%d.%d.%d\n", (ipi.ip.addr>>0)&0xff,(ipi.ip.addr>>8)&0xff,(ipi.ip.addr>>16)&0xff,(ipi.ip.addr>>24)&0xff );
stt += ets_sprintf( stt, "NM: %d.%d.%d.%d\n", (ipi.netmask.addr>>0)&0xff,(ipi.netmask.addr>>8)&0xff,(ipi.netmask.addr>>16)&0xff,(ipi.netmask.addr>>24)&0xff );
stt += ets_sprintf( stt, "GW: %d.%d.%d.%d\n", (ipi.gw.addr>>0)&0xff,(ipi.gw.addr>>8)&0xff,(ipi.gw.addr>>16)&0xff,(ipi.gw.addr>>24)&0xff );
stt += ets_sprintf( stt, "WCFG: /%s/%s/\n", wcfg.ssid, wcfg.password );
uart0_sendStr(stret);
printed_ip = 1;
}
}
}
//Timer event.
static void ICACHE_FLASH_ATTR
myTimer(void *arg)
{
uart0_sendStr(".");
}
//Called when new packet comes in.
static void ICACHE_FLASH_ATTR
udpserver_recv(void *arg, char *pusrdata, unsigned short len)
{
struct espconn *pespconn = (struct espconn *)arg;
uint8_t buffer[MAX_FRAME];
//Seems to be optional, still can cause crashes.
ets_wdt_disable();
WS2812OutBuffer( pusrdata, len );
ets_sprintf( buffer, "%03x", len );
uart0_sendStr(buffer);
}
void ICACHE_FLASH_ATTR charrx( uint8_t c )
{
//Called from UART.
}
void user_init(void)
{
uart_init(BIT_RATE_115200, BIT_RATE_115200);
int wifiMode = wifi_get_opmode();
uart0_sendStr("\r\nCustom Server\r\n");
wifi_set_opmode( 2 ); //We broadcast our ESSID, wait for peopel to join.
/*
struct station_config stationConf;
wifi_set_opmode( 1 ); //We broadcast our ESSID, wait for peopel to join.
os_memcpy(&stationConf.ssid, "xxx", ets_strlen( "xxx" ) + 1);
os_memcpy(&stationConf.password, "yyy", ets_strlen( "yyy" ) + 1);
wifi_set_opmode( 1 );
wifi_station_set_config(&stationConf);
wifi_station_connect();**/
pUdpServer = (struct espconn *)os_zalloc(sizeof(struct espconn));
ets_memset( pUdpServer, 0, sizeof( struct espconn ) );
espconn_create( pUdpServer );
pUdpServer->type = ESPCONN_UDP;
pUdpServer->proto.udp = (esp_udp *)os_zalloc(sizeof(esp_udp));
pUdpServer->proto.udp->local_port = 7777;
espconn_regist_recvcb(pUdpServer, udpserver_recv);
/* wifi_station_dhcpc_start();
*/
if( espconn_create( pUdpServer ) )
{
while(1) { uart0_sendStr( "\r\nFAULT\r\n" ); }
}
char outbuffer[] = { 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,0xff,0xff, 0x00,0xff,0x00 };
WS2812OutBuffer( outbuffer, 1 ); //Initialize the output.
//Add a process
system_os_task(procTask, procTaskPrio, procTaskQueue, procTaskQueueLen);
uart0_sendStr("\r\nBooting\r\n");
WS2812OutBuffer( outbuffer, sizeof(outbuffer) );
//Timer example
os_timer_disarm(&some_timer);
os_timer_setfn(&some_timer, (os_timer_func_t *)myTimer, NULL);
os_timer_arm(&some_timer, 100, 1);
system_os_post(procTaskPrio, 0, 0 );
}
| 2.0625 | 2 |
2024-11-18T22:25:14.398253+00:00 | 2020-08-25T07:26:30 | 59c584ffb5ec9387932fe624886e5f4cc76e363c | {
"blob_id": "59c584ffb5ec9387932fe624886e5f4cc76e363c",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-25T07:26:30",
"content_id": "dd1b9c782a5fe339a19a06c1b21fa4dcaa7d717b",
"detected_licenses": [
"MIT"
],
"directory_id": "b8b0d4a05c01bd86f30e4a4110cad307bea8bf2c",
"extension": "c",
"filename": "hd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 290144594,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2934,
"license": "MIT",
"license_type": "permissive",
"path": "/in/dev/blk/hd/hd.c",
"provenance": "stackv2-0115.json.gz:114080",
"repo_name": "Daliji/Diers",
"revision_date": "2020-08-25T07:26:30",
"revision_id": "17ae90453827768e9949c96e9a9fcd7f601bccda",
"snapshot_id": "e84e971c5e15084fe8a3f02c38f289169a6ea566",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/Daliji/Diers/17ae90453827768e9949c96e9a9fcd7f601bccda/in/dev/blk/hd/hd.c",
"visit_date": "2022-12-04T07:16:38.540869"
} | stackv2 | #include<lib/io.h>
#include<int/int.h>
#include<dev/blk.h>
#include"hd.h"
void (*hd_intr)()=0;
blk_request *cur_blk_request=0;
int hd_reset=0;
hd_request *hd_queue=0;//请求项队列
hd_request *CURRENT_HD_REQUEST=0;//当前请求项
hd_info hd_i[MAX_BLK];
int do_hd_request()
{
hd_ctrl ctrl;
REPEAT:
if(hd_queue==0){
insert_hd_request(CURRENT_HD_REQUEST);
goto REPEAT;
}
if(check_busy())return -1;
if(!check_ready())return -2;
ctrl.ctrl=hd_i[CURRENT_HD_REQUEST->hd_info].ctrl;
ctrl.start_cir=hd_i[CURRENT_HD_REQUEST->hd_info].wpcom;
if(CURRENT_HD_REQUEST->cmd==0)send_ctrl(&ctrl,&hd_readintr);
/*
*cur_blk_request=b;
*if(check_busy())return -1;//检测控制器空闲状态
*if(!check_ready())return -2;//检测驱动器是否就绪
*if(b->cmd==0)send_ctrl(b->ctrl,&hd_readintr);
*else send_ctrl(b->ctrl,&hd_writeintr);
*/
}
int check_busy()
{
int tmp=G_TIME;
while(inb_p(HD_STATUS)&0x80){
tmp--;
if(tmp<=0){
return 1;//忙碌
}
}
return 0;//空闲
}
int check_ready()
{
int tmp=G_TIME;
while(inb_p(HD_STATUS)&0x40){
tmp--;
if(tmp<=0){
return 0;//未就绪
}
}
return 1;//就绪
}
void send_ctrl(hd_ctrl *ctrl,void (*hdintr)())
{
//0x3f6
hd_intr=hdintr;
outb_p(HD_CMD,ctrl->ctrl);
outb_p(HD_ERROR,ctrl->start_cir>>2);
outb_p(HD_NSECTOR,ctrl->sec_num);
outb_p(HD_SECTOR,ctrl->start_sec);
outb_p(HD_LCYL,ctrl->cir_low);
outb_p(HD_HCYL,ctrl->cir_high);
outb_p(HD_CURRENT,dev_num);
outb_p(HD_COMMAND,ctrl->command);
}
int check_op_success()
{
if(inb_p(HD_STATUS)&0x01)return 0;
return 1;
}
void hd_readintr()
{
if(!check_op_success()){
bad_rw_intr();
reset_hd();
}
port_read(HD_DATA,cur_blk_request->buf,256);
cur_blk_request->errors=0;
//不是一次性读完?为什么还要设置并且中断?
cur_blk_request->buf+=512;
cur_blk_request->ctrl->sec_num--;
cur_blk_request->ctrl->start_sec++;
if(cur_blk_request->ctrl->sec_num){
hd_intr=&hd_readintr;
return;
}
end_request(1);
do_hd_request();
}
void hd_writeintr()
{
if(!check_op_success()){
bad_rw_intr();
reset_hd();
}
port_write(HD_DATA,cur_blk_request->buf,256);
cur_blk_request->buf+=512;
cur_blk_request->errors=0;
cur_blk_request->ctrl->sec_num--;
cur_blk_request->ctrl->start_sec++;
if(cur_blk_request->ctrl->sec_num){
hd_intr=&hd_writeintr;
return;
}
end_request(1);
do_hd_request();
}
void reset_hd()
{
int i;
if(!hd_reset)return;
hd_reset=0;
outb_p(HD_CMD,0x04);
for(i=0;i<1000;i++);
outb_p(HD_CMD,cur_blk_request->ctrl->ctrl);
}
void bad_rw_intr()
{
if(++cur_blk_request->errors>=10){
printk("bad hardisk operate.\n");
end_request(0);
}
if(cur_blk_request->errors>=3){
reset=1;
}
}
void _hd_interrupt();
void hd_init()
{
set_intr_gate(0x2e,&_hd_interrupt);
outb(inb_p(0x21)&0xfb,0x21);
outb(inb_p(0xa1)&0xbf,0xa1);
}
| 2.28125 | 2 |
2024-11-18T22:25:14.602475+00:00 | 2023-07-18T13:09:22 | 33deb601310fe3bbd3ac1241bf1fa154bed29941 | {
"blob_id": "33deb601310fe3bbd3ac1241bf1fa154bed29941",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-18T13:09:22",
"content_id": "ca1255a2adb59933bd1933966f2cbf045cbe43fe",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "4415ce9a620a87f91fd28fbef324321503c98ac8",
"extension": "c",
"filename": "main_rangeSensor.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 304455461,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1238,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/Exercises/Exercise5/main_rangeSensor.c",
"provenance": "stackv2-0115.json.gz:114210",
"repo_name": "mathworks/student-competition-code-generation-training",
"revision_date": "2023-07-18T13:09:22",
"revision_id": "5255d0715e79ddca6a5d028650983af13d963cf1",
"snapshot_id": "ca1ae75ddbb8c26b0cc0bd220ee8d409932fe615",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/mathworks/student-competition-code-generation-training/5255d0715e79ddca6a5d028650983af13d963cf1/Exercises/Exercise5/main_rangeSensor.c",
"visit_date": "2023-07-20T12:47:09.528333"
} | stackv2 | #include <stddef.h>
#include <stdio.h> /* This ert_main.c example uses printf/fflush */
#include "rangeSensor.h" /* Model's header file */
#include "rtwtypes.h"
int_T main(int_T argc, const char *argv[])
{
/* For file reading */
FILE *f;
char str[30];
/* Entry-point I/O */
double time;
double sensShort;
double sensLong;
double sensFused;
/* Timing counter */
int counter;
/* Initialize */
counter = 0;
rangeSensor_initialize();
f = fopen("rangeSensorData.txt","r");
/* Main loop */
while(!feof(f)) {
/* Read a line from the file */
fgets(str,30,f);
sscanf(str,"%lf,%lf,%lf",&time,&rangeSensor_U.sensShort,&rangeSensor_U.sensLong);
/* Call generated code, with timing */
rangeSensor_step0();
if (counter == 0) {
rangeSensor_step1();
}
counter++;
if (counter == 5) {
counter = 0;
}
/* Print results */
printf("Time: %f, Inputs: [%f %f], Output: %f\n",
time, rangeSensor_U.sensShort,
rangeSensor_U.sensLong, rangeSensor_Y.sensFused);
}
/* Terminate model */
rangeSensor_terminate();
fclose(f);
return 0;
} | 2.4375 | 2 |
2024-11-18T22:25:14.983670+00:00 | 2019-09-14T11:56:04 | bba0cdd45de5005270d76db2884e1bb97f9cdc04 | {
"blob_id": "bba0cdd45de5005270d76db2884e1bb97f9cdc04",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-14T11:56:04",
"content_id": "6d9f8972165d18ad55c78ae909dbf306a81e66a3",
"detected_licenses": [
"MIT"
],
"directory_id": "935805a4f18c852b82a7900990048d29e2fbc754",
"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": 152055934,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2076,
"license": "MIT",
"license_type": "permissive",
"path": "/stage1/boot.c",
"provenance": "stackv2-0115.json.gz:114466",
"repo_name": "PolyB/toy-bootloader",
"revision_date": "2019-09-14T11:56:04",
"revision_id": "76d9a3694fc8eb0ac145ae2173a9053cf855c4f0",
"snapshot_id": "95895a270559aad8aed47d51815de2754cc9e632",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PolyB/toy-bootloader/76d9a3694fc8eb0ac145ae2173a9053cf855c4f0/stage1/boot.c",
"visit_date": "2020-03-31T08:24:50.400186"
} | stackv2 | #include <stdint.h>
#include <stddef.h>
#include "shared/disk_props.h"
// 16bit real mode
extern uint8_t drive_number; // defined in boot_asm.s
// this function is used only to load stage2
void copy_kernel(uint8_t index, uint8_t count, void* dest)
{
uint16_t tries = 3;
uint16_t ax;
uint8_t c = 0;
uint8_t h = 0;
uint8_t s = index + 1;
if (max_head_number)
{
c = index / (max_head_number * max_sector_number);
h = (index / max_sector_number) % max_head_number;
s = (index % max_sector_number) + 1;
}
do
{
__asm__ volatile("mov %%ax, %%es; int $0x13" : "=a"(ax) :"a"(0), "d"(drive_number):"memory");
__asm__ volatile ("int $0x13" : "=a"(ax) :
"a"(0x0200 | count), // fun & count
"d"((uint16_t)h << 8 | drive_number), // head & drive number
"c"(((c & 0xFF) << 8) | (c & 0x300)>>2 | (s & 0x3f)), // cylinder & starting sector number
"b"(dest)
: "cc", "memory");
} while (--tries && (ax & 0xFF00));
if (!tries)
{
// TODO error
}
}
extern char _content_start; // linker variable
extern char _stage_2_first_section_index; // linker variable
extern char _stage_2_load_count; // linker variable
extern char _stage_3_first_section_index; // linker variable
extern char _stage_3_load_count; // linker variable
extern char _shared_start; // linker variable
extern char _shared_first_section_index; // linker variable
extern char _shared_load_count; // linker variable
void stage2_load(void); // stage2/load.c
void __attribute__((noreturn)) stage3_start(void); // stage3/start.s
void __attribute__((noreturn)) init(void)
{
copy_kernel((size_t)&_shared_first_section_index, (size_t)&_shared_load_count, &_shared_start);
copy_kernel((size_t)&_stage_2_first_section_index, (size_t)&_stage_2_load_count, &_content_start);
stage2_load();
copy_kernel((size_t)&_stage_3_first_section_index, (size_t)&_stage_3_load_count, &_content_start);
stage3_start();
}
| 2.234375 | 2 |
2024-11-18T22:25:15.430878+00:00 | 2016-02-29T18:25:53 | c384869335340f036c3bade846aba31e77faaf4a | {
"blob_id": "c384869335340f036c3bade846aba31e77faaf4a",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-29T18:25:53",
"content_id": "77a7cd78118ccbbc83e6b42dbcb612765b884732",
"detected_licenses": [
"BSD-3-Clause",
"Apache-2.0"
],
"directory_id": "299b377022f52b20e3c9696950da9007e9b078a4",
"extension": "h",
"filename": "SparseMatrix.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 19929637,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16943,
"license": "BSD-3-Clause,Apache-2.0",
"license_type": "permissive",
"path": "/include/El/core/SparseMatrix.h",
"provenance": "stackv2-0115.json.gz:114724",
"repo_name": "sg0/Elemental",
"revision_date": "2016-02-29T18:25:53",
"revision_id": "614f02509690449b553451e36bc78e7e132ea517",
"snapshot_id": "43cba65d001de299167363c349127cf8c23f7403",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sg0/Elemental/614f02509690449b553451e36bc78e7e132ea517/include/El/core/SparseMatrix.h",
"visit_date": "2021-01-15T09:33:56.394836"
} | stackv2 | /*
Copyright (c) 2009-2015, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef EL_SPARSEMATRIX_C_H
#define EL_SPARSEMATRIX_C_H
#ifdef __cplusplus
extern "C" {
#endif
/* An anonymous struct meant as a placeholder for SparseMatrix<T>
-------------------------------------------------------------- */
typedef struct ElSparseMatrix_iDummy* ElSparseMatrix_i;
typedef struct ElSparseMatrix_sDummy* ElSparseMatrix_s;
typedef struct ElSparseMatrix_dDummy* ElSparseMatrix_d;
typedef struct ElSparseMatrix_cDummy* ElSparseMatrix_c;
typedef struct ElSparseMatrix_zDummy* ElSparseMatrix_z;
typedef const struct ElSparseMatrix_iDummy* ElConstSparseMatrix_i;
typedef const struct ElSparseMatrix_sDummy* ElConstSparseMatrix_s;
typedef const struct ElSparseMatrix_dDummy* ElConstSparseMatrix_d;
typedef const struct ElSparseMatrix_cDummy* ElConstSparseMatrix_c;
typedef const struct ElSparseMatrix_zDummy* ElConstSparseMatrix_z;
/* Constructors and destructors
============================ */
/* SparseMatrix<T>::SparseMatrix()
------------------------------- */
EL_EXPORT ElError ElSparseMatrixCreate_i( ElSparseMatrix_i* A );
EL_EXPORT ElError ElSparseMatrixCreate_s( ElSparseMatrix_s* A );
EL_EXPORT ElError ElSparseMatrixCreate_d( ElSparseMatrix_d* A );
EL_EXPORT ElError ElSparseMatrixCreate_c( ElSparseMatrix_c* A );
EL_EXPORT ElError ElSparseMatrixCreate_z( ElSparseMatrix_z* A );
/* SparseMatrix<T>::~SparseMatrix()
-------------------------------- */
EL_EXPORT ElError ElSparseMatrixDestroy_i( ElConstSparseMatrix_i A );
EL_EXPORT ElError ElSparseMatrixDestroy_s( ElConstSparseMatrix_s A );
EL_EXPORT ElError ElSparseMatrixDestroy_d( ElConstSparseMatrix_d A );
EL_EXPORT ElError ElSparseMatrixDestroy_c( ElConstSparseMatrix_c A );
EL_EXPORT ElError ElSparseMatrixDestroy_z( ElConstSparseMatrix_z A );
/* Assignment and reconfiguration
============================== */
/* void SparseMatrix<T>::Empty()
----------------------------- */
EL_EXPORT ElError ElSparseMatrixEmpty_i( ElSparseMatrix_i A );
EL_EXPORT ElError ElSparseMatrixEmpty_s( ElSparseMatrix_s A );
EL_EXPORT ElError ElSparseMatrixEmpty_d( ElSparseMatrix_d A );
EL_EXPORT ElError ElSparseMatrixEmpty_c( ElSparseMatrix_c A );
EL_EXPORT ElError ElSparseMatrixEmpty_z( ElSparseMatrix_z A );
/* void SparseMatrix<T>::Resize( Int height, Int width )
----------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixResize_i
( ElSparseMatrix_i A, ElInt height, ElInt width );
EL_EXPORT ElError ElSparseMatrixResize_s
( ElSparseMatrix_s A, ElInt height, ElInt width );
EL_EXPORT ElError ElSparseMatrixResize_d
( ElSparseMatrix_d A, ElInt height, ElInt width );
EL_EXPORT ElError ElSparseMatrixResize_c
( ElSparseMatrix_c A, ElInt height, ElInt width );
EL_EXPORT ElError ElSparseMatrixResize_z
( ElSparseMatrix_z A, ElInt height, ElInt width );
/* void SparseMatrix<T>::Reserve( Int numEntries )
----------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixReserve_i
( ElSparseMatrix_i A, ElInt numEntries );
EL_EXPORT ElError ElSparseMatrixReserve_s
( ElSparseMatrix_s A, ElInt numEntries );
EL_EXPORT ElError ElSparseMatrixReserve_d
( ElSparseMatrix_d A, ElInt numEntries );
EL_EXPORT ElError ElSparseMatrixReserve_c
( ElSparseMatrix_c A, ElInt numEntries );
EL_EXPORT ElError ElSparseMatrixReserve_z
( ElSparseMatrix_z A, ElInt numEntries );
/* void SparseMatrix<T>::Update( Int row, Int col, T value )
--------------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixUpdate_i
( ElSparseMatrix_i A, ElInt row, ElInt col, ElInt value );
EL_EXPORT ElError ElSparseMatrixUpdate_s
( ElSparseMatrix_s A, ElInt row, ElInt col, float value );
EL_EXPORT ElError ElSparseMatrixUpdate_d
( ElSparseMatrix_d A, ElInt row, ElInt col, double value );
EL_EXPORT ElError ElSparseMatrixUpdate_c
( ElSparseMatrix_c A, ElInt row, ElInt col, complex_float value );
EL_EXPORT ElError ElSparseMatrixUpdate_z
( ElSparseMatrix_z A, ElInt row, ElInt col, complex_double value );
/* void SparseMatrix<T>::Zero( Int row, Int col )
---------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixZero_i
( ElSparseMatrix_i A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixZero_s
( ElSparseMatrix_s A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixZero_d
( ElSparseMatrix_d A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixZero_c
( ElSparseMatrix_c A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixZero_z
( ElSparseMatrix_z A, ElInt row, ElInt col );
/* void SparseMatrix<T>::QueueUpdate( Int row, Int col, T value )
-------------------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixQueueUpdate_i
( ElSparseMatrix_i A, ElInt row, ElInt col, ElInt value );
EL_EXPORT ElError ElSparseMatrixQueueUpdate_s
( ElSparseMatrix_s A, ElInt row, ElInt col, float value );
EL_EXPORT ElError ElSparseMatrixQueueUpdate_d
( ElSparseMatrix_d A, ElInt row, ElInt col, double value );
EL_EXPORT ElError ElSparseMatrixQueueUpdate_c
( ElSparseMatrix_c A, ElInt row, ElInt col, complex_float value );
EL_EXPORT ElError ElSparseMatrixQueueUpdate_z
( ElSparseMatrix_z A, ElInt row, ElInt col, complex_double value );
/* void SparseMatrix<T>::QueueZero( Int row, Int col )
--------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixQueueZero_i
( ElSparseMatrix_i A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixQueueZero_s
( ElSparseMatrix_s A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixQueueZero_d
( ElSparseMatrix_d A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixQueueZero_c
( ElSparseMatrix_c A, ElInt row, ElInt col );
EL_EXPORT ElError ElSparseMatrixQueueZero_z
( ElSparseMatrix_z A, ElInt row, ElInt col );
/* void SparseMatrix<T>::MakeConsistent()
-------------------------------------- */
EL_EXPORT ElError ElSparseMatrixMakeConsistent_i( ElSparseMatrix_i A );
EL_EXPORT ElError ElSparseMatrixMakeConsistent_s( ElSparseMatrix_s A );
EL_EXPORT ElError ElSparseMatrixMakeConsistent_d( ElSparseMatrix_d A );
EL_EXPORT ElError ElSparseMatrixMakeConsistent_c( ElSparseMatrix_c A );
EL_EXPORT ElError ElSparseMatrixMakeConsistent_z( ElSparseMatrix_z A );
/* Queries
======= */
/* Int SparseMatrix<T>::Height() const
----------------------------------- */
EL_EXPORT ElError ElSparseMatrixHeight_i
( ElConstSparseMatrix_i A, ElInt* height );
EL_EXPORT ElError ElSparseMatrixHeight_s
( ElConstSparseMatrix_s A, ElInt* height );
EL_EXPORT ElError ElSparseMatrixHeight_d
( ElConstSparseMatrix_d A, ElInt* height );
EL_EXPORT ElError ElSparseMatrixHeight_c
( ElConstSparseMatrix_c A, ElInt* height );
EL_EXPORT ElError ElSparseMatrixHeight_z
( ElConstSparseMatrix_z A, ElInt* height );
/* Int SparseMatrix<T>::Width() const
---------------------------------- */
EL_EXPORT ElError ElSparseMatrixWidth_i
( ElConstSparseMatrix_i A, ElInt* width );
EL_EXPORT ElError ElSparseMatrixWidth_s
( ElConstSparseMatrix_s A, ElInt* width );
EL_EXPORT ElError ElSparseMatrixWidth_d
( ElConstSparseMatrix_d A, ElInt* width );
EL_EXPORT ElError ElSparseMatrixWidth_c
( ElConstSparseMatrix_c A, ElInt* width );
EL_EXPORT ElError ElSparseMatrixWidth_z
( ElConstSparseMatrix_z A, ElInt* width );
/* Int SparseMatrix<T>::NumEntries() const
--------------------------------------- */
EL_EXPORT ElError ElSparseMatrixNumEntries_i
( ElConstSparseMatrix_i A, ElInt* numEntries );
EL_EXPORT ElError ElSparseMatrixNumEntries_s
( ElConstSparseMatrix_s A, ElInt* numEntries );
EL_EXPORT ElError ElSparseMatrixNumEntries_d
( ElConstSparseMatrix_d A, ElInt* numEntries );
EL_EXPORT ElError ElSparseMatrixNumEntries_c
( ElConstSparseMatrix_c A, ElInt* numEntries );
EL_EXPORT ElError ElSparseMatrixNumEntries_z
( ElConstSparseMatrix_z A, ElInt* numEntries );
/* Int SparseMatrix<T>::Capacity() const
------------------------------------- */
EL_EXPORT ElError ElSparseMatrixCapacity_i
( ElConstSparseMatrix_i A, ElInt* capacity );
EL_EXPORT ElError ElSparseMatrixCapacity_s
( ElConstSparseMatrix_s A, ElInt* capacity );
EL_EXPORT ElError ElSparseMatrixCapacity_d
( ElConstSparseMatrix_d A, ElInt* capacity );
EL_EXPORT ElError ElSparseMatrixCapacity_c
( ElConstSparseMatrix_c A, ElInt* capacity );
EL_EXPORT ElError ElSparseMatrixCapacity_z
( ElConstSparseMatrix_z A, ElInt* capacity );
/* bool SparseMatrix<T>::Consistent() const
---------------------------------------- */
EL_EXPORT ElError ElSparseMatrixConsistent_i
( ElConstSparseMatrix_i A, bool* consistent );
EL_EXPORT ElError ElSparseMatrixConsistent_s
( ElConstSparseMatrix_s A, bool* consistent );
EL_EXPORT ElError ElSparseMatrixConsistent_d
( ElConstSparseMatrix_d A, bool* consistent );
EL_EXPORT ElError ElSparseMatrixConsistent_c
( ElConstSparseMatrix_c A, bool* consistent );
EL_EXPORT ElError ElSparseMatrixConsistent_z
( ElConstSparseMatrix_z A, bool* consistent );
/* Graph& SparseMatrix<T>::Graph()
------------------------------- */
EL_EXPORT ElError ElSparseMatrixGraph_i( ElSparseMatrix_i A, ElGraph* graph );
EL_EXPORT ElError ElSparseMatrixGraph_s( ElSparseMatrix_s A, ElGraph* graph );
EL_EXPORT ElError ElSparseMatrixGraph_d( ElSparseMatrix_d A, ElGraph* graph );
EL_EXPORT ElError ElSparseMatrixGraph_c( ElSparseMatrix_c A, ElGraph* graph );
EL_EXPORT ElError ElSparseMatrixGraph_z( ElSparseMatrix_z A, ElGraph* graph );
/* const Graph& SparseMatrix<T>::LockedGraph() const
------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixLockedGraph_i
( ElConstSparseMatrix_i A, ElConstGraph* graph );
EL_EXPORT ElError ElSparseMatrixLockedGraph_s
( ElConstSparseMatrix_s A, ElConstGraph* graph );
EL_EXPORT ElError ElSparseMatrixLockedGraph_d
( ElConstSparseMatrix_d A, ElConstGraph* graph );
EL_EXPORT ElError ElSparseMatrixLockedGraph_c
( ElConstSparseMatrix_c A, ElConstGraph* graph );
EL_EXPORT ElError ElSparseMatrixLockedGraph_z
( ElConstSparseMatrix_z A, ElConstGraph* graph );
/* Int SparseMatrix<T>::Row( Int index ) const
------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixRow_i
( ElConstSparseMatrix_i A, ElInt index, ElInt* row );
EL_EXPORT ElError ElSparseMatrixRow_s
( ElConstSparseMatrix_s A, ElInt index, ElInt* row );
EL_EXPORT ElError ElSparseMatrixRow_d
( ElConstSparseMatrix_d A, ElInt index, ElInt* row );
EL_EXPORT ElError ElSparseMatrixRow_c
( ElConstSparseMatrix_c A, ElInt index, ElInt* row );
EL_EXPORT ElError ElSparseMatrixRow_z
( ElConstSparseMatrix_z A, ElInt index, ElInt* row );
/* Int SparseMatrix<T>::Col( Int index ) const
------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixCol_i
( ElConstSparseMatrix_i A, ElInt index, ElInt* col );
EL_EXPORT ElError ElSparseMatrixCol_s
( ElConstSparseMatrix_s A, ElInt index, ElInt* col );
EL_EXPORT ElError ElSparseMatrixCol_d
( ElConstSparseMatrix_d A, ElInt index, ElInt* col );
EL_EXPORT ElError ElSparseMatrixCol_c
( ElConstSparseMatrix_c A, ElInt index, ElInt* col );
EL_EXPORT ElError ElSparseMatrixCol_z
( ElConstSparseMatrix_z A, ElInt index, ElInt* col );
/* T SparseMatrix<T>::Value( Int index ) const
------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixValue_i
( ElConstSparseMatrix_i A, ElInt index, ElInt* value );
EL_EXPORT ElError ElSparseMatrixValue_s
( ElConstSparseMatrix_s A, ElInt index, float* value );
EL_EXPORT ElError ElSparseMatrixValue_d
( ElConstSparseMatrix_d A, ElInt index, double* value );
EL_EXPORT ElError ElSparseMatrixValue_c
( ElConstSparseMatrix_c A, ElInt index, complex_float* value );
EL_EXPORT ElError ElSparseMatrixValue_z
( ElConstSparseMatrix_z A, ElInt index, complex_double* value );
/* Int SparseMatrix<T>::EntryOffset( Int row ) const
------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixEntryOffset_i
( ElConstSparseMatrix_i A, ElInt row, ElInt* entryOffset );
EL_EXPORT ElError ElSparseMatrixEntryOffset_s
( ElConstSparseMatrix_s A, ElInt row, ElInt* entryOffset );
EL_EXPORT ElError ElSparseMatrixEntryOffset_d
( ElConstSparseMatrix_d A, ElInt row, ElInt* entryOffset );
EL_EXPORT ElError ElSparseMatrixEntryOffset_c
( ElConstSparseMatrix_c A, ElInt row, ElInt* entryOffset );
EL_EXPORT ElError ElSparseMatrixEntryOffset_z
( ElConstSparseMatrix_z A, ElInt row, ElInt* entryOffset );
/* Int SparseMatrix<T>::NumConnections( Int row ) const
---------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixNumConnections_i
( ElConstSparseMatrix_i A, ElInt row, ElInt* numConnections );
EL_EXPORT ElError ElSparseMatrixNumConnections_s
( ElConstSparseMatrix_s A, ElInt row, ElInt* numConnections );
EL_EXPORT ElError ElSparseMatrixNumConnections_d
( ElConstSparseMatrix_d A, ElInt row, ElInt* numConnections );
EL_EXPORT ElError ElSparseMatrixNumConnections_c
( ElConstSparseMatrix_c A, ElInt row, ElInt* numConnections );
EL_EXPORT ElError ElSparseMatrixNumConnections_z
( ElConstSparseMatrix_z A, ElInt row, ElInt* numConnections );
/* Int* SparseMatrix<T>::SourceBuffer()
------------------------------------ */
EL_EXPORT ElError ElSparseMatrixSourceBuffer_i
( ElSparseMatrix_i A, ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixSourceBuffer_s
( ElSparseMatrix_s A, ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixSourceBuffer_d
( ElSparseMatrix_d A, ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixSourceBuffer_c
( ElSparseMatrix_c A, ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixSourceBuffer_z
( ElSparseMatrix_z A, ElInt** sourceBuffer );
/* const Int* SparseMatrix<T>::LockedSourceBuffer() const
------------------------------------------------------ */
EL_EXPORT ElError ElSparseMatrixLockedSourceBuffer_i
( ElConstSparseMatrix_i A, const ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixLockedSourceBuffer_s
( ElConstSparseMatrix_s A, const ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixLockedSourceBuffer_d
( ElConstSparseMatrix_d A, const ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixLockedSourceBuffer_c
( ElConstSparseMatrix_c A, const ElInt** sourceBuffer );
EL_EXPORT ElError ElSparseMatrixLockedSourceBuffer_z
( ElConstSparseMatrix_z A, const ElInt** sourceBuffer );
/* Int* SparseMatrix<T>::TargetBuffer()
------------------------------------ */
EL_EXPORT ElError ElSparseMatrixTargetBuffer_i
( ElSparseMatrix_i A, ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixTargetBuffer_s
( ElSparseMatrix_s A, ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixTargetBuffer_d
( ElSparseMatrix_d A, ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixTargetBuffer_c
( ElSparseMatrix_c A, ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixTargetBuffer_z
( ElSparseMatrix_z A, ElInt** targetBuffer );
/* const Int* SparseMatrix<T>::LockedTargetBuffer() const
------------------------------------------------------ */
EL_EXPORT ElError ElSparseMatrixLockedTargetBuffer_i
( ElConstSparseMatrix_i A, const ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixLockedTargetBuffer_s
( ElConstSparseMatrix_s A, const ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixLockedTargetBuffer_d
( ElConstSparseMatrix_d A, const ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixLockedTargetBuffer_c
( ElConstSparseMatrix_c A, const ElInt** targetBuffer );
EL_EXPORT ElError ElSparseMatrixLockedTargetBuffer_z
( ElConstSparseMatrix_z A, const ElInt** targetBuffer );
/* T* SparseMatrix<T>::ValueBuffer()
--------------------------------- */
EL_EXPORT ElError ElSparseMatrixValueBuffer_i
( ElSparseMatrix_i A, ElInt** valueBuffer );
EL_EXPORT ElError ElSparseMatrixValueBuffer_s
( ElSparseMatrix_s A, float** valueBuffer );
EL_EXPORT ElError ElSparseMatrixValueBuffer_d
( ElSparseMatrix_d A, double** valueBuffer );
EL_EXPORT ElError ElSparseMatrixValueBuffer_c
( ElSparseMatrix_c A, complex_float** valueBuffer );
EL_EXPORT ElError ElSparseMatrixValueBuffer_z
( ElSparseMatrix_z A, complex_double** valueBuffer );
/* const T* SparseMatrix<T>::LockedValueBuffer() const
--------------------------------------------------- */
EL_EXPORT ElError ElSparseMatrixLockedValueBuffer_i
( ElConstSparseMatrix_i A, const ElInt** valueBuffer );
EL_EXPORT ElError ElSparseMatrixLockedValueBuffer_s
( ElConstSparseMatrix_s A, const float** valueBuffer );
EL_EXPORT ElError ElSparseMatrixLockedValueBuffer_d
( ElConstSparseMatrix_d A, const double** valueBuffer );
EL_EXPORT ElError ElSparseMatrixLockedValueBuffer_c
( ElConstSparseMatrix_c A, const complex_float** valueBuffer );
EL_EXPORT ElError ElSparseMatrixLockedValueBuffer_z
( ElConstSparseMatrix_z A, const complex_double** valueBuffer );
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* ifndef EL_SPARSEMATRIX_C_H */
| 2.078125 | 2 |
2024-11-18T22:25:15.513997+00:00 | 2018-03-13T22:53:38 | 10b6668aeb9dca40d2fbbccf96abd2ecaa47aac2 | {
"blob_id": "10b6668aeb9dca40d2fbbccf96abd2ecaa47aac2",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-13T22:53:38",
"content_id": "609721340df41840ab89e96c9d299c4cf5fcd88e",
"detected_licenses": [
"MIT"
],
"directory_id": "66ff9c9ec8a66a0d4eb3995a2985215c0e55143f",
"extension": "h",
"filename": "ctype.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 125122093,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1475,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ctype.h",
"provenance": "stackv2-0115.json.gz:114854",
"repo_name": "MikeLankamp/osldr",
"revision_date": "2018-03-13T22:53:38",
"revision_id": "34c2620d924a1a9cd774d6d924d5f004a3611b97",
"snapshot_id": "4cbdaa48004e3aa2316e34920cd2431a8cc734a9",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/MikeLankamp/osldr/34c2620d924a1a9cd774d6d924d5f004a3611b97/src/ctype.h",
"visit_date": "2021-03-30T23:44:19.509910"
} | stackv2 | #ifndef CTYPE_H
#define CTYPE_H
#include <types.h>
extern UCHAR _ctype[ 256 ];
/* Character classes */
#define _IS_UPP 0x0001 /* upper case */
#define _IS_LOW 0x0002 /* lower case */
#define _IS_DIG 0x0004 /* digit */
#define _IS_SP 0x0008 /* space */
#define _IS_PUN 0x0010 /* punctuation */
#define _IS_CTL 0x0020 /* control */
#define _IS_BLK 0x0040 /* blank */
#define _IS_HEX 0x0080 /* [0..9] or [A-F] or [a-f] */
#define _IS_ALPHA (_IS_LOW | _IS_UPP)
#define _IS_ALNUM (_IS_DIG | _IS_ALPHA)
#define _IS_GRAPH (_IS_ALNUM | _IS_HEX | _IS_PUN)
#define isalnum(c) (_ctype[ (UCHAR)(c) ] & (_IS_ALNUM))
#define isalpha(c) (_ctype[ (UCHAR)(c) ] & (_IS_ALPHA))
#define isblank(c) (_ctype[ (UCHAR)(c) ] & (_IS_BLK))
#define iscntrl(c) (_ctype[ (UCHAR)(c) ] & (_IS_CTL))
#define isdigit(c) (_ctype[ (UCHAR)(c) ] & (_IS_DIG))
#define isgraph(c) (_ctype[ (UCHAR)(c) ] & (_IS_GRAPH))
#define islower(c) (_ctype[ (UCHAR)(c) ] & (_IS_LOW))
#define isprint(c) (_ctype[ (UCHAR)(c) ] & (_IS_GRAPH | _IS_BLK))
#define ispunct(c) (_ctype[ (UCHAR)(c) ] & (_IS_PUN))
#define isspace(c) (_ctype[ (UCHAR)(c) ] & (_IS_SP))
#define isupper(c) (_ctype[ (UCHAR)(c) ] & (_IS_UPP))
#define isxdigit(c) (_ctype[ (UCHAR)(c) ] & (_IS_HEX))
#define tolower(c) ((isupper(c)) ? (c) - 'A' + 'a' : (c))
#define toupper(c) ((islower(c)) ? (c) - 'a' + 'A' : (c))
#endif
| 2.4375 | 2 |
2024-11-18T22:25:15.713927+00:00 | 2018-04-03T19:32:58 | 3de5fac8491db86311cf54845cab2cf7cb35c62f | {
"blob_id": "3de5fac8491db86311cf54845cab2cf7cb35c62f",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-04T21:52:18",
"content_id": "c87aaf05c741691a23bc1ece8c0f660c758c53e4",
"detected_licenses": [
"BSD-2-Clause",
"OpenSSL"
],
"directory_id": "509e6324fcbdb25c7ecceeb33caf0ed8fe8c4756",
"extension": "c",
"filename": "DebugPeCoffExtraActionLib.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 103672354,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11055,
"license": "BSD-2-Clause,OpenSSL",
"license_type": "permissive",
"path": "/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.c",
"provenance": "stackv2-0115.json.gz:115241",
"repo_name": "supven01/edk2",
"revision_date": "2018-04-03T19:32:58",
"revision_id": "b75d8c27bb86c5536f83beee97a0587a68fa05b0",
"snapshot_id": "11d7bf5481f68e2ad804f476747720ad3d61c707",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/supven01/edk2/b75d8c27bb86c5536f83beee97a0587a68fa05b0/ArmPkg/Library/DebugPeCoffExtraActionLib/DebugPeCoffExtraActionLib.c",
"visit_date": "2018-09-16T04:37:36.485029"
} | stackv2 | /**@file
Copyright (c) 2006 - 2009, Intel Corporation. All rights reserved.<BR>
Portions copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
Portions copyright (c) 2011 - 2012, ARM Ltd. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <PiDxe.h>
#include <Library/ArmMmuLib.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/PcdLib.h>
#include <Library/PeCoffLib.h>
#include <Library/PeCoffExtraActionLib.h>
#include <Library/PrintLib.h>
typedef RETURN_STATUS (*REGION_PERMISSION_UPDATE_FUNC) (
IN EFI_PHYSICAL_ADDRESS BaseAddress,
IN UINT64 Length
);
STATIC
RETURN_STATUS
UpdatePeCoffPermissions (
IN CONST PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext,
IN REGION_PERMISSION_UPDATE_FUNC NoExecUpdater,
IN REGION_PERMISSION_UPDATE_FUNC ReadOnlyUpdater
)
{
RETURN_STATUS Status;
EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr;
EFI_IMAGE_OPTIONAL_HEADER_UNION HdrData;
UINTN Size;
UINTN ReadSize;
UINT32 SectionHeaderOffset;
UINTN NumberOfSections;
UINTN Index;
EFI_IMAGE_SECTION_HEADER SectionHeader;
PE_COFF_LOADER_IMAGE_CONTEXT TmpContext;
EFI_PHYSICAL_ADDRESS Base;
//
// We need to copy ImageContext since PeCoffLoaderGetImageInfo ()
// will mangle the ImageAddress field
//
CopyMem (&TmpContext, ImageContext, sizeof (TmpContext));
if (TmpContext.PeCoffHeaderOffset == 0) {
Status = PeCoffLoaderGetImageInfo (&TmpContext);
if (RETURN_ERROR (Status)) {
DEBUG ((DEBUG_ERROR,
"%a: PeCoffLoaderGetImageInfo () failed (Status = %r)\n",
__FUNCTION__, Status));
return Status;
}
}
if (TmpContext.IsTeImage &&
TmpContext.ImageAddress == ImageContext->ImageAddress) {
DEBUG ((DEBUG_INFO, "%a: ignoring XIP TE image at 0x%lx\n", __FUNCTION__,
ImageContext->ImageAddress));
return RETURN_SUCCESS;
}
if (TmpContext.SectionAlignment < EFI_PAGE_SIZE) {
//
// The sections need to be at least 4 KB aligned, since that is the
// granularity at which we can tighten permissions. So just clear the
// noexec permissions on the entire region.
//
if (!TmpContext.IsTeImage) {
DEBUG ((DEBUG_WARN,
"%a: non-TE Image at 0x%lx has SectionAlignment < 4 KB (%lu)\n",
__FUNCTION__, ImageContext->ImageAddress, TmpContext.SectionAlignment));
}
Base = ImageContext->ImageAddress & ~(EFI_PAGE_SIZE - 1);
Size = ImageContext->ImageAddress - Base + ImageContext->ImageSize;
return NoExecUpdater (Base, ALIGN_VALUE (Size, EFI_PAGE_SIZE));
}
//
// Read the PE/COFF Header. For PE32 (32-bit) this will read in too much
// data, but that should not hurt anything. Hdr.Pe32->OptionalHeader.Magic
// determines if this is a PE32 or PE32+ image. The magic is in the same
// location in both images.
//
Hdr.Union = &HdrData;
Size = sizeof (EFI_IMAGE_OPTIONAL_HEADER_UNION);
ReadSize = Size;
Status = TmpContext.ImageRead (TmpContext.Handle,
TmpContext.PeCoffHeaderOffset, &Size, Hdr.Pe32);
if (RETURN_ERROR (Status) || (Size != ReadSize)) {
DEBUG ((DEBUG_ERROR,
"%a: TmpContext.ImageRead () failed (Status = %r)\n",
__FUNCTION__, Status));
return Status;
}
ASSERT (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE);
SectionHeaderOffset = TmpContext.PeCoffHeaderOffset + sizeof (UINT32) +
sizeof (EFI_IMAGE_FILE_HEADER);
NumberOfSections = (UINTN)(Hdr.Pe32->FileHeader.NumberOfSections);
switch (Hdr.Pe32->OptionalHeader.Magic) {
case EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC:
SectionHeaderOffset += Hdr.Pe32->FileHeader.SizeOfOptionalHeader;
break;
case EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC:
SectionHeaderOffset += Hdr.Pe32Plus->FileHeader.SizeOfOptionalHeader;
break;
default:
ASSERT (FALSE);
}
//
// Iterate over the sections
//
for (Index = 0; Index < NumberOfSections; Index++) {
//
// Read section header from file
//
Size = sizeof (EFI_IMAGE_SECTION_HEADER);
ReadSize = Size;
Status = TmpContext.ImageRead (TmpContext.Handle, SectionHeaderOffset,
&Size, &SectionHeader);
if (RETURN_ERROR (Status) || (Size != ReadSize)) {
DEBUG ((DEBUG_ERROR,
"%a: TmpContext.ImageRead () failed (Status = %r)\n",
__FUNCTION__, Status));
return Status;
}
Base = TmpContext.ImageAddress + SectionHeader.VirtualAddress;
if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_MEM_EXECUTE) == 0) {
if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_MEM_WRITE) == 0 &&
TmpContext.ImageType != EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) {
DEBUG ((DEBUG_INFO,
"%a: Mapping section %d of image at 0x%lx with RO-XN permissions and size 0x%x\n",
__FUNCTION__, Index, Base, SectionHeader.Misc.VirtualSize));
ReadOnlyUpdater (Base, SectionHeader.Misc.VirtualSize);
} else {
DEBUG ((DEBUG_WARN,
"%a: Mapping section %d of image at 0x%lx with RW-XN permissions and size 0x%x\n",
__FUNCTION__, Index, Base, SectionHeader.Misc.VirtualSize));
}
} else {
DEBUG ((DEBUG_INFO,
"%a: Mapping section %d of image at 0x%lx with RO-XN permissions and size 0x%x\n",
__FUNCTION__, Index, Base, SectionHeader.Misc.VirtualSize));
ReadOnlyUpdater (Base, SectionHeader.Misc.VirtualSize);
DEBUG ((DEBUG_INFO,
"%a: Mapping section %d of image at 0x%lx with RO-X permissions and size 0x%x\n",
__FUNCTION__, Index, Base, SectionHeader.Misc.VirtualSize));
NoExecUpdater (Base, SectionHeader.Misc.VirtualSize);
}
SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);
}
return RETURN_SUCCESS;
}
/**
If the build is done on cygwin the paths are cygpaths.
/cygdrive/c/tmp.txt vs c:\tmp.txt so we need to convert
them to work with RVD commands
@param Name Path to convert if needed
**/
CHAR8 *
DeCygwinPathIfNeeded (
IN CHAR8 *Name,
IN CHAR8 *Temp,
IN UINTN Size
)
{
CHAR8 *Ptr;
UINTN Index;
UINTN Index2;
Ptr = AsciiStrStr (Name, "/cygdrive/");
if (Ptr == NULL) {
return Name;
}
for (Index = 9, Index2 = 0; (Index < (Size + 9)) && (Ptr[Index] != '\0'); Index++, Index2++) {
Temp[Index2] = Ptr[Index];
if (Temp[Index2] == '/') {
Temp[Index2] = '\\' ;
}
if (Index2 == 1) {
Temp[Index2 - 1] = Ptr[Index];
Temp[Index2] = ':';
}
}
return Temp;
}
/**
Performs additional actions after a PE/COFF image has been loaded and relocated.
If ImageContext is NULL, then ASSERT().
@param ImageContext Pointer to the image context structure that describes the
PE/COFF image that has already been loaded and relocated.
**/
VOID
EFIAPI
PeCoffLoaderRelocateImageExtraAction (
IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
)
{
#if !defined(MDEPKG_NDEBUG)
CHAR8 Temp[512];
#endif
if (PcdGetBool(PcdStandaloneMmEnable) == TRUE)
{
UpdatePeCoffPermissions (ImageContext, ArmClearMemoryRegionNoExec,
ArmSetMemoryRegionReadOnly);
}
if (ImageContext->PdbPointer) {
#ifdef __CC_ARM
#if (__ARMCC_VERSION < 500000)
// Print out the command for the RVD debugger to load symbols for this image
DEBUG ((DEBUG_LOAD | DEBUG_INFO, "load /a /ni /np %a &0x%p\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp)), (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders)));
#else
// Print out the command for the DS-5 to load symbols for this image
DEBUG ((DEBUG_LOAD | DEBUG_INFO, "add-symbol-file %a 0x%p\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp)), (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders)));
#endif
#elif __GNUC__
// This may not work correctly if you generate PE/COFF directlyas then the Offset would not be required
DEBUG ((DEBUG_LOAD | DEBUG_INFO, "add-symbol-file %a 0x%p\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp)), (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders)));
#else
DEBUG ((DEBUG_LOAD | DEBUG_INFO, "Loading driver at 0x%11p EntryPoint=0x%11p\n", (VOID *)(UINTN) ImageContext->ImageAddress, FUNCTION_ENTRY_POINT (ImageContext->EntryPoint)));
#endif
} else {
DEBUG ((DEBUG_LOAD | DEBUG_INFO, "Loading driver at 0x%11p EntryPoint=0x%11p\n", (VOID *)(UINTN) ImageContext->ImageAddress, FUNCTION_ENTRY_POINT (ImageContext->EntryPoint)));
}
}
/**
Performs additional actions just before a PE/COFF image is unloaded. Any resources
that were allocated by PeCoffLoaderRelocateImageExtraAction() must be freed.
If ImageContext is NULL, then ASSERT().
@param ImageContext Pointer to the image context structure that describes the
PE/COFF image that is being unloaded.
**/
VOID
EFIAPI
PeCoffLoaderUnloadImageExtraAction (
IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
)
{
#if !defined(MDEPKG_NDEBUG)
CHAR8 Temp[512];
#endif
if (PcdGetBool(PcdStandaloneMmEnable) == TRUE)
{
UpdatePeCoffPermissions (ImageContext, ArmSetMemoryRegionNoExec,
ArmClearMemoryRegionReadOnly);
}
if (ImageContext->PdbPointer) {
#ifdef __CC_ARM
// Print out the command for the RVD debugger to load symbols for this image
DEBUG ((DEBUG_ERROR, "unload symbols_only %a\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp))));
#elif __GNUC__
// This may not work correctly if you generate PE/COFF directlyas then the Offset would not be required
DEBUG ((DEBUG_ERROR, "remove-symbol-file %a 0x%08x\n", DeCygwinPathIfNeeded (ImageContext->PdbPointer, Temp, sizeof (Temp)), (UINTN)(ImageContext->ImageAddress + ImageContext->SizeOfHeaders)));
#else
DEBUG ((DEBUG_ERROR, "Unloading %a\n", ImageContext->PdbPointer));
#endif
} else {
DEBUG ((DEBUG_ERROR, "Unloading driver at 0x%11p\n", (VOID *)(UINTN) ImageContext->ImageAddress));
}
}
| 2.046875 | 2 |
2024-11-18T22:25:16.682025+00:00 | 2016-12-01T17:07:22 | 05c8ff462e535161b2bfd90aa8570c40327751d6 | {
"blob_id": "05c8ff462e535161b2bfd90aa8570c40327751d6",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-01T17:07:22",
"content_id": "79bcc46944ecc4f4e4ec40019cc49a49b85f6633",
"detected_licenses": [
"MIT"
],
"directory_id": "f007e7620b3c36c06d79c8a040029cbcb4c3b13e",
"extension": "c",
"filename": "ex03.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 69624361,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 374,
"license": "MIT",
"license_type": "permissive",
"path": "/at07-cuda/code/src/ex03.c",
"provenance": "stackv2-0115.json.gz:115759",
"repo_name": "lellisls/PAD",
"revision_date": "2016-12-01T17:07:22",
"revision_id": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198",
"snapshot_id": "45531cca405628742e02eee42bd9e12efdb726db",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lellisls/PAD/eb4fcb9c19ca4fc2cba2a392928957efe4bd5198/at07-cuda/code/src/ex03.c",
"visit_date": "2021-01-11T18:21:20.240821"
} | stackv2 | #include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void ) {
float * data;
long int n = 1000000;
data = (float *) malloc( n * sizeof( float ) );
double start = omp_get_wtime();
int i;
for( i = 0; i < n; ++i){
data[ i ] = rand() / 1000.0f;
}
printf( "\tTempo Total : %f \n", omp_get_wtime( ) - start );
return 0;
}
| 2.671875 | 3 |
2024-11-18T22:25:17.230612+00:00 | 2023-09-02T14:55:31 | 80801538370714078c352b60cd967cb741ef9752 | {
"blob_id": "80801538370714078c352b60cd967cb741ef9752",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T14:55:31",
"content_id": "c7bae29b514975a77a1f69ec87e93508e53dec76",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca",
"extension": "c",
"filename": "cond_test.c",
"fork_events_count": 325,
"gha_created_at": "2015-03-29T15:27:48",
"gha_event_created_at": "2023-09-14T16:58:34",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 33078138,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1914,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/tests/kernel/thread/sync/cond_test.c",
"provenance": "stackv2-0115.json.gz:115888",
"repo_name": "embox/embox",
"revision_date": "2023-09-02T14:55:31",
"revision_id": "98e3c06e33f3fdac10a29c069c20775568e0a6d1",
"snapshot_id": "d6aacec876978522f01cdc4b8de37a668c6f4c80",
"src_encoding": "UTF-8",
"star_events_count": 1087,
"url": "https://raw.githubusercontent.com/embox/embox/98e3c06e33f3fdac10a29c069c20775568e0a6d1/src/tests/kernel/thread/sync/cond_test.c",
"visit_date": "2023-09-04T03:02:20.165042"
} | stackv2 | /**
* @file
* @brief Tests condition variable wait/signal methods.
*
* @date Sep 03, 2012
* @author Bulychev Anton
*/
#include <embox/test.h>
#include <kernel/thread/sync/cond.h>
#include <kernel/thread/sync/mutex.h>
#include <kernel/thread.h>
#include <kernel/task.h>
#include <sys/wait.h>
#include <util/err.h>
static struct thread *low, *high;
static cond_t c, c_private;
static struct mutex m;
EMBOX_TEST_SUITE("Condition variable test");
static void *low_run(void *arg) {
test_emit('a');
test_assert_zero(thread_launch(high));
test_emit('d');
mutex_lock(&m);
test_emit('e');
cond_signal(&c);
test_emit('f');
mutex_unlock(&m);
test_emit('h');
return NULL;
}
static void *high_run(void *arg) {
test_emit('b');
mutex_lock(&m);
test_emit('c');
cond_wait(&c, &m);
test_emit('g');
return NULL;
}
TEST_CASE("General") {
int l = 200, h = 210;
mutex_init(&m);
cond_init(&c, NULL);
low = thread_create(THREAD_FLAG_SUSPENDED, low_run, NULL);
test_assert_zero(err(low));
high = thread_create(THREAD_FLAG_SUSPENDED, high_run, NULL);
test_assert_zero(err(high));
test_assert_zero(schedee_priority_set(&low->schedee, l));
test_assert_zero(schedee_priority_set(&high->schedee, h));
test_assert_zero(thread_launch(low));
test_assert_zero(thread_join(low, NULL));
test_assert_zero(thread_join(high, NULL));
test_assert_emitted("abcdefgh");
}
static void * try_signal_private(void *unused) {
test_assert_not_zero(cond_signal(&c_private));
return NULL;
}
static void * try_signal_shared(void *unused) {
test_assert_zero(cond_signal(&c));
return NULL;
}
TEST_CASE("PROCESS_PRIVATE") {
int p1, p2;
cond_init(&c_private, NULL);
test_assert(0 <= (p1 = new_task("", try_signal_private, NULL)));
cond_init(&c, NULL);
condattr_setpshared(&c.attr, PROCESS_SHARED);
test_assert(0 <= (p2 = new_task("", try_signal_shared, NULL)));
waitpid(p1, NULL, 0);
waitpid(p2, NULL, 0);
}
| 2.75 | 3 |
2024-11-18T22:25:17.573577+00:00 | 2021-01-11T07:28:44 | b4c5ac7bf8a5d798ed1de49e2e64fd77b97e718e | {
"blob_id": "b4c5ac7bf8a5d798ed1de49e2e64fd77b97e718e",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-11T07:28:44",
"content_id": "ad838dbe2ea2bbd522328463e3d60641f0ffda29",
"detected_licenses": [
"MIT"
],
"directory_id": "60c01fd6d44f68fc560ba17cd1fbec44ca09b155",
"extension": "c",
"filename": "get_next_line.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 328559114,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2148,
"license": "MIT",
"license_type": "permissive",
"path": "/get_next_line.c",
"provenance": "stackv2-0115.json.gz:116146",
"repo_name": "kotabrog/get_next_line",
"revision_date": "2021-01-11T07:28:44",
"revision_id": "afd17c66817ab37bd312608460dc5ed8169c7f7e",
"snapshot_id": "7bd65f423fc6d584e6a618640c11d805c12a6245",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kotabrog/get_next_line/afd17c66817ab37bd312608460dc5ed8169c7f7e/get_next_line.c",
"visit_date": "2023-02-15T00:55:04.893890"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ksuzuki <ksuzuki@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/04 18:10:08 by ksuzuki #+# #+# */
/* Updated: 2020/08/22 12:52:29 by ksuzuki ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *read_join(int fd, char **line, ssize_t *n, int *flag)
{
ssize_t line_size;
ssize_t m;
char *buf;
char *rest;
char *temp;
if ((buf = (char *)malloc((BUFFER_SIZE + 1) * sizeof(char))) == NULL)
*n = -1;
line_size = *n;
rest = NULL;
while (!(*flag) && *n >= 0 && (*n = read(fd, buf, BUFFER_SIZE)) > 0)
{
buf[*n] = 0;
if ((rest = ft_strchr_ex(buf, '\n', &m, flag)) != NULL &&
(rest = ft_strndup(rest, *n - m - 1)) == NULL)
*n = -1;
if ((temp = ft_strjoin_ex(*line, buf, line_size, m)) == NULL)
*n = -1;
free(*line);
*line = temp;
line_size += m;
}
free(buf);
return (rest);
}
int get_next_line(int fd, char **line)
{
static char *fd_array[MAX_FD];
char *rest;
ssize_t n;
int find_flag;
find_flag = 0;
if (fd < 0 || MAX_FD <= fd || line == NULL)
return (-1);
rest = ft_strchr_ex(fd_array[fd], '\n', &n, &find_flag);
if (rest && (rest = ft_strndup(rest, -1)) == NULL)
n = -1;
if (n >= 0 && (*line = ft_strndup(fd_array[fd], n)) == NULL)
n = -1;
if (n >= 0 && !find_flag)
rest = read_join(fd, line, &n, &find_flag);
free(fd_array[fd]);
fd_array[fd] = rest;
if (n < 0)
{
free(*line);
free(fd_array[fd]);
*line = NULL;
return (-1);
}
return (find_flag);
}
| 2.78125 | 3 |
2024-11-18T22:25:18.605255+00:00 | 2015-02-07T12:28:10 | ce67ccd074417b991987a090f1539d3225c91804 | {
"blob_id": "ce67ccd074417b991987a090f1539d3225c91804",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-07T12:28:10",
"content_id": "9041b0384935132a912ca40e6a01cb8d9f25a76f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d109c8fd3d22fc7b1e6800efb7d85255f66b10b2",
"extension": "c",
"filename": "QNS.c",
"fork_events_count": 0,
"gha_created_at": "2014-10-09T04:11:19",
"gha_event_created_at": "2015-02-07T12:28:24",
"gha_language": "C",
"gha_license_id": null,
"github_id": 24973312,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2273,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Kovacs G. Gyorgy/LAB7/Lab7/QNS.c",
"provenance": "stackv2-0115.json.gz:117572",
"repo_name": "aut-eng-2014/aut-eng-2014",
"revision_date": "2015-02-07T12:28:10",
"revision_id": "f7f9258b4714ceef4f681cd3f791299a03493cc0",
"snapshot_id": "275f3799ce9153a13b2d0f3740ecb3ae50aeedef",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aut-eng-2014/aut-eng-2014/f7f9258b4714ceef4f681cd3f791299a03493cc0/Kovacs G. Gyorgy/LAB7/Lab7/QNS.c",
"visit_date": "2016-09-05T17:10:28.497552"
} | stackv2 |
#include "QNS.h"
//===========Queue============
List* initQueue(){
return NULL;
}
void NQ(List **Queue,int in){
if (*Queue == NULL){
*Queue = (List*) malloc(sizeof(List));
(*Queue)->value = in;
(*Queue)->next = NULL;
}
else{
List *temp = (List*) malloc(sizeof(List));
temp->value = in;
temp->next = *Queue;
*Queue = temp;
}
}
int DQ(List **Queue){
if (*Queue == NULL){
printf("\n[W]: The queue has no elements.\n");
return -1;
}
else if((*Queue)->next == NULL){
int tempNum = (*Queue)->value;
*Queue = NULL;
return tempNum;
}
else{
List *temp = *Queue;
List *tempsFather = temp;
while (temp->next != NULL){
tempsFather = temp;
temp = temp->next;
}
tempsFather->next = NULL;
return temp->value;
}
}
void printQueue(List **Queue){
printf("Printing elements: [ ");
if ((*Queue) == NULL){
printf("VOID ].\n");
return;
}
List *temp = *Queue;
while (temp != NULL){
printf("%d ",temp->value);
temp = temp->next;
}
printf("].\n");
}
//===========Stack============
List* initStack(){
return NULL;
}
void push(List **Stack, int in){
if (*Stack == NULL){
*Stack = (List*) malloc(sizeof(List));
(*Stack)->value = in;
(*Stack)->next = NULL;
}
else{
List *temp = (List*) malloc(sizeof(List));
temp->value = in;
temp->next = Stack;
*Stack = temp;
}
}
int pop(List **Stack){
if (*Stack == NULL){
printf("\n[W]: The stack is empty.");
return -1;
}
else{
int tempNum = (*Stack)->value;
*Stack = (*Stack)->next; //Memory leak.
return tempNum;
}
}
void printStack(List **Stack){
printf("Printing elements: [ ");
if (*Stack == NULL){
printf("VOID\n");
return;
}
List *temp = *Stack;
while (temp != NULL){
printf("%d ",temp->value);
temp = temp->next;
}
printf("].\n");
}
//============================
bool isEmpty(List **l){
if (*l == NULL){
return true;
}
else{
return false;
}
}
| 3.390625 | 3 |
2024-11-18T22:25:18.948469+00:00 | 2019-01-09T03:56:43 | 47462514e1d316467352e4d8765497d75a1f34df | {
"blob_id": "47462514e1d316467352e4d8765497d75a1f34df",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-09T03:56:43",
"content_id": "860f73dead585cd56f22ae606b7982a1a771b688",
"detected_licenses": [
"MIT"
],
"directory_id": "40665ca26a76d8844ac13f1655c9ce9ff2fff21c",
"extension": "c",
"filename": "lunetta.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 143732894,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1144,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lunetta.c",
"provenance": "stackv2-0115.json.gz:117830",
"repo_name": "kawaharasouta/k_lunetta",
"revision_date": "2019-01-09T03:56:43",
"revision_id": "85a79a176236411273d6428d00f7b6cf356c38ef",
"snapshot_id": "3ca072f8892a4f7545bb568bdf7e76d7bdfe8b0e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/kawaharasouta/k_lunetta/85a79a176236411273d6428d00f7b6cf356c38ef/src/lunetta.c",
"visit_date": "2020-03-25T11:27:06.835402"
} | stackv2 | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<stdint.h>
#include"include/lunetta.h"
#include"include/pkt_io.h"
#include"include/ethernet.h"
#include"include/arp.h"
#include"include/ip.h"
#include"include/udp.h"
int
lunetta_init(struct port_config *port_conf, struct ip_init_info *ip_info) {
struct ether_port *ether_port;
if (dpdk_init() == -1) {
fprintf(stderr, "dpdk_init error");
return -1;
}
port_init(port_conf);
ethernet_init(port_conf, 1);
arp_init(port_conf);
ip_info->port = get_port_pointer();
ip_init(ip_info, 1, ip_info->port, 0x0a000001);
udp_init();
ether_port = get_port_pointer();
rte_eal_remote_launch(launch_lcore_rx, (void *)ether_port, 1);
printf("launch application...\n");
sleep(5);
return 0;
}
int
lunetta_close() {
rte_eal_wait_lcore(1);
return 0;
}
uint16_t
checksum_s(uint16_t *data, uint16_t size, uint32_t init) {
uint32_t sum;
sum = init;
while(size > 1) {
sum += *(data++);
size -= 2;
}
if(size) {
sum += *(uint8_t *)data;
}
sum = (sum & 0xffff) + (sum >> 16);
sum = (sum & 0xffff) + (sum >> 16);
return ~(uint16_t)sum;
}
| 2.21875 | 2 |
2024-11-18T22:25:19.549465+00:00 | 2023-08-25T14:34:14 | cac43693bb4f3150e1154ad9dc5fd26a1f21e8e9 | {
"blob_id": "cac43693bb4f3150e1154ad9dc5fd26a1f21e8e9",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-27T00:08:13",
"content_id": "6104afbac7a62881d817eaf44d6749fa046aa088",
"detected_licenses": [
"BSD-2-Clause",
"TCL"
],
"directory_id": "c3131a4552e2cdcd34e5dd5461e76358a13a978a",
"extension": "c",
"filename": "jimsh.c",
"fork_events_count": 127,
"gha_created_at": "2011-04-12T23:47:56",
"gha_event_created_at": "2023-09-13T22:40:00",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 1606904,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5963,
"license": "BSD-2-Clause,TCL",
"license_type": "permissive",
"path": "/jimsh.c",
"provenance": "stackv2-0115.json.gz:117960",
"repo_name": "msteveb/jimtcl",
"revision_date": "2023-08-25T14:34:14",
"revision_id": "0be8ac02e4c4a9be674b0c85621b14fe1f4ef99c",
"snapshot_id": "cb8cd9ecdb67a36838735f31cb53044e74b49650",
"src_encoding": "UTF-8",
"star_events_count": 400,
"url": "https://raw.githubusercontent.com/msteveb/jimtcl/0be8ac02e4c4a9be674b0c85621b14fe1f4ef99c/jimsh.c",
"visit_date": "2023-09-04T13:01:23.193067"
} | stackv2 | /*
* jimsh - An interactive shell for Jim
*
* Copyright 2005 Salvatore Sanfilippo <antirez@invece.org>
* Copyright 2009 Steve Bennett <steveb@workware.net.au>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the Jim Tcl Project.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jim.h"
#include "jimautoconf.h"
/* From initjimsh.tcl */
extern int Jim_initjimshInit(Jim_Interp *interp);
static void JimSetArgv(Jim_Interp *interp, int argc, char *const argv[])
{
int n;
Jim_Obj *listObj = Jim_NewListObj(interp, NULL, 0);
/* Populate argv global var */
for (n = 0; n < argc; n++) {
Jim_Obj *obj = Jim_NewStringObj(interp, argv[n], -1);
Jim_ListAppendElement(interp, listObj, obj);
}
Jim_SetVariableStr(interp, "argv", listObj);
Jim_SetVariableStr(interp, "argc", Jim_NewIntObj(interp, argc));
}
static void JimPrintErrorMessage(Jim_Interp *interp)
{
Jim_MakeErrorMessage(interp);
fprintf(stderr, "%s\n", Jim_String(Jim_GetResult(interp)));
}
void usage(const char* executable_name)
{
printf("jimsh version %d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
printf("Usage: %s\n", executable_name);
printf("or : %s [options] [filename]\n", executable_name);
printf("\n");
printf("Without options: Interactive mode\n");
printf("\n");
printf("Options:\n");
printf(" --version : prints the version string\n");
printf(" --help : prints this text\n");
printf(" -e CMD : executes command CMD\n");
printf(" NOTE: all subsequent options will be passed as arguments to the command\n");
printf(" [filename|-] : executes the script contained in the named file, or from stdin if \"-\"\n");
printf(" NOTE: all subsequent options will be passed to the script\n\n");
}
int main(int argc, char *const argv[])
{
int retcode;
Jim_Interp *interp;
char *const orig_argv0 = argv[0];
/* Parse initial arguments before interpreter is started */
if (argc > 1 && strcmp(argv[1], "--version") == 0) {
printf("%d.%d\n", JIM_VERSION / 100, JIM_VERSION % 100);
return 0;
}
else if (argc > 1 && strcmp(argv[1], "--help") == 0) {
usage(argv[0]);
return 0;
}
/* Create and initialize the interpreter */
interp = Jim_CreateInterp();
Jim_RegisterCoreCommands(interp);
/* Register static extensions */
if (Jim_InitStaticExtensions(interp) != JIM_OK) {
JimPrintErrorMessage(interp);
}
Jim_SetVariableStrWithStr(interp, "jim::argv0", orig_argv0);
Jim_SetVariableStrWithStr(interp, JIM_INTERACTIVE, argc == 1 ? "1" : "0");
#ifdef USE_LINENOISE
Jim_SetVariableStrWithStr(interp, "jim::lineedit", "1");
#else
Jim_SetVariableStrWithStr(interp, "jim::lineedit", "0");
#endif
retcode = Jim_initjimshInit(interp);
if (argc == 1) {
/* Executable name is the only argument - start interactive prompt */
if (retcode == JIM_ERR) {
JimPrintErrorMessage(interp);
}
if (retcode != JIM_EXIT) {
JimSetArgv(interp, 0, NULL);
retcode = Jim_InteractivePrompt(interp);
}
}
else {
/* Additional arguments - interpret them */
if (argc > 2 && strcmp(argv[1], "-e") == 0) {
/* Evaluate code in subsequent argument */
JimSetArgv(interp, argc - 3, argv + 3);
retcode = Jim_Eval(interp, argv[2]);
if (retcode != JIM_ERR) {
int len;
const char *msg = Jim_GetString(Jim_GetResult(interp), &len);
if (fwrite(msg, len, 1, stdout) == 0) {
/* nothing */
}
putchar('\n');
}
}
else {
Jim_SetVariableStr(interp, "argv0", Jim_NewStringObj(interp, argv[1], -1));
JimSetArgv(interp, argc - 2, argv + 2);
if (strcmp(argv[1], "-") == 0) {
retcode = Jim_Eval(interp, "eval [info source [stdin read] stdin 1]");
} else {
retcode = Jim_EvalFile(interp, argv[1]);
}
}
if (retcode == JIM_ERR) {
JimPrintErrorMessage(interp);
}
}
if (retcode == JIM_EXIT) {
retcode = Jim_GetExitCode(interp);
}
else if (retcode == JIM_ERR) {
retcode = 1;
}
else {
retcode = 0;
}
Jim_FreeInterp(interp);
return retcode;
}
| 2.078125 | 2 |
2024-11-18T22:25:19.686959+00:00 | 2017-05-04T16:51:38 | 23084d2e196ca5314b252beb9a0c990579f3381f | {
"blob_id": "23084d2e196ca5314b252beb9a0c990579f3381f",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-04T16:51:41",
"content_id": "01e408d096b00134ca0f70152a739c2915f39604",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "00f38305b7cdd25c21819f445dabcd09f74bb171",
"extension": "c",
"filename": "mnist_demo.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86696011,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3120,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/demo/mnist_demo.c",
"provenance": "stackv2-0115.json.gz:118090",
"repo_name": "artix75/psyc",
"revision_date": "2017-05-04T16:51:38",
"revision_id": "4f609ca47ccbc0882bb651b133e8b463ac623126",
"snapshot_id": "73d6823f194d17486685a9207eae205c78af3808",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/artix75/psyc/4f609ca47ccbc0882bb651b133e8b463ac623126/src/demo/mnist_demo.c",
"visit_date": "2021-01-18T15:56:18.251926"
} | stackv2 | /*
Copyright (c) 2016 Fabio Nicotra.
All rights reserved.
Redistribution and use in source and binary forms are permitted
provided that the above copyright notice and this paragraph are
duplicated in all such forms and that any documentation,
advertising materials, and other materials related to such
distribution and use acknowledge that the software was developed
by the copyright holder. The name of the
copyright holder may not be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../psyc.h"
#include "../mnist.h"
#define INPUT_SIZE (28 * 28)
#define EPOCHS 30
int main(int argc, char** argv) {
if (argc < 3) {
printf("Usage %s IMAGE_FILE LABELS_FILE [TEST_FILES...]\n", argv[0]);
return 1;
}
double * training_data = NULL;
double * test_data = NULL;
int testlen = 0;
int datalen = 0;
int loaded = 0;
PSNeuralNetwork * network = PSCreateNetwork("MNIST Demo");
if (network == NULL) {
fprintf(stderr, "Could not create network!\n");
return 1;
}
PSAddLayer(network, FullyConnected, INPUT_SIZE, NULL);
PSAddLayer(network, FullyConnected, 30, NULL);
PSAddLayer(network, FullyConnected, 10, NULL);
if (network->size < 1) {
fprintf(stderr, "Could not add all layers!\n");
PSDeleteNetwork(network);
return 1;
}
if (strcmp("--load", argv[1]) == 0) {
loaded = PSLoadNetwork(network, argv[2]);
if (!loaded) {
printf("Could not load pretrained network!\n");
return 1;
}
if (network->size < 1) {
fprintf(stderr, "Could not add all layers!\n");
PSDeleteNetwork(network);
return 1;
}
} else {
datalen = loadMNISTData(TRAINING_DATA, argv[1], argv[2],
&training_data);
if (datalen == 0 || training_data == NULL) {
printf("Could not load training data!\n");
return 1;
}
}
if (argc >= 5) {
testlen = loadMNISTData(TEST_DATA, argv[3], argv[4],
&test_data);
};
printf("Data len: %d\n", datalen);
if (!loaded) PSTrain(network, training_data, datalen, EPOCHS, 3, 10, NULL,
NULL, 0);
if (network->status == STATUS_ERROR) {
PSDeleteNetwork(network);
if (training_data != NULL) free(training_data);
if (test_data != NULL) free(test_data);
return 1;
}
if (testlen > 0 && test_data != NULL) {
printf("Test Data len: %d\n", testlen);
PSTest(network, test_data, testlen);
}
PSDeleteNetwork(network);
if (training_data != NULL) free(training_data);
if (test_data != NULL) free(test_data);
return 0;
}
| 2.359375 | 2 |
2024-11-18T22:25:19.821766+00:00 | 2017-07-11T21:36:18 | 54c7922a9188e9d351e338936645798095836837 | {
"blob_id": "54c7922a9188e9d351e338936645798095836837",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-11T21:36:18",
"content_id": "faf3cbe82f0b5a14ecbdfe2e4e6440afe6ee491f",
"detected_licenses": [
"MIT"
],
"directory_id": "f04cf69c09edc25cfbfaf487bebe124efaed8d7a",
"extension": "c",
"filename": "exercise_6-06.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 96583032,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 306,
"license": "MIT",
"license_type": "permissive",
"path": "/exercise_6-06.c",
"provenance": "stackv2-0115.json.gz:118218",
"repo_name": "siebenschlaefer/tcpl-exercises",
"revision_date": "2017-07-11T21:36:18",
"revision_id": "2cc3563ce03eec1a3382fc6ccff8ee038591552e",
"snapshot_id": "6d883dc4245bf5da705f1cde01072f00cbfc492a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/siebenschlaefer/tcpl-exercises/2cc3563ce03eec1a3382fc6ccff8ee038591552e/exercise_6-06.c",
"visit_date": "2020-12-02T12:44:01.703273"
} | stackv2 | // Exercise 6-6.
// Implement a simple version of the #define processor (i.e., no arguments)
// suitable for use with C programs, based on the routines of this section. You
// may also find getch and ungetch helpful.
#include <stdio.h>
int main()
{
fprintf(stderr, "not yet done\n");
return 1;
}
| 2.46875 | 2 |
2024-11-18T22:25:20.979245+00:00 | 2017-02-10T04:15:25 | d13599d7c3fe3fe56997e05e07f3c1e65f4e000d | {
"blob_id": "d13599d7c3fe3fe56997e05e07f3c1e65f4e000d",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-10T04:15:25",
"content_id": "00bfdad37e7490f2a15d21b901686f96900a34b7",
"detected_licenses": [
"MIT"
],
"directory_id": "427183680ad57ca9914abbb8f670c8fbe874c13b",
"extension": "c",
"filename": "database.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 20321569,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1474,
"license": "MIT",
"license_type": "permissive",
"path": "/src/database.c",
"provenance": "stackv2-0115.json.gz:119381",
"repo_name": "monological/fastroute",
"revision_date": "2017-02-10T04:15:25",
"revision_id": "25055256d7bc715177ce13f85fa878f85d96e28c",
"snapshot_id": "3e34d60a8c8446ef0662502016651c885a4bb633",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/monological/fastroute/25055256d7bc715177ce13f85fa878f85d96e28c/src/database.c",
"visit_date": "2021-05-16T01:46:15.604775"
} | stackv2 | /*
** database.c - functions to read, write, manipulate graph.db
**
**
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include "database.h"
#include "util.h"
Database *_new_database(){
Database *db;
if((db = malloc(sizeof(Database))) == NULL){
perror("malloc");
exit(1);
}
return db;
}
Database *create_database(const char *name){
Database *db;
db = _new_database();
db->name = strdup(name);
printf("Creating new database '%s' with 'wb'...\n", db->name);
if((db->fp = fopen(db->name, "wb")) == NULL){
perror("open");
exit(1);
}
return db;
}
Database *open_database(const char *file_name){
Database *db;
db = _new_database();
db->name = strdup(file_name);
printf("Opening database '%s' with 'rb'...\n", db->name);
if((db->fp = fopen(db->name, "rb")) == NULL){
perror("open");
exit(1);
}
return db;
}
void close_database(Database *db){
if(db == NULL){
puts("Error: handle given is null.");
exit(1);
}
fclose(db->fp);
free((char *)db->name);
free(db);
}
size_t read_database(void *data, size_t bytes, Database *db){
size_t count;
count = fread(data, 1, bytes, db->fp);
return count;
}
size_t write_database(const void *data, size_t bytes, Database *db){
size_t count;
count = fwrite(data, 1, bytes, db->fp);
return count;
}
| 2.75 | 3 |
2024-11-18T22:25:21.083407+00:00 | 2021-03-08T01:20:39 | 34df4129705d610c34c7b35122dcc093b1e3b6f9 | {
"blob_id": "34df4129705d610c34c7b35122dcc093b1e3b6f9",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-08T01:20:39",
"content_id": "9e9289a6bf23baac7fecb5914532322415e24728",
"detected_licenses": [
"MIT"
],
"directory_id": "726b25c1fad3fda83472b0670aa24dd4ad560239",
"extension": "c",
"filename": "ebrake_tx.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": 1585,
"license": "MIT",
"license_type": "permissive",
"path": "/projects/centre_console/src/ebrake_tx.c",
"provenance": "stackv2-0115.json.gz:119511",
"repo_name": "KarimAlatrash/firmware_xiv",
"revision_date": "2021-03-08T01:20:39",
"revision_id": "347dead3880d3d467a4dfc3708db480bc770dff6",
"snapshot_id": "c05ec35e3a387de04b28be765d175f2c694086ab",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KarimAlatrash/firmware_xiv/347dead3880d3d467a4dfc3708db480bc770dff6/projects/centre_console/src/ebrake_tx.c",
"visit_date": "2023-03-16T02:18:25.977042"
} | stackv2 | #include "ebrake_tx.h"
#include "can_transmit.h"
static void prv_tx_ebrake_state(CanAckRequest *ack_ptr, void *context) {
EbrakeTxStorage *storage = (EbrakeTxStorage *)context;
CAN_TRANSMIT_SET_EBRAKE_STATE(ack_ptr, storage->state);
}
StatusCode ebrake_tx_init(EbrakeTxStorage *storage) {
CanTxRetryWrapperSettings retry_settings = { .retries = NUM_EBRAKE_TX_RETRIES };
storage->current_state = EE_EBRAKE_STATE_RELEASED;
status_ok_or_return(
can_tx_retry_wrapper_init(&storage->can_retry_wrapper_storage, &retry_settings));
return STATUS_CODE_OK;
}
EEEbrakeState get_current_state(EbrakeTxStorage *storage) {
return storage->current_state;
}
void prv_success_ebrake_tx_callback(void *context) {
EbrakeTxStorage *storage = (EbrakeTxStorage *)context;
storage->current_state = storage->state;
}
StatusCode ebrake_tx_brake_state(EbrakeTxStorage *storage, RetryTxRequest *request,
EEEbrakeState state) {
if (state >= NUM_EE_EBRAKE_STATES) {
return STATUS_CODE_INVALID_ARGS;
}
storage->state = state;
CanTxRetryWrapperRequest retry_wrapper_request = {
.retry_request = *request,
.ack_bitset = CAN_ACK_EXPECTED_DEVICES(SYSTEM_CAN_DEVICE_POWER_DISTRIBUTION_FRONT),
.tx_callback = prv_tx_ebrake_state,
.tx_callback_context = storage
};
status_ok_or_return(can_tx_retry_wrapper_register_success_callback(
&storage->can_retry_wrapper_storage, prv_success_ebrake_tx_callback, storage));
can_tx_retry_send(&storage->can_retry_wrapper_storage, &retry_wrapper_request);
return STATUS_CODE_OK;
}
| 2.21875 | 2 |
2024-11-18T22:25:21.204923+00:00 | 2012-11-29T16:11:44 | 958d6ffa5d7f82767e04003d103ae104417f5d3a | {
"blob_id": "958d6ffa5d7f82767e04003d103ae104417f5d3a",
"branch_name": "refs/heads/master",
"committer_date": "2012-11-29T16:11:44",
"content_id": "8899238efff34b16c6dee3bf2c6668638d81890a",
"detected_licenses": [
"BSD-4-Clause-UC"
],
"directory_id": "865e396d74e7fad0e7e9d11a1cf820570be673c5",
"extension": "c",
"filename": "e1000.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5899,
"license": "BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/lab/kern/e1000.c",
"provenance": "stackv2-0115.json.gz:119769",
"repo_name": "ajinkyapotdarvjti/cse506",
"revision_date": "2012-11-29T16:11:44",
"revision_id": "ab8743e08f0cf5ffaebd961555fc0fbc93c7f2de",
"snapshot_id": "70ad48ea13ae6a43dfcce9fcebc06726c93cc0f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ajinkyapotdarvjti/cse506/ab8743e08f0cf5ffaebd961555fc0fbc93c7f2de/lab/kern/e1000.c",
"visit_date": "2021-05-26T20:01:31.225402"
} | stackv2 | //#include <kern/e1000.h>
// LAB 6: Your driver code here
#include <kern/e1000.h>
#include <inc/assert.h>
#include <inc/error.h>
#include <inc/stdio.h>
#include <inc/string.h>
#include <kern/pmap.h>
//volatile uint32_t *e1000; // MMIO address to access E1000 BAR
struct tx_desc tx_desc_array[E1000_TXDESC] __attribute__ ((aligned (16)));
struct tx_pkt tx_pkt_bufs[E1000_TXDESC];
struct rcv_desc rcv_desc_array[E1000_RCVDESC] __attribute__ ((aligned (16)));
struct rcv_pkt rcv_pkt_bufs[E1000_RCVDESC];
//volatile uint32_t *e1000_bars;
// LAB 6: Your driver code here
int
e1000_attach(struct pci_func *pcif)
{
uint32_t i;
// Enable PCI device
pci_func_enable(pcif);
// Memory map I/O for PCI device
e1000 = mmio_map_region(pcif->reg_base[0],pcif->reg_size[0]);
/*
boot_map_segment(boot_pml4e, E1000_MMIOADDR,
pcif->reg_size[0], pcif->reg_base[0],
PTE_W | PTE_PCD | PTE_PWT);
//e1000 = (uint32_t *) E1000_MMIOADDR;
*/
cprintf("e1000[E1000_STATUS] = %0x\n", e1000[E1000_STATUS]);
// Initialize tx buffer array
memset(tx_desc_array, 0x0, sizeof(struct tx_desc) * E1000_TXDESC);
memset(tx_pkt_bufs, 0x0, sizeof(struct tx_pkt) * E1000_TXDESC);
for (i = 0; i < E1000_TXDESC; i++) {
tx_desc_array[i].addr = PADDR(tx_pkt_bufs[i].buf);
tx_desc_array[i].status |= E1000_TXD_STAT_DD;
}
cprintf("initialized tx buffer array");
// Initialize rcv desc buffer array
memset(rcv_desc_array, 0x0, sizeof(struct rcv_desc) * E1000_RCVDESC);
memset(rcv_pkt_bufs, 0x0, sizeof(struct rcv_pkt) * E1000_RCVDESC);
for (i = 0; i < E1000_RCVDESC; i++) {
rcv_desc_array[i].addr = PADDR(rcv_pkt_bufs[i].buf);
}
/* Transmit initialization */
// Program the Transmit Descriptor Base Address Registers
e1000[E1000_TDBAL] = PADDR(tx_desc_array);
e1000[E1000_TDBAH] = 0x0; //PADDR(tx_desc_array);
// Set the Transmit Descriptor Length Register
e1000[E1000_TDLEN] = sizeof(struct tx_desc) * E1000_TXDESC;
// Set the Transmit Descriptor Head and Tail Registers
e1000[E1000_TDH] = 0x0;
e1000[E1000_TDT] = 0x0;
// Initialize the Transmit Control Register
e1000[E1000_TCTL] |= E1000_TCTL_EN;
e1000[E1000_TCTL] |= E1000_TCTL_PSP;
e1000[E1000_TCTL] &= ~E1000_TCTL_CT;
e1000[E1000_TCTL] |= (0x10) << 4;
e1000[E1000_TCTL] &= ~E1000_TCTL_COLD;
e1000[E1000_TCTL] |= (0x40) << 12;
// Program the Transmit IPG Register
e1000[E1000_TIPG] = 0x0;
e1000[E1000_TIPG] |= (0x6) << 20; // IPGR2
e1000[E1000_TIPG] |= (0x4) << 10; // IPGR1
e1000[E1000_TIPG] |= 0xA; // IPGR
cprintf("\nTransmit registers initialized");
/* Receive Initialization */
// Program the Receive Address Registers
e1000[E1000_EERD] = 0x0;
e1000[E1000_EERD] |= E1000_EERD_START;
while (!(e1000[E1000_EERD] & E1000_EERD_DONE));
e1000[E1000_RAL] = e1000[E1000_EERD] >> 16;
e1000[E1000_EERD] = 0x1 << 8;
e1000[E1000_EERD] |= E1000_EERD_START;
while (!(e1000[E1000_EERD] & E1000_EERD_DONE));
e1000[E1000_RAL] |= e1000[E1000_EERD] & 0xffff0000;
e1000[E1000_EERD] = 0x2 << 8;
e1000[E1000_EERD] |= E1000_EERD_START;
while (!(e1000[E1000_EERD] & E1000_EERD_DONE));
e1000[E1000_RAH] = e1000[E1000_EERD] >> 16;
e1000[E1000_RAH] |= 0x1 << 31;
// Program the Receive Descriptor Base Address Registers
e1000[E1000_RDBAL] = PADDR(rcv_desc_array);
e1000[E1000_RDBAH] = 0x0;
// Set the Receive Descriptor Length Register
e1000[E1000_RDLEN] = sizeof(struct rcv_desc) * E1000_RCVDESC;
// Set the Receive Descriptor Head and Tail Registers
e1000[E1000_RDH] = 0x0;
e1000[E1000_RDT] = 0x0;
// Initialize the Receive Control Register
e1000[E1000_RCTL] |= E1000_RCTL_EN;
e1000[E1000_RCTL] &= ~E1000_RCTL_LPE;
e1000[E1000_RCTL] &= ~E1000_RCTL_LBM;
e1000[E1000_RCTL] &= ~E1000_RCTL_RDMTS;
e1000[E1000_RCTL] &= ~E1000_RCTL_MO;
e1000[E1000_RCTL] |= E1000_RCTL_BAM;
e1000[E1000_RCTL] &= ~E1000_RCTL_SZ; // 2048 byte size
e1000[E1000_RCTL] |= E1000_RCTL_SECRC;
cprintf("\nReached till end\n");
return 0;
}
int
e1000_transmit(char *data, int len)
{
if (len > TX_PKT_SIZE) {
return -E_PKT_TOO_LONG;
}
uint32_t tdt = e1000[E1000_TDT];
// Check if next tx desc is free
if (tx_desc_array[tdt].status & E1000_TXD_STAT_DD) {
memmove(tx_pkt_bufs[tdt].buf, data, len);
tx_desc_array[tdt].length = len;
tx_desc_array[tdt].status &= ~E1000_TXD_STAT_DD;
tx_desc_array[tdt].cmd |= E1000_TXD_CMD_RS;
tx_desc_array[tdt].cmd |= E1000_TXD_CMD_EOP;
e1000[E1000_TDT] = (tdt + 1) % E1000_TXDESC;
}
else { // tx queue is full!
return -E_TX_FULL;
}
return 0;
}
int
e1000_receive(char *data)
{
uint32_t rdt, len;
rdt = e1000[E1000_RDT];
if (rcv_desc_array[rdt].status & E1000_RXD_STAT_DD) {
if (!(rcv_desc_array[rdt].status & E1000_RXD_STAT_EOP)) {
panic("Don't allow jumbo frames!\n");
}
len = rcv_desc_array[rdt].length;
memmove(data, rcv_pkt_bufs[rdt].buf, len);
rcv_desc_array[rdt].status &= ~E1000_RXD_STAT_DD;
rcv_desc_array[rdt].status &= ~E1000_RXD_STAT_EOP;
e1000[E1000_RDT] = (rdt + 1) % E1000_RCVDESC;
return len;
}
return -E_RCV_EMPTY;
}
| 2.34375 | 2 |
2024-11-18T22:25:21.827417+00:00 | 2020-12-30T00:06:34 | 8c3f70b11dca8f8a91838309fea494239c550df2 | {
"blob_id": "8c3f70b11dca8f8a91838309fea494239c550df2",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-30T00:06:34",
"content_id": "2bd86b984fed45c1d9c11785aa26ba2bf3cf6ccd",
"detected_licenses": [
"MIT"
],
"directory_id": "5461139a4620a660b5da71adeb10c917d7c0bdf0",
"extension": "c",
"filename": "mutex.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 252570033,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2027,
"license": "MIT",
"license_type": "permissive",
"path": "/mutex binky/source/src/mutex.c",
"provenance": "stackv2-0115.json.gz:120154",
"repo_name": "joyalraju/RTOS",
"revision_date": "2020-12-30T00:06:34",
"revision_id": "3ae35d0b1d78fa3224565448c8816da7e9baa3f4",
"snapshot_id": "1cd400022bbea95444c0a90c747b8a6dd060744a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/joyalraju/RTOS/3ae35d0b1d78fa3224565448c8816da7e9baa3f4/mutex binky/source/src/mutex.c",
"visit_date": "2021-05-21T05:43:56.500604"
} | stackv2 | #include "board.h"
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "queue.h"
static void prvSetupHardware(void) //board setting
{
SystemCoreClockUpdate();
Board_Init();
Board_LED_Set(0, true);
Board_LED_Set(1, true);
Board_LED_Set(2, true);
}
xSemaphoreHandle xMutex;
portTickType xLastWakeTime;
static void vLEDTask1(void *pvParameters) //red led task
{
while (1)
{
xLastWakeTime = xTaskGetTickCount();
xSemaphoreTake(xMutex, portMAX_DELAY); //Accepting Mutex
Board_LED_Set(0, 0);
vTaskDelayUntil( &xLastWakeTime, 1000);
Board_LED_Set(0, 1);
xSemaphoreGive(xMutex);
vTaskDelayUntil( &xLastWakeTime, 3500);
}
}
static void vLEDTask2(void *pvParameters) //green led task
{
vTaskDelay(configTICK_RATE_HZ + configTICK_RATE_HZ / 2);
while (1)
{
xLastWakeTime = xTaskGetTickCount();
xSemaphoreTake(xMutex, portMAX_DELAY);
Board_LED_Set(1, 0);
vTaskDelayUntil( &xLastWakeTime, 1000);
Board_LED_Set(1, 1);
xSemaphoreGive(xMutex);
vTaskDelayUntil( &xLastWakeTime, 3500);
}
}
static void vLEDTask3(void *pvParameters) //blue led task
{
vTaskDelay(3 * configTICK_RATE_HZ);
while (1)
{
xLastWakeTime = xTaskGetTickCount();
xSemaphoreTake(xMutex, portMAX_DELAY);
Board_LED_Set(2, 0);
vTaskDelayUntil( &xLastWakeTime, 1000);
Board_LED_Set(2, 1);
xSemaphoreGive(xMutex);
vTaskDelayUntil( &xLastWakeTime, 3500);
}
}
int main(void)
{
prvSetupHardware();
xMutex = xSemaphoreCreateMutex(); //create mutex
xTaskCreate(vLEDTask1, (signed char* ) "vTaskLed1",
configMINIMAL_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 1UL),
(xTaskHandle *) NULL);
xTaskCreate(vLEDTask2, (signed char* ) "vTaskLed2",
configMINIMAL_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 1UL),
(xTaskHandle *) NULL);
xTaskCreate(vLEDTask3, (signed char* ) "vTaskLed3",
configMINIMAL_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 1UL),
(xTaskHandle *) NULL);
/* Start the scheduler */
vTaskStartScheduler();
return 1;
}
| 2.640625 | 3 |
2024-11-18T22:25:21.986581+00:00 | 2021-02-07T06:41:04 | 6a5c71a80d6fde269fa49addf900b76b8e14ba76 | {
"blob_id": "6a5c71a80d6fde269fa49addf900b76b8e14ba76",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-07T06:41:04",
"content_id": "0bad709275175dcbeabff582dda8d97feef0ecd9",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "83c8b2759df9ca51ec356b942b1f9f7412a76172",
"extension": "h",
"filename": "project_main.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": 7654,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/examples/CortexM0_M7/CortexM0/project_main.h",
"provenance": "stackv2-0115.json.gz:120283",
"repo_name": "grinux/TNKernel",
"revision_date": "2021-02-07T06:41:04",
"revision_id": "520e5f6f2798ca889624e491a754402a80483440",
"snapshot_id": "cc2c5d77aaa2ed91a0828afe5c3dcdbc5c42e2f2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/grinux/TNKernel/520e5f6f2798ca889624e491a754402a80483440/examples/CortexM0_M7/CortexM0/project_main.h",
"visit_date": "2023-06-30T22:47:40.324072"
} | stackv2 | /**
*
* Copyright (c) 2013,2016 Yuri Tiomkin
* All Rights Reserved
*
*
* Permission to use, copy, modify, and distribute this software in source
* and binary forms and its documentation for any purpose and without fee
* is hereby granted, provided that the above copyright notice appear
* in all copies and that both that copyright notice and this permission
* notice appear in supporting documentation.
*
*
* THIS SOFTWARE IS PROVIDED BY YURI TIOMKIN "AS IS" AND ANY EXPRESSED OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL YURI TIOMKIN OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PROJECT_MAIN_H
#define PROJECT_MAIN_H
//-- project_main.c
extern TN_DQUEUE queueShellEvents;
//-- prj_shell_func.c
extern const int g_shell_cmd_arr_size;
//-- stm32_uart.c
typedef struct _UARTINFO
{
TN_SEM tx_sem;
TN_SEM tx_rdy_sem;
unsigned int rx_buf_size;
unsigned char * rx_buf;
unsigned int rx_timeout_cnt;
unsigned int rx_timeout;
unsigned int rx_tail;
int state;
DMA_InitTypeDef DMA_InitStructure;
USART_TypeDef huart;
}UARTINFO;
extern UARTINFO g_uart2_info;
int bsp_uart2_open(UARTINFO *ui,
// USART_InitTypeDef * init_info,
unsigned char *rx_buf,
unsigned int rx_buf_size);
int bsp_uart2_close(UARTINFO *ui);
int bsp_uart2_read(UARTINFO * ui, unsigned char * buf, unsigned int max_len);
int bsp_uart2_transmit(UARTINFO * ui,
unsigned char * data,
unsigned int data_size);
int uart2_tx_str(char * str);
void uart2_tx_char(unsigned char ch);
int open_uart2(UARTINFO * ui,
unsigned char * rx_buf,
unsigned int rx_buf_len);
void do_itoa(int val, char * buf, int buf_len);
//----------------------------------------------------------------------------
int tn_dump_int_ex(unsigned char * buf, // output buffer
int buf_len, // total output buffer length
const char * fmt, // format string
int val, // value to dump
int width, // valid only if 'fmp' contains '.*' in the width field
int precision); // valid only if 'fmp' contains '.*' in the precision field
static TN_INLINE int tn_dump_int(unsigned char * buf,
int buf_len,
const char * fmt,
int val)
{
return tn_dump_int_ex(buf,
buf_len,
fmt,
val,
0,
0);
}
//----------------------------------------------------------------------------
// Converting unsigned short/integer to string according to the format options in
// 'fmt' string (snprintf like, but for the single unsigned short/integer argument
//----------------------------------------------------------------------------
int tn_dump_uint_ex(const char * fmt, // format string
unsigned char * buf, // output buffer
int buf_len, // total output buffer length
unsigned int val, // value to dump
int width, // valid only if 'fmp' contains '.*' in the width field
int precision); // valid only if 'fmp' contains '.*' in the precision field
static TN_INLINE int tn_dump_uint(const char * fmt,
unsigned char * buf,
int buf_len,
unsigned int val)
{
return tn_dump_uint_ex(fmt,
buf,
buf_len,
val,
0,
0);
}
//----------------------------------------------------------------------------
// Converting long to string according to the format options in
// 'fmt' string (snprintf like, but for the single long argument
//----------------------------------------------------------------------------
int tn_dump_long_ex(const char * fmt, // format string
unsigned char * buf, // output buffer
int buf_len, // total output buffer length
long val, // value to dump
int width, // valid only if 'fmp' contains '.*' in the width field
int precision); // valid only if 'fmp' contains '.*' in the precision field
static TN_INLINE int tn_dump_long(const char * fmt,
unsigned char * buf,
int buf_len,
long val)
{
return tn_dump_long_ex(fmt,
buf,
buf_len,
val,
0,
0);
}
//----------------------------------------------------------------------------
// Converting unsigned long to string according to the format options in
// 'fmt' string (snprintf like, but for the single unsigned long argument
//----------------------------------------------------------------------------
int tn_dump_ulong_ex(const char * fmt, // format string
unsigned char * buf, // output buffer
int buf_len, // total output buffer length
unsigned long val, // value to dump
int width, // valid only if 'fmp' contains '.*' in the width field
int precision); // valid only if 'fmp' contains '.*' in the precision field
static TN_INLINE int tn_dump_ulong(const char * fmt,
unsigned char * buf,
int buf_len,
unsigned long val)
{
return tn_dump_ulong_ex(fmt,
buf,
buf_len,
val,
0,
0);
}
//----------------------------------------------------------------------------
// Converting (unsigned) char to string according to the format options in
// 'fmt' string (snprintf like, but for the single (unsigned) char argument
//----------------------------------------------------------------------------
int tn_dump_uchar(const char * fmt, // format string
unsigned char * buf, // output buffer
int buf_len, // total output buffer length
unsigned char val); // value to dump
//-- Shell - use UART2
#define uart_tx_str(str) uart2_tx_str(str)
#define uart_tx_char(ch) uart2_tx_char(ch)
#define uart_tx_str_func uart2_tx_str
#define uart_tx_char_func uart2_tx_char
#endif /* #ifndef PROJECT_MAIN_H */
| 2.078125 | 2 |
2024-11-18T22:25:22.102995+00:00 | 2018-07-19T23:16:12 | 823fc726d3608522f315a773cea8650da65e32d1 | {
"blob_id": "823fc726d3608522f315a773cea8650da65e32d1",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-19T23:16:12",
"content_id": "fb0a18858c58287f508ecb6c999dd9d55f849fee",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cadbc494b42093b89789ed002cdb2bfd94bfe51f",
"extension": "h",
"filename": "compaxx.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 141058209,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4621,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/compaxx.h",
"provenance": "stackv2-0115.json.gz:120413",
"repo_name": "zlieber/compaxx",
"revision_date": "2018-07-19T23:16:12",
"revision_id": "1bc83a31dd927f2ecf90efbc6068ace8b1641c61",
"snapshot_id": "adeb128c3d1782d680a8ff6ed35aa03a466ba446",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/zlieber/compaxx/1bc83a31dd927f2ecf90efbc6068ace8b1641c61/compaxx.h",
"visit_date": "2020-03-23T03:57:38.442215"
} | stackv2 |
#ifndef __COMPAXX_H__
#define __COMPAXX_H__
// The Compact Compass Library (CompaxxLib)
#define MAX_CALIBRATION_POINTS 36
#define MAX_SENSOR_POINTS 200
typedef struct {
float compassHeading;
float magneticHeading;
} CalibrationPoint;
typedef struct {
float x;
float y;
float z;
} Point;
typedef struct {
/**
* A plane is stored in cartesian representation (ax + by + cz + d = 0),
* with two extra assumptions:
* 1. d >= 0
* 2. a^2 + b^2 + c^2 + d^2 = 1
* This allows us to omit storing the value of d, as we can compute
* it from the other values.
*/
float planeA;
float planeB;
float planeC;
Point compassNorth;
Point origin;
CalibrationPoint calibrationData[MAX_CALIBRATION_POINTS];
int pointCount;
} Calibration;
typedef struct {
Point sensorData;
float magneticHeading;
} CalibrationCtxPoint;
typedef struct {
CalibrationCtxPoint points[MAX_SENSOR_POINTS];
CalibrationCtxPoint finePoints[MAX_CALIBRATION_POINTS];
int pointCount;
int finePointCount;
} CalibrationContext;
#define E_SUCCESS 0
#define E_NEED_COARSE_CALIBRATION -1
#define E_NOT_ENOUGH_CALIBRATION_POINTS -2
#define E_TOO_MANY_COARSE_POINTS -3
#define E_TOO_MANY_FINE_POINTS -4
/**
* Returns current compass or magnetic heading, given 3-axis sensor
* reading. Compass heading is heading read off the compass without
* accounting for effects on the instrument of various metallic
* objects in its surroundings. As such, this function requires that a
* coarse calibration has been performed, so that we know compass
* orientation relative to horizontal plane. It also requires at least
* one fine calibration point, so that it can determine which way the
* compass is pointing on a vessel or drone.
*
* Magnetic heading requires more fine calibration points (up to 36,
* but at least 8 is recommended), and corrects the compass heading
* for effects of environment on the instrument. It is therefore more
* precise than a compass heading.
*
* @param cal Existing calibration structure. At least coarse
* calibration must have been performed.
* @param sensorData 3-axis sensor data provided by the instrument.
* @param compassHeading Pointer to variable to store result in.
* @return Error code.
*/
short getHeading(const Calibration* cal, const Point* sensorData, float* heading);
/**
* Begins the process of calibrating the instrument.
*
* @param ctx Pointer to existing CalibrationContext structure. There
* is no need to initialize anything in this structure, it will be
* done by this function.
* @return E_SUCCESS
*/
short startCalibration(CalibrationContext* ctx);
/**
* Adds a calibration point to the calibration context.
*
* Calibration points can be of two types: coarse and fine calibration
* points.
*
* Coarse calibration points contain instrument reading, and nothing
* else (magneticHeading == null). These points are used to establish
* instrument orientation relative to the horizontal plane.
*
* Fine calibration points contain correct magnetic heading, as read
* by hand bearing compass that is placed away from mangetic
* interference.
*
* For successful calibration process, it is required to provide at
* least 10 coarse calibration points, and one fine calibration
* point. This will enable reading compass heading via getHeading.
*
* If, in addition to that, at leat 8 more fine calibration points are
* provided, then getHeading will start returning a more precise
* magnetic heading instead.
*
* @param ctx Existing calibration context
* @param sensorData Sensor data as returned by the 3-axis instrument
* @param magneticHeading Optional - if this is a fine calibration
* point, then it should contain a correct magnetic heading as read by
* a hand bearing compass.
* @return Error code
*/
short addCalibrationPoint(CalibrationContext* ctx, const Point* sensorData, const float* magneticHeading);
/**
* Finalizes the calibration process and initializes the Calibration
* structure to be used in future reference.
*
* After this function returns, the CalibrationContext is no longer
* needed, and the scope in which it is defined can be exited.
*
* @param ctx Existing calibration context
* @param cal Points to Calibration structure. There is no need to
* initialize it.
* @param quality Optional quality output. Will contain quality metric
* (in percent) of the calibration performed.
* @return Error code.
*/
short finalizeCalibration(const CalibrationContext* ctx, Calibration* cal, float* quality);
#endif
| 2.5 | 2 |
2024-11-18T22:25:22.197421+00:00 | 2020-05-15T13:08:23 | 497cd7bd02dcbd73f319dd9240d5cbfd71881362 | {
"blob_id": "497cd7bd02dcbd73f319dd9240d5cbfd71881362",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-15T13:08:23",
"content_id": "dddd9aee43591825cb2d968b1a04a41fa27b3c2f",
"detected_licenses": [
"MIT"
],
"directory_id": "d4508166cf3670a2f0b2d7ac8381189e04462545",
"extension": "c",
"filename": "upcasting.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": 640,
"license": "MIT",
"license_type": "permissive",
"path": "/casting/upcasting.c",
"provenance": "stackv2-0115.json.gz:120543",
"repo_name": "nizz009/OOP-C89",
"revision_date": "2020-05-15T13:08:23",
"revision_id": "41d0ac2f315fd259e5540cbb73e40c05832de2c1",
"snapshot_id": "541653f90d93eff20783847ff65b0ac310fbad88",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nizz009/OOP-C89/41d0ac2f315fd259e5540cbb73e40c05832de2c1/casting/upcasting.c",
"visit_date": "2022-07-25T02:36:33.947639"
} | stackv2 | /* UPCASTING
* Authors: Merijn Hendriks
* License: MIT License
* Documentation: see readme.md
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct A A;
typedef struct B B;
struct A
{
int x;
};
struct B
{
A base;
int y;
};
static void A_ctor(A* self, int x)
{
if (!self)
{
return;
}
self->x = x;
}
static void B_ctor(B* self, int x, int y)
{
if (!self)
{
return;
}
A_ctor(&self->base, x);
self->y = y;
}
int main()
{
B b;
B_ctor(&b, 1, 2);
A_ctor(&b.base, 3);
printf("%d\n", b.base.x);
return EXIT_SUCCESS;
}
| 2.953125 | 3 |
2024-11-18T22:25:23.306109+00:00 | 2021-08-04T01:06:22 | 97bde30c2f546fd6d9a662f3359ebd5e68ef4275 | {
"blob_id": "97bde30c2f546fd6d9a662f3359ebd5e68ef4275",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-04T01:06:22",
"content_id": "ca30be2f3367755204ba001cfd0c1077d874b0b5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5cea73cdcd63bd3b6a9d0cbdc64f350bd7393038",
"extension": "c",
"filename": "circbuf.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": 2722,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/circbuf.c",
"provenance": "stackv2-0115.json.gz:121062",
"repo_name": "skchoi56/appscope",
"revision_date": "2021-08-04T01:06:22",
"revision_id": "869a92e15c524e911e564d5bd421e16eeffb9def",
"snapshot_id": "252941a6051e5178c1c9af4de68ba9f8c56230f0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skchoi56/appscope/869a92e15c524e911e564d5bd421e16eeffb9def/src/circbuf.c",
"visit_date": "2023-07-08T23:18:37.822789"
} | stackv2 | #define _GNU_SOURCE
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdlib.h>
#include "dbg.h"
#include "atomic.h"
#include "circbuf.h"
cbuf_handle_t
cbufInit(size_t size)
{
cbuf_handle_t cbuf = calloc(1, sizeof(struct circbuf_t));
if (!cbuf) {
DBG("Circbuf:calloc");
return NULL;
}
uint64_t *buffer = calloc(size + 1, sizeof(uint64_t));
if (!buffer) {
free(cbuf);
DBG("Circbuf:calloc");
return NULL;
}
cbufReset(cbuf);
cbuf->maxlen = size + 1;
cbuf->buffer = buffer;
return cbuf;
}
void
cbufFree(cbuf_handle_t cbuf)
{
if (!cbuf) return;
if (cbuf->buffer) free(cbuf->buffer);
free(cbuf);
return;
}
void
cbufReset(cbuf_handle_t cbuf)
{
if (!cbuf) return;
cbuf->head = 0;
cbuf->tail = 0;
return;
}
int
cbufPut(cbuf_handle_t cbuf, uint64_t data)
{
int head, head_next, attempts, success;
if (!cbuf) return -1;
attempts = success = 0;
do {
head = cbuf->head;
head_next = (head + 1) % cbuf->maxlen;
if (head_next == cbuf->tail) {
// Note: we commented this out as it caused a
// double free error when running with 100,000
// Go routines. We should determine why.
DBG("maxlen: %"PRIu64, cbuf->maxlen); // Full
break;
}
success = atomicCas32(&cbuf->head, head, head_next);
} while (!success && (attempts++ < cbuf->maxlen));
if (success) {
if (cbuf->buffer[head_next] != 0) {
// We expect that the entry is not used; has been read
DBG(NULL);
return -1;
}
cbuf->buffer[head_next] = data;
return 0;
}
return -1;
}
int
cbufGet(cbuf_handle_t cbuf, uint64_t *data)
{
int tail, tail_next, attempts, success;
if (!cbuf || !data) return -1;
attempts = success = 0;
do {
tail = cbuf->tail;
tail_next = (tail + 1) % cbuf->maxlen;
if (tail == cbuf->head) break; // Empty
success = atomicCas32(&cbuf->tail, tail, tail_next);
} while (!success && (attempts++ < cbuf->maxlen));
if (success) {
*data = cbuf->buffer[tail_next];
if (*data == 0) {
// We expect data before we read
// Should we bail out here?
DBG(NULL);
}
// Setting data to 0 to indicate to a put that we're empty
cbuf->buffer[tail_next] = 0ULL;
return 0;
}
return -1;
}
size_t
cbufCapacity(cbuf_handle_t cbuf)
{
if (!cbuf) return -1;
return cbuf->maxlen - 1;
}
int
cbufEmpty(cbuf_handle_t cbuf)
{
if (!cbuf || (cbuf->tail == cbuf->head)) return TRUE;
return FALSE;
}
| 2.84375 | 3 |
2024-11-18T22:25:23.520750+00:00 | 2013-10-10T06:12:43 | 8598a6882309059262efa99c155c056eac44803c | {
"blob_id": "8598a6882309059262efa99c155c056eac44803c",
"branch_name": "refs/heads/master",
"committer_date": "2013-10-10T06:12:43",
"content_id": "ba114815cc6807478c22088506a6380ec1dada3b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "056fcc67222afe34d96fd9cadb35469f6d305907",
"extension": "c",
"filename": "oppo_control_button.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14116459,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5927,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/driveronly_mp_rom/bootable/recovery/oppo/src/controls/oppo_control_button.c",
"provenance": "stackv2-0115.json.gz:121190",
"repo_name": "datagutt/12055",
"revision_date": "2013-10-10T06:12:43",
"revision_id": "593741d834fff91ad3587c762caea5f00b69ba69",
"snapshot_id": "a9e98f2972a76d92b7d07eee690cd1300b780efe",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/datagutt/12055/593741d834fff91ad3587c762caea5f00b69ba69/driveronly_mp_rom/bootable/recovery/oppo/src/controls/oppo_control_button.c",
"visit_date": "2020-07-21T13:04:55.731555"
} | stackv2 | /*
* Copyright (C) 2011 Ahmad Amarullah ( http://amarullz.com/ )
*
* 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 "../oppo_inter.h"
/***************************[ BUTTON ]**************************/
typedef struct{
CANVAS control;
CANVAS control_pushed;
CANVAS control_focused;
byte touchmsg;
byte focused;
byte pushed;
} ACBUTTOND, * ACBUTTONDP;
dword acbutton_oninput(void * x,int action,ATEV * atev){
ACONTROLP ctl = (ACONTROLP) x;
ACBUTTONDP d = (ACBUTTONDP) ctl->d;
dword msg = 0;
switch (action){
case ATEV_MOUSEDN:
{
vibrate(30);
d->pushed=1;
msg=aw_msg(0,1,0,0);
ctl->ondraw(ctl);
}
break;
case ATEV_MOUSEUP:
{
d->pushed=0;
if (aw_touchoncontrol(ctl,atev->x,atev->y))
msg=aw_msg(d->touchmsg,1,0,0);
else
msg=aw_msg(0,1,0,0);
ctl->ondraw(ctl);
}
break;
case ATEV_SELECT:
{
if (atev->d){
vibrate(30);
d->pushed=1;
msg=aw_msg(0,1,0,0);
ctl->ondraw(ctl);
}
else{
d->pushed=0;
msg=aw_msg(d->touchmsg,1,0,0);
ctl->ondraw(ctl);
}
}
break;
}
return msg;
}
void acbutton_ondraw(void * x){
ACONTROLP ctl= (ACONTROLP) x;
ACBUTTONDP d = (ACBUTTONDP) ctl->d;
CANVAS * pc = &ctl->win->c;
if (d->pushed)
ag_draw(pc,&d->control_pushed,ctl->x,ctl->y);
else if(d->focused)
ag_draw(pc,&d->control_focused,ctl->x,ctl->y);
else
ag_draw(pc,&d->control,ctl->x,ctl->y);
}
void acbutton_ondestroy(void * x){
ACONTROLP ctl= (ACONTROLP) x;
ACBUTTONDP d = (ACBUTTONDP) ctl->d;
ag_ccanvas(&d->control);
ag_ccanvas(&d->control_pushed);
ag_ccanvas(&d->control_focused);
free(ctl->d);
}
byte acbutton_onfocus(void * x){
ACONTROLP ctl= (ACONTROLP) x;
ACBUTTONDP d = (ACBUTTONDP) ctl->d;
d->focused=1;
ctl->ondraw(ctl);
return 1;
}
void acbutton_onblur(void * x){
ACONTROLP ctl= (ACONTROLP) x;
ACBUTTONDP d = (ACBUTTONDP) ctl->d;
d->focused=0;
ctl->ondraw(ctl);
}
ACONTROLP acbutton(
AWINDOWP win,
int x,
int y,
int w,
int h,
char * text,
byte isbig,
byte touchmsg,
int style
){
//-- Validate Minimum Size
if (h<agdp()*16) h=agdp()*16;
if (w<agdp()*16) w=agdp()*16;
//-- Initializing Text Metrics
int txtw = ag_txtwidth(text,isbig);
int txth = ag_fontheight(isbig);
int txtx = round(w/2) - round(txtw/2);
int txty = round(h/2) - round(txth/2);
//-- Initializing Button Data
ACBUTTONDP d = (ACBUTTONDP) malloc(sizeof(ACBUTTOND));
memset(d,0,sizeof(ACBUTTOND));
//-- Save Touch Message & Set Stats
d->touchmsg = touchmsg;
d->focused = 0;
d->pushed = 0;
//-- Initializing Canvas
ag_canvas(&d->control,w,h);
ag_canvas(&d->control_pushed,w,h);
ag_canvas(&d->control_focused,w,h);
if (style == 1) {
//-- Draw Rest Control
ag_draw_ex(&d->control,&win->c,0,0,x,y,w,h);
atheme_draw("img.button", &d->control,0,0,w,h);
ag_text(&d->control,txtw,txtx,txty,text,acfg()->txt_menu,isbig);
//-- Draw Pushed Control
ag_draw_ex(&d->control_pushed,&win->c,0,0,x,y,w,h);
atheme_draw("img.button.focus", &d->control_pushed,0,0,w,h);
ag_text(&d->control_pushed,txtw,txtx,txty,text,acfg()->txt_select,isbig);
//-- Draw Focused Control
ag_draw_ex(&d->control_focused,&win->c,0,0,x,y,w,h);
atheme_draw("img.button.focus", &d->control_focused,0,0,w,h);
ag_text(&d->control_focused,txtw,txtx,txty,text,acfg()->txt_select,isbig);
} else {
//-- Draw Rest Control
ag_draw_ex(&d->control,&win->c,0,0,x,y,w,h);
//ag_rect(&d->control, 0, 0, w, h, acfg()->winbg);
ag_roundgrad(&d->control,0,0,w,h,acfg()->winbg,acfg()->winbg, agdp());
ag_rect(&d->control, 0, 1, w, 1, acfg()->menuline_bot);
ag_rect(&d->control, 0, 0, w, 1, acfg()->menuline_top);
ag_text(&d->control,txtw,txtx,txty,text,acfg()->txt_menu,isbig);
//-- Draw Pushed Control
ag_draw_ex(&d->control_pushed,&win->c,0,0,x,y,w,h);
//ag_rect(&d->control_pushed, 0, 0, w, h, acfg()->selectbg);
ag_roundgrad(&d->control_pushed,0,0,w,h,acfg()->selectbg,acfg()->selectbg, agdp());
ag_rect(&d->control_pushed, 0, 1, w, 1, acfg()->menuline_bot);
ag_rect(&d->control_pushed, 0, 0, w, 1, acfg()->menuline_top);
ag_text(&d->control_pushed,txtw,txtx,txty,text,acfg()->txt_select,isbig);
//-- Draw Focused Control
ag_draw_ex(&d->control_focused,&win->c,0,0,x,y,w,h);
//ag_rect(&d->control_focused, 0, 0, w, h, acfg()->selectbg);
ag_roundgrad(&d->control_focused,0,0,w,h,acfg()->selectbg,acfg()->selectbg, agdp());
ag_rect(&d->control_focused, 0, 1, w, 1, acfg()->menuline_bot);
ag_rect(&d->control_focused, 0, 0, w, 1, acfg()->menuline_top);
ag_text(&d->control_focused,txtw,txtx,txty,text,acfg()->txt_select,isbig);
}
//-- Initializing Control
ACONTROLP ctl = malloc(sizeof(ACONTROL));
ctl->ondestroy= &acbutton_ondestroy;
ctl->oninput = &acbutton_oninput;
ctl->ondraw = &acbutton_ondraw;
ctl->onblur = &acbutton_onblur;
ctl->onfocus = &acbutton_onfocus;
ctl->win = win;
ctl->x = x;
ctl->y = y;
ctl->w = w;
ctl->h = h;
ctl->forceNS = 0;
ctl->d = (void *) d;
aw_add(win,ctl);
return ctl;
}
| 2.140625 | 2 |
2024-11-18T22:25:24.571849+00:00 | 2023-08-30T19:33:44 | 4c4bd87ad3564d240586a9d8059998e537cba366 | {
"blob_id": "4c4bd87ad3564d240586a9d8059998e537cba366",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-30T19:33:44",
"content_id": "b7c393aa77fbd6d688b3b74329064dfa4bce3347",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "e65a4dbfbfb0e54e59787ba7741efee12f7687f3",
"extension": "c",
"filename": "patch-lib-stdfns.c",
"fork_events_count": 918,
"gha_created_at": "2011-05-26T11:15:35",
"gha_event_created_at": "2023-09-08T04:06:26",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 1803961,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1131,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/security/mhash/files/patch-lib-stdfns.c",
"provenance": "stackv2-0115.json.gz:122094",
"repo_name": "freebsd/freebsd-ports",
"revision_date": "2023-08-30T19:33:44",
"revision_id": "605a2983f245ac63f5420e023e7dce56898ad801",
"snapshot_id": "86f2e89d43913412c4f6b2be3e255bc0945eac12",
"src_encoding": "UTF-8",
"star_events_count": 916,
"url": "https://raw.githubusercontent.com/freebsd/freebsd-ports/605a2983f245ac63f5420e023e7dce56898ad801/security/mhash/files/patch-lib-stdfns.c",
"visit_date": "2023-08-30T21:46:28.720924"
} | stackv2 | Description: Check a memory allocation and use the POSIX INT_* constants.
Author: Peter Pentchev <roam@FreeBSD.org>
Forwarded: http://sourceforge.net/mailarchive/message.php?msg_name=20090910102100.GA26539%40straylight.m.ringlet.net
Last-Update: 2009-09-10
--- lib/stdfns.c.orig
+++ lib/stdfns.c
@@ -360,11 +360,11 @@
{
return(0);
}
- return(-MAXINT);
+ return(-INT_MAX);
}
if (s2 == NULL)
{
- return(MAXINT);
+ return(INT_MAX);
}
return(memcmp(s1, s2, n));
@@ -491,11 +491,11 @@
{
return(0);
}
- return(-MAXINT);
+ return(-INT_MAX);
}
if (src2 == NULL)
{
- return(MAXINT);
+ return(INT_MAX);
}
return(strcmp((char *) src1, (char *) src2));
}
@@ -514,11 +514,11 @@
{
return(0);
}
- return(-MAXINT);
+ return(-INT_MAX);
}
if (src2 == NULL)
{
- return(MAXINT);
+ return(INT_MAX);
}
return(strncmp((char *) src1, (char *) src2, n));
}
@@ -552,6 +552,8 @@
mutils_word8 *ptrOut = buffer;
mutils_word32 loop;
+ if (buffer == NULL)
+ return(NULL);
for (loop = 0; loop < len; loop++, ptrIn++)
{
*ptrOut++ = mutils_val2char((*ptrIn & 0xf0) >> 4);
| 2.0625 | 2 |
2024-11-18T22:25:24.912332+00:00 | 2019-01-06T13:30:31 | 3f7d1e21e1c5ada02250fcb465d6faae92d9f1ae | {
"blob_id": "3f7d1e21e1c5ada02250fcb465d6faae92d9f1ae",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-06T13:30:31",
"content_id": "e2509b43fe68f171b68b84a41cc6b7a60a87c7d1",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "97af4170da974b80bb9871adced9284b9124134a",
"extension": "c",
"filename": "custom_rsh.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": 6699,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/test/utils/custom_rsh2/custom_rsh.c",
"provenance": "stackv2-0115.json.gz:122479",
"repo_name": "curiousTauseef/netsem",
"revision_date": "2019-01-06T13:30:31",
"revision_id": "0b02450eee334fc42f74ad3da09d3ce1a0698a48",
"snapshot_id": "af21de72cc30d343afc4d15a989bd048868b0490",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/curiousTauseef/netsem/0b02450eee334fc42f74ad3da09d3ce1a0698a48/test/utils/custom_rsh2/custom_rsh.c",
"visit_date": "2020-05-21T07:25:50.275225"
} | stackv2 | #include <winsock2.h>
#include <windows.h>
#include <stdio.h>
/* WARNING: win32 environments are buffers that contain null-terminated */
/* strings of the form "var=value" concatenated and followed by an extra */
/* null at the end, i.e. at the end of the buffer there are *two* null */
/* values! */
/* Error reporting function */
void error_abort(char *msg)
{
fprintf(stderr, "custom_rsh: %s\n", msg);
abort();
}
void warning(char *msg)
{
#ifdef DEBUG
fprintf(stderr, "custom_rsh: %s\n", msg);
#endif
}
void wsa_error_abort(char *msg)
{
int err;
err = WSAGetLastError();
fprintf(stderr, "custom_rsh: winsock error -- %s(%d)\n", strerror(err), err);
error_abort(msg);
}
/* Initialise winsock */
void initWinsock()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
//Initialise the winsock library (version 2.2 compat)
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0)
error_abort("Could not init winsock\n");
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
WSACleanup();
error_abort("Could not init winsock. Version 2 not available\n");
}
}
/* Worker thread: read the execution string from the connected socket, */
/* parse the commands and create the required process with the correct */
/* environment. Wait until the socket is disconnected then kill the */
/* previously created process, release all memory and close the socket */
DWORD WINAPI thread_body(LPVOID lpsock) {
SOCKET sdconn;
char recv_buf[2048], *progpath, *oldenv, *newenv;
int recv_len, i, j, endofenv=0;
int oldlen1, oldlen2, newlen=0;
PROCESS_INFORMATION pinfo;
STARTUPINFO sinfo;
ZeroMemory(&sinfo, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
ZeroMemory(&pinfo, sizeof(pinfo));
//Copy in the sock descriptor and free the temporary memory allocation
memcpy(&sdconn, lpsock, sizeof(SOCKET));
free(lpsock);
/* Read command from connected socket */
ZeroMemory(recv_buf, 2048);
recv_len = recv(sdconn, recv_buf, 2048, 0);
if(recv_len == 0) {
warning("recv returned end-of-file");
goto exit;
} else if(recv_len == SOCKET_ERROR)
wsa_error_abort("recv raised an error");
/* Decide which netsem tool to run */
switch(recv_buf[0]) {
case 'S':
#ifdef DEBUG
printf("SLURP\n");
#endif
if((progpath = getenv("EXEC_SLURP")) == NULL)
error_abort("EXEC_SLURP not found in the environment");
break;
case 'L':
#ifdef DEBUG
printf("LIBD\n");
#endif
if((progpath = getenv("EXEC_LIBD")) == NULL)
error_abort("EXEC_LIBD not found in the environment");
break;
case 'I':
#ifdef DEBUG
printf("INJECTOR\n");
#endif
if((progpath = getenv("EXEC_INJECTOR")) == NULL)
error_abort("EXEC_INJECTOR not found in the environment");
break;
case 'T':
error_abort("TCP_DEBUG not supported on windows");
break;
case 'C':
if((progpath = getenv("EXEC_TSCCAL")) == NULL)
error_abort("EXEC_TSCCAL not found in the environment");
break;
default:
error_abort("received an unknown program command");
break;
}
#ifdef DEBUG
printf("progpath: %s\n", progpath);
printf("cmdline: %s\n", &recv_buf[1]);
#endif
/* Replace each * and $ with a null */
/* Record the position of the first * -- this is */
/* the index of the end of the environment vars */
for(i=0; i<2048; i++)
if(recv_buf[i] == '*') {
recv_buf[i] = '\0';
if(endofenv == 0) endofenv = i;
} else if(recv_buf[i] == '$') {
recv_buf[i] = '\0';
}
oldlen1 = endofenv; //length of environment vars from socket
/* Get the current process's environment */
oldenv = GetEnvironmentStrings();
for(i=0; ; i++)
if(oldenv[i] == '\0' && oldenv[i+1] == '\0')
break;
oldlen2 = i+1; //length of the current process's environment */
/* Create buffer for the new environment */
newlen = oldlen1 + oldlen2 + 1;
if((newenv = malloc(newlen)) == NULL)
error_abort("malloc failed");
/* Copy the current process's environment and the environment */
/* from the socket into the new environment buffer */
for(i=0; i<oldlen2; i++)
newenv[i] = oldenv[i];
for(j=1; j<oldlen1; j++,i++)
newenv[i] = recv_buf[j];
/* Put the mandatory extra null on the end of the new environment */
newenv[i] = '\0';
/* Create the process */
if(!CreateProcess(progpath, &recv_buf[endofenv+1], NULL, NULL, TRUE, 0, newenv, NULL, &sinfo, &pinfo))
error_abort("create process failed");
/* Wait until the connection dies */
while(1) {
recv_len = recv(sdconn, recv_buf, 2048, 0);
if(recv_len == 0 || recv_len == SOCKET_ERROR) {
/* Kill the process and exit */
#ifdef WIN32
printf("Killing\n");
#endif
free(newenv);
FreeEnvironmentStrings(oldenv);
TerminateProcess(pinfo.hProcess, 0);
break;
}
}
exit:
//Close the socket now we are done
if(closesocket(sdconn) == SOCKET_ERROR)
wsa_error_abort("close of connected socket failed");
return 0;
}
int main(int argc, char *argv[])
{
SOCKET sd, newconn, *tempsd;
HANDLE threadHnd;
DWORD threadId;
struct sockaddr_in bind_addr, newconn_addr;
int newconn_size;
if(argc != 3)
error_abort("Incorrect args: custom_rsh ip_addr port");
initWinsock();
if((sd = socket(AF_INET, SOCK_STREAM, 6)) == INVALID_SOCKET)
wsa_error_abort("Call to socket() failed");
ZeroMemory(&bind_addr, sizeof(bind_addr));
bind_addr.sin_family = AF_INET;
bind_addr.sin_addr.s_addr = inet_addr(argv[1]);
bind_addr.sin_port = htons(atoi(argv[2]));
if(bind(sd, (struct sockaddr*)&bind_addr, sizeof(bind_addr)) == SOCKET_ERROR)
wsa_error_abort("bind() failed");
if(listen(sd, 10) == SOCKET_ERROR)
wsa_error_abort("listen() failed");
/* Accept new connections and pass them to a worker thread */
while(1) {
ZeroMemory(&newconn_addr, sizeof(newconn_addr));
newconn_size = sizeof(newconn_addr);
if((newconn = accept(sd, (struct sockaddr*)&newconn_addr, &newconn_size)) == INVALID_SOCKET) {
wsa_error_abort("accept() failed but will continue anyway");
continue;
}
/* Need to pass a copy of the sd to eliminate the obvious race condition */
/* Thread is responsible of calling free() */
if((tempsd = malloc(sizeof(SOCKET))) == NULL) {
warning("malloc failed but will continue");
continue;
}
memcpy(tempsd, &newconn, sizeof(SOCKET));
if((threadHnd = CreateThread(NULL, 0, thread_body, tempsd, 0, &threadId)) == NULL) {
warning("CreateThread() failed but will continue anyway");
continue;
}
}
WSACleanup();
return 0;
}
| 2.484375 | 2 |
2024-11-18T22:25:25.047192+00:00 | 2023-06-21T12:52:04 | e4cf7b2c876f0967ece3eea9c1b3214610e7579f | {
"blob_id": "e4cf7b2c876f0967ece3eea9c1b3214610e7579f",
"branch_name": "refs/heads/develop",
"committer_date": "2023-06-21T12:52:04",
"content_id": "e2e82942f812c7db1b3dc60e1794d89cb044969a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3f97df4f7e06c653be69c547c7e2efb7a9b5aad0",
"extension": "c",
"filename": "tz_context.c",
"fork_events_count": 1356,
"gha_created_at": "2016-02-18T08:04:18",
"gha_event_created_at": "2023-08-22T09:43:24",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 51990771,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5801,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/CMSIS/Core/Template/ARMv8-M/tz_context.c",
"provenance": "stackv2-0115.json.gz:122610",
"repo_name": "ARM-software/CMSIS_5",
"revision_date": "2023-06-21T12:52:04",
"revision_id": "a75f01746df18bb5b929dfb8dc6c9407fac3a0f3",
"snapshot_id": "ef832c23aa9af025718f5aa3c780b4870d2ff060",
"src_encoding": "UTF-8",
"star_events_count": 2872,
"url": "https://raw.githubusercontent.com/ARM-software/CMSIS_5/a75f01746df18bb5b929dfb8dc6c9407fac3a0f3/CMSIS/Core/Template/ARMv8-M/tz_context.c",
"visit_date": "2023-09-06T02:49:34.281196"
} | stackv2 | /******************************************************************************
* @file tz_context.c
* @brief Context Management for Armv8-M TrustZone - Sample implementation
* @version V1.1.1
* @date 10. January 2018
******************************************************************************/
/*
* Copyright (c) 2016-2018 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* 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 "RTE_Components.h"
#include CMSIS_device_header
#include "tz_context.h"
/// Number of process slots (threads may call secure library code)
#ifndef TZ_PROCESS_STACK_SLOTS
#define TZ_PROCESS_STACK_SLOTS 8U
#endif
/// Stack size of the secure library code
#ifndef TZ_PROCESS_STACK_SIZE
#define TZ_PROCESS_STACK_SIZE 256U
#endif
typedef struct {
uint32_t sp_top; // stack space top
uint32_t sp_limit; // stack space limit
uint32_t sp; // current stack pointer
} stack_info_t;
static stack_info_t ProcessStackInfo [TZ_PROCESS_STACK_SLOTS];
static uint64_t ProcessStackMemory[TZ_PROCESS_STACK_SLOTS][TZ_PROCESS_STACK_SIZE/8U];
static uint32_t ProcessStackFreeSlot = 0xFFFFFFFFU;
/// Initialize secure context memory system
/// \return execution status (1: success, 0: error)
__attribute__((cmse_nonsecure_entry))
uint32_t TZ_InitContextSystem_S (void) {
uint32_t n;
if (__get_IPSR() == 0U) {
return 0U; // Thread Mode
}
for (n = 0U; n < TZ_PROCESS_STACK_SLOTS; n++) {
ProcessStackInfo[n].sp = 0U;
ProcessStackInfo[n].sp_limit = (uint32_t)&ProcessStackMemory[n];
ProcessStackInfo[n].sp_top = (uint32_t)&ProcessStackMemory[n] + TZ_PROCESS_STACK_SIZE;
*((uint32_t *)ProcessStackMemory[n]) = n + 1U;
}
*((uint32_t *)ProcessStackMemory[--n]) = 0xFFFFFFFFU;
ProcessStackFreeSlot = 0U;
// Default process stack pointer and stack limit
__set_PSPLIM((uint32_t)ProcessStackMemory);
__set_PSP ((uint32_t)ProcessStackMemory);
// Privileged Thread Mode using PSP
__set_CONTROL(0x02U);
return 1U; // Success
}
/// Allocate context memory for calling secure software modules in TrustZone
/// \param[in] module identifies software modules called from non-secure mode
/// \return value != 0 id TrustZone memory slot identifier
/// \return value 0 no memory available or internal error
__attribute__((cmse_nonsecure_entry))
TZ_MemoryId_t TZ_AllocModuleContext_S (TZ_ModuleId_t module) {
uint32_t slot;
(void)module; // Ignore (fixed Stack size)
if (__get_IPSR() == 0U) {
return 0U; // Thread Mode
}
if (ProcessStackFreeSlot == 0xFFFFFFFFU) {
return 0U; // No slot available
}
slot = ProcessStackFreeSlot;
ProcessStackFreeSlot = *((uint32_t *)ProcessStackMemory[slot]);
ProcessStackInfo[slot].sp = ProcessStackInfo[slot].sp_top;
return (slot + 1U);
}
/// Free context memory that was previously allocated with \ref TZ_AllocModuleContext_S
/// \param[in] id TrustZone memory slot identifier
/// \return execution status (1: success, 0: error)
__attribute__((cmse_nonsecure_entry))
uint32_t TZ_FreeModuleContext_S (TZ_MemoryId_t id) {
uint32_t slot;
if (__get_IPSR() == 0U) {
return 0U; // Thread Mode
}
if ((id == 0U) || (id > TZ_PROCESS_STACK_SLOTS)) {
return 0U; // Invalid ID
}
slot = id - 1U;
if (ProcessStackInfo[slot].sp == 0U) {
return 0U; // Inactive slot
}
ProcessStackInfo[slot].sp = 0U;
*((uint32_t *)ProcessStackMemory[slot]) = ProcessStackFreeSlot;
ProcessStackFreeSlot = slot;
return 1U; // Success
}
/// Load secure context (called on RTOS thread context switch)
/// \param[in] id TrustZone memory slot identifier
/// \return execution status (1: success, 0: error)
__attribute__((cmse_nonsecure_entry))
uint32_t TZ_LoadContext_S (TZ_MemoryId_t id) {
uint32_t slot;
if ((__get_IPSR() == 0U) || ((__get_CONTROL() & 2U) == 0U)) {
return 0U; // Thread Mode or using Main Stack for threads
}
if ((id == 0U) || (id > TZ_PROCESS_STACK_SLOTS)) {
return 0U; // Invalid ID
}
slot = id - 1U;
if (ProcessStackInfo[slot].sp == 0U) {
return 0U; // Inactive slot
}
// Setup process stack pointer and stack limit
__set_PSPLIM(ProcessStackInfo[slot].sp_limit);
__set_PSP (ProcessStackInfo[slot].sp);
return 1U; // Success
}
/// Store secure context (called on RTOS thread context switch)
/// \param[in] id TrustZone memory slot identifier
/// \return execution status (1: success, 0: error)
__attribute__((cmse_nonsecure_entry))
uint32_t TZ_StoreContext_S (TZ_MemoryId_t id) {
uint32_t slot;
uint32_t sp;
if ((__get_IPSR() == 0U) || ((__get_CONTROL() & 2U) == 0U)) {
return 0U; // Thread Mode or using Main Stack for threads
}
if ((id == 0U) || (id > TZ_PROCESS_STACK_SLOTS)) {
return 0U; // Invalid ID
}
slot = id - 1U;
if (ProcessStackInfo[slot].sp == 0U) {
return 0U; // Inactive slot
}
sp = __get_PSP();
if ((sp < ProcessStackInfo[slot].sp_limit) ||
(sp > ProcessStackInfo[slot].sp_top)) {
return 0U; // SP out of range
}
ProcessStackInfo[slot].sp = sp;
// Default process stack pointer and stack limit
__set_PSPLIM((uint32_t)ProcessStackMemory);
__set_PSP ((uint32_t)ProcessStackMemory);
return 1U; // Success
}
| 2.046875 | 2 |
2024-11-18T22:25:25.740260+00:00 | 2014-09-29T18:49:57 | 2db2b26f1fe2e1ab15358257d3503ce27deaf404 | {
"blob_id": "2db2b26f1fe2e1ab15358257d3503ce27deaf404",
"branch_name": "refs/heads/master",
"committer_date": "2014-09-29T18:49:57",
"content_id": "cb39711a00f9fe82db572be7c891fa06d7c7e1ce",
"detected_licenses": [
"MIT"
],
"directory_id": "a40cbca65b95808f0ca187c2ade3c271bd3997ae",
"extension": "h",
"filename": "lobjder.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": 4357,
"license": "MIT",
"license_type": "permissive",
"path": "/include/lobjder.h",
"provenance": "stackv2-0115.json.gz:123002",
"repo_name": "ionutzmar/opengl_project",
"revision_date": "2014-09-29T18:49:57",
"revision_id": "ff6f84761991e56deca4a82bcfcd02c77529e7ba",
"snapshot_id": "799ddbd11878e8a8cd1bcfdf6ba3861ad963ac22",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ionutzmar/opengl_project/ff6f84761991e56deca4a82bcfcd02c77529e7ba/include/lobjder.h",
"visit_date": "2021-01-12T21:46:16.484143"
} | stackv2 | /*
lobjder library
Copyright (c) 2014 Neacsu Razvan
A simple OpenGL library to load .obj files and display them
Usage:
Declare a variable that contains the model
lbj_Model myModel;
Set the paths to model, material and textures
lbj_SetPaths("./path/to/model/", "./path/to/material/", "./path/to/texture/");
Load the file
lbj_LoadOBJToModel("model.obj", &myModel);
lbj_CreateVBO(&myModel, 0); // << Optional if you don't want to use VBOs
Then display the model using immediate mode
lbj_DrawModelIM(myModel);
or using VBO (must create the VBO before)
lbj_DrawModelVBO(myModel);
Done.
Note: model.obj must be in "./path/to/model/", model.mtl must be in "./path/to/material/" and other .jpg, .png, .bmp etc. files in "./path/to/texture/"
Note: Triangle and quad faces are supported. N-GONS are NOT supported
Note: stb_image is used for loading textures. See http://nothings.org/stb_image.c for more info
*/
#include <stdio.h>
#include <GL/glut.h>
// A 3 float vector
typedef struct {
GLfloat x, y, z;
} lbj_vector3f;
// A 3 int vector
typedef struct {
unsigned int x, y, z;
} lbj_vector3i;
// lbj_Arrayv is used for vertices, texture coordonates and normals
typedef struct {
lbj_vector3f * array;
size_t used;
size_t size;
} lbj_Arrayv;
// lbj_Arrayf is used for faces
typedef struct {
lbj_vector3i* array[4];
size_t used;
size_t size;
} lbj_Arrayf;
// Material structure
typedef struct {
char * fileName; // File name
unsigned char* texData; // Texture data
int texWidth; // Texture width
int texHeight; // Texture height
GLuint glTexName; // Texture name: used with glBindTexture(GL_TEXTURE_2D, texName) to swich to diffrent textures
char * matName; // Material name
GLfloat Ka[3]; // Material Ambient color
GLfloat Kd[3]; // Material Diffuse color
GLfloat Ks[3]; // Material Specular color
GLfloat Ns; // Material Shininess. Ranges form 0 to 1000
GLfloat Tr; // Material Transparency. 1 = fully opaque 0 = fully transparent
lbj_vector3f offset; // Texture offset, not used
lbj_vector3f scale; // Texture scale, not used
int illum; // not used
} lbj_Material;
// Material array
typedef struct {
lbj_Material * array;
size_t used;
size_t size;
} lbj_Arraym;
// Material index array
typedef struct {
unsigned int * array;
size_t used;
size_t size;
} lbj_Arraymi;
// Model structure
typedef struct {
// List of vertices
lbj_Arrayv v;
// Texture coordinates
lbj_Arrayv vt;
// Normals
lbj_Arrayv vn;
// Face Definitions
lbj_Arrayf f;
// Materials used
lbj_Arraym mats;
// Material index
lbj_Arraymi matsi;
// VBO vertex Buffer ID
GLuint vertexBuffID;
// VBO index Buffer ID
GLuint indexBuffID;
} lbj_Model;
// A vertex structure used for VBO
typedef struct {
// Position
GLfloat pos[3];
// Normal
GLfloat normal[3];
// Texture coordonates
GLfloat texCoord[2];
} lbj_VBOVertex;
// Sets paths to search for models, textures and materials
void lbj_SetPaths(char * modelsFolderPath, char * materialsFolderPath, char * texturesFolderPath);
// Loads a .obj file to a model
void lbj_LoadOBJToModel(char * fileName, lbj_Model * model);
// Draws the model to the scene using immediate mode
void lbj_DrawModelIM(lbj_Model model);
// Loads a .mtl file to a material array
void lbj_LoadMTLToMaterials(char * fileName, lbj_Arraym * mat, int init); // init = 0 will append all materials found to the array, init = 1 will initialize the array
// Loads a material to be used for drawing
void lbj_LoadMaterial(lbj_Material mat);
// Loads a default material to be used for drawing
void lbj_LoadDefaultMaterial();
// Set up flipping: 1 = flip, 0 = don't flip, other = leave unchanged
void lbj_SetFlipping(int _flipU, // Flip texture horizontally
int _flipV, // Flip texture vertically
int _flipX, // Flip model on the x axis
int _flipY, // Flip model on the y axis
int _flipZ); // Flip model on the z axis
// Creates and populates a VBO for the model
// Set "economic" to 1 if you want to reuse vertices or to 0 if you don't want to
// IMPORTANT: Don't use economic with large models: IT'S EXTREMELY SLOW
void lbj_CreateVBO(lbj_Model * model, int economic);
// Draws the model using VBO
void lbj_DrawModelVBO(lbj_Model model);
// Whether to print stats about the model or just warnings
void lbj_PrintStats(int value); | 2.828125 | 3 |
2024-11-18T22:25:26.911348+00:00 | 2023-08-13T07:00:15 | 910668b40c1f17258b9ac723805299cabdd8cae0 | {
"blob_id": "910668b40c1f17258b9ac723805299cabdd8cae0",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-13T07:00:15",
"content_id": "b8cdd8c1ec6e93f62b54c0e3226042883edb2b72",
"detected_licenses": [
"MIT"
],
"directory_id": "2266eb133fc3121daf0aa7f4560626b46b94afe0",
"extension": "c",
"filename": "zhi.c",
"fork_events_count": 49,
"gha_created_at": "2017-11-28T03:05:14",
"gha_event_created_at": "2023-02-01T03:42:14",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 112278568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3332,
"license": "MIT",
"license_type": "permissive",
"path": "/kungfu/skill/jiuyin-shengong/perform/zhi.c",
"provenance": "stackv2-0115.json.gz:123652",
"repo_name": "oiuv/mud",
"revision_date": "2023-08-13T07:00:15",
"revision_id": "e9ff076724472256b9b4bd88c148d6bf71dc3c02",
"snapshot_id": "6fbabebc7b784279fdfae06d164f5aecaa44ad90",
"src_encoding": "UTF-8",
"star_events_count": 99,
"url": "https://raw.githubusercontent.com/oiuv/mud/e9ff076724472256b9b4bd88c148d6bf71dc3c02/kungfu/skill/jiuyin-shengong/perform/zhi.c",
"visit_date": "2023-08-18T20:18:37.848801"
} | stackv2 | // zhi.c 九阴神指
#include <ansi.h>
inherit F_SSERVER;
#define ZHI "「" HIY "九阴神指" NOR "」"
int perform(object me, object target)
{
string msg;
object weapon;
int n;
int skill, ap, dp;
if (userp(me) && !me->query("can_perform/jiuyin-shengong/zhi"))
return notify_fail("你所使用的外功中没有这种功能。\n");
if (!target)
{
me->clean_up_enemy();
target = me->select_opponent();
}
skill = me->query_skill("jiuyin-shengong", 1);
if (!me->is_fighting(target))
return notify_fail(ZHI "只能对战斗中的对手使用。\n");
if (me->query_temp("weapon"))
return notify_fail(ZHI "只能空手施展!\n");
if (skill < 250)
return notify_fail("你的九阴神功等级不够,无法施展" ZHI "!\n");
if (me->query("neili") < 250)
return notify_fail("你现在真气不够,难以施展" ZHI "!\n");
if (me->query_skill_prepared("finger") != "jiuyin-shengong" && me->query_skill_prepared("unarmed") != "jiuyin-shengong")
return notify_fail("你没有准备使用九阴神功,无法施展" ZHI "。\n");
if (!living(target))
return notify_fail("对方都已经这样了,用不着这么费力吧?\n");
me->add("neili", -100);
ap = me->query_skill("unarmed");
if (ap < me->query_skill("finger"))
ap = me->query_skill("finger");
ap += me->query_skill("martial-cognize", 1);
dp = target->query_skill("parry") + target->query_skill("martial-cognize", 1);
msg = HIY "$N" HIY "出手成指,随意点戳,似乎看尽了$n" HIY + "招式中的破绽。\n" NOR;
if (ap / 2 + random(ap * 2) > dp)
{
n = 4 + random(4);
if (ap * 11 / 20 + random(ap) > dp)
{
msg += HIY "$n" HIY "见来指玄幻无比,全然无法抵挡,慌乱之下破绽迭出,$N" HIY "随手连出" + chinese_number(n) + "指!\n" NOR;
message_combatd(msg, me, target);
while (n-- && me->is_fighting(target))
{
if (random(2) && !target->is_busy())
target->start_busy(1);
COMBAT_D->do_attack(me, target, 0, 0);
}
me->start_busy(1 + random(n));
weapon = target->query_temp("weapon");
if (weapon && random(ap) / 2 > dp && weapon->query("type") != "pin")
{
msg = HIW "$n" HIW "觉得眼前眼花缭乱,手中的" + weapon->name() +
HIW "一时竟然拿捏不住,脱手而出!\n" NOR;
weapon->move(environment(me));
}
else
{
msg = HIY "$n勉力抵挡,一时间再也无力反击。\n" NOR;
}
if (!me->is_fighting(target))
// Don't show the message
return 1;
}
else
{
msg += HIY "$n" HIY "不及多想,连忙抵挡,全然无法反击。\n" NOR;
if (!target->is_busy())
target->start_busy(4 + random(skill / 30));
}
}
else
{
msg += HIC "不过$n" HIC "紧守门户,不露半点破绽。\n" NOR;
me->start_busy(3 + random(2));
}
message_combatd(msg, me, target);
return 1;
}
| 2.1875 | 2 |
2024-11-18T22:25:26.957123+00:00 | 2021-02-01T17:27:12 | 77e86ed04893b751c8799c925107082e4116d9a9 | {
"blob_id": "77e86ed04893b751c8799c925107082e4116d9a9",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-01T17:27:12",
"content_id": "106f58089c33a8afa6883f4e3843001c0dcf3d5c",
"detected_licenses": [
"MIT"
],
"directory_id": "dc4df80060e74ad8c201c92bd20970b3823cc5ec",
"extension": "c",
"filename": "GL_Texture.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": 1251,
"license": "MIT",
"license_type": "permissive",
"path": "/AURAE/AURAE/PC/Graphics/GL_Texture.c",
"provenance": "stackv2-0115.json.gz:123783",
"repo_name": "DreamcastNick/LMP3D",
"revision_date": "2021-02-01T17:27:12",
"revision_id": "d64b5dd2b8368c991e4c627ed6b72387ac721cb3",
"snapshot_id": "98412edae17428395a4c078b67eaad664923c1b1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DreamcastNick/LMP3D/d64b5dd2b8368c991e4c627ed6b72387ac721cb3/AURAE/AURAE/PC/Graphics/GL_Texture.c",
"visit_date": "2023-02-26T05:34:43.341474"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#ifdef PC
#include <GL/gl.h>
#include "AURAE/AURAE.h"
void AURAE_Texture_Upload_VRAM(AURAE_Texture *texture)
{
glBindTexture(GL_TEXTURE_2D,texture->address);
glTexImage2D (
GL_TEXTURE_2D, //Type : texture 2D
0, //Mipmap : aucun
texture->color, //Couleurs : 4
texture->w, //Largeur
texture->h, //Hauteur
0, //Largeur du bord : 0
texture->psm,
texture->psm2, //Type des couleurs
texture->pixel //Addresse de l'texture
);
}
void AURAE_Texture_Upload(AURAE_Texture *texture)
{
if(texture == NULL) return;
glGenTextures(1,&texture->address);
AURAE_Texture_Upload_VRAM(texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //GL_LINEAR
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
void AURAE_Texture_Setup(AURAE_Texture *texture)
{
if(texture == NULL) return;
glBindTexture(GL_TEXTURE_2D,texture->address);
}
void AURAE_Texture_Free_VRAM(AURAE_Texture *texture)
{
GLuint tid = (GLuint)texture->address;
glDeleteTextures(1,&tid);
}
void AURAE_VRAM_Info(char *info)
{
//int vram = (PS2_vram_pointer&0xFFFFFF);
//sprintf(info,"vram :%x/0x100000\n",vram);
}
#endif
| 2.421875 | 2 |
2024-11-18T22:25:27.776931+00:00 | 2019-09-27T14:16:14 | 4c30a21692a37e793080ecc10124a87c8e49f263 | {
"blob_id": "4c30a21692a37e793080ecc10124a87c8e49f263",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-27T14:16:14",
"content_id": "91c2504e780cfe2fa2cc876c2969f5b103e9b555",
"detected_licenses": [
"MIT"
],
"directory_id": "2710624ebc794bd1735548d66c33bee7882b3a1d",
"extension": "c",
"filename": "error_correction.c",
"fork_events_count": 0,
"gha_created_at": "2019-08-16T13:18:22",
"gha_event_created_at": "2019-08-16T13:18:22",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 202730872,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 48453,
"license": "MIT",
"license_type": "permissive",
"path": "/src/error_correction.c",
"provenance": "stackv2-0115.json.gz:123914",
"repo_name": "sriharikrishna/QuaC",
"revision_date": "2019-09-27T14:16:14",
"revision_id": "679018a8f2642ca4c1fdf2b5eee275b4645bdbad",
"snapshot_id": "80e4cf75f299100ca76b24a450bb95d57f8e9412",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sriharikrishna/QuaC/679018a8f2642ca4c1fdf2b5eee275b4645bdbad/src/error_correction.c",
"visit_date": "2020-07-05T18:30:03.828708"
} | stackv2 | #include "kron_p.h" //Includes petscmat.h and operators_p.h
#include "quac_p.h"
#include "error_correction.h"
#include "operators.h"
#include "quantum_gates.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
Mat *_DQEC_mats;
int _discrete_ec = 0;
void build_recovery_lin(Mat *recovery_mat,operator error,char commutation_string[],int n_stabilizers,...){
va_list ap;
PetscScalar plus_or_minus_1=1.0,scale_val;
PetscInt i;
PetscReal fill;
Mat temp_op_mat, work_mat1, work_mat2, this_stab;
/*
* We are calculating the recovery operator, which is defined as:
* R = E * (1 +/- M_1)/2 * (1 +/- M_2)/2 * ...
* where E is the error and M_i is the stabilizer. The +/- is chosen
* based on whether E commutes or anti-commutes with the stabilizer
*/
/* Construct our error matrix */
combine_ops_to_mat(&temp_op_mat,1,error);
/*
* Copy the error matrix into our recovery matrix
* This works as an initialization
*/
MatConvert(temp_op_mat,MATSAME,MAT_INITIAL_MATRIX,recovery_mat);
MatConvert(temp_op_mat,MATSAME,MAT_INITIAL_MATRIX,&work_mat1);
va_start(ap,n_stabilizers);
fill = 1.0;
/* Loop through stabilizers */
for (i=0;i<n_stabilizers;i++){
this_stab = va_arg(ap,Mat);
/* Look up commutation pattern from commutation_string */
if (commutation_string[i]=='1') {
plus_or_minus_1 = 1.0;
} else if (commutation_string[i]=='0') {
plus_or_minus_1 = -1.0;
} else {
if (nid==0){
printf("ERROR! commutation_string had a bad character! It can \n");
printf(" only have 0 or 1!\n");
exit(0);
}
}
/* Copy our stabilizer */
MatCopy(this_stab,work_mat1,DIFFERENT_NONZERO_PATTERN);;
/* Calculate M +/- I */
MatShift(work_mat1,plus_or_minus_1);
/* Calculate +/- 0.5 * (M +/- I) */
scale_val = 0.5 * plus_or_minus_1;
MatScale(work_mat1,scale_val);
/* Calculate C * +/- 0.5 * (M +/- I) */
MatMatMult(*recovery_mat,work_mat1,MAT_INITIAL_MATRIX,fill,&work_mat2);
/* Copy the result back into recovery_mat */
MatCopy(work_mat2,*recovery_mat,DIFFERENT_NONZERO_PATTERN);
/* Free work_mat2 */
MatDestroy(&work_mat2);
}
va_end(ap);
MatDestroy(&work_mat1);
return;
}
/*
* create_stabilizer stores the set of operators which make up a stabilizer
* Inputs:
* int n_ops: the number of operators in the stabilizer
* operators op1, op2,...: the operators that make up the stabilizer
* Outputs:
* stabilizer *stab: a new stabilizer object, which just stores the list of operators
*/
void create_stabilizer(stabilizer *stab,int n_ops,...){
va_list ap;
PetscInt i;
va_start(ap,n_ops);
(*stab).n_ops = n_ops;
(*stab).ops = malloc(n_ops*sizeof(struct operator));
/* Loop through passed in ops and store in list */
for (i=0;i<n_ops;i++){
(*stab).ops[i] = va_arg(ap,operator);
}
va_end(ap);
return;
}
/*
* destroy_stabilizer frees the memory from a stabilizer.
* Inputs:
* stabilizer *stab - pointer to stabilizer to be freed
*/
void destroy_stabilizer(stabilizer *stab){
free((*stab).ops);
}
/*
* add_lin_recovery adds a Lindblad L(C) term to the system of equations, where
* L(C)p = C p C^t - 1/2 (C^t C p + p C^t C)
* Or, in superoperator space (t = conjugate transpose, T = transpose, * = conjugate)
* Lp = C* cross C - 1/2(C^T C* cross I + I cross C^t C) p
* For this routine, C is a recovery operator, constructed of an error,
* commutation relations, stabilizers.
* Inputs:
* PetscScalar a: scalar to multiply L term (note: Full term, not sqrt())
* Mat add_to_lin: mat to make L(C) of
* Outputs:
* none
*/
void add_lin_recovery(PetscScalar a,PetscInt same_rate,operator error,char commutation_string[],int n_stabilizers,...){
va_list ap;
PetscScalar mat_scalar,add_to_mat,op_val;
PetscInt i,Istart,Iend,this_i,i_stab,j_stab,k_stab,l_stab;
PetscInt i1,i2,j1,j2,num_nonzero1,num_nonzero2,i_comb,j_comb;
/*
* The following arrays are used in C* C calculationsg
* Maybe this is memory inefficient, but it takes
* far less memory than the DM, so it should be fine
*/
PetscScalar this_row1[total_levels],this_row2[total_levels];
PetscInt row_nonzeros1[total_levels],row_nonzeros2[total_levels];
stabilizer *stabs;
/*
* We are calculating the recovery operator, which is defined as:
* R = E * (1 +/- M_1)/2 * (1 +/- M_2)/2 * ...
* where E is the error and M_i is the stabilizer. The +/- is chosen
* based on whether E commutes or anti-commutes with the stabilizer
*
* We will directly add the superoperator expanded values into the
* full_A matrix, never explicitly building R, but rather,
* building I cross R^t R + (R^t R)* cross I + R* cross R
*/
PetscLogEventBegin(add_lin_recovery_event,0,0,0,0);
_check_initialized_A();
_lindblad_terms = 1;
if (PetscAbsComplex(a)!=0) {
MatGetOwnershipRange(full_A,&Istart,&Iend);
va_start(ap,n_stabilizers);
stabs = malloc(n_stabilizers*sizeof(struct stabilizer));
/* Loop through passed in ops and store in list */
for (i=0;i<n_stabilizers;i++){
stabs[i] = va_arg(ap,stabilizer);
}
va_end(ap);
/*
* Construct R^t R. Due to interesting relations among the pauli operators
* (sig_i * sig_i) = I and sig_i = sig_i^t, as well as the fact that
* pauli operators from different subspaces commute and the stabilizers
* themselve commute, R^t R has a rather simple form:
*
* R^t R = \prod_i (I + M_i)/2
*
* This is almost the same as R, but without the error!
* This product is very similar to the elementary symmetric polynomials, and there
* are formula for calculating the values (which we don't make use of at this point,
* given we plan to have few stabilizers at this time).
* An example, with 3 stabilizers:
*
* R^t R = 1/2^3 (I + M_1 + M_2 + M_3 + M_1*M_2 + M_1*M_3 + M_2*M_3 + M_1*M_2*M_3)
*
* Generally, the form is:
* R^t R = 1/2^n (I + \sum_i M_i + \sum_i<j M_i*M_j + \sum_i<j<k M_i*M_j*M_k + ...)
*
* Since all M_i are constructed of tensor products (like I \cross Z \cross Z), and each of
* the submatrices are very sparse, we can use tricks (like in combine_ops_to_mat) to
* efficiently generate each of the members of the sum.
*
* Due to the form of commutation strings, if all of the error rates for each of
* the recover operators are the same, you only need to add the U* cross U terms
*/
mat_scalar = -1/pow(2,n_stabilizers) * 0.5 * a; //Store the common multiplier for all terms, -0.5*a*1/4^n
/* First, do I cross C^t C and (C^t C)* cross I */
/*
* We break it up into different numbers of stabilizers, for the different
* numbers of terms (i.e., M_i or M_i*M_j, or M_i*M_j*M_k, etc)
* There should be a general way to do this that supports any number,
* but we code only to a maximum of 4 for now.
*/
/* I terms - a * (I cross I + I cross I) = 2*a*I in the total space*/
MatGetOwnershipRange(full_A,&Istart,&Iend);
for (i=Istart;i<Iend;i++){
add_to_mat = 2*mat_scalar;
MatSetValue(full_A,i,i,add_to_mat,ADD_VALUES);
}
if (same_rate==0) {
/* Single M_i terms */
for (i=Istart;i<Iend;i++){
for (i_stab=0;i_stab<2;i_stab++){//n_stabilizers;i_stab++){
/* First loop through i_stab's ops */
/* Reset this_i and op_val to identity */
this_i = i; // The leading index which we check
op_val = 1.0;
// Add I cross U
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
add_to_mat = op_val * mat_scalar;
/* printf("add_to_mat: %f i: %d this_i: %d\n",add_to_mat,i,this_i); */
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
// Add U* cross I
/* Reset this_i and op_val to identity */
this_i = i; // The leading index which we check
op_val = 1.0;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],1);
add_to_mat = op_val * mat_scalar;
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
}
}
if (n_stabilizers > 1) {
/* M_i*M_j terms */
for (i=Istart;i<Iend;i++){
for (i_stab=0;i_stab<n_stabilizers;i_stab++){
for (j_stab=i_stab+1;j_stab<n_stabilizers;j_stab++){
/* First loop through i_stab's ops */
/* Reset this_i and op_val to identity */
// Add I cross U
this_i = i; // The leading index which we check
op_val = 1.0;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],-1);
}
add_to_mat = op_val * mat_scalar;
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
// Add U* cross I
this_i = i; // The leading index which we check
op_val = 1.0;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],1);
}
add_to_mat = op_val * mat_scalar;
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
}
}
}
}
if (n_stabilizers>2) {
/* M_i*M_j*M_k terms */
for (i=Istart;i<Iend;i++){
for (i_stab=0;i_stab<n_stabilizers;i_stab++){
for (j_stab=i_stab+1;j_stab<n_stabilizers;j_stab++){
for (k_stab=j_stab+1;k_stab<n_stabilizers;k_stab++){
// Add I cross U
/* Reset this_i and op_val to identity */
this_i = i; // The leading index which we check
op_val = 1.0;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],-1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[k_stab],commutation_string[k_stab],-1);
}
add_to_mat = op_val * mat_scalar;
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
// Add I cross U
/* Reset this_i and op_val to identity */
this_i = i; // The leading index which we check
op_val = 1.0;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[k_stab],commutation_string[k_stab],1);
}
add_to_mat = op_val * mat_scalar;
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
}
}
}
}
}
if (n_stabilizers>3) {
/* M_i*M_j*M_k*M_l terms */
for (i=Istart;i<Iend;i++){
for (i_stab=0;i_stab<n_stabilizers;i_stab++){
for (j_stab=i_stab+1;j_stab<n_stabilizers;j_stab++){
for (k_stab=j_stab+1;k_stab<n_stabilizers;k_stab++){
for (l_stab=k_stab+1;l_stab<n_stabilizers;l_stab++){
// Add I cross U
/* Reset this_i and op_val to identity */
this_i = i; // The leading index which we check
op_val = 1.0;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],-1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[k_stab],commutation_string[k_stab],-1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[l_stab],commutation_string[l_stab],-1);
}
add_to_mat = op_val * mat_scalar;
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
// Add U* cross I
/* Reset this_i and op_val to identity */
this_i = i; // The leading index which we check
op_val = 1.0;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[k_stab],commutation_string[k_stab],1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[l_stab],commutation_string[l_stab],1);
}
add_to_mat = op_val * mat_scalar;
MatSetValue(full_A,i,this_i,add_to_mat,ADD_VALUES);
}
}
}
}
}
}
}
if (n_stabilizers>4) {
if (nid==0){
printf("ERROR! A maximum of 4 stabilizers is supported at this time!\n");
exit(0);
}
}
/*
* Add (C* cross C) to the superoperator matrix,
* We expand R* and R, get their respective i,j
* and use _add_to_PETSc_kron_ij to add the value
* to the full_A
*
* R = E * (1 +/- M_1)/2 * (1 +/- M_2)/2 * ...
* or
* R = E * \prod_i (1 +/- M_i)/2
*
* Similar to the calculation of R^t R above,
* we expand the product as:
*
* R = E * (I + M_1 + M_2 + M_3 + M_1 * M_2 + ...)
*
* a la elementary symmetric polynomials.
* We take a given i, calculate the value for each
* of the individual terms, then sum it all up.
*/
// Store common prefactors. 2*n_stab because C* cross C
mat_scalar = 1/pow(2,2*n_stabilizers) * a;
// FIXME Consider distributing this loop in some smart fashion
/* for (i1=0;i1<total_levels;i1++){ */
/* /\* Get the nonzeros for row i1 of C *\/ */
/* _get_row_nonzeros(this_row1,row_nonzeros1,&num_nonzero1,i1,error,commutation_string,n_stabilizers,stabs); */
/* for (i2=0;i2<total_levels;i2++){ */
/* /\* Get the nonzeros for row i2 of C *\/ */
/* /\* FIXME: Consider skipping the i1=i2 spot *\/ */
/* _get_row_nonzeros(this_row2,row_nonzeros2,&num_nonzero2,i2,error,commutation_string,n_stabilizers,stabs); */
/* /\* */
/* * Use the general formula for the kronecker product between */
/* * two matrices to find the full value */
/* *\/ */
/* for (j1=0;j1<num_nonzero1;j1++){ */
/* for (j2=0;j2<num_nonzero2;j2++){ */
/* /\* Get the combind indices *\/ */
/* i_comb = total_levels*i1 + i2; */
/* j_comb = total_levels*row_nonzeros1[j1] + row_nonzeros2[j2]; */
/* add_to_mat = mat_scalar * */
/* PetscConjComplex(this_row1[row_nonzeros1[j1]])* */
/* this_row2[row_nonzeros2[j2]]; */
/* if (i_comb>=Istart&&i_comb<Iend) MatSetValue(full_A,i_comb,j_comb,add_to_mat,ADD_VALUES); */
/* } */
/* } */
/* } */
/* } */
for (i=Istart;i<Iend;i++){
/* Calculate i1, i2 */
i1 = i/total_levels;
i2 = i%total_levels;
_get_row_nonzeros(this_row1,row_nonzeros1,&num_nonzero1,i1,error,commutation_string,n_stabilizers,stabs);
_get_row_nonzeros(this_row2,row_nonzeros2,&num_nonzero2,i2,error,commutation_string,n_stabilizers,stabs);
for (j1=0;j1<num_nonzero1;j1++){
for (j2=0;j2<num_nonzero2;j2++){
/* Get the combind indices */
i_comb = total_levels*i1 + i2;
j_comb = total_levels*row_nonzeros1[j1] + row_nonzeros2[j2];
add_to_mat = mat_scalar *
PetscConjComplex(this_row1[row_nonzeros1[j1]])*
this_row2[row_nonzeros2[j2]];
if (PetscAbsComplex(add_to_mat)>1e-5){
MatSetValue(full_A,i_comb,j_comb,add_to_mat,ADD_VALUES);
}
}
}
}
}
PetscLogEventEnd(add_lin_recovery_event,0,0,0,0);
return;
}
/* Get the j and val from a stabilizer - essentially multiply the ops for a given row
* tensor_control - switch on which superoperator to compute
* -1: I cross G
* 0: G* cross G
* 1: G* cross I
*/
void _get_this_i_and_val_from_stab(PetscInt *this_i, PetscScalar *op_val,stabilizer stab,
char commutation_char,PetscInt tensor_control){
PetscInt j,this_j;
PetscScalar val;
PetscReal plus_or_minus_1=1.0;
if (commutation_char=='1') {
plus_or_minus_1 = 1.0;
} else if (commutation_char=='0') {
plus_or_minus_1 = -1.0;
} else {
if (nid==0){
printf("ERROR! commutation_string had a bad character! It can \n");
printf(" only have 0 or 1!\n");
exit(0);
}
}
for (j=0;j<stab.n_ops;j++){
_get_val_j_from_global_i(*this_i,stab.ops[j],&this_j,&val,tensor_control); // Get the corresponding j and val
if (this_j<0) {
/*
* Negative j says there is no nonzero value for a given this_i
* As such, we can immediately break the loop for i
*/
*op_val = 0.0;
break;
} else {
*this_i = this_j;
*op_val = *op_val*val;
}
}
if (tensor_control!=0){
/*
* We don't need to apply plus_or_minus_1 if tensor
* control is 0 because we would apply it twice (U* and U),
* always leading to +1
*/
*op_val = *op_val*plus_or_minus_1; //Include commutation information
}
}
/* Gets the nonzeros in a row for a given i, error operator, and stabilizers */
void _get_row_nonzeros(PetscScalar this_row[],PetscInt row_nonzeros[],PetscInt *num_nonzero,PetscInt i,operator error,char commutation_string[],int n_stabilizers,stabilizer stabs[]){
PetscScalar error_val,op_val;
PetscInt j,this_i,error_i,i_stab,j_stab,k_stab,l_stab,found;
/* Get the error terms nonzero for this i */
_get_val_j_from_global_i(i,error,&error_i,&error_val,-1); // Get the corresponding j and val
this_i = error_i; // The leading index which we check
op_val = error_val;
/*
* Reset num_nonzero. We need not reset the arrays because
* we will only access the indices described in the list,
* and those values will be correspondingly updated
*/
*num_nonzero = 0;
/* E * I term - since this is the first term, we know we haven't added anything yet*/
this_row[this_i] = op_val;
row_nonzeros[*num_nonzero] = this_i;
*num_nonzero = *num_nonzero + 1;
/*
* Single E * M_i terms. The error term is included from the
* fact tht this_i and op_val are reset to the error
* operator's values for each new stabilizer.
*/
for (i_stab=0;i_stab<n_stabilizers;i_stab++){
/* Reset this_i and op_val to error values */
this_i = error_i; // The leading index which we check
op_val = error_val;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
if (op_val!=0.0) {
/*
* Check if we already have a value in this spot.
* This is a linear search; it should be fine, since
* these matrices are incredibly sparse. But, consider
* changing to faster search.
*/
found = 0;
for (j=0;j<*num_nonzero;j++){
if (this_i==row_nonzeros[j]) {
// Found it!
found = 1;
break;
}
}
/* Add to this_row1 */
if (found==1){
/* There was a value here, so add to it */
this_row[this_i] = this_row[this_i] + op_val;
} else {
/* This is a new value, so just set */
this_row[this_i] = op_val;
row_nonzeros[*num_nonzero] = this_i;
*num_nonzero = *num_nonzero + 1;
}
}
}
if (n_stabilizers>1) {
/* M_i*M_j terms */
for (i_stab=0;i_stab<n_stabilizers;i_stab++){
for (j_stab=i_stab+1;j_stab<n_stabilizers;j_stab++){
/* Reset this_i and op_val to error values */
this_i = error_i; // The leading index which we check
op_val = error_val;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],-1);
}
/*
* Now we have an element of the matrix form of E*M_i*M_j,
* add it to the row_nonzero value
*/
if (op_val!=0.0) {
/*
* Check if we already have a value in this spot.
* This is a linear search; it should be fine, since
* these matrices are incredibly sparse. But, consider
* changing to faster search.
*/
found = 0;
for (j=0;j<*num_nonzero;j++){
if (this_i==row_nonzeros[j]) {
// Found it!
found = 1;
break;
}
}
/* Add to this_row1 */
if (found==1){
/* There was a value here, so add to it */
this_row[this_i] = this_row[this_i] + op_val;
} else {
/* This is a new value, so just set */
this_row[this_i] = op_val;
row_nonzeros[*num_nonzero] = this_i;
*num_nonzero = *num_nonzero + 1;
}
}
}
}
}
if (n_stabilizers>2) {
/* M_i*M_j*M_k terms */
for (i_stab=0;i_stab<n_stabilizers;i_stab++){
for (j_stab=i_stab+1;j_stab<n_stabilizers;j_stab++){
for (k_stab=j_stab+1;k_stab<n_stabilizers;k_stab++){
/* Reset this_i and op_val to error values */
this_i = error_i; // The leading index which we check
op_val = error_val;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],-1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[k_stab],commutation_string[k_stab],-1);
}
/*
* Now we have an element of the matrix form of E*M_i*M_j,
* add it to the row_nonzero value
*/
if (op_val!=0.0) {
/*
* Check if we already have a value in this spot.
* This is a linear search; it should be fine, since
* these matrices are incredibly sparse. But, consider
* changing to faster search.
*/
found = 0;
for (j=0;j<*num_nonzero;j++){
if (this_i==row_nonzeros[j]) {
// Found it!
found = 1;
break;
}
}
/* Add to this_row1 */
if (found==1){
/* There was a value here, so add to it */
this_row[this_i] = this_row[this_i] + op_val;
} else {
/* This is a new value, so just set */
this_row[this_i] = op_val;
row_nonzeros[*num_nonzero] = this_i;
*num_nonzero = *num_nonzero + 1;
}
}
}
}
}
}
if (n_stabilizers>3) {
/* M_i*M_j*M_k*M_l terms */
for (i_stab=0;i_stab<n_stabilizers;i_stab++){
for (j_stab=i_stab+1;j_stab<n_stabilizers;j_stab++){
for (k_stab=j_stab+1;k_stab<n_stabilizers;k_stab++){
for (l_stab=k_stab+1;l_stab<n_stabilizers;l_stab++){
/* Reset this_i and op_val to error values */
this_i = error_i; // The leading index which we check
op_val = error_val;
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[i_stab],commutation_string[i_stab],-1);
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[j_stab],commutation_string[j_stab],-1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[k_stab],commutation_string[k_stab],-1);
}
if (op_val!= 0.0) {
_get_this_i_and_val_from_stab(&this_i,&op_val,stabs[l_stab],commutation_string[l_stab],-1);
}
/*
* Now we have an element of the matrix form of E*M_i*M_j,
* add it to the row_nonzero value
*/
if (op_val!=0.0) {
/*
* Check if we already have a value in this spot.
* This is a linear search; it should be fine, since
* these matrices are incredibly sparse. But, consider
* changing to faster search.
*/
found = 0;
for (j=0;j<*num_nonzero;j++){
if (this_i==row_nonzeros[j]) {
// Found it!
found = 1;
break;
}
}
/* Add to this_row1 */
if (found==1){
/* There was a value here, so add to it */
this_row[this_i] = this_row[this_i] + op_val;
} else {
/* This is a new value, so just set */
this_row[this_i] = op_val;
row_nonzeros[*num_nonzero] = this_i;
*num_nonzero = *num_nonzero + 1;
}
}
}
}
}
}
}
return;
}
/*
* Create an encoder. The first of the passed in systems is assumed to be the
* qubit that is encoded/decoded to.
*/
void create_encoded_qubit(encoded_qubit *new_encoder,encoder_type my_encoder_type,...){
PetscInt num_qubits,i,qubit;
va_list ap;
if(my_encoder_type==NONE){
num_qubits = 1;
(*new_encoder).num_qubits = num_qubits;
(*new_encoder).my_encoder_type = NONE;
(*new_encoder).qubits = malloc(num_qubits*sizeof(PetscInt));
va_start(ap,num_qubits);
for (i=0;i<num_qubits;i++){
qubit = va_arg(ap,int);
(*new_encoder).qubits[i] = qubit;
}
create_circuit(&((*new_encoder).encoder_circuit),1);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,EYE,(*new_encoder).qubits[0]);
create_circuit(&((*new_encoder).decoder_circuit),1);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,EYE,(*new_encoder).qubits[0]);
} else if(my_encoder_type==BIT){
num_qubits = 3;
(*new_encoder).num_qubits = num_qubits;
(*new_encoder).my_encoder_type = BIT;
(*new_encoder).qubits = malloc(num_qubits*sizeof(PetscInt));
va_start(ap,num_qubits);
for (i=0;i<num_qubits;i++){
qubit = va_arg(ap,int);
(*new_encoder).qubits[i] = qubit;
}
create_circuit(&((*new_encoder).encoder_circuit),2);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[2]);
create_circuit(&((*new_encoder).decoder_circuit),2);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[1]);
} else if(my_encoder_type==PHASE){
num_qubits = 3;
(*new_encoder).num_qubits = num_qubits;
(*new_encoder).my_encoder_type = PHASE;
(*new_encoder).qubits = malloc(num_qubits*sizeof(PetscInt));
va_start(ap,num_qubits);
for (i=0;i<num_qubits;i++){
qubit = va_arg(ap,int);
(*new_encoder).qubits[i] = qubit;
}
create_circuit(&((*new_encoder).encoder_circuit),5);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[2]);
create_circuit(&((*new_encoder).decoder_circuit),5);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CNOT,(*new_encoder).qubits[0],(*new_encoder).qubits[1]);
} else if(my_encoder_type==FIVE){
num_qubits = 5;
(*new_encoder).num_qubits = num_qubits;
(*new_encoder).my_encoder_type = FIVE;
(*new_encoder).qubits = malloc(num_qubits*sizeof(PetscInt));
va_start(ap,num_qubits);
for (i=0;i<num_qubits;i++){
qubit = va_arg(ap,int);
(*new_encoder).qubits[i] = qubit;
}
create_circuit(&((*new_encoder).encoder_circuit),21);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CmZ,(*new_encoder).qubits[0],(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[0],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[4],(*new_encoder).qubits[3]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[4],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CXZ,(*new_encoder).qubits[4],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,SIGMAZ,(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[3]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[3],(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[3],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CNOT,(*new_encoder).qubits[3],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[2],(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[2],(*new_encoder).qubits[3]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CNOT,(*new_encoder).qubits[2],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[1],(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CZ,(*new_encoder).qubits[1],(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,CXZ,(*new_encoder).qubits[1],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).encoder_circuit),1.0,SIGMAZ,(*new_encoder).qubits[1]);
create_circuit(&((*new_encoder).decoder_circuit),21);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,SIGMAZ,(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZX,(*new_encoder).qubits[1],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[1],(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[1],(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CNOT,(*new_encoder).qubits[2],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[2],(*new_encoder).qubits[3]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[2],(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CNOT,(*new_encoder).qubits[3],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[3],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[3],(*new_encoder).qubits[2]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[3]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,SIGMAZ,(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZX,(*new_encoder).qubits[4],(*new_encoder).qubits[0]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[4],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[4],(*new_encoder).qubits[3]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,HADAMARD,(*new_encoder).qubits[4]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CZ,(*new_encoder).qubits[0],(*new_encoder).qubits[1]);
add_gate_to_circuit(&((*new_encoder).decoder_circuit),1.0,CmZ,(*new_encoder).qubits[0],(*new_encoder).qubits[4]);
} else {
if (nid==0){
printf("ERROR! Encoding type not understood!\n");
exit(0);
}
}
return;
}
//The ... are the encoders, assumes we decode to the first of the list in the encoder
void add_encoded_gate_to_circuit(circuit *circ,PetscReal time,gate_type my_gate_type,...){
int num_qubits=0,qubit,i;
va_list ap;
encoded_qubit *encoders;
PetscReal theta;
if (_gate_array_initialized==0){
//Initialize the array of gate function pointers
_initialize_gate_function_array();
_gate_array_initialized = 1;
}
_check_gate_type(my_gate_type,&num_qubits);
if ((*circ).num_gates==(*circ).gate_list_size){
if (nid==0){
printf("ERROR! Gate list not large enough (encoded)!\n");
exit(1);
}
}
PetscMalloc1(num_qubits,&encoders);
if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ) {
va_start(ap,num_qubits+1);
} else {
va_start(ap,num_qubits);
}
//First, get the encoders
for (i=0;i<num_qubits;i++){
encoders[i] = va_arg(ap,encoded_qubit);
}
// Now, add the decoding circuit(s) to the output circuit
for (i=0;i<num_qubits;i++){
// Only add a decoder if we have an encoded qubit
if (encoders[i].my_encoder_type!=NONE){
add_circuit_to_circuit(circ,encoders[i].decoder_circuit,time);
}
}
// FIXME: Call add_gate_to_circuit here
// Store arguments for the logical operation in list
(*circ).gate_list[(*circ).num_gates].qubit_numbers = malloc(num_qubits*sizeof(int));
(*circ).gate_list[(*circ).num_gates].time = time;
(*circ).gate_list[(*circ).num_gates].my_gate_type = my_gate_type;
(*circ).gate_list[(*circ).num_gates]._get_val_j_from_global_i = _get_val_j_functions_gates[my_gate_type+_min_gate_enum];
// Loop through and store qubits
for (i=0;i<num_qubits;i++){
qubit = encoders[i].qubits[0]; //assumes we decode to the first of the list
(*circ).gate_list[(*circ).num_gates].qubit_numbers[i] = qubit;
}
if (my_gate_type==RX||my_gate_type==RY||my_gate_type==RZ) {
//Get the theta parameter from the last argument passed in
theta = va_arg(ap,PetscReal);
(*circ).gate_list[(*circ).num_gates].theta = theta;
} else {
//Set theta to 0
(*circ).gate_list[(*circ).num_gates].theta = 0;
}
(*circ).num_gates = (*circ).num_gates + 1;
// Now, reencode our qubits
for (i=0;i<num_qubits;i++){
// Only add a decoder if we have an encoded qubit
if (encoders[i].my_encoder_type!=NONE){
add_circuit_to_circuit(circ,encoders[i].encoder_circuit,time);
}
}
return;
}
//The ... are the encoders, assumes we encode from the first of the list in the encoder
void encode_state(Vec rho,PetscInt num_logical_qubits,...){
PetscInt i,j;
va_list ap;
encoded_qubit this_qubit;
va_start(ap,num_logical_qubits);
//Loop through the qubit, multiplying rho by the encoding circuit
for (i=0;i<num_logical_qubits;i++){
this_qubit = va_arg(ap,encoded_qubit);
for (j=0;j<this_qubit.encoder_circuit.num_gates;j++) {
_apply_gate(this_qubit.encoder_circuit.gate_list[j],rho);
}
}
return;
}
//The ... are the encoders, assumes we encode from the first of the list in the encoder
void decode_state(Vec rho,PetscInt num_logical_qubits,...){
PetscInt i,j;
va_list ap;
encoded_qubit this_qubit;
va_start(ap,num_logical_qubits);
//Loop through the qubit, multiplying rho by the encoding circuit
for (i=0;i<num_logical_qubits;i++){
this_qubit = va_arg(ap,encoded_qubit);
for (j=0;j<this_qubit.decoder_circuit.num_gates;j++) {
_apply_gate(this_qubit.decoder_circuit.gate_list[j],rho);
}
}
return;
}
void add_continuous_error_correction(encoded_qubit this_qubit,PetscReal correction_rate){
stabilizer S1,S2,S3,S4;
operator qubit0,qubit1,qubit2,qubit3,qubit4;
if (this_qubit.my_encoder_type == NONE){
//No encoding, no error correction needed
} else if (this_qubit.my_encoder_type == BIT){
qubit0 = subsystem_list[this_qubit.qubits[0]];
qubit1 = subsystem_list[this_qubit.qubits[1]];
qubit2 = subsystem_list[this_qubit.qubits[2]];
create_stabilizer(&S1,2,qubit0->sig_z,qubit1->sig_z);
create_stabilizer(&S2,2,qubit1->sig_z,qubit2->sig_z);
add_lin_recovery(correction_rate,1,qubit0->eye,(char *)"11",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit0->sig_x,(char *)"01",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit1->sig_x,(char *)"00",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit2->sig_x,(char *)"10",2,S1,S2);
destroy_stabilizer(&S1);
destroy_stabilizer(&S2);
} else if (this_qubit.my_encoder_type == PHASE){
qubit0 = subsystem_list[this_qubit.qubits[0]];
qubit1 = subsystem_list[this_qubit.qubits[1]];
qubit2 = subsystem_list[this_qubit.qubits[2]];
create_stabilizer(&S1,2,qubit0->sig_x,qubit1->sig_x);
create_stabilizer(&S2,2,qubit1->sig_x,qubit2->sig_x);
add_lin_recovery(correction_rate,1,qubit0->eye,(char *)"11",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit0->sig_z,(char *)"01",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit1->sig_z,(char *)"00",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit2->sig_z,(char *)"10",2,S1,S2);
destroy_stabilizer(&S1);
destroy_stabilizer(&S2);
} else if (this_qubit.my_encoder_type == FIVE) {
qubit0 = subsystem_list[this_qubit.qubits[0]];
qubit1 = subsystem_list[this_qubit.qubits[1]];
qubit2 = subsystem_list[this_qubit.qubits[2]];
qubit3 = subsystem_list[this_qubit.qubits[3]];
qubit4 = subsystem_list[this_qubit.qubits[4]];
create_stabilizer(&S1,4,qubit0->sig_x,qubit1->sig_z,qubit2->sig_z,qubit3->sig_x);
create_stabilizer(&S2,4,qubit1->sig_x,qubit2->sig_z,qubit3->sig_z,qubit4->sig_x);
create_stabilizer(&S3,4,qubit2->sig_x,qubit3->sig_z,qubit4->sig_z,qubit0->sig_x);
create_stabilizer(&S4,4,qubit3->sig_x,qubit4->sig_z,qubit0->sig_z,qubit1->sig_x);
add_lin_recovery(correction_rate,1,qubit0->eye,(char *)"1111",4,S1,S2,S3,S4);
//Qubit 0 errors
add_lin_recovery(correction_rate,1,qubit0->sig_x,(char *)"1110",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit0->sig_y,(char *)"0100",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit0->sig_z,(char *)"0101",4,S1,S2,S3,S4);
//Qubit 1 errors
add_lin_recovery(correction_rate,1,qubit1->sig_x,(char *)"0111",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit1->sig_y,(char *)"0010",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit1->sig_z,(char *)"1010",4,S1,S2,S3,S4);
//Qubit 2 errors
add_lin_recovery(correction_rate,1,qubit2->sig_x,(char *)"0011",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit2->sig_y,(char *)"1101",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit2->sig_z,(char *)"0001",4,S1,S2,S3,S4);
//Qubit 3 errors
add_lin_recovery(correction_rate,1,qubit3->sig_x,(char *)"1001",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit3->sig_y,(char *)"0110",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit3->sig_z,(char *)"0000",4,S1,S2,S3,S4);
//Qubit 4 errors
add_lin_recovery(correction_rate,1,qubit4->sig_x,(char *)"1100",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit4->sig_y,(char *)"1011",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit4->sig_z,(char *)"1000",4,S1,S2,S3,S4);
destroy_stabilizer(&S1);
destroy_stabilizer(&S2);
destroy_stabilizer(&S3);
destroy_stabilizer(&S4);
} else {
if (nid==0){
printf("ERROR! Encoder type not understood!\n");
exit(1);
}
}
return;
}
void add_discrete_error_correction(encoded_qubit this_qubit,PetscReal correction_rate){
stabilizer S1,S2,S3,S4;
operator qubit0,qubit1,qubit2,qubit3,qubit4;
if (this_qubit.my_encoder_type == NONE){
//No encoding, no error correction needed
} else if (this_qubit.my_encoder_type == BIT){
qubit0 = subsystem_list[this_qubit.qubits[0]];
qubit1 = subsystem_list[this_qubit.qubits[1]];
qubit2 = subsystem_list[this_qubit.qubits[2]];
create_stabilizer(&S1,2,qubit0->sig_z,qubit1->sig_z);
create_stabilizer(&S2,2,qubit1->sig_z,qubit2->sig_z);
add_lin_recovery(correction_rate,1,qubit0->eye,(char *)"11",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit0->sig_x,(char *)"01",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit1->sig_x,(char *)"00",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit2->sig_x,(char *)"10",2,S1,S2);
destroy_stabilizer(&S1);
destroy_stabilizer(&S2);
} else if (this_qubit.my_encoder_type == PHASE){
qubit0 = subsystem_list[this_qubit.qubits[0]];
qubit1 = subsystem_list[this_qubit.qubits[1]];
qubit2 = subsystem_list[this_qubit.qubits[2]];
create_stabilizer(&S1,2,qubit0->sig_x,qubit1->sig_x);
create_stabilizer(&S2,2,qubit1->sig_x,qubit2->sig_x);
add_lin_recovery(correction_rate,1,qubit0->eye,(char *)"11",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit0->sig_z,(char *)"01",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit1->sig_z,(char *)"00",2,S1,S2);
add_lin_recovery(correction_rate,1,qubit2->sig_z,(char *)"10",2,S1,S2);
destroy_stabilizer(&S1);
destroy_stabilizer(&S2);
} else if (this_qubit.my_encoder_type == FIVE) {
qubit0 = subsystem_list[this_qubit.qubits[0]];
qubit1 = subsystem_list[this_qubit.qubits[1]];
qubit2 = subsystem_list[this_qubit.qubits[2]];
qubit3 = subsystem_list[this_qubit.qubits[3]];
qubit4 = subsystem_list[this_qubit.qubits[4]];
create_stabilizer(&S1,4,qubit0->sig_x,qubit1->sig_z,qubit2->sig_z,qubit3->sig_x);
create_stabilizer(&S2,4,qubit1->sig_x,qubit2->sig_z,qubit3->sig_z,qubit4->sig_x);
create_stabilizer(&S3,4,qubit2->sig_x,qubit3->sig_z,qubit4->sig_z,qubit0->sig_x);
create_stabilizer(&S4,4,qubit3->sig_x,qubit4->sig_z,qubit0->sig_z,qubit1->sig_x);
add_lin_recovery(correction_rate,1,qubit0->eye,(char *)"1111",4,S1,S2,S3,S4);
//Qubit 0 errors
add_lin_recovery(correction_rate,1,qubit0->sig_x,(char *)"1110",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit0->sig_y,(char *)"0100",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit0->sig_z,(char *)"0101",4,S1,S2,S3,S4);
//Qubit 1 errors
add_lin_recovery(correction_rate,1,qubit1->sig_x,(char *)"0111",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit1->sig_y,(char *)"0010",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit1->sig_z,(char *)"1010",4,S1,S2,S3,S4);
//Qubit 2 errors
add_lin_recovery(correction_rate,1,qubit2->sig_x,(char *)"0011",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit2->sig_y,(char *)"1101",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit2->sig_z,(char *)"0001",4,S1,S2,S3,S4);
//Qubit 3 errors
add_lin_recovery(correction_rate,1,qubit3->sig_x,(char *)"1001",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit3->sig_y,(char *)"0110",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit3->sig_z,(char *)"0000",4,S1,S2,S3,S4);
//Qubit 4 errors
add_lin_recovery(correction_rate,1,qubit4->sig_x,(char *)"1100",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit4->sig_y,(char *)"1011",4,S1,S2,S3,S4);
add_lin_recovery(correction_rate,1,qubit4->sig_z,(char *)"1000",4,S1,S2,S3,S4);
destroy_stabilizer(&S1);
destroy_stabilizer(&S2);
destroy_stabilizer(&S3);
destroy_stabilizer(&S4);
} else {
if (nid==0){
printf("ERROR! Encoder type not understood!\n");
exit(1);
}
}
return;
}
/* EventFunction is one step in Petsc to apply some action at a specific time.
* This function checks to see if an event has happened.
*/
PetscErrorCode _DQEC_EventFunction(TS ts,PetscReal t,Vec U,PetscScalar *fvalue,void *ctx) {
/* Check if the time has passed a gate */
/* /\* We signal that we passed the time by returning a negative number *\/ */
/* for (i=0;i<_num_DQEC;i++){ */
/* fvalue[i] = _correction_time[i] - t; */
/* if (fvalue[i]<0){ */
/* _correction_time[i] = _correction_time[i] + _correction_dt[i]; */
/* } */
/* } */
return(0);
}
/* PostEventFunction is the other step in Petsc. If an event has happend, petsc will call this function
* to apply that event.
*/
PetscErrorCode _DQEC_PostEventFunction(TS ts,PetscInt nevents,PetscInt event_list[],PetscReal t,Vec U,PetscBool forward,void* ctx) {
PetscInt i,i_ev;
Vec tmp_answer;
VecDuplicate(U,&tmp_answer);
if (nevents) {
//Loop through events
for (i_ev=0;i_ev<nevents;i_ev++){
MatMult(_DQEC_mats[i],U,tmp_answer);
VecCopy(tmp_answer,U);
}
VecDestroy(&tmp_answer);
}
TSSetSolution(ts,U);
return(0);
}
//Take an old circuit and encode it
void encode_circuit(circuit old_circ,circuit *encoded_circ,PetscInt num_encoders,...){
PetscInt i,j;
int num_qubits=0;
PetscReal time,theta;
va_list ap;
gate_type my_gate_type;
encoded_qubit encoders[50]; //50 is more systems than we will be able to do
int qubit_numbers[50];
va_start(ap,num_encoders);
for (i=0;i<num_encoders;i++){
encoders[i] = va_arg(ap,encoded_qubit);
}
for (i=0;i<old_circ.num_gates;i++){
time = old_circ.gate_list[i].time;
my_gate_type = old_circ.gate_list[i].my_gate_type;
_check_gate_type(my_gate_type,&num_qubits);
theta = old_circ.gate_list[i].theta;
for (j=0;j<num_qubits;j++){
qubit_numbers[j] = old_circ.gate_list[i].qubit_numbers[j];
}
if (num_qubits==1){
// Get the encoder for that qubit
add_encoded_gate_to_circuit(encoded_circ,time,my_gate_type,encoders[qubit_numbers[0]],theta);
} else {
add_encoded_gate_to_circuit(encoded_circ,time,my_gate_type,
encoders[qubit_numbers[0]],encoders[qubit_numbers[1]]);
}
}
return;
}
| 2.40625 | 2 |
2024-11-18T22:25:27.943877+00:00 | 2021-08-04T00:53:58 | e1fc5318f8fb52c332430c6307658296b635b2d6 | {
"blob_id": "e1fc5318f8fb52c332430c6307658296b635b2d6",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-04T00:53:58",
"content_id": "3316b00c7dfa7b1e32a3c4123ad22f2d25a13ee2",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "b006b09820fe2fe881118cded96bb6fdd8a86c06",
"extension": "c",
"filename": "task.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 391238666,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 612,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/05-Preemptive/task.c",
"provenance": "stackv2-0115.json.gz:124174",
"repo_name": "riscv2os/mini-riscv-os",
"revision_date": "2021-08-04T00:53:58",
"revision_id": "71ec5263f5b9807a68c1708c8db0f0f58f071749",
"snapshot_id": "f196f455045df774cc8f6060df23bfff1a919dbe",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/riscv2os/mini-riscv-os/71ec5263f5b9807a68c1708c8db0f0f58f071749/05-Preemptive/task.c",
"visit_date": "2023-06-28T19:00:11.613324"
} | stackv2 | #include "task.h"
#include "lib.h"
uint8_t task_stack[MAX_TASK][STACK_SIZE];
struct context ctx_os;
struct context ctx_tasks[MAX_TASK];
struct context *ctx_now;
int taskTop=0; // total number of task
// create a new task
int task_create(void (*task)(void))
{
int i=taskTop++;
ctx_tasks[i].ra = (reg_t) task;
ctx_tasks[i].sp = (reg_t) &task_stack[i][STACK_SIZE-1];
return i;
}
// switch to task[i]
void task_go(int i) {
ctx_now = &ctx_tasks[i];
sys_switch(&ctx_os, &ctx_tasks[i]);
}
// switch back to os
void task_os() {
struct context *ctx = ctx_now;
ctx_now = &ctx_os;
sys_switch(ctx, &ctx_os);
}
| 2.5 | 2 |
2024-11-18T22:25:28.000509+00:00 | 2019-12-17T14:38:54 | 56b309570061ababf061c2013f2c142cfe4402e1 | {
"blob_id": "56b309570061ababf061c2013f2c142cfe4402e1",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-17T14:38:54",
"content_id": "a856f25e86b98b37b8d46e2d9ca524ff2c6dfb9e",
"detected_licenses": [
"MIT"
],
"directory_id": "fc888818f3aa9ed9fcd0551a430d0e3ea5d98fd1",
"extension": "c",
"filename": "three.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 228630658,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1409,
"license": "MIT",
"license_type": "permissive",
"path": "/Guía 13/three.c",
"provenance": "stackv2-0115.json.gz:124302",
"repo_name": "DBFritz/IB_ICOM",
"revision_date": "2019-12-17T14:38:54",
"revision_id": "e505f62be2a33d4a6004ffdbf82a6a7ebef907d7",
"snapshot_id": "a009e06a5303ac90e05fc5c07bb839a8508fce95",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/DBFritz/IB_ICOM/e505f62be2a33d4a6004ffdbf82a6a7ebef907d7/Guía 13/three.c",
"visit_date": "2020-11-25T11:03:17.735218"
} | stackv2 | int TreeNumNodes(Tree_t t)
{
if(t == TREE_EMPTY)
return 0;
return 1 + TreeNumNodes(TREE_LEFT(t))
+ TreeNumNodes(TREE_RIGHT(t));
}
// retorna verdadero/falso indicando si e existe o nó dentro de t
int TreeIsMember(int e, Tree_t t)
{
if (t == TREE_EMPTY)
return 0;
if(TREE_CONT(t) == e)
return 1;
if( TREE_CONT(t) > e)
return TreeIsMember(e, TREE_LEFT(t));
return TreeIsMember(e, TREE_RIGHT(t));
}
int TreeHeight(Tree_t t)
{
int hl, hr;
if (t == TREE_EMPTY)
return 0;
hl = TreeHeight(TREE_LEFT(t));
hr = TreeHeight(TREE_RIGHT(t));
return 1 + ((hl > hr) ? hl : hr);
}
// función auxiliary para crear un árbol de un solo nodo
Tree_t TreeCreateNode(int e)
{
Tree_t nT = (Tree_t) malloc(sizeof(struct TNode));
assert(nT);
TREE_CONT(nT) = e;
TREE_LEFT(nT) = TREE_RIGHT(nT) = TREE_EMPTY;
return nT;
}
// hace insersión ordenada en el árbol
Tree_t TreeInsertOrdered(int e, Tree_t t)
{
if(t == TREE_EMPTY)
return TreeCreateNode(e);
if(TREE_CONT(t) >= e)
TREE_LEFT(t) = TreeInsertOrdered(e, TREE_LEFT(t));
else
TREE_RIGHT(t) = TreeInsertOrdered(e, TREE_RIGHT(t));
return t;
}
void TreePrint(Tree_t t)
{
if(t != TREE_EMPTY) {
TreePrint(TREE_LEFT(t));
printf("%d\n", TREE_CONT(t));
TreePrint(TREE_RIGHT(t));
}
}
// destruye el árbol, liberando recursos
void TreeDestroy(Tree_t t)
{
if(t != TREE_EMPTY) {
TreeDestroy(TREE_LEFT(t));
TreeDestroy(TREE_RIGHT(t));
free(t);
}
} | 2.890625 | 3 |
2024-11-18T22:25:29.663575+00:00 | 2023-08-30T16:07:24 | 34014eb095e718fdac72530d25249264ea0caf51 | {
"blob_id": "34014eb095e718fdac72530d25249264ea0caf51",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T16:07:24",
"content_id": "47479a82fc3bc164999df67a1dd171f657c46eea",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "331640994b1b6f66c1639278571ddbdc6c8c0751",
"extension": "c",
"filename": "nxt_errno.c",
"fork_events_count": 452,
"gha_created_at": "2017-09-06T15:45:30",
"gha_event_created_at": "2023-09-12T01:28:22",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 102627638,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3783,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/nxt_errno.c",
"provenance": "stackv2-0115.json.gz:124693",
"repo_name": "nginx/unit",
"revision_date": "2023-08-30T16:07:24",
"revision_id": "9b22b6957bc87b3df002d0bc691fdae6a20abdac",
"snapshot_id": "eabcd067eaa60f4bdcf0cfaffe7d9932add2c66a",
"src_encoding": "UTF-8",
"star_events_count": 4649,
"url": "https://raw.githubusercontent.com/nginx/unit/9b22b6957bc87b3df002d0bc691fdae6a20abdac/src/nxt_errno.c",
"visit_date": "2023-09-04T02:02:13.581700"
} | stackv2 |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) NGINX, Inc.
*/
#include <nxt_main.h>
/*
* The strerror() messages are copied because:
*
* 1) strerror() and strerror_r() functions are not Async-Signal-Safe,
* therefore, they can not be used in signal handlers;
*
* 2) a direct sys_errlist[] array may be used instead of these functions,
* but Linux linker warns about this usage:
*
* warning: `sys_errlist' is deprecated; use `strerror' or `strerror_r' instead
* warning: `sys_nerr' is deprecated; use `strerror' or `strerror_r' instead
*
* causing false bug reports.
*/
static u_char *nxt_bootstrap_strerror(nxt_err_t err, u_char *errstr,
size_t size);
static u_char *nxt_runtime_strerror(nxt_err_t err, u_char *errstr, size_t size);
nxt_strerror_t nxt_strerror = nxt_bootstrap_strerror;
static nxt_str_t *nxt_sys_errlist;
static nxt_uint_t nxt_sys_nerr;
nxt_int_t
nxt_strerror_start(void)
{
char *msg;
u_char *p;
size_t size, length, n;
nxt_uint_t err, invalid;
/* The last entry. */
size = nxt_length("Unknown error");
/*
* Linux has holes for error codes 41 and 58, so the loop
* stops only after 100 invalid codes in succession.
*/
for (invalid = 0; invalid < 100 && nxt_sys_nerr < 65536; nxt_sys_nerr++) {
nxt_set_errno(0);
msg = strerror((int) nxt_sys_nerr);
/*
* strerror() behaviour on passing invalid error code depends
* on OS and version:
* Linux returns "Unknown error NN";
* FreeBSD, NetBSD and OpenBSD return "Unknown error: NN"
* and set errno to EINVAL;
* Solaris 10 returns "Unknown error" and sets errno to EINVAL;
* Solaris 9 returns "Unknown error";
* Solaris 2 returns NULL;
* MacOSX returns "Unknown error: NN";
* AIX returns "Error NNN occurred.";
* HP-UX returns "Unknown error" for invalid codes lesser than 250
* or empty string for larger codes.
*/
if (msg == NULL) {
invalid++;
continue;
}
length = nxt_strlen(msg);
size += length;
if (length == 0 /* HP-UX empty strings. */
|| nxt_errno == NXT_EINVAL
|| memcmp(msg, "Unknown error", 13) == 0)
{
invalid++;
continue;
}
#if (NXT_AIX)
if (memcmp(msg, "Error ", 6) == 0
&& memcmp(msg + length - 10, " occurred.", 9) == 0)
{
invalid++;
continue;
}
#endif
}
nxt_sys_nerr -= invalid;
nxt_main_log_debug("sys_nerr: %d", nxt_sys_nerr);
n = (nxt_sys_nerr + 1) * sizeof(nxt_str_t);
nxt_sys_errlist = nxt_malloc(n + size);
if (nxt_sys_errlist == NULL) {
return NXT_ERROR;
}
p = nxt_pointer_to(nxt_sys_errlist, n);
for (err = 0; err < nxt_sys_nerr; err++) {
msg = strerror((int) err);
length = nxt_strlen(msg);
nxt_sys_errlist[err].length = length;
nxt_sys_errlist[err].start = p;
p = nxt_cpymem(p, msg, length);
}
nxt_sys_errlist[err].length = 13;
nxt_sys_errlist[err].start = p;
nxt_memcpy(p, "Unknown error", 13);
nxt_strerror = nxt_runtime_strerror;
return NXT_OK;
}
static u_char *
nxt_bootstrap_strerror(nxt_err_t err, u_char *errstr, size_t size)
{
return nxt_cpystrn(errstr, (u_char *) strerror(err), size);
}
static u_char *
nxt_runtime_strerror(nxt_err_t err, u_char *errstr, size_t size)
{
nxt_str_t *msg;
nxt_uint_t n;
n = nxt_min((nxt_uint_t) err, nxt_sys_nerr);
msg = &nxt_sys_errlist[n];
size = nxt_min(size, msg->length);
return nxt_cpymem(errstr, msg->start, size);
}
| 2.421875 | 2 |
2024-11-18T22:25:29.734398+00:00 | 2021-02-01T02:46:31 | 2af992feaea2896a5a45c327552a7cefd3de8135 | {
"blob_id": "2af992feaea2896a5a45c327552a7cefd3de8135",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-01T02:46:31",
"content_id": "97cd0ee08f964bb1ce62e4e283889db66bb90922",
"detected_licenses": [
"MIT"
],
"directory_id": "305df2eecb86c0199e2c21c377a81e478b91470f",
"extension": "h",
"filename": "FXCG_STRING.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 333373661,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 982,
"license": "MIT",
"license_type": "permissive",
"path": "/Prizm/example/src/FXCG_STRING.h",
"provenance": "stackv2-0115.json.gz:124822",
"repo_name": "FAN-DONE/Soft3DForPrizm",
"revision_date": "2021-02-01T02:46:31",
"revision_id": "0369c61300c6bafada6204ecad3b05c0b5e82342",
"snapshot_id": "da87831009b93a12b9e2f6580dea8af944a588f9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FAN-DONE/Soft3DForPrizm/0369c61300c6bafada6204ecad3b05c0b5e82342/Prizm/example/src/FXCG_STRING.h",
"visit_date": "2023-02-23T06:52:25.499615"
} | stackv2 | #ifndef FXCG_STRING_H
#define FXCG_STRING_H
static inline void Memset4(void* dst, int val, unsigned int dwords) {
int* point = (int*)dst;
for (unsigned int i = 0; i < dwords; i++) {
*(point++) = val;
}
}
char *Itoa(int num,char *str,int radix) {
char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned unum;
int i=0,j,k;
if(radix==10&&num<0)
{
unum=(unsigned)-num;
str[i++]='-';
}
else unum=(unsigned)num;
do
{
str[i++]=index[unum%(unsigned)radix];
unum/=radix;
}while(unum);
str[i]='\0';
if(str[0]=='-') k=1;
else k=0;
char temp;
for(j=k;j<=(i-k-1)/2.0;j++)
{
temp=str[j];
str[j]=str[i-j-1];
str[i-j-1]=temp;
}
return str;
}
static unsigned int lastrandom = 0x12345678;
static inline void Srand(unsigned int seed) {
lastrandom = seed;
}
static inline int Rand(void) {
lastrandom = 0x41C64E6D * lastrandom + 0x3039;
return lastrandom >> 16;
}
#endif
| 2.5 | 2 |
2024-11-18T22:25:30.178610+00:00 | 2019-03-16T18:03:36 | fff11ad3d51e45b552ccbf7a9bf322eefdaf28b8 | {
"blob_id": "fff11ad3d51e45b552ccbf7a9bf322eefdaf28b8",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-16T18:03:36",
"content_id": "8a431b553fd3c3212b589defcca4d8a54fb240f7",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d1313c3a19feae4e06cf9178e9cdb701332f6d23",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 729,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/list/main.c",
"provenance": "stackv2-0115.json.gz:125340",
"repo_name": "fcgll520/kore.io_websocket",
"revision_date": "2019-03-16T18:03:36",
"revision_id": "9dbc9ce2efd42f9aaba5459ab5d0808e963df650",
"snapshot_id": "123e6575425bae7dc24b5987b445797a9f085f12",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fcgll520/kore.io_websocket/9dbc9ce2efd42f9aaba5459ab5d0808e963df650/list/main.c",
"visit_date": "2021-10-23T09:17:54.051892"
} | stackv2 | #include "stdio.h"
#include "globi_ee.h"
struct fucker{
char* who;
};
void on_hello(void*, void*);
int main(){
const char* ev_str = "hello";
const char* fake_ev = "fake";
struct fucker foo;
foo.who = "papa";
ee_t *ee=ee_new();
if(ee==NULL){
printf("ee is NULL\n");
return 0;
}
ee_on(ee, ev_str, on_hello, (void*)&foo);
ee_on(ee, ev_str, on_hello, (void*)&foo);
ee_emit(ee, ev_str, "mama");
ee_emit(ee, ev_str, "sister");
ee_emit(ee, fake_ev, "brother");
ee_remove_listener(ee, ev_str, on_hello);
ee_destroy(ee);
printf("*** Buy! ***\n");
return 0;
}
void on_hello(void* d, void* b){
printf("on_hello() occured.\n");
printf("data d: %s\n",(char*)d);
struct fucker* c=(struct fucker*)b;
printf("data b: %s\n", c->who);
}
| 2.59375 | 3 |
2024-11-18T22:25:30.380776+00:00 | 2017-12-25T15:15:04 | 31f4d99996d0bbd69424bff0e378f5bbc264c000 | {
"blob_id": "31f4d99996d0bbd69424bff0e378f5bbc264c000",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-01T15:55:02",
"content_id": "03c347d0d90d53196bdda63c6fc4faf96df71e0f",
"detected_licenses": [
"MIT"
],
"directory_id": "fe169fd9c94e103d58f274197a5f11c4baa0aeea",
"extension": "c",
"filename": "merge.c",
"fork_events_count": 3,
"gha_created_at": "2015-01-13T19:12:39",
"gha_event_created_at": "2015-01-27T19:31:05",
"gha_language": "C",
"gha_license_id": null,
"github_id": 29206235,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1785,
"license": "MIT",
"license_type": "permissive",
"path": "/main/src/sort/merge.c",
"provenance": "stackv2-0115.json.gz:125599",
"repo_name": "AgentD/ctools",
"revision_date": "2017-12-25T15:15:04",
"revision_id": "85281b6e50382f3106a5d7bac6bb541238e885d2",
"snapshot_id": "59196b74dfadce76d1ec314c0a2463eee6ec83d9",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/AgentD/ctools/85281b6e50382f3106a5d7bac6bb541238e885d2/main/src/sort/merge.c",
"visit_date": "2020-04-03T22:42:14.863226"
} | stackv2 | /* merge.c -- This file is part of ctools
*
* Copyright (C) 2015 - David Oberhollenzer
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
/*
Merge sort implementation is based on "Algorithms, 4th Edition"
by ROBERT SEDGEWICK and KEVIN WAYNE.
*/
#define TL_EXPORT
#include "tl_sort.h"
#include <string.h>
#include <stdlib.h>
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
static TL_INLINE void swap(char *a, char *b, size_t n)
{
size_t i;
char t;
for (i = 0; i < n; ++i) {
t = *a;
*(a++) = *b;
*(b++) = t;
}
}
static TL_INLINE void merge(char *dst, char *auxlo, char *auxmid,
char *auxhi, char *auxlast,
size_t size, tl_compare cmp)
{
memcpy(auxlo, dst, auxlast - auxlo + size);
while (auxlo <= auxmid && auxhi <= auxlast) {
if (cmp(auxhi, auxlo) < 0) {
memcpy(dst, auxhi, size);
auxhi += size;
} else {
memcpy(dst, auxlo, size);
auxlo += size;
}
dst += size;
}
if (auxhi <= auxlast) {
memcpy(dst, auxhi, auxlast - auxhi + size);
} else if (auxlo <= auxmid) {
memcpy(dst, auxlo, auxmid - auxlo + size);
}
}
int tl_mergesort(void *data, size_t N, size_t size, tl_compare cmp)
{
char *dst, *auxlo, *auxmid, *auxhi, *auxlast, *aux;
size_t n, i, hi, step;
aux = malloc(N * size);
if (!aux)
return 0;
for (step = 2 * size, n = 1; n < N; n *= 2, step *= 2) {
dst = (char *)data;
auxlo = aux;
auxhi = aux + step / 2;
auxmid = auxhi - size;
for (i = 0; i < N - n; i += 2 * n) {
hi = MIN(i + n + n - 1, N - 1);
auxlast = aux + hi * size;
merge(dst, auxlo, auxmid, auxhi, auxlast, size, cmp);
dst += step;
auxlo += step;
auxmid += step;
auxhi += step;
}
}
free(aux);
return 1;
}
| 2.875 | 3 |
2024-11-18T22:25:30.543731+00:00 | 2015-08-16T04:29:24 | c66a7213c87433b591615bfe422d8f7db632890a | {
"blob_id": "c66a7213c87433b591615bfe422d8f7db632890a",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-16T04:29:24",
"content_id": "33564ec2e4b6f95227d0387e781bb570126cdd61",
"detected_licenses": [
"MIT"
],
"directory_id": "d8ef8d0273995047e5d237ba100eee3bd0d42afc",
"extension": "h",
"filename": "Outputs.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": 4501,
"license": "MIT",
"license_type": "permissive",
"path": "/Software/Src/Outputs.h",
"provenance": "stackv2-0115.json.gz:125729",
"repo_name": "kedi007/PowerSupply",
"revision_date": "2015-08-16T04:29:24",
"revision_id": "211513f3c52a76853bd7f6919abaabce5cca5fa2",
"snapshot_id": "cc457065ff0ded7f7e79d0fbcf64cd6934b546a7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kedi007/PowerSupply/211513f3c52a76853bd7f6919abaabce5cca5fa2/Software/Src/Outputs.h",
"visit_date": "2022-06-14T23:45:25.599451"
} | stackv2 | //////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2015 Peter Walsh, Milford, NH 03055
// All Rights Reserved under the MIT license as outlined below.
//
// FILE
// Outputs.h
//
// SYNOPSIS
//
//
// //////////////////////////////////////
// //
// // In Outputs.h
// //
// ...Choose port and pins for output (Default: PortC.2/PortC.3)
//
// //////////////////////////////////////
// //
// // In Main.c
// //
// OutputsInit();
// :
//
// Output1Set(bool Value); // Turn output 1 on or off
// Output2Set(bool Value); // Turn output 2 on or off
//
// if( Output1Get ) ...do something // Recall current output setting
// if( Output2Get ) ...do something // Recall current output setting
//
// DESCRIPTION
//
// Output processing
//
// Manage outputs
//
// VERSION: 2015.06.27
//
//////////////////////////////////////////////////////////////////////////////////////////
//
// MIT LICENSE
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
#ifndef OUTPUTS_H
#define OUTPUTS_H
#include <stdbool.h>
#include <avr\io.h>
#include <avr\interrupt.h>
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// The port and bit which represents the input
//
#define OUTPUT1_PORT C // PortC
#define OUTPUT1_BIT 2 // Pin 2
#define OUTPUT2_PORT C // PortC
#define OUTPUT2_BIT 3 // Pin 3
//
// End of user configurable options
//
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
#define Output1Get _BIT_ON(_PORT(OUTPUT1_PORT),OUTPUT1_BIT)
#define Output2Get _BIT_ON(_PORT(OUTPUT2_PORT),OUTPUT2_BIT)
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// OutputsInit - Initialize outputs
//
// Inputs: None.
//
// Outputs: None.
//
void OutputsInit(void);
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// Output1Set - Set output1
//
// Inputs: TRUE to set output ON
// FALSE otherwise
//
// Outputs: None.
//
void Output1Set(bool Set);
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
//
// Output2Set - Set output2
//
// Inputs: TRUE to set output ON
// FALSE otherwise
//
// Outputs: None.
//
void Output2Set(bool Set);
#endif // OUTPUTS_H - entire file
| 2.078125 | 2 |
2024-11-18T22:25:30.893192+00:00 | 2011-09-30T14:07:28 | 3b6f0dba5097e8097bf49225365607ea77bed5d6 | {
"blob_id": "3b6f0dba5097e8097bf49225365607ea77bed5d6",
"branch_name": "refs/heads/master",
"committer_date": "2011-09-30T14:07:28",
"content_id": "d7bd1f5ae3f221b44afd810190ffeedde6872f5a",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b0a9450d90d734b71db05ae27004b1261f034be5",
"extension": "c",
"filename": "mbobject.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 62825644,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2924,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/mbaf/mbobject.c",
"provenance": "stackv2-0115.json.gz:126115",
"repo_name": "aguai/MadButterfly",
"revision_date": "2011-09-30T14:07:28",
"revision_id": "005c4b56aac7a40c0c4c53bb80ee38b07665e266",
"snapshot_id": "7adfb25909b255c7d8b75908e883671ab2e637e4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/aguai/MadButterfly/005c4b56aac7a40c0c4c53bb80ee38b07665e266/src/mbaf/mbobject.c",
"visit_date": "2021-01-17T17:03:37.959510"
} | stackv2 | // -*- indent-tabs-mode: t; tab-width: 8; c-basic-offset: 4; -*-
// vim: sw=4:ts=8:sts=4
#include "mb_types.h"
#include "mb_obj.h"
#include "mb_config.h"
void mb_obj_set_pos(mb_obj_t *obj, co_aix x, co_aix y)
{
if (MBO_TYPE(obj) == MBO_COORD) {
coord_x(((coord_t *) obj)) = x;
coord_y(((coord_t *) obj)) = y;
#ifdef SH_TEXT
} else if (MBO_TYPE(obj) == MBO_TEXT) {
sh_text_set_pos((shape_t *) obj, x, y);
#endif
} else {
return;
}
}
void mb_obj_get_pos(mb_obj_t *obj, co_aix *x, co_aix *y)
{
if (MBO_TYPE(obj) == MBO_COORD) {
*x = coord_x((coord_t *) obj);
*y = coord_y((coord_t *) obj);
#ifdef SH_TEXT
} else if (MBO_TYPE(obj) == MBO_TEXT) {
sh_text_get_pos((shape_t *) obj, x, y);
#endif
} else {
return;
}
}
void mb_obj_set_text(mb_obj_t *obj, const char *text)
{
if (MBO_TYPE(obj) == MBO_COORD) {
geo_t *geo;
shape_t *shape;
coord_t *g = (coord_t *) obj;
FOR_COORD_MEMBERS(g, geo) {
shape = geo_get_shape(geo);
#ifdef SH_TEXT
if(shape->obj.obj_type == MBO_TEXT) {
sh_text_set_text(shape, text);
return;
}
#endif
}
#ifdef SH_TEXT
} else if (MBO_TYPE(obj) == MBO_TEXT) {
sh_text_set_text((shape_t *) obj,text);
#endif
} else {
return;
}
}
void mb_obj_get_text(mb_obj_t *obj, char *text,int size)
{
if (MBO_TYPE(obj) == MBO_COORD) {
geo_t *geo;
shape_t *shape;
coord_t *g = (coord_t *) obj;
FOR_COORD_MEMBERS(g, geo) {
shape = geo_get_shape(geo);
#ifdef SH_TEXT
if(shape->obj.obj_type == MBO_TEXT) {
sh_text_get_text(shape, text,size);
return;
}
#endif
}
#ifdef SH_TEXT
} else if (MBO_TYPE(obj) == MBO_TEXT) {
sh_text_get_text((shape_t *) obj,text,size);
#endif
} else {
*text = 0;
return;
}
}
void mb_obj_set_scalex(mb_obj_t *obj,int scale)
{
if (MBO_TYPE(obj) == MBO_COORD) {
coord_set_scalex((coord_t *) obj, scale);
} else {
}
}
int mb_obj_get_scalex(mb_obj_t *obj)
{
if (MBO_TYPE(obj) == MBO_COORD) {
return coord_scalex((coord_t *) obj);
} else {
return 100;
}
}
void mb_obj_set_scaley(mb_obj_t *obj,int scale)
{
if (MBO_TYPE(obj) == MBO_COORD) {
coord_set_scaley((coord_t *) obj, scale);
} else {
}
}
int mb_obj_get_scaley(mb_obj_t *obj)
{
if (MBO_TYPE(obj) == MBO_COORD) {
return coord_scaley((coord_t *) obj);
} else {
return 100;
}
}
void mb_obj_set_rotation(mb_obj_t *obj, int degree)
{
printf("%s is not implemented yet\n",__FUNCTION__);
}
int mb_obj_get_rotation(mb_obj_t *obj)
{
printf("%s is not implemented yet\n",__FUNCTION__);
}
void mb_obj_set_color(mb_obj_t *obj, int color)
{
printf("%s is not implemented yet\n",__FUNCTION__);
}
int mb_obj_get_color(mb_obj_t *obj)
{
printf("%s is not implemented yet\n",__FUNCTION__);
return 0;
}
| 2.4375 | 2 |
2024-11-18T22:25:31.058077+00:00 | 2022-06-12T18:13:23 | fa0430f5cb68fac4fdc3aa261fa36eb8b7478f78 | {
"blob_id": "fa0430f5cb68fac4fdc3aa261fa36eb8b7478f78",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-12T18:13:23",
"content_id": "8ccdbb744cc764c87bf606a0f5291c6c152c4960",
"detected_licenses": [
"ISC"
],
"directory_id": "722cf9ab069d75af63664eeae0c35c63aa73c51c",
"extension": "c",
"filename": "enstrdup.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146619247,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 851,
"license": "ISC",
"license_type": "permissive",
"path": "/enstrdup.c",
"provenance": "stackv2-0115.json.gz:126376",
"repo_name": "maandree/libsimple",
"revision_date": "2022-06-12T18:13:23",
"revision_id": "3d6482b0949159c33d6ac2972a69868bdda766f2",
"snapshot_id": "1427bca158ad2af6bc601d6398b4cfffd1713cfb",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/maandree/libsimple/3d6482b0949159c33d6ac2972a69868bdda766f2/enstrdup.c",
"visit_date": "2022-07-04T08:30:37.349945"
} | stackv2 | /* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST
char *
libsimple_enstrdup(int status, const char *s)
{
size_t n = strlen(s) + 1;
char *ret = aligned_alloc(1, n);
if (!ret)
enprintf(status, "strdup:");
memcpy(ret, s, n);
return ret;
}
#else
#include "test.h"
int
main(void)
{
struct allocinfo *info;
char *s;
assert((s = libsimple_enstrdup(1, "hello")));
if (have_custom_malloc()) {
assert((info = get_allocinfo(s)));
assert(info->size == 6);
assert(info->alignment == 1);
assert(!info->zeroed);
}
assert(!strcmp(s, "hello"));
free(s);
if (have_custom_malloc()) {
alloc_fail_in = 1;
assert_exit_ptr(libsimple_enstrdup(14, "hello"));
assert(exit_status == 14);
assert_stderr("%s: strdup: %s\n", argv0, strerror(ENOMEM));
assert(!alloc_fail_in);
}
return 0;
}
#endif
| 2.640625 | 3 |
2024-11-18T22:25:31.285068+00:00 | 2016-03-22T17:50:16 | 6c63809f7fdc4a71b70d8907b50132ecd3d8f07f | {
"blob_id": "6c63809f7fdc4a71b70d8907b50132ecd3d8f07f",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-22T17:50:16",
"content_id": "6509360038813aa2f086e057e98d17f2093772bd",
"detected_licenses": [
"MIT"
],
"directory_id": "e6ecef381df3c3f67b760485790b25b3694a114e",
"extension": "c",
"filename": "Demos.c",
"fork_events_count": 0,
"gha_created_at": "2016-03-22T05:31:42",
"gha_event_created_at": "2016-03-22T05:31:42",
"gha_language": null,
"gha_license_id": null,
"github_id": 54447976,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4111,
"license": "MIT",
"license_type": "permissive",
"path": "/Demos.c",
"provenance": "stackv2-0115.json.gz:126506",
"repo_name": "ScottSWu/ece-r2-linesensor",
"revision_date": "2016-03-22T17:50:16",
"revision_id": "10682b9196bd4095fbc42d0acc7930a92303347d",
"snapshot_id": "17e3db60583887a519a6b16362101dff006a6f85",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ScottSWu/ece-r2-linesensor/10682b9196bd4095fbc42d0acc7930a92303347d/Demos.c",
"visit_date": "2021-01-24T21:58:17.712822"
} | stackv2 | /*******************************************************************************
* Filename: Demos.c
*
* Important Links:
* https://github.com/adafruit/Adafruit_TCS34725
* http://iotdk.intel.com/docs/master/mraa/index.html
******************************************************************************/
#include "Demos.h"
#define rmax 105
#define rmin 90
#define gmax 105
#define gmin 90
#define bmax 55
#define bmin 45
// TODO make a method for compution rgb as fraction of clear
// TODO consistent indentation (no tabs, tab = 2 space)
void raw_loop(Adafruit_TCS34725* sensor) {
for (;;) {
uint16_t red, green, blue, clear, colorTemp, lux;
/***************************************************************************
* setInterrupt(sensor, 0) turns the led on and setInterrupt(sensor, 1)
* turns it off. This and the 60ms results in faster responses times, likely
* as a result of the photodiode's operation.
**************************************************************************/
setInterrupt(sensor, 0);
usleep(60);
getRawData(sensor, &red, &green, &blue, &clear);
setInterrupt(sensor, 1);
colorTemp = calculateColorTemperature(red, green, blue);
lux = calculateLux(red, green, blue);
fprintf(stdout, "Color Temp: %d K - ", colorTemp);
fprintf(stdout, "Lux: %d - ", lux);
fprintf(stdout, "R: %d ", red);
fprintf(stdout, "G: %d ", green);
fprintf(stdout, "B: %d ", blue);
fprintf(stdout, "C: %d \n", clear);
}
}
void rgb_loop(Adafruit_TCS34725* sensor) {
uint16_t red, green, blue, clear;
uint32_t sum;
double r, g, b;
for (;;) {
//setInterrupt(sensor, 0);
usleep(60);
getRawData(sensor, &red, &green, &blue, &clear);
//setInterrupt(sensor, 1);
usleep(500000);
sum = clear;
r = red; r /= sum; r *= 256;
g = green; g /= sum; g *= 256;
b = blue; b /= sum; b *= 256;
fprintf(stdout, "R: %d, G: %d, B: %d\n", (int)r, (int)g, (int)b);
}
}
// TODO
// Uses gamma decoding to make an RGB led display the color read by the
// color sensor.
void gamma_loop(Adafruit_TCS34725* sensor) {
// gamma table converts RGB colors to what humans see. Read
// https://learn.adafruit.com/led-tricks-gamma-correction
uint8_t gammatable[256];
int i = 0;
for(; i < 256; i++) {
float x = i;
x /= 255;
x = pow(x, 2.5);
x *= 255;
gammatable[i] = x;
}
uint16_t red, green, blue, clear;
uint32_t sum;
double r, g, b;
for (;;) {
setInterrupt(sensor, 0);
usleep(60);
getRawData(sensor, &red, &green, &blue, &clear);
setInterrupt(sensor, 1);
sum = clear;
r = red; r /= sum; r *= 256;
g = green; g /= sum; g *= 256;
b = blue; b /= sum; b *= 256;
// fprintf(stdout, "R: %d, G: %d, B: %d\n", (int)r, (int)g, (int)b);
fprintf(stdout, "R: %d, G: %d, B: %d\n", gammatable[(int)r],
gammatable[(int)g], gammatable[(int)b]);
}
}
void detect_loop(Adafruit_TCS34725* sensor) {
uint16_t red, green, blue, clear;
uint32_t sum;
double r, g, b;
int rval, gval, bval;
// persistence filter
int count = 3;
int current = 0;
int detected = 0;
for (;;) {
//setInterrupt(sensor, 0);
//usleep(60);
getRawData(sensor, &red, &green, &blue, &clear);
//setInterrupt(sensor, 1);
usleep(1000000);
sum = clear;
r = red; r /= sum; r *= 256;
g = green; g /= sum; g *= 256;
b = blue; b /= sum; b *= 256;
rval = (int)r;
gval = (int)g;
bval = (int)b;
printf("%d %d %d %d\n", red, green, blue, sum);
printf("%d %d %d\n", rval, gval, bval);
if((rval > rmin) && (rval < rmax) && (gval > gmin) && (gval < gmax) && (bval > bmin) && (bval < bmax)) {
if (current == 2) detected = 1;
current = (current == count) ? count : current + 1;
} else {
if (current == 1) detected = 0;
current = (current == 0) ? 0 : current - 1;
}
if (detected) {fprintf(stdout, "Detected\n");}
else {fprintf(stdout, "Not Detected\n");}
}
}
| 2.765625 | 3 |
2024-11-18T22:25:32.097520+00:00 | 2020-07-26T11:06:41 | 89f1b8dfd412d20c85ae856adf6b3778d7cc1998 | {
"blob_id": "89f1b8dfd412d20c85ae856adf6b3778d7cc1998",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-26T11:06:41",
"content_id": "2541030ff0b86094896d2c5b9b601c999e38f9e9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0545919a3ceafe18059b9ac3a5ccab8566f6ded9",
"extension": "c",
"filename": "sdpi_ip_struct.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 174526262,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12451,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/sdpi_ip_struct.c",
"provenance": "stackv2-0115.json.gz:126767",
"repo_name": "fragileeye/libsdpi",
"revision_date": "2020-07-26T11:06:41",
"revision_id": "60c81a1f189d96f9fa96dcbcee9541c6130425f6",
"snapshot_id": "bb14dc0e046328657ee7747ca2abe55820aa4c88",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fragileeye/libsdpi/60c81a1f189d96f9fa96dcbcee9541c6130425f6/src/sdpi_ip_struct.c",
"visit_date": "2021-07-11T02:30:10.464368"
} | stackv2 | #include "sdpi_ip_struct.h"
#pragma warning(disable:4996)
sdpi_num_patricia_tree_t *
sdpi_num_patricia_init()
{
sdpi_num_patricia_tree_t * tmp_tree = malloc(sizeof(sdpi_num_patricia_tree_t));
if(tmp_tree)
{
tmp_tree->nodes = 0;
tmp_tree->root = NULL;
}
return tmp_tree;
}
void sdpi_num_patricia_free_nodes(
sdpi_num_patricia_tree_t *tree,
sdpi_num_patricia_node_t *node
)
{
if(!node) return;
if(node->left)
{
sdpi_num_patricia_free_nodes(tree, node->left);
}
if(node->right)
{
sdpi_num_patricia_free_nodes(tree, node->right);
}
sdpi_num_patricia_node_delete(node);
}
void
sdpi_num_patricia_free(
sdpi_num_patricia_tree_t *tree
)
{
sdpi_num_patricia_free_nodes(tree, tree->root);
free(tree);
}
sdpi_ip_mask_t *
sdpi_num_patricia_prefix_new(
int ip_addr,
unsigned int bits
)
{
sdpi_ip_mask_t *tmp_prefix = malloc(sizeof(sdpi_ip_mask_t));
if(tmp_prefix)
{
tmp_prefix->ip_addr = ip_addr;
tmp_prefix->bits = bits;
}
return tmp_prefix;
}
void
sdpi_num_patricia_prefix_delete(
sdpi_ip_mask_t *prefix
)
{
free(prefix);
}
sdpi_num_patricia_node_t *
sdpi_num_patricia_node_new(
sdpi_ip_mask_t *init_prefix
)
{
sdpi_num_patricia_node_t *tmp_node = malloc(
sizeof(sdpi_num_patricia_node_t));
if(tmp_node)
{
tmp_node->bits = !init_prefix ? 0 : init_prefix->bits;
tmp_node->prefix = init_prefix;
tmp_node->parent = tmp_node->left = tmp_node->right = NULL;
}
return tmp_node;
}
void
sdpi_num_patricia_node_delete(
sdpi_num_patricia_node_t *node
)
{
if(node && node->prefix)
{
sdpi_num_patricia_prefix_delete(node->prefix);
}
free(node);
}
//定位与target有公共前缀的节点
sdpi_num_patricia_node_t *
sdpi_num_patricia_node_locate(
sdpi_num_patricia_tree_t *tree,
sdpi_ip_mask_t *lookup_prefix,
unsigned int *locate_addr,
unsigned int *locate_bits
)
{
sdpi_num_patricia_node_t *traverse_node = NULL;
sdpi_num_patricia_node_t *previous_node = NULL;
unsigned int lookup_addr = 0;
unsigned int lookup_bits = 0;
unsigned int index_addr = 0;
unsigned int index_bits = 0;
unsigned int different_bit = 0;
unsigned int tmp_value = 0;
if(!tree || !tree->nodes)
{
return NULL;
}
lookup_bits = lookup_prefix->bits;
lookup_addr = lookup_prefix->ip_addr;
//找到target节点的可能子节点,因为只有target子节点(或本身)才与target有公共前缀
//值得注意的是,需要跳过prefix = NULL的情况,因为prefix=NULL的节点为glue节点。
traverse_node = tree->root;
while(traverse_node->bits < lookup_bits || !traverse_node->prefix)
{
if(SDPI_BIT_SET(lookup_addr, traverse_node->bits))
{
if(traverse_node->right)
{
traverse_node = traverse_node->right;
}
else
{
break;
}
}
else
{
if(traverse_node->left)
{
traverse_node = traverse_node->left;
}
else
{
break;
}
}
}
index_bits = traverse_node->prefix->bits;
index_addr = traverse_node->prefix->ip_addr;
tmp_value = ~(index_addr ^ lookup_addr);
//找公共前缀的位置
while(tmp_value & 0x80000000)
{
different_bit++;
tmp_value <<= 1;
}
different_bit = SDPI_MIN_VALUE(different_bit, SDPI_MIN_VALUE(index_bits, lookup_bits));
//找具有公共前缀的节点,从traverse节点回溯
previous_node = traverse_node->parent;
while(previous_node && previous_node->bits >= different_bit)
{
traverse_node = previous_node;
previous_node = previous_node->parent;
}
*locate_addr = index_addr;
*locate_bits = different_bit;
return traverse_node;
}
//精确查找
sdpi_num_patricia_node_t *
sdpi_num_patricia_node_lookup(
sdpi_num_patricia_tree_t *tree,
sdpi_ip_mask_t *lookup_prefix
)
{
sdpi_num_patricia_node_t *find_node = NULL;
sdpi_num_patricia_node_t *traverse_node = tree->root;
sdpi_ip_mask_t *prefix = NULL;
while(traverse_node->bits < lookup_prefix->bits || !traverse_node->prefix)
{
if(SDPI_BIT_SET(lookup_prefix->ip_addr, traverse_node->bits))
{
if(traverse_node->right)
{
traverse_node = traverse_node->right;
}
else
{
break;
}
}
else
{
if(traverse_node->left)
{
traverse_node = traverse_node->left;
}
else
{
break;
}
}
}
prefix = traverse_node->prefix;
//prefix不可能为空,因为只有glue_node节点的prefix为NULL,而退出上面循环的节点肯定不为glue_node。
if(prefix->bits == lookup_prefix->bits && prefix->ip_addr == lookup_prefix->ip_addr)
{
find_node = traverse_node;
}
return find_node;
}
//模糊查找:针对同一子网的情况
sdpi_num_patricia_node_t *
sdpi_num_patricia_node_lookup_ex(
sdpi_num_patricia_tree_t *tree,
sdpi_ip_mask_t *lookup_prefix
)
{
sdpi_num_patricia_node_t *traverse_node = tree->root;
sdpi_num_patricia_node_t *find_node = NULL;
sdpi_ip_mask_t *index_prefix = NULL;
unsigned int target_subnet = 0;
unsigned int locate_subnet = 0;
while(traverse_node->bits < lookup_prefix->bits || !traverse_node->prefix)
{
if(SDPI_BIT_SET(lookup_prefix->ip_addr, traverse_node->bits))
{
if(traverse_node->right)
{
traverse_node = traverse_node->right;
}
else
{
break;
}
}
else
{
if(traverse_node->left)
{
traverse_node = traverse_node->left;
}
else
{
break;
}
}
}
index_prefix = traverse_node->prefix;
//prefix不可能为空,因为只有glue_node节点的prefix为NULL,而退出上面循环的节点肯定不为glue_node。
if(index_prefix->bits <= lookup_prefix->bits)
{
target_subnet = SDPI_BIT_VALUE(lookup_prefix->ip_addr, index_prefix->bits);
locate_subnet = SDPI_BIT_VALUE(index_prefix->ip_addr, index_prefix->bits);
find_node = locate_subnet == target_subnet ? traverse_node : NULL;
}
return find_node;
}
sdpi_num_patricia_node_t *
sdpi_num_patricia_node_insert(
sdpi_num_patricia_tree_t *tree,
sdpi_ip_mask_t *insert_prefix
)
{
sdpi_num_patricia_node_t *insert_node = NULL;
sdpi_num_patricia_node_t *glue_node = NULL;
sdpi_num_patricia_node_t *locate_node = NULL;
unsigned int locate_addr = 0;
unsigned int locate_bits = 0;
unsigned int different_bit = 0;
unsigned int insert_addr = 0;
unsigned int insert_bits = 0;
char alert_ip[SDPI_IP_MAX_SIZE];
//非法参数
if(!tree || !insert_prefix)
{
return NULL;
}
//先创建一个待插入节点
if(!(insert_node = sdpi_num_patricia_node_new(insert_prefix)))
{
return NULL;
}
//空树就直接赋值头结点
if(tree->nodes == 0)
{
tree->root = insert_node;
tree->nodes += 1;
return insert_node;
}
//定位不到与prefix有公共前缀的节点,则说明树是空树,这是不可能的,空树的情况前面已经处理了。
if(!(locate_node = sdpi_num_patricia_node_locate(
tree, insert_prefix, &locate_addr, &different_bit)))
{
fprintf(stderr, "sdpi_num_patricia_node_locate failed!");
return NULL;
}
locate_bits = locate_node->bits;
insert_bits = insert_prefix->bits;
insert_addr = insert_prefix->ip_addr;
//找到节点了,先删除创建的节点,然后返回找到的节点,不用插入了。
if(different_bit == insert_bits && different_bit == locate_bits)
{
if(!locate_node->prefix)
{
locate_node->prefix = sdpi_num_patricia_prefix_new(insert_addr, insert_bits);
}
sdpi_number_to_ip(locate_addr, alert_ip, sizeof(alert_ip));
fprintf(stdout, "no need to add: %s\n", alert_ip);
sdpi_num_patricia_node_delete(insert_node);
return locate_node;
}
//说明target为located节点的父节点
if(different_bit == insert_bits)
{
if(SDPI_BIT_SET(locate_addr, different_bit))
{
insert_node->right = locate_node;
}
else
{
insert_node->left = locate_node;
}
insert_node->parent = locate_node->parent;
//注意考虑located_node为根节点的情况,此时根节点的父节点为NULL
if(!locate_node->parent)
{
tree->root = insert_node;
}
else if(locate_node->parent->right == locate_node)
{
locate_node->parent->right = insert_node;
}
else
{
locate_node->parent->left = insert_node;
}
locate_node->parent = insert_node;
tree->nodes += 1;
return insert_node;
}
if(different_bit == locate_bits)
{
if(SDPI_BIT_SET(insert_addr, different_bit))
{
locate_node->right = insert_node;
}
else
{
locate_node->left = insert_node;
}
insert_node->parent = locate_node;
tree->nodes += 1;
return insert_node;
}
//否则创建glue节点为target和located节点的公共父节点
//fprintf(stdout, "%s: %s\n", __FUNCTION__, "glue node is inserting!");
if(!(glue_node = sdpi_num_patricia_node_new(NULL)))
{
sdpi_num_patricia_node_delete(insert_node);
return NULL;
}
glue_node->bits = different_bit;
if(SDPI_BIT_SET(insert_addr, different_bit))
{
glue_node->right = insert_node;
glue_node->left = locate_node;
}
else
{
glue_node->right = locate_node;
glue_node->left = insert_node;
}
glue_node->parent = locate_node->parent;
if(!locate_node->parent)
{
tree->root = glue_node;
}
else if(locate_node->parent->right == locate_node)
{
locate_node->parent->right = glue_node;
}
else
{
locate_node->parent->left = glue_node;
}
insert_node->parent = glue_node;
locate_node->parent = glue_node;
tree->nodes += 2;
return insert_node;
}
void sdpi_num_patricia_traverse(
sdpi_num_patricia_node_t *root
)
{
char ip_addr[SDPI_IP_MAX_SIZE];
sdpi_ip_mask_t *prefix = NULL;
if(!root) return;
if(root->prefix)
{
prefix = root->prefix;
sdpi_number_to_ip(prefix->ip_addr, ip_addr, sizeof(ip_addr));
fprintf(stdout, "ip: %s, bits: %u\n", ip_addr, prefix->bits);
}
if(root->left)
{
sdpi_num_patricia_traverse(root->left);
}
if(root->right)
{
sdpi_num_patricia_traverse(root->right);
}
}
void
sdpi_num_patricia_node_remove(
sdpi_num_patricia_tree_t *tree,
sdpi_num_patricia_node_t *node
)
{
sdpi_num_patricia_node_t *tmp_parent = NULL;
sdpi_num_patricia_node_t *tmp_child = NULL;
if(!tree || !tree->nodes || !node)
{
return;
}
if(node->left && node->right)
{
//将其变成glue节点
if(node->prefix)
{
sdpi_num_patricia_prefix_delete(node->prefix);
node->prefix = NULL;
}
return; //本身即为glue节点,直接返回
}
tmp_parent = node->parent;
//叶子节点,值得注意的考虑当前节点的父节点是否为glue节点,如果
//其父节点为glue节点,在删除当前节点的时候,还要删除其父节点。
if(!node->left && !node->right)
{
if(!tmp_parent)
{
sdpi_num_patricia_node_delete(node);
tree->root = NULL; tree->nodes = 0;
return;
}
//其父节点不为glue节点
if(tmp_parent->prefix)
{
if(node == tmp_parent->right)
{
tmp_parent->right = NULL;
}
else
{
tmp_parent->left = NULL;
}
sdpi_num_patricia_node_delete(node);
tree->nodes--;
return;
}
else //其父节点为glue节点的情况
{
tmp_child = (node == tmp_parent->right) ? \
tmp_parent->right : tmp_parent->left;
if(!tmp_parent->parent)
{
sdpi_num_patricia_node_delete(node);
sdpi_num_patricia_node_delete(tmp_parent);
tree->root = tmp_child; tree->nodes -= 2;
return;
}
if(tmp_parent->parent->right == tmp_parent)
{
tmp_parent->parent->right = tmp_child;
}
else
{
tmp_parent->parent->left = tmp_child;
}
tmp_child->parent = tmp_parent->parent;
sdpi_num_patricia_node_delete(node);
sdpi_num_patricia_node_delete(tmp_parent);
tree->nodes -= 2;
return;
}
}
//此时prefix也一定不为空,单支节点不可能为glue节点!
tmp_child = node->left ? node->left : node->right;
tmp_child->parent = tmp_parent;
if(!tmp_parent)
{
sdpi_num_patricia_node_delete(node);
tree->root = tmp_child; tree->nodes--;
return;
}
if(node == tmp_parent->left)
{
tmp_parent->left = tmp_child;
}
else
{
tmp_parent->right = tmp_child;
}
sdpi_num_patricia_node_delete(node);
tree->nodes--;
return;
}
int sdpi_ip_to_number(
char * str_ip_addr
)
{
int u1, u2, u3, u4;
if(4 == sscanf(str_ip_addr, "%d.%d.%d.%d", &u1, &u2, &u3, &u4))
{
return (u1 << 24) | (u2 << 16) | (u3 << 8) | u4;
}
return 0;
}
char *sdpi_number_to_ip(
int num_ip_addr,
char str_ip_addr[],
unsigned int size
)
{
if(str_ip_addr)
{
snprintf(str_ip_addr, size, "%u.%u.%u.%u",
(num_ip_addr >> 24) & 0xff, (num_ip_addr >> 16) & 0xff,
(num_ip_addr >> 8) & 0xff, num_ip_addr & 0xff
);
}
return str_ip_addr;
}
| 2.34375 | 2 |
2024-11-18T22:25:32.312875+00:00 | 2023-06-09T15:10:45 | 64e5d31c4512cae774e0fd1f1b1c22151d3f518a | {
"blob_id": "64e5d31c4512cae774e0fd1f1b1c22151d3f518a",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-16T20:50:30",
"content_id": "497cceb78537d1da315ab2900379e90d0138541b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "53cda8fbbd71c021f58ac60ec70309c82985e355",
"extension": "c",
"filename": "frameworkkey_generate.c",
"fork_events_count": 8,
"gha_created_at": "2017-08-11T02:07:40",
"gha_event_created_at": "2023-06-16T20:50:32",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 99981802,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5649,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/signframework/frameworkkey_generate.c",
"provenance": "stackv2-0115.json.gz:127025",
"repo_name": "open-power/sb-signing-framework",
"revision_date": "2023-06-09T15:10:45",
"revision_id": "c72d9ff8c2eab48de451f3b16cd58542a643ac07",
"snapshot_id": "bead5f351e3610afce760fd7a93379627bc2b0af",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/open-power/sb-signing-framework/c72d9ff8c2eab48de451f3b16cd58542a643ac07/src/signframework/frameworkkey_generate.c",
"visit_date": "2023-06-28T06:25:56.385364"
} | stackv2 | /* Copyright 2017 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include "framework_utils.h"
#include "utils.h"
#include "cca_functions.h"
/* local prototypes */
int GetArgs(int argc,
char **argv);
void PrintUsage(void);
/* global variables */
FILE *messageFile = NULL;
int verbose = TRUE;
int debug = TRUE;
int main(int argc, char** argv)
{
int rc = 0;
FrameworkConfig frameworkConfig;
unsigned char masterAesKeyToken[CCA_KEY_IDENTIFIER_LENGTH];
unsigned char *masterAesKeyTokenOut = NULL; /* CCA key token (not the plaintext AES
key) */
size_t masterAesKeyTokenLengthOut;
unsigned char eku[AES128_SIZE]; /* password encryption key */
unsigned char aku[AKU_SIZE]; /* password authentication HMAC key */
messageFile = stdout; /* trace always goes to stdout */
FrameworkConfig_Init(&frameworkConfig); /* freed @1 */
/* get command line arguments */
if (rc == 0) {
rc = GetArgs(argc, argv);
}
/* get the framework configuration file object */
if (rc == 0) {
rc = FrameworkConfig_Parse(FALSE, /* do not need master key */
TRUE, /* validate */
&frameworkConfig);
}
/* verify that the file does not exist */
if (rc == 0) {
if (verbose) fprintf(messageFile, "Testing for key token file %s\n",
frameworkConfig.masterAesKeyTokenFilename);
if (frameworkConfig.masterAesKeyToken != NULL) {
fprintf(messageFile, "Error, File %s already exists\n",
frameworkConfig.masterAesKeyTokenFilename);
rc = ERROR_CODE;
}
}
/* generate a master key */
if (rc == 0) {
if (verbose) fprintf(messageFile, "Generating key token\n");
rc = Key_Generate(masterAesKeyToken);
}
/* write the AES key token to a file */
if (rc == 0) {
if (verbose) fprintf(messageFile, "Writing key token to %s\n",
frameworkConfig.masterAesKeyTokenFilename);
rc = File_WriteBinaryFile(masterAesKeyToken,
sizeof(masterAesKeyToken),
frameworkConfig.masterAesKeyTokenFilename);
}
/* validate that the master AES key token file can be read */
if (rc == 0) {
if (verbose) fprintf(messageFile, "Reading back key token\n");
rc = File_ReadBinaryFile(&masterAesKeyTokenOut, /* freed @5 */
&masterAesKeyTokenLengthOut,
CCA_KEY_IDENTIFIER_LENGTH,
frameworkConfig.masterAesKeyTokenFilename);
}
/* sanity check the length */
if (rc == 0) {
if (masterAesKeyTokenLengthOut != sizeof(masterAesKeyToken)) {
fprintf(messageFile, "Error reading %s - length mismatch\n",
frameworkConfig.masterAesKeyTokenFilename);
rc = ERROR_CODE;
}
}
/* sanity check the contents */
if (rc == 0) {
rc = memcmp(masterAesKeyToken, masterAesKeyTokenOut, masterAesKeyTokenLengthOut);
if (rc != 0) {
fprintf(messageFile, "Error reading %s - data mismatch\n",
frameworkConfig.masterAesKeyTokenFilename);
rc = ERROR_CODE;
}
}
/* validate that the master AES key token can be used */
if (rc == 0) {
if (verbose) fprintf(messageFile, "Using key token\n");
rc = Password_KDF(eku, /* user encryption key */
aku, /* user authentication HMAC key */
frameworkConfig.frameworkAdmins[0], /* dummy sender */
masterAesKeyToken);
}
/* cleanup */
FrameworkConfig_Delete(&frameworkConfig); /* @1 */
free(masterAesKeyTokenOut); /* @5 */
/* erase the secret keys before exit */
memset(eku, 0, AES128_SIZE);
memset(aku, 0, AKU_SIZE);
fprintf(messageFile, "\nframeworkkey_generate rc %d\n\n", rc);
return rc;
}
/* GetArgs() gets the command line arguments
Returns ERROR_CODE on error.
*/
int GetArgs(int argc,
char **argv)
{
int rc = 0;
int i;
/* command line argument defaults */
verbose = FALSE;
/* get the command line arguments */
for (i=1 ; (i<argc) && (rc == 0) ; i++) {
if (strcmp(argv[i],"-h") == 0) {
PrintUsage();
rc = ERROR_CODE;
}
else if (strcmp(argv[i],"-v") == 0) {
verbose = TRUE;
}
else {
printf("frameworkkey_generate: Error, %s is not a valid option\n", argv[i]);
PrintUsage();
rc = ERROR_CODE;
}
}
return rc;
}
void PrintUsage()
{
printf("\n");
printf("frameworkkey_generate:\n"
"\t[-v - verbose tracing]\n"
"\t[-h - print usage help]\n");
printf("\n");
printf("\n");
return;
}
| 2.234375 | 2 |
2024-11-18T22:25:32.556010+00:00 | 2023-01-11T22:54:07 | 7a078ea861ca463b251bca2fdadf2bae50d9c428 | {
"blob_id": "7a078ea861ca463b251bca2fdadf2bae50d9c428",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-11T22:54:07",
"content_id": "206c00a305107e248269f94768ff3fb0cdb930bb",
"detected_licenses": [
"MIT"
],
"directory_id": "4edd539e79d33f7a08a4c928d113771e9dac0740",
"extension": "c",
"filename": "setfontxy.c",
"fork_events_count": 55,
"gha_created_at": "2014-11-30T22:02:07",
"gha_event_created_at": "2022-11-03T04:07:37",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 27351671,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 232,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/burger/setfontxy.c",
"provenance": "stackv2-0115.json.gz:127412",
"repo_name": "Olde-Skuul/doom3do",
"revision_date": "2023-01-11T22:54:07",
"revision_id": "8a5cdae476e09f2bedd2cc4dcd105dae4b35d4af",
"snapshot_id": "84ae4f312e919d070dcb838f7765c5c1ad3f5efd",
"src_encoding": "UTF-8",
"star_events_count": 658,
"url": "https://raw.githubusercontent.com/Olde-Skuul/doom3do/8a5cdae476e09f2bedd2cc4dcd105dae4b35d4af/lib/burger/setfontxy.c",
"visit_date": "2023-03-07T19:10:13.752129"
} | stackv2 | #include "Burger.h"
/**********************************
Set the pen for the font manager
**********************************/
void FontSetXY(Word x,Word y)
{
FontX = x; /* Save off the X */
FontY = y; /* Save off the Y */
}
| 2.125 | 2 |
2024-11-18T22:25:32.682071+00:00 | 2023-06-13T11:34:49 | 629217c03bc730368f25a687b6fc180ab25462a0 | {
"blob_id": "629217c03bc730368f25a687b6fc180ab25462a0",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-13T11:34:49",
"content_id": "be856646bd1f09b925911ac338d66fb628f666b1",
"detected_licenses": [
"MIT"
],
"directory_id": "cfa39a4c71a733f39bf6d1f32ef540d3a49d608c",
"extension": "c",
"filename": "stat.c",
"fork_events_count": 73,
"gha_created_at": "2018-03-02T02:58:07",
"gha_event_created_at": "2023-03-08T03:47:15",
"gha_language": "Rust",
"gha_license_id": "MIT",
"github_id": 123522329,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 705,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/unistd/stat.c",
"provenance": "stackv2-0115.json.gz:127540",
"repo_name": "redox-os/relibc",
"revision_date": "2023-06-13T11:34:49",
"revision_id": "1ef79540776f2290924e5d996ef38c13e9f1d505",
"snapshot_id": "7d622ae036ccfedc31cbb19e7453f9caa1df873c",
"src_encoding": "UTF-8",
"star_events_count": 834,
"url": "https://raw.githubusercontent.com/redox-os/relibc/1ef79540776f2290924e5d996ef38c13e9f1d505/tests/unistd/stat.c",
"visit_date": "2023-08-31T01:42:51.820667"
} | stackv2 | #include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include "test_helpers.h"
int main(void) {
printf("sizeof(struct stat): %ld\n", sizeof(struct stat));
struct stat buf;
int stat_status = stat("unistd/stat.c", &buf);
ERROR_IF(stat, stat_status, == -1);
UNEXP_IF(stat, stat_status, != 0);
printf("st_size: %lu\n", buf.st_size);
printf("st_blksize: %lu\n", buf.st_blksize);
printf("st_dev: %lu\n", buf.st_dev);
printf("st_ino: %lu\n", buf.st_ino);
printf("st_mode: %o\n", buf.st_mode);
printf("st_nlink: %lu\n", buf.st_nlink);
printf("st_uid: %u\n", buf.st_uid);
printf("st_gid: %u\n", buf.st_gid);
}
| 2.640625 | 3 |
2024-11-18T22:25:32.856110+00:00 | 2020-04-15T22:31:04 | 3b8d24e53419218702a600d2de382bba22786e9e | {
"blob_id": "3b8d24e53419218702a600d2de382bba22786e9e",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-15T22:31:04",
"content_id": "2efd97fc61028979c52869aa66757aa4fdd9929e",
"detected_licenses": [
"MIT"
],
"directory_id": "41cb09de0e54d2d9db7b8c08c8d3a3fa913253c7",
"extension": "c",
"filename": "sprite.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": 603,
"license": "MIT",
"license_type": "permissive",
"path": "/src/sprite.c",
"provenance": "stackv2-0115.json.gz:127798",
"repo_name": "sxin-h/texpackr",
"revision_date": "2020-04-15T22:31:04",
"revision_id": "fd58c27dc9f85ad562cc58a131a33fb338feb6e4",
"snapshot_id": "478ade20e3e3bb00abf5bab32ac64216f70fcde9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sxin-h/texpackr/fd58c27dc9f85ad562cc58a131a33fb338feb6e4/src/sprite.c",
"visit_date": "2022-04-17T23:10:50.903570"
} | stackv2 | #include "texpackr/sprite.h"
#include "texpackr/png_util.h"
#include <stdlib.h>
void texpackr_sprite_free(texpackr_sprite* sp)
{
// free internals
texpackr_sprite_free_internals(sp);
// free itself
free(sp);
}
void texpackr_sprite_free_internals(texpackr_sprite* sp)
{
// free string
free(sp->filename);
sp->filename = NULL;
// free image data (if any)
if (sp->image_data != NULL)
{
texpackr_free_png_image_data((png_bytepp)sp->image_data, sp->size.y);
sp->image_data = NULL;
}
// reset other attributes
sp->offset.x = -1;
sp->offset.y = -1;
sp->size.x = -1;
sp->size.y = -1;
}
| 2.515625 | 3 |
2024-11-18T22:25:33.080121+00:00 | 2019-06-07T16:12:22 | b99cec69edbb42764114b33aea80380771f7401f | {
"blob_id": "b99cec69edbb42764114b33aea80380771f7401f",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-07T16:17:18",
"content_id": "fd858181c09113e78243bd6cfde97f6d5a06939c",
"detected_licenses": [
"MIT"
],
"directory_id": "f73ca367e91ebb1b9f96af18aaf04decbcc279f9",
"extension": "c",
"filename": "sys.c",
"fork_events_count": 0,
"gha_created_at": "2019-06-07T16:15:02",
"gha_event_created_at": "2019-09-22T13:57:08",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 190774173,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12003,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/sys.c",
"provenance": "stackv2-0115.json.gz:128056",
"repo_name": "ArvinJIN/Linux-kernel-Learning",
"revision_date": "2019-06-07T16:12:22",
"revision_id": "755ecbd5c27fae6f732a4486cd59784445b6d0a6",
"snapshot_id": "c77e94472096ba317b1a8a5524360ffad16c1162",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ArvinJIN/Linux-kernel-Learning/755ecbd5c27fae6f732a4486cd59784445b6d0a6/kernel/sys.c",
"visit_date": "2020-06-01T12:07:13.763411"
} | stackv2 | /*
* linux/kernel/sys.c
*
* (C) 1991 Linus Torvalds
*/
#include <errno.h>
#include <linux/sched.h>
#include <linux/tty.h>
#include <linux/kernel.h>
#include <linux/config.h>
#include <asm/segment.h>
#include <sys/times.h>
#include <sys/utsname.h>
#include <sys/param.h>
#include <sys/resource.h>
#include <string.h>
/*
* The timezone where the local system is located. Used as a default by some
* programs who obtain this value by using gettimeofday.
*/
struct timezone sys_tz = { 0, 0};
extern int session_of_pgrp(int pgrp);
int sys_ftime()
{
return -ENOSYS;
}
int sys_break()
{
return -ENOSYS;
}
int sys_ptrace()
{
return -ENOSYS;
}
int sys_stty()
{
return -ENOSYS;
}
int sys_gtty()
{
return -ENOSYS;
}
int sys_rename()
{
return -ENOSYS;
}
int sys_prof()
{
return -ENOSYS;
}
/*
* This is done BSD-style, with no consideration of the saved gid, except
* that if you set the effective gid, it sets the saved gid too. This
* makes it possible for a setgid program to completely drop its privileges,
* which is often a useful assertion to make when you are doing a security
* audit over a program.
*
* The general idea is that a program which uses just setregid() will be
* 100% compatible with BSD. A program which uses just setgid() will be
* 100% compatible with POSIX w/ Saved ID's.
*/
int sys_setregid(int rgid, int egid)
{
if (rgid>0) {
if ((current->gid == rgid) ||
suser())
current->gid = rgid;
else
return(-EPERM);
}
if (egid>0) {
if ((current->gid == egid) ||
(current->egid == egid) ||
suser()) {
current->egid = egid;
current->sgid = egid;
} else
return(-EPERM);
}
return 0;
}
/*
* setgid() is implemeneted like SysV w/ SAVED_IDS
*/
int sys_setgid(int gid)
{
if (suser())
current->gid = current->egid = current->sgid = gid;
else if ((gid == current->gid) || (gid == current->sgid))
current->egid = gid;
else
return -EPERM;
return 0;
}
int sys_acct()
{
return -ENOSYS;
}
int sys_phys()
{
return -ENOSYS;
}
int sys_lock()
{
return -ENOSYS;
}
int sys_mpx()
{
return -ENOSYS;
}
int sys_ulimit()
{
return -ENOSYS;
}
int sys_time(long * tloc)
{
int i;
i = CURRENT_TIME;
if (tloc) {
verify_area(tloc,4);
put_fs_long(i,(unsigned long *)tloc);
}
return i;
}
/*
* Unprivileged users may change the real user id to the effective uid
* or vice versa. (BSD-style)
*
* When you set the effective uid, it sets the saved uid too. This
* makes it possible for a setuid program to completely drop its privileges,
* which is often a useful assertion to make when you are doing a security
* audit over a program.
*
* The general idea is that a program which uses just setreuid() will be
* 100% compatible with BSD. A program which uses just setuid() will be
* 100% compatible with POSIX w/ Saved ID's.
*/
int sys_setreuid(int ruid, int euid)
{
int old_ruid = current->uid;
if (ruid>0) {
if ((current->euid==ruid) ||
(old_ruid == ruid) ||
suser())
current->uid = ruid;
else
return(-EPERM);
}
if (euid>0) {
if ((old_ruid == euid) ||
(current->euid == euid) ||
suser()) {
current->euid = euid;
current->suid = euid;
} else {
current->uid = old_ruid;
return(-EPERM);
}
}
return 0;
}
/*
* setuid() is implemeneted like SysV w/ SAVED_IDS
*
* Note that SAVED_ID's is deficient in that a setuid root program
* like sendmail, for example, cannot set its uid to be a normal
* user and then switch back, because if you're root, setuid() sets
* the saved uid too. If you don't like this, blame the bright people
* in the POSIX commmittee and/or USG. Note that the BSD-style setreuid()
* will allow a root program to temporarily drop privileges and be able to
* regain them by swapping the real and effective uid.
*/
int sys_setuid(int uid)
{
if (suser())
current->uid = current->euid = current->suid = uid;
else if ((uid == current->uid) || (uid == current->suid))
current->euid = uid;
else
return -EPERM;
return(0);
}
int sys_stime(long * tptr)
{
if (!suser())
return -EPERM;
startup_time = get_fs_long((unsigned long *)tptr) - jiffies/HZ;
jiffies_offset = 0;
return 0;
}
int sys_times(struct tms * tbuf)
{
if (tbuf) {
verify_area(tbuf,sizeof *tbuf);
put_fs_long(current->utime,(unsigned long *)&tbuf->tms_utime);
put_fs_long(current->stime,(unsigned long *)&tbuf->tms_stime);
put_fs_long(current->cutime,(unsigned long *)&tbuf->tms_cutime);
put_fs_long(current->cstime,(unsigned long *)&tbuf->tms_cstime);
}
return jiffies;
}
int sys_brk(unsigned long end_data_seg)
{
if (end_data_seg >= current->end_code &&
end_data_seg < current->start_stack - 16384)
current->brk = end_data_seg;
return current->brk;
}
/*
* This needs some heave checking ...
* I just haven't get the stomach for it. I also don't fully
* understand sessions/pgrp etc. Let somebody who does explain it.
*
* OK, I think I have the protection semantics right.... this is really
* only important on a multi-user system anyway, to make sure one user
* can't send a signal to a process owned by another. -TYT, 12/12/91
*/
int sys_setpgid(int pid, int pgid)
{
int i;
if (!pid)
pid = current->pid;
if (!pgid)
pgid = current->pid;
if (pgid < 0)
return -EINVAL;
for (i=0 ; i<NR_TASKS ; i++)
if (task[i] && (task[i]->pid == pid) &&
((task[i]->p_pptr == current) ||
(task[i] == current))) {
if (task[i]->leader)
return -EPERM;
if ((task[i]->session != current->session) ||
((pgid != pid) &&
(session_of_pgrp(pgid) != current->session)))
return -EPERM;
task[i]->pgrp = pgid;
return 0;
}
return -ESRCH;
}
int sys_getpgrp(void)
{
return current->pgrp;
}
int sys_setsid(void)
{
if (current->leader && !suser())
return -EPERM;
current->leader = 1;
current->session = current->pgrp = current->pid;
current->tty = -1;
return current->pgrp;
}
/*
* Supplementary group ID's
*/
int sys_getgroups(int gidsetsize, gid_t *grouplist)
{
int i;
if (gidsetsize)
verify_area(grouplist, sizeof(gid_t) * gidsetsize);
for (i = 0; (i < NGROUPS) && (current->groups[i] != NOGROUP);
i++, grouplist++) {
if (gidsetsize) {
if (i >= gidsetsize)
return -EINVAL;
put_fs_word(current->groups[i], (short *) grouplist);
}
}
return(i);
}
int sys_setgroups(int gidsetsize, gid_t *grouplist)
{
int i;
if (!suser())
return -EPERM;
if (gidsetsize > NGROUPS)
return -EINVAL;
for (i = 0; i < gidsetsize; i++, grouplist++) {
current->groups[i] = get_fs_word((unsigned short *) grouplist);
}
if (i < NGROUPS)
current->groups[i] = NOGROUP;
return 0;
}
int in_group_p(gid_t grp)
{
int i;
if (grp == current->egid)
return 1;
for (i = 0; i < NGROUPS; i++) {
if (current->groups[i] == NOGROUP)
break;
if (current->groups[i] == grp)
return 1;
}
return 0;
}
static struct utsname thisname = {
UTS_SYSNAME, UTS_NODENAME, UTS_RELEASE, UTS_VERSION, UTS_MACHINE
};
int sys_uname(struct utsname * name)
{
int i;
if (!name) return -ERROR;
verify_area(name,sizeof *name);
for(i=0;i<sizeof *name;i++)
put_fs_byte(((char *) &thisname)[i],i+(char *) name);
return 0;
}
/*
* Only sethostname; gethostname can be implemented by calling uname()
*/
int sys_sethostname(char *name, int len)
{
int i;
if (!suser())
return -EPERM;
if (len > MAXHOSTNAMELEN)
return -EINVAL;
for (i=0; i < len; i++) {
if ((thisname.nodename[i] = get_fs_byte(name+i)) == 0)
break;
}
if (thisname.nodename[i]) {
thisname.nodename[i>MAXHOSTNAMELEN ? MAXHOSTNAMELEN : i] = 0;
}
return 0;
}
int sys_getrlimit(int resource, struct rlimit *rlim)
{
if (resource >= RLIM_NLIMITS)
return -EINVAL;
verify_area(rlim,sizeof *rlim);
put_fs_long(current->rlim[resource].rlim_cur,
(unsigned long *) rlim);
put_fs_long(current->rlim[resource].rlim_max,
((unsigned long *) rlim)+1);
return 0;
}
int sys_setrlimit(int resource, struct rlimit *rlim)
{
struct rlimit new, *old;
if (resource >= RLIM_NLIMITS)
return -EINVAL;
old = current->rlim + resource;
new.rlim_cur = get_fs_long((unsigned long *) rlim);
new.rlim_max = get_fs_long(((unsigned long *) rlim)+1);
if (((new.rlim_cur > old->rlim_max) ||
(new.rlim_max > old->rlim_max)) &&
!suser())
return -EPERM;
*old = new;
return 0;
}
/*
* It would make sense to put struct rusuage in the task_struct,
* except that would make the task_struct be *really big*. After
* task_struct gets moved into malloc'ed memory, it would
* make sense to do this. It will make moving the rest of the information
* a lot simpler! (Which we're not doing right now because we're not
* measuring them yet).
*/
int sys_getrusage(int who, struct rusage *ru)
{
struct rusage r;
unsigned long *lp, *lpend, *dest;
if (who != RUSAGE_SELF && who != RUSAGE_CHILDREN)
return -EINVAL;
verify_area(ru, sizeof *ru);
memset((char *) &r, 0, sizeof(r));
if (who == RUSAGE_SELF) {
r.ru_utime.tv_sec = CT_TO_SECS(current->utime);
r.ru_utime.tv_usec = CT_TO_USECS(current->utime);
r.ru_stime.tv_sec = CT_TO_SECS(current->stime);
r.ru_stime.tv_usec = CT_TO_USECS(current->stime);
} else {
r.ru_utime.tv_sec = CT_TO_SECS(current->cutime);
r.ru_utime.tv_usec = CT_TO_USECS(current->cutime);
r.ru_stime.tv_sec = CT_TO_SECS(current->cstime);
r.ru_stime.tv_usec = CT_TO_USECS(current->cstime);
}
lp = (unsigned long *) &r;
lpend = (unsigned long *) (&r+1);
dest = (unsigned long *) ru;
for (; lp < lpend; lp++, dest++)
put_fs_long(*lp, dest);
return(0);
}
int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
{
if (tv) {
verify_area(tv, sizeof *tv);
put_fs_long(startup_time + CT_TO_SECS(jiffies+jiffies_offset),
(unsigned long *) tv);
put_fs_long(CT_TO_USECS(jiffies+jiffies_offset),
((unsigned long *) tv)+1);
}
if (tz) {
verify_area(tz, sizeof *tz);
put_fs_long(sys_tz.tz_minuteswest, (unsigned long *) tz);
put_fs_long(sys_tz.tz_dsttime, ((unsigned long *) tz)+1);
}
return 0;
}
/*
* The first time we set the timezone, we will warp the clock so that
* it is ticking GMT time instead of local time. Presumably,
* if someone is setting the timezone then we are running in an
* environment where the programs understand about timezones.
* This should be done at boot time in the /etc/rc script, as
* soon as possible, so that the clock can be set right. Otherwise,
* various programs will get confused when the clock gets warped.
*/
int sys_settimeofday(struct timeval *tv, struct timezone *tz)
{
static int firsttime = 1;
void adjust_clock();
if (!suser())
return -EPERM;
if (tz) {
sys_tz.tz_minuteswest = get_fs_long((unsigned long *) tz);
sys_tz.tz_dsttime = get_fs_long(((unsigned long *) tz)+1);
if (firsttime) {
firsttime = 0;
if (!tv)
adjust_clock();
}
}
if (tv) {
int sec, usec;
sec = get_fs_long((unsigned long *)tv);
usec = get_fs_long(((unsigned long *)tv)+1);
startup_time = sec - jiffies/HZ;
jiffies_offset = usec * HZ / 1000000 - jiffies%HZ;
}
return 0;
}
/*
* Adjust the time obtained from the CMOS to be GMT time instead of
* local time.
*
* This is ugly, but preferable to the alternatives. Otherwise we
* would either need to write a program to do it in /etc/rc (and risk
* confusion if the program gets run more than once; it would also be
* hard to make the program warp the clock precisely n hours) or
* compile in the timezone information into the kernel. Bad, bad....
*
* XXX Currently does not adjust for daylight savings time. May not
* need to do anything, depending on how smart (dumb?) the BIOS
* is. Blast it all.... the best thing to do not depend on the CMOS
* clock at all, but get the time via NTP or timed if you're on a
* network.... - TYT, 1/1/92
*/
void adjust_clock()
{
startup_time += sys_tz.tz_minuteswest*60;
}
int sys_umask(int mask)
{
int old = current->umask;
current->umask = mask & 0777;
return (old);
}
| 2.40625 | 2 |
2024-11-18T22:25:33.244732+00:00 | 2021-04-04T16:50:11 | 92ccb5f17fa3526a83f7bf67ab531339ff1aa350 | {
"blob_id": "92ccb5f17fa3526a83f7bf67ab531339ff1aa350",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-04T16:50:11",
"content_id": "0931bca3d8e3372aca3784f679e0f702650298c0",
"detected_licenses": [
"MIT"
],
"directory_id": "e4680bff66970dffb896a8baecf1cd6eac68632a",
"extension": "c",
"filename": "kernel.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 354027324,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1201,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel.c",
"provenance": "stackv2-0115.json.gz:128315",
"repo_name": "Dinuda/ASM",
"revision_date": "2021-04-04T16:50:11",
"revision_id": "eb26dfa67ffad2c7b1b21cf7fe5a8edc4c0ed437",
"snapshot_id": "806a5d0073b666752ce8242ebaad95552332487f",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Dinuda/ASM/eb26dfa67ffad2c7b1b21cf7fe5a8edc4c0ed437/kernel.c",
"visit_date": "2023-03-29T20:11:39.957968"
} | stackv2 | // assigns the start address
// resets terminal location
#define VGA_ADDRESS 0xB8000 /*video memory begins here */
/* VGA provides support for 16 colours */
#define BLACK 0
#define GREEN 2
#define RED 4
#define YELLOW 14
#define WHITE_COLOR 15
unsigned short *terminal_buffer;
unsigned int vga_index;
/* clears the terminal */
void clear_screen(void)
{
int index = 0;
/* there are 25 lines each of 80 coloumns each element takes 2 bytes*/
while (index < 80 * 25 * 2) {
terminal_buffer[index] = ' ';
index += 2;
}
}
// prints the message in one color
void print_string(char *str, unsigned char color)
{
int index = 0;
while (str[index]) {
terminal_buffer[vga_index] = (unsigned short)str[index]|(unsigned short)color << 8;
index++;
vga_index++;
}
}
// sets internal location marker to the next line
// prints another message
// returns back to the bootcode
void main(void)
{
terminal_buffer = (unsigned short *)VGA_ADDRESS;
vga_index = 0;
clear_screen();
print_string("Hello from ASM Journal!", YELLOW);
vga_index = 80; /* next line */
print_string("Goodbye from ASM Journal!", RED);
return;
}
| 3.171875 | 3 |
2024-11-18T22:25:33.330918+00:00 | 2015-11-24T14:07:50 | 7cf762e4f47e327ce574b98f189e57215a049804 | {
"blob_id": "7cf762e4f47e327ce574b98f189e57215a049804",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-24T14:07:50",
"content_id": "b76efdf7cf4280f5fdb15e8be18f27ab19958130",
"detected_licenses": [
"Intel"
],
"directory_id": "b1ccfd9d590cde12875fb877f21773dd61e8e9d8",
"extension": "c",
"filename": "downsample.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46795325,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7287,
"license": "Intel",
"license_type": "permissive",
"path": "/beta/platform/pxa27x/lib/downsample.c",
"provenance": "stackv2-0115.json.gz:128444",
"repo_name": "ekiwi/tinyos-1.x",
"revision_date": "2015-11-24T14:07:50",
"revision_id": "93cab8e9a78b666dff68121357405cea8a2c48fa",
"snapshot_id": "cf7f6042c9620db9daf10b48268cded8b35cbdda",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ekiwi/tinyos-1.x/93cab8e9a78b666dff68121357405cea8a2c48fa/beta/platform/pxa27x/lib/downsample.c",
"visit_date": "2016-08-11T08:14:21.323343"
} | stackv2 | // This is the implementation for the decimation algorithm by factors
// 2 to 256, in powers of 2.
#include "wmmx.h"
#include "downsample.h"
#include "coef.inc"
#include <string.h>
#define WMMX_ENABLE 1
//downsampleTempBuffer_t *tempbuf;
extern void firdecim_s(short int factor_M, long int H_size, short int* p_H,
short int* p_Z, long int num_inp, short int *p_inp,
short int *p_out, short int sc);
int downsampleInit(downsampleStates_t *st, downsampleTempBuffer_t *tempBuf){
int i;
#if WMMX_ENABLE
startWMMX();
#endif
for (i=0; i<88; i++) {
st->states88a[i]=0;
st->states88b[i]=0;
}
for (i=0; i<168; i++) {
st->states168[i]=0;
}
st->tempbuf = tempBuf;
return 1;
}
// FUNCTION: firdecim
// DECRIPTION: Decimates an input sequence by factor_M, using anti-aliasing
// filter specified by pointer p_H.
// PARAMS:
// FIR decimation filter
// factor_M: decimation factor
// H_size: length of FIR filter
// p_H: pointer to FIR filter
// p_Z: pointer to tap delay line
// num_inp: number of input data points (assume multiple of factor_M)
// p_inp: pointer to input data buffer
// p_out: pointer to output data buffer
// sc: scaling factor
//
// Jonathan Huang
// 5/17/05
#ifndef WMMX_ENABLE
void firdecim(short int factor_M, long int H_size, short int* p_H,
short int* p_Z, long int num_inp, short int *p_inp,
short int *p_out, short int sc)
{
int tap, num_out, sh;
// long int sum;
long long sum;
/* this implementation assuems num_inp is a multiple of factor_M */
//assert(num_inp % factor_M == 0);
sh = sc+7;
num_out = 0;
//printf("number of input samples: %d\n",num_inp);
while (num_inp >= factor_M) {
/* shift Z delay line up to make room for next samples */
for (tap = H_size - 1; tap >= factor_M; tap--) {
p_Z[tap] = p_Z[tap - factor_M];
}
/* copy next samples from input buffer to bottom of Z delay line */
for (tap = factor_M - 1; tap >= 0; tap--) {
p_Z[tap] = *p_inp++;
}
num_inp -= factor_M;
/* calculate FIR sum */
sum = 0;
for (tap = 0; tap < H_size; tap++) {
//sum += (p_H[tap] * p_Z[tap])>>sh;
sum += (p_H[tap] * p_Z[tap]);
}
// *p_out++ = (short int)(sum >> 9); /* store sum and point to next output */
*p_out++ = (short int)(sum >> (sc+16)); /* store sum and point to next output */
num_out++;
}
//*p_num_out = num_out; /* pass number of outputs back to caller */
}
#endif
// FUNCTION: downsample
// DESCRIPTION:
// Decimates a sequence of samples by a factor K. This implementation
// assumes 16-bit filter coefficients, so the maximum stopband attenuation
// is -80 dB. The passband has ripple of no more than 0.01 dB, and starts
// to roll off at 0.4 * final sampling rate.
// PARAMS:
// DownsampStates *d := filter states of decimation filters
// short int *inbuf := pointer to input buffer : must be aligned on an 8 byte boundary
// long int Nsamp := number of input samples : must be a power of and an integer multiple of K
// short int *outbuf := pointer to output buffer : no restriction on alignment
// (output length is Nsamp/K)
// short int K := decimation factor (from 2 to 256, powers of 2 only)
// RETURN VALUES:
// -1 := error, number of input samples not divisible by K
// -2 := error, value of K invalid
// 1 := decimation successful
//
// Jonathan Huang
// 5/17/05
int downsample(downsampleStates_t *d, short int *inbuf, long int Nsamp,
short int *outbuf, short int K) {
int status;
status = 1;
if ((Nsamp%K) != 0) status = -1;
switch(K) {
case 1:
memcpy(outbuf,inbuf,2*Nsamp);
break;
#ifdef WMMX_ENABLE
case 2:
firdecim_s(2,LEN2X88,h2x88,d->states88a,Nsamp,inbuf,
outbuf,SC2X88);
break;
case 4:
firdecim_s(4,LEN4X168,h4x168,d->states168,Nsamp,inbuf,
outbuf,SC4X168);
break;
case 8:
firdecim_s(4,LEN4X56,h4x56,d->states88a,Nsamp,inbuf,
d->tempbuf,SC4X56);
firdecim_s(2,LEN2X88,h2x88,d->states88b,Nsamp/4,d->tempbuf,
outbuf,SC2X88);
break;
case 16:
firdecim_s(4,LEN4X56,h4x56,d->states88a,Nsamp,inbuf,
d->tempbuf,SC4X56);
firdecim_s(4,LEN4X168,h4x168,d->states168,Nsamp/4,d->tempbuf,
outbuf,SC4X168);
break;
case 32:
firdecim_s(8,LEN8X88,h8x88,d->states88a,Nsamp,inbuf,
d->tempbuf,SC8X88);
firdecim_s(4,LEN4X168,h4x168,d->states168,Nsamp/8,d->tempbuf,
outbuf,SC4X168);
break;
case 64:
firdecim_s(4,LEN4X56,h4x56,d->states88a,Nsamp,inbuf,
d->tempbuf,SC4X56);
firdecim_s(4,LEN4X56,h4x56,d->states88b,Nsamp/4,d->tempbuf,
inbuf,SC4X56);
firdecim_s(4,LEN4X168,h4x168,d->states168,Nsamp/16,inbuf,
outbuf,SC4X168);
break;
case 128:
firdecim_s(8,LEN8X88,h8x88,d->states88a,Nsamp,inbuf,
d->tempbuf,SC8X88);
firdecim_s(4,LEN4X56,h4x56,d->states88b,Nsamp/8,d->tempbuf,
inbuf,SC4X56);
firdecim_s(4,LEN4X168,h4x168,d->states168,Nsamp/32,inbuf,
outbuf,SC4X168);
break;
case 256:
firdecim_s(8,LEN8X88,h8x88,d->states88a,Nsamp,inbuf,
d->tempbuf,SC8X88);
firdecim_s(8,LEN8X88,h8x88,d->states88b,Nsamp/8,d->tempbuf,
inbuf,SC8X88);
firdecim_s(4,LEN4X168,h4x168,d->states168,Nsamp/64,inbuf,
outbuf,SC4X168);
break;
#else
case 2:
firdecim(2,LEN2X88,h2x88,d->states88a,Nsamp,inbuf,
outbuf,SC2X88);
break;
case 4:
firdecim(4,LEN4X168,h4x168,d->states168,Nsamp,inbuf,
outbuf,SC4X168);
break;
case 8:
firdecim(4,LEN4X56,h4x56,d->states88a,Nsamp,inbuf,
d->tempbuf,SC4X56);
firdecim(2,LEN2X88,h2x88,d->states88b,Nsamp/4,d->tempbuf,
outbuf,SC2X88);
break;
case 16:
firdecim(4,LEN4X56,h4x56,d->states88a,Nsamp,inbuf,
d->tempbuf,SC4X56);
firdecim(4,LEN4X168,h4x168,d->states168,Nsamp/4,d->tempbuf,
outbuf,SC4X168);
break;
case 32:
firdecim(8,LEN8X88,h8x88,d->states88a,Nsamp,inbuf,
d->tempbuf,SC8X88);
firdecim(4,LEN4X168,h4x168,d->states168,Nsamp/8,d->tempbuf,
outbuf,SC4X168);
break;
case 64:
firdecim(4,LEN4X56,h4x56,d->states88a,Nsamp,inbuf,
d->tempbuf,SC4X56);
firdecim(4,LEN4X56,h4x56,d->states88b,Nsamp/4,d->tempbuf,
inbuf,SC4X56);
firdecim(4,LEN4X168,h4x168,d->states168,Nsamp/16,inbuf,
outbuf,SC4X168);
break;
case 128:
firdecim(8,LEN8X88,h8x88,d->states88a,Nsamp,inbuf,
d->tempbuf,SC8X88);
firdecim(4,LEN4X56,h4x56,d->states88b,Nsamp/8,d->tempbuf,
inbuf,SC4X56);
firdecim(4,LEN4X168,h4x168,d->states168,Nsamp/32,inbuf,
outbuf,SC4X168);
break;
case 256:
firdecim(8,LEN8X88,h8x88,d->states88a,Nsamp,inbuf,
d->tempbuf,SC8X88);
firdecim(8,LEN8X88,h8x88,d->states88b,Nsamp/8,d->tempbuf,
inbuf,SC8X88);
firdecim(4,LEN4X168,h4x168,d->states168,Nsamp/64,inbuf,
outbuf,SC4X168);
break;
#endif
default:
status = -2;
}
return status;
}
| 2.765625 | 3 |
2024-11-18T22:25:33.571458+00:00 | 2014-07-15T02:30:09 | e6c37c929d4f04ef91441078eb0168089ced95d3 | {
"blob_id": "e6c37c929d4f04ef91441078eb0168089ced95d3",
"branch_name": "refs/heads/master",
"committer_date": "2014-07-15T02:30:09",
"content_id": "29bf0067456d4539b703b3f6c3fe19117db4c5fe",
"detected_licenses": [
"MIT-Modern-Variant"
],
"directory_id": "ebfaca83570372a1b9c355b8a52a226fe56967d0",
"extension": "c",
"filename": "cktbindn.c",
"fork_events_count": 8,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 21843543,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1451,
"license": "MIT-Modern-Variant",
"license_type": "permissive",
"path": "/src/lib/ckt/cktbindn.c",
"provenance": "stackv2-0115.json.gz:128830",
"repo_name": "pickleburger/spice3f5",
"revision_date": "2014-07-15T02:30:09",
"revision_id": "73335519d0d7046c754c652569258c5ff1107cf4",
"snapshot_id": "f11ea44bac248140bde36580c91214d9387a454b",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/pickleburger/spice3f5/73335519d0d7046c754c652569258c5ff1107cf4/src/lib/ckt/cktbindn.c",
"visit_date": "2020-04-14T13:39:13.154546"
} | stackv2 | /**********
Copyright 1990 Regents of the University of California. All rights reserved.
Author: 1985 Thomas L. Quarles
**********/
/* CKTbindNode
* bind a node of the specified device of the given type to its place
* in the specified circuit.
*/
#include "spice.h"
#include <stdio.h>
#include "ifsim.h"
#include "smpdefs.h"
#include "cktdefs.h"
#include "util.h"
#include "devdefs.h"
#include "sperror.h"
#include "suffix.h"
extern SPICEdev *DEVices[];
/*ARGSUSED*/
int
CKTbindNode(ckt,fast,term,node)
GENERIC *ckt;
GENERIC *fast;
int term;
GENERIC *node;
{
int mappednode;
register int type = ((GENinstance *)fast)->GENmodPtr->GENmodType;
mappednode = ((CKTnode *)node)->number;
if(*((*DEVices[type]).DEVpublic.terms) >= term && term >0 ) {
switch(term) {
default: return(E_NOTERM);
case 1:
((GENinstance *)fast)->GENnode1 = mappednode;
break;
case 2:
((GENinstance *)fast)->GENnode2 = mappednode;
break;
case 3:
((GENinstance *)fast)->GENnode3 = mappednode;
break;
case 4:
((GENinstance *)fast)->GENnode4 = mappednode;
break;
case 5:
((GENinstance *)fast)->GENnode5 = mappednode;
break;
}
return(OK);
} else {
return(E_NOTERM);
}
}
| 2.046875 | 2 |
2024-11-18T22:25:33.892088+00:00 | 2020-01-30T22:08:52 | 10638264bc664c24b3d946c265599a5a67eb4302 | {
"blob_id": "10638264bc664c24b3d946c265599a5a67eb4302",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-30T22:08:52",
"content_id": "f5a13f44dc83d6429d59dfbe51561cb3d3bf0940",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0677d788eb8b6f6f6211187afd8bb23edf45e609",
"extension": "c",
"filename": "arithmetictest.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 157774304,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 509,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/arithmetictest.c",
"provenance": "stackv2-0115.json.gz:128958",
"repo_name": "dan-seol/C",
"revision_date": "2020-01-30T22:08:52",
"revision_id": "ffacb4ddac3139476f38068b41b73cd9e966f7d0",
"snapshot_id": "9d27d2ba2ffae625fb3488bcdfd200c749581b97",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dan-seol/C/ffacb4ddac3139476f38068b41b73cd9e966f7d0/arithmetictest.c",
"visit_date": "2020-04-06T20:30:04.262827"
} | stackv2 | #include <stdio.h>
#include <math.h>
int power2(int m){
if(m==0){
return 1;
} else if (m < 0) { // positive integer assumes
printf("This functions is defined for nonnegative integers only");
return -1;
} else {
return 2*power2(m-1);
}
}
int main(void){
int n = 5;
printf("%d\n", n/2);
int m= 9;
printf("%f %d\n",log2(m), (int)(log2(m)));
printf("%d\n", (log2(m) - (int)log2(m) ==0));
printf("%d\n", power2(0));
printf("%d\n", power2(2));
printf("%d\n", power2(3));
}
| 3.25 | 3 |
2024-11-18T22:25:34.287033+00:00 | 2021-03-31T22:06:24 | 985aaa45437d9e29151246bd7f45c623be63f7d4 | {
"blob_id": "985aaa45437d9e29151246bd7f45c623be63f7d4",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-31T22:06:24",
"content_id": "17e884c53e975944cc55d8c088f40e86fae868e4",
"detected_licenses": [
"MIT"
],
"directory_id": "7fe1bfa8d15c799235cac6c6820702a5c8648087",
"extension": "c",
"filename": "configure.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 353498314,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16154,
"license": "MIT",
"license_type": "permissive",
"path": "/src/configure.c",
"provenance": "stackv2-0115.json.gz:129608",
"repo_name": "chucktilbury/atlang",
"revision_date": "2021-03-31T22:06:24",
"revision_id": "c862ec6bf7192e2713ca65146aec7b6c75b09fa0",
"snapshot_id": "ea757e3372d3e19dd2681e936aab59d812382883",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chucktilbury/atlang/c862ec6bf7192e2713ca65146aec7b6c75b09fa0/src/configure.c",
"visit_date": "2023-03-28T09:23:43.956911"
} | stackv2 | /*
* Stand-alone command line parser.
*
* Command parameters have the format of "-x arg". In this, 'x' can be any letter or number
* and they are case sensitive. Command switches are exactly 2 characters and may NOT be
* combined. In other words, the arg "-xasc12" is parsed as "-x", "asc12". This is not
* optimal, and may change. It would be better to have command args any arbitrary length,
* but that is not easy to fix with this implementation.
*
*/
// TODO Only look at the parameter for the length of it, so that the value can be
// concatenated to it.
#include "common.h"
//static char cmd_line_buffer[1024*4];
static char prog_name[1024];
static configuration_t* find_config_by_arg(const char* arg) {
for(int i = 0; _global_config[i].type != CONFIG_TYPE_END; i++) {
if(_global_config[i].arg == NULL)
continue;
else if(!strncmp(arg, _global_config[i].arg, strlen(_global_config[i].arg))) {
return &_global_config[i];
}
}
return NULL;
}
static configuration_t* find_config_by_name(const char* name) {
for(int i = 0; _global_config[i].type != CONFIG_TYPE_END; i++) {
if(_global_config[i].name == NULL)
continue;
else if(!strcmp(name, _global_config[i].name)) {
return &_global_config[i];
}
}
return NULL;
}
// aborts program if required parameter is not found
static void check_required(void) {
int hlp = 0;
for(int i = 0; _global_config[i].type != CONFIG_TYPE_END; i++) {
if(_global_config[i].required != 0 && _global_config[i].touched == 0) {
fprintf(stderr, "CMD ERROR: required parameter \"%s\" (%s) is missing\n",
_global_config[i].arg? _global_config[i].arg: "none",
_global_config[i].name);
show_use(); // does not return
}
if(_global_config[i].touched > 1 && _global_config[i].once) {
fprintf(stderr, "CMD_ERROR: parameter \"%s\" (%s) can appear only once\n",
_global_config[i].arg? _global_config[i].arg: "none",
_global_config[i].name);
show_use(); // does not return
}
if(_global_config[i].type == CONFIG_TYPE_HELP && _global_config[i].value.number)
hlp++;
}
if(hlp)
show_use();
}
void destroy_config(void) {
log_debug("destroy_config: enter");
for(int i = 0; _global_config[i].type != CONFIG_TYPE_END; i++) {
switch(_global_config[i].type) {
case CONFIG_TYPE_STR: {
//fprintf(stderr, "CFG: string: %s: %s\n", _global_config[i].name, _global_config[i].value.string);
FREE(_global_config[i].value.string);
}
break;
case CONFIG_TYPE_LIST: {
//fprintf(stderr, "CFG: list: %s\n", _global_config[i].name);
ptr_list_t* lst = _global_config[i].value.list;
reset_ptr_list(lst);
for(void* item = get_ptr_list_next(lst); item != NULL; item = get_ptr_list_next(lst)) {
//fprintf(stderr, "CFG: list item: %s\n", (char*)item);
FREE(item);
}
destroy_ptr_list(lst);
}
break;
case CONFIG_TYPE_BOOL:
case CONFIG_TYPE_NUM:
case CONFIG_TYPE_HELP:
case CONFIG_TYPE_END:
break; // do nothing, no memory allocated
default:
fprintf(stderr, "CFG ERROR: unknown configuration type (hello weeds)\n");
exit(1);
}
}
log_debug("destroy_config: leave");
}
static void init_config(void) {
for(int i = 0; _global_config[i].name != NULL; i++) {
if(_global_config[i].type == CONFIG_TYPE_LIST) {
if(_global_config[i].value.string != NULL) {
// save the default value
ptr_list_t* list = create_ptr_list();
char* ptr = STRDUP(_global_config[i].value.string);
if(strchr(ptr, ':')) {
// parse through a list
for(char* tmp = strtok(ptr, ":"); tmp != NULL; tmp = strtok(NULL, ":"))
append_ptr_list(list, STRDUP(tmp));
FREE(ptr);
}
else
append_ptr_list(list, ptr);
_global_config[i].value.list = list;
}
else
_global_config[i].value.list = create_ptr_list();
}
else if(_global_config[i].type == CONFIG_TYPE_STR) {
// this will be a literal string, so allocate it to allow us to destroy it later.
if(_global_config[i].value.string != NULL) {
char* ptr = STRDUP(_global_config[i].value.string);
_global_config[i].value.string = ptr;
}
}
}
//atexit(destroy_config);
}
int configure(int argc, char** argv) {
configuration_t* config;
int idx;
init_config();
strncpy(prog_name, argv[0], sizeof(prog_name));
for(idx = 1; idx < argc; idx++) {
config = find_config_by_arg(argv[idx]);
if(config == NULL) {
if(argv[idx][0] == '-') {
fprintf(stderr, "CMD ERROR: Unknown configuration parameter: \"%s\"\n", argv[idx]);
show_use(); // does not return
}
else {
// it's an input file
config = find_config_by_name("INFILES");
const char* ptr = STRDUP(argv[idx]);
append_ptr_list(config->value.list, (void*)ptr);
config->touched++;
continue;
}
}
switch(config->type) {
case CONFIG_TYPE_NUM: {
char* value;
if(strlen(argv[idx]) > strlen(config->arg))
value = &argv[idx][strlen(config->arg)];
else {
idx++;
value = argv[idx];
}
int num = (int)strtol(value, NULL, 0);
if(num == 0 && errno != 0) {
fprintf(stderr, "CMD ERROR: Cannot convert string \"%s\" to a number\n", argv[idx]);
show_use();
}
config->value.number = num;
config->touched++;
}
break;
case CONFIG_TYPE_LIST: {
char* value;
if(strlen(argv[idx]) > strlen(config->arg))
value = &argv[idx][strlen(config->arg)];
else {
idx++;
value = argv[idx];
}
char* ptr = STRDUP(value);
if(strchr(ptr, ':')) {
// parse through a list
for(char* tmp = strtok(ptr, ":"); tmp != NULL; tmp = strtok(NULL, ":"))
append_ptr_list(config->value.list, STRDUP(tmp));
FREE(ptr);
}
else
append_ptr_list(config->value.list, (void*)ptr);
config->touched++;
}
break;
case CONFIG_TYPE_STR: {
char* value;
if(strlen(argv[idx]) > strlen(config->arg))
value = &argv[idx][strlen(config->arg)];
else {
idx++;
value = argv[idx];
}
config->value.string = STRDUP(value);
config->touched++;
}
break;
case CONFIG_TYPE_HELP:
case CONFIG_TYPE_BOOL:
config->value.number = (config->value.number & 0x01) ^ 0x01;
config->touched++;
break;
default:
fprintf(stderr, "CFG ERROR: Unexpected configuration type (hello weeds)\n");
exit(1);
}
}
check_required();
return idx;
}
char* get_prog_name(void) {
return prog_name;
}
void* get_config(const char* name) {
void* retv = NULL;
if(!strcmp(name, "PROG_NAME"))
retv = (void*)prog_name;
else {
configuration_t* config = find_config_by_name(name);
if(config == NULL) {
fprintf(stderr, "CFG ERROR: Cannot find configuration item: \"%s\"\n", name);
exit(1);
}
switch(config->type) {
case CONFIG_TYPE_NUM:
case CONFIG_TYPE_BOOL:
retv = (void*)&config->value.number;
break;
case CONFIG_TYPE_STR:
retv = (void*)config->value.string;
break;
case CONFIG_TYPE_LIST:
if(config->value.list->nitems == 0)
retv = NULL;
else
retv = (void*)config->value.list->buffer;
break;
default:
fprintf(stderr, "CFG ERROR: Unknown config type\n");
exit(1);
}
}
return retv;
}
// given the parameter name, iterate the list. Returns any parameter by a string ptr,
// including a number. Returns NULL when the end is reached.
char* iterate_config(const char* name) {
char* retv = NULL;
configuration_t* config = find_config_by_name(name);
if(config == NULL) {
fprintf(stderr, "CFG ERROR: Cannot find configuration parameter: \"%s\"\n", name);
exit(1);
}
switch(config->type) {
case CONFIG_TYPE_NUM:
case CONFIG_TYPE_BOOL:
// there can be only exactly one value here. Allocate the buffer if it does not exist
// and then return it.
if(config->iter_buf == NULL) {
config->iter_buf = CALLOC(12, sizeof(char)); // maximum number of characters in an int.
snprintf(config->iter_buf, 12, "%d", config->value.number);
}
else {
FREE(config->iter_buf);
config->iter_buf = NULL;
}
retv = config->iter_buf;
break;
case CONFIG_TYPE_STR:
// there can be only exactly one value here. It's already a (char*).
if(config->iter_buf == NULL)
config->iter_buf = config->value.string;
else
config->iter_buf = NULL;
retv = config->iter_buf;
break;
case CONFIG_TYPE_LIST:
// This type actually gets iterated. use strtok_r() to iterate it.
if(config->iter_buf != NULL) {
config->iter_buf = get_ptr_list_next(config->value.list);
retv = config->iter_buf;
}
else {
reset_ptr_list(config->value.list);
config->iter_buf = get_ptr_list_next(config->value.list);
retv = config->iter_buf;
}
break;
default:
fprintf(stderr, "CFG ERROR: Cannot iterate configuration parameter\n");
exit(1);
}
return retv;
}
// call this before starting an iteration
void reset_config_list(const char* name) {
configuration_t* config = find_config_by_name(name);
if(config->type == CONFIG_TYPE_LIST)
reset_ptr_list(config->value.list);
// else just do nothing
}
void show_use(void) {
fprintf(stderr, "Use: %s <parameters> <file list>\n", prog_name);
for(int i = 0; _global_config[i].type != CONFIG_TYPE_END; i++) {
switch(_global_config[i].type) {
case CONFIG_TYPE_NUM:
fprintf(stderr, "\n %2s <num> %s\n",
_global_config[i].arg != NULL? _global_config[i].arg: "",
_global_config[i].help);
fprintf(stderr, " val: %d required: %s\n",
_global_config[i].value.number,
_global_config[i].required? "TRUE": "FALSE");
break;
case CONFIG_TYPE_STR:
fprintf(stderr, "\n %2s <str> %s\n",
_global_config[i].arg != NULL? _global_config[i].arg: "",
_global_config[i].help);
fprintf(stderr, " val: %s required: %s\n",
_global_config[i].value.string,
_global_config[i].required? "TRUE": "FALSE");
break;
case CONFIG_TYPE_BOOL:
case CONFIG_TYPE_HELP:
fprintf(stderr, "\n %2s <bool> %s\n",
_global_config[i].arg != NULL? _global_config[i].arg: "",
_global_config[i].help);
fprintf(stderr, " val: %s required: %s\n",
_global_config[i].value.number? "TRUE": "FALSE",
_global_config[i].required? "TRUE": "FALSE");
break;
case CONFIG_TYPE_LIST:
fprintf(stderr, "\n %2s <list> %s\n",
_global_config[i].arg != NULL? _global_config[i].arg: "",
_global_config[i].help);
fprintf(stderr, " required: %s\n", _global_config[i].required? "TRUE": "FALSE");
if(_global_config[i].value.list->nitems != 0) {
ptr_list_t* list = _global_config[i].value.list;
fprintf(stderr, " ");
for(char* ptr = get_ptr_list_next(list); ptr != NULL; ptr = get_ptr_list_next(list))
fprintf(stderr, "%s ", ptr);
fprintf(stderr, "\n");
}
else
fprintf(stderr, " <empty>\n");
break;
default:
fprintf(stderr, "INTERNAL ERROR: Cannot parse command line\n");
exit(1);
}
}
fprintf(stderr, "\n");
exit(1);
}
#ifdef __TESTING_CONFIGURE_C__
/*
* Sanity check this functionality.
*
* example:
* ./cfg -o filename.fn -i f1.c:f2.c:f3.c -v 10
* -or-
* ./cfg -ofilename.fn -if1.c:f2.c:f3.c -v10
*
*/
BEGIN_CONFIG
CONFIG_NUM("-v", "VERBOSE", "Control the verbosity", 0, 0)
CONFIG_STR("-o", "OUT_FILE", "Name the output file", 1, NULL)
CONFIG_BOOL("-boo", "BOOL_VAL", "Demostrate a boolean value", 0, 0)
CONFIG_LIST("-i", "INPUT_FILES", "List of files to be compiled", 1, NULL)
CONFIG_LIST("-s", "FILE_SEARCH", "Set the search path list", 0, "./:./include")
END_CONFIG
int main(int argc, char** argv) {
int n = configure(argc, argv);
printf("num_parms: %d\n", n);
printf("verbosity: %d\n", *(int*)get_config("VERBOSE"));
printf("file_search: %s\n", (char*)get_config("FILE_SEARCH"));
printf("file_list: %s\n", (char*)get_config("INPUT_FILES"));
printf("out file: %s\n", (char*)get_config("OUT_FILE"));
printf("prog_name: %s\n", (char*)get_config("PROG_NAME"));
printf("bool_val: %d\n", GET_CONFIG_BOOL("BOOL_VAL"));
printf("\nVERBOSE: ");
for(char* str = iterate_config("VERBOSE"); str != NULL; str = iterate_config("VERBOSE"))
printf("%s ", str);
printf("\n");
printf("FILE_SEARCH: ");
for(char* str = iterate_config("FILE_SEARCH"); str != NULL; str = iterate_config("FILE_SEARCH"))
printf("%s ", str);
printf("\n");
printf("INPUT_FILES: ");
for(char* str = iterate_config("INPUT_FILES"); str != NULL; str = iterate_config("INPUT_FILES"))
printf("%s ", str);
printf("\n");
printf("OUT_FILE: ");
for(char* str = iterate_config("OUT_FILE"); str != NULL; str = iterate_config("OUT_FILE"))
printf("%s ", str);
printf("\n");
printf("BOOL_VAL: ");
for(char* str = iterate_config("BOOL_VAL"); str != NULL; str = iterate_config("BOOL_VAL"))
printf("%s ", str);
printf("\n");
//show_use();
}
#endif
| 2.515625 | 3 |
2024-11-18T22:25:34.540833+00:00 | 2020-10-24T07:06:51 | c5efcbc729ab1a000f7ac7732e1d6976230481ee | {
"blob_id": "c5efcbc729ab1a000f7ac7732e1d6976230481ee",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-24T07:06:51",
"content_id": "00b60092c99104ade5cae03ebdece13acb8673c8",
"detected_licenses": [
"MIT"
],
"directory_id": "4743a9cdcea389b3d555ea9868f1f17f0019c404",
"extension": "c",
"filename": "admin-menu.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 292138466,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1080,
"license": "MIT",
"license_type": "permissive",
"path": "/project_based_good_pratics/admin-menu.c",
"provenance": "stackv2-0115.json.gz:129737",
"repo_name": "thalisses/TADS-PFDA1",
"revision_date": "2020-10-24T07:06:51",
"revision_id": "154a057d8347f2062cb5edce6c79df308a15c5bb",
"snapshot_id": "4d3544f74d2d65372c9b3d6368c61e225e369bf9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/thalisses/TADS-PFDA1/154a057d8347f2062cb5edce6c79df308a15c5bb/project_based_good_pratics/admin-menu.c",
"visit_date": "2023-01-02T03:53:04.559025"
} | stackv2 | /* Bibliotecas */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib-drive-thru.h"
char menu (void)
{
/* Vari�vel local */
char escolha;
system ("clear");
printf ("\n============================");
printf ("\n M E N U ");
printf ("\n============================");
printf ("\n 1. Cadastrar produtos ");
printf ("\n 2. Consultar produtos ");
printf ("\n 3. Consultar vendas ");
printf ("\n 0. FIM ");
printf ("\n============================");
printf ("\n Escolha: "); fflush (stdin); escolha = getchar();
return (escolha);
}
void admin (char tecla)
{
switch ( tecla )
{
case '1': system("./add-products"); break;
case '2':
{
visualizarProdutos();
printf("\n Aperte qualquer tecla para continuar...");
getchar();
}
break;
case '3': printf("Chama o modulo de vendas"); break;
}
}
/* Corpo do Programa */
int main ()
{
char op;
while ( op != '0' )
{
op = menu();
getchar();
admin ( op );
}
return (0);
}
| 3.109375 | 3 |
2024-11-18T22:25:34.794203+00:00 | 2015-01-28T19:05:56 | 777cbd020d059a906d0d99e5ef6db04e7d3932a8 | {
"blob_id": "777cbd020d059a906d0d99e5ef6db04e7d3932a8",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-28T19:05:56",
"content_id": "cdb7949d9093be11d85f6b2df694ccf5f8152f11",
"detected_licenses": [
"MIT"
],
"directory_id": "f3a6fe70cd4f1024ecd2d794e9d5ea583680c8b2",
"extension": "c",
"filename": "malloctest.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 29983122,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6158,
"license": "MIT",
"license_type": "permissive",
"path": "/kern/test/malloctest.c",
"provenance": "stackv2-0115.json.gz:129997",
"repo_name": "computist/os161",
"revision_date": "2015-01-28T19:05:56",
"revision_id": "ade7922890379032c6040277d39a8991a07da92c",
"snapshot_id": "9a14380d1195111c256f568f91aa2708fb29002a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/computist/os161/ade7922890379032c6040277d39a8991a07da92c/kern/test/malloctest.c",
"visit_date": "2021-01-10T19:37:47.905403"
} | stackv2 | /*
* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009
* The President and Fellows of Harvard College.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Test code for kmalloc.
*/
#include <types.h>
#include <kern/errno.h>
#include <lib.h>
#include <thread.h>
#include <synch.h>
#include <vm.h> /* for PAGE_SIZE */
#include <test.h>
/*
* Test kmalloc; allocate ITEMSIZE bytes NTRIES times, freeing
* somewhat later.
*
* The total of ITEMSIZE * NTRIES is intended to exceed the size of
* available memory.
*
* mallocstress does the same thing, but from NTHREADS different
* threads at once.
*/
#define NTRIES 1200
#define ITEMSIZE 997
#define NTHREADS 8
static
int
mallocthread(void *sm, unsigned long num)
{
struct semaphore *sem = sm;
void *ptr;
void *oldptr=NULL;
void *oldptr2=NULL;
int i;
for (i=0; i<NTRIES; i++) {
ptr = kmalloc(ITEMSIZE);
if (ptr==NULL) {
if (sem) {
kprintf("thread %lu: kmalloc returned NULL\n",
num);
V(sem);
return -1;
}
kprintf("kmalloc returned null; test failed.\n");
return -1;
}
if (oldptr2) {
kfree(oldptr2);
}
oldptr2 = oldptr;
oldptr = ptr;
}
if (oldptr2) {
kfree(oldptr2);
}
if (oldptr) {
kfree(oldptr);
}
if (sem) {
V(sem);
}
return 0;
}
int
malloctest(int nargs, char **args)
{
(void)nargs;
(void)args;
kprintf("Starting kmalloc test...\n");
mallocthread(NULL, 0);
kprintf("kmalloc test done\n");
return 0;
}
int
mallocstress(int nargs, char **args)
{
struct semaphore *sem;
int i, result;
(void)nargs;
(void)args;
sem = sem_create("mallocstress", 0);
if (sem == NULL) {
panic("mallocstress: sem_create failed\n");
}
kprintf("Starting kmalloc stress test...\n");
for (i=0; i<NTHREADS; i++) {
result = thread_fork("mallocstress", NULL, NULL,
mallocthread, sem, i);
if (result) {
panic("mallocstress: thread_fork failed: %s\n",
strerror(result));
}
}
for (i=0; i<NTHREADS; i++) {
P(sem);
}
sem_destroy(sem);
kprintf("kmalloc stress test done\n");
return 0;
}
int
malloctest3(int nargs, char **args)
{
static const unsigned sizes[5] = { 32, 41, 109, 86, 9 };
unsigned numptrs;
size_t ptrspace;
size_t blocksize;
unsigned numptrblocks;
void ***ptrblocks;
unsigned curblock, curpos, cursizeindex, cursize;
size_t totalsize;
unsigned i, j;
unsigned char *ptr;
if (nargs != 2) {
kprintf("malloctest3: usage: malloctest3 numobjects\n");
return EINVAL;
}
numptrs = atoi(args[1]);
ptrspace = numptrs * sizeof(void *);
/* Use the subpage allocator for the pointer blocks too. */
blocksize = PAGE_SIZE / 4;
numptrblocks = DIVROUNDUP(ptrspace, blocksize);
kprintf("malloctest3: %u objects, %u pointer blocks\n",
numptrs, numptrblocks);
ptrblocks = kmalloc(numptrblocks * sizeof(ptrblocks[0]));
if (ptrblocks == NULL) {
panic("malloctest3: failed on pointer block array\n");
}
for (i=0; i<numptrblocks; i++) {
ptrblocks[i] = kmalloc(blocksize);
if (ptrblocks[i] == NULL) {
panic("malloctest3: failed on pointer block %u\n", i);
}
}
curblock = 0;
curpos = 0;
cursizeindex = 0;
totalsize = 0;
for (i=0; i<numptrs; i++) {
cursize = sizes[cursizeindex];
ptr = kmalloc(cursize);
if (ptr == NULL) {
kprintf("malloctest3: failed on object %u size %u\n",
i, cursize);
kprintf("malloctest3: pos %u in pointer block %u\n",
curpos, curblock);
kprintf("malloctest3: total so far %zu\n", totalsize);
panic("malloctest3: failed.\n");
}
for (j=0; j<cursize; j++) {
ptr[j] = (unsigned char) i;
}
ptrblocks[curblock][curpos] = ptr;
curpos++;
if (curpos >= blocksize / sizeof(void *)) {
curblock++;
curpos = 0;
}
totalsize += cursize;
}
kprintf("malloctest3: %zu bytes allocated\n", totalsize);
curblock = 0;
curpos = 0;
cursizeindex = 0;
for (i=0; i<numptrs; i++) {
cursize = sizes[cursizeindex];
ptr = ptrblocks[curblock][curpos];
KASSERT(ptr != NULL);
for (j=0; j<cursize; j++) {
if (ptr[j] == (unsigned char) i) {
continue;
}
kprintf("malloctest3: failed on object %u size %u\n",
i, cursize);
kprintf("malloctest3: pos %u in pointer block %u\n",
curpos, curblock);
kprintf("malloctest3: at object offset %u\n", j);
kprintf("malloctest3: expected 0x%x, found 0x%x\n",
ptr[j], (unsigned char) i);
panic("malloctest3: failed.\n");
}
kfree(ptr);
curpos++;
if (curpos >= blocksize / sizeof(void *)) {
curblock++;
curpos = 0;
}
KASSERT(totalsize > 0);
totalsize -= cursize;
}
KASSERT(totalsize == 0);
for (i=0; i<numptrblocks; i++) {
KASSERT(ptrblocks[i] != NULL);
kfree(ptrblocks[i]);
}
kfree(ptrblocks);
kprintf("malloctest3: passed\n");
return 0;
}
| 2.1875 | 2 |
2024-11-18T22:25:34.894177+00:00 | 2020-01-27T15:47:27 | bec8fbbf49e8200a5aa896a48ee1c0feafa95ce3 | {
"blob_id": "bec8fbbf49e8200a5aa896a48ee1c0feafa95ce3",
"branch_name": "refs/heads/xing",
"committer_date": "2020-01-27T15:47:27",
"content_id": "a9d74be37c038e2e98370f50d112fa24db37b27d",
"detected_licenses": [
"MIT"
],
"directory_id": "546928a445835225f82f68294a3f7cd428d01504",
"extension": "c",
"filename": "typhoeus_multi.c",
"fork_events_count": 8,
"gha_created_at": "2010-12-31T07:32:44",
"gha_event_created_at": "2021-05-27T07:26:07",
"gha_language": "Ruby",
"gha_license_id": "MIT",
"github_id": 1210441,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6964,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/typhoeus/typhoeus_multi.c",
"provenance": "stackv2-0115.json.gz:130127",
"repo_name": "xing/typhoeus",
"revision_date": "2020-01-27T15:47:27",
"revision_id": "d6ed9586ede1628d0b38498370aed5585c45fcb7",
"snapshot_id": "b908efcc2a909ad84f0a345400c36996ea43b4c5",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/xing/typhoeus/d6ed9586ede1628d0b38498370aed5585c45fcb7/ext/typhoeus/typhoeus_multi.c",
"visit_date": "2021-09-03T14:29:07.081384"
} | stackv2 | /* Make sure select() works with >1024 file handles open. */
#include <sys/types.h>
#undef __FD_SETSIZE
#define __FD_SETSIZE 524288
#include <typhoeus_multi.h>
#include <errno.h>
static void multi_read_info(VALUE self, CURLM *multi_handle);
static void dealloc(CurlMulti *curl_multi) {
curl_multi_cleanup(curl_multi->multi);
free(curl_multi);
}
static VALUE multi_add_handle(VALUE self, VALUE easy) {
CurlEasy *curl_easy;
CurlMulti *curl_multi;
CURLMcode mcode;
VALUE easy_handles;
Data_Get_Struct(easy, CurlEasy, curl_easy);
Data_Get_Struct(self, CurlMulti, curl_multi);
mcode = curl_multi_add_handle(curl_multi->multi, curl_easy->curl);
if (mcode != CURLM_CALL_MULTI_PERFORM && mcode != CURLM_OK) {
rb_raise(rb_eRuntimeError, "An error occured adding the handle: %d: %s", mcode, curl_multi_strerror(mcode));
}
curl_easy_setopt(curl_easy->curl, CURLOPT_PRIVATE, easy);
curl_multi->active++;
easy_handles = rb_iv_get(self, "@easy_handles");
rb_ary_push(easy_handles, easy);
if (mcode == CURLM_CALL_MULTI_PERFORM) {
curl_multi_perform(curl_multi->multi, &(curl_multi->running));
}
//
// if (curl_multi->running) {
// printf("call read_info on add<br/>");
// multi_read_info(self, curl_multi->multi);
// }
return easy;
}
static VALUE multi_remove_handle(VALUE self, VALUE easy) {
CurlEasy *curl_easy;
CurlMulti *curl_multi;
VALUE easy_handles;
Data_Get_Struct(easy, CurlEasy, curl_easy);
Data_Get_Struct(self, CurlMulti, curl_multi);
curl_multi->active--;
curl_multi_remove_handle(curl_multi->multi, curl_easy->curl);
easy_handles = rb_iv_get(self, "@easy_handles");
rb_ary_delete(easy_handles, easy);
return easy;
}
static void multi_read_info(VALUE self, CURLM *multi_handle) {
int msgs_left, result;
CURLMsg *msg;
CURLcode ecode;
CURL *easy_handle;
VALUE easy;
long response_code;
/* check for finished easy handles and remove from the multi handle */
while ((msg = curl_multi_info_read(multi_handle, &msgs_left))) {
if (msg->msg != CURLMSG_DONE) {
continue;
}
easy_handle = msg->easy_handle;
result = msg->data.result;
if (easy_handle) {
ecode = curl_easy_getinfo(easy_handle, CURLINFO_PRIVATE, &easy);
if (ecode != 0) {
rb_raise(rb_eRuntimeError, "error getting easy object: %d: %s", ecode, curl_easy_strerror(ecode));
}
response_code = -1;
curl_easy_getinfo(easy_handle, CURLINFO_RESPONSE_CODE, &response_code);
multi_remove_handle(self, easy);
rb_iv_set(easy, "@curl_return_code", INT2FIX(result));
if (result != 0) {
rb_funcall(easy, rb_intern("failure"), 0);
}
else if ((response_code >= 200 && response_code < 300) || response_code == 0) {
rb_funcall(easy, rb_intern("success"), 0);
}
else if (response_code >= 300 && response_code < 600) {
rb_funcall(easy, rb_intern("failure"), 0);
}
}
}
}
/* called by multi_perform and fire_and_forget */
static void rb_curl_multi_run(VALUE self, CURLM *multi_handle, int *still_running) {
CURLMcode mcode;
do {
mcode = curl_multi_perform(multi_handle, still_running);
} while (mcode == CURLM_CALL_MULTI_PERFORM);
if (mcode != CURLM_OK) {
rb_raise(rb_eRuntimeError, "an error occured while running perform: %d: %s", mcode, curl_multi_strerror(mcode));
}
multi_read_info( self, multi_handle );
}
static VALUE fire_and_forget(VALUE self) {
CurlMulti *curl_multi;
Data_Get_Struct(self, CurlMulti, curl_multi);
rb_curl_multi_run( self, curl_multi->multi, &(curl_multi->running) );
return Qnil;
}
#define FD_SET_INIT do { \
rb_fd_init(&fdread); \
rb_fd_init(&fdwrite); \
rb_fd_init(&fdexcep); \
} while (0);
#define FD_SET_ZERO do { \
rb_fd_zero(&fdread); \
rb_fd_zero(&fdwrite); \
rb_fd_zero(&fdexcep); \
} while (0);
#define FD_SET_TERM do { \
rb_fd_term(&fdread); \
rb_fd_term(&fdwrite); \
rb_fd_term(&fdexcep); \
} while (0);
static VALUE multi_perform(VALUE self) {
CURLMcode mcode;
CurlMulti *curl_multi;
int maxfd, rc;
rb_fdset_t fdread, fdwrite, fdexcep;
FD_SET_INIT;
long timeout;
struct timeval tv = {0, 0};
Data_Get_Struct(self, CurlMulti, curl_multi);
rb_curl_multi_run( self, curl_multi->multi, &(curl_multi->running) );
while(curl_multi->running) {
FD_SET_ZERO;
/* get the curl suggested time out */
mcode = curl_multi_timeout(curl_multi->multi, &timeout);
if (mcode != CURLM_OK) {
FD_SET_TERM;
rb_raise(rb_eRuntimeError, "an error occured getting the timeout: %d: %s", mcode, curl_multi_strerror(mcode));
}
if (timeout == 0) { /* no delay */
rb_curl_multi_run( self, curl_multi->multi, &(curl_multi->running) );
continue;
}
else if (timeout < 0) {
timeout = 1;
}
tv.tv_sec = timeout / 1000;
tv.tv_usec = ((int)timeout * 1000) % 1000000;
/* load the fd sets from the multi handle */
mcode = curl_multi_fdset(curl_multi->multi, fdread.fdset, fdwrite.fdset, fdexcep.fdset, &maxfd);
if (mcode != CURLM_OK) {
FD_SET_TERM;
rb_raise(rb_eRuntimeError, "an error occured getting the fdset: %d: %s", mcode, curl_multi_strerror(mcode));
}
rc = rb_thread_fd_select(maxfd+1, &fdread, &fdwrite, &fdexcep, &tv);
if (rc < 0) {
FD_SET_TERM;
rb_raise(rb_eRuntimeError, "error on thread select: %d", errno);
}
rb_curl_multi_run( self, curl_multi->multi, &(curl_multi->running) );
}
FD_SET_TERM;
return Qnil;
}
static VALUE active_handle_count(VALUE self) {
CurlMulti *curl_multi;
Data_Get_Struct(self, CurlMulti, curl_multi);
return INT2FIX(curl_multi->active);
}
static VALUE multi_cleanup(VALUE self) {
CurlMulti *curl_multi;
Data_Get_Struct(self, CurlMulti, curl_multi);
curl_multi_cleanup(curl_multi->multi);
curl_multi->active = 0;
curl_multi->running = 0;
return Qnil;
}
#undef FD_SET_INIT
#undef FD_SET_ZERO
#undef FD_SET_TERM
static VALUE new(int argc, VALUE *argv, VALUE klass ARG_UNUSED) {
CurlMulti *curl_multi = ALLOC(CurlMulti);
VALUE multi;
curl_multi->multi = curl_multi_init();
curl_multi->active = 0;
curl_multi->running = 0;
multi = Data_Wrap_Struct(cTyphoeusMulti, 0, dealloc, curl_multi);
rb_obj_call_init(multi, argc, argv);
return multi;
}
void init_typhoeus_multi() {
VALUE klass = cTyphoeusMulti = rb_define_class_under(mTyphoeus, "Multi", rb_cObject);
rb_define_singleton_method(klass, "new", new, -1);
rb_define_private_method(klass, "multi_add_handle", multi_add_handle, 1);
rb_define_private_method(klass, "multi_remove_handle", multi_remove_handle, 1);
rb_define_private_method(klass, "multi_perform", multi_perform, 0);
rb_define_private_method(klass, "multi_cleanup", multi_cleanup, 0);
rb_define_private_method(klass, "active_handle_count", active_handle_count, 0);
rb_define_method(klass, "fire_and_forget", fire_and_forget, 0);
}
| 2.421875 | 2 |
2024-11-18T22:25:34.940737+00:00 | 2023-02-16T11:27:40 | 993d1b85a8f2039d354b24e1628f1ddcef7d4e18 | {
"blob_id": "993d1b85a8f2039d354b24e1628f1ddcef7d4e18",
"branch_name": "refs/heads/main",
"committer_date": "2023-02-16T14:59:16",
"content_id": "d39a64f46aec2ad71692c8386714b3cf367ad8d5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e8302c75d770d1608b317d6af5c483bbad6c0493",
"extension": "h",
"filename": "rtio_executor_simple.h",
"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": 1876,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/zephyr/rtio/rtio_executor_simple.h",
"provenance": "stackv2-0115.json.gz:130256",
"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/include/zephyr/rtio/rtio_executor_simple.h",
"visit_date": "2023-09-04T00:20:35.217393"
} | stackv2 | /*
* Copyright (c) 2022 Intel Corporation.
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef ZEPHYR_INCLUDE_RTIO_RTIO_EXECUTOR_SIMPLE_H_
#define ZEPHYR_INCLUDE_RTIO_RTIO_EXECUTOR_SIMPLE_H_
#include <zephyr/rtio/rtio.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief RTIO Simple Executor
*
* Provides the simplest possible executor without any concurrency
* or reinterpretation of requests.
*
* @defgroup rtio_executor_simple RTIO Simple Executor
* @ingroup rtio
* @{
*/
/**
* @brief Submit to the simple executor
*
* @param r RTIO context to submit
*
* @retval 0 always succeeds
*/
int rtio_simple_submit(struct rtio *r);
/**
* @brief Report a SQE has completed successfully
*
* @param r RTIO context to use
* @param sqe RTIO SQE to report success
* @param result Result of the SQE
*/
void rtio_simple_ok(struct rtio *r, const struct rtio_sqe *sqe, int result);
/**
* @brief Report a SQE has completed with error
*
* @param r RTIO context to use
* @param sqe RTIO SQE to report success
* @param result Result of the SQE
*/
void rtio_simple_err(struct rtio *r, const struct rtio_sqe *sqe, int result);
/**
* @brief Simple Executor
*/
struct rtio_simple_executor {
struct rtio_executor ctx;
};
/**
* @cond INTERNAL_HIDDEN
*/
static const struct rtio_executor_api z_rtio_simple_api = {
.submit = rtio_simple_submit,
.ok = rtio_simple_ok,
.err = rtio_simple_err
};
/**
* @endcond INTERNAL_HIDDEN
*/
/**
* @brief Define a simple executor with a given name
*
* @param name Symbol name, must be unique in the context in which its used
*/
#define RTIO_EXECUTOR_SIMPLE_DEFINE(name) \
struct rtio_simple_executor name = { .ctx = { .api = &z_rtio_simple_api } };
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_RTIO_RTIO_EXECUTOR_SIMPLE_H_ */
| 2.21875 | 2 |
2024-11-18T22:25:35.019682+00:00 | 2017-10-29T13:21:04 | 4712ea0a0587d4604c800671df6eddc532c249a7 | {
"blob_id": "4712ea0a0587d4604c800671df6eddc532c249a7",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-29T13:21:04",
"content_id": "8a19826895de1fbeed797584ca144b7cc9fb8b1a",
"detected_licenses": [
"MIT"
],
"directory_id": "cbedf7235a4a971cde7959ee74cfb41c46ec0b7b",
"extension": "c",
"filename": "fenceshortbars.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 101375229,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 632,
"license": "MIT",
"license_type": "permissive",
"path": "/opengl/cg_assignment/assignment/fence/fenceshortbars.c",
"provenance": "stackv2-0115.json.gz:130386",
"repo_name": "ah-khalil/Computer-Graphics",
"revision_date": "2017-10-29T13:21:04",
"revision_id": "29a94897fd65ae33e47045c612a54a7ade18d877",
"snapshot_id": "ab9d64a7632fdacf84c7388509897174a6deef74",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ah-khalil/Computer-Graphics/29a94897fd65ae33e47045c612a54a7ade18d877/opengl/cg_assignment/assignment/fence/fenceshortbars.c",
"visit_date": "2021-01-20T03:56:24.333198"
} | stackv2 | #include "fenceshortbars.h"
//function: create_fenceshortbars
//use: creates the fence vertical bars on top of the fence for use in the fence.c file
void create_fenceshortbars() {
GLfloat mat_diffuse[] = { 0.1f, 0.1f, 0.1f, 0.1f };
GLfloat mat_specular[] = { 0.0f, 1.0f, 2.0f, 1.0f };
const GLfloat high_shininess = 0.0f;
GLUquadric* quad = gluNewQuadric();
glEnable(GL_COLOR_MATERIAL);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialf(GL_FRONT, GL_SHININESS, high_shininess);
gluCylinder(quad, 0.1f, 0.1f, 0.5f, 12, 12);
glDisable(GL_COLOR_MATERIAL);
}
| 2.140625 | 2 |
2024-11-18T22:25:38.881280+00:00 | 2017-12-19T17:11:23 | b9eda3b698c84f59c9459dfc1d59a4d1b9581a7c | {
"blob_id": "b9eda3b698c84f59c9459dfc1d59a4d1b9581a7c",
"branch_name": "refs/heads/develop",
"committer_date": "2017-12-19T17:11:23",
"content_id": "e5ed0d0bc218854cb204b9fd0c6578958683a3d3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4c92dfa45076ba45250ed558c3580cb90040d6a8",
"extension": "c",
"filename": "triggers.c",
"fork_events_count": 1,
"gha_created_at": "2015-03-13T19:40:08",
"gha_event_created_at": "2016-12-14T15:08:00",
"gha_language": "C",
"gha_license_id": null,
"github_id": 32176956,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4444,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/generate/triggers.c",
"provenance": "stackv2-0115.json.gz:131164",
"repo_name": "bbcarchdev/spindle",
"revision_date": "2017-12-19T17:11:23",
"revision_id": "8c34e28f88f73e5fe1f1433f03901c9a4d80bc81",
"snapshot_id": "bcc99d6e1f6b34bc231f69d8e133def781813795",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/bbcarchdev/spindle/8c34e28f88f73e5fe1f1433f03901c9a4d80bc81/generate/triggers.c",
"visit_date": "2020-04-04T03:54:11.751211"
} | stackv2 | /* Spindle: Co-reference aggregation engine
*
* Author: Mo McRoberts <mo.mcroberts@bbc.co.uk>
*
* Copyright (c) 2014-2017 BBC
*
* 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.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "p_spindle-generate.h"
/* Add a trigger URI */
int
spindle_trigger_add(SPINDLEENTRY *cache, const char *uri, unsigned int kind, const char *id)
{
size_t c;
struct spindle_trigger_struct *p;
for(c = 0; c < cache->ntriggers; c++)
{
if(!strcmp(cache->triggers[c].uri, uri))
{
cache->triggers[c].kind |= kind;
if(!cache->triggers[c].id && id)
{
cache->triggers[c].id = strdup(id);
}
return 0;
}
}
p = (struct spindle_trigger_struct *) realloc(cache->triggers, (cache->ntriggers + 1) * (sizeof(struct spindle_trigger_struct)));
if(!p)
{
return -1;
}
cache->triggers = p;
p = &(cache->triggers[cache->ntriggers]);
memset(p, 0, sizeof(struct spindle_trigger_struct));
p->uri = strdup(uri);
if(!p->uri)
{
return -1;
}
if(id)
{
p->id = strdup(id);
if(!p->id)
{
free(p->uri);
return -1;
}
}
p->kind = kind;
cache->ntriggers++;
return 0;
}
int
spindle_trigger_apply(SPINDLEENTRY *entry)
{
SQL_STATEMENT *rs;
int flags;
const char *id;
if(!entry->generate->db)
{
return 0;
}
rs = sql_queryf(entry->generate->db, "SELECT \"id\", \"flags\", \"triggerid\" FROM \"triggers\" WHERE \"triggerid\" = %Q AND \"triggerid\" <> \"id\"", entry->id);
if(!rs)
{
return -1;
}
for(; !sql_stmt_eof(rs); sql_stmt_next(rs))
{
// Get the id of the target
id = sql_stmt_str(rs, 0);
// Get the flags to apply
flags = (int) sql_stmt_long(rs, 1);
/* Trigger updates that have this entry's flag in scope */
if (entry->flags & flags)
{
// Do a logical OR if there is already a trigger scheduled (status = DIRTY and flags <> 0)
sql_executef(entry->generate->db, "UPDATE \"state\" SET \"flags\" = \"flags\" | %d WHERE \"id\" = %Q AND \"flags\" <> 0 AND \"status\" = 'DIRTY'", flags, id);
// Set the flag in case we set a previously completed or rejected resource (status != DIRTY)
sql_executef(entry->generate->db, "UPDATE \"state\" SET \"flags\" = %d WHERE \"id\" = %Q AND \"status\" <> 'DIRTY'", flags, id);
// Set the target as DIRTY
sql_executef(entry->generate->db, "UPDATE \"state\" SET \"status\" = %Q WHERE \"id\" = %Q", "DIRTY", id);
}
}
sql_stmt_destroy(rs);
return 0;
}
/* Update any triggers which have one of our URIs */
int
spindle_triggers_update(SPINDLEENTRY *data)
{
size_t c;
if(!data->generate->spindle->db)
{
return 0;
}
if(sql_executef(data->generate->spindle->db, "UPDATE \"triggers\" SET \"triggerid\" = %Q WHERE \"uri\" = %Q",
data->id, data->localname))
{
return -1;
}
for(c = 0; c < data->refcount; c++)
{
if(sql_executef(data->generate->spindle->db, "UPDATE \"triggers\" SET \"triggerid\" = %Q WHERE \"uri\" = %Q",
data->id, data->refs[c]))
{
return -1;
}
}
return 0;
}
/* Add the set of trigger URIs to the database
* Checks the trigger doesnt already exist to prevent trigger loop.
* Adds an entry to triggers for id, uri, flags, triggerid
* args:
* sql - libsql handle
* id
* data - Spindle Entry
* Returns:
* 0 on success
* -1 on failure
*/
int
spindle_triggers_index(SQL *sql, const char *id, SPINDLEENTRY *data)
{
size_t c;
SQL_STATEMENT *rs;
for(c = 0; c < data->ntriggers; c++)
{
// Check if we are about to create a loop
rs = sql_queryf(sql, "SELECT \"id\" FROM \"triggers\" WHERE \"id\" = %Q AND \"triggerid\" = %Q", data->triggers[c].id, id);
if(!rs)
{
return -1;
}
if(sql_stmt_eof(rs)) {
if(sql_executef(sql, "INSERT INTO \"triggers\" (\"id\", \"uri\", \"flags\", \"triggerid\") VALUES (%Q, %Q, '%d', %Q)",
id, data->triggers[c].uri, data->triggers[c].kind, data->triggers[c].id))
{
sql_stmt_destroy(rs);
return -1;
}
}
sql_stmt_destroy(rs);
}
return 0;
}
| 2.296875 | 2 |
2024-11-18T22:25:39.319022+00:00 | 2021-06-18T17:13:37 | 88771541e890e442ca1e649100c85f2d7ad8df83 | {
"blob_id": "88771541e890e442ca1e649100c85f2d7ad8df83",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-18T17:13:37",
"content_id": "0ec038d6f31f432c77f95de0208f84b2e8d50e3b",
"detected_licenses": [
"MIT"
],
"directory_id": "6c90e781993fe0447d20aab166445e8ec3b49e70",
"extension": "c",
"filename": "two.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 302421625,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 753,
"license": "MIT",
"license_type": "permissive",
"path": "/pointers/two.c",
"provenance": "stackv2-0115.json.gz:131553",
"repo_name": "devalmagno/codigosEmC",
"revision_date": "2021-06-18T17:13:37",
"revision_id": "6088192997afdc27fe936f6a1720ac0deaecbae4",
"snapshot_id": "7dc6a510b628477cdbaac74f40b9771a1cc87127",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/devalmagno/codigosEmC/6088192997afdc27fe936f6a1720ac0deaecbae4/pointers/two.c",
"visit_date": "2023-05-24T14:34:51.270513"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
// 2) Escreva um programa que contenha duas variáveis inteiras. Leia essas variáveis do teclado. Em seguida, compare seus endereços e exiba o conteúdo do maior endereço.
int main() {
system("cls");
int var1, var2;
int *p1, *p2;
printf(">>> POINTEIROS\n\n");
printf("Digite o valor de var1: \t");
scanf("%d", &var1);
printf("Digite o valor de var2: \t");
scanf("%d", &var2);
p1 = &var1;
p2 = &var2;
printf("\n\nEndereco var1: %d \t | \t Endereco de var2: %d\n\n", p1, p2);
printf("O conteudo da variavel de maior endereco e: \t");
if (p1 > p2) {
printf("%d VAR1", var1);
} else {
printf("%d VAR2", var2);
}
return 0;
} | 3.9375 | 4 |
2024-11-18T22:25:39.388741+00:00 | 2016-10-10T23:38:11 | 0b4683e5205726eeb0b6086679cd4f6572a67279 | {
"blob_id": "0b4683e5205726eeb0b6086679cd4f6572a67279",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-10T23:38:11",
"content_id": "c878f06fda25791f289ba2a7a81d3ebb3a64f8cc",
"detected_licenses": [
"MIT"
],
"directory_id": "8808aa4b2feaa1033941d3ecf669ae46d14c8a43",
"extension": "c",
"filename": "stomp_proto_unsubscribe.c",
"fork_events_count": 7,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 54813508,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1069,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lib/stomp_proto_unsubscribe.c",
"provenance": "stackv2-0115.json.gz:131683",
"repo_name": "newtmq/newtmq-server",
"revision_date": "2016-10-10T23:38:11",
"revision_id": "11799ffbf89f87146ff81956deebc727c6403665",
"snapshot_id": "7dd08aeab543a7e8892aee4941405a3f47ebc11e",
"src_encoding": "UTF-8",
"star_events_count": 21,
"url": "https://raw.githubusercontent.com/newtmq/newtmq-server/11799ffbf89f87146ff81956deebc727c6403665/src/lib/stomp_proto_unsubscribe.c",
"visit_date": "2021-06-06T06:00:07.620329"
} | stackv2 | #include <newt/common.h>
#include <newt/stomp_management_worker.h>
#include <newt/frame.h>
#include <assert.h>
struct attrinfo_t {
char *id;
};
static int handler_id(char *context, void *data, linedata_t *_hdr) {
struct attrinfo_t *attrinfo = (struct attrinfo_t *)data;
int ret = RET_ERROR;
if(attrinfo != NULL) {
attrinfo->id = context;
ret = RET_SUCCESS;
}
return ret;
}
static stomp_header_handler_t handlers[] = {
{"id:", handler_id},
{0},
};
frame_t *handler_stomp_unsubscribe(frame_t *frame) {
struct attrinfo_t attrinfo = {0};
assert(frame != NULL);
assert(frame->cinfo != NULL);
if(iterate_header(&frame->h_attrs, handlers, &attrinfo) == RET_ERROR) {
err("(handle_stomp_unsubscribe) validation error");
stomp_send_error(frame->sock, "failed to validate header\n");
return NULL;
}
if(attrinfo.id != NULL) {
subscribe_t *sub_info = get_subscriber(attrinfo.id);
if(sub_info != NULL) {
pthread_cancel(sub_info->thread_id);
}
unregister_subscriber(attrinfo.id);
}
return NULL;
}
| 2.25 | 2 |
2024-11-18T22:25:39.632319+00:00 | 2021-03-22T05:11:55 | bf888c0d5c4ff294120e628a295a8b5bf5eea68f | {
"blob_id": "bf888c0d5c4ff294120e628a295a8b5bf5eea68f",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-22T05:11:55",
"content_id": "ef59b1c4300610c1a61e7ee50cfdc847263394ed",
"detected_licenses": [
"MIT"
],
"directory_id": "1a40d1a3835d9d556ea844d44494e7f2345697c9",
"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": 346951520,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1907,
"license": "MIT",
"license_type": "permissive",
"path": "/example/example.c",
"provenance": "stackv2-0115.json.gz:132075",
"repo_name": "memoryhole/libkiss",
"revision_date": "2021-03-22T05:11:55",
"revision_id": "cce60de8d0c1aac63b5ebb83ad819c6b70a63d30",
"snapshot_id": "ec538f98ce19e3057baa8d5e7b87725c36265f12",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/memoryhole/libkiss/cce60de8d0c1aac63b5ebb83ad819c6b70a63d30/example/example.c",
"visit_date": "2023-03-24T07:59:53.860935"
} | stackv2 | #include <stdint.h>
#include <stdio.h>
#include <assert.h>
#include "libkiss.h"
void print_frame(struct kiss_frame* frame) {
printf("Frame command=%d port=%d data=", frame->command.details.command, frame->command.details.port);
for (uint16_t i = 0; i < frame->data_size; i++) {
printf("%02x ", frame->data[i]);
}
printf("\n");
}
int main(int argc, char* argv[]) {
(void)argc;
(void)argv;
struct kiss_frame frame;
// Parse in a single pass
printf("SINGLE PASS\n");
uint8_t data1[] = {FEND, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, FEND};
uint16_t data1_size = sizeof(data1) / sizeof(uint8_t);
kiss_init(&frame);
assert(DONE == kiss_parse(&frame, data1, data1_size));
print_frame(&frame);
// Parse in multiple passes (useful if reading partial data from a socket or file)
// CONTINUE means that the buffer was consumed and no frame was parsed yet
// DONE means a frame is parsed and the buffer can be re-used
// DONE_HAS_MORE means a frame has been parsed, but there is remaining data in the buffer that needs to be fed. Keep calling until the state is DONE or CONTINUE.
printf("\nMULTIPLE PASSES\n");
uint8_t data2[] = {FEND, 0x00, 0x01, FEND, FEND, 0x00, 0x02, 0x03, 0x04, 0x05, 0x06, FEND};
uint16_t data_size = sizeof(data2) / sizeof(uint8_t);
kiss_init(&frame);
enum kiss_parse_state state = CONTINUE;
for (int i = i; i < data_size; i += 3) {
state = kiss_parse(&frame, data2 + i, 3);
if (DONE == state) {
print_frame(&frame);
} else if (DONE_HAS_MORE == state) {
print_frame(&frame);
while(DONE_HAS_MORE == (state = kiss_parse(&frame, data2 + i, 3))) {
print_frame(&frame);
}
if (DONE == state) {
print_frame(&frame);
}
}
}
return 0;
}
| 3 | 3 |
2024-11-18T22:25:39.688981+00:00 | 2021-03-12T18:39:12 | b6d85e9712d1d4dff466d609a758a9f0385886ef | {
"blob_id": "b6d85e9712d1d4dff466d609a758a9f0385886ef",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-12T18:39:12",
"content_id": "12cc95a36254d678e8b482f5b6fe26d0b04ab5b8",
"detected_licenses": [
"Zlib"
],
"directory_id": "5cba7c9a9deb0aaf20fea1649b76532e2b0314e1",
"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": 344546592,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2266,
"license": "Zlib",
"license_type": "permissive",
"path": "/src/util.c",
"provenance": "stackv2-0115.json.gz:132205",
"repo_name": "MobSlicer152/frankentar",
"revision_date": "2021-03-12T18:39:12",
"revision_id": "51a731fec1063ae6524f695e015599abe78a2f98",
"snapshot_id": "60983a204bfdcb3e97cecea27878d1fcb7c78427",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MobSlicer152/frankentar/51a731fec1063ae6524f695e015599abe78a2f98/src/util.c",
"visit_date": "2023-03-13T16:14:57.130985"
} | stackv2 | #define STB_SPRINTF_IMPLEMENTATION
#include "frankentar/util.h"
#ifdef __cplusplus
extern "C" {
#endif
char *ftar_fmt_text_va(size_t *len_ret, const char *fmt, va_list args)
{
size_t len;
char *buf;
va_list ap;
errno = 0;
/* Check our parameters */
if (!len_ret || !fmt || !args) {
errno = EINVAL;
return fmt;
}
/* Copy the arglist */
va_copy(ap, args);
/* Determine how large the buffer has to be */
len = stbsp_vsnprintf(NULL, 0, fmt, args) + 1;
if (!len) {
errno = E2BIG;
len = 512;
}
/* Now we know how big the buffer will be */
buf = calloc(len, sizeof(char));
if (!buf) {
errno = ENOMEM;
len = -1;
return fmt;
}
/* Now put the string in the buffer and return */
stbsp_vsnprintf(buf, len, fmt, ap);
if (!buf) {
errno = E2BIG;
len = -1;
return fmt;
}
*len_ret = len;
errno = 0;
return buf;
}
char *ftar_fmt_text(size_t *len_ret, const char *fmt, ...)
{
va_list args;
char *fmt_ptr;
errno = 0;
/* Check everything */
if (!len_ret || !fmt) {
errno = EINVAL;
return fmt;
}
va_start(args, fmt);
fmt_ptr = ftar_fmt_text_va(len_ret, fmt, args);
va_end(args);
errno = 0;
return fmt_ptr;
}
void
#ifdef _MSC_VER
__declspec(noreturn)
#else
__attribute__((noreturn))
#endif
ftar_err_exit(int code, const char *msg, ...)
{
va_list args;
char *fmt;
size_t len;
/* Check args */
if (!msg)
fmt = ftar_fmt_text(&len, "Unknown error occured\n");
/* Format the message */
va_start(args, msg);
fmt = ftar_fmt_text_va(&len, msg, args);
va_end(args);
/* Print it out */
fprintf(stderr, "%s", fmt);
/* Now exit */
exit(code);
}
bool ftar_get_y_or_n(const char *message, ...)
{
bool res;
char *resp;
char *msg;
va_list args;
size_t len;
errno = 0;
/* Check our argument */
if (!message) {
errno = EINVAL;
return false;
}
/* Format the message */
va_start(args, message);
msg = ftar_fmt_text_va(&len, message, args);
va_end(args);
/* Allocate a buffer for the response */
resp = calloc(4, sizeof(char));
if (!resp)
return false;
/* Read the response */
printf("%s", msg);
errno = 0;
scanf("%3s", resp);
if (errno)
return false;
/* Check the response */
res = (*resp == 'y' || *resp == 'Y');
errno = 0;
return res;
}
#ifdef __cplusplus
}
#endif
| 2.53125 | 3 |
2024-11-18T22:25:39.768383+00:00 | 2011-12-09T16:09:34 | d9c60225a804ddb9268ac3722609edc5d21bf618 | {
"blob_id": "d9c60225a804ddb9268ac3722609edc5d21bf618",
"branch_name": "refs/heads/master",
"committer_date": "2011-12-09T16:09:34",
"content_id": "ecae4073f79b4549668b9939f9f280aebd84f466",
"detected_licenses": [
"MIT"
],
"directory_id": "9d0faa470fce9d9ab6b5a5c1919bee1235a40234",
"extension": "c",
"filename": "uva469.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2307870,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2726,
"license": "MIT",
"license_type": "permissive",
"path": "/graph_traversal/uva469/uva469.c",
"provenance": "stackv2-0115.json.gz:132335",
"repo_name": "yanhan/cs2010",
"revision_date": "2011-12-09T16:09:34",
"revision_id": "cec23ac5cf68af2e2c17f6f4241a6cc63c8480eb",
"snapshot_id": "565919e6e66e0e5673fb266b4b1f83d3bc6a079b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/yanhan/cs2010/cec23ac5cf68af2e2c17f6f4241a6cc63c8480eb/graph_traversal/uva469/uva469.c",
"visit_date": "2016-09-06T11:07:45.680382"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSZ 4096
#define MAXROWS 99
#define IMPOS_SZ 2000000
#define DIRS 8
#define WATER 'W'
#define VISITED 'D'
/*#define PRINT_DEBUG*/
struct pt {
int row;
int col;
};
struct pt queue[IMPOS_SZ];
int qhead, qtail;
int rows, cols;
char land[MAXROWS + 4][MAXROWS + 4];
/* N, NE, E, SE, S, SW, W, NW */
int d_row[DIRS] = {-1, -1, 0, 1, 1, 1, 0, -1};
int d_col[DIRS] = { 0, 1, 1, 1, 0, -1, -1, -1};
void restore_lands()
{
int i, k;
for (i = 0; i < rows; i++) {
for (k = 0; k < cols; k++) {
if (land[i][k] == VISITED)
land[i][k] = WATER;
}
}
}
int floodfill(int r, int c)
{
int i, k, m;
int curRow, curCol;
int nRow, nCol;
int wetlands = 0;
memset(queue, 0, sizeof(queue));
qhead = qtail = 0;
queue[qtail].row = r;
queue[qtail].col = c;
qtail++;
while (qhead < qtail) {
curRow = queue[qhead].row;
curCol = queue[qhead].col;
qhead++;
if (land[curRow][curCol] != WATER)
continue;
land[curRow][curCol] = VISITED;
++wetlands;
for (i = 0; i < DIRS; i++) {
nRow = curRow + d_row[i];
nCol = curCol + d_col[i];
if (nRow < 0 || nRow >= rows || nCol < 0 || nCol >= cols)
continue;
if (land[nRow][nCol] != WATER)
continue;
queue[qtail].row = nRow;
queue[qtail].col = nCol;
qtail++;
}
}
/* Change back */
restore_lands();
return wetlands;
}
int main(int argc, char *argv[])
{
int i, k, m;
int wetlands;
int numCases;
char buf[BUFSZ];
rows = cols = numCases = 0;
gets(buf);
sscanf(buf, "%d", &numCases);
/* Blank line */
gets(buf);
if (strcmp(buf, "")) {
fprintf(stderr, "Not blank line!\n");
exit(1);
}
for (i = 0; i < numCases; i++) {
rows = 0;
memset(land, 0, sizeof(land));
while (1) {
gets(land[rows]);
if (land[rows][0] != 'L' && land[rows][0] != 'W')
break;
rows++;
}
cols = strlen(land[0]);
#ifdef PRINT_DEBUG
for (k = 0; k < rows; k++) {
for (m = 0; m < cols; m++) {
putchar(land[k][m]);
}
putchar('\n');
}
#endif
k = m = 0;
/* first of the k lines was stored in the last land buffer */
sscanf(land[rows], "%d %d", &k, &m);
#ifdef PRINT_DEBUG
printf("i = %d, j = %d\n", k, m);
#endif
if (i > 0)
putchar('\n');
/* Change to 0 based from 1 based */
wetlands = floodfill(k - 1, m - 1);
printf("%d\n", wetlands);
while (1) {
if (!gets(buf))
goto done;
else if (!strcmp(buf, ""))
break;
sscanf(buf, "%d %d", &k, &m);
#ifdef PRINT_DEBUG
printf("i = %d, j = %d\n", k, m);
#endif
/*
* Flood fill time
* Change to 0 based from 1 based
*/
wetlands = floodfill(k - 1, m - 1);
printf("%d\n", wetlands);
}
}
done:
return 0;
}
| 2.640625 | 3 |
2024-11-18T22:25:40.268152+00:00 | 2020-07-29T00:41:06 | 2e89e4182152933b69a4d73aea422f4617f1e69a | {
"blob_id": "2e89e4182152933b69a4d73aea422f4617f1e69a",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-29T00:41:06",
"content_id": "73793e501da503fccc714d10e4383247676eeef4",
"detected_licenses": [
"BSD-3-Clause",
"MIT"
],
"directory_id": "545aaa434c52dab32749858771ec64aea933d1ce",
"extension": "c",
"filename": "qt.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": 3441,
"license": "BSD-3-Clause,MIT",
"license_type": "permissive",
"path": "/testing/qt.c",
"provenance": "stackv2-0115.json.gz:132984",
"repo_name": "Wjt1127/twizzler-1",
"revision_date": "2020-07-29T00:41:06",
"revision_id": "a73bdde1ddab66be12bee7f4222fdd836e2b0d54",
"snapshot_id": "68b4b0928c96d9005e1c1b66effe10d7e51628cf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Wjt1127/twizzler-1/a73bdde1ddab66be12bee7f4222fdd836e2b0d54/testing/qt.c",
"visit_date": "2023-06-13T04:51:47.094019"
} | stackv2 | #include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"
#include <linux/futex.h>
#include <stdatomic.h>
#include <sys/syscall.h>
#include <unistd.h>
//#define PR printf
#define PR(...)
struct queue_hdr *create_q(size_t len)
{
struct queue_hdr *hdr = malloc(sizeof(*hdr));
memset(hdr, 0, sizeof(*hdr));
hdr->subqueue[0].length = len;
hdr->subqueue[1].length = len;
hdr->subqueue[0].stride = 8;
hdr->subqueue[1].stride = 8;
hdr->subqueue[0].queue = calloc(len, 8);
hdr->subqueue[1].queue = calloc(len, 8);
return hdr;
}
#define QUEUE_NONBLOCK 1
int queue_submit(struct queue_hdr *hdr, struct queue_entry *qe, int flags)
{
return queue_sub_enqueue(hdr, SUBQUEUE_SUBM, qe, !!(flags & QUEUE_NONBLOCK));
}
int queue_complete(struct queue_hdr *hdr, struct queue_entry *qe, int flags)
{
return queue_sub_enqueue(hdr, SUBQUEUE_CMPL, qe, !!(flags & QUEUE_NONBLOCK));
}
int N = 3;
_Atomic int done = 0;
int icount = 100000;
void *prod(void *a)
{
static _Atomic int __id = 0;
int id = ++__id;
struct queue_hdr *hdr = a;
unsigned x = 0;
for(x = 0; x < icount; x++) {
PR("%d: enqueue %d\n", id, x);
// for(volatile long i = 0; i < 4000; i++)
// ;
// usleep(1);
struct queue_entry e;
e.info = x * N + (id - 1);
if(queue_sub_enqueue(hdr, SUBQUEUE_SUBM, &e, 0) < 0)
abort();
}
done++;
return NULL;
}
size_t nrb = 0x100000;
char *bm;
unsigned max = 0;
void *cons(void *a)
{
struct queue_hdr *hdr = a;
while(1) {
struct queue_entry e;
if(queue_sub_dequeue(hdr, SUBQUEUE_SUBM, &e, done == N) < 0) {
if(done == N)
break;
abort();
}
if(done == N && e.info == 0)
break;
if(e.info > max)
max = e.info;
if(e.info >= nrb)
abort();
bm[e.info / 8] |= (1 << (e.info % 8));
PR(" GOT %d\n", e.info);
}
}
#include <time.h>
void timespec_diff(struct timespec *start, struct timespec *stop, struct timespec *result)
{
if((stop->tv_nsec - start->tv_nsec) < 0) {
result->tv_sec = stop->tv_sec - start->tv_sec - 1;
result->tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000ul;
} else {
result->tv_sec = stop->tv_sec - start->tv_sec;
result->tv_nsec = stop->tv_nsec - start->tv_nsec;
}
return;
}
int main()
{
struct queue_hdr *hdr = create_q(32);
bm = malloc(nrb / 8);
memset(bm, 0, nrb / 8);
struct timespec start, end, diff;
clock_gettime(CLOCK_MONOTONIC, &start);
pthread_t threads[N];
for(int i = 0; i < N; i++) {
pthread_create(&threads[i], NULL, prod, hdr);
}
cons(hdr);
for(int i = 0; i < N; i++) {
pthread_join(threads[i], NULL);
}
clock_gettime(CLOCK_MONOTONIC, &end);
timespec_diff(&start, &end, &diff);
uint64_t ns = diff.tv_nsec + diff.tv_sec * 1000000000ul;
printf("time %d threads %d max %d inserted/th %ld ns ( %4.4lf seconds )\n",
N,
max + 1,
icount,
ns,
(double)ns / 1000000000);
printf("futex-enqueue-total: %9ld\n", calls_to_futex);
printf("futex-enqueue-sleep: %9ld\n", ctf_sleeps);
printf("futex-enqueue-wakes: %9ld\n", ctf_wakes);
printf("futex-dequeue-total: %9ld\n", dqcalls_to_futex);
printf("futex-dequeue-sleep: %9ld\n", dqctf_sleeps);
printf("futex-dequeue-wakes: %9ld\n", dqctf_wakes);
int ret = 0;
fprintf(stderr, "DONE :: REPORT\n");
for(unsigned i = 0; i <= max; i++) {
if((bm[i / 8] & (1 << (i % 8))) == 0) {
fprintf(stderr, "missing entry %d\n", i);
ret = 1;
}
}
return ret;
}
| 2.609375 | 3 |
2024-11-18T22:25:40.575764+00:00 | 2019-06-04T16:35:50 | fd11ba006057e3ddd6691fd8f73aed5448ae7915 | {
"blob_id": "fd11ba006057e3ddd6691fd8f73aed5448ae7915",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-04T16:35:50",
"content_id": "42d8368ba44238646acdd2e712c82944d4231ca4",
"detected_licenses": [
"Apache-2.0",
"BSD-2-Clause"
],
"directory_id": "a16ce229d246581218833bdbbc04c1bd5ecb77df",
"extension": "c",
"filename": "IndexLinear.c",
"fork_events_count": 0,
"gha_created_at": "2019-06-04T16:34:26",
"gha_event_created_at": "2019-06-04T16:34:27",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 190241068,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 25192,
"license": "Apache-2.0,BSD-2-Clause",
"license_type": "permissive",
"path": "/contrib/lua-torch/nn/lib/THNN/generic/IndexLinear.c",
"provenance": "stackv2-0115.json.gz:133243",
"repo_name": "gollux/rspamd",
"revision_date": "2019-06-04T16:35:50",
"revision_id": "e68ea4ea38376ba0eedf36578c3499159e675c90",
"snapshot_id": "389c4abbb3356aa6958725020a76229856ba8b77",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gollux/rspamd/e68ea4ea38376ba0eedf36578c3499159e675c90/contrib/lua-torch/nn/lib/THNN/generic/IndexLinear.c",
"visit_date": "2020-05-31T10:26:38.138917"
} | stackv2 | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/IndexLinear.c"
#else
#ifdef _OPENMP
#include <omp.h>
#endif
/* Threshold used to trigger multithreading */
#ifndef THNN_SPARSE_OMP_THRESHOLD
#define THNN_SPARSE_OMP_THRESHOLD 100000
#endif
/* Threshold used to trigger BLAS axpy call */
#ifndef THNN_SPARSE_OUTDIM_THRESHOLD
#define THNN_SPARSE_OUTDIM_THRESHOLD 49
#endif
/* sign MACRO */
#ifndef THNN_INDEXLINEAR_SIGN
#define THNN_INDEXLINEAR_SIGN(a) ( ( (a) < 0 ) ? -1 : ( (a) > 0 ) )
#endif
static bool THNN_(checkKeysValues)(THLongTensor* keys, THTensor* values)
{
return THLongTensor_size(keys, 0) == THTensor_(nElement)(values)
&& THTensor_(nDimension)(values) == 1
&& THLongTensor_nDimension(keys) == 1;
}
void THNN_(IndexLinear_updateOutput)(
THNNState *state,
THLongTensor *keys,
long keysOffset,
THTensor *values,
THLongTensor *sizes,
THLongTensor *cumSumSizes,
THTensor *output,
THTensor *weight,
THTensor *bias,
THTensor *normalizedValues,
int train)
{
/* Retrieve all the dimensions of the problem */
long batchSize = THLongTensor_size(sizes, 0);
long keysSize = THLongTensor_size(keys, 0);
long outDim = THTensor_(size)(bias, 0);
long woutDim = THTensor_(size)(weight, 1);
int maxNormalize = woutDim - outDim;
long* sizesData = THLongTensor_data(sizes);
long* cumSumSizesData = THLongTensor_data(cumSumSizes);
/* Define/resize the normalized values tensor if maxNormalize is > 0 */
real* normalizedValuesData = NULL;
if (maxNormalize)
{
THTensor_(resize1d)(normalizedValues, keysSize);
normalizedValuesData = THTensor_(data)(normalizedValues);
}
/* Resize the output */
THTensor_(resize2d)(output, batchSize, outDim);
/* Access the storage data/strides */
real* outputData = THTensor_(data)(output);
real* valuesData = THTensor_(data)(values);
real* weightData = THTensor_(data)(weight);
long weightStride0 = weight->stride[0];
real* biasData = THTensor_(data)(bias);
long* keysData = THLongTensor_data(keys);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THLongTensor_isContiguous(keys), 1, "keys vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(values), 3, "values vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(output), 6, "output vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 7, "weight matrix must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 8, "bias vector must be contiguous");
THArgCheck(THNN_(checkKeysValues)(keys, values), 1, "Keys and values should have the same number of elements");
THArgCheck(THTensor_(isContiguous)(normalizedValues), 9, "normalizedValues vector must be contiguous");
long i,j,k;
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations. */
if (outDim == 1)
{
THVector_(fill)(outputData, *biasData, batchSize);
if (maxNormalize)
{
/* Parallelize on the batch itself */
#pragma omp parallel \
for private(i,j) \
firstprivate(outDim, keysOffset, \
weightData, keysData, \
valuesData, outputData, \
cumSumSizesData, sizesData) \
schedule(static) \
if(keysSize*outDim > THNN_SPARSE_OMP_THRESHOLD && batchSize > 1)
for (j = 0; j < batchSize; j++)
{
real* loutputData = outputData + j;
real val = 0;
real absVal = 0;
long offset = j == 0 ? 0 : cumSumSizesData[j - 1];
for (i = 0; i < sizesData[j]; i++)
{
long woffset = weightStride0*(keysData[offset] + keysOffset);
absVal = fabs(valuesData[offset]);
if (train)
{
if (absVal > weightData[woffset])
{
weightData[woffset] = absVal;
weightData[woffset+1] = 1/absVal;
}
/*
* The following can be used to scale the size of the updates
* depending on some rule, e.g. the frequency of a feature, ...
* This is used at update time.
* TODO: implement a smarter update scale.
*/
weightData[woffset+2] = 1;
}
normalizedValuesData[offset] = (absVal > weightData[woffset] ? THNN_INDEXLINEAR_SIGN(valuesData[offset]):valuesData[offset]*weightData[woffset+1]) + weightData[woffset+3];
val += normalizedValuesData[offset] * weightData[woffset+maxNormalize];
offset++;
}
*loutputData += val;
}
}
else
{
/* Parallelize on the batch itself */
#pragma omp parallel \
for private(i,j) \
firstprivate(outDim, weightData, \
keysData, valuesData, \
outputData, cumSumSizesData, \
sizesData) \
schedule(static) \
if(keysSize*outDim > THNN_SPARSE_OMP_THRESHOLD && batchSize > 1)
for (j = 0; j < batchSize; j++)
{
long offset = j == 0 ? 0 : cumSumSizesData[j - 1];
real* loutputData = outputData + j;
real val = 0;
for (i = 0; i < sizesData[j]; i++)
{
val += weightData[weightStride0*(keysData[offset] + keysOffset)] * valuesData[offset];
offset++;
}
*loutputData += val;
}
}
}
else {
#pragma omp parallel \
for private(i,j,k) \
firstprivate(outDim, weightData, \
keysData, valuesData, \
biasData, outputData, \
cumSumSizesData, sizesData) \
schedule(static) \
if(keysSize*outDim > THNN_SPARSE_OMP_THRESHOLD && batchSize > 1)
for (j = 0; j < batchSize; j++)
{
long offset = j == 0 ? 0 : cumSumSizesData[j - 1];
real val = 0;
real* loutputData = outputData + j*outDim;
real* lweightData = weightData;
memcpy(loutputData, biasData, outDim*sizeof(real));
for (i = 0; i < sizesData[j]; i++)
{
real val;
long woffset = weightStride0*(keysData[offset] + keysOffset);
if (maxNormalize)
{
val = valuesData[offset];
real absVal = fabs(val);
if (train)
{
if (absVal > weightData[woffset])
{
weightData[woffset] = absVal;
weightData[woffset+1] = 1/absVal;
}
/*
* The following can be used to scale the size of the updates
* depending on some rule, e.g. the frequency of a feature, ...
* The commented section thereafter is just an example of what can be done:
*
*```
* weightData[woffset+2] = weightData[woffset+2]==0?1:(weightData[woffset+2] / (weightData[woffset+2] + 1));
* real alpha = 1;
* real beta = 0.01;
* real gamma = 1 - 0.000001;
* real l = weightData[woffset+2]==0?1/gamma:(weightData[woffset+2] - beta) / (alpha - beta);
* l = gamma*l;
* weightData[woffset+2] = (alpha-beta)*l + beta;
* ```
*
* TODO: implement a smarter update scale.
*/
weightData[woffset+2] = 1;
}
/* Normalize + Clamp */
val = (absVal > weightData[woffset] ? THNN_INDEXLINEAR_SIGN(val):val*weightData[woffset+1]) + weightData[woffset+3];
normalizedValuesData[offset] = val;
lweightData = weightData + woffset + maxNormalize;
}
else
{
val = valuesData[offset];
lweightData = weightData + woffset;
}
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, val, lweightData, 1, loutputData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
loutputData[k] += lweightData[k] * val;
}
}
offset++;
}
}
}
return;
}
void THNN_(IndexLinear_updateParameters)(
THNNState *state,
THTensor *gradWeight,
THTensor *gradBias,
THTensor *weight,
THTensor *bias,
THLongTensor *runningKeys,
THLongTensor *cumSumSizes,
long keysOffset,
accreal weightDecay_,
accreal learningRate_)
{
real weightDecay = TH_CONVERT_ACCREAL_TO_REAL(weightDecay_);
real learningRate = TH_CONVERT_ACCREAL_TO_REAL(learningRate_);
/* Retrieve all the dimensions of the problem */
long outDim = THTensor_(size)(bias, 0);
long woutDim = THTensor_(size)(weight, 1);
int maxNormalize = woutDim - outDim;
long keysSize = THLongTensor_size(runningKeys, 0);
/* Access the storage data/strides */
real* gradWeightData = THTensor_(data)(gradWeight);
real* weightData = THTensor_(data)(weight);
long weightStride0 = weight->stride[0];
real* gradBiasData = THTensor_(data)(gradBias);
real* biasData = THTensor_(data)(bias);
long* keysData = THLongTensor_data(runningKeys);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THTensor_(isContiguous)(gradWeight), 1, "gradWeight must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradBias), 2, "gradBias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 3, "gradBias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 4, "gradBias vector must be contiguous");
THArgCheck(THLongTensor_isContiguous(runningKeys), 5, "keys vector must be contiguous");
int j,k;
long offset = 0;
/* Update the bias first */
THVector_(cadd)(biasData, biasData, gradBiasData, -learningRate, outDim);
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations.
* No multithreading here as this could
* corrupt the results (hogwild style) */
if (outDim == 1)
{
if (maxNormalize)
{
if (weightDecay)
{
for (j = 0; j < keysSize; j++)
{
long woffset = weightStride0*(keysData[j] + keysOffset) + maxNormalize;
real lr = learningRate*weightData[woffset-2];
weightData[woffset-1] -= weightData[woffset]*gradWeightData[2*j]*lr;
weightData[woffset] -= gradWeightData[2*j+1]*lr - weightDecay * weightData[woffset-2] * weightData[woffset];
}
}
else
{
for (j = 0; j < keysSize; j++)
{
long woffset = weightStride0*(keysData[j] + keysOffset) + maxNormalize;
real lr = learningRate*weightData[woffset-2];
weightData[woffset-1] -= weightData[woffset]*gradWeightData[2*j]*lr;
weightData[woffset] -= gradWeightData[2*j+1]*lr;
}
}
}
else
{
if (weightDecay)
{
for (j = 0; j < keysSize; j++)
{
long woffset = weightStride0*(keysData[j] + keysOffset);
weightData[woffset] -= gradWeightData[j]*learningRate + weightDecay * weightData[woffset];
}
}
else
{
for (j = 0; j < keysSize; j++)
{
weightData[weightStride0*(keysData[j] + keysOffset)] -= gradWeightData[j]*learningRate;
}
}
}
}
else
{
for (j = 0; j < keysSize; j++)
{
real lr = learningRate;
real wd = weightDecay;
real* lweightData;
long woffset = weightStride0*(keysData[j] + keysOffset);
real* lgradWeightData = gradWeightData + j*outDim;
if (maxNormalize)
{
lgradWeightData += j*outDim;
/* weightData[woffset + 2] */
lweightData = weightData + woffset + maxNormalize - 2;
lr = lr*lweightData[0];
wd = weightDecay*lweightData[0];
/* weightData[woffset + 3] */
lweightData++;
for (k=0; k < outDim; k++)
{
lweightData[0] -= lgradWeightData[k]*lweightData[k+1]*lr;
}
lweightData++;
lgradWeightData += outDim;
}
else
{
lweightData = weightData + woffset;
}
/* We do sparse weight decay.
* We think it makes more sense. */
if (weightDecay)
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= lweightData[k]*wd;
}
}
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, -lr, lgradWeightData, 1, lweightData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= lgradWeightData[k]*lr;
}
}
}
}
}
void THNN_(IndexLinear_accUpdateGradParameters)(
THNNState *state,
THLongTensor *keys,
long keysOffset,
THTensor *values,
THLongTensor *sizes,
THLongTensor *cumSumSizes,
THTensor *gradOutput,
THTensor *weight,
THTensor *bias,
accreal weightDecay_,
accreal scale_)
{
real weightDecay = TH_CONVERT_ACCREAL_TO_REAL(weightDecay_);
real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_);
/* Retrieve all the dimensions of the problem */
long batchSize = THLongTensor_size(sizes, 0);
long keysSize = THLongTensor_size(keys, 0);
long outDim = THTensor_(size)(bias, 0);
long woutDim = THTensor_(size)(weight, 1);
int maxNormalize = woutDim - outDim;
THArgCheck(THNN_(checkKeysValues)(keys, values), 1, "Keys and values should have the same number of elements");
/* Access the storage data/strides */
real* gradOutputData = THTensor_(data)(gradOutput);
real* valuesData =THTensor_(data)(values);
real* weightData = THTensor_(data)(weight);
real* biasData = THTensor_(data)(bias);
long weightStride0 = weight->stride[0];
long biasStride = bias->stride[0];
long* keysData = THLongTensor_data(keys);
long* sizesData = THLongTensor_data(sizes);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THLongTensor_isContiguous(keys), 1, "keys vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(values), 3, "values vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradOutput), 6, "gradOutput vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 7, "weight matrix must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 8, "bias matrix must be contiguous");
int i,j,k;
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations.
* No multithreading here as this could
* corrupt the results (hogwild style) */
if (outDim == 1)
{
if (maxNormalize)
{
long offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lgradOutputData = gradOutputData + j;
*biasData -= *lgradOutputData * scale;
real val = *lgradOutputData * scale;
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
long idx = weightStride0*(keysData[offset] + keysOffset) + maxNormalize;
weightData[idx-1] -= weightData[idx]*val*weightData[idx-2];
weightData[idx] -= (val*valuesData[offset] - weightDecay * weightData[idx])*weightData[idx-2];
offset++;
}
}
offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
long idx = weightStride0*(keysData[offset] + keysOffset) + maxNormalize;
weightData[idx-2] = 0;
offset++;
}
}
}
else
{
if (weightDecay)
{
long offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lgradOutputData = gradOutputData + j;
*biasData -= *lgradOutputData * scale;
real val = *lgradOutputData * scale;
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
long idx = weightStride0*(keysData[offset] + keysOffset);
weightData[idx] -= val * valuesData[offset] + weightData[idx] * weightDecay;
offset++;
}
}
}
else
{
long offset = 0;
for (j = 0; j < batchSize; j++)
{
real val = gradOutputData[j] * scale;
for (i = 0; i < sizesData[j]; i++)
{
weightData[(keysData[offset] + keysOffset)*weightStride0] -= val * valuesData[offset];
offset++;
}
*biasData -= val;
}
}
}
}
else {
long offset = 0;
for (j = 0; j < batchSize; j++)
{
real val = 0;
real* lgradOutputData = gradOutputData + j*outDim;
real* lweightData = weightData;
THVector_(cadd)(biasData, biasData, lgradOutputData, -scale, outDim);
for (i = 0; i < sizesData[j]; i++)
{
real val = valuesData[offset] * scale;
real wd = weightDecay;
// Max normalize case
if (maxNormalize)
{
lweightData = weightData + weightStride0*(keysData[offset] + keysOffset) + (maxNormalize-2);
val *= lweightData[0];
wd *= lweightData[0];
for (k=0; k < outDim; k++)
{
lweightData[1] -= lweightData[k+2]*scale*lgradOutputData[k]*lweightData[0];
}
lweightData += 2;
}
else
{
lweightData = weightData + weightStride0*(keysData[offset] + keysOffset);
}
/* We do sparse weight decay.
* We think it makes more sense. */
if (weightDecay)
{
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, -wd, lweightData, 1, lweightData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= wd * lweightData[k];
}
}
}
if (outDim > THNN_SPARSE_OUTDIM_THRESHOLD)
{
THBlas_(axpy)(outDim, -val, lgradOutputData, 1, lweightData, 1);
}
else
{
for (k=0; k < outDim; k++)
{
lweightData[k] -= val * lgradOutputData[k];
}
}
offset++;
}
}
/* Max Normalize case:
* Reset the smart update scaling if
* one does it batch-wise.
* TODO: Decide what to do with that piece of code.
* NB: If the code belowe is uncommented, so should the commented
* code in IndexLinear:zeroGradParameters() */
/*
if (maxNormalize)
{
offset = 0;
for (j = 0; j < batchSize; j++)
{
real* lweightData = weightData;
for (i = 0; i < sizesData[j]; i++)
{
real val = valuesData[offset] * scale;
real wd = weightDecay;
lweightData = weightData + weightStride0*(keysData[offset] + keysOffset) + (maxNormalize-2);
lweightData[0] = 0;
offset++;
}
}
}
*/
}
return;
}
void THNN_(IndexLinear_accGradParameters)(
THNNState *state,
THLongTensor *keys,
long keysOffset,
THTensor *values,
THLongTensor *sizes,
THLongTensor *cumSumSizes,
THTensor *gradOutput,
THTensor *gradWeight,
THTensor *gradBias,
THTensor *weight,
THTensor *bias,
THTensor *valuesBuffer,
accreal weightDecay_,
accreal scale_)
{
real weightDecay = TH_CONVERT_ACCREAL_TO_REAL(weightDecay_);
real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_);
/* Retrieve all the dimensions of the problem */
long batchSize = THLongTensor_size(sizes, 0);
long keysSize = THLongTensor_size(keys, 0);
long outDim = THTensor_(size)(bias, 0);
long woutDim = THTensor_(size)(weight, 1);
long maxNormalize = (woutDim - outDim) > 0 ?1:0;
THArgCheck(THNN_(checkKeysValues)(keys, values), 1, "Keys and values should have the same number of elements");
long* sizesData = THLongTensor_data(sizes);
/* COmpute the cumulative sizes */
THLongTensor* cumSizes = THLongTensor_new();
THLongTensor_cumsum(cumSizes, sizes, 0);
long* cumSizesData = THLongTensor_data(cumSizes);
/* Resize the gradWeight buffer to keep it dense.
* That speeds up updates A LOT assuming random mem access. */
THTensor_(resize2d)(gradWeight, keysSize, outDim * (maxNormalize>0?2:1));
/* Access the storage data/strides */
real* gradOutputData = THTensor_(data)(gradOutput);
real* valuesData =THTensor_(data)(values);
real* gradWeightData = THTensor_(data)(gradWeight);
real* weightData = THTensor_(data)(weight);
real* gradBiasData = THTensor_(data)(gradBias);
long gradWeightStride0 = gradWeight->stride[0];
long weightStride0 = weight->stride[0];
long* keysData = THLongTensor_data(keys);
/* Make sure these inputs are contiguous to accelerate computations */
THArgCheck(THLongTensor_isContiguous(keys), 1, "keys vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(values), 3, "values vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradOutput), 6, "gradOutput vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradWeight), 7, "gradWeight must be contiguous");
THArgCheck(THTensor_(isContiguous)(gradBias), 8, "gradBias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(weight), 9, "weight must be contiguous");
THArgCheck(THTensor_(isContiguous)(bias), 10, "bias vector must be contiguous");
THArgCheck(THTensor_(isContiguous)(valuesBuffer), 11, "valuesBuffer must be contiguous");
int i,j,k;
/* Separate cases: output dimension is == 1, or > 1
* This allows for some optimizations.
* No multithreading here as this could
* corrupt the results (hogwild style) */
if (outDim == 1)
{
for (j = 0; j < batchSize; j++)
{
long offset = j==0?0:cumSizesData[j-1];
real val = gradOutputData[j] * scale;
real* lgradWeightData = gradWeightData + offset;
real* lvaluesData = valuesData + offset;
long end = sizesData[j];
if (maxNormalize)
{
lgradWeightData += offset;
i = 0;
for(;i < end; i++)
{
lgradWeightData[2*i] = val;
lgradWeightData[2*i+1] = val * lvaluesData[i];
}
}
else
{
i = 0;
for(;i < end-4; i += 4)
{
lgradWeightData[i] = val * lvaluesData[i];
lgradWeightData[i+1] = val * lvaluesData[i+1];
lgradWeightData[i+2] = val * lvaluesData[i+2];
lgradWeightData[i+3] = val * lvaluesData[i+3];
}
for(; i < end; i++)
{
lgradWeightData[i] = val * lvaluesData[i];
}
}
*gradBiasData += val;
offset += end;
}
}
else {
for (j = 0; j < batchSize; j++)
{
long offset = j==0?0:cumSizesData[j-1];
real val = 0;
real* lgradOutputData = gradOutputData + j*outDim;
real* lgradWeightData = gradWeightData;
real* lweightData = weightData;
THVector_(cadd)(gradBiasData, gradBiasData, lgradOutputData, scale, outDim);
for (i = 0; i < sizesData[j]; i++)
{
real val = valuesData[offset] * scale;
lgradWeightData = gradWeightData + offset*outDim;
if (maxNormalize)
{
lgradWeightData += offset*outDim;
k = 0;
for(;k < outDim-4; k += 4)
{
lgradWeightData[k] = lgradOutputData[k]*scale;
lgradWeightData[k+1] = lgradOutputData[k+1]*scale;
lgradWeightData[k+2] = lgradOutputData[k+2]*scale;
lgradWeightData[k+3] = lgradOutputData[k+3]*scale;
}
for(; k < outDim; k++)
{
lgradWeightData[k] = lgradOutputData[k]*scale;
}
lgradWeightData += outDim;
}
k = 0;
for(;k < outDim-4; k += 4)
{
lgradWeightData[k] = val * lgradOutputData[k];
lgradWeightData[k+1] = val * lgradOutputData[k+1];
lgradWeightData[k+2] = val * lgradOutputData[k+2];
lgradWeightData[k+3] = val * lgradOutputData[k+3];
}
for(; k < outDim; k++)
{
lgradWeightData[k] = val * lgradOutputData[k];
}
offset++;
}
}
}
THLongTensor_free(cumSizes);
return;
}
#endif
| 2.125 | 2 |
2024-11-18T22:25:40.652712+00:00 | 2023-08-30T19:55:29 | f138d68760df5172f103ff4142405a6ee1f719ac | {
"blob_id": "f138d68760df5172f103ff4142405a6ee1f719ac",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T19:55:29",
"content_id": "5eeb61a921940702ee9ef13bd999aa15a0131eaa",
"detected_licenses": [
"MIT"
],
"directory_id": "83e7dc1281874779c46dfadcc15b2bb66d8e599c",
"extension": "h",
"filename": "lv_tiny_ttf.h",
"fork_events_count": 2218,
"gha_created_at": "2016-06-08T04:14:34",
"gha_event_created_at": "2023-09-14T17:59:34",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 60667730,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1664,
"license": "MIT",
"license_type": "permissive",
"path": "/src/libs/tiny_ttf/lv_tiny_ttf.h",
"provenance": "stackv2-0115.json.gz:133373",
"repo_name": "lvgl/lvgl",
"revision_date": "2023-08-30T19:55:29",
"revision_id": "5c984b4a5364b6455966eb3a860153806c51626f",
"snapshot_id": "7d51d6774d6ac71df7101fc7ded56fea4b70be01",
"src_encoding": "UTF-8",
"star_events_count": 9296,
"url": "https://raw.githubusercontent.com/lvgl/lvgl/5c984b4a5364b6455966eb3a860153806c51626f/src/libs/tiny_ttf/lv_tiny_ttf.h",
"visit_date": "2023-08-30T22:39:20.283922"
} | stackv2 | /**
* @file lv_templ.h
*
*/
#ifndef LV_TINY_TTF_H
#define LV_TINY_TTF_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#include "../../../lvgl.h"
#if LV_USE_TINY_TTF
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
#if LV_TINY_TTF_FILE_SUPPORT !=0
/* create a font from the specified file or path with the specified line height.*/
lv_font_t * lv_tiny_ttf_create_file(const char * path, lv_coord_t line_height);
/* create a font from the specified file or path with the specified line height with the specified cache size.*/
lv_font_t * lv_tiny_ttf_create_file_ex(const char * path, lv_coord_t line_height, size_t cache_size);
#endif
/* create a font from the specified data pointer with the specified line height.*/
lv_font_t * lv_tiny_ttf_create_data(const void * data, size_t data_size, lv_coord_t line_height);
/* create a font from the specified data pointer with the specified line height and the specified cache size.*/
lv_font_t * lv_tiny_ttf_create_data_ex(const void * data, size_t data_size, lv_coord_t line_height, size_t cache_size);
/* set the size of the font to a new line_height*/
void lv_tiny_ttf_set_size(lv_font_t * font, lv_coord_t line_height);
/* destroy a font previously created with lv_tiny_ttf_create_xxxx()*/
void lv_tiny_ttf_destroy(lv_font_t * font);
/**********************
* MACROS
**********************/
#endif /*LV_USE_TINY_TTF*/
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif /*LV_TINY_TTF_H*/
| 2.15625 | 2 |
2024-11-18T22:25:40.801778+00:00 | 2021-05-25T08:29:01 | 35b5748b231bc1819d0bf3187497ea0a3a4c695b | {
"blob_id": "35b5748b231bc1819d0bf3187497ea0a3a4c695b",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-25T08:29:01",
"content_id": "17ea0ecb2b970472ac308eb3adf753442ed55b26",
"detected_licenses": [
"MIT"
],
"directory_id": "82873b85f33c88a9a717394296a4a658f6903493",
"extension": "c",
"filename": "nlpreclean.c",
"fork_events_count": 0,
"gha_created_at": "2020-09-01T12:45:02",
"gha_event_created_at": "2020-09-01T12:45:03",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 291995472,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4845,
"license": "MIT",
"license_type": "permissive",
"path": "/nlp/sources/ogm_nlp/lib/nlpreclean.c",
"provenance": "stackv2-0115.json.gz:133633",
"repo_name": "odespesse/viky-ai",
"revision_date": "2021-05-25T08:29:01",
"revision_id": "de617b2798e49698e756eec0e0d6add89b57d0e0",
"snapshot_id": "c191a88cb44f2e99288c7472b23ffc5b609482f3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/odespesse/viky-ai/de617b2798e49698e756eec0e0d6add89b57d0e0/nlp/sources/ogm_nlp/lib/nlpreclean.c",
"visit_date": "2023-08-17T23:09:42.982666"
} | stackv2 | /*
* Handling choice of request expressions
* Copyright (c) 2017 Pertimm, by Patrick Constant
* Dev : October 2017
* Version 1.0
*/
#include "ogm_nlp.h"
static int NlpRequestExpressionsCleanCmp(gconstpointer ptr_request_expression1, gconstpointer ptr_request_expression2,
gpointer user_data);
#if 0
static int NlpRequestExpressionCleanOld(og_nlp_th ctrl_nlp_th, struct request_expression *request_expression_old);
static og_bool NlpRequestExpressionUsesOld(og_nlp_th ctrl_nlp_th, struct request_expression *request_expression,
struct request_expression *request_expression_old);
#endif
og_status NlpRequestExpressionsClean(og_nlp_th ctrl_nlp_th)
{
int request_expression_used = OgHeapGetCellsUsed(ctrl_nlp_th->hrequest_expression);
struct request_expression *request_expressions = OgHeapGetCell(ctrl_nlp_th->hrequest_expression, 0);
IFn(request_expressions) DPcErr;
int nb_deleted_request_expressions = 0;
for (int i = 0; i < request_expression_used; i++)
{
struct request_expression *request_expression = request_expressions + i;
if (request_expression->deleted == 0) continue;
if (i < ctrl_nlp_th->new_request_expression_start)
{
// Its seems we do not need to clean old expressions,
// and the code to do it is bugged in NlpRequestExpressionCleanOld
//IFE(NlpRequestExpressionCleanOld(ctrl_nlp_th, request_expression));
//NlpThrowErrorTh(ctrl_nlp_th, "NlpRequestExpressionsClean: cleaning of an old expression %d not done", i);
//DPcErr;
request_expression->deleted = 0;
}
nb_deleted_request_expressions++;
}
if (nb_deleted_request_expressions >= 1 && request_expression_used > 1)
{
g_qsort_with_data(request_expressions, request_expression_used, sizeof(struct request_expression),
NlpRequestExpressionsCleanCmp, NULL);
int new_request_expression_used = request_expression_used;
for (int i = request_expression_used - 1; i >= 0; i--)
{
struct request_expression *request_expression = request_expressions + i;
if (request_expression->deleted) new_request_expression_used = i;
else break;
}
IFE(OgHeapSetCellsUsed(ctrl_nlp_th->hrequest_expression, new_request_expression_used));
request_expression_used = OgHeapGetCellsUsed(ctrl_nlp_th->hrequest_expression);
for (int i = 0; i < request_expression_used; i++)
{
struct request_expression *request_expression = request_expressions + i;
request_expression->self_index = i;
}
}
DONE;
}
static int NlpRequestExpressionsCleanCmp(gconstpointer ptr_request_expression1, gconstpointer ptr_request_expression2,
gpointer user_data)
{
struct request_expression *request_expression1 = (struct request_expression *) ptr_request_expression1;
struct request_expression *request_expression2 = (struct request_expression *) ptr_request_expression2;
if (request_expression1->deleted != request_expression2->deleted)
{
return (request_expression1->deleted - request_expression2->deleted);
}
// It is very important to avoid changing the order of the request expressions
return request_expression1->self_index - request_expression2->self_index;
}
#if 0
static int NlpRequestExpressionCleanOld(og_nlp_th ctrl_nlp_th, struct request_expression *request_expression_old)
{
struct request_expression *request_expressions = OgHeapGetCell(ctrl_nlp_th->hrequest_expression, 0);
IFn(request_expressions) DPcErr;
for (int i = 0; i < ctrl_nlp_th->new_request_expression_start; i++)
{
struct request_expression *request_expression = request_expressions + i;
if (request_expression->deleted) continue;
og_bool uses_old = NlpRequestExpressionUsesOld(ctrl_nlp_th, request_expression, request_expression_old);
IFE(uses_old);
if (uses_old)
{
request_expression->deleted = 1;
IFE(NlpRequestExpressionCleanOld(ctrl_nlp_th, request_expression));
}
}
DONE;
}
static og_bool NlpRequestExpressionUsesOld(og_nlp_th ctrl_nlp_th, struct request_expression *request_expression,
struct request_expression *request_expression_old)
{
for (int i = 0; i < request_expression->orips_nb; i++)
{
struct request_input_part *request_input_part = NlpGetRequestInputPart(ctrl_nlp_th, request_expression, i);
IFN(request_input_part) DPcErr;
if (request_input_part->type == nlp_input_part_type_Interpretation)
{
struct request_expression *sub_request_expression = OgHeapGetCell(ctrl_nlp_th->hrequest_expression,
request_input_part->Irequest_expression);
IFN(sub_request_expression) DPcErr;
if (sub_request_expression->self_index == request_expression_old->self_index) return TRUE;
}
}
return FALSE;
}
#endif
| 2.390625 | 2 |
2024-11-18T22:25:40.953564+00:00 | 2019-12-04T00:19:02 | c709759b6e098bac9021dd0d38ad16dfb966b04d | {
"blob_id": "c709759b6e098bac9021dd0d38ad16dfb966b04d",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-04T00:19:02",
"content_id": "575ecba471d41c52c0e1334cf6768041cfed55ad",
"detected_licenses": [
"MIT"
],
"directory_id": "5cb8e6ed8f6fa3136ffc99266364bf860b4a6e5d",
"extension": "c",
"filename": "GraphTest.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 225739057,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 878,
"license": "MIT",
"license_type": "permissive",
"path": "/pa4/GraphTest.c",
"provenance": "stackv2-0115.json.gz:133894",
"repo_name": "t2fu/CMPS101",
"revision_date": "2019-12-04T00:19:02",
"revision_id": "1c4fe200608efaddc78f75f5693e8312bd3f6bb1",
"snapshot_id": "eb98bab95fe799af40140e1c203877c7c3fbd256",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/t2fu/CMPS101/1c4fe200608efaddc78f75f5693e8312bd3f6bb1/pa4/GraphTest.c",
"visit_date": "2020-09-24T10:45:33.151520"
} | stackv2 | /*
* Assignment: Programming Assignment 4(pa4)
* Programmer: Tiancheng Fu
* CruzId: tfu6
* Student id: 1600058
*/
#include<stdio.h>
#include<stdlib.h>
#include"Graph.h"
int main(int argc, char* argv[]){
Graph G = newGraph(6);
//printf("Size: %d", getSize(G));
addEdge(G,1,2);
addEdge(G,1,3);
addEdge(G,2,4);
addEdge(G,2,5);
addEdge(G,2,6);
addEdge(G,3,4);
addEdge(G,4,5);
addEdge(G,5,6);
BFS(G,1);
//printf("%d\n", "NIL");
printf("Order: %d\n", getOrder(G));
printf("Size: %d\n", getSize(G));
printf("Source: %d\n", getSource(G));
printf("Parent: %d\n", getParent(G, 4));
printf("Distance: %d\n", getDist(G, 4));
List Path = newList();
getPath(Path, G, 4);
printList(stdout, Path);
printf("\n");
printGraph(stdout, G);
makeNull(G);
printf("Order: %d\n", getOrder(G));
printf("Size: %d\n", getSize(G));
freeGraph(&G);
}
| 2.40625 | 2 |
2024-11-18T22:25:41.230341+00:00 | 2014-03-21T04:38:34 | 85a55e44351942f9d58dfd4f6ff9a2de041fd227 | {
"blob_id": "85a55e44351942f9d58dfd4f6ff9a2de041fd227",
"branch_name": "refs/heads/master",
"committer_date": "2014-03-21T04:38:34",
"content_id": "bd6301c20e41867dde4ca3f4038367bc59d33e9e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "510d058ef8a38be0792a440284c7748f02742cd0",
"extension": "c",
"filename": "defer_file_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3493,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/tests/defer_file_test.c",
"provenance": "stackv2-0115.json.gz:134022",
"repo_name": "mpalmer/libmarquise",
"revision_date": "2014-03-21T04:38:34",
"revision_id": "c72da4007c6b66609d92bce8ee39d89226a2aa5c",
"snapshot_id": "c58b2ec0f7c26fd4a95d5b09d2a3e098e4711aef",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mpalmer/libmarquise/c72da4007c6b66609d92bce8ee39d89226a2aa5c/src/tests/defer_file_test.c",
"visit_date": "2021-01-20T16:24:19.647367"
} | stackv2 | #include <glib.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include "../structs.h"
#include "../defer.h"
#include "../macros.h"
typedef struct {
deferral_file *df;
} fixture;
void setup(fixture * f, gconstpointer td)
{
f->df = marquise_deferral_file_new();
}
void teardown(fixture * f, gconstpointer td)
{
marquise_deferral_file_close(f->df);
marquise_deferral_file_free(f->df);
}
void setup_envvar(fixture *f, gconstpointer td)
{
const char *tmpl = "/tmp/marquise_defer_test";
mkdir(tmpl, 0777);
setenv("LIBMARQUISE_DEFERRAL_DIR", tmpl, 1);
f->df = marquise_deferral_file_new();
}
void teardown_envvar(fixture *f, gconstpointer td)
{
marquise_deferral_file_close(f->df);
marquise_deferral_file_free(f->df);
rmdir("/tmp/marquise_defer_test");
}
void defer_then_read(fixture * f, gconstpointer td)
{
// two test bursts, we expect it to behave as a LIFO stack
data_burst *first = malloc(sizeof(data_burst));
first->data = malloc(6);
memcpy(first->data, "first", 6);
first->length = 6;
data_burst *last = malloc(sizeof(data_burst));
last->data = malloc(5);
memcpy(first->data, "last", 5);
last->length = 5;
marquise_defer_to_file(f->df, first);
marquise_defer_to_file(f->df, last);
data_burst *first_retrieved = marquise_retrieve_from_file(f->df);
g_assert_cmpuint(last->length, ==, first_retrieved->length);
g_assert_cmpstr((char *)last->data, ==, (char *)first_retrieved->data);
data_burst *last_retrieved = marquise_retrieve_from_file(f->df);
g_assert_cmpuint(first->length, ==, last_retrieved->length);
g_assert_cmpstr((char *)first->data, ==, (char *)last_retrieved->data);
data_burst *nonexistent = marquise_retrieve_from_file(f->df);
g_assert(!nonexistent);
free_databurst(first);
free_databurst(last);
free_databurst(first_retrieved);
free_databurst(last_retrieved);
}
void defer_unlink_then_read(fixture * f, gconstpointer td)
{
data_burst *first = malloc(sizeof(data_burst));
first->data = malloc(6);
memcpy(first->data, "first", 6);
first->length = 6;
marquise_defer_to_file(f->df, first);
unlink(f->df->path);
data_burst *nonexistent = marquise_retrieve_from_file(f->df);
g_assert(!nonexistent);
free_databurst(first);
}
void unlink_defer_then_read(fixture * f, gconstpointer td)
{
data_burst *first = malloc(sizeof(data_burst));
first->data = malloc(6);
memcpy(first->data, "first", 6);
first->length = 6;
unlink(f->df->path);
marquise_defer_to_file(f->df, first);
data_burst *first_retrieved = marquise_retrieve_from_file(f->df);
g_assert(first_retrieved);
g_assert_cmpuint(first->length, ==, first_retrieved->length);
g_assert_cmpstr((char *)first->data, ==, (char *)first_retrieved->data);
free_databurst(first);
free_databurst(first_retrieved);
}
void set_defer_dir(fixture *f, gconstpointer td)
{
const char *tmpl = "/tmp/marquise_defer_test";
int d = strncmp(f->df->path, tmpl, strlen(tmpl));
g_assert_cmpint(d, ==, 0);
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
g_test_add("/defer_file/defer_then", fixture, NULL, setup,
defer_then_read, teardown);
g_test_add("/defer_file/defer_unlink_then_read", fixture, NULL, setup,
defer_unlink_then_read, teardown);
g_test_add("/defer_file/unlink_defer_then_read", fixture, NULL, setup,
unlink_defer_then_read, teardown);
g_test_add("/defer_file/set_defer_dir", fixture, NULL, setup_envvar,
set_defer_dir, teardown_envvar);
return g_test_run();
}
| 2.203125 | 2 |
2024-11-18T22:25:41.292359+00:00 | 2017-08-01T17:17:07 | 8a18deedbf0aa20d30be618490fd785f459eafad | {
"blob_id": "8a18deedbf0aa20d30be618490fd785f459eafad",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-01T17:17:07",
"content_id": "550b42eb0cba01528b9849fbffaf653c61a15fcd",
"detected_licenses": [
"MIT"
],
"directory_id": "fc6d0fa503ef9f1228127d3800040dd247d7bc35",
"extension": "c",
"filename": "kyu-6-equal-sides-of-an-array.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98666176,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1420,
"license": "MIT",
"license_type": "permissive",
"path": "/practice/codewars/kyu-6-equal-sides-of-an-array.c",
"provenance": "stackv2-0115.json.gz:134152",
"repo_name": "KoderDojo/c",
"revision_date": "2017-08-01T17:17:07",
"revision_id": "10248960ff24e88039490420b6ec46543d9b0563",
"snapshot_id": "897661ba5f89afb4d1340b3de7b5f15f54e92dd6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KoderDojo/c/10248960ff24e88039490420b6ec46543d9b0563/practice/codewars/kyu-6-equal-sides-of-an-array.c",
"visit_date": "2021-01-01T19:44:27.907993"
} | stackv2 | #include <assert.h>
#include <stdlib.h>
int sumArray(const int *values, int length) {
int total = 0;
for(int i=0; i < length; i++) {
total += values[i];
}
return total;
}
int find_even_index(const int *values, int length) {
if (length == 0) return 0;
int leftTotal = 0;
int rightTotal = sumArray(values, length) - values[0];
int i;
for(i=0; i < length; i++) {
if (leftTotal == rightTotal)
return i;
leftTotal += values[i];
rightTotal -= values[i+1];
}
return -1;
}
// Test Code
int main (int argc, char *argv[]) {
{
int arr[] = {1, 2, 3, 4, 3, 2, 1};
int expected = 3;
int result = find_even_index(arr, (int)(sizeof(arr)/sizeof(arr[0])));
assert(expected == result);
}
{
int arr[] = { 1,100,50,-51,1,1 };
int expected = 1;
int result = find_even_index(arr, (int)(sizeof(arr)/sizeof(arr[0])));
assert(expected == result);
}
{
int arr[] = { 20,10,-80,10,10,15,35 };
int expected = 0;
int result = find_even_index(arr, (int)(sizeof(arr)/sizeof(arr[0])));
assert(expected == result);
}
{
int arr[] = { -1,-2,-3,-4,-3,-2,-1 };
int expected = 3;
int result = find_even_index(arr, (int)(sizeof(arr)/sizeof(arr[0])));
assert(expected == result);
}
return 0;
}
| 3.46875 | 3 |
2024-11-18T22:25:41.408357+00:00 | 2017-07-15T07:08:06 | 2d91299a58cd6cfbb3a09bf81947243ab9e619d0 | {
"blob_id": "2d91299a58cd6cfbb3a09bf81947243ab9e619d0",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-15T07:08:06",
"content_id": "28f792068b396d15312d52eed3b6886da844037f",
"detected_licenses": [
"MIT"
],
"directory_id": "c296f6be9fc88b8e8b482219c1b99b10502549b5",
"extension": "c",
"filename": "func.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 54762204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 301,
"license": "MIT",
"license_type": "permissive",
"path": "/c/func.c",
"provenance": "stackv2-0115.json.gz:134284",
"repo_name": "junkainiu/learning",
"revision_date": "2017-07-15T07:08:06",
"revision_id": "4968bf1c5f21caa285eac57c85292ebc6b900b21",
"snapshot_id": "abbbb8eb09e11a671f4f57406ccd8b7fe805478c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/junkainiu/learning/4968bf1c5f21caa285eac57c85292ebc6b900b21/c/func.c",
"visit_date": "2021-06-19T09:08:04.563155"
} | stackv2 | #include <stdio.h>
int max(int num1, int num2);
int main()
{
int a = 300;
int b = 200;
int ret;
ret = max(a, b);
printf("Max value is : %d\n", ret);
return 0;
}
int max(int num1, int num2){
if (num1 > num2){
return num1;
} else {
return num2;
}
}
| 3.34375 | 3 |
2024-11-18T22:25:41.513076+00:00 | 2022-08-24T18:41:06 | 998de604c12e958887fc8da5fcd73f8c901ef9ce | {
"blob_id": "998de604c12e958887fc8da5fcd73f8c901ef9ce",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-24T18:41:06",
"content_id": "941c6ba7eca14174f005f436c31102aa0551ec66",
"detected_licenses": [
"BSD-3-Clause",
"ISC",
"BSD-2-Clause"
],
"directory_id": "335cde238cbc05d3aad101633ba61d759e0c5b10",
"extension": "c",
"filename": "sun.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 234764989,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6220,
"license": "BSD-3-Clause,ISC,BSD-2-Clause",
"license_type": "permissive",
"path": "/op/sun.c",
"provenance": "stackv2-0115.json.gz:134413",
"repo_name": "tbvdm/siren",
"revision_date": "2022-08-24T18:41:06",
"revision_id": "6f14bef27eee4da24f9eb3dccf0e2529509b0fa5",
"snapshot_id": "e2d838af595f6e108c9155cd32189bdb234b4a5e",
"src_encoding": "UTF-8",
"star_events_count": 18,
"url": "https://raw.githubusercontent.com/tbvdm/siren/6f14bef27eee4da24f9eb3dccf0e2529509b0fa5/op/sun.c",
"visit_date": "2023-03-11T03:12:25.833641"
} | stackv2 | /*
* Copyright (c) 2012 Tim van der Molen <tim@kariliq.nl>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "../config.h"
#include <sys/ioctl.h>
#include <sys/types.h>
/* NetBSD has <sys/audioio.h>; Solaris has <sys/audio.h>. */
#ifdef HAVE_SYS_AUDIO_H
#include <sys/audio.h>
#else
#include <sys/audioio.h>
#endif
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "../siren.h"
#define OP_SUN_BUFSIZE 4096
#define OP_SUN_DEVICE "/dev/audio"
#define OP_SUN_GAIN_TO_PERCENT(gain) \
((100 * ((gain) - AUDIO_MIN_GAIN) + \
(AUDIO_MAX_GAIN - AUDIO_MIN_GAIN + 1) / 2) / \
(AUDIO_MAX_GAIN - AUDIO_MIN_GAIN))
#define OP_SUN_PERCENT_TO_GAIN(percent) \
(((AUDIO_MAX_GAIN - AUDIO_MIN_GAIN) * (percent) + 50) / 100)
static void op_sun_close(void);
static size_t op_sun_get_buffer_size(void);
static int op_sun_get_volume(void);
static int op_sun_get_volume_support(void);
static int op_sun_init(void);
static int op_sun_open(void);
static void op_sun_set_volume(unsigned int);
static int op_sun_start(struct sample_format *);
static int op_sun_stop(void);
static int op_sun_write(struct sample_buffer *);
struct op op = {
"sun",
OP_PRIORITY_SUN,
NULL,
op_sun_close,
op_sun_get_buffer_size,
op_sun_get_volume,
op_sun_get_volume_support,
op_sun_init,
op_sun_open,
op_sun_set_volume,
op_sun_start,
op_sun_stop,
op_sun_write
};
static int op_sun_fd;
static int op_sun_volume;
static char *op_sun_device;
static void
op_sun_close(void)
{
free(op_sun_device);
}
/* Return the buffer size in bytes. */
static size_t
op_sun_get_buffer_size(void)
{
return OP_SUN_BUFSIZE;
}
static int
op_sun_get_volume(void)
{
audio_info_t info;
/* If the device hasn't been opened, then return the saved volume. */
if (op_sun_fd == -1)
return op_sun_volume;
if (ioctl(op_sun_fd, AUDIO_GETINFO, &info) == -1) {
LOG_ERR("ioctl: AUDIO_GETINFO");
msg_err("Cannot get volume");
return -1;
}
return OP_SUN_GAIN_TO_PERCENT(info.play.gain);
}
static int
op_sun_get_volume_support(void)
{
return 1;
}
static int
op_sun_init(void)
{
option_add_string("sun-device", OP_SUN_DEVICE, player_reopen_op);
return 0;
}
static int
op_sun_open(void)
{
op_sun_device = option_get_string("sun-device");
LOG_INFO("using device %s", op_sun_device);
op_sun_fd = open(op_sun_device, O_WRONLY);
if (op_sun_fd == -1) {
LOG_ERR("open: %s", op_sun_device);
msg_err("Cannot open %s", op_sun_device);
free(op_sun_device);
return -1;
}
op_sun_volume = op_sun_get_volume();
close(op_sun_fd);
op_sun_fd = -1;
if (op_sun_volume == -1) {
free(op_sun_device);
return -1;
}
return 0;
}
static void
op_sun_set_volume(unsigned int volume)
{
audio_info_t info;
if (op_sun_fd == -1) {
msg_errx("Cannot change the volume level while the device is "
"closed");
return;
}
AUDIO_INITINFO(&info);
info.play.gain = OP_SUN_PERCENT_TO_GAIN(volume);
if (ioctl(op_sun_fd, AUDIO_SETINFO, &info) == -1) {
LOG_ERR("ioctl: AUDIO_SETINFO");
msg_err("Cannot set volume");
}
}
static int
op_sun_start(struct sample_format *sf)
{
audio_info_t info;
op_sun_fd = open(op_sun_device, O_WRONLY);
if (op_sun_fd == -1) {
LOG_ERR("open: %s", op_sun_device);
msg_err("Cannot open %s", op_sun_device);
return -1;
}
AUDIO_INITINFO(&info);
info.play.channels = sf->nchannels;
info.play.precision = sf->nbits;
info.play.sample_rate = sf->rate;
#ifdef AUDIO_ENCODING_SLINEAR
info.play.encoding = AUDIO_ENCODING_SLINEAR;
#else
info.play.encoding = AUDIO_ENCODING_LINEAR;
#endif
if (ioctl(op_sun_fd, AUDIO_SETINFO, &info) == -1) {
LOG_ERR("ioctl: AUDIO_SETINFO");
msg_err("Cannot set audio parameters");
goto error;
}
if (ioctl(op_sun_fd, AUDIO_GETINFO, &info) == -1) {
LOG_ERR("ioctl: AUDIO_GETINFO");
msg_err("Cannot get audio parameters");
goto error;
}
LOG_INFO("sample_rate=%u, channels=%u, precision=%u, encoding=%u",
info.play.sample_rate, info.play.channels, info.play.precision,
info.play.encoding);
if (info.play.channels != sf->nchannels) {
LOG_ERRX("%u channels not supported", sf->nchannels);
msg_errx("%u channels not supported", sf->nchannels);
goto error;
}
if (info.play.precision != sf->nbits) {
LOG_ERRX("%u bits per sample not supported", sf->nbits);
msg_errx("%u bits per sample not supported", sf->nbits);
goto error;
}
/* Allow a 0.5% deviation in the sampling rate. */
if (info.play.sample_rate < sf->rate * 995 / 1000 ||
info.play.sample_rate > sf->rate * 1005 / 1000) {
LOG_ERRX("sampling rate (%u Hz) not supported", sf->rate);
msg_errx("Sampling rate not supported");
goto error;
}
switch (info.play.encoding) {
#ifdef AUDIO_ENCODING_SLINEAR_BE
case AUDIO_ENCODING_SLINEAR_BE:
sf->byte_order = BYTE_ORDER_BIG;
break;
#endif
#ifdef AUDIO_ENCODING_SLINEAR_LE
case AUDIO_ENCODING_SLINEAR_LE:
sf->byte_order = BYTE_ORDER_LITTLE;
break;
#endif
case AUDIO_ENCODING_LINEAR:
sf->byte_order = player_get_byte_order();
break;
default:
LOG_ERRX("AUDIO_ENCODING_LINEAR not supported");
msg_errx("Audio encoding not supported");
goto error;
}
return 0;
error:
close(op_sun_fd);
op_sun_fd = -1;
return -1;
}
static int
op_sun_stop(void)
{
op_sun_volume = op_sun_get_volume();
close(op_sun_fd);
op_sun_fd = -1;
return 0;
}
static int
op_sun_write(struct sample_buffer *sb)
{
if (write(op_sun_fd, sb->data, sb->len_b) < 0) {
LOG_ERR("write: %s", op_sun_device);
msg_err("Playback error");
return -1;
}
return 0;
}
| 2.171875 | 2 |
2024-11-18T22:25:41.699524+00:00 | 2022-11-28T10:05:51 | 68fce5e8dbcacb88c678cacac5c2e6747e79a99f | {
"blob_id": "68fce5e8dbcacb88c678cacac5c2e6747e79a99f",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-28T10:05:51",
"content_id": "85b3da736416ce751460a22f9939797b6b146183",
"detected_licenses": [
"MIT"
],
"directory_id": "a8966368090e6972bd838a3a79d86ac03d52e27f",
"extension": "c",
"filename": "sim.c",
"fork_events_count": 56,
"gha_created_at": "2018-11-24T00:33:53",
"gha_event_created_at": "2022-02-24T11:17:59",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 158889536,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 25648,
"license": "MIT",
"license_type": "permissive",
"path": "/sim.c",
"provenance": "stackv2-0115.json.gz:134674",
"repo_name": "hundredrabbits/Orca-c",
"revision_date": "2022-11-28T10:05:51",
"revision_id": "e6a9a30ba09f71e18ec85aa613fb0ebdd6c9bec6",
"snapshot_id": "f98fb363a4b1d4409fabc6d668158b84575bb1d0",
"src_encoding": "UTF-8",
"star_events_count": 444,
"url": "https://raw.githubusercontent.com/hundredrabbits/Orca-c/e6a9a30ba09f71e18ec85aa613fb0ebdd6c9bec6/sim.c",
"visit_date": "2023-08-06T14:39:40.982012"
} | stackv2 | #include "sim.h"
#include "gbuffer.h"
//////// Utilities
static Glyph const glyph_table[36] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', // 0-11
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 12-23
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', // 24-35
};
enum { Glyphs_index_count = sizeof glyph_table };
static inline Glyph glyph_of(Usz index) {
assert(index < Glyphs_index_count);
return glyph_table[index];
}
static U8 const index_table[128] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 32-47
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // 48-63
0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 64-79
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 0, 0, 0, 0, 0, // 80-95
0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 96-111
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 0, 0, 0, 0, 0}; // 112-127
static ORCA_FORCEINLINE Usz index_of(Glyph c) { return index_table[c & 0x7f]; }
// Reference implementation:
// static Usz index_of(Glyph c) {
// if (c >= '0' && c <= '9') return (Usz)(c - '0');
// if (c >= 'A' && c <= 'Z') return (Usz)(c - 'A' + 10);
// if (c >= 'a' && c <= 'z') return (Usz)(c - 'a' + 10);
// return 0;
// }
static ORCA_FORCEINLINE bool glyph_is_lowercase(Glyph g) { return g & 1 << 5; }
static ORCA_FORCEINLINE Glyph glyph_lowered_unsafe(Glyph g) {
return (Glyph)(g | 1 << 5);
}
static inline Glyph glyph_with_case(Glyph g, Glyph caser) {
enum { Case_bit = 1 << 5, Alpha_bit = 1 << 6 };
return (Glyph)((g & ~Case_bit) | ((~g & Alpha_bit) >> 1) |
(caser & Case_bit));
}
static ORCA_PURE bool oper_has_neighboring_bang(Glyph const *gbuf, Usz h, Usz w,
Usz y, Usz x) {
Glyph const *gp = gbuf + w * y + x;
if (x < w - 1 && gp[1] == '*')
return true;
if (x > 0 && *(gp - 1) == '*')
return true;
if (y < h - 1 && gp[w] == '*')
return true;
// note: negative array subscript on rhs of short-circuit, may cause ub if
// the arithmetic under/overflows, even if guarded the guard on lhs is false
if (y > 0 && *(gp - w) == '*')
return true;
return false;
}
// Returns UINT8_MAX if not a valid note.
static U8 midi_note_number_of(Glyph g) {
int sharp = (g & 1 << 5) >> 5; // sharp=1 if lowercase
g &= (Glyph) ~(1 << 5); // make uppercase
if (g < 'A' || g > 'Z') // A through Z only
return UINT8_MAX;
// We want C=0, D=1, E=2, etc. A and B are equivalent to H and I.
int deg = g <= 'B' ? 'G' - 'B' + g - 'A' : g - 'C';
return (U8)(deg / 7 * 12 + (I8[]){0, 2, 4, 5, 7, 9, 11}[deg % 7] + sharp);
}
typedef struct {
Glyph *vars_slots;
Oevent_list *oevent_list;
Usz random_seed;
} Oper_extra_params;
static void oper_poke_and_stun(Glyph *restrict gbuffer, Mark *restrict mbuffer,
Usz height, Usz width, Usz y, Usz x, Isz delta_y,
Isz delta_x, Glyph g) {
Isz y0 = (Isz)y + delta_y;
Isz x0 = (Isz)x + delta_x;
if (y0 < 0 || x0 < 0 || (Usz)y0 >= height || (Usz)x0 >= width)
return;
Usz offs = (Usz)y0 * width + (Usz)x0;
gbuffer[offs] = g;
mbuffer[offs] |= Mark_flag_sleep;
}
// For anyone editing this in the future: the "no inline" here is deliberate.
// You may think that inlining is always faster. Or even just letting the
// compiler decide. You would be wrong. Try it. If you really want this VM to
// run faster, you will need to use computed goto or assembly.
#define OPER_FUNCTION_ATTRIBS ORCA_NOINLINE static void
#define BEGIN_OPERATOR(_oper_name) \
OPER_FUNCTION_ATTRIBS oper_behavior_##_oper_name( \
Glyph *const restrict gbuffer, Mark *const restrict mbuffer, \
Usz const height, Usz const width, Usz const y, Usz const x, \
Usz Tick_number, Oper_extra_params *const extra_params, \
Mark const cell_flags, Glyph const This_oper_char) { \
(void)gbuffer; \
(void)mbuffer; \
(void)height; \
(void)width; \
(void)y; \
(void)x; \
(void)Tick_number; \
(void)extra_params; \
(void)cell_flags; \
(void)This_oper_char;
#define END_OPERATOR }
#define PEEK(_delta_y, _delta_x) \
gbuffer_peek_relative(gbuffer, height, width, y, x, _delta_y, _delta_x)
#define POKE(_delta_y, _delta_x, _glyph) \
gbuffer_poke_relative(gbuffer, height, width, y, x, _delta_y, _delta_x, \
_glyph)
#define STUN(_delta_y, _delta_x) \
mbuffer_poke_relative_flags_or(mbuffer, height, width, y, x, _delta_y, \
_delta_x, Mark_flag_sleep)
#define POKE_STUNNED(_delta_y, _delta_x, _glyph) \
oper_poke_and_stun(gbuffer, mbuffer, height, width, y, x, _delta_y, \
_delta_x, _glyph)
#define LOCK(_delta_y, _delta_x) \
mbuffer_poke_relative_flags_or(mbuffer, height, width, y, x, _delta_y, \
_delta_x, Mark_flag_lock)
#define IN Mark_flag_input
#define OUT Mark_flag_output
#define NONLOCKING Mark_flag_lock
#define PARAM Mark_flag_haste_input
#define LOWERCASE_REQUIRES_BANG \
if (glyph_is_lowercase(This_oper_char) && \
!oper_has_neighboring_bang(gbuffer, height, width, y, x)) \
return
#define STOP_IF_NOT_BANGED \
if (!oper_has_neighboring_bang(gbuffer, height, width, y, x)) \
return
#define PORT(_delta_y, _delta_x, _flags) \
mbuffer_poke_relative_flags_or(mbuffer, height, width, y, x, _delta_y, \
_delta_x, (_flags) ^ Mark_flag_lock)
//////// Operators
#define UNIQUE_OPERATORS(_) \
_('!', midicc) \
_('#', comment) \
_('%', midi) \
_('*', bang) \
_(':', midi) \
_(';', udp) \
_('=', osc) \
_('?', midipb)
#define ALPHA_OPERATORS(_) \
_('A', add) \
_('B', subtract) \
_('C', clock) \
_('D', delay) \
_('E', movement) \
_('F', if) \
_('G', generator) \
_('H', halt) \
_('I', increment) \
_('J', jump) \
_('K', konkat) \
_('L', lesser) \
_('M', multiply) \
_('N', movement) \
_('O', offset) \
_('P', push) \
_('Q', query) \
_('R', random) \
_('S', movement) \
_('T', track) \
_('U', uclid) \
_('V', variable) \
_('W', movement) \
_('X', teleport) \
_('Y', yump) \
_('Z', lerp)
BEGIN_OPERATOR(movement)
if (glyph_is_lowercase(This_oper_char) &&
!oper_has_neighboring_bang(gbuffer, height, width, y, x))
return;
Isz delta_y, delta_x;
switch (glyph_lowered_unsafe(This_oper_char)) {
case 'n':
delta_y = -1;
delta_x = 0;
break;
case 'e':
delta_y = 0;
delta_x = 1;
break;
case 's':
delta_y = 1;
delta_x = 0;
break;
case 'w':
delta_y = 0;
delta_x = -1;
break;
default:
// could cause strict aliasing problem, maybe
delta_y = 0;
delta_x = 0;
break;
}
Isz y0 = (Isz)y + delta_y;
Isz x0 = (Isz)x + delta_x;
if (y0 >= (Isz)height || x0 >= (Isz)width || y0 < 0 || x0 < 0) {
gbuffer[y * width + x] = '*';
return;
}
Glyph *restrict g_at_dest = gbuffer + (Usz)y0 * width + (Usz)x0;
if (*g_at_dest == '.') {
*g_at_dest = This_oper_char;
gbuffer[y * width + x] = '.';
mbuffer[(Usz)y0 * width + (Usz)x0] |= Mark_flag_sleep;
} else {
gbuffer[y * width + x] = '*';
}
END_OPERATOR
BEGIN_OPERATOR(midicc)
for (Usz i = 1; i < 4; ++i) {
PORT(0, (Isz)i, IN);
}
STOP_IF_NOT_BANGED;
Glyph channel_g = PEEK(0, 1);
Glyph control_g = PEEK(0, 2);
Glyph value_g = PEEK(0, 3);
if (channel_g == '.' || control_g == '.')
return;
Usz channel = index_of(channel_g);
if (channel > 15)
return;
PORT(0, 0, OUT);
Oevent_midi_cc *oe =
(Oevent_midi_cc *)oevent_list_alloc_item(extra_params->oevent_list);
oe->oevent_type = Oevent_type_midi_cc;
oe->channel = (U8)channel;
oe->control = (U8)index_of(control_g);
oe->value = (U8)(index_of(value_g) * 127 / 35); // 0~35 -> 0~127
END_OPERATOR
BEGIN_OPERATOR(comment)
// restrict probably ok here...
Glyph const *restrict gline = gbuffer + y * width;
Mark *restrict mline = mbuffer + y * width;
Usz max_x = x + 255;
if (width < max_x)
max_x = width;
for (Usz x0 = x + 1; x0 < max_x; ++x0) {
Glyph g = gline[x0];
mline[x0] |= (Mark)Mark_flag_lock;
if (g == '#')
break;
}
END_OPERATOR
BEGIN_OPERATOR(bang)
gbuffer_poke(gbuffer, height, width, y, x, '.');
END_OPERATOR
BEGIN_OPERATOR(midi)
for (Usz i = 1; i < 6; ++i) {
PORT(0, (Isz)i, IN);
}
STOP_IF_NOT_BANGED;
Glyph channel_g = PEEK(0, 1);
Glyph octave_g = PEEK(0, 2);
Glyph note_g = PEEK(0, 3);
Glyph velocity_g = PEEK(0, 4);
Glyph length_g = PEEK(0, 5);
U8 octave_num = (U8)index_of(octave_g);
if (octave_g == '.')
return;
if (octave_num > 9)
octave_num = 9;
U8 note_num = midi_note_number_of(note_g);
if (note_num == UINT8_MAX)
return;
Usz channel_num = index_of(channel_g);
if (channel_num > 15)
channel_num = 15;
Usz vel_num;
if (velocity_g == '.') {
// If no velocity is specified, set it to full.
vel_num = 127;
} else {
vel_num = index_of(velocity_g);
// MIDI notes with velocity zero are actually note-offs. (MIDI has two ways
// to send note offs. Zero-velocity is the alternate way.) If there is a zero
// velocity, we'll just not do anything.
if (vel_num == 0)
return;
vel_num = vel_num * 8 - 1; // 1~16 -> 7~127
if (vel_num > 127)
vel_num = 127;
}
PORT(0, 0, OUT);
Oevent_midi_note *oe =
(Oevent_midi_note *)oevent_list_alloc_item(extra_params->oevent_list);
oe->oevent_type = (U8)Oevent_type_midi_note;
oe->channel = (U8)channel_num;
oe->octave = octave_num;
oe->note = note_num;
oe->velocity = (U8)vel_num;
// Mask used here to suppress bad GCC Wconversion for bitfield. This is bad
// -- we should do something smarter than this.
oe->duration = (U8)(index_of(length_g) & 0x7Fu);
oe->mono = This_oper_char == '%' ? 1 : 0;
END_OPERATOR
BEGIN_OPERATOR(udp)
Usz n = width - x - 1;
if (n > 16)
n = 16;
Glyph const *restrict gline = gbuffer + y * width + x + 1;
Mark *restrict mline = mbuffer + y * width + x + 1;
Glyph cpy[Oevent_udp_string_count];
Usz i;
for (i = 0; i < n; ++i) {
Glyph g = gline[i];
if (g == '.')
break;
cpy[i] = g;
mline[i] |= Mark_flag_lock;
}
n = i;
STOP_IF_NOT_BANGED;
PORT(0, 0, OUT);
Oevent_udp_string *oe =
(Oevent_udp_string *)oevent_list_alloc_item(extra_params->oevent_list);
oe->oevent_type = (U8)Oevent_type_udp_string;
oe->count = (U8)n;
for (i = 0; i < n; ++i) {
oe->chars[i] = cpy[i];
}
END_OPERATOR
BEGIN_OPERATOR(osc)
PORT(0, 1, IN | PARAM);
PORT(0, 2, IN | PARAM);
Usz len = index_of(PEEK(0, 2));
if (len > Oevent_osc_int_count)
len = Oevent_osc_int_count;
for (Usz i = 0; i < len; ++i) {
PORT(0, (Isz)i + 3, IN);
}
STOP_IF_NOT_BANGED;
Glyph g = PEEK(0, 1);
if (g != '.') {
PORT(0, 0, OUT);
U8 buff[Oevent_osc_int_count];
for (Usz i = 0; i < len; ++i) {
buff[i] = (U8)index_of(PEEK(0, (Isz)i + 3));
}
Oevent_osc_ints *oe =
&oevent_list_alloc_item(extra_params->oevent_list)->osc_ints;
oe->oevent_type = (U8)Oevent_type_osc_ints;
oe->glyph = g;
oe->count = (U8)len;
for (Usz i = 0; i < len; ++i) {
oe->numbers[i] = buff[i];
}
}
END_OPERATOR
BEGIN_OPERATOR(midipb)
for (Usz i = 1; i < 4; ++i) {
PORT(0, (Isz)i, IN);
}
STOP_IF_NOT_BANGED;
Glyph channel_g = PEEK(0, 1);
Glyph msb_g = PEEK(0, 2);
Glyph lsb_g = PEEK(0, 3);
if (channel_g == '.')
return;
Usz channel = index_of(channel_g);
if (channel > 15)
return;
PORT(0, 0, OUT);
Oevent_midi_pb *oe =
(Oevent_midi_pb *)oevent_list_alloc_item(extra_params->oevent_list);
oe->oevent_type = Oevent_type_midi_pb;
oe->channel = (U8)channel;
oe->msb = (U8)(index_of(msb_g) * 127 / 35); // 0~35 -> 0~127
oe->lsb = (U8)(index_of(lsb_g) * 127 / 35);
END_OPERATOR
BEGIN_OPERATOR(add)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph a = PEEK(0, -1);
Glyph b = PEEK(0, 1);
Glyph g = glyph_table[(index_of(a) + index_of(b)) % Glyphs_index_count];
POKE(1, 0, glyph_with_case(g, b));
END_OPERATOR
BEGIN_OPERATOR(subtract)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph a = PEEK(0, -1);
Glyph b = PEEK(0, 1);
Isz val = (Isz)index_of(b) - (Isz)index_of(a);
if (val < 0)
val = -val;
POKE(1, 0, glyph_with_case(glyph_of((Usz)val), b));
END_OPERATOR
BEGIN_OPERATOR(clock)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph b = PEEK(0, 1);
Usz rate = index_of(PEEK(0, -1));
Usz mod_num = index_of(b);
if (rate == 0)
rate = 1;
if (mod_num == 0)
mod_num = 8;
Glyph g = glyph_of(Tick_number / rate % mod_num);
POKE(1, 0, glyph_with_case(g, b));
END_OPERATOR
BEGIN_OPERATOR(delay)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Usz rate = index_of(PEEK(0, -1));
Usz mod_num = index_of(PEEK(0, 1));
if (rate == 0)
rate = 1;
if (mod_num == 0)
mod_num = 8;
Glyph g = Tick_number % (rate * mod_num) == 0 ? '*' : '.';
POKE(1, 0, g);
END_OPERATOR
BEGIN_OPERATOR(if)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph g0 = PEEK(0, -1);
Glyph g1 = PEEK(0, 1);
POKE(1, 0, g0 == g1 ? '*' : '.');
END_OPERATOR
BEGIN_OPERATOR(generator)
LOWERCASE_REQUIRES_BANG;
Isz out_x = (Isz)index_of(PEEK(0, -3));
Isz out_y = (Isz)index_of(PEEK(0, -2)) + 1;
Isz len = (Isz)index_of(PEEK(0, -1));
PORT(0, -3, IN | PARAM); // x
PORT(0, -2, IN | PARAM); // y
PORT(0, -1, IN | PARAM); // len
for (Isz i = 0; i < len; ++i) {
PORT(0, i + 1, IN);
PORT(out_y, out_x + i, OUT | NONLOCKING);
Glyph g = PEEK(0, i + 1);
POKE_STUNNED(out_y, out_x + i, g);
}
END_OPERATOR
BEGIN_OPERATOR(halt)
LOWERCASE_REQUIRES_BANG;
PORT(1, 0, IN | PARAM);
END_OPERATOR
BEGIN_OPERATOR(increment)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, IN | OUT);
Glyph ga = PEEK(0, -1);
Glyph gb = PEEK(0, 1);
Usz rate = 1;
if (ga != '.' && ga != '*')
rate = index_of(ga);
Usz max = index_of(gb);
Usz val = index_of(PEEK(1, 0));
if (max == 0)
max = 36;
val = val + rate;
val = val % max;
POKE(1, 0, glyph_with_case(glyph_of(val), gb));
END_OPERATOR
BEGIN_OPERATOR(jump)
LOWERCASE_REQUIRES_BANG;
Glyph g = PEEK(-1, 0);
if (g == This_oper_char)
return;
PORT(-1, 0, IN);
for (Isz i = 1; i <= 256; ++i) {
if (PEEK(i, 0) != This_oper_char) {
PORT(i, 0, OUT);
POKE(i, 0, g);
break;
}
STUN(i, 0);
}
END_OPERATOR
// Note: this is merged from a pull request without being fully tested or
// optimized
BEGIN_OPERATOR(konkat)
LOWERCASE_REQUIRES_BANG;
Isz len = (Isz)index_of(PEEK(0, -1));
if (len == 0)
len = 1;
PORT(0, -1, IN | PARAM);
for (Isz i = 0; i < len; ++i) {
PORT(0, i + 1, IN);
Glyph var = PEEK(0, i + 1);
if (var != '.') {
Usz var_idx = index_of(var);
Glyph result = extra_params->vars_slots[var_idx];
PORT(1, i + 1, OUT);
POKE(1, i + 1, result);
}
}
END_OPERATOR
BEGIN_OPERATOR(lesser)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph ga = PEEK(0, -1);
Glyph gb = PEEK(0, 1);
if (ga == '.' || gb == '.') {
POKE(1, 0, '.');
} else {
Usz ia = index_of(ga);
Usz ib = index_of(gb);
Usz out = ia < ib ? ia : ib;
POKE(1, 0, glyph_with_case(glyph_of(out), gb));
}
END_OPERATOR
BEGIN_OPERATOR(multiply)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph a = PEEK(0, -1);
Glyph b = PEEK(0, 1);
Glyph g = glyph_table[(index_of(a) * index_of(b)) % Glyphs_index_count];
POKE(1, 0, glyph_with_case(g, b));
END_OPERATOR
BEGIN_OPERATOR(offset)
LOWERCASE_REQUIRES_BANG;
Isz in_x = (Isz)index_of(PEEK(0, -2)) + 1;
Isz in_y = (Isz)index_of(PEEK(0, -1));
PORT(0, -1, IN | PARAM);
PORT(0, -2, IN | PARAM);
PORT(in_y, in_x, IN);
PORT(1, 0, OUT);
POKE(1, 0, PEEK(in_y, in_x));
END_OPERATOR
BEGIN_OPERATOR(push)
LOWERCASE_REQUIRES_BANG;
Usz key = index_of(PEEK(0, -2));
Usz len = index_of(PEEK(0, -1));
PORT(0, -1, IN | PARAM);
PORT(0, -2, IN | PARAM);
PORT(0, 1, IN);
if (len == 0)
return;
Isz out_x = (Isz)(key % len);
for (Usz i = 0; i < len; ++i) {
LOCK(1, (Isz)i);
}
PORT(1, out_x, OUT);
POKE(1, out_x, PEEK(0, 1));
END_OPERATOR
BEGIN_OPERATOR(query)
LOWERCASE_REQUIRES_BANG;
Isz in_x = (Isz)index_of(PEEK(0, -3)) + 1;
Isz in_y = (Isz)index_of(PEEK(0, -2));
Isz len = (Isz)index_of(PEEK(0, -1));
Isz out_x = 1 - len;
PORT(0, -3, IN | PARAM); // x
PORT(0, -2, IN | PARAM); // y
PORT(0, -1, IN | PARAM); // len
// todo direct buffer manip
for (Isz i = 0; i < len; ++i) {
PORT(in_y, in_x + i, IN);
PORT(1, out_x + i, OUT);
Glyph g = PEEK(in_y, in_x + i);
POKE(1, out_x + i, g);
}
END_OPERATOR
BEGIN_OPERATOR(random)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph gb = PEEK(0, 1);
Usz a = index_of(PEEK(0, -1));
Usz b = index_of(gb);
if (b == 0)
b = 36;
Usz min, max;
if (a == b) {
POKE(1, 0, glyph_of(a));
return;
} else if (a < b) {
min = a;
max = b;
} else {
min = b;
max = a;
}
// Initial input params for the hash
Usz key = (extra_params->random_seed + y * width + x) ^
(Tick_number << UINT32_C(16));
// 32-bit shift_mult hash to evenly distribute bits
key = (key ^ UINT32_C(61)) ^ (key >> UINT32_C(16));
key = key + (key << UINT32_C(3));
key = key ^ (key >> UINT32_C(4));
key = key * UINT32_C(0x27d4eb2d);
key = key ^ (key >> UINT32_C(15));
// Hash finished. Restrict to desired range of numbers.
Usz val = key % (max - min) + min;
POKE(1, 0, glyph_with_case(glyph_of(val), gb));
END_OPERATOR
BEGIN_OPERATOR(track)
LOWERCASE_REQUIRES_BANG;
Usz key = index_of(PEEK(0, -2));
Usz len = index_of(PEEK(0, -1));
PORT(0, -2, IN | PARAM);
PORT(0, -1, IN | PARAM);
if (len == 0)
return;
Isz read_val_x = (Isz)(key % len) + 1;
for (Usz i = 0; i < len; ++i) {
LOCK(0, (Isz)(i + 1));
}
PORT(0, (Isz)read_val_x, IN);
PORT(1, 0, OUT);
POKE(1, 0, PEEK(0, read_val_x));
END_OPERATOR
// https://www.computermusicdesign.com/
// simplest-euclidean-rhythm-algorithm-explained/
BEGIN_OPERATOR(uclid)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, OUT);
Glyph left = PEEK(0, -1);
Usz steps = 1;
if (left != '.' && left != '*')
steps = index_of(left);
Usz max = index_of(PEEK(0, 1));
if (max == 0)
max = 8;
Usz bucket = (steps * (Tick_number + max - 1)) % max + steps;
Glyph g = (bucket >= max) ? '*' : '.';
POKE(1, 0, g);
END_OPERATOR
BEGIN_OPERATOR(variable)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
Glyph left = PEEK(0, -1);
Glyph right = PEEK(0, 1);
if (left != '.') {
// Write
Usz var_idx = index_of(left);
extra_params->vars_slots[var_idx] = right;
} else if (right != '.') {
// Read
PORT(1, 0, OUT);
Usz var_idx = index_of(right);
Glyph result = extra_params->vars_slots[var_idx];
POKE(1, 0, result);
}
END_OPERATOR
BEGIN_OPERATOR(teleport)
LOWERCASE_REQUIRES_BANG;
Isz out_x = (Isz)index_of(PEEK(0, -2));
Isz out_y = (Isz)index_of(PEEK(0, -1)) + 1;
PORT(0, -2, IN | PARAM); // x
PORT(0, -1, IN | PARAM); // y
PORT(0, 1, IN);
PORT(out_y, out_x, OUT | NONLOCKING);
POKE_STUNNED(out_y, out_x, PEEK(0, 1));
END_OPERATOR
BEGIN_OPERATOR(yump)
LOWERCASE_REQUIRES_BANG;
Glyph g = PEEK(0, -1);
if (g == This_oper_char)
return;
PORT(0, -1, IN);
for (Isz i = 1; i <= 256; ++i) {
if (PEEK(0, i) != This_oper_char) {
PORT(0, i, OUT);
POKE(0, i, g);
break;
}
STUN(0, i);
}
END_OPERATOR
BEGIN_OPERATOR(lerp)
LOWERCASE_REQUIRES_BANG;
PORT(0, -1, IN | PARAM);
PORT(0, 1, IN);
PORT(1, 0, IN | OUT);
Glyph g = PEEK(0, -1);
Glyph b = PEEK(0, 1);
Isz rate = g == '.' || g == '*' ? 1 : (Isz)index_of(g);
Isz goal = (Isz)index_of(b);
Isz val = (Isz)index_of(PEEK(1, 0));
Isz mod = val <= goal - rate ? rate : val >= goal + rate ? -rate : goal - val;
POKE(1, 0, glyph_with_case(glyph_of((Usz)(val + mod)), b));
END_OPERATOR
//////// Run simulation
void orca_run(Glyph *restrict gbuf, Mark *restrict mbuf, Usz height, Usz width,
Usz tick_number, Oevent_list *oevent_list, Usz random_seed) {
Glyph vars_slots[Glyphs_index_count];
memset(vars_slots, '.', sizeof(vars_slots));
Oper_extra_params extras;
extras.vars_slots = &vars_slots[0];
extras.oevent_list = oevent_list;
extras.random_seed = random_seed;
for (Usz iy = 0; iy < height; ++iy) {
Glyph const *glyph_row = gbuf + iy * width;
Mark const *mark_row = mbuf + iy * width;
for (Usz ix = 0; ix < width; ++ix) {
Glyph glyph_char = glyph_row[ix];
if (ORCA_LIKELY(glyph_char == '.'))
continue;
Mark cell_flags = mark_row[ix] & (Mark_flag_lock | Mark_flag_sleep);
if (cell_flags & (Mark_flag_lock | Mark_flag_sleep))
continue;
switch (glyph_char) {
#define UNIQUE_CASE(_oper_char, _oper_name) \
case _oper_char: \
oper_behavior_##_oper_name(gbuf, mbuf, height, width, iy, ix, tick_number, \
&extras, cell_flags, glyph_char); \
break;
#define ALPHA_CASE(_upper_oper_char, _oper_name) \
case _upper_oper_char: \
case (char)(_upper_oper_char | 1 << 5): \
oper_behavior_##_oper_name(gbuf, mbuf, height, width, iy, ix, tick_number, \
&extras, cell_flags, glyph_char); \
break;
UNIQUE_OPERATORS(UNIQUE_CASE)
ALPHA_OPERATORS(ALPHA_CASE)
#undef UNIQUE_CASE
#undef ALPHA_CASE
}
}
}
}
| 2.578125 | 3 |
2024-11-18T22:25:41.879190+00:00 | 2018-05-19T04:51:41 | a0c21f9c4e2a6110aae24f29c852e6233663bc56 | {
"blob_id": "a0c21f9c4e2a6110aae24f29c852e6233663bc56",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-19T04:51:41",
"content_id": "0bc690d8aff7677114650563c7c165755e85443a",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5bb3eb30b84fa43f69f0603339c21e7697e25fb2",
"extension": "c",
"filename": "los_bsp_key.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134030545,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1052,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/platform/ATSAMG55-XPRO/los_bsp_key.c",
"provenance": "stackv2-0115.json.gz:134932",
"repo_name": "Huawei-LiteOS/LiteOS_Kernel",
"revision_date": "2018-05-19T04:51:41",
"revision_id": "25070df19e352858eeb12656423c3dceb9b93208",
"snapshot_id": "16411b1f682a9983b4f782e986d8cd12d7329556",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Huawei-LiteOS/LiteOS_Kernel/25070df19e352858eeb12656423c3dceb9b93208/platform/ATSAMG55-XPRO/los_bsp_key.c",
"visit_date": "2020-03-17T23:04:17.462977"
} | stackv2 | #include "los_bsp_key.h"
#ifdef LOS_ATMSAMG55xx
#include "samg55.h" // Device header
#include "Board_Buttons.h" // ::Board Support:Buttons
#endif
/*****************************************************************************
Function : LOS_EvbKeyInit
Description : Init GIOP Key
Input : None
Output : None
Return : None
*****************************************************************************/
void LOS_EvbKeyInit(void)
{
#ifdef LOS_ATMSAMG55xx
Buttons_Initialize();
#endif
return;
}
/*****************************************************************************
Function : LOS_EvbGetKeyVal
Description : Get GIOP Key value
Input : int KeyNum
Output : None
Return : KeyVal
*****************************************************************************/
unsigned int LOS_EvbGetKeyVal(int KeyNum)
{
unsigned int KeyVal = LOS_GPIO_ERR;
//add you code here.
#ifdef LOS_ATMSAMG55xx
KeyVal = Buttons_GetState();
#endif
return KeyVal;
}
| 2.015625 | 2 |
2024-11-18T22:25:42.004110+00:00 | 2023-08-16T11:44:49 | 7ed7722ef0d7353c80ba4050c3fe997da938acb7 | {
"blob_id": "7ed7722ef0d7353c80ba4050c3fe997da938acb7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-16T11:44:49",
"content_id": "98305000e5c3b0780ce386dcf75ec0284919258d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "45400bf1909326a9cb932b9cfc4e19187cb3c30a",
"extension": "h",
"filename": "list.h",
"fork_events_count": 0,
"gha_created_at": "2022-05-01T15:43:52",
"gha_event_created_at": "2022-05-01T15:43:53",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 487576029,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1629,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/system/hardware/arm/miyoo/drivers/audio/list.h",
"provenance": "stackv2-0115.json.gz:135062",
"repo_name": "tonytsangzen/EwokOS",
"revision_date": "2023-08-16T11:44:49",
"revision_id": "f298275b28367157aa794d85fcfcc797e00eda79",
"snapshot_id": "f46cd99435ccea213ebb14fb05a6a2f057e6907b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tonytsangzen/EwokOS/f298275b28367157aa794d85fcfcc797e00eda79/system/hardware/arm/miyoo/drivers/audio/list.h",
"visit_date": "2023-08-17T20:50:44.551533"
} | stackv2 |
#ifndef _TEMP_LIST_H_
#define _TEMP_LIST_H_
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct listnode
{
struct listnode *next;
struct listnode *prev;
};
#define node_to_item(node, container, member) \
(container *) (((char*) (node)) - offsetof(container, member))
#define list_declare(name) \
struct listnode name = { \
.next = &(name), \
.prev = &(name), \
}
#define list_for_each(node, list) \
for ((node) = (list)->next; (node) != (list); (node) = (node)->next)
#define list_for_each_reverse(node, list) \
for ((node) = (list)->prev; (node) != (list); (node) = (node)->prev)
#define list_for_each_safe(node, n, list) \
for ((node) = (list)->next, (n) = (node)->next; \
(node) != (list); \
(node) = (n), (n) = (node)->next)
static inline void list_init(struct listnode *node)
{
node->next = node;
node->prev = node;
}
static inline void list_add_tail(struct listnode *head, struct listnode *item)
{
item->next = head;
item->prev = head->prev;
head->prev->next = item;
head->prev = item;
}
static inline void list_add_head(struct listnode *head, struct listnode *item)
{
item->next = head->next;
item->prev = head;
head->next->prev = item;
head->next = item;
}
static inline void list_remove(struct listnode *item)
{
item->next->prev = item->prev;
item->prev->next = item->next;
}
#define list_empty(list) ((list) == (list)->next)
#define list_head(list) ((list)->next)
#define list_tail(list) ((list)->prev)
#ifdef __cplusplus
};
#endif /* __cplusplus */
#endif
| 2.6875 | 3 |
2024-11-18T22:25:42.088764+00:00 | 2020-10-02T18:41:23 | f2916c9296aa43000f76f17f42f841c87efa8cd9 | {
"blob_id": "f2916c9296aa43000f76f17f42f841c87efa8cd9",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-02T18:41:23",
"content_id": "ce766f4b83c5a70257e86a0eb090079e0c8b7f43",
"detected_licenses": [
"Unlicense"
],
"directory_id": "35cc6230b785ed9630617aecc6359f4c656e3a55",
"extension": "c",
"filename": "checker_v_loop_control.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 171051566,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1500,
"license": "Unlicense",
"license_type": "permissive",
"path": "/fpush_swap/checker_v_loop_control.c",
"provenance": "stackv2-0115.json.gz:135190",
"repo_name": "whyh/push_swap",
"revision_date": "2020-10-02T18:41:23",
"revision_id": "6ab5c860716b8875b94bb659e8a39fcbd2145f70",
"snapshot_id": "bf682b93bd398522e10cb741f58273bc7e7e204f",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/whyh/push_swap/6ab5c860716b8875b94bb659e8a39fcbd2145f70/fpush_swap/checker_v_loop_control.c",
"visit_date": "2021-07-02T00:19:23.225360"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* checker_v_loop_control.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dderevyn <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/04 21:08:22 by dderevyn #+# #+# */
/* Updated: 2019/03/04 21:08:22 by dderevyn ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int push_swap_v_loop(void *param)
{
t_push_swap_vis *vis;
long long n;
vis = param;
if (vis->buff && !vis->buff[vis->i])
{
vis->pause = 1;
push_swap_v_draw(vis);
}
else if (vis->buff && vis->pause == 0)
{
vis->o++;
n = (LL)ft_strchr_i(&(vis->buff[vis->i]), ' ');
vis->status = ft_strndup(&(vis->buff[vis->i]), n);
push_swap_exec(vis, vis->status);
push_swap_v_draw(vis);
ft_strdel(&(vis->status));
vis->i += n + 1;
}
return (1);
}
int push_swap_v_close(void *param)
{
t_push_swap_vis *vis;
vis = param;
push_swap_exit(vis);
exit(0);
return (1);
}
| 2.390625 | 2 |
2024-11-18T22:25:42.266819+00:00 | 2021-10-04T08:17:02 | 5acdbe4cb3b6b87cec2e64256bee26f8823f4f0b | {
"blob_id": "5acdbe4cb3b6b87cec2e64256bee26f8823f4f0b",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-04T08:17:02",
"content_id": "cce2df67702d74428d7d7a6c18dfd7fd347adb19",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "daf2b9a45d95ec2760e7512ffdbd8b875792d914",
"extension": "h",
"filename": "tuya_ble_app_bulk_data_demo.h",
"fork_events_count": 0,
"gha_created_at": "2021-10-04T08:12:50",
"gha_event_created_at": "2021-10-04T08:12:51",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 413331588,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3076,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/example/bulk_data/tuya_ble_app_bulk_data_demo.h",
"provenance": "stackv2-0115.json.gz:135320",
"repo_name": "hjytry/tuya-ble-sdk",
"revision_date": "2021-10-04T08:17:02",
"revision_id": "815c07120e96372e8746e9d01a21381a8fdd8655",
"snapshot_id": "511dd2b202536047bfca3532e1d45caffc2e4595",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hjytry/tuya-ble-sdk/815c07120e96372e8746e9d01a21381a8fdd8655/example/bulk_data/tuya_ble_app_bulk_data_demo.h",
"visit_date": "2023-08-15T08:33:57.555748"
} | stackv2 | #ifndef TUYA_BLE_APP_BULK_DATA_DEMO_H_
#define TUYA_BLE_APP_BULK_DATA_DEMO_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "tuya_ble_type.h"
/**@brief Function for handling the bulk data events.
*
* @details The bulk data reading steps are:
*
* 1. The mobile app first reads the bulk data information of the specified type, and triggers the Tuya BLE SDK
* to send the 'TUYA_BLE_BULK_DATA_EVT_READ_INFO' event to the device application. The event data contains the
* type value of the bulk data to be read by the mobile app. The device application calls the 'tuya_ble_bulk_data_response()'
* function to send the total length, total CRC32, block size and other information of the bulk data to the mobile app.
*
* 2. The mobile app starts the bulk data reading process according to the data information returned by the device application.
* First trigger the Tuya BLE SDK to send the 'TUYA_BLE_BULK_DATA_EVT_READ_BLOCK' event to request the data information of
* the first block, including block number (starting from 0), block size, and CRC16 of the block data. The device application
* calls the'tuya_ble_bulk_data_response()' function to reply to the block data information.
* 3. After sending the block data information to the mobile app, the Tuya BLE SDK will automatically send the'TUYA_BLE_BULK_DATA_EVT_SEND_DATA'
* event to the device application. The event data contains the block number to be read. The device application calls the'tuya_ble_bulk_data_response()'
* function to send the block data .
* 4. After sending the block data information to the mobile app, the Tuya BLE SDK will automatically send the'TUYA_BLE_BULK_DATA_EVT_SEND_DATA'
* event to the device application. The event data contains the block number to be read. The device application calls the'tuya_ble_bulk_data_response()'
* function to send the block data.
* 5. After reading all the blocks, the mobile app will verify the data. When the verification is completed, all the dp point data in it will be parsed and
* uploaded to the cloud. When the upload is complete, the Tuya BLE SDK will be triggered to send the'TUYA_BLE_BULK_DATA_EVT_ERASE' event to the device
* application. The event data contains The type value of bulk data to be erased, after the device application erases the data,
* call the'tuya_ble_bulk_data_response()' function to send the erase result.
* 6. If the device defines multiple types of bulk data, the mobile app will initiate the process of reading bulk data of other types.
*
* @note The application must call this function where it receives the @ref TUYA_BLE_CB_EVT_BULK_DATA event.
*
* @param[in] p_data Event data received from the SDK.
*
*/
void tuya_ble_app_bulk_data_handler(tuya_ble_bulk_data_request_t *evt);
/**@brief Function for generate bulk data for testing.
*
* @details The device application calls this function to generate bulkdata test data.
*
*/
void tuya_ble_test_bulk_data_generation(void);
#ifdef __cplusplus
}
#endif
#endif //
| 2.15625 | 2 |
2024-11-18T22:25:42.364316+00:00 | 2021-06-15T15:43:56 | a37ae1ee127ae6c83e13f071590f788eb26ed94c | {
"blob_id": "a37ae1ee127ae6c83e13f071590f788eb26ed94c",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-15T15:43:56",
"content_id": "b458d596a7d4623eb46f2641dc0497d935b93cf8",
"detected_licenses": [
"MIT"
],
"directory_id": "ebcb94127c44084b06731637a87acbee0357b1f2",
"extension": "c",
"filename": "libbenchmark_datastructure_btree_au_pthread_rwlock.c",
"fork_events_count": 1,
"gha_created_at": "2020-09-25T23:32:37",
"gha_event_created_at": "2020-10-02T12:57:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 298700099,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 20533,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/liblfds7.1.1/test_and_benchmark/libbenchmark/src/libbenchmark_datastructures_btree_au/libbenchmark_datastructure_btree_au_pthread_rwlock.c",
"provenance": "stackv2-0115.json.gz:135449",
"repo_name": "TomatOid/powhatan",
"revision_date": "2021-06-15T15:43:56",
"revision_id": "a885159b7a544c6060c66c2b074941538b1bf9ef",
"snapshot_id": "ff789cf03a22ecc8312278626ebecc8ef12521cb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/TomatOid/powhatan/a885159b7a544c6060c66c2b074941538b1bf9ef/lib/liblfds7.1.1/test_and_benchmark/libbenchmark/src/libbenchmark_datastructures_btree_au/libbenchmark_datastructure_btree_au_pthread_rwlock.c",
"visit_date": "2023-06-01T16:09:05.523570"
} | stackv2 | /***** includes *****/
#include "libbenchmark_datastructure_btree_au_internal.h"
/***** private prototypes *****/
static void libbenchmark_datastructure_btree_au_internal_inorder_walk_from_largest_get_next_smallest_element( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue );
static void libbenchmark_datastructure_btree_au_internal_inorder_walk_from_smallest_get_next_largest_element( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue );
/****************************************************************************/
void libbenchmark_datastructure_btree_au_pthread_rwlock_init( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus,
int (*key_compare_function)(void const *new_key, void const *existing_key),
enum libbenchmark_datastructure_btree_au_pthread_rwlock_existing_key existing_key,
void *user_state )
{
LFDS711_PAL_ASSERT( baus != NULL );
LFDS711_PAL_ASSERT( key_compare_function != NULL );
// TRD : existing_key can be any value in its range
// TRD : user_state can be NULL
baus->root = NULL;
baus->key_compare_function = key_compare_function;
baus->existing_key = existing_key;
baus->user_state = user_state;
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_CREATE( baus->lock );
LFDS711_MISC_BARRIER_STORE;
lfds711_misc_force_store();
return;
}
/****************************************************************************/
void libbenchmark_datastructure_btree_au_pthread_rwlock_cleanup( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus,
void (*element_cleanup_callback)(struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element *baue) )
{
enum libbenchmark_datastructure_btree_au_delete_action
delete_action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_SELF; // TRD : to remove compiler warning
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element
*baue,
*temp;
LFDS711_PAL_ASSERT( baus != NULL );
// TRD : element_delete_function can be NULL
if( element_cleanup_callback != NULL )
{
libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_absolute_position_for_read( baus, &baue, LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_ABSOLUTE_POSITION_ROOT );
while( baue != NULL )
{
if( baue->left == NULL and baue->right == NULL )
delete_action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_SELF;
if( baue->left != NULL and baue->right == NULL )
delete_action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_SELF_REPLACE_WITH_LEFT_CHILD;
if( baue->left == NULL and baue->right != NULL )
delete_action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_SELF_REPLACE_WITH_RIGHT_CHILD;
if( baue->left != NULL and baue->right != NULL )
delete_action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_MOVE_LEFT;
switch( delete_action )
{
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_SELF:
// TRD : if we have a parent (we could be root) set his point to us to NULL
if( baue->up != NULL )
{
if( baue->up->left == baue )
baue->up->left = NULL;
if( baue->up->right == baue )
baue->up->right = NULL;
}
temp = baue;
libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_relative_position_for_read( baus, &baue, LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_UP );
element_cleanup_callback( baus, temp );
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_SELF_REPLACE_WITH_LEFT_CHILD:
baue->left->up = baue->up;
if( baue->up != NULL )
{
if( baue->up->left == baue )
baue->up->left = baue->left;
if( baue->up->right == baue )
baue->up->right = baue->left;
}
temp = baue;
libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_relative_position_for_read( baus, &baue, LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_LEFT );
element_cleanup_callback( baus, temp );
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_SELF_REPLACE_WITH_RIGHT_CHILD:
baue->right->up = baue->up;
if( baue->up != NULL )
{
if( baue->up->left == baue )
baue->up->left = baue->right;
if( baue->up->right == baue )
baue->up->right = baue->right;
}
temp = baue;
libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_relative_position_for_read( baus, &baue, LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_RIGHT );
element_cleanup_callback( baus, temp );
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_DELETE_MOVE_LEFT:
libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_relative_position_for_read( baus, &baue, LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_LEFT );
break;
}
}
}
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_DESTROY( baus->lock );
return;
}
/****************************************************************************/
enum libbenchmark_datastructure_btree_au_pthread_rwlock_insert_result libbenchmark_datastructure_btree_au_pthread_rwlock_insert( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus,
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element *baue,
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **existing_baue )
{
int
compare_result = 0;
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element
*baue_next = NULL,
*baue_parent = NULL,
*baue_temp;
LFDS711_PAL_ASSERT( baus != NULL );
LFDS711_PAL_ASSERT( baue != NULL );
// TRD : existing_baue can be NULL
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_GET_WRITE( baus->lock );
baue->up = baue->left = baue->right = NULL;
baue_temp = baus->root;
while( baue_temp != NULL )
{
compare_result = baus->key_compare_function( baue->key, baue_temp->key );
if( compare_result == 0 )
{
if( existing_baue != NULL )
*existing_baue = baue_temp;
switch( baus->existing_key )
{
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_EXISTING_KEY_OVERWRITE:
LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_SET_VALUE_IN_ELEMENT( *baus, *baue_temp, baue->value );
return LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_INSERT_RESULT_SUCCESS_OVERWRITE;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_EXISTING_KEY_FAIL:
return LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_INSERT_RESULT_FAILURE_EXISTING_KEY;
break;
}
}
if( compare_result < 0 )
baue_next = baue_temp->left;
if( compare_result > 0 )
baue_next = baue_temp->right;
baue_parent = baue_temp;
baue_temp = baue_next;
}
if( baue_parent == NULL )
{
baue->up = baus->root;
baus->root = baue; }
if( baue_parent != NULL )
{
if( compare_result <= 0 )
{
baue->up = baue_parent;
baue_parent->left = baue;
}
if( compare_result > 0 )
{
baue->up = baue_parent;
baue_parent->right = baue;
}
}
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_RELEASE( baus->lock );
// TRD : if we get to here, we added (not failed or overwrite on exist) a new element
if( existing_baue != NULL )
*existing_baue = NULL;
return LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_INSERT_RESULT_SUCCESS;
}
/****************************************************************************/
int libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_key_for_read( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus,
int (*key_compare_function)(void const *new_key, void const *existing_key),
void *key,
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue )
{
int
compare_result = !0,
rv = 1;
LFDS711_PAL_ASSERT( baus != NULL );
// TRD : key_compare_function can be NULL
// TRD : key can be NULL
LFDS711_PAL_ASSERT( baue != NULL );
if( key_compare_function == NULL )
key_compare_function = baus->key_compare_function;
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_GET_READ( baus->lock );
*baue = baus->root;
while( *baue != NULL and compare_result != 0 )
{
compare_result = key_compare_function( key, (*baue)->key );
if( compare_result < 0 )
*baue = (*baue)->left;
if( compare_result > 0 )
*baue = (*baue)->right;
}
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_RELEASE( baus->lock );
if( *baue == NULL )
rv = 0;
return rv;
}
/****************************************************************************/
int libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_key_for_write( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus,
int (*key_compare_function)(void const *new_key, void const *existing_key),
void *key,
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue )
{
int
compare_result = !0,
rv = 1;
LFDS711_PAL_ASSERT( baus != NULL );
// TRD : key_compare_function can be NULL
// TRD : key can be NULL
LFDS711_PAL_ASSERT( baue != NULL );
if( key_compare_function == NULL )
key_compare_function = baus->key_compare_function;
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_GET_WRITE( baus->lock );
*baue = baus->root;
while( *baue != NULL and compare_result != 0 )
{
compare_result = key_compare_function( key, (*baue)->key );
if( compare_result < 0 )
*baue = (*baue)->left;
if( compare_result > 0 )
*baue = (*baue)->right;
}
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_RELEASE( baus->lock );
if( *baue == NULL )
rv = 0;
return rv;
}
/****************************************************************************/
int libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_absolute_position_for_read( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue, enum libbenchmark_datastructure_btree_au_pthread_rwlock_absolute_position absolute_position )
{
int
rv = 1;
LFDS711_PAL_ASSERT( baus != NULL );
LFDS711_PAL_ASSERT( baue != NULL );
// TRD : absolute_position can be any value in its range
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_GET_READ( baus->lock );
*baue = baus->root;
switch( absolute_position )
{
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_ABSOLUTE_POSITION_ROOT:
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_ABSOLUTE_POSITION_LARGEST_IN_TREE:
if( *baue != NULL )
while( (*baue)->right != NULL )
*baue = (*baue)->right;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_ABSOLUTE_POSITION_SMALLEST_IN_TREE:
if( *baue != NULL )
while( (*baue)->left != NULL )
*baue = (*baue)->left;
break;
}
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_RELEASE( baus->lock );
if( *baue == NULL )
rv = 0;
return rv;
}
/****************************************************************************/
int libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_relative_position_for_read( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue, enum libbenchmark_datastructure_btree_au_pthread_rwlock_relative_position relative_position )
{
int
rv = 1;
LFDS711_PAL_ASSERT( baus != NULL );
LFDS711_PAL_ASSERT( baue != NULL );
// TRD : relative_position can baue any value in its range
if( *baue == NULL )
return 0;
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_GET_READ( baus->lock );
switch( relative_position )
{
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_UP:
*baue = (*baue)->up;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_LEFT:
*baue = (*baue)->left;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_RIGHT:
*baue = (*baue)->right;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_SMALLEST_ELEMENT_BELOW_CURRENT_ELEMENT:
*baue = (*baue)->left;
if( *baue != NULL )
while( (*baue)->right != NULL )
*baue = (*baue)->right;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_LARGEST_ELEMENT_BELOW_CURRENT_ELEMENT:
*baue = (*baue)->right;
if( *baue != NULL )
while( (*baue)->left != NULL )
*baue = (*baue)->left;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_NEXT_SMALLER_ELEMENT_IN_ENTIRE_TREE:
libbenchmark_datastructure_btree_au_internal_inorder_walk_from_largest_get_next_smallest_element( baus, baue );
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_PTHREAD_RWLOCK_RELATIVE_POSITION_NEXT_LARGER_ELEMENT_IN_ENTIRE_TREE:
libbenchmark_datastructure_btree_au_internal_inorder_walk_from_smallest_get_next_largest_element( baus, baue );
break;
}
LIBBENCHMARK_PAL_LOCK_PTHREAD_RWLOCK_RELEASE( baus->lock );
if( *baue == NULL )
rv = 0;
return rv;
}
/****************************************************************************/
#pragma warning( disable : 4100 )
static void libbenchmark_datastructure_btree_au_internal_inorder_walk_from_largest_get_next_smallest_element( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue )
{
enum libbenchmark_datastructure_btree_au_move
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_INVALID;
enum flag
finished_flag = LOWERED;
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element
*left = NULL,
*up = NULL,
*up_left = NULL,
*up_right = NULL;
LFDS711_PAL_ASSERT( baus != NULL );
LFDS711_PAL_ASSERT( baue != NULL );
/* TRD : from any given element, the next smallest element is;
1. if we have a left, it's the largest element on the right branch of our left child
2. if we don't have a left, and we're on the right of our parent, then it's our parent
3. if we don't have a left, and we're on the left of our parent or we have no parent,
iterative up the tree until we find the first child who is on the right of its parent; then it's the parent
*/
left = (*baue)->left;
up = (*baue)->up;
if( up != NULL )
{
up_left = (*baue)->up->left;
up_right = (*baue)->up->right;
}
if( left != NULL )
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_LARGEST_FROM_LEFT_CHILD;
if( left == NULL and up != NULL and up_right == *baue )
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_GET_PARENT;
if( (left == NULL and up == NULL) or (up != NULL and up_left == *baue and left == NULL) )
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_MOVE_UP_TREE;
switch( action )
{
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_INVALID:
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_SMALLEST_FROM_RIGHT_CHILD:
// TRD : eliminates a compiler warning
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_LARGEST_FROM_LEFT_CHILD:
*baue = left;
if( *baue != NULL )
while( (*baue)->right != NULL )
*baue = (*baue)->right;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_GET_PARENT:
*baue = up;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_MOVE_UP_TREE:
while( finished_flag == LOWERED )
{
up = (*baue)->up;
if( up != NULL )
up_left = (*baue)->up->left;
if( *baue != NULL and up != NULL and *baue == up_left )
*baue = up;
else
finished_flag = RAISED;
}
*baue = up;
break;
}
return;
}
#pragma warning( default : 4100 )
/****************************************************************************/
#pragma warning( disable : 4100 )
static void libbenchmark_datastructure_btree_au_internal_inorder_walk_from_smallest_get_next_largest_element( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue )
{
enum libbenchmark_datastructure_btree_au_move
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_INVALID;
enum flag
finished_flag = LOWERED;
struct libbenchmark_datastructure_btree_au_pthread_rwlock_element
*right = NULL,
*up = NULL,
*up_left = NULL,
*up_right = NULL;
LFDS711_PAL_ASSERT( baus != NULL );
LFDS711_PAL_ASSERT( baue != NULL );
right = (*baue)->right;
up = (*baue)->up;
if( up != NULL )
{
up_left = (*baue)->up->left;
up_right = (*baue)->up->right;
}
if( right != NULL )
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_SMALLEST_FROM_RIGHT_CHILD;
if( right == NULL and up != NULL and up_left == *baue )
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_GET_PARENT;
if( (right == NULL and up == NULL) or (up != NULL and up_right == *baue and right == NULL) )
action = LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_MOVE_UP_TREE;
switch( action )
{
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_INVALID:
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_LARGEST_FROM_LEFT_CHILD:
// TRD : remove compiler warning
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_SMALLEST_FROM_RIGHT_CHILD:
*baue = right;
if( *baue != NULL )
while( (*baue)->left != NULL )
*baue = (*baue)->left;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_GET_PARENT:
*baue = up;
break;
case LIBBENCHMARK_DATASTRUCTURE_BTREE_AU_MOVE_MOVE_UP_TREE:
while( finished_flag == LOWERED )
{
up = (*baue)->up;
if( up != NULL )
up_right = (*baue)->up->right;
if( *baue != NULL and up != NULL and *baue == up_right )
*baue = up;
else
finished_flag = RAISED;
}
*baue = up;
break;
}
return;
}
#pragma warning( default : 4100 )
/****************************************************************************/
int libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_absolute_position_and_then_by_relative_position( struct libbenchmark_datastructure_btree_au_pthread_rwlock_state *baus, struct libbenchmark_datastructure_btree_au_pthread_rwlock_element **baue, enum libbenchmark_datastructure_btree_au_pthread_rwlock_absolute_position absolute_position, enum libbenchmark_datastructure_btree_au_pthread_rwlock_relative_position relative_position )
{
int
rv;
LFDS711_PAL_ASSERT( baus != NULL );
LFDS711_PAL_ASSERT( baue != NULL );
// TRD: absolute_position can be any value in its range
// TRD: relative_position can be any value in its range
if( *baue == NULL )
rv = libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_absolute_position_for_read( baus, baue, absolute_position );
else
rv = libbenchmark_datastructure_btree_au_pthread_rwlock_get_by_relative_position_for_read( baus, baue, relative_position );
return rv;
}
| 2.3125 | 2 |
2024-11-18T22:25:42.700248+00:00 | 2020-03-05T02:04:55 | 9dd0519dfa4400cb72d3a6e925d3f66b97a77efb | {
"blob_id": "9dd0519dfa4400cb72d3a6e925d3f66b97a77efb",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-05T02:04:55",
"content_id": "307b99a78d11e2e8346b92b7ec8f22c3fde0ff5a",
"detected_licenses": [
"MIT"
],
"directory_id": "243ae6949c7400cd0abf22361b7a05a757a4fa71",
"extension": "c",
"filename": "ft_strjoin.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 244536351,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1330,
"license": "MIT",
"license_type": "permissive",
"path": "/ft_strjoin.c",
"provenance": "stackv2-0115.json.gz:135967",
"repo_name": "mferoc/libft",
"revision_date": "2020-03-05T02:04:55",
"revision_id": "4f062e97a390ba4228006b75b28b180bba656268",
"snapshot_id": "e18b932448eaaa6a2ce6f6ada18a61fdba16e7f6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mferoc/libft/4f062e97a390ba4228006b75b28b180bba656268/ft_strjoin.c",
"visit_date": "2022-04-06T19:48:36.791958"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strjoin.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mathferr <mathferr@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/10 16:55:27 by mathferr #+# #+# */
/* Updated: 2020/02/13 15:59:29 by mathferr ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strjoin(char const *s1, char const *s2)
{
char *str_joined;
str_joined = NULL;
if (s1 && s2)
str_joined = malloc(ft_strlen(s1) + ft_strlen(s2) + 1);
if (str_joined == NULL)
return (NULL);
else
{
ft_strcpy(str_joined, (char *)s1);
ft_strcat(str_joined, (char *)s2);
}
return (str_joined);
}
/*
**int main(void)
**{
** printf("%s\n", ft_strjoin("Brasil", "-COMUNISTA"));
** return (0);
**}
*/
| 2.9375 | 3 |
2024-11-18T22:25:42.965273+00:00 | 2015-03-15T20:50:28 | 5db2c1d6943da84107b615266a8a3b41c41812eb | {
"blob_id": "5db2c1d6943da84107b615266a8a3b41c41812eb",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-15T20:50:28",
"content_id": "5394ef65c9766192c40d7e32ae9eb92a4393d09c",
"detected_licenses": [
"Zlib"
],
"directory_id": "692c18b8e6dbd4925d151e08b167333da344176d",
"extension": "c",
"filename": "LL.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32283281,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1565,
"license": "Zlib",
"license_type": "permissive",
"path": "/modules/mod_chipmunk.new/LL.c",
"provenance": "stackv2-0115.json.gz:136354",
"repo_name": "google-code/bennugd-monolithic",
"revision_date": "2015-03-15T20:50:28",
"revision_id": "96eb4faa4ce81715be90bac92a4427c1f6ec5682",
"snapshot_id": "870b5cfdec63269fa5acf8785bfe8145cd178a58",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/google-code/bennugd-monolithic/96eb4faa4ce81715be90bac92a4427c1f6ec5682/modules/mod_chipmunk.new/LL.c",
"visit_date": "2016-08-07T04:04:15.674097"
} | stackv2 | #include "LL.h"
//#include <stdio.h>
void LLinicializa(nodo ** n){
*n= malloc(sizeof(nodo));
(*n)->elem=NULL;
(*n)->sig=NULL;
}
void LLagrega(nodo * n, void * p){
nodo * sig=n->sig;
n->sig= malloc(sizeof(nodo));
n->sig->elem=p;
n->sig->sig=sig;
}
void LLelimina(nodo * n,void * am, funCom r, funcionElm funEl,int hFree){
for(;n->sig!=NULL;n=n->sig){
if (r(am,n->sig->elem)){
nodo * sig = n->sig->sig;
funEl(n->sig->elem);
if (hFree)
free(n->sig);
n->sig=sig;
if (n->sig==NULL)
return;
}
}
}
void * LLbusca(nodo * n,void * bm, funCom r){
for(;n->sig!=NULL;n=n->sig){
if (r(bm,n->sig->elem)){
// printf("busca %d %d\n",n->sig->elem, bm); fflush(stdout);
return n->sig->elem;
}
}
return NULL;
}
void LLeliminaTodo(nodo * n,funcionElm funEl,int hFree){
while(n!=NULL && n->sig!=NULL){
nodo * sig = n->sig->sig;
funEl(n->sig->elem);
if (hFree){
free(n->sig);
n->sig=sig;
}
}
free(n);
}
void LLimprime(nodo * n){
if (n==NULL){
printf("Lista vacia \n");
return;
}
printf("____________________________\n");fflush(stdout);
for(;n->sig!=NULL;n=n->sig){
printf("%d\n",n->sig->elem);fflush(stdout);
}
printf("____________________________\n");fflush(stdout);
}
| 3.125 | 3 |
2024-11-18T22:25:43.024330+00:00 | 2021-11-16T11:31:36 | 2e19c2773cac9e5d29654111f82d5a46cb31cc3d | {
"blob_id": "2e19c2773cac9e5d29654111f82d5a46cb31cc3d",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-16T11:31:36",
"content_id": "7efd4d897027182a5ce0b28ebe05e8ce71e65e0a",
"detected_licenses": [
"MIT"
],
"directory_id": "8511cb21a347b558883a68deed5c3a1f4a9610ac",
"extension": "c",
"filename": "8_1.c",
"fork_events_count": 0,
"gha_created_at": "2021-03-08T19:56:36",
"gha_event_created_at": "2021-11-16T11:31:36",
"gha_language": "C",
"gha_license_id": null,
"github_id": 345778097,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 858,
"license": "MIT",
"license_type": "permissive",
"path": "/archiwum_pp2/8_1.c",
"provenance": "stackv2-0115.json.gz:136482",
"repo_name": "maresyp/dante_pp2",
"revision_date": "2021-11-16T11:31:36",
"revision_id": "42d91e144cb2193a7eb7ea1a4e80f3a8ad59fb3a",
"snapshot_id": "65974ff5eddf382ff79b324b71ce91daa6b482b0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/maresyp/dante_pp2/42d91e144cb2193a7eb7ea1a4e80f3a8ad59fb3a/archiwum_pp2/8_1.c",
"visit_date": "2023-09-04T10:07:58.623644"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int is_equal(int a, int b) {
return !(a ^ b);
}
int is_negative(int value) {
if (is_equal(0, value)) return 0;
int tmp = (value & 0x80000000);
if (is_equal(tmp, 0)) return 0;
return 1;
}
int main(){
printf("zapodaj:\n");
int a,b;
if (!(is_equal(scanf("%d %d", &a, &b), 2))) {
printf("Incorrect input");
return 1;
} else {
int res = is_equal(a, b);
if (is_equal(res, 0)) {
printf("nierowne\n");
} else {
printf("rowne\n");
}
if (!is_negative(a)) {
printf("nieujemna ");
} else {
printf("ujemna ");
}
if (!is_negative(b)) {
printf("nieujemna");
} else {
printf("ujemna");
}
}
return 0;
}
| 3.375 | 3 |
2024-11-18T22:25:43.147815+00:00 | 2017-01-25T08:04:24 | f34fdb79d985bb7a639f04a6d4b993e69a0780f6 | {
"blob_id": "f34fdb79d985bb7a639f04a6d4b993e69a0780f6",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-25T08:04:24",
"content_id": "0aedec0ffac11bee74c682696778fb4ff0f9650b",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "83cf56fcc0f38e70a473831d0d1ce5d6e2872a53",
"extension": "c",
"filename": "CODE_LIST.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 84274162,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 405,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Hackathon_170108_图形化物联网开发平台_凌梦团队/USER/CODE_LIST.c",
"provenance": "stackv2-0115.json.gz:136739",
"repo_name": "cxh0806/LiteOS_Hackathon",
"revision_date": "2017-01-25T08:04:24",
"revision_id": "a5fbcf664b582b1f9288acba488a58ea3d3a3110",
"snapshot_id": "43b98c6e2744b94262bc5cf63e1cd14d6cbf0f00",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cxh0806/LiteOS_Hackathon/a5fbcf664b582b1f9288acba488a58ea3d3a3110/Hackathon_170108_图形化物联网开发平台_凌梦团队/USER/CODE_LIST.c",
"visit_date": "2021-06-10T09:17:57.578065"
} | stackv2 |
#include "typedef.h"
uint16 InsDisc_CurrentIndex;
#define MaxNumber 30000
uint8 ByteCodeList[MaxNumber];
void CODE_Start()
{
InsDisc_CurrentIndex = 0;
}
void CODE_AddIns( uint8 ins )
{
ByteCodeList[InsDisc_CurrentIndex] = ins;
++InsDisc_CurrentIndex;
}
uint8 CODE_ReadIns( uint16 addr )
{
return ByteCodeList[addr];
}
void CODE_Save()
{
}
void CODE_Load()
{
}
| 2.0625 | 2 |
2024-11-18T22:25:43.336696+00:00 | 2021-06-06T19:16:29 | cdbd9a17dd30db6c820775ef9f4ccd83ca8ef766 | {
"blob_id": "cdbd9a17dd30db6c820775ef9f4ccd83ca8ef766",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-06T19:16:29",
"content_id": "d4f855e8f76426846dde2a164b2c7c6b16dd0171",
"detected_licenses": [
"MIT"
],
"directory_id": "22315e5a136669b01aac65ade2dbe97f33eaff36",
"extension": "c",
"filename": "program to calculate how many refuelings are needed in a speedway.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 280022226,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1186,
"license": "MIT",
"license_type": "permissive",
"path": "/[06 2020]logic and algorithm and programming lab I/exercises/program to calculate how many refuelings are needed in a speedway.c",
"provenance": "stackv2-0115.json.gz:136999",
"repo_name": "frigo-augusto/College-work-and-exercises",
"revision_date": "2021-06-06T19:16:29",
"revision_id": "ce0bdce125dde2b67783e0c1bfe1f4797cb80e0d",
"snapshot_id": "67be3d503822006ef4331029dede26d9155f17f0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/frigo-augusto/College-work-and-exercises/ce0bdce125dde2b67783e0c1bfe1f4797cb80e0d/[06 2020]logic and algorithm and programming lab I/exercises/program to calculate how many refuelings are needed in a speedway.c",
"visit_date": "2023-05-24T06:06:06.154386"
} | stackv2 | #include <stdio.h>
int main()
{
printf ("program to calculate how many refuelings are needed in a speedway");
int speedway, laps, consumption, refueling, totalm, totall, minkm;
printf ("speedway laps, consumption and refuelings calcultaor\n");
printf ("what is the lenght of the speedway?\n");
scanf ("%d", &speedway);
printf("how many laps will be completed?\n");
scanf ("%d", &laps);
printf("what is the consumption of the car in km/l?");
scanf ("%d", &consumption);
printf ("how many refuelings are wanted?");
scanf ("%d", &refueling);
totalm = laps * speedway;
totall = (totalm / 1000)/ (consumption);
minkm = totall % refueling;
if (totalm/1000 > consumption && minkm > 0)
{
printf ("is necessary go through %d km until refuel the first time", minkm);
}
else if (totalm/1000 > consumption)
{
printf ("0 km until the refuel");
}
else if (consumption * refueling < totalm/1000)
{
printf ("insufficient refuel");
}
else
{
printf ("refuelings are not necessary");
}
printf ("\nend of program execution");
return 0;
} | 3.21875 | 3 |
2024-11-18T22:25:43.672825+00:00 | 2021-09-17T08:36:52 | cb8f4d4838516b27d864725a77bc592a744a0b2c | {
"blob_id": "cb8f4d4838516b27d864725a77bc592a744a0b2c",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-17T08:36:52",
"content_id": "836088514071ecb7f84b883e8620686ffd4c8dc7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "00d7d20e73da531690c6b851b07e83dfa86810b6",
"extension": "c",
"filename": "fork.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 116935096,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2128,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/fork.c",
"provenance": "stackv2-0115.json.gz:137127",
"repo_name": "carstenmichel/forktester",
"revision_date": "2021-09-17T08:36:52",
"revision_id": "e74f96cdf3167e4ada950ddf1c047386942e988d",
"snapshot_id": "2d2c9bab4c3d50469756605656b21f048f3e2bba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/carstenmichel/forktester/e74f96cdf3167e4ada950ddf1c047386942e988d/src/fork.c",
"visit_date": "2021-11-23T10:37:27.310991"
} | stackv2 | #include "config.h"
#include <stdio.h>
#include <errno.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <sys/wait.h>
void checkIfFunctionsDoExist()
{
#ifndef HAVE_GETTIMEOFDAY
printf("getTimeOfDay not supported");
exit(1);
#endif
#ifndef HAVE_STRERROR
printf("strerr not supported");
exit(2);
#endif
#ifndef HAVE_UNISTD_H
printf("Fork not supported");
exit(3);
#endif
}
void firstTest()
{
FILE *fd;
int charactersWritten = 0;
int returnCode = 0xff;
struct timeval first, second;
fd = fopen("test.txt", "w");
charactersWritten = fprintf(fd, "Hello World!\n");
gettimeofday(&first, NULL);
returnCode = fclose(fd);
gettimeofday(&second, NULL);
printf("First close took %d \n", second.tv_usec - first.tv_usec);
if (returnCode == 0)
{
printf("First close was successfull\n");
}
else
{
printf("First close was *NOT* ok \n");
}
// Start to manipulate the file pointer to prevent the gcc optimizer to suppress the 2nd close
int tempCounter = 0xff;
tempCounter = fd->_blksize;
fd->_blksize=0;
fd->_blksize=tempCounter;
// End of magic
gettimeofday(&first, NULL);
returnCode = fclose(fd);
gettimeofday(&second, NULL);
printf("Second close took %d \n", second.tv_usec - first.tv_usec);
if (returnCode == 0)
{
printf("Second close was successfull\n");
}
else
{
printf("Second close was *NOT* ok with %d \n", returnCode);
printf("Errno is %d\n", errno);
char *text = strerror((int)errno);
printf("Error string is %s \n", text);
}
}
void runInFork()
{
pid_t pid = 0xff;
pid = fork();
if (pid == 0)
{
// CHILD
printf("Starting Child\n");
firstTest();
}
else
{
//PARENT
printf("Start waiting for Child\n");
wait(NULL);
printf("Finished waiting for Child\n");
}
}
int main()
{
checkIfFunctionsDoExist();
runInFork();
} | 3.078125 | 3 |
2024-11-18T22:25:43.797577+00:00 | 2019-07-17T18:07:00 | c2425abaf54fc0c9e7870b4204256c7fecc5bcd9 | {
"blob_id": "c2425abaf54fc0c9e7870b4204256c7fecc5bcd9",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-17T18:07:00",
"content_id": "95130d6187f1b1036bd8570cb4b4a54c905f3f2b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ebd0599202440b48ec980b54efb7c2a57898fe38",
"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": 197451593,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1813,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/duck/main.c",
"provenance": "stackv2-0115.json.gz:137387",
"repo_name": "stevenleeg/tomu-ducky",
"revision_date": "2019-07-17T18:07:00",
"revision_id": "c2fcddc1f7425701081148392c64ae5bfc941d32",
"snapshot_id": "9214f64a991d2dd1c6ab3fb7d1a6fa73d2c4b6ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/stevenleeg/tomu-ducky/c2fcddc1f7425701081148392c64ae5bfc941d32/duck/main.c",
"visit_date": "2020-06-21T12:31:09.008556"
} | stackv2 | #include <libopencm3/cm3/common.h>
#include <libopencm3/cm3/vector.h>
#include <libopencm3/cm3/scb.h>
#include <libopencm3/cm3/systick.h>
#include <libopencm3/efm32/wdog.h>
#include <libopencm3/efm32/gpio.h>
#include <libopencm3/efm32/cmu.h>
#include <stdbool.h>
#include <stdio.h>
#include <toboot.h>
TOBOOT_CONFIGURATION(0);
#define SYSTICK_FREQUENCY 1000
#define USB_CLK_FREQUENCY 24000000
#define LED_GREEN_PORT GPIOA
#define LED_GREEN_PIN GPIO0
#define LED_RED_PORT GPIOB
#define LED_RED_PIN GPIO7
uint32_t millis = 0;
bool prev_value = false;
void sys_tick_handler(void) {
// Start with the green LED turned on, so the two toggle
if (millis == 0) {
gpio_toggle(LED_GREEN_PORT, LED_GREEN_PIN);
}
millis++;
if (millis % 1000 == 0 && prev_value) {
gpio_toggle(LED_RED_PORT, LED_RED_PIN);
prev_value = !prev_value;
} else if (millis % 1000 == 0 && !prev_value) {
gpio_toggle(LED_GREEN_PORT, LED_GREEN_PIN);
prev_value = !prev_value;
}
}
int main(int argc, char **argv) {
(void) argc;
(void) argv;
// Disable watchdog, letting the Tomu know that the program is running and
// it doesn't need to reboot
WDOG_CTRL = 0;
cmu_periph_clock_enable(CMU_GPIO);
// Setup our ports
gpio_mode_setup(LED_RED_PORT, GPIO_MODE_WIRED_AND, LED_RED_PIN);
gpio_mode_setup(LED_GREEN_PORT, GPIO_MODE_WIRED_AND, LED_GREEN_PIN);
// I have no idea what's going on here
cmu_osc_on(USHFRCO);
cmu_wait_for_osc_ready(USHFRCO);
CMU_USBCRCTRL = CMU_USBCRCTRL_EN;
CMU_CMD = CMU_CMD_HFCLKSEL(5);
while (!(CMU_STATUS & CMU_STATUS_USHFRCODIV2SEL));
systick_set_frequency(SYSTICK_FREQUENCY, USB_CLK_FREQUENCY);
systick_counter_enable();
systick_interrupt_enable();
while (1);
}
| 2.28125 | 2 |
2024-11-18T22:25:44.162275+00:00 | 2015-01-20T16:16:25 | 1bd1f2a19724c316ac1f54268c642e28f483cfd2 | {
"blob_id": "1bd1f2a19724c316ac1f54268c642e28f483cfd2",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-20T16:16:25",
"content_id": "c0457154be334d165bb95411def0696ab1442d78",
"detected_licenses": [
"MIT"
],
"directory_id": "bce31cc1f6d64a9a564d6466ba1a603bf6895a6b",
"extension": "c",
"filename": "zad5.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 23259123,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1691,
"license": "MIT",
"license_type": "permissive",
"path": "/microcontroller_network_applications/lab2/zad5.c",
"provenance": "stackv2-0115.json.gz:137646",
"repo_name": "piotrgiedziun/university",
"revision_date": "2015-01-20T16:16:25",
"revision_id": "93097f071d592ad3d70b4c8cf1311498b5e1df3c",
"snapshot_id": "30b6344f64d72e1809d206de444896387a47d6df",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/piotrgiedziun/university/93097f071d592ad3d70b4c8cf1311498b5e1df3c/microcontroller_network_applications/lab2/zad5.c",
"visit_date": "2016-09-06T06:46:40.224827"
} | stackv2 | /**
* arduino duemilanove - atmega328p
* ================================
* This code will blink built-in LED (PB5 - pin 13) and external LED (PB4 - pin 12)
* Timer1 is 16 bytes so you can count 16000 times (cuz max is 65535 > 16000)
* but Timer2 is 8 bytes so you cant count up to 16000 times (255 is maximum value),
* so in order to use it as 1 ms interrupt you have to slow it 256 times.
* This way you will be counting from 0xFF-62.
* ================================
* Schematic: http://arduino.cc/en/uploads/Main/arduino-duemilanove-schematic.pdf
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#define LED PB5
#define LED2 PB4
// TIMER1 - 16 bits -> 65535 max
#define TIMER_START 0xFFFF-16000
// TIMER2 - 8 bit -> 255 max
#define TIMER2_START 0xFF-62
volatile int counter = 0;
volatile int counter2 = 0;
int main()
{
DDRB = 0xFFFF;
// SET TIMER COUNT
TCNT1 = TIMER_START;
TCNT2 = TIMER2_START;
// ENABLE OVERFLOW INTERRUPT
TIMSK1 = (1 << TOIE1);
TIMSK2 = (1 << TOIE2);
// ENABLE INTERRUPT
sei();
// CONFIGURE TIMER 1
TCCR1A = 0x00; // NORMAL
TCCR1B = _BV(CS10); // clkI/O/1 (No prescaling)
TCCR1C = 0x00; // COUNTER
// CONFIGURE TIMER 2
TCCR2A = 0x00; // NORMAL
TCCR2B = _BV(CS22) | _BV(CS21); // 256 TIMES SLOWER
while(1);
return 0;
}
ISR(TIMER2_OVF_vect) {
// SET TIMER2 COUNT
TCNT2 = TIMER2_START;
counter2++;
if (counter2 == 1000) {
PORTB |= _BV(LED2);
}else if (counter == 2000) {
counter2 = 0;
PORTB &= ~_BV(LED2);
}
}
ISR(TIMER1_OVF_vect) {
// SET TIMER COUNT
TCNT1 = TIMER_START;
counter++;
if (counter == 1000) {
PORTB |= _BV(LED);
}else if (counter == 2000) {
counter = 0;
PORTB &= ~_BV(LED);
}
} | 3.15625 | 3 |
2024-11-18T22:25:44.212775+00:00 | 2020-07-11T04:22:05 | 71f4c4a86b54e53d6625c5ccdca69bd1686b3f1d | {
"blob_id": "71f4c4a86b54e53d6625c5ccdca69bd1686b3f1d",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-11T04:24:55",
"content_id": "9388bedbe29551937885fad843beecc621ba4c4a",
"detected_licenses": [
"MIT"
],
"directory_id": "1a8e5836442c28d408c5ce75bcf65436d4462b6d",
"extension": "c",
"filename": "dijkstra.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": 1906,
"license": "MIT",
"license_type": "permissive",
"path": "/homework/hw5_parallel_sssp/dijkstra.c",
"provenance": "stackv2-0115.json.gz:137775",
"repo_name": "kuailehaha/CS110",
"revision_date": "2020-07-11T04:22:05",
"revision_id": "aa9f4d3b77387c3d39bc91b4a0f4689fbf9f6baa",
"snapshot_id": "1871eb90f053e744f02932de0f3e03feb48504ed",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kuailehaha/CS110/aa9f4d3b77387c3d39bc91b4a0f4689fbf9f6baa/homework/hw5_parallel_sssp/dijkstra.c",
"visit_date": "2022-11-13T00:09:32.819339"
} | stackv2 | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "global.h"
/* Find nearest not yet visited node */
static unsigned nearest(unsigned *dist, bool *visited)
{
unsigned min = INF, index = 0;
/* Iterate through dist to find nearest node on the frontier */
for (unsigned i = 0; i < n; i++)
if (!visited[i] && dist[i] < min)
min = dist[i], index = i;
return index;
}
/* Update distance to source if new path is shorter */
static void relax(unsigned *dist, unsigned *pred, unsigned u, unsigned v)
{
/* Set temp to INF at overflow */
unsigned temp = saturating_add(dist[u], c[u][v]);
if (temp < dist[v])
{
/* Update distance to source if new path is shorter */
dist[v] = temp;
pred[v] = u;
}
}
/* Sequential dijkstra algorithm */
void dijkstra()
{
/* Distance from source to all nodes, initialized to infinity */
unsigned *dist = malloc(sizeof(unsigned) * n);
unsigned *pred = malloc(sizeof(unsigned) * n);
bool *visited = calloc(n, sizeof(bool));
/* Initialize distance from source to other nodes as infinity, itself as 0 */
memset(dist, 0xff, sizeof(unsigned) * n);
dist[s] = 0;
/* Loop */
for (unsigned i = 0; i < n - 1; i++)
{
/* Find nearest not yet visited node */
unsigned u = nearest(dist, visited);
/* Add node to visited */
visited[u] = true;
/* Terminal node is found, exit early */
if (u == t)
break;
/* Update node u's neighbors */
for (unsigned v = 0; v < n; v++)
relax(dist, pred, u, v);
}
/* Print distance of shortest path from s to t */
printf("%u\n", dist[t]);
/* Print route from s to t */
print_route(pred, t);
printf("%u\n", t);
/* Free allocated memory */
free(dist), free(pred), free(visited);
}
| 3.234375 | 3 |
2024-11-18T22:25:44.372627+00:00 | 2017-06-03T12:26:04 | 9e83ab0bfeebd9a3e468433196be04ae6464bf37 | {
"blob_id": "9e83ab0bfeebd9a3e468433196be04ae6464bf37",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-03T12:26:04",
"content_id": "03d58972e8786fce9d0b3581fa4ec5601277d78e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3839a59d66f65daaaf9f8f12ed1952223ecc116c",
"extension": "c",
"filename": "lifo.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 80175240,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2544,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/kernel/unified/lifo.c",
"provenance": "stackv2-0115.json.gz:138036",
"repo_name": "Jason0204/jasontek_f103rb-zephyrOS-project",
"revision_date": "2017-06-03T12:26:04",
"revision_id": "21f354f9f0f13ff5f9fe0ed4236fa79635068591",
"snapshot_id": "74e7863222c05e10f30a1c8951c43af60bc57baf",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Jason0204/jasontek_f103rb-zephyrOS-project/21f354f9f0f13ff5f9fe0ed4236fa79635068591/kernel/unified/lifo.c",
"visit_date": "2021-01-11T14:37:16.982857"
} | stackv2 | /*
* Copyright (c) 2010-2015 Wind River Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** @file
*
* @brief dynamic-size LIFO queue object
*/
#include <kernel.h>
#include <kernel_structs.h>
#include <misc/debug/object_tracing_common.h>
#include <toolchain.h>
#include <sections.h>
#include <wait_q.h>
#include <ksched.h>
#include <init.h>
extern struct k_lifo _k_lifo_list_start[];
extern struct k_lifo _k_lifo_list_end[];
struct k_lifo *_trace_list_k_lifo;
#ifdef CONFIG_DEBUG_TRACING_KERNEL_OBJECTS
/*
* Complete initialization of statically defined lifos.
*/
static int init_lifo_module(struct device *dev)
{
ARG_UNUSED(dev);
struct k_lifo *lifo;
for (lifo = _k_lifo_list_start; lifo < _k_lifo_list_end; lifo++) {
SYS_TRACING_OBJ_INIT(k_lifo, lifo);
}
return 0;
}
SYS_INIT(init_lifo_module, PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_OBJECTS);
#endif /* CONFIG_DEBUG_TRACING_KERNEL_OBJECTS */
void k_lifo_init(struct k_lifo *lifo)
{
lifo->list = (void *)0;
sys_dlist_init(&lifo->wait_q);
SYS_TRACING_OBJ_INIT(k_lifo, lifo);
}
void k_lifo_put(struct k_lifo *lifo, void *data)
{
struct k_thread *first_pending_thread;
unsigned int key;
key = irq_lock();
first_pending_thread = _unpend_first_thread(&lifo->wait_q);
if (first_pending_thread) {
_abort_thread_timeout(first_pending_thread);
_ready_thread(first_pending_thread);
_set_thread_return_value_with_data(first_pending_thread,
0, data);
if (!_is_in_isr() && _must_switch_threads()) {
(void)_Swap(key);
return;
}
} else {
*(void **)data = lifo->list;
lifo->list = data;
}
irq_unlock(key);
}
void *k_lifo_get(struct k_lifo *lifo, int32_t timeout)
{
unsigned int key;
void *data;
key = irq_lock();
if (likely(lifo->list)) {
data = lifo->list;
lifo->list = *(void **)data;
irq_unlock(key);
return data;
}
if (timeout == K_NO_WAIT) {
irq_unlock(key);
return NULL;
}
_pend_current_thread(&lifo->wait_q, timeout);
return _Swap(key) ? NULL : _current->base.swap_data;
}
| 2.03125 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.