added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T20:55:35.233904+00:00 | 2018-02-22T18:48:04 | bcc530110493cb41efa79d245faddb70f970eebc | {
"blob_id": "bcc530110493cb41efa79d245faddb70f970eebc",
"branch_name": "refs/heads/enlightenment-0.17",
"committer_date": "2018-02-22T18:48:04",
"content_id": "db7dfc2e2238c377144188d18f8f96059e77d919",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "63aa1f1eaa6ee94031915cc147ffc93b82159118",
"extension": "c",
"filename": "e_mod_main.c",
"fork_events_count": 1,
"gha_created_at": "2016-09-06T05:09:03",
"gha_event_created_at": "2019-09-15T07:28:45",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 67475285,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3235,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/modules/illume-keyboard/e_mod_main.c",
"provenance": "stackv2-0092.json.gz:41887",
"repo_name": "Elive/enlightenment",
"revision_date": "2018-02-22T18:48:04",
"revision_id": "0a5ff4bd5adea88f70347354eabd93fdad63eed6",
"snapshot_id": "87bfb5e621b0bd1a2f5f84d34f89df0998882aa2",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Elive/enlightenment/0a5ff4bd5adea88f70347354eabd93fdad63eed6/src/modules/illume-keyboard/e_mod_main.c",
"visit_date": "2023-07-18T16:06:47.018484"
} | stackv2 | #include "e.h"
#include "e_mod_main.h"
#include "e_mod_config.h"
#include "e_kbd_int.h"
/* local function prototypes */
static void _il_kbd_stop(void);
static void _il_kbd_start(void);
static Eina_Bool _il_kbd_cb_exit(void *data, int type, void *event);
/* local variables */
static E_Kbd_Int *ki = NULL;
static Ecore_Exe *_kbd_exe = NULL;
static Ecore_Event_Handler *_kbd_exe_exit_handler = NULL;
EAPI E_Module_Api e_modapi = { E_MODULE_API_VERSION, "Illume Keyboard" };
EAPI void *
e_modapi_init(E_Module *m)
{
if (!il_kbd_config_init(m)) return NULL;
_il_kbd_start();
e_module_delayed_set(m, 1);
return m;
}
EAPI int
e_modapi_shutdown(E_Module *m __UNUSED__)
{
_il_kbd_stop();
il_kbd_config_shutdown();
return 1;
}
EAPI int
e_modapi_save(E_Module *m __UNUSED__)
{
return il_kbd_config_save();
}
EAPI void
il_kbd_cfg_update(void)
{
_il_kbd_stop();
_il_kbd_start();
}
static void
_il_kbd_stop(void)
{
if (ki) e_kbd_int_free(ki);
ki = NULL;
if (_kbd_exe) ecore_exe_interrupt(_kbd_exe);
_kbd_exe = NULL;
if (_kbd_exe_exit_handler) ecore_event_handler_del(_kbd_exe_exit_handler);
_kbd_exe_exit_handler = NULL;
}
static void
_il_kbd_start(void)
{
if (il_kbd_cfg->use_internal)
{
ki = e_kbd_int_new(il_kbd_cfg->mod_dir,
il_kbd_cfg->mod_dir, il_kbd_cfg->mod_dir);
}
else if (il_kbd_cfg->run_keyboard)
{
E_Exec_Instance *inst;
Efreet_Desktop *desktop;
desktop = efreet_util_desktop_file_id_find(il_kbd_cfg->run_keyboard);
if (!desktop)
{
Efreet_Desktop *d;
Eina_List *kbds, *l;
kbds = efreet_util_desktop_category_list("Keyboard");
if (kbds)
{
EINA_LIST_FOREACH(kbds, l, d)
{
const char *dname;
dname = ecore_file_file_get(d->orig_path);
if (dname)
{
if (!strcmp(dname, il_kbd_cfg->run_keyboard))
{
desktop = d;
efreet_desktop_ref(desktop);
break;
}
}
}
EINA_LIST_FREE(kbds, d)
efreet_desktop_free(d);
}
}
if (desktop)
{
E_Zone *zone;
zone = e_util_zone_current_get(e_manager_current_get());
inst = e_exec(zone, desktop, NULL, NULL, "illume-keyboard");
if (inst)
{
_kbd_exe = inst->exe;
_kbd_exe_exit_handler =
ecore_event_handler_add(ECORE_EXE_EVENT_DEL,
_il_kbd_cb_exit, NULL);
}
efreet_desktop_free(desktop);
}
}
}
static Eina_Bool
_il_kbd_cb_exit(void *data __UNUSED__, int type __UNUSED__, void *event)
{
Ecore_Exe_Event_Del *ev;
ev = event;
if (ev->exe == _kbd_exe) _kbd_exe = NULL;
return ECORE_CALLBACK_PASS_ON;
}
| 2.03125 | 2 |
2024-11-18T20:55:36.554565+00:00 | 2014-09-15T13:09:15 | bac3f1b5c82c77fa983b934d0f9f15997bb1704d | {
"blob_id": "bac3f1b5c82c77fa983b934d0f9f15997bb1704d",
"branch_name": "refs/heads/master",
"committer_date": "2014-09-15T13:09:15",
"content_id": "ed702093705c851459607806d579094f5a3e9de2",
"detected_licenses": [
"MIT"
],
"directory_id": "74ce510ef4157c422f52153f308d42d63bd4cb16",
"extension": "c",
"filename": "mod_bam.c",
"fork_events_count": 2,
"gha_created_at": "2014-04-10T19:52:19",
"gha_event_created_at": "2014-09-15T13:04:32",
"gha_language": "C",
"gha_license_id": null,
"github_id": 18649585,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19619,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mod_bam/mod_bam.c",
"provenance": "stackv2-0092.json.gz:42657",
"repo_name": "lindenb/mod_bio",
"revision_date": "2014-09-15T13:09:15",
"revision_id": "deeab84bd698f5888221b27724166ee61f38122b",
"snapshot_id": "3bb1e1fe4ac798abffca62c33acb22c28cca7f5b",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/lindenb/mod_bio/deeab84bd698f5888221b27724166ee61f38122b/src/mod_bam/mod_bam.c",
"visit_date": "2020-05-18T10:56:44.368832"
} | stackv2 | /**
* Author: Pierre Lindenbaum PhD
* April 2014
* Motivation: apache2 module for Bioinformatics
* WWW: http://github.com/lindenb/mod_bio
*/
#include <zlib.h>
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include "htslib/sam.h"
#include "htslib/kstring.h"
#include "r_utils.h"
/** call back to print AUX data in BAM record */
struct aux_callback_t
{
request_rec *r;
int (*print)( struct aux_callback_t*,const uint8_t* key,char type,const kstring_t* str, int index);
};
struct bam_callback_t
{
HttpParamPtr httParams;
samFile* samFile;
bam_hdr_t *header;
request_rec *r;
long count;
const char* region;
const char* jsonp_callback;
void (*startdocument)( struct bam_callback_t*);
void (*enddocument)( struct bam_callback_t*);
int (*show)( struct bam_callback_t*,const bam1_t *b);
};
/** PLAIN handlers ***************************************************/
static void plainStart( struct bam_callback_t* handler)
{
ap_set_content_type(handler->r, "text/plain");
ap_rputs(handler->header->text,handler->r);
}
static void plainEnd( struct bam_callback_t* handler)
{
}
static int plainShow(
struct bam_callback_t* handler,
const bam1_t *b
)
{
int ret=0;
kstring_t ks = { 0, 0, NULL };
if( sam_format1(handler->header, b,&ks)<0) return -1;
ret=ap_rputs(ks.s,handler->r);// write the alignment to `r'
ap_rputc('\n',handler->r);
free(ks.s);
return ret;
}
#define NEWKS kstring_t str = { 0, 0, NULL }
#define FREEKS(n) free(str.s);s+=n
#define ECHO_AUX(type) callback->print(callback,key,type,&str,num_count++)
/* generic loop to print AUX data*/
int print_aux_data(struct aux_callback_t* callback, const bam1_t *b)
{
int num_count=0;
uint8_t *s;
s = bam_get_aux(b); // aux
while (s+4 <= b->data + b->l_data)
{
uint8_t type, key[2];
key[0] = s[0]; key[1] = s[1];
s += 2; type = *s++;
if (type == 'A') {
NEWKS;
kputc(*s, &str);
ECHO_AUX('A');
FREEKS(1);
} else if (type == 'C')
{
NEWKS;
kputw(*s, &str);
ECHO_AUX('i');
FREEKS(1);
++s;
} else if (type == 'c')
{
NEWKS;
kputw(*(int8_t*)s, &str);
ECHO_AUX('i');
FREEKS(1);
}
else if (type == 'S')
{
if (s+2 <= b->data + b->l_data) {
NEWKS;
kputw(*(uint16_t*)s, &str);
ECHO_AUX('i');
FREEKS(2);
} else return -1;
} else if (type == 's') {
if (s+2 <= b->data + b->l_data) {
NEWKS;
kputw(*(int16_t*)s, &str);
ECHO_AUX('i');
FREEKS(2);
} else return -1;
} else if (type == 'I') {
if (s+4 <= b->data + b->l_data) {
NEWKS;
kputw(*(uint32_t*)s, &str);
ECHO_AUX('i');
FREEKS(4);
} else return -1;
} else if (type == 'i') {
if (s+4 <= b->data + b->l_data) {
NEWKS;
kputw(*(int32_t*)s, &str);
ECHO_AUX('i');
FREEKS(4);
} else return -1;
} else if (type == 'f'){
if (s+4 <= b->data + b->l_data) {
NEWKS;
ksprintf(&str, "%g", *(float*)s);
ECHO_AUX('f');
FREEKS(4);
} else return -1;
} else if (type == 'd') {
if (s+8 <= b->data + b->l_data)
{
NEWKS;
ksprintf(&str, "%g", *(double*)s);
ECHO_AUX('d');
FREEKS(8);
} else return -1;
} else if (type == 'Z' || type == 'H')
{
NEWKS;
while (s < b->data + b->l_data && *s) kputc(*s++, &str);
ECHO_AUX((char)type);
FREEKS(8);
if (s >= b->data + b->l_data)
{
return -1;
}
++s;
} else if (type == 'B') {
uint8_t sub_type = *(s++);
int32_t n;
int i;
memcpy(&n, s, 4);
s += 4; // no point to the start of the array
if (s + n >= b->data + b->l_data)
return -1;
for (i = 0; i < n; ++i) { // FIXME: for better performance, put the loop after "if"
NEWKS;
if ('c' == sub_type) { kputw(*(int8_t*)s, &str); ECHO_AUX(sub_type);FREEKS(1); }
else if ('C' == sub_type) { kputw(*(uint8_t*)s, &str);ECHO_AUX(sub_type);FREEKS(1); }
else if ('s' == sub_type) { kputw(*(int16_t*)s, &str); ECHO_AUX(sub_type);FREEKS(2); }
else if ('S' == sub_type) { kputw(*(uint16_t*)s, &str); ECHO_AUX(sub_type);FREEKS(2); }
else if ('i' == sub_type) { kputw(*(int32_t*)s, &str); ECHO_AUX(sub_type);FREEKS(4); }
else if ('I' == sub_type) { kputuw(*(uint32_t*)s, &str);ECHO_AUX(sub_type);FREEKS(4); }
else if ('f' == sub_type) { ksprintf(&str, "%g", *(float*)s); ECHO_AUX(sub_type);FREEKS(4); }
else {free(str.s);}
}
}
}
return 0;
}
/** XML handlers ***************************************************/
static void xmlStart( struct bam_callback_t* handler)
{
ap_set_content_type(handler->r, "text/xml");
ap_rputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<sam-file git-version=\"" MOD_BIO_VERSION "\">\n<header>",handler->r);
ap_xmlPuts(handler->header->text,handler->r);
ap_rputs("</header><records>",handler->r);
}
static void xmlEnd( struct bam_callback_t* handler)
{
ap_rputs("</records>\n</sam-file>\n",handler->r);
}
#define ap_kputw(i,r) ap_rprintf(r,"%d",i)
#define ap_kputuw(i,r) ap_rprintf(r,"%u",i)
#define OPEN_TAG(tag) ap_rputs("<" tag ">",handler->r)
#define CLOSE_TAG(tag) ap_rputs("</" tag ">",handler->r)
#define SIMPLE_STR_TAG(tag,a) do{if((a)!=NULL) {\
OPEN_TAG(tag);\
ap_xmlPuts((a),handler->r);\
CLOSE_TAG(tag);\
}} while(0)
#define SIMPLE_INT_TAG(tag,a) do{\
OPEN_TAG(tag);\
ap_kputw(a,handler->r);\
CLOSE_TAG(tag);\
} while(0)
static int xmlPrintAux(
struct aux_callback_t* handler,
const uint8_t* key,
char type,
const kstring_t* str,
int index)
{
ap_rputs("<aux name=\"",handler->r);
ap_rwrite((void*)key,2,handler->r);
ap_rprintf(handler->r,"\" type=\"%c\">",type);
ap_xmlPuts(str->s,handler->r);\
return ap_rputs("</aux>",handler->r);
}
static int xmlShow(
struct bam_callback_t* handler,
const bam1_t *b
)
{
struct aux_callback_t auxh;
//uint8_t *s;
int i;
const bam1_core_t *c = &b->core;
OPEN_TAG("sam");
SIMPLE_STR_TAG("name",bam_get_qname(b));
SIMPLE_INT_TAG("flag",c->flag);
if (c->tid >= 0)
{ // chr
SIMPLE_STR_TAG("chrom",handler->header->target_name[c->tid]);
}
SIMPLE_INT_TAG("pos",c->pos + 1);
SIMPLE_INT_TAG("mapq",c->qual);
if (c->n_cigar) { // cigar
OPEN_TAG("cigar-string");
uint32_t *cigar = bam_get_cigar(b);
for (i = 0; i < c->n_cigar; ++i)
{
ap_rprintf( handler->r,"<cigar op='%c' count='%d'/>",
bam_cigar_opchr(cigar[i]),
bam_cigar_oplen(cigar[i])
);
}
CLOSE_TAG("cigar-string");
}
if (c->mtid >= 0)
{
SIMPLE_STR_TAG("mate_chrom",handler->header->target_name[c->mtid]);
SIMPLE_INT_TAG("mate_pos",c->mpos + 1);
SIMPLE_INT_TAG("insert_size",c->isize + 1);
}
if (c->l_qseq)
{ // seq and qual
OPEN_TAG("sequence");
uint8_t *s = bam_get_seq(b);
for (i = 0; i < c->l_qseq; ++i) ap_rputc("=ACMGRSVTWYHKDBN"[bam_seqi(s, i)], handler->r);
CLOSE_TAG("sequence");
s = bam_get_qual(b);
if(!(s[0] == 0xff))
{
OPEN_TAG("qual");
for (i = 0; i < c->l_qseq; ++i) ap_rputc(s[i] + 33, handler->r);
CLOSE_TAG("qual");
}
}
OPEN_TAG("aux-list");
auxh.r = handler->r;
auxh.print = xmlPrintAux;
print_aux_data(&auxh,b);
CLOSE_TAG("aux-list");
return CLOSE_TAG("sam");
}
#undef CLOSE_TAG
#undef OPEN_TAG
#undef SIMPLE_STR_TAG
#undef SIMPLE_INT_TAG
#undef ap_kputw
#undef ap_kputuw
/** json handlers ***************************************************/
static void jsonStart( struct bam_callback_t* handler)
{
if(handler->jsonp_callback!=NULL)
{
ap_set_content_type(handler->r, MIME_TYPE_JAVASCRIPT);
ap_rputs(handler->jsonp_callback,handler->r);
ap_rputc('(',handler->r);
}
else
{
ap_set_content_type(handler->r, MIME_TYPE_JSON);
}
ap_rputs("{\"header\":",handler->r);
ap_jsonQuote(handler->header->text,handler->r);
ap_rputs(",\"records\":[",handler->r);
}
static void jsonEnd( struct bam_callback_t* handler)
{
ap_rputs("]}",handler->r);
if(handler->jsonp_callback!=NULL)
{
ap_rputs(");\n",handler->r);
}
}
#define ap_kputw(i,r) ap_rprintf(r,"%d",i)
#define ap_kputuw(i,r) ap_rprintf(r,"%u",i)
#define OPEN_TAG(s) ap_rputs(",\"" s "\":",handler->r);
#define SIMPLE_INT_TAG(tag,i) ap_rprintf(handler->r,",\"" tag "\":%d",i)
#define SIMPLE_STR_TAG(tag,s) do { if(s!=NULL) {OPEN_TAG(tag);ap_jsonQuote(s,handler->r);}} while(0)
static int jsonPrintAux(
struct aux_callback_t* handler,
const uint8_t* key,
char type,
const kstring_t* str,
int index)
{
if(index>0) ap_rputc(',',handler->r);
ap_rputs("{\"name\":\"",handler->r);
ap_rwrite((void*)key,2,handler->r);
ap_rputs("\",\"type\":\"",handler->r);
ap_rprintf( handler->r,"%c:",type);
ap_rputs("\",\"value\":",handler->r);
switch(type)
{
case 'i':case 'I':case 'f':ap_rputs(str->s,handler->r);break;
default:ap_jsonQuote(str->s,handler->r);break;
}
return ap_rputc('}',handler->r);;
}
static int jsonShow(
struct bam_callback_t* handler,
const bam1_t *b
)
{
int i=0;
struct aux_callback_t auxh;
//uint8_t *s;
const bam1_core_t *c = &b->core;
if(handler->count>0) ap_rputc(',',handler->r);
ap_rputc('\n',handler->r);
ap_rputs("{\"name\":",handler->r);
ap_jsonQuote(bam_get_qname(b),handler->r);
SIMPLE_INT_TAG("flag",c->flag);
if (c->tid >= 0)
{ // chr
SIMPLE_STR_TAG("chrom",handler->header->target_name[c->tid]);
}
SIMPLE_INT_TAG("pos",c->pos + 1);
SIMPLE_INT_TAG("mapq",c->qual);
if (c->n_cigar) { // cigar
OPEN_TAG("cigar");
ap_rputc('[',handler->r);
uint32_t *cigar = bam_get_cigar(b);
for (i = 0; i < c->n_cigar; ++i)
{
if(i>0) ap_rputc(',',handler->r);
ap_rprintf( handler->r,"{\"op\":\"%c\",\"count\":%d}",
bam_cigar_opchr(cigar[i]),
bam_cigar_oplen(cigar[i])
);
}
ap_rputc(']',handler->r);
}
if (c->mtid >= 0)
{
SIMPLE_STR_TAG("mate-chrom",handler->header->target_name[c->mtid]);
SIMPLE_INT_TAG("mate-pos",c->mpos + 1);
SIMPLE_INT_TAG("insert-size",c->isize + 1);
}
if (c->l_qseq)
{ // seq and qual
OPEN_TAG("sequence");
ap_rputc('\"',handler->r);
uint8_t *s = bam_get_seq(b);
for (i = 0; i < c->l_qseq; ++i) ap_rputc("=ACMGRSVTWYHKDBN"[bam_seqi(s, i)], handler->r);
ap_rputc('\"',handler->r);
s = bam_get_qual(b);
if(!(s[0] == 0xff))
{
ap_rputs(",\"qual\":\"",handler->r);
for (i = 0; i < c->l_qseq; ++i) ap_rputc(s[i] + 33, handler->r);
ap_rputc('\"',handler->r);
}
}
ap_rputs(",\"aux\":[",handler->r);
auxh.r = handler->r;
auxh.print = jsonPrintAux;
print_aux_data(&auxh,b);
ap_rputc(']',handler->r);//end aux-list
return ap_rputc('}',handler->r);
}
#undef CLOSE_TAG
#undef OPEN_TAG
#undef SIMPLE_STR_TAG
#undef SIMPLE_INT_TAG
#undef ap_kputw
#undef ap_kputuw
/** HTML handlers ***************************************************/
static void htmlStart( struct bam_callback_t* handler)
{
ap_set_content_type(handler->r, MIME_TYPE_HTML);
ap_rputs("<!doctype html>\n<html lang=\"en\">",handler->r);
ap_rputs("<head>",handler->r);
printDefaulthtmlHead(handler->r);
ap_rputs("</head>",handler->r);
ap_rputs("<body>",handler->r);
ap_rprintf(handler->r,
"<form>"
"<label for='format'>Format:</label> <select id='format' name='format'>"
"<option value='html'>html</option>"
"<option value='json'>json</option>"
"<option value='xml'>xml</option>"
"<option value='text'>text</option>"
"</select> "
"<label for='limit'>Limit:</label> <input id='limit' name='limit' placeholder='max records' type=\"number\" value=\"%d\"/>"
"<label for='region'>Region:</label> <input id='region' name='region' placeholder='chrom:start-end' ",
DEFAULT_LIMIT_RECORDS
);
if(handler->region!=NULL)
{
ap_rputs(" value=\"",handler->r);
ap_xmlPuts(handler->region,handler->r);
ap_rputs("\"",handler->r);
}
ap_rputs("/>"
"<input type='submit'/></form><div>"
,handler->r);
if(handler->region!=NULL)
{
ap_rputs("<h3>",handler->r);
ap_xmlPuts(handler->region,handler->r);
ap_rputs("</h3>",handler->r);
}
ap_rputs("<div class='fileheader'>"
,handler->r);
ap_xmlPuts(handler->header->text,handler->r);
ap_rputs("</div><div><table>"
"<thead><tr>"
"<th>Name</th>"
"<th>Flag</th>"
"<th>Chrom</th>"
"<th>Pos</th>"
"<th>mapQ</th>"
"<th>Cigar</th>"
"<th>Mate Chrom</th>"
"<th>Mate Pos</th>"
"<th>TLen</th>"
"<th>SEQ</th>"
"<th>Qual</th>"
"<th>Aux</th>"
"</tr></thead><tbody>"
,handler->r);
}
static void htmlEnd( struct bam_callback_t* handler)
{
ap_rputs("<tbody></table></div>",handler->r);
ap_rputs(html_address,handler->r);
ap_rputs("</body></html>\n",handler->r);
}
#define ap_kputw(i,r) ap_rprintf(r,"%d",i)
#define ap_kputuw(i,r) ap_rprintf(r,"%u",i)
#define OPEN_TAG(tag) ap_rputs("<" tag ">",handler->r)
#define CLOSE_TAG(tag) ap_rputs("</" tag ">",handler->r)
#define SIMPLE_STR_TAG(a) do{if((a)!=NULL) {\
OPEN_TAG("td");\
ap_xmlPuts((a),handler->r);\
CLOSE_TAG("td");\
}} while(0)
#define SIMPLE_INT_TAG(a) do{\
OPEN_TAG("td");\
ap_kputw(a,handler->r);\
CLOSE_TAG("td");\
} while(0)
static int htmlPrintAux(
struct aux_callback_t* handler,
const uint8_t* key,
char type,
const kstring_t* str,
int index)
{
ap_rputs("<span>",handler->r);
ap_rwrite((void*)key,2,handler->r);
ap_rprintf( handler->r,":%c:",type);
ap_xmlPuts(str->s,handler->r);\
return ap_rputs("</span> ",handler->r);
}
static int htmlShow(
struct bam_callback_t* handler,
const bam1_t *b
)
{
struct aux_callback_t auxh;
//uint8_t *s;
int i;
const bam1_core_t *c = &b->core;
ap_rprintf( handler->r,"<tr class=\"row%d\">",
(int)(handler->count%2)
);
SIMPLE_STR_TAG(bam_get_qname(b));
SIMPLE_INT_TAG(c->flag);
if (c->tid >= 0)
{ // chr
SIMPLE_STR_TAG(handler->header->target_name[c->tid]);
}
else
{
OPEN_TAG("td");CLOSE_TAG("td");
}
SIMPLE_INT_TAG(c->pos + 1);
SIMPLE_INT_TAG(c->qual);
OPEN_TAG("td");
if (c->n_cigar) { // cigar
uint32_t *cigar = bam_get_cigar(b);
for (i = 0; i < c->n_cigar; ++i)
{
ap_rprintf( handler->r,
"<span class=\"c%c\">%c%d</span>",
tolower(bam_cigar_opchr(cigar[i])=='='?'m':bam_cigar_opchr(cigar[i])),
bam_cigar_opchr(cigar[i]),
bam_cigar_oplen(cigar[i])
);
}
}
if (c->mtid >= 0)
{
SIMPLE_STR_TAG(handler->header->target_name[c->mtid]);
SIMPLE_INT_TAG(c->mpos + 1);
SIMPLE_INT_TAG(c->isize + 1);
}
else
{
OPEN_TAG("td");CLOSE_TAG("td");
OPEN_TAG("td");CLOSE_TAG("td");
OPEN_TAG("td");CLOSE_TAG("td");
}
if (c->l_qseq)
{ // seq and qual
OPEN_TAG("td");
uint8_t *s = bam_get_seq(b);
for (i = 0; i < c->l_qseq; ++i)
{
char base="=ACMGRSVTWYHKDBN"[bam_seqi(s, i)];
ap_rprintf(handler->r,"<span class=\"b%c\">%c</span>",tolower(base),base);
}
CLOSE_TAG("td");
s = bam_get_qual(b);
if(!(s[0] == 0xff))
{
OPEN_TAG("td");
for (i = 0; i < c->l_qseq; ++i) ap_rputc(s[i] + 33, handler->r);
CLOSE_TAG("td");
}
else
{
OPEN_TAG("td");CLOSE_TAG("td");
}
}
else
{
OPEN_TAG("td");CLOSE_TAG("td");
OPEN_TAG("td");CLOSE_TAG("td");
}
OPEN_TAG("td");
auxh.r = handler->r;
auxh.print = htmlPrintAux;
print_aux_data(&auxh,b);
CLOSE_TAG("td");
CLOSE_TAG("tr");
return 0;
}
#undef CLOSE_TAG
#undef OPEN_TAG
#undef SIMPLE_STR_TAG
#undef SIMPLE_INT_TAG
#undef ap_kputw
#undef ap_kputuw
/* Define prototypes of our functions in this module */
static void register_hooks(apr_pool_t *pool);
static int bam_handler(request_rec *r);
/* Define our module as an entity and assign a function for registering hooks */
module AP_MODULE_DECLARE_DATA bam_module =
{
STANDARD20_MODULE_STUFF,
NULL, // Per-directory configuration handler
NULL, // Merge handler for per-directory configurations
NULL, // Per-server configuration handler
NULL, // Merge handler for per-server configurations
NULL, // Any directives we may have for httpd
register_hooks // Our hook registering function
};
static void register_hooks(apr_pool_t *pool)
{
ap_hook_handler(bam_handler, NULL, NULL, APR_HOOK_LAST);
}
#define SETUP_HANDLER(prefix)\
handler.startdocument= prefix ## Start;\
handler.enddocument= prefix ## End;\
handler.show=prefix ## Show
/**
* Workhorse method for BAM
*
*/
static int bam_handler(request_rec *r)
{
struct bam_callback_t handler;
int http_status=OK;
hts_itr_t *iter=NULL;
hts_idx_t *idx=NULL;
bam1_t *b=NULL;
long limit=DEFAULT_LIMIT_RECORDS;
memset((void*)&handler,0,sizeof(struct bam_callback_t));
if (!r->handler || strcmp(r->handler, "bam-handler")) return (DECLINED);
if (strcmp(r->method, "GET")!=0) return DECLINED;
if(r->canonical_filename==NULL) return DECLINED;
if(!str_ends_with(r->canonical_filename,".bam")) return DECLINED;
/* check file exists */
if(!fileExists(r->canonical_filename))
{
return HTTP_NOT_FOUND;
}
handler.r=r;
handler.httParams = HttpParamParseGET(r);
if( handler.httParams==NULL) return DECLINED;
/* only one loop, we use this to cleanup the code, instead of using a goto statement */
do {
const char* format=HttpParamGet(handler.httParams,"format");
const char* limit_str=HttpParamGet(handler.httParams,"limit");
handler.region=HttpParamGet(handler.httParams,"region");
int iterator_was_requested=FALSE;
b=bam_init1();
if(b==NULL)
{
http_status=HTTP_INTERNAL_SERVER_ERROR;
break;
}
if(limit_str!=NULL)
{
limit=atol(limit_str);
}
if(format==NULL)
{
http_status=DECLINED;
break;
}
else if(strcmp(format,"xml")==0)
{
SETUP_HANDLER(xml);
}
else if(strcmp(format,"json")==0 || strcmp(format,"jsonp")==0)
{
handler.jsonp_callback=HttpParamGet(handler.httParams,"callback");
SETUP_HANDLER(json);
}
else if(strcmp(format,"html")==0)
{
SETUP_HANDLER(html);
}
else
{
SETUP_HANDLER(plain);
}
handler.samFile = sam_open(r->canonical_filename,"r");
if(handler.samFile==NULL)
{
http_status=HTTP_NOT_FOUND;
break;
}
handler.header= sam_hdr_read(handler.samFile);
if(handler.header==NULL)
{
http_status=HTTP_INTERNAL_SERVER_ERROR;
break;
}
if(handler.region!=NULL && !str_is_empty(handler.region))
{
iterator_was_requested=TRUE;
idx = bam_index_load(r->canonical_filename);
if(idx!=NULL)
{
iter = bam_itr_querys(idx, handler.header, handler.region);
}
}
handler.startdocument(&handler);
while(limit==-1 || handler.count<limit)
{
int r;
if(!iterator_was_requested)
{
r = sam_read1(handler.samFile, handler.header, b);
}
else if(iter!=NULL)
{
r = bam_itr_next(handler.samFile, iter, b);
}
else
{
r=-1;
}
if(r<0) break;
if(handler.show(&handler,b)<0) break;
handler.count++;
}
handler.enddocument(&handler);
} while(0);/* always abort */
//cleanup
HttpParamFree(handler.httParams);
if(b!=NULL) bam_destroy1(b);
if(iter!=NULL) hts_itr_destroy(iter);
if(idx!=NULL) hts_idx_destroy(idx);
if(handler.header!=NULL) bam_hdr_destroy(handler.header);
if(handler.samFile!=NULL) sam_close(handler.samFile);
return http_status;
}
| 2.375 | 2 |
2024-11-18T20:55:36.651882+00:00 | 2020-07-31T20:48:43 | 238c53aa8be992d3d97e64a576a67b93b6d4b624 | {
"blob_id": "238c53aa8be992d3d97e64a576a67b93b6d4b624",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-31T20:48:43",
"content_id": "1cc392e7f33513bb42d0eb74326cc5cb15278fde",
"detected_licenses": [
"MIT"
],
"directory_id": "b717e07cee4466f2ca2c5281d731960ab0618cb7",
"extension": "h",
"filename": "Dict.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": 16292,
"license": "MIT",
"license_type": "permissive",
"path": "/include/ift/core/dtypes/Dict.h",
"provenance": "stackv2-0092.json.gz:42787",
"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/core/dtypes/Dict.h",
"visit_date": "2023-04-29T15:21:55.681739"
} | stackv2 | /**
* @file iftDict.h
* @brief Definitions and functions of a Generic Dict based on Hash Tables.
* @author Samuel Martins
* @date Jan 17, 2016
* @ingroup Dictionary
*
* - An example about how to create, insert, and print elements can be found in demo/Miscellaneous/iftTestDict1.c
* - An example about how to get elements can be found in demo/Miscellaneous/iftTestDict2.c
* - An example about how to remove elements can be found in demo/Miscellaneous/iftTestDict3.c
*/
#ifndef IFT_DICT_H
#define IFT_DICT_H
#ifdef __cplusplus
extern "C" {
#endif
#include "ift/core/dtypes/BasicDataTypes.h"
/**
* @brief When creating a new dict, it has this initial size.
* @ingroup Dictionary
*/
#define IFT_INITIAL_DICT_SIZE 103
/**
* @brief When creating a new dict, it has this initial size.
* @ingroup Dictionary
*/
#define IFT_HASH_FAIL -1 // "flag" to indicate that there is no available buckets in the dict
/**
* @brief A pair of Key Value of generic datatypes used as iteration for iftDict.
* @author Samuel Martins
* @date Jan 6th, 2016
* @ingroup Dictionary
*/
typedef struct ift_key_val {
/** Key as Generic Value */
iftGVal key;
/** Value as Generic Value */
iftGVal val;
/** Previous KeyVal of the iterator */
int prev;
/** Next KeyVal of the iterator */
int next;
} iftKeyVal;
/**
* @brief A generic dictionary based on Hash Table that stores pairs of key values. All keys will have a common datatype, the same holds to all values.
* @author Samuel Martins
* @date Jan 6th, 2016
* @ingroup Dictionary
*
* @note Its type definition in iftBasicDataType.h
*/
struct ift_dict {
/** Size of the dict. When inserting more elements than this size, the dict is expanded with a new size. */
size_t capacity;
/** Number of busy buckets of the dict. */
size_t n_busy_buckets;
/** Dictionary. */
iftKeyVal *table;
/** It indicates if the Destroy Function will deallocate all elements from the dict */
bool erase_elements;
/** First key, for iteration (and world domination) purposes.*/
int firstKey;
/** Last key, for iteration (and world domination) purposes.*/
int lastKey;
};
/**
* @brief Array of Dictionaries. Useful to insert/get array of dicts in Json files
* @author Samuel Martins
* @date Sep 15, 2017
*/
typedef struct ift_dict_array {
/** Size of Array */
size_t n;
/** Array of Dicts */
iftDict **val;
} iftDictArray;
/**
* @brief Creates a Dictionary structure, based on Hash Tables, that stores pairs of keys and values of any type.
* @author Samuel Martins
* @date Jan 17th, 2016
* @ingroup Dictionary
*
* @note The initial size of the dict is IFT_INITIAL_DICT_SIZE. When the dict is FULL, it will be resized automatically.
* @note Initially, empty buckets of the dictionary has key type and val type equals to IFT_UNTYPED.
*
* @return The created dictionary.
*
* @sa iftCreateDictWithApproxSize(), iftCreateDictWithInitialSize()
*/
iftDict *iftCreateDict();
/**
* @brief Creates a Dictionary with an approximate size.
* @author Samuel Martins
* @date Jan 17th, 2016
* @ingroup Dictionary
*
* Initially, empty buckets of the dictionary has key type and val type equals to IFT_UNTYPED.
*
* Actually, the <b>real dictionary size</b> is computed from the passed approximate size <b>n</b>,
* and it is a bigger and better size used to minimize collisions due to the hashing.\n
* The real dictionary size is found according to the following rules:
* -# size >= n;
* -# size is the farthest prime number of the powers of 2 that surround <b>n</b>;
* -# size and (1 + (k % m)), where m = size - 2, do not have GCD (greatest common divisor);
* -# (1 + (k % m)) > size, where m = size - 2.
*
* @param n The approximate size of the Dict.
* @return The created dictionary.
*
* @note When the dict is FULL, it will be resized automatically.
* @note Initially, empty buckets of the dictionary has key type and val type equals to IFT_UNTYPED.
*
* @sa iftCreateDict(), iftCreateDictWithInitialSize()
*/
iftDict *iftCreateDictWithApproxSize(size_t n);
/**
* @brief Creates a Dictionary with the initial size <b>n</n>. USE iftCreateDictWithApproxSize() INSTEAD OF.
* @author Samuel Martins
* @date Jan 17th, 2016
* @ingroup Dictionary
*
* @param n The initial size of the Dict.
* @return The created dictionary.
*
* @note When the dict is FULL, it will be resized automatically.
* @note Initially, empty buckets of the dictionary has key type and val type equals to IFT_UNTYPED.
*
* @sa iftCreateDict(), iftCreateDictWithApproxSize()
*/
iftDict *iftCreateDictWithInitialSize(size_t n);
/**
* @brief Destroys a dictionary. If the filed erase_elements is true, it will deallocate EVERYTHING dynamically allocated.
* @author Samuel Martins
* @date Jan 17, 2016
* @ingroup Dictionary
*/
void iftDestroyDict(iftDict **dict);
/**
* @brief Create an array of n dictionaries.
* @author Samuka Martins
* @date Sep 15, 2017
*/
iftDictArray *iftCreateDictArray(size_t n);
/**
* @brief Destroy an array of n dictionaries.
* @author Samuka Martins
* @date Sep 15, 2017
*/
void iftDestroyDictArray(iftDictArray **dict_arr);
/**
* @brief Copies a dictionary.
* @author Samuel Martins
* @date Feb 29, 2016
* @ingroup Dictionary
*/
iftDict *iftCopyDict(const iftDict *dict);
/**
* @brief Checks if the dict is empty.
* @author Samuel Martins
* @date Jan 17th, 2016
* @ingroup Dictionary
*/
bool iftIsDictEmpty(const iftDict *dict);
/**
* @brief Checks if the dict is full.
* @author Samuel Martins
* @date Jan 17th, 2016
* @ingroup Dictionary
*/
bool iftIsDictFull(const iftDict *dict);
/**
* @brief Checks if the dict contains the key. SUPER SLOW FUNCTION IF USED INSIDE LOOPS
* @author Samuel Martins
* @date Feb 16, 2016
* @ingroup Dictionary
*
* When seeking the key, it ignores empty buckets and continue the search until all buckets
* have been visited.\n
* This enables that a key B rehashed (i.e., assigned to a new position), due to a colision with
* a key A, is able to reach its real position even if the key A have been removed.\n
*
* @param KEY The key to be checked.
* @param DICT The considered dict.
* @param KEY_INDEX Returns the dict table index of the key, if it exists. Otherwise, the IFT_HASH_FAIL is returned.
* @return True if the dict contains the key and false otherwise.
*
* @attention If the <code>key_index</code> is NULL, nothing is returned to it.
* @warning If the GVal key is indeed a string, it will be deallocated at the end of the function.
*/
#define iftDictContainKey(KEY, DICT, KEY_INDEX) iftDictContainGKey(iftCreateGVal((KEY)), (DICT), (KEY_INDEX))
/**
* @brief Checks if the dict contains the key (of the type GVal). USE THE MACRO FUNCTION iftDictContainKey() INSTEAD OF.
* @author Samuel Martins
* @date Jan 17th, 2016
* @ingroup Dictionary
*
* When seeking the key, it ignores empty buckets and continue the search until all buckets
* have been visited.\n
* This enables that a key B rehashed (i.e., assigned to a new position), due to a colision with
* a key A, is able to reach its real position even if the key A have been removed.\n
*
* @param key The GVal key to be checked.
* @param dict The considered dict.
* @param key_index Returns the dict table index of the key, if it exists. Otherwise, the IFT_HASH_FAIL is returned.
* @return True if the dict contains the key and false otherwise.
*
* @note USE THE MACRO FUNCTION iftDictContainKey() INSTEAD OF.
* @warning If the <code>key_index</code> is NULL, nothing is returned to it.
* @warning If the key is a string, it is deallocated at the end of the function.
*/
bool iftDictContainGKey(iftGVal key, const iftDict *dict, size_t *key_index);
/**
* @brief Prints the dictionary in a fancy style.
* @author Samuel Martins
* @date Jan 17th, 2016
* @ingroup Dictionary
* @sa iftPrintDictMinified(), iftPrintDictAsArray()
*/
void iftPrintDict(const iftDict *dict);
/**
* @brief Prints the dictionary in a minified view.
* @author Samuel Martins
* @date Feb 4th, 2016
* @ingroup Dictionary
* @sa iftPrintDict(), iftPrintDictAsArray()
*/
void iftPrintDictMinified(const iftDict *dict);
/**
* @brief Prints the dictionary similarly to an array, by starting from the beginning index to the end.
* @author Samuel Martins
* @date Feb 4th, 2016
* @ingroup Dictionary
* @sa iftPrintDict(), iftPrintDictMinified()
*/
void iftPrintDictAsArray(const iftDict *dict);
/**
* @brief Generic function to insertion of elements into a dictionary. All elements (KEY and VAL) are passed as REFERENCE (not a copy) to dict.
* @author Samuel Martins
* @date Feb 4th, 2016
* @ingroup Dictionary
*
* @param KEY The key of any datatype to be inserted.
* @param VAL The value of any datatype to be inserted.
* @param DICT The target dictionary where the pair key value will be inserted.
*
* @note A datatype #GVal is created for the key and val and then both are inserted in the dictionary.
*/
#define iftInsertIntoDict(KEY,VAL,DICT) iftInsertKeyValIntoDict(iftCreateGVal(KEY), iftCreateGVal(VAL), DICT)
/**
* @brief Insert a pair of generic key val into the dictionary. USE THE MACRO FUNCTION iftInsertIntoDict() INSTEAD OF.
* @author Samuel Martins
* @date Feb 4th, 2016
* @ingroup Dictionary
*
* @param key The generic key to be inserted.
* @param val The generic val to be inserted.
* @param dict The target dictionary where the generic pair key value will be inserted.
* @return True if the pair were inserted, False otherwise.
*
* @attention USE THE MACRO FUNCTION iftInsertIntoDict() INSTEAD OF.
* @warning The allowed Datatypes for the keys are:\n
* <b>char, unsigned char, string (char, unsigned char, string (char*), short, int, long, unsigned short,
* unsigned int, "unsigned long, float, double.</b>
*/
bool iftInsertKeyValIntoDict(iftGVal key, iftGVal val, iftDict *dict);
/**
* @brief Gets the REFERENCE (except the string which is passed as a COPY) of the value from the dict based on its key.
*
* It is possible to pass multiple keys, according to dict hierarchy. For that, use the following format:
* "key1:key2:key3:keyn"
*
* @author Samuel Martins
* @date Feb 12, 2016
* @ingroup Dictionary
*
* @param KEY The key used to get the value.
* @param DICT The used dictionary.
* @return The desired value.
*
* @warning The value is not removed from the dict.
* @warning If the key is a string, it is deallocated at the end.
* @exception If the input key does not exist.
* @{
*/
#define iftGetBoolValFromDict(KEY,DICT) iftGetBoolVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_BOOL_TYPE))
#define iftGetCharValFromDict(KEY,DICT) iftGetCharVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_CHAR_TYPE))
#define iftGetUCharValFromDict(KEY,DICT) iftGetUCharVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_UCHAR_TYPE))
#define iftGetStrValFromDict(KEY,DICT) iftGetStrVal(iftCopyGVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_STR_TYPE)))
#define iftGetConstStrValFromDict(KEY,DICT) iftGetConstStrVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_STR_TYPE))
#define iftGetLongValFromDict(KEY,DICT) iftGetLongVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_LONG_TYPE))
#define iftGetULongValFromDict(KEY,DICT) iftGetULongVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_ULONG_TYPE))
#define iftGetDblValFromDict(KEY,DICT) iftGetDblVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_DBL_TYPE))
#define iftGetPtrValFromDict(KEY,DICT) iftGetPtrVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_PTR_TYPE))
#define iftGetIntArrayFromDict(KEY, DICT) iftGetIntArrayVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_INT_ARRAY_TYPE))
#define iftGetDblArrayFromDict(KEY, DICT) iftGetDblArrayVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_DBL_ARRAY_TYPE))
#define iftGetStrArrayFromDict(KEY, DICT) iftGetStrArrayVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_STR_ARRAY_TYPE))
#define iftGetIntMatrixFromDict(KEY, DICT) iftGetIntMatrixVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_INT_MATRIX_TYPE))
#define iftGetDblMatrixFromDict(KEY, DICT) iftGetDblMatrixVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_DBL_MATRIX_TYPE))
#define iftGetStrMatrixFromDict(KEY, DICT) iftGetStrMatrixVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_STR_MATRIX_TYPE))
#define iftGetDictFromDict(KEY, DICT) iftGetDictVal(iftGetGValFromDict(iftCreateGVal((KEY)), (DICT), IFT_DICT_TYPE))
/** @} */
/**
* @brief Gets (without removing) the generic value (#iftGVal) from the dict based on its key, which is also an #iftGVal.\n
* Use the Getter Macro functions (iftGet*ValFromDict()) instead of.
* @author Samuel Martins
* @date Feb 12, 2016
* @ingroup Dictionary
*
* @param KEY The key used to get the value.
* @param DICT The used dictionary.
* @return The desired value.
*
* @attention Use the Getter Macro functions (iftGet*ValFromDict()) instead of.
* @warning The value is not removed from the dict.
* @warning If the key is a string, it is deallocated at the end of the function.
* @exception If the input key does not exist.
*/
iftGVal iftGetGValFromDict(iftGVal key, const iftDict *dict, iftCDataType true_val_type);
/**
* @brief Removes the value from the dict based on its key.
* @author Samuel Martins
* @date Feb 12, 2016
* @ingroup Dictionary
*
* @param KEY The key used to get the value.
* @param DICT The used dictionary.
* @return The desired value.
*
* @warning If the key is a string, it is deallocated at the end of the function.
* @exception If the input key does not exist.
* @{
*/
#define iftRemoveValFromDict(KEY,DICT) iftRemoveGValFromDict(iftCreateGVal(KEY), DICT)
/** @} */
/**
* @brief Removes the generic value (#iftGVal) from the dict based on its key, which is also an #iftGVal.
* Use the Getter Macro functions (iftRemove*ValFromDict()) instead of.
* @author Samuel Martins
* @date Feb 12, 2016
* @ingroup Dictionary
*
* @param KEY The key used to get the value.
* @param DICT The used dictionary.
* @return The desired value.
*
* @attention Use the Getter Macro functions (iftRemove*ValFromDict()) instead of.
* @warning If the key is a string, it is deallocated in the end of the function.
* @exception If the input key does not exist.
*/
bool iftRemoveGValFromDict(iftGVal key, iftDict *dict);
/**
* @brief Updates the generic value (#iftGVal) from the dict based on its key, which is also an #iftGVal.
*
* @author Cesar Castelo
* @date Feb 22, 2018
* @ingroup Dictionary
*
* @param KEY The key used to get the value.
* @param VAL The value to be inserted.
* @param DICT The used dictionary.
* @return The desired value.
*
* @warning This is NOT an efficient implementation (suitable only for small dictionaries).
* It just calls the iftRemoveValFromDict and iftInsertIntoDict functions
*/
void iftUpdateValInDict(iftGVal key, iftGVal val, iftDict *dict);
/**
* @brief Returns the first element in the dictionary.
* @author Peixinho
* @April, 2016
*/
iftKeyVal iftDictFirst(const iftDict* dict);
/**
* @brief Gets the next element in the dictionary.
* @author Peixinho
* @date April, 2016
*/
iftKeyVal iftDictNext(const iftDict* dict, const iftKeyVal keyval);
/**
* @brief Check if this is a valid element in the dictionary, for iteration.
* @author Peixinho
* @date April, 2016
*/
bool iftDictValidKey(const iftKeyVal keyval);
/**
* @brief Convert an Integer Array to a Dict. The elements from the array will be the keys from the dict,
* whereas theirs indices will be the corresponding values from the dict.
*
* @author Samuka Martins
* @date Sep 13, 2017
*/
iftDict *iftIntArrayToDict(const int *arr, size_t n);
/**
* @brief Merges two dictionaries and return a new one
*
* @author Cesar Castelo
* @date Feb 27, 2018
*/
iftDict *iftMergeDicts(iftDict *dict1, iftDict *dict2);
/**
* @brief Creates a string from a dictionary in a minifield view.
* @author Cesar Castelo
* @date March 01, 2018
* @ingroup Dictionary
*/
char *iftDictToStringMinified(const iftDict *dict);
#ifdef __cplusplus
}
#endif
#endif //IFT_DICT_H
| 2.6875 | 3 |
2024-11-18T20:55:36.723933+00:00 | 2023-09-02T15:16:12 | 2f23a2bc56b8c99e83655b24d2c64c9ddfb2af08 | {
"blob_id": "2f23a2bc56b8c99e83655b24d2c64c9ddfb2af08",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T15:16:12",
"content_id": "3c09b725a78db5436a2896d5127dc71fe5cda89f",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9ceacf33fd96913cac7ef15492c126d96cae6911",
"extension": "c",
"filename": "recover.c",
"fork_events_count": 1235,
"gha_created_at": "2016-08-30T18:18:25",
"gha_event_created_at": "2023-08-08T02:42:25",
"gha_language": "C",
"gha_license_id": null,
"github_id": 66966208,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 21956,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/usr.bin/vi/common/recover.c",
"provenance": "stackv2-0092.json.gz:42916",
"repo_name": "openbsd/src",
"revision_date": "2023-09-02T15:16:12",
"revision_id": "9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9",
"snapshot_id": "ab97ef834fd2d5a7f6729814665e9782b586c130",
"src_encoding": "UTF-8",
"star_events_count": 3394,
"url": "https://raw.githubusercontent.com/openbsd/src/9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9/usr.bin/vi/common/recover.c",
"visit_date": "2023-09-02T18:54:56.624627"
} | stackv2 | /* $OpenBSD: recover.c,v 1.32 2022/02/20 19:45:51 tb Exp $ */
/*-
* Copyright (c) 1993, 1994
* The Regents of the University of California. All rights reserved.
* Copyright (c) 1993, 1994, 1995, 1996
* Keith Bostic. All rights reserved.
*
* See the LICENSE file for redistribution information.
*/
#include "config.h"
#include <sys/queue.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
/*
* We include <sys/file.h>, because the open #defines were found there
* on historical systems. We also include <fcntl.h> because the open(2)
* #defines are found there on newer systems.
*/
#include <sys/file.h>
#include <bitstring.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "common.h"
/*
* Recovery code.
*
* The basic scheme is as follows. In the EXF structure, we maintain full
* paths of a b+tree file and a mail recovery file. The former is the file
* used as backing store by the DB package. The latter is the file that
* contains an email message to be sent to the user if we crash. The two
* simple states of recovery are:
*
* + first starting the edit session:
* the b+tree file exists and is mode 700, the mail recovery
* file doesn't exist.
* + after the file has been modified:
* the b+tree file exists and is mode 600, the mail recovery
* file exists, and is exclusively locked.
*
* In the EXF structure we maintain a file descriptor that is the locked
* file descriptor for the mail recovery file. NOTE: we sometimes have to
* do locking with fcntl(2). This is a problem because if you close(2) any
* file descriptor associated with the file, ALL of the locks go away. Be
* sure to remember that if you have to modify the recovery code. (It has
* been rhetorically asked of what the designers could have been thinking
* when they did that interface. The answer is simple: they weren't.)
*
* To find out if a recovery file/backing file pair are in use, try to get
* a lock on the recovery file.
*
* To find out if a backing file can be deleted at boot time, check for an
* owner execute bit. (Yes, I know it's ugly, but it's either that or put
* special stuff into the backing file itself, or correlate the files at
* boot time, neither of which looks like fun.) Note also that there's a
* window between when the file is created and the X bit is set. It's small,
* but it's there. To fix the window, check for 0 length files as well.
*
* To find out if a file can be recovered, check the F_RCV_ON bit. Note,
* this DOES NOT mean that any initialization has been done, only that we
* haven't yet failed at setting up or doing recovery.
*
* To preserve a recovery file/backing file pair, set the F_RCV_NORM bit.
* If that bit is not set when ending a file session:
* If the EXF structure paths (rcv_path and rcv_mpath) are not NULL,
* they are unlink(2)'d, and free(3)'d.
* If the EXF file descriptor (rcv_fd) is not -1, it is closed.
*
* The backing b+tree file is set up when a file is first edited, so that
* the DB package can use it for on-disk caching and/or to snapshot the
* file. When the file is first modified, the mail recovery file is created,
* the backing file permissions are updated, the file is sync(2)'d to disk,
* and the timer is started. Then, at RCV_PERIOD second intervals, the
* b+tree file is synced to disk. RCV_PERIOD is measured using SIGALRM, which
* means that the data structures (SCR, EXF, the underlying tree structures)
* must be consistent when the signal arrives.
*
* The recovery mail file contains normal mail headers, with two additions,
* which occur in THIS order, as the FIRST TWO headers:
*
* X-vi-recover-file: file_name
* X-vi-recover-path: recover_path
*
* Since newlines delimit the headers, this means that file names cannot have
* newlines in them, but that's probably okay. As these files aren't intended
* to be long-lived, changing their format won't be too painful.
*
* Btree files are named "vi.XXXX" and recovery files are named "recover.XXXX".
*/
#define VI_FHEADER "X-vi-recover-file: "
#define VI_PHEADER "X-vi-recover-path: "
static int rcv_copy(SCR *, int, char *);
static void rcv_email(SCR *, int);
static char *rcv_gets(char *, size_t, int);
static int rcv_mailfile(SCR *, int, char *);
static int rcv_mktemp(SCR *, char *, char *, int);
static int rcv_openat(SCR *, int, const char *, int *);
/*
* rcv_tmp --
* Build a file name that will be used as the recovery file.
*
* PUBLIC: int rcv_tmp(SCR *, EXF *, char *);
*/
int
rcv_tmp(SCR *sp, EXF *ep, char *name)
{
struct stat sb;
static int warned = 0;
int fd;
char *dp, *p, path[PATH_MAX];
/*
* !!!
* ep MAY NOT BE THE SAME AS sp->ep, DON'T USE THE LATTER.
*/
if (opts_empty(sp, O_RECDIR, 0))
goto err;
dp = O_STR(sp, O_RECDIR);
if (stat(dp, &sb)) {
if (!warned) {
warned = 1;
msgq(sp, M_SYSERR, "%s", dp);
goto err;
}
return 1;
}
/* Newlines delimit the mail messages. */
for (p = name; *p; ++p)
if (*p == '\n') {
msgq(sp, M_ERR,
"Files with newlines in the name are unrecoverable");
goto err;
}
(void)snprintf(path, sizeof(path), "%s/vi.XXXXXXXXXX", dp);
if ((fd = rcv_mktemp(sp, path, dp, S_IRWXU)) == -1)
goto err;
(void)close(fd);
if ((ep->rcv_path = strdup(path)) == NULL) {
msgq(sp, M_SYSERR, NULL);
(void)unlink(path);
err: msgq(sp, M_ERR,
"Modifications not recoverable if the session fails");
return (1);
}
/* We believe the file is recoverable. */
F_SET(ep, F_RCV_ON);
return (0);
}
/*
* rcv_init --
* Force the file to be snapshotted for recovery.
*
* PUBLIC: int rcv_init(SCR *);
*/
int
rcv_init(SCR *sp)
{
EXF *ep;
recno_t lno;
ep = sp->ep;
/* Only do this once. */
F_CLR(ep, F_FIRSTMODIFY);
/* If we already know the file isn't recoverable, we're done. */
if (!F_ISSET(ep, F_RCV_ON))
return (0);
/* Turn off recoverability until we figure out if this will work. */
F_CLR(ep, F_RCV_ON);
/* Test if we're recovering a file, not editing one. */
if (ep->rcv_mpath == NULL) {
/* Build a file to mail to the user. */
if (rcv_mailfile(sp, 0, NULL))
goto err;
/* Force a read of the entire file. */
if (db_last(sp, &lno))
goto err;
/* Turn on a busy message, and sync it to backing store. */
sp->gp->scr_busy(sp,
"Copying file for recovery...", BUSY_ON);
if (ep->db->sync(ep->db, R_RECNOSYNC)) {
msgq_str(sp, M_SYSERR, ep->rcv_path,
"Preservation failed: %s");
sp->gp->scr_busy(sp, NULL, BUSY_OFF);
goto err;
}
sp->gp->scr_busy(sp, NULL, BUSY_OFF);
}
/* Turn off the owner execute bit. */
(void)chmod(ep->rcv_path, S_IRUSR | S_IWUSR);
/* We believe the file is recoverable. */
F_SET(ep, F_RCV_ON);
return (0);
err: msgq(sp, M_ERR,
"Modifications not recoverable if the session fails");
return (1);
}
/*
* rcv_sync --
* Sync the file, optionally:
* flagging the backup file to be preserved
* snapshotting the backup file and send email to the user
* sending email to the user if the file was modified
* ending the file session
*
* PUBLIC: int rcv_sync(SCR *, u_int);
*/
int
rcv_sync(SCR *sp, u_int flags)
{
EXF *ep;
int fd, rval;
char *dp, buf[1024];
/* Make sure that there's something to recover/sync. */
ep = sp->ep;
if (ep == NULL || !F_ISSET(ep, F_RCV_ON))
return (0);
/* Sync the file if it's been modified. */
if (F_ISSET(ep, F_MODIFIED)) {
/* Clear recovery sync flag. */
F_CLR(ep, F_RCV_SYNC);
if (ep->db->sync(ep->db, R_RECNOSYNC)) {
F_CLR(ep, F_RCV_ON | F_RCV_NORM);
msgq_str(sp, M_SYSERR,
ep->rcv_path, "File backup failed: %s");
return (1);
}
/* REQUEST: don't remove backing file on exit. */
if (LF_ISSET(RCV_PRESERVE))
F_SET(ep, F_RCV_NORM);
/* REQUEST: send email. */
if (LF_ISSET(RCV_EMAIL))
rcv_email(sp, ep->rcv_fd);
}
/*
* !!!
* Each time the user exec's :preserve, we have to snapshot all of
* the recovery information, i.e. it's like the user re-edited the
* file. We copy the DB(3) backing file, and then create a new mail
* recovery file, it's simpler than exiting and reopening all of the
* underlying files.
*
* REQUEST: snapshot the file.
*/
rval = 0;
if (LF_ISSET(RCV_SNAPSHOT)) {
if (opts_empty(sp, O_RECDIR, 0))
goto err;
dp = O_STR(sp, O_RECDIR);
(void)snprintf(buf, sizeof(buf), "%s/vi.XXXXXXXXXX", dp);
if ((fd = rcv_mktemp(sp, buf, dp, S_IRUSR | S_IWUSR)) == -1)
goto err;
sp->gp->scr_busy(sp,
"Copying file for recovery...", BUSY_ON);
if (rcv_copy(sp, fd, ep->rcv_path) ||
close(fd) || rcv_mailfile(sp, 1, buf)) {
(void)unlink(buf);
(void)close(fd);
rval = 1;
}
sp->gp->scr_busy(sp, NULL, BUSY_OFF);
}
if (0) {
err: rval = 1;
}
/* REQUEST: end the file session. */
if (LF_ISSET(RCV_ENDSESSION))
F_SET(sp, SC_EXIT_FORCE);
return (rval);
}
/*
* rcv_mailfile --
* Build the file to mail to the user.
*/
static int
rcv_mailfile(SCR *sp, int issync, char *cp_path)
{
EXF *ep;
GS *gp;
struct passwd *pw;
size_t len;
time_t now;
uid_t uid;
int fd;
char *dp, *p, *t, buf[4096], mpath[PATH_MAX];
char *t1, *t2, *t3;
char host[HOST_NAME_MAX+1];
gp = sp->gp;
if ((pw = getpwuid(uid = getuid())) == NULL) {
msgq(sp, M_ERR,
"Information on user id %u not found", uid);
return (1);
}
if (opts_empty(sp, O_RECDIR, 0))
return (1);
dp = O_STR(sp, O_RECDIR);
(void)snprintf(mpath, sizeof(mpath), "%s/recover.XXXXXXXXXX", dp);
if ((fd = rcv_mktemp(sp, mpath, dp, S_IRUSR | S_IWUSR)) == -1)
return (1);
/*
* XXX
* We keep an open lock on the file so that the recover option can
* distinguish between files that are live and those that need to
* be recovered. There's an obvious window between the mkstemp call
* and the lock, but it's pretty small.
*/
ep = sp->ep;
if (file_lock(sp, NULL, NULL, fd, 1) != LOCK_SUCCESS)
msgq(sp, M_SYSERR, "Unable to lock recovery file");
if (!issync) {
/* Save the recover file descriptor, and mail path. */
ep->rcv_fd = fd;
if ((ep->rcv_mpath = strdup(mpath)) == NULL) {
msgq(sp, M_SYSERR, NULL);
goto err;
}
cp_path = ep->rcv_path;
}
/*
* XXX
* We can't use stdio(3) here. The problem is that we may be using
* fcntl(2), so if ANY file descriptor into the file is closed, the
* lock is lost. So, we could never close the FILE *, even if we
* dup'd the fd first.
*/
t = sp->frp->name;
if ((p = strrchr(t, '/')) == NULL)
p = t;
else
++p;
(void)time(&now);
(void)gethostname(host, sizeof(host));
len = snprintf(buf, sizeof(buf),
"%s%s\n%s%s\n%s\n%s\n%s%s\n%s%s\n%s\n%s\n\n",
VI_FHEADER, t, /* Non-standard. */
VI_PHEADER, cp_path, /* Non-standard. */
"Reply-To: root",
"From: root (Nvi recovery program)",
"To: ", pw->pw_name,
"Subject: Nvi saved the file ", p,
"Precedence: bulk", /* For vacation(1). */
"Auto-Submitted: auto-generated");
if (len > sizeof(buf) - 1)
goto lerr;
if (write(fd, buf, len) != len)
goto werr;
len = snprintf(buf, sizeof(buf),
"%s%.24s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n\n",
"On ", ctime(&now), ", the user ", pw->pw_name,
" was editing a file named ", t, " on the machine ",
host, ", when it was saved for recovery. ",
"You can recover most, if not all, of the changes ",
"to this file using the -r option to ", getprogname(), ":\n\n\t",
getprogname(), " -r ", t);
if (len > sizeof(buf) - 1) {
lerr: msgq(sp, M_ERR, "Recovery file buffer overrun");
goto err;
}
/*
* Format the message. (Yes, I know it's silly.)
* Requires that the message end in a <newline>.
*/
#define FMTCOLS 60
for (t1 = buf; len > 0; len -= t2 - t1, t1 = t2) {
/* Check for a short length. */
if (len <= FMTCOLS) {
t2 = t1 + (len - 1);
goto wout;
}
/* Check for a required <newline>. */
t2 = strchr(t1, '\n');
if (t2 - t1 <= FMTCOLS)
goto wout;
/* Find the closest space, if any. */
for (t3 = t2; t2 > t1; --t2)
if (*t2 == ' ') {
if (t2 - t1 <= FMTCOLS)
goto wout;
t3 = t2;
}
t2 = t3;
/* t2 points to the last character to display. */
wout: *t2++ = '\n';
/* t2 points one after the last character to display. */
if (write(fd, t1, t2 - t1) != t2 - t1)
goto werr;
}
if (issync) {
rcv_email(sp, fd);
if (close(fd)) {
werr: msgq(sp, M_SYSERR, "Recovery file");
goto err;
}
}
return (0);
err: if (!issync)
ep->rcv_fd = -1;
if (fd != -1)
(void)close(fd);
return (1);
}
/*
* rcv_openat --
* Open a recovery file in the specified dir and lock it.
*
* PUBLIC: int rcv_openat(SCR *, int, const char *, int *)
*/
static int
rcv_openat(SCR *sp, int dfd, const char *name, int *locked)
{
struct stat sb;
int fd, dummy;
/*
* If it's readable, it's recoverable.
* Note: file_lock() sets the close on exec flag for us.
*/
fd = openat(dfd, name, O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
if (fd == -1)
goto bad;
/*
* Real vi recovery files are created with mode 0600.
* If not a regular file or the mode has changed, skip it.
*/
if (fstat(fd, &sb) == -1 || !S_ISREG(sb.st_mode) ||
(sb.st_mode & ALLPERMS) != (S_IRUSR | S_IWUSR))
goto bad;
if (locked == NULL)
locked = &dummy;
switch ((*locked = file_lock(sp, NULL, NULL, fd, 0))) {
case LOCK_FAILED:
/*
* XXX
* Assume that a lock can't be acquired, but that we
* should permit recovery anyway. If this is wrong,
* and someone else is using the file, we're going to
* die horribly.
*/
break;
case LOCK_SUCCESS:
break;
case LOCK_UNAVAIL:
/* If it's locked, it's live. */
goto bad;
}
return fd;
bad:
if (fd != -1)
close(fd);
return -1;
}
/*
* people making love
* never exactly the same
* just like a snowflake
*
* rcv_list --
* List the files that can be recovered by this user.
*
* PUBLIC: int rcv_list(SCR *);
*/
int
rcv_list(SCR *sp)
{
struct dirent *dp;
struct stat sb;
DIR *dirp;
int fd;
FILE *fp;
int found;
char *p, *t, file[PATH_MAX], path[PATH_MAX];
/* Open the recovery directory for reading. */
if (opts_empty(sp, O_RECDIR, 0))
return (1);
p = O_STR(sp, O_RECDIR);
if ((dirp = opendir(p)) == NULL) {
msgq_str(sp, M_SYSERR, p, "recdir: %s");
return (1);
}
/* Read the directory. */
for (found = 0; (dp = readdir(dirp)) != NULL;) {
if (strncmp(dp->d_name, "recover.", 8))
continue;
if ((fd = rcv_openat(sp, dirfd(dirp), dp->d_name, NULL)) == -1)
continue;
/* Check the headers. */
if ((fp = fdopen(fd, "r")) == NULL) {
close(fd);
continue;
}
if (fgets(file, sizeof(file), fp) == NULL ||
strncmp(file, VI_FHEADER, sizeof(VI_FHEADER) - 1) ||
(p = strchr(file, '\n')) == NULL ||
fgets(path, sizeof(path), fp) == NULL ||
strncmp(path, VI_PHEADER, sizeof(VI_PHEADER) - 1) ||
(t = strchr(path, '\n')) == NULL) {
msgq_str(sp, M_ERR, dp->d_name,
"%s: malformed recovery file");
goto next;
}
*p = *t = '\0';
/*
* If the file doesn't exist, it's an orphaned recovery file,
* toss it.
*
* XXX
* This can occur if the backup file was deleted and we crashed
* before deleting the email file.
*/
errno = 0;
if (stat(path + sizeof(VI_PHEADER) - 1, &sb) &&
errno == ENOENT) {
(void)unlinkat(dirfd(dirp), dp->d_name, 0);
goto next;
}
/* Get the last modification time and display. */
(void)fstat(fd, &sb);
(void)printf("%.24s: %s\n",
ctime(&sb.st_mtime), file + sizeof(VI_FHEADER) - 1);
found = 1;
/* Close, discarding lock. */
next: (void)fclose(fp);
}
if (found == 0)
(void)printf("%s: No files to recover\n", getprogname());
(void)closedir(dirp);
return (0);
}
/*
* rcv_read --
* Start a recovered file as the file to edit.
*
* PUBLIC: int rcv_read(SCR *, FREF *);
*/
int
rcv_read(SCR *sp, FREF *frp)
{
struct dirent *dp;
struct stat sb;
DIR *dirp;
EXF *ep;
struct timespec rec_mtim;
int fd, found, lck, requested, sv_fd;
char *name, *p, *t, *rp, *recp, *pathp;
char file[PATH_MAX], path[PATH_MAX], recpath[PATH_MAX];
if (opts_empty(sp, O_RECDIR, 0))
return (1);
rp = O_STR(sp, O_RECDIR);
if ((dirp = opendir(rp)) == NULL) {
msgq_str(sp, M_SYSERR, rp, "%s");
return (1);
}
name = frp->name;
sv_fd = -1;
rec_mtim.tv_sec = rec_mtim.tv_nsec = 0;
recp = pathp = NULL;
for (found = requested = 0; (dp = readdir(dirp)) != NULL;) {
if (strncmp(dp->d_name, "recover.", 8))
continue;
if ((size_t)snprintf(recpath, sizeof(recpath), "%s/%s",
rp, dp->d_name) >= sizeof(recpath))
continue;
if ((fd = rcv_openat(sp, dirfd(dirp), dp->d_name, &lck)) == -1)
continue;
/* Check the headers. */
if (rcv_gets(file, sizeof(file), fd) == NULL ||
strncmp(file, VI_FHEADER, sizeof(VI_FHEADER) - 1) ||
(p = strchr(file, '\n')) == NULL ||
rcv_gets(path, sizeof(path), fd) == NULL ||
strncmp(path, VI_PHEADER, sizeof(VI_PHEADER) - 1) ||
(t = strchr(path, '\n')) == NULL) {
msgq_str(sp, M_ERR, recpath,
"%s: malformed recovery file");
goto next;
}
*p = *t = '\0';
++found;
/*
* If the file doesn't exist, it's an orphaned recovery file,
* toss it.
*
* XXX
* This can occur if the backup file was deleted and we crashed
* before deleting the email file.
*/
errno = 0;
if (stat(path + sizeof(VI_PHEADER) - 1, &sb) &&
errno == ENOENT) {
(void)unlink(dp->d_name);
goto next;
}
/* Check the file name. */
if (strcmp(file + sizeof(VI_FHEADER) - 1, name))
goto next;
++requested;
/*
* If we've found more than one, take the most recent.
*/
(void)fstat(fd, &sb);
if (recp == NULL ||
timespeccmp(&rec_mtim, &sb.st_mtim, <)) {
p = recp;
t = pathp;
if ((recp = strdup(recpath)) == NULL) {
msgq(sp, M_SYSERR, NULL);
recp = p;
goto next;
}
if ((pathp = strdup(path)) == NULL) {
msgq(sp, M_SYSERR, NULL);
free(recp);
recp = p;
pathp = t;
goto next;
}
if (p != NULL) {
free(p);
free(t);
}
rec_mtim = sb.st_mtim;
if (sv_fd != -1)
(void)close(sv_fd);
sv_fd = fd;
} else
next: (void)close(fd);
}
(void)closedir(dirp);
if (recp == NULL) {
msgq_str(sp, M_INFO, name,
"No files named %s, readable by you, to recover");
return (1);
}
if (found) {
if (requested > 1)
msgq(sp, M_INFO,
"There are older versions of this file for you to recover");
if (found > requested)
msgq(sp, M_INFO,
"There are other files for you to recover");
}
/*
* Create the FREF structure, start the btree file.
*
* XXX
* file_init() is going to set ep->rcv_path.
*/
if (file_init(sp, frp, pathp + sizeof(VI_PHEADER) - 1, 0)) {
free(recp);
free(pathp);
(void)close(sv_fd);
return (1);
}
/*
* We keep an open lock on the file so that the recover option can
* distinguish between files that are live and those that need to
* be recovered. The lock is already acquired, just copy it.
*/
ep = sp->ep;
ep->rcv_mpath = recp;
ep->rcv_fd = sv_fd;
if (lck != LOCK_SUCCESS)
F_SET(frp, FR_UNLOCKED);
/* We believe the file is recoverable. */
F_SET(ep, F_RCV_ON);
return (0);
}
/*
* rcv_copy --
* Copy a recovery file.
*/
static int
rcv_copy(SCR *sp, int wfd, char *fname)
{
int nr, nw, off, rfd;
char buf[8 * 1024];
if ((rfd = open(fname, O_RDONLY)) == -1)
goto err;
while ((nr = read(rfd, buf, sizeof(buf))) > 0)
for (off = 0; nr; nr -= nw, off += nw)
if ((nw = write(wfd, buf + off, nr)) < 0)
goto err;
if (nr == 0)
return (0);
err: msgq_str(sp, M_SYSERR, fname, "%s");
return (1);
}
/*
* rcv_gets --
* Fgets(3) for a file descriptor.
*/
static char *
rcv_gets(char *buf, size_t len, int fd)
{
int nr;
char *p;
if ((nr = read(fd, buf, len - 1)) == -1)
return (NULL);
buf[nr] = '\0';
if ((p = strchr(buf, '\n')) == NULL)
return (NULL);
(void)lseek(fd, (off_t)((p - buf) + 1), SEEK_SET);
return (buf);
}
/*
* rcv_mktemp --
* Paranoid make temporary file routine.
*/
static int
rcv_mktemp(SCR *sp, char *path, char *dname, int perms)
{
int fd;
/*
* !!!
* We expect mkstemp(3) to set the permissions correctly. On
* historic System V systems, mkstemp didn't. Do it here, on
* GP's. This also protects us from users with stupid umasks.
*
* XXX
* The variable perms should really be a mode_t.
*/
if ((fd = mkstemp(path)) == -1 || fchmod(fd, perms) == -1) {
msgq_str(sp, M_SYSERR, dname, "%s");
if (fd != -1) {
close(fd);
unlink(path);
fd = -1;
}
}
return (fd);
}
/*
* rcv_email --
* Send email.
*/
static void
rcv_email(SCR *sp, int fd)
{
struct stat sb;
pid_t pid;
/*
* In secure mode, our pledge(2) includes neither "proc"
* nor "exec". So simply skip sending the mail.
* Later vi -r still works because rcv_mailfile()
* already did all the necessary setup.
*/
if (O_ISSET(sp, O_SECURE))
return;
if (_PATH_SENDMAIL[0] != '/' || stat(_PATH_SENDMAIL, &sb) == -1)
msgq_str(sp, M_SYSERR,
_PATH_SENDMAIL, "not sending email: %s");
else {
/*
* !!!
* If you need to port this to a system that doesn't have
* sendmail, the -t flag causes sendmail to read the message
* for the recipients instead of specifying them some other
* way.
*/
switch (pid = fork()) {
case -1: /* Error. */
msgq(sp, M_SYSERR, "fork");
break;
case 0: /* Sendmail. */
if (lseek(fd, 0, SEEK_SET) == -1) {
msgq(sp, M_SYSERR, "lseek");
_exit(127);
}
if (fd != STDIN_FILENO) {
if (dup2(fd, STDIN_FILENO) == -1) {
msgq(sp, M_SYSERR, "dup2");
_exit(127);
}
close(fd);
}
execl(_PATH_SENDMAIL, "sendmail", "-t", (char *)NULL);
msgq(sp, M_SYSERR, _PATH_SENDMAIL);
_exit(127);
default: /* Parent. */
while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
continue;
break;
}
}
}
| 2.21875 | 2 |
2024-11-18T20:55:37.025717+00:00 | 2021-09-07T16:19:14 | 2beeaf55ea53f8cdbbb7fe91879d00b8d3a04055 | {
"blob_id": "2beeaf55ea53f8cdbbb7fe91879d00b8d3a04055",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-07T16:19:14",
"content_id": "730781d427f52f99030669ad375a9e61eaf947dd",
"detected_licenses": [
"Unlicense"
],
"directory_id": "8ba97b32627b0cd8e768fa8d3de3cb379f0fc3e5",
"extension": "c",
"filename": "entab.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 387881249,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 586,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Introduction/10_External_Vars_and_Scope/code/entab.c",
"provenance": "stackv2-0092.json.gz:43303",
"repo_name": "jazznerd206/KandR",
"revision_date": "2021-09-07T16:19:14",
"revision_id": "ceced7d0dfa3f177863bcbbb3118b0e1d0a652a0",
"snapshot_id": "1f97bb0548158512a77fb5e2040f959d78539ec2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jazznerd206/KandR/ceced7d0dfa3f177863bcbbb3118b0e1d0a652a0/Introduction/10_External_Vars_and_Scope/code/entab.c",
"visit_date": "2023-08-03T19:07:15.512617"
} | stackv2 | // replace all tabs with the corresponding amount of other characters
#include <stdio.h>
#include <ctype.h>
#define TAB 8
void main()
{
int c, i, j, blank, tab;
blank = tab = i = 0;
while ((c = getchar()) != EOF) {
if (isalpha(c) != 0 || isdigit(c) != 0) {
printf("This function only accepts blank spaces.");
}
if (c == ' ') {
++blank;
if (blank == 7) {
++tab;
blank = 0;
}
}
else if (c == '\n') {
while (tab > 0) {
putchar('\t');
--tab;
}
while (blank > 0) {
putchar(' ');
--blank;
}
printf("|<- EOF\n");
}
}
}
| 3.1875 | 3 |
2024-11-18T20:55:37.388108+00:00 | 2018-11-23T05:15:07 | aba4a539b3fa49bf20aba75933a1acb6297ad13d | {
"blob_id": "aba4a539b3fa49bf20aba75933a1acb6297ad13d",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-23T05:15:07",
"content_id": "8dd476350812a7b13102f4f158360eb28659c5c4",
"detected_licenses": [
"MIT"
],
"directory_id": "133ee2ed3b5f8313ab77419b7cf0c09389687105",
"extension": "c",
"filename": "todoer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 158776013,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7261,
"license": "MIT",
"license_type": "permissive",
"path": "/todoer.c",
"provenance": "stackv2-0092.json.gz:43432",
"repo_name": "Larisho/todoer",
"revision_date": "2018-11-23T05:15:07",
"revision_id": "da7b950be09349b38f6a1725e205763d775ca387",
"snapshot_id": "790daeeaccd6df1f23d9facf7f0ecbbc9a36e0a2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Larisho/todoer/da7b950be09349b38f6a1725e205763d775ca387/todoer.c",
"visit_date": "2020-04-07T22:34:44.536069"
} | stackv2 | #include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include "queue.h"
#define PATH_MAX 4096
typedef struct {
char base_dir[PATH_MAX];
char *exclude_dirs;
bool output_count;
} Options;
int searchFile(const char *filename, bool count_only) {
FILE *file = fopen(filename, "r");
if (file == NULL)
return 0;
int line_number = 0;
int matches = 0;
bool found_match = false;
int chars_read = 0;
size_t n = 0;
char *line = NULL;
while ((chars_read = getline(&line, &n, file)) > 0) {
line_number++;
char *pch = strstr(line, "// TODO");
if (pch) {
matches++;
if (!count_only) {
if (!found_match) {
printf("%s:\n", filename);
found_match = true;
}
char line_col[11];
snprintf(line_col, 11, "(%d:%td)", line_number, pch - line + 1);
printf("%-4s%11s %s%s", "", line_col, pch, (line[chars_read - 1] == '\n' ? "" : "\n"));
}
}
}
if (found_match) {
printf("\n");
}
free(line);
fclose(file);
return matches;
}
int isValidDirectory(const char *dir) {
if (dir[0] == '.') {
if (dir[1] == '\0' || (dir[1] == '.' && dir[2] == '\0')) {
return 0;
}
}
return 1;
}
bool is_excluded(char d_name[256], char *excluded) {
if (excluded == NULL)
return false;
char buffer[256] = {0};
char *i = excluded;
int buf = 0;
for (; *i; buf++) {
if (*i != ';' && buf < 255) {
buffer[buf] = *i;
i++;
continue;
}
buffer[buf] = '\0';
if (strncmp(buffer, d_name, 256) == 0) {
return true;
}
memset(buffer, 0, sizeof buffer);
buf = -1;
i++;
}
if (buf > -1 && strncmp(buffer, d_name, 256) == 0) {
return true;
}
return false;
}
void walkDirectoryTree(Options *opts) {
struct dirent *dir; /* Directory object */
struct stat file_stat; /* Stats object */
char *base; /* Absolute value of current directory */
char *path = malloc(PATH_MAX * sizeof(char)); /* Allocate space for path */
int total_matches = 0;
/* While items are still left in the queue... */
while ((base = dequeue())) {
/* Open directory stream */
DIR *d = opendir(base); /* Directory stream */
if (errno != 0) {
/* If user doesn't have read access, skip it */
if (errno == EACCES) {
errno = 0;
free(base);
continue;
}
if (errno == ENOTDIR || errno == ENOENT) {
perror(base);
free(base);
free(path);
destroy_queue();
exit(-1);
}
}
if (d) { /* If stream isn't null... */
while ((dir = readdir(d))) { /* For each file in the current directory... */
/* compose path, adding separator if needed */
sprintf(path, "%s%s%s", base, (base[strlen(base)-1] == '/' ? "" : "/"), dir->d_name);
lstat(path, &file_stat); /* Get stats for path */
if (errno != 0) {
if (errno == EIO || errno == ENOENT || errno == ELOOP) {
perror(path);
free(path);
free(base);
closedir(d);
destroy_queue();
exit(-1);
}
else {
errno = 0;
continue;
}
}
if (S_ISDIR(file_stat.st_mode) && isValidDirectory(dir->d_name)) { /* If path points to directory and it isn't '.' or '..'... */
if (!is_excluded(dir->d_name, opts->exclude_dirs))
enqueue(path); /* Add the directory to the queue */
}
else if (S_ISREG(file_stat.st_mode)) { // TODO: Only search if file && not binary file
total_matches += searchFile(path, opts->output_count); /* Search file for pattern */
}
}
free(base);
}
closedir(d); /* Be nice and close the directory stream :) */
}
if (opts->output_count)
printf("TODOs: %d\n", total_matches);
free(path);
}
void print_help() {
printf("DESCRIPTION:\n"
" This program recursively searches the files in the CWD (current working directory) for TODO comments\n"
" and prints them to STDOUT with file and line/column number information.\n"
"\n"
"Usage: todoer [OPTIONS]\n"
"\n"
"OPTIONS:\n"
" -c Just print the number of TODOs found\n"
" -d <PATH> Start searching for TODOs in the directory specified by path.\n"
" Path must point to a directory.\n"
" -e <DNAMES> Exclude directories whose name matches of the names provided.\n"
" Ex: -e 'build_output;dist' to exclude files in the 'build_output' and 'dist' directories.\n"
"\n"
"EXAMPLES:\n"
" todoer -d ~/source/my-proj -e 'dist;node_modules' Get all the TODOs in the my-proj directory while\n"
" excluding files in the 'dist' and 'node_modules'\n"
" directories.\n"
" todoer -cd ~/source/my-proj Print the number of TODOs found in the my-proj\n"
" directory.\n"
"\n"
"LICENSE:\n"
" MIT\n\n");
}
void parse(int argc, char **argv, Options *opts) {
int match;
bool directory_assigned = false;
bool output_count_assigned = false;
bool exclude_dirs_assigned = false;
while ((match = getopt(argc, argv, "d:e:ch")) != -1) {
switch (match) {
case 'd':
strncpy(opts->base_dir, optarg, PATH_MAX);
directory_assigned = true;
break;
case 'c':
opts->output_count = true;
output_count_assigned = true;
break;
case 'e':
opts->exclude_dirs = strdup(optarg);
exclude_dirs_assigned = true;
break;
case 'h':
print_help();
exit(0);
break;
case '?':
// TODO(gab): Maybe consider removing this logic since the getopt library prints stuff out
if (optopt == 'd' || optopt == 'e')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
exit(-1);
}
}
if (!directory_assigned) {
getcwd(opts->base_dir, PATH_MAX);
}
if (!output_count_assigned) {
opts->output_count = false;
}
if (!exclude_dirs_assigned) {
opts->exclude_dirs = NULL;
}
}
int main(int argc, char **argv) {
Options opts;
parse(argc, argv, &opts);
enqueue(opts.base_dir);
walkDirectoryTree(&opts);
free(opts.exclude_dirs); /* Free pointer here (allocated using strdup) */
destroy_queue();
return 0;
}
/* Test code for the is_excluded method */
/* struct Test { */
/* char buffer[256]; */
/* char *exclusion_list; */
/* }; */
/* int main() { */
/* struct Test arr[7] = { {"node_modules", "src;node;node_modules"}, */
/* {"src", "node;nol;hold;"}, */
/* {"weee", "weee"}, */
/* {"holdthephone!", "hold;the;phone;!"}, */
/* {"", "w00t"}, */
/* {"w00t", ""}, */
/* {"", ""} }; */
/* for (int i = 0; i < 7; i++) { */
/* printf("d_name: '%s', exclusion list: '%s', is_excluded?: %s\n", */
/* arr[i].buffer, arr[i].exclusion_list, */
/* is_excluded(arr[i].buffer, arr[i].exclusion_list) ? "excluded": "not excluded"); */
/* } */
/* } */
| 2.6875 | 3 |
2024-11-18T20:55:37.464008+00:00 | 2023-06-12T02:40:29 | ed7e044c81548e932eb60ee0c881dd7ae3f703ba | {
"blob_id": "ed7e044c81548e932eb60ee0c881dd7ae3f703ba",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-12T02:40:29",
"content_id": "118e2a8b035ca5e5fa3d344d36bdd51e1b9a1e8b",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "678fd5a42f580d442b7cb1dc279249e968b285ff",
"extension": "h",
"filename": "file.h",
"fork_events_count": 20,
"gha_created_at": "2011-05-03T03:31:43",
"gha_event_created_at": "2023-06-12T09:32:18",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 1694539,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3341,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/include/fxcg/file.h",
"provenance": "stackv2-0092.json.gz:43561",
"repo_name": "Jonimoose/libfxcg",
"revision_date": "2023-06-12T02:40:29",
"revision_id": "acf23fd3104706f5da28d44731e54ed6615678b1",
"snapshot_id": "b0159220189775fed386f6b3195c9761b598f8ee",
"src_encoding": "UTF-8",
"star_events_count": 88,
"url": "https://raw.githubusercontent.com/Jonimoose/libfxcg/acf23fd3104706f5da28d44731e54ed6615678b1/include/fxcg/file.h",
"visit_date": "2023-06-22T06:30:18.787728"
} | stackv2 | #ifndef _FXCG_FILE_H
#define _FXCG_FILE_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
enum
{
CREATEMODE_FILE = 1,
CREATEMODE_FOLDER = 5
};
enum
{
READ = 0,
READ_SHARE = 1,
WRITE = 2,
READWRITE = 3,
READWRITE_SHARE = 4
};
int Bfile_CloseFile_OS( int HANDLE );
int Bfile_CreateEntry_OS( const unsigned short*filename, int mode, size_t *size);
int Bfile_DeleteEntry( const unsigned short *filename );
int Bfile_RenameEntry( const unsigned short *oldpath, const unsigned short *newpath );
int Bfile_FindClose( int FindHandle );
int Bfile_FindFirst( const char *pathname, int *FindHandle, char *foundfile, void *fileinfo );
int Bfile_FindFirst_NON_SMEM( const char *pathname, int *FindHandle, char *foundfile, void *fileinfo );
int Bfile_FindNext( int FindHandle, char *foundfile, char *fileinfo );
int Bfile_FindNext_NON_SMEM( int FindHandle, char *foundfile, char *fileinfo );
int Bfile_GetFileSize_OS(int handle);
int Bfile_OpenFile_OS(const unsigned short *filename, int mode, int null);
int Bfile_ReadFile_OS( int HANDLE, void *buf, int size, int readpos );
int Bfile_SeekFile_OS( int handle, int pos );
int Bfile_TellFile_OS( int handle );
int Bfile_WriteFile_OS( int HANDLE, const void *buf, int size );
void Bfile_NameToStr_ncpy(char* dest, const unsigned short* source, size_t n);
void Bfile_StrToName_ncpy(unsigned short *dest, const char *source, size_t n);
int Bfile_Name_MatchMask( const short*mask, const short*filename );
int Bfile_GetMediaFree_OS( unsigned short*media_id, int*freespace );
/*
Given a file handle and a 4 KB aligned block address within the file,
returns the direct memory access pointer for that file.
!Warning! This address is no longer valid if any OS file operations are
performed.
*/
int Bfile_GetBlockAddress(int handle, int blockAddress, unsigned char** outPtr);
int SMEM_FindFirst( const unsigned short*pattern, unsigned short*foundfile );
int MCS_CreateDirectory( unsigned char*dir );
int MCS_DeleteDirectory( unsigned char*dir );
int MCSDelVar2( unsigned char*dir, unsigned char*item );
int MCS_GetCapa( int*current_bottom );
int MCSGetData1( int offset, int len_to_copy, void*buffer );
int MCSGetDlen2( unsigned char*dir, unsigned char*item, int*data_len );
int MCS_GetMainMemoryStart( void );
int MCSGetOpenItem( unsigned char*item );
int MCSOvwDat2( unsigned char*dir, unsigned char*item, int bytes_to_write, void*buffer, int write_offset );
int MCSPutVar2( unsigned char*dir, unsigned char*item, int data_len, void*buffer );
int MCS_WriteItem( unsigned char*dir, unsigned char*item, short itemtype, int data_length, int buffer );
int MCS_GetState( int*maxspace, int*currentload, int*remainingspace );
/* not sure if these should belong in here, in display.h or in app.h
(these are syscalls that display, have their own keyboard "life" and are related to files)
Also, since SaveFileD... and OpenFileD... only work with g3p files, (at least until we find more about their parameters),
their names are subject to change. (gbl08ma)
*/
int SaveFileDialog( unsigned short *filenamebuffer, int mode );
int OverwriteConfirmation( char*name, int mode );
int OpenFileDialog( unsigned short keycode, unsigned short *filenamebuffer, int filenamebufferlength );
int ConfirmFileOverwriteDialog( unsigned short *filename );
#ifdef __cplusplus
}
#endif
#endif
| 2.28125 | 2 |
2024-11-18T20:55:37.569555+00:00 | 2016-06-10T05:06:27 | dcf7fc6d2c209883d6a8667efd6b5e36b4f25836 | {
"blob_id": "dcf7fc6d2c209883d6a8667efd6b5e36b4f25836",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-10T05:06:27",
"content_id": "cd173b04ab56b46e41ad76c3aebab41190409235",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "560e77115c6d04308c1b1f30e2213baa2e2b1d4c",
"extension": "c",
"filename": "bdd_cal.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60823531,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1390,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/bdd_cal.c",
"provenance": "stackv2-0092.json.gz:43691",
"repo_name": "bernied/bitbuddy",
"revision_date": "2016-06-10T05:06:27",
"revision_id": "1c4c7d0c2df935527951a478c5114d5c6e40282e",
"snapshot_id": "4fde2fdfe99155f4c279357efd43029fcea88e3e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bernied/bitbuddy/1c4c7d0c2df935527951a478c5114d5c6e40282e/src/bdd_cal.c",
"visit_date": "2021-01-19T11:29:14.787645"
} | stackv2 | #include "bdd_cal.h"
static Cal_BddManager manager =NULL;
static Cal_Bdd* vars;
BB_bdd
BB_false()
{
return Cal_BddZero(manager);
}
BB_bdd
BB_true()
{
return Cal_BddOne(manager);
}
BB_bdd
BB_not(BB_bdd bdd)
{
return BB_addref(Cal_BddNot(manager, bdd));
}
BB_bdd
BB_apply(BB_bdd lhs, BB_bdd rhs, BB_op_type op)
{
BB_bdd bdd;
switch(op)
{
case BB_AND:
bdd = Cal_BddAnd(manager, lhs, rhs);
break;
case BB_OR:
bdd = Cal_BddOr(manager, lhs, rhs);
break;
case BB_XOR:
bdd = Cal_BddXor(manager, lhs, rhs);
break;
}
return BB_addref(bdd);
}
BB_bdd
BB_addref(BB_bdd bdd)
{
Cal_BddUnFree(manager, bdd);
return bdd;
}
BB_bdd
BB_delref(BB_bdd bdd)
{
Cal_BddFree(manager, bdd);
return bdd;
}
void
BB_setvarnum(int vars)
{
//LAMb
}
BB_bdd
BB_ithvar(int i)
{
return vars[i];
}
int
BB_satcount(BB_bdd bdd)
{
return 0; //LAMb
}
void
BB_print_dot(int n, BB_bdd bdd)
{
}
void
BB_save(BB_bdd bdd, char* name)
{
FILE* file = fopen(name, "w");
Cal_BddDumpBdd(manager, bdd, NULL, file);
fclose(file);
}
void
BB_init(struct arg_t* args, int inputs, int outputs)
{
manager = Cal_BddManagerInit();
vars = (Cal_Bdd*) malloc((inputs+1) * sizeof(Cal_Bdd));
for(int i=0; i <= inputs; ++i) {
vars[i] = Cal_BddManagerCreateNewVarLast(manager);
}
}
void
BB_done()
{
Cal_BddManagerQuit(manager);
manager = NULL;
}
| 2.578125 | 3 |
2024-11-18T20:55:37.659956+00:00 | 2018-12-23T13:01:25 | be4cdbea68b9a946c15358678abfd542fa9ee6a7 | {
"blob_id": "be4cdbea68b9a946c15358678abfd542fa9ee6a7",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-23T13:01:25",
"content_id": "7f9f8fa809d74510ad6987294e101fa2162b0308",
"detected_licenses": [
"MIT"
],
"directory_id": "2473eaf6946fa24192a3fd5513eab91044d672e3",
"extension": "h",
"filename": "draw.h",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87583853,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2042,
"license": "MIT",
"license_type": "permissive",
"path": "/switch/include/draw.h",
"provenance": "stackv2-0092.json.gz:43821",
"repo_name": "FlagBrew/Pickr",
"revision_date": "2018-12-23T13:01:25",
"revision_id": "7db645f4d0dd651e869f593266b1b0e8965e8db8",
"snapshot_id": "db0000095ab5f34712aa868303e175035bc41c07",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/FlagBrew/Pickr/7db645f4d0dd651e869f593266b1b0e8965e8db8/switch/include/draw.h",
"visit_date": "2021-10-09T07:12:25.616110"
} | stackv2 | #ifndef DRAW_H
#define DRAW_H
#include <switch.h>
#include "types.h"
extern const ffnt_header_t tahoma24_nxfnt;
extern const ffnt_header_t interuiregular20_nxfnt;
extern const ffnt_header_t interuimedium42_nxfnt;
#define font24 &tahoma24_nxfnt
#define font20 &interuiregular20_nxfnt
#define font42 &interuimedium42_nxfnt
extern u8* g_framebuf;
extern u32 g_framebufWidth;
// the following code is from nx-hbmenu
// https://github.com/switchbrew/nx-hbmenu/blob/master/common/common.h#L63
static inline u8 BlendColor(u32 src, u32 dst, u8 alpha)
{
u8 one_minus_alpha = (u8)255 - alpha;
return (dst*alpha + src*one_minus_alpha)/(u8)255;
}
static inline color_t MakeColor(u8 r, u8 g, u8 b, u8 a)
{
color_t clr;
clr.r = r;
clr.g = g;
clr.b = b;
clr.a = a;
return clr;
}
static inline void DrawPixel(u32 x, u32 y, color_t clr)
{
if (x >= 1280 || y >= 720)
return;
u32 off = (y * g_framebufWidth + x)*4;
g_framebuf[off] = BlendColor(g_framebuf[off], clr.r, clr.a); off++;
g_framebuf[off] = BlendColor(g_framebuf[off], clr.g, clr.a); off++;
g_framebuf[off] = BlendColor(g_framebuf[off], clr.b, clr.a); off++;
g_framebuf[off] = 0xff;
}
static inline void Draw4PixelsRaw(u32 x, u32 y, color_t clr)
{
if (x >= 1280 || y >= 720 || x > 1280-4)
return;
u32 color = clr.r | (clr.g<<8) | (clr.b<<16) | (0xff<<24);
u128 val = color | ((u128)color<<32) | ((u128)color<<64) | ((u128)color<<96);
u32 off = (y * g_framebufWidth + x)*4;
*((u128*)&g_framebuf[off]) = val;
}
void rectangle(u32 x, u32 y, u16 w, u16 h, color_t color);
void DrawPixel(u32 x, u32 y, color_t clr);
void DrawText(const ffnt_header_t* font, u32 x, u32 y, color_t clr, const char* text);
void GetTextDimensions(const ffnt_header_t* font, const char* text, u32* width_out, u32* height_out);
void DrawImage(int x, int y, int width, int height, const u8 *image, ImageMode mode);
void DrawImageBlend(int x, int y, int width, int height, const u8 *image, ImageMode mode, color_t color);
#endif | 2.21875 | 2 |
2024-11-18T20:55:39.398511+00:00 | 2012-09-06T18:24:44 | 6f4389c9529be35262f4207d34c80657efebc75f | {
"blob_id": "6f4389c9529be35262f4207d34c80657efebc75f",
"branch_name": "refs/heads/version/2.0.0",
"committer_date": "2012-09-06T18:24:44",
"content_id": "8ab796ecb5240e4b88a5c9945db1d46135610f77",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "5c5ef945a8f49aafb109042291baa22d25e4793a",
"extension": "c",
"filename": "bplus_iterator.c",
"fork_events_count": 4,
"gha_created_at": "2012-05-30T07:15:36",
"gha_event_created_at": "2013-10-09T15:01:38",
"gha_language": "C",
"gha_license_id": null,
"github_id": 4492053,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4855,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/src/bplus_iterator.c",
"provenance": "stackv2-0092.json.gz:44077",
"repo_name": "berenm/bplus-tree",
"revision_date": "2012-09-06T18:24:44",
"revision_id": "3f543381a017d080d5d3d16be4b513dfd2db50bc",
"snapshot_id": "72d403a1dda65371672c5c387bf534beff30144f",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/berenm/bplus-tree/3f543381a017d080d5d3d16be4b513dfd2db50bc/src/bplus_iterator.c",
"visit_date": "2021-01-15T19:28:27.303885"
} | stackv2 | /**
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
*/
#include "bplus_iterator.h"
#include "bplus_leaf.h"
#include "bplus_search.h"
static BplusIterator* bplus_iterator_new_full(BplusTree const* tree,
BplusLeaf const* leaf_from, BplusItem const* item_from,
BplusLeaf const* leaf_to, BplusItem const* item_to)
{
BplusIterator* iterator = g_slice_new(BplusIterator);
iterator->leaf_from = leaf_from;
iterator->item_from = item_from;
iterator->leaf_to = leaf_to;
iterator->item_to = item_to;
iterator->item = item_from;
iterator->leaf = leaf_from;
return iterator;
}
static BplusIterator* bplus_iterator_new_to_last(BplusTree const* tree, BplusLeaf const* leaf_from, BplusItem const* item_from)
{
return bplus_iterator_new_full(tree, leaf_from, item_from, tree->last, tree->last->node.items + tree->last->node.length);
}
static BplusIterator* bplus_iterator_new_from_first(BplusTree const* tree, BplusLeaf const* leaf_to, BplusItem const* item_to)
{
return bplus_iterator_new_full(tree, tree->first, tree->first->node.items, leaf_to, item_to);
}
BplusIterator* bplus_iterator_new(BplusTree const* tree)
{
return bplus_iterator_new_to_last(tree, tree->first, tree->first->node.items);
}
void bplus_iterator_destroy(BplusIterator* iterator)
{
g_return_if_fail(iterator != NULL);
g_slice_free(BplusIterator, iterator);
}
gboolean bplus_iterator_next(BplusIterator* iterator)
{
g_return_val_if_fail(iterator != NULL, FALSE);
BplusItem const* const next = iterator->item + 1;
BplusLeaf const* const leaf = iterator->leaf;
if (next == iterator->item_to)
return FALSE;
if (next - leaf->node.items < leaf->node.length)
{
++iterator->item;
}
else
{
if (leaf->right == NULL)
return FALSE;
iterator->leaf = leaf->right;
iterator->item = leaf->right->node.items;
}
return TRUE;
}
gboolean bplus_iterator_previous(BplusIterator* iterator)
{
g_return_val_if_fail(iterator != NULL, FALSE);
BplusItem const* const item = iterator->item;
BplusLeaf const* const leaf = iterator->leaf;
if (item == iterator->item_from)
return FALSE;
if (item - leaf->node.items == 0)
{
if (leaf->left == NULL)
return FALSE;
iterator->leaf = leaf->left;
iterator->item = leaf->left->node.items + leaf->left->node.length;
}
--iterator->item;
return TRUE;
}
BplusItem const* bplus_iterator_get_item(BplusIterator const* iterator)
{
g_return_val_if_fail(iterator != NULL, NULL);
if (iterator->item_from == iterator->item_to)
return NULL;
return iterator->item;
}
BplusIterator* bplus_tree_first(BplusTree const* tree)
{
g_return_val_if_fail(tree != NULL, NULL);
return bplus_iterator_new(tree);
}
BplusIterator* bplus_iterator_from_key(BplusTree const* tree, BplusKey const key)
{
g_return_val_if_fail(tree != NULL, NULL);
BplusPath path_from;
BplusPath path_to;
bplus_tree_get_paths_to_key_range(tree, key, key, &path_from, &path_to);
return bplus_iterator_new_to_last(tree, (BplusLeaf*) path_from.leaf, path_from.leaf->items + path_from.index[0]);
}
BplusIterator* bplus_iterator_to_key(BplusTree const* tree, BplusKey const key)
{
g_return_val_if_fail(tree != NULL, NULL);
BplusPath path_from;
BplusPath path_to;
bplus_tree_get_paths_to_key_range(tree, key, key, &path_from, &path_to);
return bplus_iterator_new_from_first(tree, (BplusLeaf*) path_to.leaf, path_to.leaf->items + path_to.index[0]);
}
BplusIterator* bplus_iterator_for_key(BplusTree const* tree, BplusKey const key)
{
g_return_val_if_fail(tree != NULL, NULL);
BplusPath path_from;
BplusPath path_to;
bplus_tree_get_paths_to_key_range(tree, key, key, &path_from, &path_to);
return bplus_iterator_new_full(tree,
(BplusLeaf*) path_from.leaf, path_from.leaf->items + path_from.index[0],
(BplusLeaf*) path_to.leaf, path_to.leaf->items + path_to.index[0]);
}
BplusIterator* bplus_iterator_for_key_range(BplusTree const* tree, BplusKey const key_from, BplusKey const key_to)
{
g_return_val_if_fail(tree != NULL, NULL);
BplusPath path_from;
BplusPath path_to;
bplus_tree_get_paths_to_key_range(tree, key_from, key_to, &path_from, &path_to);
return bplus_iterator_new_full(tree,
(BplusLeaf*) path_from.leaf, path_from.leaf->items + path_from.index[0],
(BplusLeaf*) path_to.leaf, path_to.leaf->items + path_to.index[0]);
}
| 2.59375 | 3 |
2024-11-18T20:55:39.618212+00:00 | 2020-09-10T11:51:01 | 4622937dd2dc3f257fdef00435924c048b39b903 | {
"blob_id": "4622937dd2dc3f257fdef00435924c048b39b903",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-10T11:51:01",
"content_id": "d1b6aed0564c7ee712d7c865e50310728350b944",
"detected_licenses": [
"MIT"
],
"directory_id": "0212ec483c93063666fd0bb3e5dd9dab8a9a5a81",
"extension": "c",
"filename": "mx_export.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236258809,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1844,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mx_export.c",
"provenance": "stackv2-0092.json.gz:44336",
"repo_name": "unitucode/ush",
"revision_date": "2020-09-10T11:51:01",
"revision_id": "775cc7f75c30e3fba4a088f9d6334c482dda31d3",
"snapshot_id": "8b1d6717bced941428cdbca1822b418268738d31",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/unitucode/ush/775cc7f75c30e3fba4a088f9d6334c482dda31d3/src/mx_export.c",
"visit_date": "2022-12-15T06:27:34.597587"
} | stackv2 | #include "ush.h"
static bool parse_error(char *arg) {
char *arg_name = mx_get_var_info(arg, 0);
if (mx_match(arg, "^[-+]"))
fprintf(stderr, "export: does not accept any options: %c%c\n",
arg[0], arg[1]);
else if (mx_match(arg, "^[0-9]"))
fprintf(stderr, "export: not an identifier: %s\n", arg_name);
else
fprintf(stderr, "export: not valid in this context: %s\n", arg_name);
mx_strdel(&arg_name);
return 1;
}
static void add_var_to_lists(char *arg) {
mx_var_list_insert(SHELL, arg);
mx_var_list_insert(EXP, arg);
mx_strdel(&arg);
}
static void export_var_to_lists(char *arg) {
t_list **shell_list = mx_get_var_list(SHELL);
t_list *current = *shell_list;
char *arg_name = NULL;
char *var_name = NULL;
mx_get_name(arg, &arg_name);
while (current) {
mx_get_name(current->data, &var_name);
if (strcmp(arg_name, var_name) == 0) {
mx_var_list_insert(EXP, current->data);
mx_putenv(current->data);
break ;
}
current = current->next;
if (current)
mx_get_name(current->data, &var_name);
}
if (!current)
add_var_to_lists(mx_strjoin(arg, "="));
mx_delete_names(&var_name, &arg_name, NULL);
}
int mx_export(char **args, int fd) {
bool args_stop = 0;
if (args[0] == NULL)
mx_print_var_list(EXP, fd);
else
for (int i = 0; args[i] && !args_stop; i++)
if (mx_match(args[i], MX_EXPORT_ARG))
if (!mx_match(args[i], "="))
export_var_to_lists(args[i]);
else {
mx_putenv(args[i]);
add_var_to_lists(strdup(args[i]));
}
else
args_stop = parse_error(args[i]);
return 0;
}
| 2.390625 | 2 |
2024-11-18T20:55:39.808136+00:00 | 2013-01-14T14:22:36 | b3bc625c55e5889430d4ab352cb757b022262d4a | {
"blob_id": "b3bc625c55e5889430d4ab352cb757b022262d4a",
"branch_name": "refs/heads/master",
"committer_date": "2013-01-14T14:22:36",
"content_id": "07cc59f96bc3febfb9bcbfa0a3b6fcd0a16a08ba",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e5269c6f9569a48911433ee55abdbf8652cf6063",
"extension": "h",
"filename": "xc_shm.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7882580,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2212,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/xcache/xc_shm.h",
"provenance": "stackv2-0092.json.gz:44464",
"repo_name": "fnu/xcache-src",
"revision_date": "2013-01-14T14:22:36",
"revision_id": "5455706b2312eab5868cc753c226b41542f61001",
"snapshot_id": "85ed24825caaf2bb6878c059deb94e009785d19e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fnu/xcache-src/5455706b2312eab5868cc753c226b41542f61001/xcache/xc_shm.h",
"visit_date": "2020-05-07T09:15:05.363845"
} | stackv2 | #ifndef XC_SHM_H
#define XC_SHM_H
#include <stdlib.h>
typedef struct _xc_shm_handlers_t xc_shm_handlers_t;
#ifndef XC_SHM_IMPL
struct _xc_shm_t {
const xc_shm_handlers_t *handlers;
};
#define XC_SHM_IMPL _xc_shm_t
#endif
typedef struct XC_SHM_IMPL xc_shm_t;
typedef size_t xc_shmsize_t;
/* shm */
#define XC_SHM_CAN_READONLY(func) int func(xc_shm_t *shm)
#define XC_SHM_IS_READWRITE(func) int func(xc_shm_t *shm, const void *p)
#define XC_SHM_IS_READONLY(func) int func(xc_shm_t *shm, const void *p)
#define XC_SHM_TO_READWRITE(func) void *func(xc_shm_t *shm, void *p)
#define XC_SHM_TO_READONLY(func) void *func(xc_shm_t *shm, void *p)
#define XC_SHM_INIT(func) xc_shm_t *func(xc_shmsize_t size, int readonly_protection, const void *arg1, const void *arg2)
#define XC_SHM_DESTROY(func) void func(xc_shm_t *shm)
#define XC_SHM_MEMINIT(func) void *func(xc_shm_t *shm, xc_shmsize_t size)
#define XC_SHM_MEMDESTROY(func) void func(void *mem)
#define XC_SHM_HANDLERS(name) { \
xc_##name##_can_readonly \
, xc_##name##_is_readwrite \
, xc_##name##_is_readonly \
, xc_##name##_to_readwrite \
, xc_##name##_to_readonly \
\
, xc_##name##_init \
, xc_##name##_destroy \
\
, xc_##name##_meminit \
, xc_##name##_memdestroy \
}
struct _xc_shm_handlers_t {
XC_SHM_CAN_READONLY((*can_readonly));
XC_SHM_IS_READWRITE((*is_readwrite));
XC_SHM_IS_READONLY((*is_readonly));
XC_SHM_TO_READWRITE((*to_readwrite));
XC_SHM_TO_READONLY((*to_readonly));
XC_SHM_INIT((*init));
XC_SHM_DESTROY((*destroy));
XC_SHM_MEMINIT((*meminit));
XC_SHM_MEMDESTROY((*memdestroy));
};
typedef struct _xc_shm_scheme_t xc_shm_scheme_t;
void xc_shm_init_modules();
int xc_shm_scheme_register(const char *name, const xc_shm_handlers_t *handlers);
const xc_shm_handlers_t *xc_shm_scheme_find(const char *name);
xc_shm_scheme_t *xc_shm_scheme_first();
xc_shm_scheme_t *xc_shm_scheme_next(xc_shm_scheme_t *scheme);
const char *xc_shm_scheme_name(xc_shm_scheme_t *scheme);
xc_shm_t *xc_shm_init(const char *type, xc_shmsize_t size, int readonly_protection, const void *arg1, const void *arg2);
void xc_shm_destroy(xc_shm_t *shm);
#endif
| 2.125 | 2 |
2024-11-18T20:55:39.881930+00:00 | 2020-10-07T17:17:11 | 2c9934378edb03132a515e65f367db4a06ac168f | {
"blob_id": "2c9934378edb03132a515e65f367db4a06ac168f",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-07T17:17:11",
"content_id": "47452f9050a5f09fa34b842db4288a2578c2a020",
"detected_licenses": [
"MIT"
],
"directory_id": "9acdffe297cf2862e00d81175b3b6983cde1191a",
"extension": "c",
"filename": "hangman.c",
"fork_events_count": 2,
"gha_created_at": "2020-10-08T13:54:23",
"gha_event_created_at": "2020-10-12T15:59:18",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 302357091,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4536,
"license": "MIT",
"license_type": "permissive",
"path": "/Projects/hangman/hangman.c",
"provenance": "stackv2-0092.json.gz:44593",
"repo_name": "Red-0111/Hacktoberfest-2",
"revision_date": "2020-10-07T17:17:11",
"revision_id": "e108cb451a5dc7cb7fee5307fa8d288d5f6dda3e",
"snapshot_id": "7f621e0065594a146b89780bff42842445db80ba",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Red-0111/Hacktoberfest-2/e108cb451a5dc7cb7fee5307fa8d288d5f6dda3e/Projects/hangman/hangman.c",
"visit_date": "2022-12-28T20:47:44.825212"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
char chosenWord[25];
int chosenWordLength;
char guessState[25];
int hangState = 1;
char available[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char HANG_STATES[7][10 * 9] =
{
" + +---- +---- +---- +---- +---- +---- +---- ",
" | | | O | O | O | O | O | O ",
" | | | | + | --+ | --+-- | --+-- | --+--",
" | | | | | | | | | | | | | ",
" | | | | | | | / | / \\ ",
" | | | | | | | | ",
"/*****\\ /*****\\ /*****\\ /*****\\ /*****\\ /*****\\ /*****\\ /*****\\ /*****\\ "};
FILE *openWordBankCSV();
void processCSV(int random);
void selectWordFromCSV(char wordArray[][25], int random);
void drawHang(int hangState);
void drawWord();
void drawAvailableLetters();
void initStage();
void makeGuess(char guess);
void checkWinner();
int main()
{
initStage();
return (0);
}
void initStage()
{
srand(time(0));
processCSV(rand() % 1005);
drawHang(hangState);
drawWord();
drawAvailableLetters();
while (hangState < 8)
{
puts("Make a guess!");
char g;
scanf("%c%*c", &g);
makeGuess(g);
drawHang(hangState);
drawWord();
drawAvailableLetters();
checkWinner();
}
printf("The correct word was:\n%s \nThanks for playing\n", chosenWord);
}
void checkWinner()
{
int isWinner = 1;
for (int i = 0; i < chosenWordLength; i++)
{
if (guessState[i] == ' ' || guessState[i] == '\0')
{
isWinner = 0;
break;
}
}
if (isWinner)
{
puts("You Win!");
exit(0);
}
}
void makeGuess(char guess)
{
int isAvailable = 0;
for (int i = 0; i < 26; i++)
{
if (toupper(guess) == available[i])
{
isAvailable = 1;
available[i] = ' ';
break;
}
}
if (isAvailable)
{
int isCorrectGuess = 0;
for (int i = 0; i < chosenWordLength; i++)
{
char *p = guessState;
if (chosenWord[i] == guess)
{
isCorrectGuess = 1;
p += i;
*p = guess;
}
}
if (!isCorrectGuess)
{
hangState += 1;
}
}
}
void drawWord()
{
printf("\t\t");
for (int i = 0; i < chosenWordLength; i++)
{
char c = 32;
if(guessState[i] != '\0'){
c = guessState[i];
}
printf("%c ", toupper(c));
}
printf("\n\t\t");
for (int i = 0; i < chosenWordLength; i++)
{
printf("_ ");
}
}
void drawAvailableLetters()
{
printf("\n");
for (int i = 0; i < 26; i++)
{
printf("%c ", available[i]);
}
puts("\n");
}
void drawHang(int hangState)
{
printf("\n word has %d characters\n", chosenWordLength);
for (int i = 0; i < 7; i++)
{
printf("%.10s\n", &HANG_STATES[i][hangState * 10]);
}
puts("\n");
}
void selectWordFromCSV(char wordArray[][25], int random)
{
char *p = wordArray[random];
int count = 1;
while (*p != '\0')
{
count += 1;
p += 1;
}
chosenWordLength = count - 1;
for (int i = 0; i < count; i++)
{
chosenWord[i] = wordArray[random][i];
}
}
void processCSV(int random)
{
FILE *words = openWordBankCSV();
char buff[2];
int wordPos = 0;
int charPos = 0;
char wordArray[1200][25];
while (fgets(buff, 2, words))
{
if (buff[0] == ',')
{
charPos = 0;
wordPos += 1;
}
else
{
if (buff[0] != ' ')
{
wordArray[wordPos][charPos] = buff[0];
charPos += 1;
}
}
}
fclose(words);
selectWordFromCSV(wordArray, random);
}
FILE *openWordBankCSV()
{
FILE *words = fopen("wordbank.csv", "r");
if (!words)
{
puts("ERROR opening file");
exit(1);
}
return words;
} | 2.90625 | 3 |
2024-11-18T20:55:40.118110+00:00 | 2020-09-20T16:06:44 | ba923d125741f296359d2167441d42bce207ee81 | {
"blob_id": "ba923d125741f296359d2167441d42bce207ee81",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-20T16:06:44",
"content_id": "eb69113edd3a5fde827debc610d1c8cb3bff9d1c",
"detected_licenses": [
"MIT"
],
"directory_id": "7fbd738098805dc43024ad806c0226e5b65aca8b",
"extension": "c",
"filename": "PROCESS.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 205164055,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6234,
"license": "MIT",
"license_type": "permissive",
"path": "/src/PROCESS.c",
"provenance": "stackv2-0092.json.gz:44851",
"repo_name": "ImAbdollahzadeh/LiBOS",
"revision_date": "2020-09-20T16:06:44",
"revision_id": "8182ef50f5849eaa19d95f699d0d06bf8fc74ba5",
"snapshot_id": "446192aa9173ac2eb7d6eaa5a54f3bae7099fb8c",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/ImAbdollahzadeh/LiBOS/8182ef50f5849eaa19d95f699d0d06bf8fc74ba5/src/PROCESS.c",
"visit_date": "2021-07-13T10:31:26.933624"
} | stackv2 | #include "../include/PROCESS.h"
#include "../include/PRINT.h"
#include "../include/MEMORY.h"
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ GLOBAL AND STATIC VARIABLES
#define PROCESS_BEGIN_VIRTUAL_ADDRESS 0x40000000 // at address 1GB
#define PROCESS_DEFAULT_PAGE_SIZE 0x1000
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
BOOL initialize_process(void)
{
if( !paging_is_activate() )
{
panic("cannot initialize proceses without paging activation\n");
return FALSE;
}
PAGE_DIRECTORY* pd = (PAGE_DIRECTORY*)(get_pdbr());
if( !pd )
{
panic("LiBOS has no initialized PDBR\n");
return FALSE;
}
return TRUE;
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
PROCESS* create_process(UINT_32 function_address)
{
PAGE_DIRECTORY* address_space;
PROCESS* process;
THREAD* main_thread;
/* assign the process virtual address space, zero it, and map it to itself (IMPORTANT for later page fault handlings) */
address_space = (PAGE_DIRECTORY*)physical_page_alloc();
if (!address_space)
{
printk("process with function address ^ failed to create a virtual address space\n", function_address);
return 0;
}
__LiBOS_MemZero(address_space, 4096);
map_physical_address(address_space, address_space, address_space, (I86_PTE_PRESENT | I86_PTE_WRITABLE | I86_PTE_USER));
/* assign the process main thread, zero it, and map it to the process's page directory */
main_thread = (THREAD*)physical_page_alloc();
__LiBOS_MemZero(main_thread, 4096);
map_physical_address(address_space, main_thread, main_thread, (I86_PTE_PRESENT | I86_PTE_WRITABLE | I86_PTE_USER));
/* map KERN_MEM (address 0 to 1GB) and SYS_MEM into process's address space (address 3GB to 4GB) */
UINT_32 i;
PAGE_DIRECTORY* mpgd = get_libos_main_page_directory();
for(i = 0; i < 256; i++)
{
__LiBOS_MemCopy(&(mpgd->entries[i ]), &(address_space->entries[i ]), sizeof(UINT_32)); /* 0GB - 1GB ~> for KERN_MEM */
__LiBOS_MemCopy(&(mpgd->entries[768 + i]), &(address_space->entries[768 + i]), sizeof(UINT_32)); /* 3GB - 4GB ~> for SYS_MEM */
}
/* create PCB */
process = (PROCESS*)physical_page_alloc();
__LiBOS_MemZero(process, 4096);
map_physical_address(address_space, process, process, (I86_PTE_PRESENT | I86_PTE_WRITABLE | I86_PTE_USER));
process->pid = 1;
process->page_directory = address_space;
process->priority = 1;
process->state = PROCESS_STATE_ACTIVE;
process->cpu = 0 /* for now BSP cpu */;
process->ioapic = 0 /* for now BSP cpu */;
/* create thread descriptor */
__LiBOS_MemZero(&main_thread->frame, sizeof(TRAP_FRAME));
main_thread->parent = process;
main_thread->priority = 1;
main_thread->state = PROCESS_STATE_ACTIVE;
main_thread->frame.eip = function_address;
main_thread->frame.flags = INTERRUPT_ENABLE_FLAG;
/* Create stack, zero it, and map it to the process's page directory */
void* stack = (void*)PROCESS_BEGIN_VIRTUAL_ADDRESS;
void* stack_phys = physical_page_alloc();
__LiBOS_MemZero(stack_phys, 4096);
map_physical_address(address_space, stack, stack_phys, (I86_PTE_PRESENT | I86_PTE_WRITABLE | I86_PTE_USER));
/* final initialization */
main_thread->initial_stack = stack + PROCESS_DEFAULT_PAGE_SIZE;
main_thread->stack_limit = (void*)stack; // default: 4KB
main_thread->frame.esp = (UINT_32)main_thread->initial_stack;
main_thread->frame.ebp = (UINT_32)main_thread->initial_stack;
/* rgister main_thread into process's list of threads */
process->thread_list[0] = *main_thread;
return process;
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
THREAD* create_thread(PROCESS* process)
{
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
void execute_process(PROCESS* process)
{
if (process->pid == PROC_INVALID_ID)
return;
if (!process->page_directory)
return;
/* get esp and eip of main thread */
UINT_32 entry_point = (process->thread_list[0]).frame.eip;
UINT_32 process_stack = (process->thread_list[0]).frame.esp;
/* switch to process address space */
_CLI();
set_pdbr(process->page_directory);
/* execute process in kernel mode */
execute_kernel_mode_process(process_stack, entry_point);
/* switch back to kernel address space */
PAGE_DIRECTORY* mpgd = get_libos_main_page_directory();
_CLI();
set_pdbr(mpgd->entries);
_STI();
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
void terminate_process(PROCESS* process)
{
if (process->pid == PROC_INVALID_ID)
return;
/* release threads */
UINT_8 i = 0;
THREAD* thread = &(process->thread_list[i]);
/* get physical address of stack */
void* stack_frame = get_physical_address(process->page_directory, (UINT_32)thread->initial_stack);
/* unmap and release stack memory */
unmap_physical_address(process->page_directory, (UINT_32)thread->initial_stack);
//-------------free_physical_block(stack_frame); // ALREADY DONE ?!
/* unmap and release image memory */
UINT_32 page;
for(UINT_32 page = 0; page < 1 /* by default, we assumed no process larger than 4KB */; page++)
{
UINT_32 phys = 0;
UINT_32 virt = 0;
/* get virtual address of page */
//--------------virt = thread->imageBase + (page * PAGE_SIZE);
/* get physical address of page */
phys = (UINT_32)get_physical_address(process->page_directory, virt);
/* unmap and release page */
unmap_physical_address(process->page_directory, virt);
//----free_physical_block((void*)phys);
}
/* restore kernel selectors */
//------------------restore_kernel_after_process_termination();
}
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 2.5625 | 3 |
2024-11-18T20:55:40.186666+00:00 | 2023-03-16T14:41:42 | 21f2ba543c5c754ac906438c57535b2fdca34f95 | {
"blob_id": "21f2ba543c5c754ac906438c57535b2fdca34f95",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-16T14:42:35",
"content_id": "50536cfceb56a911b2bc1af6a2000ffe89b7af15",
"detected_licenses": [
"MIT"
],
"directory_id": "2be6e0573d5691e084629c32ecb43142b5b5a1ee",
"extension": "c",
"filename": "cursor.c",
"fork_events_count": 39,
"gha_created_at": "2010-03-28T19:20:25",
"gha_event_created_at": "2023-02-10T12:11:39",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 583744,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4069,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cursor.c",
"provenance": "stackv2-0092.json.gz:44980",
"repo_name": "mpereira/tty-solitaire",
"revision_date": "2023-03-16T14:41:42",
"revision_id": "ef83b74a3c791c6faa5ad90fe437a5641ce0795c",
"snapshot_id": "35dc0437e9595351ab5a4a998ea19be38c998c5b",
"src_encoding": "UTF-8",
"star_events_count": 252,
"url": "https://raw.githubusercontent.com/mpereira/tty-solitaire/ef83b74a3c791c6faa5ad90fe437a5641ce0795c/src/cursor.c",
"visit_date": "2023-04-08T16:07:42.618073"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ncurses.h>
#include <assert.h>
#include "cursor.h"
#include "game.h"
#include "common.h"
void cursor_malloc(struct cursor **cursor) {
if (!(*cursor = malloc(sizeof(**cursor)))) {
tty_solitaire_generic_error(errno, __FILE__, __LINE__);
}
(*cursor)->window = newwin(1, 1, CURSOR_BEGIN_Y, CURSOR_BEGIN_X);
}
void cursor_init(struct cursor *cursor) {
mvwin(cursor->window, CURSOR_BEGIN_Y, CURSOR_BEGIN_X);
cursor->y = CURSOR_BEGIN_Y;
cursor->x = CURSOR_BEGIN_X;
cursor->marked = false;
}
void cursor_free(struct cursor *cursor) {
delwin(cursor->window);
free(cursor);
}
void cursor_mark(struct cursor *cursor) {
cursor->marked = true;
}
void cursor_unmark(struct cursor *cursor) {
cursor->marked = false;
}
void cursor_move(struct cursor *cursor, enum movement movement) {
switch (movement) {
case LEFT:
if (cursor->x > CURSOR_BEGIN_X) {
cursor->x = cursor->x - 8;
if (cursor->y > CURSOR_BEGIN_Y) {
cursor_move(cursor, UP);
cursor_move(cursor, DOWN);
}
}
break;
case DOWN:
if (cursor->y == CURSOR_BEGIN_Y) {
switch (cursor->x - 3) {
case MANEUVRE_0_BEGIN_X:
cursor->y = cursor->y + 7 + stack_length(deck->maneuvre[0]);
break;
case MANEUVRE_1_BEGIN_X:
cursor->y = cursor->y + 7 + stack_length(deck->maneuvre[1]);
break;
case MANEUVRE_2_BEGIN_X:
cursor->y = cursor->y + 7 + stack_length(deck->maneuvre[2]);
break;
case MANEUVRE_3_BEGIN_X:
cursor->y = cursor->y + 7 + stack_length(deck->maneuvre[3]);
break;
case MANEUVRE_4_BEGIN_X:
cursor->y = cursor->y + 7 + stack_length(deck->maneuvre[4]);
break;
case MANEUVRE_5_BEGIN_X:
cursor->y = cursor->y + 7 + stack_length(deck->maneuvre[5]);
break;
case MANEUVRE_6_BEGIN_X:
cursor->y = cursor->y + 7 + stack_length(deck->maneuvre[6]);
break;
}
}
break;
case RIGHT:
if (cursor->x < 49) {
cursor->x = cursor->x + 8;
if (cursor->y > CURSOR_BEGIN_Y) {
cursor_move(cursor, UP);
cursor_move(cursor, DOWN);
}
}
break;
case UP:
if (cursor->y > CURSOR_BEGIN_Y) {
cursor->y = CURSOR_BEGIN_Y;
}
break;
}
}
enum movement cursor_direction(int key) {
switch (key) {
case 'h':
case KEY_LEFT:
return(LEFT);
case 'j':
case KEY_DOWN:
return(DOWN);
case 'k':
case KEY_UP:
return(UP);
case 'l':
case KEY_RIGHT:
return(RIGHT);
default:
endwin();
game_end();
assert(false && "invalid cursor direction");
}
}
struct stack **cursor_stack(struct cursor *cursor) {
if (cursor->y == CURSOR_BEGIN_Y) {
switch (cursor->x) {
case CURSOR_STOCK_X: return(&(deck->stock));
case CURSOR_WASTE_PILE_X: return(&(deck->waste_pile));
case CURSOR_FOUNDATION_0_X: return(&(deck->foundation[0]));
case CURSOR_FOUNDATION_1_X: return(&(deck->foundation[1]));
case CURSOR_FOUNDATION_2_X: return(&(deck->foundation[2]));
case CURSOR_FOUNDATION_3_X: return(&(deck->foundation[3]));
case CURSOR_INVALID_SPOT_X: return(NULL);
default:
endwin();
game_end();
assert(false && "invalid stack");
}
} else {
switch (cursor->x) {
case CURSOR_MANEUVRE_0_X: return(&(deck->maneuvre[0]));
case CURSOR_MANEUVRE_1_X: return(&(deck->maneuvre[1]));
case CURSOR_MANEUVRE_2_X: return(&(deck->maneuvre[2]));
case CURSOR_MANEUVRE_3_X: return(&(deck->maneuvre[3]));
case CURSOR_MANEUVRE_4_X: return(&(deck->maneuvre[4]));
case CURSOR_MANEUVRE_5_X: return(&(deck->maneuvre[5]));
case CURSOR_MANEUVRE_6_X: return(&(deck->maneuvre[6]));
default:
endwin();
game_end();
assert(false && "invalid stack");
}
}
}
bool cursor_on_stock(struct cursor *cursor) {
return(cursor_stack(cursor) && *cursor_stack(cursor) == deck->stock);
}
bool cursor_on_invalid_spot(struct cursor *cursor) {
return(!cursor_stack(cursor));
}
| 2.296875 | 2 |
2024-11-18T20:55:40.732460+00:00 | 2018-02-09T18:48:44 | 5f903f3a1030c9ea04c05fb836abd5f8244f04dd | {
"blob_id": "5f903f3a1030c9ea04c05fb836abd5f8244f04dd",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-09T18:48:44",
"content_id": "fe088d8b950bd40a4f8ef5ac7e9e85f5d1cb2677",
"detected_licenses": [
"Unlicense"
],
"directory_id": "0a04bfbd42585ce3643e2e58f55d9fcc525cbce7",
"extension": "c",
"filename": "lab71.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 120942811,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2414,
"license": "Unlicense",
"license_type": "permissive",
"path": "/lab7/lab71.c",
"provenance": "stackv2-0092.json.gz:45238",
"repo_name": "mwalls1/CPRE-185",
"revision_date": "2018-02-09T18:48:44",
"revision_id": "cad13e483beaf07a286c570bd029500b4efd36fe",
"snapshot_id": "43453991215f69fbbef0a0be2b5fedc039257e4a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mwalls1/CPRE-185/cad13e483beaf07a286c570bd029500b4efd36fe/lab7/lab71.c",
"visit_date": "2021-05-02T00:21:43.225208"
} | stackv2 | // 185 Lab 7
#include <stdio.h>
#define MAXPOINTS 10000
// compute the average of the first num_items of buffer
double avg(double buffer[], int num_items);
double avg(double buffer[], int num_items)
{
int i = 0;
double average;
for(i = 0; i < num_items; i++)
{
average+=buffer[i];
}
return (average/(1.0*num_items));
}
//update the max and min of the first num_items of array
void maxmin(double array[], int num_items, double* max, double* min);
void maxmin(double array[], int num_items, double* max, double* min)
{
*min = array[0];
*max = array[0];
int i = 0;
for(i=0; i < num_items; i++)
{
if(array[i]>*max)
*max=array[i];
else if(array[i]<*min)
*min = array[i];
}
}
//shift length-1 elements of the buffer to the left and put the
//new_item on the right.
void updatebuffer(double buffer[], int length, double new_item);
void updatebuffer(double buffer[], int length, double new_item)
{
int i = 0;
for(i = length-2; i>=0; i--)
{
buffer[i+1] = buffer[i];
}
buffer[0] = new_item;
}
int main(int argc, char* argv[]) {
/* DO NOT CHANGE THIS PART OF THE CODE */
int bT, bC, bX, bS;
double x[MAXPOINTS], y[MAXPOINTS], z[MAXPOINTS];
int lengthofavg = 0;
int i = 0;
double x1, y1, z1, avgX, avgY, avgZ, maxX, maxY, maxZ, minX, minY, minZ;
if (argc>1) {
sscanf(argv[1], "%d", &lengthofavg );
printf("You entered a buffer length of %d\n", lengthofavg);
}
else {
printf("Enter a length on the command line\n");
return -1;
}
if (lengthofavg <1 || lengthofavg >MAXPOINTS) {
printf("Invalid length\n");
return -1;
}
/* PUT YOUR CODE HERE */
for(i = 0; i < lengthofavg; i++)
{
scanf("%lf, %lf, %lf, %d, %d, %d, %d",&x1, &y1, &z1, &bT, &bC, &bX, &bS);
updatebuffer(x, lengthofavg, x1);
updatebuffer(y, lengthofavg, y1);
updatebuffer(z, lengthofavg, z1);
}
do
{
scanf("%lf, %lf, %lf, %d, %d, %d, %d",&x1, &y1, &z1, &bT, &bC, &bX, &bS);
updatebuffer(x, lengthofavg, x1);
updatebuffer(y, lengthofavg, y1);
updatebuffer(z, lengthofavg, z1);
avgX=avg(x,lengthofavg);
avgY=avg(y,lengthofavg);
avgZ=avg(z,lengthofavg);
maxmin(x,lengthofavg,&maxX,&minX);
maxmin(y,lengthofavg,&maxY,&minY);
maxmin(z,lengthofavg,&maxZ,&minZ);
printf("%10lf, %10lf, %10lf, %10lf, %10lf, %10lf, %10lf, %10lf, %10lf, %10lf, %10lf, %10lf\n", x1, avgX, minX, maxX, y1, avgY, minY, maxY, z1, avgZ, minZ, maxZ);
fflush(stdout);
}while(bS==0);
}
| 3.453125 | 3 |
2024-11-18T20:55:41.151828+00:00 | 2019-08-16T00:39:05 | e6f5c45bac1f0e020fc229ae7438227b85b3a25b | {
"blob_id": "e6f5c45bac1f0e020fc229ae7438227b85b3a25b",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-16T00:39:05",
"content_id": "a55b37654bbeaf897deae02dcadcfa4ccb76d86c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5f6ebd088a0e5d79f0ea5257872dcad917a23a2f",
"extension": "c",
"filename": "pruloop.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": 3142,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/apps/haptictest/pruloop.c",
"provenance": "stackv2-0092.json.gz:45368",
"repo_name": "cyunis/openWearable",
"revision_date": "2019-08-16T00:39:05",
"revision_id": "8fcced995e42fa5281587c8be020dec929b7dada",
"snapshot_id": "0f4bad66721a83f4f5ce536ec9171ea685000229",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cyunis/openWearable/8fcced995e42fa5281587c8be020dec929b7dada/apps/haptictest/pruloop.c",
"visit_date": "2020-07-21T13:53:14.551163"
} | stackv2 | /* Copyright 2017-2019 Jonathan Realmuto
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 "pruloop.h"
#include "encoder.h"
#include "sync.h"
#include "pwmdriver.h"
volatile register uint32_t __R30;
volatile register uint32_t __R31;
const uint32_t Td_default = 5000;
const uint32_t Np_default = 1;
uint32_t flag, t0, t;
const uint8_t sync_pin = 8;
sync_t* sync;
// ---------------------------------------------------------------------------
// PRU0
//
// Edit user defined functions below
// ---------------------------------------------------------------------------
void Pru0Init(pru_mem_t* mem) {
mem->p->Td = Td_default;
mem->p->Np = Np_default;
flag = 0;
debug_buff[0] = encoderInit();
sync = SyncInitChan(sync_pin);
SyncOutLow(sync);
}
void Pru0UpdateState(const pru_count_t* c,
const param_mem_t* p_,
const lut_mem_t* l_,
state_t* s_,
pru_ctl_t* ctl_) {
if (PruGetCtlBit(ctl_, 0)) {
if (flag == 0) {
t0 = c->frame;
SyncOutHigh(sync);
flag = 1;
}
t = (c->frame - t0)*p_->fs_hz / (p_->Td - p_->Td/p_->fs_hz);
s_->xd = fix16_ssub(fix16_smul(fix16_from_int(90),
fix16_sadd(fix16_sdiv(
fix16_from_int( (int32_t) l_->lut[t % 1000]),
fix16_from_int(1000)),fix16_one)),fix16_from_int(90));
if ((c->frame-t0) == (p_->Np*p_->Td)) {
flag = 0;
PruClearCtlBit(ctl_,0);
SyncOutLow(sync);
}
} else {
s_->xd = 0;
}
encoderSample(&s_->x);
s_->vsync = (uint32_t)SyncOutState(sync);
}
void Pru0UpdateControl(const pru_count_t* c,
const param_mem_t* p_,
const lut_mem_t* l_,
state_t* s_,
pru_ctl_t* ctl_){
}
void Pru0Cleanup(void) {
}
// ---------------------------------------------------------------------------
// PRU1
//
// Edit user defined functions below
// ---------------------------------------------------------------------------
void Pru1Init(pru_mem_t* mem) {
pwmInit();
pwmSetCmpValue((uint16_t)5000);
}
void Pru1UpdateState(const pru_count_t* c,
const param_mem_t* p_,
const lut_mem_t* l_,
state_t* s_,
pru_ctl_t* ctl_) {
}
void Pru1UpdateControl(const pru_count_t* c,
const param_mem_t* p_,
const lut_mem_t* l_,
state_t* s_,
pru_ctl_t* ctl_) {
}
void Pru1Cleanup(void) {
pwmCleanUp();
}
| 2.0625 | 2 |
2024-11-18T20:55:41.309985+00:00 | 2022-10-08T12:53:58 | 2f3f222332ef26f4dfdc0e94346bb4b4ff45f0fa | {
"blob_id": "2f3f222332ef26f4dfdc0e94346bb4b4ff45f0fa",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-08T12:53:58",
"content_id": "5dc8e0dc88be31842219123f74d7ec6f96e32bfa",
"detected_licenses": [
"MIT"
],
"directory_id": "cdbc0478f7d630d7c7bbbd7cfce2499f0fe4689b",
"extension": "c",
"filename": "Tree_Inorder_Traversal.c",
"fork_events_count": 514,
"gha_created_at": "2020-09-28T14:09:43",
"gha_event_created_at": "2023-01-22T07:12:14",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 299329204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1034,
"license": "MIT",
"license_type": "permissive",
"path": "/C/Tree_Inorder_Traversal.c",
"provenance": "stackv2-0092.json.gz:45627",
"repo_name": "sukritishah15/DS-Algo-Point",
"revision_date": "2022-10-08T12:53:58",
"revision_id": "1b6040f7d9af5830882b53916e83d53a9c0d67d1",
"snapshot_id": "79bf3f7767592e5d6dd49b97a14a800b90c82e88",
"src_encoding": "UTF-8",
"star_events_count": 1185,
"url": "https://raw.githubusercontent.com/sukritishah15/DS-Algo-Point/1b6040f7d9af5830882b53916e83d53a9c0d67d1/C/Tree_Inorder_Traversal.c",
"visit_date": "2023-08-28T18:17:55.003418"
} | stackv2 | /* Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Sample Input : 1 2 3 4 5
Sample output : 4 2 5 1 3
Time Complexity : O(n)
Auxiliary Space : If we don’t consider size of stack for function calls then O(1) otherwise O(n).
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lptr,*rptr;
}node;
node *newnode(int data)
{
node *newn;
newn = (node*)malloc(sizeof(node));
newn->data = data;
newn->lptr = NULL;
newn->rptr = NULL;
return newn;
}
/*Function for INORDER Transversal*/
void inorder(node *root)
{
if(root != NULL)
{
inorder(root->lptr);
printf("%d ", root->data);
inorder(root->rptr);
}
}
int main()
{
node *root;
root = newnode(1);
root->lptr = newnode(2);
root->rptr = newnode(3);
root->lptr->lptr = newnode(4);
root->lptr->rptr = newnode(5);
printf("In Order Transversal: ");
inorder(root);
return 0;
}
| 4.15625 | 4 |
2024-11-18T20:55:41.849956+00:00 | 2015-10-01T18:40:20 | b584e280552b564a57fee6b9aad2e35686d7702d | {
"blob_id": "b584e280552b564a57fee6b9aad2e35686d7702d",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-01T18:40:20",
"content_id": "70829cc484e75ed7ad1ca6eb478b559258db5a3c",
"detected_licenses": [
"MIT"
],
"directory_id": "835a2a93fbdbc95eb9a23205ea98c93b039355ed",
"extension": "c",
"filename": "s.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 43503850,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2102,
"license": "MIT",
"license_type": "permissive",
"path": "/s.c",
"provenance": "stackv2-0092.json.gz:46526",
"repo_name": "FilWisher/circuits",
"revision_date": "2015-10-01T18:40:20",
"revision_id": "0d0a927f9ca850c602ebfdda54c3875336cdd42e",
"snapshot_id": "8b9b0f9a38994a06e08d7293286acab2a98529b3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FilWisher/circuits/0d0a927f9ca850c602ebfdda54c3875336cdd42e/s.c",
"visit_date": "2021-01-10T17:19:19.926324"
} | stackv2 | #include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_BUF 10000
#define MAX_REQUEST 10000
#define SOCK_PATH "/tmp/circuits"
typedef struct sockaddr_un Sock_Address;
#define ADDRSIZE sizeof(Sock_Address)
Sock_Address
make_socket_address(void)
{
Sock_Address addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, SOCK_PATH);
return addr;
}
int
create_socket(void)
{
int fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
perror("create_socket: socket");
exit(1);
}
return fd;
}
void
bind_socket_to_fd(int fd, struct sockaddr *addr)
{
unlink(SOCK_PATH); /* unlink path incase already open */
//printf("attempting to bind to %s\n", addr->);
if (bind(fd, addr, ADDRSIZE) == -1) {
perror("bind_socket_to_fd: bind");
exit(1);
}
}
int
accept_waiting_connection(int server, struct sockaddr *connection, socklen_t *len)
{
int c_fd;
if ((c_fd = accept(server, connection, len)) == -1) {
perror("accept_waiting_connection: accept");
exit(1);
} else {
printf("connected");
}
return c_fd;
}
void
send_response(int client_fd, char *response)
{
if (send(client_fd, response, strlen(response), 0) < 0) {
perror("send_response: send");
}
}
int
receive_request(int client_fd, char *request)
{
return recv(client_fd, request, MAX_REQUEST, 0);
}
int
main(int argc, char *argv[])
{
int s_fd, c_fd;
Sock_Address addr, connection;
socklen_t len = sizeof(Sock_Address);
char *request;
s_fd = create_socket();
addr = make_socket_address();
bind_socket_to_fd(s_fd, (struct sockaddr *)&addr);
listen(s_fd, 7);
while (1) {
int err, n, c_fd, done = 0;
c_fd = accept_waiting_connection(s_fd,
(struct sockaddr *)&connection, &len);
while (!done) {
n = receive_request(c_fd, request);
printf("\nrequest: ", request);
send_response(c_fd, "ARTY FARTY");
done = 1;
}
}
unlink(SOCK_PATH);
return 0;
}
| 2.828125 | 3 |
2024-11-18T20:55:42.019945+00:00 | 2021-12-15T02:34:12 | 2d3f9bf678783093eccdc9565c49909b1d62e20d | {
"blob_id": "2d3f9bf678783093eccdc9565c49909b1d62e20d",
"branch_name": "refs/heads/master",
"committer_date": "2021-12-15T02:34:12",
"content_id": "053710c75b5ac3484f6a08dfbc73db9783253506",
"detected_licenses": [
"MIT"
],
"directory_id": "146af13070aa180b755cebca19f1b0f7e31362a8",
"extension": "c",
"filename": "timing.c",
"fork_events_count": 0,
"gha_created_at": "2016-09-03T15:53:00",
"gha_event_created_at": "2016-09-03T15:53:00",
"gha_language": null,
"gha_license_id": null,
"github_id": 67298468,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2298,
"license": "MIT",
"license_type": "permissive",
"path": "/vic/drivers/shared_all/src/timing.c",
"provenance": "stackv2-0092.json.gz:46655",
"repo_name": "andrewsoong/VIC",
"revision_date": "2021-12-15T02:34:12",
"revision_id": "8f6cc0661bdc67c4f6caabdd4dcd0b8782517435",
"snapshot_id": "b31eb39fb0a88d3909e1aa3cbda4ad25a8528d6e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andrewsoong/VIC/8f6cc0661bdc67c4f6caabdd4dcd0b8782517435/vic/drivers/shared_all/src/timing.c",
"visit_date": "2022-07-18T16:34:45.461649"
} | stackv2 | /******************************************************************************
* @section DESCRIPTION
*
* Routines to calculate and store model runtime timing.
*****************************************************************************/
#include <vic_driver_shared_all.h>
/******************************************************************************
* @brief Get wall time
*****************************************************************************/
double
get_wall_time()
{
struct timeval time;
if (gettimeofday(&time, NULL)) {
log_err("Unable to get time of day")
}
return (double) time.tv_sec + (double) time.tv_usec * 0.000001;
}
/******************************************************************************
* @brief Get CPU time
*****************************************************************************/
double
get_cpu_time()
{
return (double) clock() / CLOCKS_PER_SEC;
}
/******************************************************************************
* @brief Initialize timer values
*****************************************************************************/
void
timer_init(timer_struct *t)
{
t->start_wall = 0;
t->start_cpu = 0;
t->delta_wall = 0;
t->delta_cpu = 0;
}
/******************************************************************************
* @brief Start timer
*****************************************************************************/
void
timer_start(timer_struct *t)
{
timer_init(t);
t->start_wall = get_wall_time();
t->start_cpu = get_cpu_time();
}
/******************************************************************************
* @brief Stop timer
*****************************************************************************/
void
timer_stop(timer_struct *t)
{
t->stop_wall = get_wall_time();
t->stop_cpu = get_cpu_time();
t->delta_wall += t->stop_wall - t->start_wall;
t->delta_cpu += t->stop_cpu - t->start_cpu;
}
/******************************************************************************
* @brief Continue timer without resetting counters
*****************************************************************************/
void
timer_continue(timer_struct *t)
{
t->start_wall = get_wall_time();
t->start_cpu = get_cpu_time();
}
| 2.40625 | 2 |
2024-11-18T20:55:42.354441+00:00 | 2022-05-25T23:10:04 | 8393d59660a8d0f59d08ac0d046ab9d588fe94df | {
"blob_id": "8393d59660a8d0f59d08ac0d046ab9d588fe94df",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-25T23:10:04",
"content_id": "074754a86b29deebe5e595b2cd0af8f786bbeb7c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3e39e2fa31158d6d86a23773946084db17cd3317",
"extension": "h",
"filename": "esp_crypto_lock.h",
"fork_events_count": 1,
"gha_created_at": "2019-07-08T17:15:54",
"gha_event_created_at": "2022-02-20T21:04:41",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 195855829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1840,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/esp_hw_support/include/soc/esp32s3/esp_crypto_lock.h",
"provenance": "stackv2-0092.json.gz:47040",
"repo_name": "igrr/esp-idf",
"revision_date": "2022-05-25T23:10:04",
"revision_id": "4823bd824d4c5ccd050a061c3241da26cf768e47",
"snapshot_id": "75455577353a3ca82a7e9009ab9d00b5687a1388",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/igrr/esp-idf/4823bd824d4c5ccd050a061c3241da26cf768e47/components/esp_hw_support/include/soc/esp32s3/esp_crypto_lock.h",
"visit_date": "2022-06-10T08:00:11.179173"
} | stackv2 | /*
* SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/**
* This API should be used by all components which use the SHA, AES, HMAC and DS crypto hardware on the ESP32S3.
* Not all of them can be used in parallel because they use the same underlying module.
* E.g., HMAC uses SHA or DS uses HMAC and AES. See the ESP32S3 Technical Reference Manual for more details.
*
* Other unrelated components must not use it.
*/
/**
* @brief Acquire lock for Digital Signature(DS) cryptography peripheral
*
* Internally also takes the HMAC lock, as the DS depends on the HMAC peripheral
*/
void esp_crypto_ds_lock_acquire(void);
/**
* @brief Release lock for Digital Signature(DS) cryptography peripheral
*
* Internally also releases the HMAC lock, as the DS depends on the HMAC peripheral
*/
void esp_crypto_ds_lock_release(void);
/**
* @brief Acquire lock for HMAC cryptography peripheral
*
* Internally also takes the SHA & AES lock, as the HMAC depends on the SHA peripheral
*/
void esp_crypto_hmac_lock_acquire(void);
/**
* @brief Release lock for HMAC cryptography peripheral
*
* Internally also releases the SHA & AES lock, as the HMAC depends on the SHA peripheral
*/
void esp_crypto_hmac_lock_release(void);
/**
* @brief Acquire lock for the SHA and AES cryptography peripheral.
*
*/
void esp_crypto_sha_aes_lock_acquire(void);
/**
* @brief Release lock for the SHA and AES cryptography peripheral.
*
*/
void esp_crypto_sha_aes_lock_release(void);
/**
* Acquire lock for the MPI/RSA cryptography peripheral
*/
void esp_crypto_mpi_lock_acquire(void);
/**
* Release lock for the MPI/RSA cryptography peripheral
*/
void esp_crypto_mpi_lock_release(void);
#ifdef __cplusplus
}
#endif
| 2.015625 | 2 |
2024-11-18T20:55:42.458689+00:00 | 2020-09-15T04:18:11 | cf3072fda4c84355608227c32c025a634f8771d8 | {
"blob_id": "cf3072fda4c84355608227c32c025a634f8771d8",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-15T04:18:11",
"content_id": "21df6e04250bc57f8f06b0468e332499d2e798e7",
"detected_licenses": [
"MIT"
],
"directory_id": "75afbda7e5f2c04453b187d7fb896257aa563602",
"extension": "c",
"filename": "cutestsuite.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 195657108,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2295,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cutestsuite.c",
"provenance": "stackv2-0092.json.gz:47168",
"repo_name": "hadichahine/cest",
"revision_date": "2020-09-15T04:18:11",
"revision_id": "9cbe2cafc512ddda88de015ebcc7e9ed45f8fbff",
"snapshot_id": "8e02278ffd7f210b24364abd8173dfcc9d9400cf",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/hadichahine/cest/9cbe2cafc512ddda88de015ebcc7e9ed45f8fbff/src/cutestsuite.c",
"visit_date": "2021-07-09T20:04:41.003062"
} | stackv2 | #include <stdlib.h>
#include "cutest.h"
#include "linkedlist.h"
#include "e4c.h"
#include "mem_alloc.h"
typedef struct {
char *name;
LinkedList *testsList;
void (*beforeStartFunction)();
void (*afterFinishFunction)();
int hook_crashed;
} CUTestSuite;
void emptyFunction(){}
CUTestSuite *CUTestSuite_create(char *name){
CUTestSuite *testSuite = (CUTestSuite*)mem_alloc(sizeof(CUTestSuite));
testSuite->name = name;
testSuite->testsList = createLinkedList();
testSuite->beforeStartFunction = emptyFunction;
testSuite->afterFinishFunction = emptyFunction;
testSuite->hook_crashed = 0;
return testSuite;
}
char *CUTestSuite_name(CUTestSuite *testSuite){
return testSuite->name;
}
void CUTestSuite_addTest(CUTestSuite *testSuite, char *name, void (*testFunction)(Assert *assert)){
CUTest *test = CUTest_create(name, testFunction);
addItemToLinkedList(testSuite->testsList,test);
}
void CUTestSuite_runHookBeforeStartingSuite(CUTestSuite *testSuite, void (*hook)()){
testSuite->beforeStartFunction = hook;
}
void CUTestSuite_runHookAfterFinishingSuite(CUTestSuite *testSuite, void (*hook)()){
testSuite->afterFinishFunction = hook;
}
#define use_context(code) if(!e4c_context_is_ready()){e4c_using_context(E4C_TRUE) code }else code
void CUTestSuite_execute(CUTestSuite *testSuite){
use_context({
try{
testSuite->beforeStartFunction();
while(!reachedEnd(testSuite->testsList))
CUTest_execute(next(testSuite->testsList));
reset(testSuite->testsList);
testSuite->afterFinishFunction();
}catch(BadPointerException){
testSuite->hook_crashed = 1;
}catch(ArithmeticException){
testSuite->hook_crashed = 1;
}
})
}
int CUTestSuite_didPass(CUTestSuite *testSuite){
int didPass = 1;
while(!reachedEnd(testSuite->testsList))
didPass = CUTest_didTestPass(next(testSuite->testsList)) && didPass;
reset(testSuite->testsList);
return !testSuite->hook_crashed && didPass;
}
void CUTestSuite_destroy(CUTestSuite *testSuite){
while(!reachedEnd(testSuite->testsList))
CUTest_destroy(next(testSuite->testsList));
reset(testSuite->testsList);
destructList(testSuite->testsList);
free(testSuite);
} | 2.53125 | 3 |
2024-11-18T20:55:42.710428+00:00 | 2017-09-14T05:32:06 | ba0e1f6b0c68bdc1bb6c1400995531a85402d056 | {
"blob_id": "ba0e1f6b0c68bdc1bb6c1400995531a85402d056",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-14T05:32:06",
"content_id": "9b4c17f1cf22324bdbe45a1ec03e4b72d9bd1274",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "2204d942514817212010a6b97893873b35ac44ce",
"extension": "c",
"filename": "ipc.c",
"fork_events_count": 0,
"gha_created_at": "2017-09-14T16:21:35",
"gha_event_created_at": "2017-09-14T16:21:35",
"gha_language": null,
"gha_license_id": null,
"github_id": 103555252,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 43672,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/apps/sel4test-tests/src/tests/ipc.c",
"provenance": "stackv2-0092.json.gz:47555",
"repo_name": "dornerworks/sel4test",
"revision_date": "2017-09-14T05:32:06",
"revision_id": "5c7a41d656f289dba42e17edbb16918f4ff8c7bf",
"snapshot_id": "9d95220dfba273bb08c9aea5a293c5ba5c7ac68f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dornerworks/sel4test/5c7a41d656f289dba42e17edbb16918f4ff8c7bf/apps/sel4test-tests/src/tests/ipc.c",
"visit_date": "2023-09-01T15:11:56.065022"
} | stackv2 | /*
* Copyright 2017, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the BSD 2-Clause license. Note that NO WARRANTY is provided.
* See "LICENSE_BSD2.txt" for details.
*
* @TAG(DATA61_BSD)
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <sel4/sel4.h>
#include <vka/object.h>
#include "../helpers.h"
#define MIN_LENGTH 0
#define MAX_LENGTH (seL4_MsgMaxLength)
#define FOR_EACH_LENGTH(len_var) \
for(int len_var = MIN_LENGTH; len_var <= MAX_LENGTH; len_var++)
typedef int (*test_func_t)(seL4_Word /* endpoint */, seL4_Word /* seed */, seL4_Word /* reply */,
seL4_CPtr /* extra */);
static int
send_func(seL4_Word endpoint, seL4_Word seed, seL4_Word reply, seL4_Word extra)
{
FOR_EACH_LENGTH(length) {
seL4_MessageInfo_t tag = seL4_MessageInfo_new(0, 0, 0, length);
for (int i = 0; i < length; i++) {
seL4_SetMR(i, seed);
seed++;
}
seL4_Send(endpoint, tag);
}
return sel4test_get_result();
}
static int
nbsend_func(seL4_Word endpoint, seL4_Word seed, seL4_Word reply, seL4_Word extra)
{
FOR_EACH_LENGTH(length) {
seL4_MessageInfo_t tag = seL4_MessageInfo_new(0, 0, 0, length);
for (int i = 0; i < length; i++) {
seL4_SetMR(i, seed);
seed++;
}
seL4_NBSend(endpoint, tag);
}
return sel4test_get_result();
}
static int
call_func(seL4_Word endpoint, seL4_Word seed, seL4_Word reply, seL4_Word extra)
{
FOR_EACH_LENGTH(length) {
seL4_MessageInfo_t tag = seL4_MessageInfo_new(0, 0, 0, length);
/* Construct a message. */
for (int i = 0; i < length; i++) {
seL4_SetMR(i, seed);
seed++;
}
tag = seL4_Call(endpoint, tag);
seL4_Word actual_len = length;
/* Sanity check the received message. */
if (actual_len <= seL4_MsgMaxLength) {
test_assert(seL4_MessageInfo_get_length(tag) == actual_len);
} else {
actual_len = seL4_MsgMaxLength;
}
for (int i = 0; i < actual_len; i++) {
seL4_Word mr = seL4_GetMR(i);
test_check(mr == seed);
seed++;
}
}
return sel4test_get_result();
}
static int
wait_func(seL4_Word endpoint, seL4_Word seed, seL4_Word reply, seL4_Word extra)
{
FOR_EACH_LENGTH(length) {
seL4_MessageInfo_t tag;
seL4_Word sender_badge = 0;
tag = api_recv(endpoint, &sender_badge, reply);
seL4_Word actual_len = length;
if (actual_len <= seL4_MsgMaxLength) {
test_assert(seL4_MessageInfo_get_length(tag) == actual_len);
} else {
actual_len = seL4_MsgMaxLength;
}
for (int i = 0; i < actual_len; i++) {
seL4_Word mr = seL4_GetMR(i);
test_check(mr == seed);
seed++;
}
}
return sel4test_get_result();
}
static int
nbwait_func(seL4_Word endpoint, seL4_Word seed, seL4_Word reply, seL4_Word nbwait_should_wait)
{
if (!nbwait_should_wait) {
return sel4test_get_result();
}
FOR_EACH_LENGTH(length) {
seL4_MessageInfo_t tag;
seL4_Word sender_badge = 0;
tag = api_recv(endpoint, &sender_badge, reply);
seL4_Word actual_len = length;
if (actual_len <= seL4_MsgMaxLength) {
test_assert(seL4_MessageInfo_get_length(tag) == actual_len);
} else {
actual_len = seL4_MsgMaxLength;
}
for (int i = 0; i < actual_len; i++) {
seL4_Word mr = seL4_GetMR(i);
test_check(mr == seed);
seed++;
}
}
return sel4test_get_result();
}
static int
replywait_func(seL4_Word endpoint, seL4_Word seed, seL4_CPtr reply, seL4_Word extra)
{
int first = 1;
seL4_MessageInfo_t tag = seL4_MessageInfo_new(0, 0, 0, 0);
FOR_EACH_LENGTH(length) {
seL4_Word sender_badge = 0;
/* First reply/wait can't reply. */
if (first) {
#ifdef CONFIG_KERNEL_RT
tag = seL4_NBSendRecv(endpoint, tag, endpoint, &sender_badge, reply);
#else
tag = seL4_Recv(endpoint, &sender_badge);
#endif
first = 0;
} else {
tag = api_reply_recv(endpoint, tag, &sender_badge, reply);
}
seL4_Word actual_len = length;
/* Sanity check the received message. */
if (actual_len <= seL4_MsgMaxLength) {
test_assert(seL4_MessageInfo_get_length(tag) == actual_len);
} else {
actual_len = seL4_MsgMaxLength;
}
for (int i = 0; i < actual_len; i++) {
seL4_Word mr = seL4_GetMR(i);
test_check(mr == seed);
seed++;
}
/* Seed will have changed more if the message was truncated. */
for (int i = actual_len; i < length; i++) {
seed++;
}
/* Construct a reply. */
for (int i = 0; i < actual_len; i++) {
seL4_SetMR(i, seed);
seed++;
}
}
/* Need to do one last reply to match call. */
api_reply(reply, tag);
return sel4test_get_result();
}
static int
reply_and_wait_func(seL4_Word endpoint, seL4_Word seed, seL4_CPtr reply, seL4_Word unused)
{
int first = 1;
seL4_MessageInfo_t tag;
FOR_EACH_LENGTH(length) {
seL4_Word sender_badge = 0;
/* First reply/wait can't reply. */
if (!first) {
api_reply(reply, tag);
} else {
first = 0;
}
tag = api_recv(endpoint, &sender_badge, reply);
seL4_Word actual_len = length;
/* Sanity check the received message. */
if (actual_len <= seL4_MsgMaxLength) {
test_assert(seL4_MessageInfo_get_length(tag) == actual_len);
} else {
actual_len = seL4_MsgMaxLength;
}
for (int i = 0; i < actual_len; i++) {
seL4_Word mr = seL4_GetMR(i);
test_check(mr == seed);
seed++;
}
/* Seed will have changed more if the message was truncated. */
for (int i = actual_len; i < length; i++) {
seed++;
}
/* Construct a reply. */
for (int i = 0; i < actual_len; i++) {
seL4_SetMR(i, seed);
seed++;
}
}
/* Need to do one last reply to match call. */
api_reply(reply, tag);
return sel4test_get_result();
}
#ifdef CONFIG_KERNEL_RT
/* this function is expected to talk to another version of itself, second implies
* that this is the second to be executed */
static int
nbsendrecv_func(seL4_Word endpoint, seL4_Word seed, seL4_Word reply, seL4_Word unused)
{
FOR_EACH_LENGTH(length) {
api_nbsend_recv(endpoint, seL4_MessageInfo_new(0, 0, 0, MAX_LENGTH), endpoint, NULL, reply);
}
/* signal we're done to hanging second thread */
seL4_NBSend(endpoint, seL4_MessageInfo_new(0, 0, 0, MAX_LENGTH));
return sel4test_get_result();
}
#endif /* CONFIG_KERNEL_RT */
static int
test_ipc_pair(env_t env, test_func_t fa, test_func_t fb, bool inter_as, seL4_Word nr_cores)
{
helper_thread_t thread_a, thread_b;
vka_t *vka = &env->vka;
UNUSED int error;
seL4_CPtr ep = vka_alloc_endpoint_leaky(vka);
seL4_Word start_number = 0xabbacafe;
/* Test sending messages of varying lengths. */
/* Please excuse the awful indending here. */
for (int core_a = 0; core_a < nr_cores; core_a++) {
for (int core_b = 0; core_b < nr_cores; core_b++) {
for (int sender_prio = 98; sender_prio <= 102; sender_prio++) {
for (int waiter_prio = 100; waiter_prio <= 100; waiter_prio++) {
for (int sender_first = 0; sender_first <= 1; sender_first++) {
ZF_LOGD("%d %s %d\n",
sender_prio, sender_first ? "->" : "<-", waiter_prio);
seL4_Word thread_a_arg0, thread_b_arg0;
seL4_CPtr thread_a_reply, thread_b_reply;
if (inter_as) {
create_helper_process(env, &thread_a);
cspacepath_t path;
vka_cspace_make_path(&env->vka, ep, &path);
thread_a_arg0 = sel4utils_copy_path_to_process(&thread_a.process, path);
assert(thread_a_arg0 != -1);
create_helper_process(env, &thread_b);
thread_b_arg0 = sel4utils_copy_path_to_process(&thread_b.process, path);
assert(thread_b_arg0 != -1);
thread_a_reply = SEL4UTILS_REPLY_SLOT;
thread_b_reply = SEL4UTILS_REPLY_SLOT;
} else {
create_helper_thread(env, &thread_a);
create_helper_thread(env, &thread_b);
thread_a_arg0 = ep;
thread_b_arg0 = ep;
thread_a_reply = get_helper_reply(&thread_a);
thread_b_reply = get_helper_reply(&thread_b);
}
set_helper_priority(env, &thread_a, sender_prio);
set_helper_priority(env, &thread_b, waiter_prio);
set_helper_affinity(env, &thread_a, core_a);
set_helper_affinity(env, &thread_b, core_b);
/* Set the flag for nbwait_func that tells it whether or not it really
* should wait. */
int nbwait_should_wait;
nbwait_should_wait =
(sender_prio < waiter_prio);
/* Threads are enqueued at the head of the scheduling queue, so the
* thread enqueued last will be run first, for a given priority. */
if (sender_first) {
start_helper(env, &thread_b, (helper_fn_t) fb, thread_b_arg0, start_number,
thread_b_reply, nbwait_should_wait);
start_helper(env, &thread_a, (helper_fn_t) fa, thread_a_arg0, start_number,
thread_a_reply, nbwait_should_wait);
} else {
start_helper(env, &thread_a, (helper_fn_t) fa, thread_a_arg0, start_number,
thread_a_reply, nbwait_should_wait);
start_helper(env, &thread_b, (helper_fn_t) fb, thread_b_arg0, start_number,
thread_b_reply, nbwait_should_wait);
}
wait_for_helper(&thread_a);
wait_for_helper(&thread_b);
cleanup_helper(env, &thread_a);
cleanup_helper(env, &thread_b);
start_number += 0x71717171;
}
}
}
}
}
error = cnode_delete(env, ep);
test_assert(!error);
return sel4test_get_result();
}
static int
test_send_wait(env_t env)
{
return test_ipc_pair(env, send_func, wait_func, false, env->cores);
}
DEFINE_TEST(IPC0001, "Test seL4_Send + seL4_Recv", test_send_wait)
static int
test_call_replywait(env_t env)
{
return test_ipc_pair(env, call_func, replywait_func, false, env->cores);
}
DEFINE_TEST(IPC0002, "Test seL4_Call + seL4_ReplyRecv", test_call_replywait)
static int
test_call_reply_and_wait(env_t env)
{
return test_ipc_pair(env, call_func, reply_and_wait_func, false, env->cores);
}
DEFINE_TEST(IPC0003, "Test seL4_Send + seL4_Reply + seL4_Recv", test_call_reply_and_wait)
static int
test_nbsend_wait(env_t env)
{
return test_ipc_pair(env, nbsend_func, nbwait_func, false, 1);
}
DEFINE_TEST(IPC0004, "Test seL4_NBSend + seL4_Recv", test_nbsend_wait)
static int
test_send_wait_interas(env_t env)
{
return test_ipc_pair(env, send_func, wait_func, true, env->cores);
}
DEFINE_TEST(IPC1001, "Test inter-AS seL4_Send + seL4_Recv", test_send_wait_interas)
static int
test_call_replywait_interas(env_t env)
{
return test_ipc_pair(env, call_func, replywait_func, true, env->cores);
}
DEFINE_TEST(IPC1002, "Test inter-AS seL4_Call + seL4_ReplyRecv", test_call_replywait_interas)
static int
test_call_reply_and_wait_interas(env_t env)
{
return test_ipc_pair(env, call_func, reply_and_wait_func, true, env->cores);
}
DEFINE_TEST(IPC1003, "Test inter-AS seL4_Send + seL4_Reply + seL4_Recv", test_call_reply_and_wait_interas)
static int
test_nbsend_wait_interas(env_t env)
{
return test_ipc_pair(env, nbsend_func, nbwait_func, true, 1);
}
DEFINE_TEST(IPC1004, "Test inter-AS seL4_NBSend + seL4_Recv", test_nbsend_wait_interas)
static int
test_ipc_abort_in_call(env_t env)
{
helper_thread_t thread_a;
vka_t * vka = &env->vka;
seL4_CPtr ep = vka_alloc_endpoint_leaky(vka);
seL4_CPtr reply = vka_alloc_reply_leaky(vka);
seL4_Word start_number = 0xabbacafe;
create_helper_thread(env, &thread_a);
set_helper_priority(env, &thread_a, 100);
start_helper(env, &thread_a, (helper_fn_t) call_func, ep, start_number, 0, 0);
/* Wait for the endpoint that it's going to call. */
seL4_Word sender_badge = 0;
api_recv(ep, &sender_badge, reply);
/* Now suspend the thread. */
seL4_TCB_Suspend(get_helper_tcb(&thread_a));
/* Now resume the thread. */
seL4_TCB_Resume(get_helper_tcb(&thread_a));
/* Now suspend it again for good measure. */
seL4_TCB_Suspend(get_helper_tcb(&thread_a));
/* And delete it. */
cleanup_helper(env, &thread_a);
return sel4test_get_result();
}
DEFINE_TEST(IPC0010, "Test suspending an IPC mid-Call()", test_ipc_abort_in_call)
#ifdef CONFIG_KERNEL_RT
#define RUNS 10
static void
server_fn(seL4_CPtr endpoint, seL4_CPtr reply, volatile int *state)
{
/* signal the intialiser that we are done */
ZF_LOGD("Server call");
*state = *state + 1;
seL4_MessageInfo_t info = api_nbsend_recv(endpoint, info, endpoint, NULL, reply);
/* from here on we are running on borrowed time */
ZF_LOGD("Server awake!\n");
int i = 0;
while (i < RUNS) {
test_assert(seL4_GetMR(0) == 12345678);
seL4_SetMR(0, 0xdeadbeef);
*state = *state + 1;
ZF_LOGD("Server replyRecv\n");
info = seL4_ReplyRecv(endpoint, info, NULL, reply);
i++;
}
}
static void
proxy_fn(seL4_CPtr receive_endpoint, seL4_CPtr call_endpoint, seL4_Word reply, volatile int *state)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
/* signal the initialiser that we are awake */
ZF_LOGD("Proxy nbsendrecv, sending on ep %lu, receiving on ep %lu, reply is %lu\n", call_endpoint, receive_endpoint, reply);
*state = *state + 1;
info = api_nbsend_recv(call_endpoint, info, receive_endpoint, NULL, reply);
/* when we get here we are running on a donated scheduling context,
as the initialiser has taken ours away */
int i = 0;
while (i < RUNS) {
test_assert(seL4_GetMR(0) == 12345678);
seL4_SetMR(0, 12345678);
ZF_LOGD("Proxy call\n");
seL4_Call(call_endpoint, info);
test_assert(seL4_GetMR(0) == 0xdeadbeef);
seL4_SetMR(0, 0xdeadbeef);
ZF_LOGD("Proxy replyRecv\n");
*state = *state + 1;
info = seL4_ReplyRecv(receive_endpoint, info, NULL, reply);
i++;
}
}
static void
client_fn(seL4_CPtr endpoint, bool fastpath, int unused, volatile int *state)
{
/* make the message greater than 4 in size if we do not want to hit the fastpath */
uint32_t length = fastpath ? 1 : 8;
int i = 0;
while (i < RUNS) {
seL4_SetMR(0, 12345678);
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, length);
ZF_LOGD("Client calling on ep %lu\n", endpoint);
info = seL4_Call(endpoint, info);
test_assert(seL4_GetMR(0) == 0xdeadbeef);
i++;
*state = *state + 1;
}
}
static int
single_client_server_chain_test(env_t env, int fastpath, int prio_diff)
{
const int num_proxies = 5;
int client_prio = 10;
int server_prio = client_prio + (prio_diff * num_proxies);
helper_thread_t client, server;
helper_thread_t proxies[num_proxies];
volatile int client_state = 0;
volatile int server_state = 0;
volatile int proxy_state[num_proxies];
create_helper_thread(env, &client);
set_helper_priority(env, &client, client_prio);
seL4_CPtr receive_endpoint = vka_alloc_endpoint_leaky(&env->vka);
seL4_CPtr first_endpoint = receive_endpoint;
/* create proxies */
for (int i = 0; i < num_proxies; i++) {
int prio = server_prio + (prio_diff * i);
proxy_state[i] = 0;
seL4_CPtr call_endpoint = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &proxies[i]);
set_helper_priority(env, &proxies[i], prio);
ZF_LOGD("Start proxy\n");
start_helper(env, &proxies[i], (helper_fn_t) proxy_fn, receive_endpoint,
call_endpoint, proxies[i].thread.reply.cptr, (seL4_Word) &proxy_state[i]);
/* wait for proxy to initialise */
ZF_LOGD("Recv for proxy\n");
seL4_Wait(call_endpoint, NULL);
test_eq(proxy_state[i], 1);
/* now take away its scheduling context */
int error = api_sc_unbind(proxies[i].thread.sched_context.cptr);
test_eq(error, seL4_NoError);
receive_endpoint = call_endpoint;
}
/* create the server */
create_helper_thread(env, &server);
set_helper_priority(env, &server, server_prio);
ZF_LOGD("Start server");
start_helper(env, &server, (helper_fn_t) server_fn, receive_endpoint, server.thread.reply.cptr,
(seL4_Word) &server_state, 0);
/* wait for server to initialise on our time */
ZF_LOGD("Recv for server");
seL4_Wait(receive_endpoint, NULL);
test_eq(server_state, 1);
/* now take it's scheduling context away */
int error = api_sc_unbind(server.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
ZF_LOGD("Start client");
start_helper(env, &client, (helper_fn_t) client_fn, first_endpoint,
fastpath, RUNS, (seL4_Word) &client_state);
/* sleep and let the testrun */
ZF_LOGD("wait_for_helper() for client");
wait_for_helper(&client);
test_eq(server_state, RUNS + 1);
test_eq(client_state, RUNS);
for (int i = 0; i < num_proxies; i++) {
test_eq(proxy_state[i], RUNS + 1);
}
return sel4test_get_result();
}
int test_single_client_slowpath_same_prio(env_t env)
{
return single_client_server_chain_test(env, 0, 0);
}
DEFINE_TEST(IPC0011, "Client-server inheritance: slowpath, same prio", test_single_client_slowpath_same_prio)
int test_single_client_slowpath_higher_prio(env_t env)
{
return single_client_server_chain_test(env, 0, 1);
}
DEFINE_TEST(IPC0012, "Client-server inheritance: slowpath, client higher prio",
test_single_client_slowpath_higher_prio)
int test_single_client_slowpath_lower_prio(env_t env)
{
return single_client_server_chain_test(env, 0, -1);
}
DEFINE_TEST(IPC0013, "Client-server inheritance: slowpath, client lower prio",
test_single_client_slowpath_lower_prio)
int test_single_client_fastpath_higher_prio(env_t env)
{
return single_client_server_chain_test(env, 1, 1);
}
DEFINE_TEST(IPC0014, "Client-server inheritance: fastpath, client higher prio", test_single_client_fastpath_higher_prio)
int
test_single_client_fastpath_same_prio(env_t env)
{
return single_client_server_chain_test(env, 1, 0);
}
DEFINE_TEST(IPC0015, "Client-server inheritance: fastpath, client same prio", test_single_client_fastpath_same_prio)
static void
ipc0016_call_once_fn(seL4_CPtr endpoint, volatile int *state)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
*state = *state + 1;
ZF_LOGD("Call %d\n", *state);
seL4_Call(endpoint, info);
ZF_LOGD("Resumed with reply\n");
*state = *state + 1;
}
static void
ipc0016_reply_once_fn(seL4_CPtr endpoint, seL4_CPtr reply)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
/* send initialisation context back */
ZF_LOGD("seL4_nbsendrecv\n");
api_nbsend_recv(endpoint, info, endpoint, NULL, reply);
/* reply */
ZF_LOGD("Reply\n");
seL4_Send(reply, info);
/* wait (keeping sc) */
ZF_LOGD("Recv\n");
seL4_Wait(endpoint, NULL);
test_assert(!"should not get here");
}
static int test_transfer_on_reply(env_t env)
{
volatile int state = 1;
helper_thread_t client, server;
seL4_CPtr endpoint = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &client);
create_helper_thread(env, &server);
set_helper_priority(env, &client, 10);
set_helper_priority(env, &server, 11);
start_helper(env, &server, (helper_fn_t) ipc0016_reply_once_fn, endpoint, server.thread.reply.cptr, 0, 0);
/* wait for server to initialise */
seL4_Wait(endpoint, NULL);
/* now remove the schedluing context */
int error = api_sc_unbind(server.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
/* start the client */
start_helper(env, &client, (helper_fn_t) ipc0016_call_once_fn, endpoint,
(seL4_Word) &state, 0, 0);
/* the server will attempt to steal the clients scheduling context
* by using seL4_Send instead of seL4_ReplyWait. However,
* a reply cap is a guarantee that a scheduling context will be returned,
* so it does return to the client and the server hangs.
*/
wait_for_helper(&client);
test_eq(state, 3);
return sel4test_get_result();
}
DEFINE_TEST(IPC0016, "Test reply returns scheduling context",
test_transfer_on_reply);
/* used by ipc0017 and ipc0019 */
static void
sender(seL4_CPtr endpoint, volatile int *state)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
ZF_LOGD("Client send\n");
*state = 1;
seL4_Send(endpoint, info);
*state = 2;
}
static void
wait_server(seL4_CPtr endpoint, int messages)
{
/* signal test that we are initialised */
seL4_Send(endpoint, seL4_MessageInfo_new(0, 0, 0, 0));
int i = 0;
while (i < messages) {
ZF_LOGD("Server wait\n");
seL4_Wait(endpoint, NULL);
i++;
}
}
static int
test_send_to_no_sc(env_t env)
{
/* sends should block until the server gets a scheduling context.
* nb sends should not block */
helper_thread_t server, client1, client2;
seL4_CPtr endpoint = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &server);
create_helper_thread(env, &client1);
create_helper_thread(env, &client2);
set_helper_priority(env, &server, 10);
set_helper_priority(env, &client1, 9);
set_helper_priority(env, &client2, 9);
const int num_server_messages = 4;
start_helper(env, &server, (helper_fn_t) wait_server, endpoint, num_server_messages, 0, 0);
seL4_Wait(endpoint, NULL);
int error = api_sc_unbind(server.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
/* this message should not result in the server being scheduled */
ZF_LOGD("NBSend");
seL4_SetMR(0, 12345678);
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 1);
seL4_NBSend(endpoint, info);
test_eq(seL4_GetMR(0), (seL4_Word)12345678);
/* start clients */
volatile int state1 = 0;
volatile int state2 = 0;
start_helper(env, &client1, (helper_fn_t) sender, endpoint, (seL4_Word) &state1, 0, 0);
start_helper(env, &client2, (helper_fn_t) sender, endpoint, (seL4_Word) &state2, 0 , 0);
/* set our prio down, both clients should block as the server cannot
* run without a schedluing context */
error = seL4_TCB_SetPriority(env->tcb, 8);
test_eq(error, seL4_NoError);
test_eq(state1, 1);
test_eq(state2, 1);
/* restore the servers schedluing context */
error = api_sc_bind(server.thread.sched_context.cptr, server.thread.tcb.cptr);
test_eq(error, seL4_NoError);
/* now the clients should be unblocked */
test_eq(state1, 2);
test_eq(state2, 2);
/* this should work */
seL4_NBSend(endpoint, info);
/* and so should this */
seL4_Send(endpoint, info);
/* if the server received the correct number of messages it should now be done */
wait_for_helper(&server);
return sel4test_get_result();
}
DEFINE_TEST(IPC0017, "Test seL4_Send/seL4_NBSend to a server with no scheduling context", test_send_to_no_sc)
static void
ipc0018_helper(seL4_CPtr endpoint, volatile int *state)
{
*state = 1;
while (1) {
ZF_LOGD("Send");
seL4_Send(endpoint, seL4_MessageInfo_new(0, 0, 0, 0));
*state = *state + 1;
}
}
static int
test_receive_no_sc(env_t env)
{
helper_thread_t client;
volatile int state = 0;
seL4_CPtr endpoint = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &client);
set_helper_priority(env, &client, 10);
int error = seL4_TCB_SetPriority(env->tcb, 9);
test_eq(error, seL4_NoError);
/* start the client, it will increment state and send a message */
start_helper(env, &client, (helper_fn_t) ipc0018_helper, endpoint,
(seL4_Word) &state, 0, 0);
test_eq(state, 1);
/* clear the clients scheduling context */
ZF_LOGD("Unbind scheduling context");
error = api_sc_unbind(client.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
/* now we should be able to receive the message, but since the client
* no longer has a schedluing context it should not run
*/
ZF_LOGD("Recv");
seL4_Wait(endpoint, NULL);
/* check thread has not run */
test_eq(state, 1);
/* now set the schedluing context again */
error = api_sc_bind(client.thread.sched_context.cptr,
client.thread.tcb.cptr);
test_eq(error, seL4_NoError);
test_eq(state, 2);
/* now get another message */
seL4_Wait(endpoint, NULL);
test_eq(state, 3);
/* and another, to check client is well and truly running */
seL4_Wait(endpoint, NULL);
test_eq(state, 4);
return sel4test_get_result();
}
DEFINE_TEST(IPC0018, "Test receive from a client with no scheduling context",
test_receive_no_sc);
static int
delete_sc_client_sending_on_endpoint(env_t env)
{
helper_thread_t client;
volatile int state = 0;
seL4_CPtr endpoint = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &client);
set_helper_priority(env, &client, 10);
/* set our prio below the helper */
int error = seL4_TCB_SetPriority(env->tcb, 9);
test_eq(error, seL4_NoError);
start_helper(env, &client, (helper_fn_t) sender, endpoint, (seL4_Word) &state, 0, 0);
/* the client will run and send on the endpoint */
test_eq(state, 1);
/* now delete the scheduling context - this should unbind the client
* but not remove the message */
ZF_LOGD("Destroying schedluing context");
vka_free_object(&env->vka, &client.thread.sched_context);
ZF_LOGD("seL4_Wait");
seL4_Wait(endpoint, NULL);
test_eq(state, 1);
return sel4test_get_result();
}
DEFINE_TEST(IPC0019, "Test deleteing the scheduling context while a client is sending on an endpoint", delete_sc_client_sending_on_endpoint);
static void
ipc0020_helper(seL4_CPtr endpoint, volatile int *state)
{
*state = 1;
while (1) {
ZF_LOGD("Recv");
seL4_Wait(endpoint, NULL);
*state = *state + 1;
}
}
static int
delete_sc_client_waiting_on_endpoint(env_t env)
{
helper_thread_t waiter;
volatile int state = 0;
seL4_CPtr endpoint = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &waiter);
set_helper_priority(env, &waiter, 10);
int error = seL4_TCB_SetPriority(env->tcb, 9);
start_helper(env, &waiter, (helper_fn_t) ipc0020_helper, endpoint, (seL4_Word) &state, 0, 0);
/* helper should run and block receiving on endpoint */
test_eq(state, 1);
/* destroy scheduling context */
vka_free_object(&env->vka, &waiter.thread.sched_context);
/* send message */
seL4_Send(endpoint, seL4_MessageInfo_new(0, 0, 0, 0));
/* thread should not have moved */
test_eq(state, 1);
/* now create a new scheduling context and give it to the thread */
seL4_CPtr sched_context = vka_alloc_sched_context_leaky(&env->vka);
error = api_sched_ctrl_configure(simple_get_sched_ctrl(&env->simple, 0), sched_context,
1000 * US_IN_S, 1000 * US_IN_S, 0, 0);
test_eq(error, seL4_NoError);
error = api_sc_bind(sched_context, waiter.thread.tcb.cptr);
test_eq(error, seL4_NoError);
/* now the thread should run and receive the message */
test_eq(state, 2);
return sel4test_get_result();
}
DEFINE_TEST(IPC0020, "test deleting a scheduling context while the client is waiting on an endpoint",
delete_sc_client_waiting_on_endpoint);
static void ipc21_faulter_fn(int *addr)
{
ZF_LOGD("Fault at %p\n", addr);
*addr = 0xdeadbeef;
ZF_LOGD("Resumed\n");
}
static void ipc21_fault_handler_fn(seL4_CPtr endpoint, vspace_t *vspace, reservation_t *res, seL4_CPtr reply)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
info = api_nbsend_recv(endpoint, info, endpoint, NULL, reply);
while (1) {
test_check(seL4_isVMFault_tag(info));
void *addr = (void *) seL4_GetMR(seL4_VMFault_Addr);
ZF_LOGD("Handling fault at %p\n", addr);
int error = vspace_new_pages_at_vaddr(vspace, addr, 1, seL4_PageBits, *res);
test_eq(error, seL4_NoError);
seL4_ReplyRecv(endpoint, info, NULL, reply);
}
}
static int test_fault_handler_donated_sc(env_t env)
{
helper_thread_t handler, faulter;
void *vaddr = NULL;
seL4_CPtr endpoint = vka_alloc_endpoint_leaky(&env->vka);
reservation_t res = vspace_reserve_range(&env->vspace, PAGE_SIZE_4K, seL4_AllRights, 1, &vaddr);
test_check(vaddr != NULL);
create_helper_thread(env, &handler);
create_helper_thread(env, &faulter);
/* start fault handler */
start_helper(env, &handler, (helper_fn_t) ipc21_fault_handler_fn,
endpoint, (seL4_Word) &env->vspace, (seL4_Word) &res,
handler.thread.reply.cptr);
/* wait for it to initialise */
seL4_Wait(endpoint, NULL);
/* now remove its scheduling context */
int error = api_sc_unbind(handler.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
/* set fault handler */
seL4_CapData_t data = seL4_CapData_Guard_new(0, seL4_WordBits - env->cspace_size_bits);
seL4_CapData_t null = {{0}};
error = api_tcb_set_space(faulter.thread.tcb.cptr, endpoint, seL4_CapNull,
env->cspace_root, data, env->page_directory, null);
test_eq(error, seL4_NoError);
/* start the fault handler */
start_helper(env, &faulter, (helper_fn_t) ipc21_faulter_fn, (seL4_Word) vaddr, 0, 0, 0);
/* the faulter handler will restore the faulter and we should not block here */
wait_for_helper(&faulter);
return sel4test_get_result();
}
DEFINE_TEST(IPC0021, "Test fault handler on donated scheduling context",
test_fault_handler_donated_sc);
static void
ipc22_client_fn(seL4_CPtr endpoint, volatile int *state)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
ZF_LOGD("Client init");
seL4_Call(endpoint, info);
*state = *state + 1;
ZF_LOGD("Client receive reply");
}
static seL4_CPtr ipc22_go;
static void
ipc22_server_fn(seL4_CPtr init_ep, seL4_CPtr reply_cap)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
ZF_LOGD("Server init\n");
/* wait for the signal to go from the test runner -
* we have to block here to wait for all the clients to
* start and queue up - otherwise they will all be served
* by the same server and the point is to test stack spawning */
api_nbsend_recv(init_ep, info, init_ep, NULL, reply_cap);
ZF_LOGD("Server reply to fwded cap\n");
seL4_Send(reply_cap, info);
}
static void
ipc22_stack_spawner_fn(env_t env, seL4_CPtr endpoint, int server_prio, seL4_Word unused)
{
helper_thread_t servers[RUNS];
seL4_CPtr init_ep = vka_alloc_endpoint_leaky(&env->vka);
/* first we signal to endpoint to tell the test runner we are ready */
seL4_CPtr first_ep = endpoint;
ZF_LOGD("Stack spawner init");
for (int i = 0; i < RUNS; i++) {
create_helper_thread(env, &servers[i]);
set_helper_priority(env, &servers[i], server_prio);
api_nbsend_recv(first_ep, seL4_MessageInfo_new(0, 0, 0, 0), endpoint, NULL,
servers[i].thread.reply.cptr);
/* after the first nbsend, we want to signal the clients via init_ep */
first_ep = init_ep;
ZF_LOGD("Got another client\n");
/* start helper and allow to initialise */
ZF_LOGD("Spawn server\n");
start_helper(env, &servers[i], (helper_fn_t) ipc22_server_fn, init_ep,
servers[i].thread.reply.cptr, 0, 0);
/* wait for it to block */
seL4_Wait(init_ep, NULL);
/* now remove the schedling context */
int error = api_sc_unbind(servers[i].thread.sched_context.cptr);
test_eq(error, seL4_NoError);
}
/* signal the last client */
api_nbsend_recv(first_ep, seL4_MessageInfo_new(0, 0, 0, 0), endpoint, NULL, servers[RUNS - 1].thread.reply.cptr);
}
static int test_stack_spawning_server(env_t env)
{
helper_thread_t clients[RUNS];
helper_thread_t stack_spawner;
seL4_CPtr endpoint = vka_alloc_endpoint_leaky(&env->vka);
ipc22_go = vka_alloc_endpoint_leaky(&env->vka);
volatile int state = 0;
int our_prio = 10;
create_helper_thread(env, &stack_spawner);
set_helper_mcp(env, &stack_spawner, seL4_MaxPrio);
start_helper(env, &stack_spawner, (helper_fn_t) ipc22_stack_spawner_fn,
(seL4_Word) env, endpoint, our_prio + 1, RUNS);
/* wait for stack spawner to init */
ZF_LOGD("Wait for stack spawner to init");
seL4_Wait(endpoint, NULL);
/* take away scheduling context */
int error = api_sc_unbind(stack_spawner.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
set_helper_priority(env, &stack_spawner, our_prio + 2);
error = seL4_TCB_SetPriority(env->tcb, our_prio);
test_eq(error, seL4_NoError);
set_helper_priority(env, &stack_spawner, our_prio + 2);
set_helper_mcp(env, &stack_spawner, seL4_MaxPrio - 1);
ZF_LOGD("Starting clients");
/* create and start clients */
for (int i = 0; i < RUNS; i++) {
create_helper_thread(env, &clients[i]);
set_helper_priority(env, &clients[i], our_prio + 1);
start_helper(env, &clients[i], (helper_fn_t) ipc22_client_fn, endpoint, (seL4_Word) &state, i, 0);
}
/* set our priority down so servers can run */
error = seL4_TCB_SetPriority(env->tcb, our_prio - 2);
test_eq(error, seL4_NoError);
for (int i = 0; i < RUNS; i++) {
wait_for_helper(&clients[i]);
}
ZF_LOGD("Done");
/* make sure all the clients got served */
test_eq(state, RUNS);
return sel4test_get_result();
}
DEFINE_TEST(IPC0022, "Test stack spawning server with scheduling context donation",
test_stack_spawning_server);
static void ipc23_client_fn(seL4_CPtr ep, volatile int *state)
{
seL4_MessageInfo_t info = seL4_MessageInfo_new(0, 0, 0, 0);
*state = 1;
ZF_LOGD("Call");
seL4_Call(ep, info);
/* should not get here */
*state = 2;
}
/* used by ipc0023 and 0024 */
static void ipc23_server_fn(seL4_CPtr client_ep, seL4_CPtr wait_ep, seL4_CPtr reply)
{
/* send to the wait_ep to tell the test we are initialised,
* then wait on the client_ep to receive a scheduling context */
api_nbsend_recv(wait_ep, seL4_MessageInfo_new(0, 0, 0, 0), client_ep, NULL, reply);
/* now block */
seL4_Wait(wait_ep, NULL);
}
static int test_delete_reply_cap_sc(env_t env)
{
helper_thread_t client, server;
volatile int state = 0;
seL4_CPtr client_ep = vka_alloc_endpoint_leaky(&env->vka);
seL4_CPtr server_ep = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &client);
create_helper_thread(env, &server);
start_helper(env, &client, (helper_fn_t) ipc23_client_fn, client_ep,
(seL4_Word) &state, 0, 0);
start_helper(env, &server, (helper_fn_t) ipc23_server_fn, client_ep,
server_ep, server.thread.reply.cptr, 0);
/* wait for server to init */
seL4_Wait(server_ep, NULL);
/* take its scheduling context away */
int error = api_sc_unbind(server.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
/* set the client and server prio higher than ours so they can run */
error = seL4_TCB_SetPriority(env->tcb, 10);
test_eq(error, seL4_NoError);
set_helper_priority(env, &client, 11);
set_helper_priority(env, &server, 11);
/* now the client should have run and called the server*/
test_eq(state, 1);
/* delete scheduling context */
vka_free_object(&env->vka,& client.thread.sched_context);
/* try to reply, the client should not run as it has no scheduling context */
seL4_Signal(server.thread.reply.cptr);
test_eq(state, 1);
return sel4test_get_result();
}
DEFINE_TEST(IPC0023, "Test deleting the scheduling context tracked in a reply cap",
test_delete_reply_cap_sc)
static int test_delete_reply_cap_then_sc(env_t env)
{
helper_thread_t client, server;
volatile int state = 0;
seL4_CPtr client_ep = vka_alloc_endpoint_leaky(&env->vka);
seL4_CPtr server_ep = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &client);
create_helper_thread(env, &server);
set_helper_priority(env, &client, 11);
set_helper_priority(env, &server, 11);
/* start server */
start_helper(env, &server, (helper_fn_t) ipc23_server_fn, client_ep,
server_ep, server.thread.reply.cptr, 0);
ZF_LOGD("Waiting for server");
/* wait for server to init */
seL4_Wait(server_ep, NULL);
/* set our prio down so client can run */
int error = seL4_TCB_SetPriority(env->tcb, 10);
test_eq(error, 0);
ZF_LOGD("Removed sc\n");
/* remove schedluing context */
error = api_sc_unbind(server.thread.sched_context.cptr);
test_eq(error, seL4_NoError);
ZF_LOGD("Start client");
/* start client */
start_helper(env, &client, (helper_fn_t) ipc23_client_fn, client_ep,
(seL4_Word) &state, 0, 0);
/* client should have started */
test_eq(state, 1);
ZF_LOGD("Steal reply cap ");
/* nuke the reply cap */
vka_free_object(&env->vka, &server.thread.reply);
/* nuke the sc */
vka_free_object(&env->vka, &client.thread.sched_context);
ZF_LOGD("Done");
/* caller should not run */
test_eq(1, state);
return sel4test_get_result();
}
DEFINE_TEST(IPC0024, "Test deleting the reply cap in the scheduling context",
test_delete_reply_cap_then_sc);
static int test_nbsendrecv(env_t env)
{
return test_ipc_pair(env, (test_func_t) nbsendrecv_func, (test_func_t) nbsendrecv_func, false, env->cores);
}
DEFINE_TEST(IPC0025, "Test seL4_nbsendrecv + seL4_nbsendrecv", test_nbsendrecv)
static int test_nbsendrecv_interas(env_t env)
{
return test_ipc_pair(env, (test_func_t) nbsendrecv_func, (test_func_t) nbsendrecv_func, false, env->cores);
}
DEFINE_TEST(IPC0026, "Test interas seL4_nbsendrecv + seL4_nbsendrecv", test_nbsendrecv_interas)
static int
test_sched_donation_low_prio_server(env_t env)
{
helper_thread_t client, server, server2;
seL4_CPtr ep = vka_alloc_endpoint_leaky(&env->vka);
create_helper_thread(env, &client);
int error = create_passive_thread(env, &server, (helper_fn_t) replywait_func, ep, 0, client.thread.reply.cptr, 0);
test_eq(error, seL4_NoError);
/* make client higher prio than server */
set_helper_priority(env, &server, 1);
set_helper_priority(env, &client, 2);
ZF_LOGD("Start client");
start_helper(env, &client, (helper_fn_t) call_func, ep, 0, 0, 0);
ZF_LOGD("Wait for helper");
wait_for_helper(&client);
/* give server a sc to finish on */
error = api_sc_bind(server.thread.sched_context.cptr,
server.thread.tcb.cptr);
test_eq(error, 0);
wait_for_helper(&server);
/* now try again, but start the client first */
start_helper(env, &client, (helper_fn_t) call_func, ep, 0, 0, 0);
error = create_passive_thread(env, &server2, (helper_fn_t) replywait_func, ep, 0,
client.thread.reply.cptr, 0);
test_eq(error, seL4_NoError);
ZF_LOGD("Wait for helper");
wait_for_helper(&client);
error = api_sc_bind(server2.thread.sched_context.cptr,
server2.thread.tcb.cptr);
test_eq(error, 0);
wait_for_helper(&server2);
return sel4test_get_result();
}
DEFINE_TEST(IPC0027, "Test sched donation to low prio server", test_sched_donation_low_prio_server)
#if CONFIG_MAX_NUM_NODES > 1
static void
ipc28_server_fn(seL4_CPtr ep, seL4_CPtr reply, volatile int *state)
{
api_nbsend_recv(ep, seL4_MessageInfo_new(0, 0, 0, 0), ep, NULL, reply);
while (1) {
*state = *state + 1;
seL4_ReplyRecv(ep, seL4_MessageInfo_new(0, 0, 0, 0), NULL, reply);
}
}
static int
ipc28_client_fn(seL4_CPtr ep, volatile int *state) {
while (*state < RUNS) {
seL4_Call(ep, seL4_MessageInfo_new(0, 0, 0, 0));
*state = *state + 1;
}
return 0;
}
static int
test_sched_donation_cross_core(env_t env)
{
seL4_CPtr ep = vka_alloc_endpoint_leaky(&env->vka);
helper_thread_t clients[env->cores - 1];
helper_thread_t server;
volatile int states[env->cores - 1];
volatile seL4_Word server_state = 0;
/* start server on core 0 */
create_helper_thread(env, &server);
/* start a client on each other core */
for (int i = 0; i < env->cores - 1; i++) {
states[i] = 0;
create_helper_thread(env, &clients[i]);
set_helper_affinity(env, &clients[i], i + 1);
}
/* start server */
start_helper(env, &server, (helper_fn_t) ipc28_server_fn, ep, get_helper_reply(&server),
(seL4_Word) &server_state, 0);
/* wait for server to init */
seL4_Wait(ep, NULL);
/* convert to passive */
int error = api_sc_unbind(get_helper_sched_context(&server));
test_eq(error, seL4_NoError);
/* start clients */
for (int i = 0; i < env->cores - 1; i++) {
start_helper(env, &clients[i], (helper_fn_t) ipc28_client_fn, ep, (seL4_Word) &states[i], 0, 0);
}
/* wait for the clients */
for (int i = 0; i < env->cores - 1; i++) {
error = wait_for_helper(&clients[i]);
test_eq(error, 0);
test_eq(states[i], RUNS);
}
test_eq(server_state, RUNS * (env->cores - 1));
return sel4test_get_result();
}
DEFINE_TEST(IPC0028, "Cross core sched donation", test_sched_donation_cross_core);
#endif /* CONFIG_MAX_NUM_NODES */
#endif /* CONFIG_KERNEL_RT */
| 2.03125 | 2 |
2024-11-18T20:55:45.442995+00:00 | 2017-10-10T18:26:28 | f3d5f692e0a37ba0a777ab79ce9a5e633a4e585c | {
"blob_id": "f3d5f692e0a37ba0a777ab79ce9a5e633a4e585c",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-10T18:26:28",
"content_id": "59cf6a76d03279934e10d09e5852ac775cb546e1",
"detected_licenses": [
"Unlicense"
],
"directory_id": "142d2507ffdbd4219134399a86a10b8587ce4f3f",
"extension": "c",
"filename": "parsingTwoIntegersBackAndForth.c",
"fork_events_count": 0,
"gha_created_at": "2017-09-28T11:58:33",
"gha_event_created_at": "2017-10-10T18:25:07",
"gha_language": "C",
"gha_license_id": null,
"github_id": 105142756,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 946,
"license": "Unlicense",
"license_type": "permissive",
"path": "/test/parsingTwoIntegersBackAndForth.c",
"provenance": "stackv2-0092.json.gz:47812",
"repo_name": "judo347/SideScroller",
"revision_date": "2017-10-10T18:26:28",
"revision_id": "574e5b2c2dbb5537c953ed7e955faeeb8203ce45",
"snapshot_id": "9d49a32b989632cb1420ecda62b4bcefc35713f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/judo347/SideScroller/574e5b2c2dbb5537c953ed7e955faeeb8203ce45/test/parsingTwoIntegersBackAndForth.c",
"visit_date": "2021-07-13T02:34:38.469365"
} | stackv2 | #include <stdio.h>
/* IMPROVED */
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = ++x;
*quot = --y;
}
int main()
{
int x = 5,y = 5, prod, quot;
Calculate(x, y, &prod, ");
x = prod;
y = quot;
printf("%d %d\n", prod, quot);
printf("%d %d\n", x, y);
return 0;
}
/* WORKS
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = x*y;
*quot = x/y;
}
int main()
{
int x = 10,y = 2, prod, quot;
Calculate(x, y, &prod, ");
printf("%d %d\n", prod, quot);
return 0;
}
*/
/* USING STRUCT - DOES NOT WORK!
struct player
{
int x;
int y;
};
void plusFunc(struct currentplayer)
{
currentplayer.x = currentplayer.x + 1;
currentplayer.y = currentplayer.y + 1;
}
int main(void)
{
struct player currentplayer;
currentplayer.x = 5;
currentplayer.y = 5;
printf("%d %d\n", currentplayer.x, currentplayer.y);
return 0;
}
*/
| 3.25 | 3 |
2024-11-18T20:55:45.711302+00:00 | 2015-04-17T17:56:20 | 03ae44b2966c43aa219fec11141ee4002cbc9919 | {
"blob_id": "03ae44b2966c43aa219fec11141ee4002cbc9919",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-17T17:56:20",
"content_id": "87f33eb6410496511dd03a4994860deb33b64d8a",
"detected_licenses": [
"ISC"
],
"directory_id": "66bdc05e3e7e0a2069cbf59a8dad1fdf7a52caef",
"extension": "c",
"filename": "_fwrite.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7389536,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1145,
"license": "ISC",
"license_type": "permissive",
"path": "/gcc/stdio/_fwrite.c",
"provenance": "stackv2-0092.json.gz:47940",
"repo_name": "razzlefratz/MotleyTools",
"revision_date": "2015-04-17T17:56:20",
"revision_id": "3c69c574351ce6f4b7e687c13278d4b6cbb200f3",
"snapshot_id": "5e44f1315baa1be6fe5221916ccc834a96b59ca6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/razzlefratz/MotleyTools/3c69c574351ce6f4b7e687c13278d4b6cbb200f3/gcc/stdio/_fwrite.c",
"visit_date": "2020-05-19T05:01:58.992424"
} | stackv2 | /*====================================================================*
*
* size_t _fwrite(void const *buffer, size_t itemsize, size_t count, FILE *fp);
*
* _stdio.h
*
* copy the specified number of items, each of the specified size, to
* the buffer assigned to a file pointer; return the number of items
* actually copied or 0 on end-of-file or i/o error;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#include "_stdio.h"
size_t _fwrite (void const *buffer, size_t itemsize, size_t count, FILE * fp)
{
register char *buf = (char *) (buffer);
register size_t index;
if ((fp != NULL) && ((fp->_flag & (_IOWRITE | _IOERR | _IOEOF)) == _IOWRITE))
{
count *= itemsize;
for (index = 0; index < count; index++)
{
if ((fp->_cnt <= 0) && (_fflush (fp) == EOF))
{
break;
}
fp->_cnt--;
*fp->_ptr++ = buf [index];
}
return (((fp->_flag & (_IOERR)) != 0)? 0: index / itemsize);
}
else
{
return (0);
}
}
| 2.8125 | 3 |
2024-11-18T20:55:46.163170+00:00 | 2022-08-22T20:21:02 | 77dc8f27594a54a796da7c22d9a301a15b171f98 | {
"blob_id": "77dc8f27594a54a796da7c22d9a301a15b171f98",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-22T21:10:43",
"content_id": "3d6e4d6d8972203a1940030e10094679ad5e66d5",
"detected_licenses": [
"MIT"
],
"directory_id": "1d3d12dbc0b670c74e8eabe50dc9149580a7dc2c",
"extension": "c",
"filename": "fa_fft.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 137582286,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6769,
"license": "MIT",
"license_type": "permissive",
"path": "/src/libfalabaac/fa_fft.c",
"provenance": "stackv2-0092.json.gz:48068",
"repo_name": "Sound-Linux-More/falabaac",
"revision_date": "2022-08-22T20:21:02",
"revision_id": "c9f6723e2e8272e1726d25ca07d7696fdbb14c21",
"snapshot_id": "f87e099777fc7e40caee8e232e0d2454e08d61e1",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/Sound-Linux-More/falabaac/c9f6723e2e8272e1726d25ca07d7696fdbb14c21/src/libfalabaac/fa_fft.c",
"visit_date": "2022-09-11T15:57:49.602542"
} | stackv2 | /*
falab - free algorithm lab
Copyright (C) 2012 luolongzhi 罗龙智 (Chengdu, China)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
filename: fa_fft.c
version : 2.1.0.229
time : 2019/07/14
author : luolongzhi ( falab2012@gmail.com luolongzhi@gmail.com )
code URL: https://github.com/Sound-Linux-More/falabaac
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fa_fastmath.h"
#include "fa_fft.h"
typedef struct _fa_fft_ctx_t
{
int base;
int length;
int *bit_rvs;
float *fft_work;
float *cos_ang;
float *sin_ang;
} fa_fft_ctx_t;
static int bit_reverse(int *buf_rvs, int size)
{
int r = 0; // counter
int s = 0; // bit-reversal of r/2
int N2 = size << 1; // N<<1 == N*2
int i = 0;
do
{
buf_rvs[i++] = s;
r += 2;
s ^= size - (size / (r&-r));
}
while (r < N2);
return s;
}
/*
decimation-in-freq radix-2 in-place butterfly
data: (array of float, order below)
re(0),im(0),re(1),im(1),...,re(size-1),im(size-1)
means size=array_length/2
useage:
intput in normal order
output in bit-reversed order
*/
static void dif_butterfly(float *data, long size, float *cos_ang, float *sin_ang)
{
long angle, astep, dl;
float xr, yr, xi, yi, wr, wi, dr, di;
float *l1, *l2, *end, *ol2;
astep = 1;
end = data + size + size;
for (dl = size; dl > 1; dl >>= 1, astep += astep)
{
l1 = data;
l2 = data + dl;
for (; l2 < end; l1 = l2, l2 = l2 + dl)
{
ol2 = l2;
for (angle = 0; l1 < ol2; l1 += 2, l2 += 2)
{
wr = cos_ang[angle];
wi = -sin_ang[angle];
xr = *l1 + *l2;
xi = *(l1+1) + *(l2+1);
dr = *l1 - *l2;
di = *(l1+1) - *(l2+1);
yr = dr*wr - di*wi;
yi = dr*wi + di*wr;
*(l1) = xr;
*(l1+1) = xi;
*(l2) = yr;
*(l2+1) = yi;
angle += astep;
}
}
}
}
/*
decimation-in-time radix-2 in-place inverse butterfly
data: (array of float, below order)
re(0),im(0),re(1),im(1),...,re(size-1),im(size-1)
means size=array_length/2
useage:
intput in bit-reversed order
output in normal order
*/
static void inverse_dit_butterfly(float *data, long size, float *cos_ang, float *sin_ang)
{
long angle,astep,dl;
float xr, yr, xi, yi, wr, wi, dr, di;
float *l1, *l2, *end, *ol2;
astep = size >> 1;
end = data + size + size;
for (dl = 2; astep > 0; dl += dl, astep >>= 1)
{
l1 = data;
l2 = data + dl;
for (; l2 < end; l1 = l2, l2 = l2 + dl)
{
ol2 = l2;
for (angle = 0; l1 < ol2; l1 += 2, l2 += 2)
{
wr = cos_ang[angle];
wi = sin_ang[angle];
xr = *l1;
xi = *(l1+1);
yr = *l2;
yi = *(l2+1);
dr = yr*wr - yi*wi;
di = yr*wi + yi*wr;
*(l1) = xr + dr;
*(l1+1) = xi + di;
*(l2) = xr - dr;
*(l2+1) = xi - di;
angle += astep;
}
}
}
}
/*
in-place Radix-2 FFT for complex values
data: (array of float, below order)
re(0),im(0),re(1),im(1),...,re(size-1),im(size-1)
means size=array_length/2 !!
output is in similar order, normalized by array length
*/
void fa_fft(uintptr_t handle, float *data)
{
int i, bit;
fa_fft_ctx_t *f = (fa_fft_ctx_t *)handle;
float *temp = f->fft_work;
int size = f->length;
int *bit_rvs = f->bit_rvs;
float *cos_ang = f->cos_ang;
float *sin_ang = f->sin_ang;
dif_butterfly(data, size, cos_ang, sin_ang);
for (i = 0 ; i < size ; i++)
{
bit = bit_rvs[i];
temp[i+i] = data[bit+bit];
temp[i+i+1] = data[bit+bit+1];
}
for (i = 0; i < size ; i++)
{
data[i+i] = temp[i+i];
data[i+i+1] = temp[i+i+1];
}
}
/*
in-place Radix-2 inverse FFT for complex values
data: (array of float, below order)
re(0),im(0),re(1),im(1),...,re(size-1),im(size-1)
means size=array_length/2 !!
output is in similar order, NOT normalized by array length
*/
void fa_ifft(uintptr_t handle, float* data)
{
int i, bit;
fa_fft_ctx_t *f = (fa_fft_ctx_t *)handle;
float *temp = f->fft_work;
int size = f->length;
int *bit_rvs = f->bit_rvs;
float *cos_ang = f->cos_ang;
float *sin_ang = f->sin_ang;
for (i = 0 ; i < size ; i++)
{
bit = bit_rvs[i];
temp[i+i] = data[bit+bit];
temp[i+i+1] = data[bit+bit+1];
}
for (i = 0; i < size ; i++)
{
data[i+i] = temp[i+i]/size;
data[i+i+1] = temp[i+i+1]/size;
}
inverse_dit_butterfly(data, size, cos_ang, sin_ang);
}
uintptr_t fa_fft_init(int size)
{
int i;
float ang;
fa_fft_ctx_t *f = NULL;
f = (fa_fft_ctx_t *)malloc(sizeof(fa_fft_ctx_t));
memset(f, 0, sizeof(fa_fft_ctx_t));
f->length = size;
// f->base = (int)(log(size)/log(2));
f->base = (int)(FA_LOG2(size));
if ((1<<f->base) < size)
f->base += 1;
f->bit_rvs = (int *)malloc(sizeof(int)*size);
f->fft_work = (float *)malloc(sizeof(float)*size*2);
f->cos_ang = (float *)malloc(sizeof(float)*size);
f->sin_ang = (float *)malloc(sizeof(float)*size);
bit_reverse(f->bit_rvs,size);
for (i = 0 ; i < size ; i++)
{
ang = (float)(2*M_PI*i)/size;
f->cos_ang[i] = (float)FA_COS(ang);
f->sin_ang[i] = (float)FA_SIN(ang);
}
return (uintptr_t)f;
}
void fa_fft_uninit(uintptr_t handle)
{
fa_fft_ctx_t *f = (fa_fft_ctx_t *)handle;
free(f->bit_rvs);
free(f->fft_work);
free(f->cos_ang);
free(f->sin_ang);
f->bit_rvs = NULL;
f->fft_work = NULL;
f->cos_ang = NULL;
f->sin_ang = NULL;
free(f);
f = NULL;
}
| 2.734375 | 3 |
2024-11-18T20:55:46.540502+00:00 | 2018-03-07T04:10:01 | e4a3145dd758a217e28fd9430149d285bcd56682 | {
"blob_id": "e4a3145dd758a217e28fd9430149d285bcd56682",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-07T04:10:01",
"content_id": "85a8b392491c6bae147e1e8b71f6095117ba61d6",
"detected_licenses": [
"MIT"
],
"directory_id": "116061a9665d16d60b97d8ef8db9ce2039610593",
"extension": "h",
"filename": "config_macros.h",
"fork_events_count": 2,
"gha_created_at": "2017-01-22T17:35:57",
"gha_event_created_at": "2018-03-06T13:43:06",
"gha_language": "C",
"gha_license_id": null,
"github_id": 79733397,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3600,
"license": "MIT",
"license_type": "permissive",
"path": "/util/config_macros.h",
"provenance": "stackv2-0092.json.gz:48327",
"repo_name": "FirstEast/radiance",
"revision_date": "2018-03-07T04:10:01",
"revision_id": "1a239c5b429ad98f45701d2911a6ca9facc7905f",
"snapshot_id": "09f61df73c51cb3def3a2c073d83b4fafcab7bdf",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/FirstEast/radiance/1a239c5b429ad98f45701d2911a6ca9facc7905f/util/config_macros.h",
"visit_date": "2021-01-11T11:46:46.246486"
} | stackv2 | #ifndef __CORE_CONFIG_MACROS_H__
#define __CORE_CONFIG_MACROS_H__
#define N_MAX_LIST_ELEMENTS 32
// LIST_NAME(slot) --> slots
// LIST_N_NAME(slot) --> n_slots
// LIST_PREFIX(slot) --> "slot_"
#define LIST_NAME(name) name ## s
#define LIST_N_NAME(name) n_ ## name ## s
#define LIST_PREFIX(name) STRINGIFY(name) "_"
// Each type FOO must define FOO_PARSE, FOO_FORMAT, FOO_FREE, FOO_PREP macros
// FOO valid C type, e.g. `int`, `struct foo`, `char *`
// FOO FOO_PARSE(char * s) Parse the input from a string. `s` can be modified after this call, so strdup if nessassary
// FOO_FORMAT(FOO f) Give a suitable representation to printf. `printf(FOO_FORMAT(f));` should be valid. See examples.
// void FOO_FREE(FOO f) Free/destroy the object f; or nop with `(void)(f)`
// FOO FOO_PREP(F) Macro to convert a set of C tokens `F` into a FOO object. Only used at compile/start-up time.
// Numeric types
#define INT int
#define SINT16 Sint16
#define UINT16 Uint16
#define FLOAT float
#define INT_PARSE(x) atoi(x)
#define SINT16_PARSE(x) atoi(x)
#define UINT16_PARSE(x) atoi(x)
#define FLOAT_PARSE(x) atof(x)
#define INT_FORMAT(x) "%d", x
#define SINT16_FORMAT(x) "%d", x
#define UINT16_FORMAT(x) "%d", x
#define FLOAT_FORMAT(x) "%f", x
#define INT_FREE(x) (void)(x)
#define SINT16_FREE(x) (void)(x)
#define UINT16_FREE(x) (void)(x)
#define FLOAT_FREE(x) (void)(x)
#define INT_PREP(x) x
#define SINT16_PREP(x) x
#define UINT16_PREP(x) x
#define FLOAT_PREP(x) x
// String type
#define STRING char *
#define STRING_PARSE(x) strdup(x)
#define STRING_PREP(x) strdup(x)
#define STRING_FORMAT(x) "%s", x
#define STRING_FREE(x) free(x)
#define CONCAT(x, y) CONCAT2(x, y)
#define CONCAT2(x, y) x ## y
#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x
#define EXPAND(...) __VA_ARGS__
/* ISEMPTY macro from https://gustedt.wordpress.com/2010/06/08/detect-empty-macro-arguments/ */
#define _ARG16(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, ...) _15
#define HAS_COMMA(...) _ARG16(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)
#define _TRIGGER_PARENTHESIS_(...) ,
#define ISEMPTY(...) \
_ISEMPTY( \
/* test if there is just one argument, eventually an empty \
one */ \
HAS_COMMA(__VA_ARGS__), \
/* test if _TRIGGER_PARENTHESIS_ together with the argument \
adds a comma */ \
HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__), \
/* test if the argument together with a parenthesis \
adds a comma */ \
HAS_COMMA(__VA_ARGS__ (/*empty*/)), \
/* test if placing it between _TRIGGER_PARENTHESIS_ and the \
parenthesis adds a comma */ \
HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__ (/*empty*/)) \
)
#define PASTE5(_0, _1, _2, _3, _4) _0 ## _1 ## _2 ## _3 ## _4
#define _ISEMPTY(_0, _1, _2, _3) HAS_COMMA(PASTE5(_IS_EMPTY_CASE_, _0, _1, _2, _3))
#define _IS_EMPTY_CASE_0001 ,
/* End of ISEMPTY macro code */
#define PREFIX(prefix, suffix) CONCAT(CONCAT(PREFIX_, ISEMPTY(prefix))(prefix), suffix)
#define PREFIX_1(prefix) prefix
#define PREFIX_0(prefix) CONCAT(prefix, _)
#endif // End of include guard
| 2.1875 | 2 |
2024-11-18T20:55:46.657237+00:00 | 2023-03-31T07:55:02 | 1deb126231d8321e271d7c970e5aa7b106bc5f10 | {
"blob_id": "1deb126231d8321e271d7c970e5aa7b106bc5f10",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-31T14:23:11",
"content_id": "7c98c6a63d3f2385a56996ac126a01469395e9df",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "997a173e1a758750ca90e5f15e5f826344916c74",
"extension": "c",
"filename": "errorstream.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-10T09:30:49",
"gha_event_created_at": "2020-02-10T09:30:50",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 239473744,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2241,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/errorstream.c",
"provenance": "stackv2-0092.json.gz:48455",
"repo_name": "exg/async",
"revision_date": "2023-03-31T07:55:02",
"revision_id": "63583e1fd83f872d19195d28948f510892984e1d",
"snapshot_id": "9c0cc2ec53b669d2e0332494d8859d2f3544c0dc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/exg/async/63583e1fd83f872d19195d28948f510892984e1d/src/errorstream.c",
"visit_date": "2023-04-26T19:23:21.896327"
} | stackv2 | #include "errorstream.h"
#include <errno.h>
#include <unistd.h>
#include <fsdyn/fsalloc.h>
#include <fstrace.h>
#include "async_version.h"
struct errorstream {
async_t *async;
uint64_t uid;
int err;
action_1 callback;
};
FSTRACE_DECL(ASYNC_ERRORSTREAM_CREATE, "UID=%64u PTR=%p ASYNC=%p ERRNO=%E");
errorstream_t *make_errorstream(async_t *async, int err)
{
errorstream_t *estr = fsalloc(sizeof *estr);
estr->async = async;
estr->uid = fstrace_get_unique_id();
FSTRACE(ASYNC_ERRORSTREAM_CREATE, estr->uid, estr, async, err);
estr->err = err;
estr->callback = NULL_ACTION_1;
return estr;
}
FSTRACE_DECL(ASYNC_ERRORSTREAM_READ, "UID=%64u WANT=%z GOT=-1 ERRNO=%e");
ssize_t errorstream_read(errorstream_t *estr, void *buf, size_t count)
{
errno = estr->err;
FSTRACE(ASYNC_ERRORSTREAM_READ, estr->uid, count);
return -1;
}
static ssize_t _read(void *obj, void *buf, size_t count)
{
return errorstream_read(obj, buf, count);
}
FSTRACE_DECL(ASYNC_ERRORSTREAM_CLOSE, "UID=%64u");
void errorstream_close(errorstream_t *estr)
{
FSTRACE(ASYNC_ERRORSTREAM_CLOSE, estr->uid);
async_wound(estr->async, estr);
estr->async = NULL;
}
static void _close(void *obj)
{
errorstream_close(obj);
}
FSTRACE_DECL(ASYNC_ERRORSTREAM_REGISTER, "UID=%64u OBJ=%p ACT=%p");
void errorstream_register_callback(errorstream_t *estr, action_1 action)
{
FSTRACE(ASYNC_ERRORSTREAM_REGISTER, estr->uid, action.obj, action.act);
estr->callback = action;
}
static void _register_callback(void *obj, action_1 action)
{
errorstream_register_callback(obj, action);
}
FSTRACE_DECL(ASYNC_ERRORSTREAM_UNREGISTER, "UID=%64u");
void errorstream_unregister_callback(errorstream_t *estr)
{
FSTRACE(ASYNC_ERRORSTREAM_UNREGISTER, estr->uid);
estr->callback = NULL_ACTION_1;
}
static void _unregister_callback(void *obj)
{
errorstream_unregister_callback(obj);
}
static const struct bytestream_1_vt errorstream_vt = {
.read = _read,
.close = _close,
.register_callback = _register_callback,
.unregister_callback = _unregister_callback
};
bytestream_1 errorstream_as_bytestream_1(errorstream_t *estr)
{
return (bytestream_1) { estr, &errorstream_vt };
}
| 2.1875 | 2 |
2024-11-18T20:55:46.789334+00:00 | 2020-10-28T09:08:34 | 16733b3a58a5f446b2c232d894b5eb94a79e0b44 | {
"blob_id": "16733b3a58a5f446b2c232d894b5eb94a79e0b44",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-28T09:08:34",
"content_id": "276f052564f0e0fe81831d3b66166c292e87308d",
"detected_licenses": [
"MIT"
],
"directory_id": "d55dfd316b17c597dc69a0a873092b6db8c2776d",
"extension": "c",
"filename": "exercise09.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 305801564,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 450,
"license": "MIT",
"license_type": "permissive",
"path": "/MediumLevelExercises/Exercise09/exercise09.c",
"provenance": "stackv2-0092.json.gz:48711",
"repo_name": "ZaroDev/ProgrammingExercises",
"revision_date": "2020-10-28T09:08:34",
"revision_id": "abb94d1fbda5d1f4e53e6f108bed07df2519f6ad",
"snapshot_id": "40f71c1ace89437a9df84c21bc6c3ab37fc853e8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ZaroDev/ProgrammingExercises/abb94d1fbda5d1f4e53e6f108bed07df2519f6ad/MediumLevelExercises/Exercise09/exercise09.c",
"visit_date": "2023-01-01T06:27:52.433050"
} | stackv2 | //09. Write a program that asks for a sequence of numbers to the user and show the sum of all of them. Process stops when 0 is introduced.
#include <stdio.h>
int main()
{
int num = 0;
int sum = 0;
int counter = 1;
printf("Write 0 when you want to stop the process\n");
while (counter > 0)
{
printf("Introduce your number: ");
scanf_s("%i", &num);
sum += num;
counter = num;
}
printf("Sum = %i", sum);
getchar();
return 0;
} | 4.125 | 4 |
2024-11-18T20:55:47.174521+00:00 | 2021-02-24T16:21:07 | c70d7d064638b5c0e4d73887f3c69c720613f9ff | {
"blob_id": "c70d7d064638b5c0e4d73887f3c69c720613f9ff",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-24T16:21:07",
"content_id": "e37e14de1dd760e6f06dbaf59db6530893bfd507",
"detected_licenses": [
"MIT"
],
"directory_id": "90e6a97bd351b20994766cfb4f580d514edd2d8a",
"extension": "c",
"filename": "house.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 341025154,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 922,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/Basic-RTS/PART_1/source/house.c",
"provenance": "stackv2-0092.json.gz:49738",
"repo_name": "hugolardosa/learning-NDS-Dev",
"revision_date": "2021-02-24T16:21:07",
"revision_id": "2979962b61378c924e666d8e4e44012970de7ba1",
"snapshot_id": "06836c9759e218b7e222ff38a7989c8a2019afd3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hugolardosa/learning-NDS-Dev/2979962b61378c924e666d8e4e44012970de7ba1/examples/Basic-RTS/PART_1/source/house.c",
"visit_date": "2023-03-09T20:44:28.386747"
} | stackv2 | #include <nds.h>
#include "house.h"
extern const unsigned int spritesheetTiles[2880];
House initHouse() {
House house = {SCREEN_WIDTH / 2 - 8, SCREEN_HEIGHT / 2 - 8};
house.gfx = oamAllocateGfx(&oamSub, SpriteSize_16x16, SpriteColorFormat_256Color);
house.gfx_frame = (u8*)spritesheetTiles;
return house;
}
void generateHouse(House * house) {
u8* offset = house->gfx_frame + 4 * 16*16;
dmaCopy(offset, house->gfx, 16*16);
oamSet(&oamSub,
1, // oam entry id
house->x, house->y, // x, y location
0, 15, // priority, palette
SpriteSize_16x16,
SpriteColorFormat_256Color,
house->gfx, // the oam gfx
-1, false, false, false, false, false);
}
bool hideHouseMenu(touchPosition touch, House * house) {
if (touch.px > house->x && touch.px < house->x + 16 // stylus inside x pos of house
&& touch.py > house->y && touch.py < house->y + 16) { // inside y pos of house
return false;
}
return true;
}
| 2.21875 | 2 |
2024-11-18T20:55:47.235268+00:00 | 2016-02-18T21:12:13 | 30bf13b610b60b694efea00b57364dcba1ec0fde | {
"blob_id": "30bf13b610b60b694efea00b57364dcba1ec0fde",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-18T21:12:13",
"content_id": "8df2a04c99805bcbdfda19422ea8028dfb3fe011",
"detected_licenses": [
"MIT"
],
"directory_id": "f3661f205bf544e34e5a810b1bee0cffc053b00c",
"extension": "c",
"filename": "shell_core.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 52038959,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9650,
"license": "MIT",
"license_type": "permissive",
"path": "/src/shell_core.c",
"provenance": "stackv2-0092.json.gz:49867",
"repo_name": "utpalsolanki/shell",
"revision_date": "2016-02-18T21:12:13",
"revision_id": "99d3a8c90d1daf3c0468b5ba6bcc540ce8c1dc51",
"snapshot_id": "d8a16eec2904e8a250f9a7960f278b789e423e29",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/utpalsolanki/shell/99d3a8c90d1daf3c0468b5ba6bcc540ce8c1dc51/src/shell_core.c",
"visit_date": "2021-01-10T02:09:24.782217"
} | stackv2 | #include "shell.h"
/* ---------------------------------------------------------------------
* funct : Init RC file check
* args : RC file name, other scratchpad variable
* ret : None.
*
* Detail: This funciton open RC file name given in argument.
* Go through it line by line. Execute commands.
* Starting character '#' is for line comment
*
* --------------------------------------------------------------------*/
void checkRcFile(char *fileName, char *cmdOrig, char *readString, char *command, char *args, char *cmd[])
{
//Scratchpad initialize
FILE *rcFile;
int read,l;
char *line=malloc(COMMAND_INPUT_CAPACITY);
rcFile = fopen(fileName,"r+");
//If file not exist!
if(rcFile <= 1)
{
printf("No RC file to read\n");
return;
}
printf("Executing %s\n",fileName);
//Go through line by line
while ((read = getline(&line, &l, rcFile)) != -1)
{
if(line[0] != '#' && strlen(line)>1)
{
printf("%s", line);
sprintf(readString,"%s\n",line);
//We have command line ready to be parsed
intermediatePipingCheck(cmdOrig,readString,command, args, cmd);
}
}
fclose(rcFile);
}
/* ---------------------------------------------------------------------
* funct : A core function for command interpreter
* args : User raw input string, Scratchpad variables
* ret : None
*
* Detail: This function implement core functionality of shell.
* It go over word by word and execute command as required.
* Create child process to execute command. Wait for child
* to finish or go ahead if non-waiting is request.
*
* --------------------------------------------------------------------*/
int coreParser(char *cmdOrig, char *readString, char *command, char *args, char *cmd[])
{
//Copy user input for backup
memcpy(cmdOrig,readString,COMMAND_INPUT_CAPACITY);
//Convert user string to separate command words.
enum inputType commandParseState = parseInput(readString, &command, &args, cmd);
//If user didn't write anything.
if( commandParseState == NO_COMMAND)
{
//This is to recover newline issue while scripting is on.
//When user hit enter, it should not reflect in log.
if(isScriptRunning == TRUE)
{
printf("%s\n",readString);
//Go up by one line.
printf("\033[F");
}
}
//If we have some user input
if(commandParseState > NO_COMMAND)
{
//Alias command handler
if(strstr(cmd[0],"alias") != NULL)
{
pushAlias(cmdOrig);
pushHistory(cmdOrig);
return 0;
}
//Check If we have this command in alias lists.
if(isCommandAliased(cmdOrig,readString,cmd)==TRUE)
{
memcpy(cmdOrig,readString,COMMAND_INPUT_CAPACITY);
printf("%s\nAliased to %s\n",cmdOrig,readString);
memset(cmd,0,sizeof(cmd));
commandParseState = parseInput(readString, &command, &args, cmd);
}
//Chech for special command '!!' to role over last command
if(strstr(cmd[0],"!!") != NULL && strlen(readString) == strlen("!!"))
{
struct cmdContainer_t *temp;
temp = &cmdContainer;
while(temp->next != NULL){temp = temp->next;}
//If had no history at all.
if(temp->next == NULL && temp->prev == NULL)
{
printf("No history available\n");
return 0;
}
//Fetching last command
memcpy(readString, temp->cmdString,COMMAND_INPUT_CAPACITY);
memcpy(cmdOrig,readString,COMMAND_INPUT_CAPACITY);
//Give it back to parser
printf("%s\n",readString);
commandParseState = parseInput(readString, &command, &args, cmd);
}
//Check for special command '!#' to role over particular history
if(cmd[0][0] == '!' && cmd[0][1] != '!' && strlen(cmd[0]) > 1)
{
int reqNumber = atoi(&cmd[0][1]);
struct cmdContainer_t *temp;
int cmdFound=FALSE;
//Number validation
if(reqNumber <= 0)
{
printf("Invalid number of history command requested\n");
return 0;
}
//Going through list
temp = &cmdContainer;
while(temp->next != NULL)
{
temp = temp->next;
if(temp->cmdNo + 1 == reqNumber)
{
cmdFound = TRUE;
memcpy(readString, temp->cmdString,COMMAND_INPUT_CAPACITY);
memcpy(cmdOrig,readString,COMMAND_INPUT_CAPACITY);
printf("%s\n",readString);
commandParseState = parseInput(readString, &command, &args, cmd);
break;
}
}
//If given number of history not present
if(cmdFound == FALSE)
{
printf("Number for history command not valid\n");
return 0;
}
}
//Exit command handler
if(strstr(cmd[0],"exit") != NULL && (strlen(cmd[0]) == strlen("exit")))
{
pushHistory(cmdOrig);
exit(0);
}
//History command handler
if(strstr(cmd[0],"history") != NULL && (strlen(cmd[0]) == strlen("history")))
{
commandHistory(cmd);
pushHistory(cmdOrig);
return 0;
}
//Check for script start stop request
if(strstr(cmd[0],"script") != NULL && (strlen(cmd[0]) == strlen("script")))
{
if(isScriptRunning == FALSE)
{
startLogging(cmd);
isScriptRunning = TRUE;
}
else
{
printf("scripting is already enabled, use endscript to stop.\n");
}
pushHistory(cmdOrig);
return 0;
}
//Chech for script start stop request
if(strstr(cmd[0],"endscript") != NULL && (strlen(cmd[0]) == strlen("endscript")))
{
printf("script end\n");
if(isScriptRunning == TRUE)
{
stopLogging(cmd);
isScriptRunning = FALSE;
}
else
{
printf("scripting is already off\n");
}
pushHistory(cmdOrig);
return 0;
}
//Check for 'set' type of request
if(strstr(cmd[0],"set") != NULL && (strlen(cmd[0]) == strlen("set")))
{
setHandler(cmdOrig,readString,cmd);
return 0;
}
//Check for additional command 'showpath'.
if(strstr(cmd[0],"showpath") != NULL && (strlen(cmd[0]) == strlen("showpath")))
{
printEnv();
return 0;
}
}
//-----------------------------------------------------------------//
//---------Start Executing Command, Based on Args------------------//
switch(commandParseState)
{
case INPUT_ERROR:
printf("Input Error, Could not understand %s \n",readString);
break;
case NO_COMMAND:
break;
case ONLY_COMMAND:
processCommand(cmdOrig, readString,cmd,TRUE);
break;
case ARGS_AND_COMMAND:
processCommand(cmdOrig, readString,cmd,TRUE);
break;
case ARGS_AND_COMMAND_DONT_WAIT:
processCommand(cmdOrig, readString,cmd,FALSE);
break;
default:
printf("Parsing Error\n");
break;
}
return 0;
}
/* ---------------------------------------------------------------------
* funct : Command string parser
* args : User input string, Scratchpad memory.
* ret : ENUM state based on argument if any?
*
* Detail: This funciton does string parsing of user input.
* Create different states based on arguments.
*
* --------------------------------------------------------------------*/
enum inputType parseInput(const char *inString, char **comm, char **args, char *cmd[])
{
int i = 0;
char *parser = inString;
//Null input validation
if(strlen(inString)==0)
return NO_COMMAND;
//Max input validation
if(strlen(inString)>MAX_COMMAND_STRING)
{
printf("User can not enter command worth more than %d bytes long, please try again\n",MAX_COMMAND_STRING);
return NO_COMMAND;
}
//Split each word in a line and store it in cmd.
while(1)
{
cmd[i++] = parser;
parser = strstr(parser," ");
if(parser == NULL)
{
break;
}
else
{
*parser = '\0';
parser++;
}
}
//If we had just one command
if(i==1)
return ONLY_COMMAND;
//If we had command with arguments
if(i>1)
{
if(cmd[i-1][0]=='&')
{
cmd[i-1] = NULL;
return ARGS_AND_COMMAND_DONT_WAIT;
}
else
return ARGS_AND_COMMAND;
}
return INPUT_ERROR;
}
/* ---------------------------------------------------------------------
* funct : Execute command
* args : Command container, scratchpad memory
* ret : None.
*
* Detail: This function execute actual command binary by forking
* a child process. It wait for child to get done. Or else
* dont wait if last argument is character '&'.
*
* --------------------------------------------------------------------*/
void processCommand(char *cmdOrig, char *cmdString, char *cmd[], int isWait)
{
//Save this command to history
pushHistory(cmdOrig);
//Create a child
pid_t p = fork();
//---- From now, we are two process---
//Check if we are child ?
if(p == 0)
{
//Try executing commmand in default path settings,
//If command found, new binary will take over this process.
execvp(cmd[0],cmd);
//We are here because last call failed.
struct envPath_t *envTemp;
envTemp = &envPath;
//Check over for binary in different PATH variables
do
{
char cmd_path[COMMAND_INPUT_CAPACITY] = {0};
//Automate /bin or /bin/ input.
if(envTemp->path[strlen(envTemp->path)-1] == '/')
{
sprintf(cmd_path,"%s%s",envTemp->path,cmd[0]);
}
else
{
sprintf(cmd_path,"%s/%s",envTemp->path,cmd[0]);
}
//Verbose search path
sprintf(printBuf,"Trying at :%s\n",cmd_path);verPrint(printBuf);memset(printBuf,0,sizeof(printBuf));//VER
//Try command at new path
int i = execvp(cmd_path,cmd);
envTemp = envTemp->next;
}while(envTemp != NULL);
//We are here such that, there is no command in path variabls also.
printf("No such command: %s \n",cmd[0]);
exit(0);
}
//What parent process should while child is on work ?
else
{
//Wait for command to get over
if(isWait == TRUE)
{
int status;
while(waitpid(p, &status, 0) == -1);
}
else
{
return;
}
}
}
| 2.546875 | 3 |
2024-11-18T20:55:48.807207+00:00 | 2019-10-28T11:46:55 | 34cd9b6a0234ec2f91e2371295bd7dce004f5e47 | {
"blob_id": "34cd9b6a0234ec2f91e2371295bd7dce004f5e47",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-28T11:46:55",
"content_id": "f34c6062ee1a37fbd18dfeda1960c47e5424df31",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "73185944d6e7ec558dd7da69d3f5edefa64c1c96",
"extension": "c",
"filename": "lab9.c",
"fork_events_count": 0,
"gha_created_at": "2019-10-04T09:43:01",
"gha_event_created_at": "2019-10-28T11:46:57",
"gha_language": "Python",
"gha_license_id": "BSD-2-Clause",
"github_id": 212782128,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 720,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/books/CProgramming/cp5_array/lab9.c",
"provenance": "stackv2-0092.json.gz:50124",
"repo_name": "Bingwen-Hu/hackaway",
"revision_date": "2019-10-28T11:46:55",
"revision_id": "69727d76fd652390d9660e9ea4354ba5cc76dd5c",
"snapshot_id": "b5a233b6a1a4865389f0be04bcb63db88809e4c7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Bingwen-Hu/hackaway/69727d76fd652390d9660e9ea4354ba5cc76dd5c/books/CProgramming/cp5_array/lab9.c",
"visit_date": "2020-08-06T01:17:39.135931"
} | stackv2 | /* read an array of integers and print even and odd separately */
#include <stdio.h>
void printByParity(int lst[], int len);
int main(){
int lst[] = {2, 3, 6, 8, 11, 18, 21, 25};
int len = 8;
printByParity(lst, len);
return 0;
}
void printByParity(int lst[], int len){
int even[len], odd[len], nEven, nOdd;
nEven = nOdd = 0;
for (int i=0; i<len; i++){
if (lst[i] % 2 == 0){
even[nEven] = lst[i];
nEven++;
} else {
odd[nOdd] = lst[i];
nOdd++;
}
}
printf("Even numbers: ");
for (int i=0; i<nEven; i++){
printf("\t%d", even[i]);
}
puts("");
printf("Odd numbers: ");
for (int i=0; i<nOdd; i++){
printf("\t%d", odd[i]);
}
puts("");
}
| 3.96875 | 4 |
2024-11-18T20:55:49.330890+00:00 | 2020-01-24T19:01:15 | db85a2d82ec7c4eeb1c9033b2ddeaf7948b1b6df | {
"blob_id": "db85a2d82ec7c4eeb1c9033b2ddeaf7948b1b6df",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-24T19:01:15",
"content_id": "1c31aaffee084ad15a8907c3b0d8832e0c26d261",
"detected_licenses": [
"MIT"
],
"directory_id": "5d8decacd2defa666d4e1cab293e62e8ec24f7eb",
"extension": "c",
"filename": "timer.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": 388,
"license": "MIT",
"license_type": "permissive",
"path": "/MeOSLDR/timer.c",
"provenance": "stackv2-0092.json.gz:50254",
"repo_name": "michalismeng/Me-Operating-System",
"revision_date": "2020-01-24T19:01:15",
"revision_id": "e00e3963d843b04b578ee2c44f6b0773c1df5b68",
"snapshot_id": "6a7bc6f4cf919bce3b6b13583a5c787697632e63",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/michalismeng/Me-Operating-System/e00e3963d843b04b578ee2c44f6b0773c1df5b68/MeOSLDR/timer.c",
"visit_date": "2023-04-27T11:29:58.552820"
} | stackv2 | #include "timer.h"
volatile uint32 ticks; // volatile is necessary for the sleep function, where compiler thinks millis is constant valued
void timer_callback(registers_t* regs)
{
ticks++;
}
uint32 millis()
{
if (frequency == 0)
PANIC("Zero freq");
return (1000 * ticks) / frequency;
}
void sleep(uint32 _time)
{
uint32 start = millis();
while (millis() < start + _time);
} | 2.515625 | 3 |
2024-11-18T20:55:49.402071+00:00 | 2019-10-03T10:06:15 | 45bb4b19c5caf35abd9f7fd0b0ddaa263dda252f | {
"blob_id": "45bb4b19c5caf35abd9f7fd0b0ddaa263dda252f",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-03T10:06:15",
"content_id": "435f4a39d0e5a64db52fbf984e10032458ba269d",
"detected_licenses": [
"MIT"
],
"directory_id": "bf032eadba72b6e4259e7e1b8ba6d029d6b6aaca",
"extension": "c",
"filename": "q13_2a.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 201007059,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1550,
"license": "MIT",
"license_type": "permissive",
"path": "/PartThree/col13/q13_2a.c",
"provenance": "stackv2-0092.json.gz:50383",
"repo_name": "sujimodern/Programming-Pearls",
"revision_date": "2019-10-03T10:06:15",
"revision_id": "354c6d4e3b7149b1b0fdac442610b7d3776f1131",
"snapshot_id": "ba6161a9c4544199f71727a234b1f6cc3da89921",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sujimodern/Programming-Pearls/354c6d4e3b7149b1b0fdac442610b7d3776f1131/PartThree/col13/q13_2a.c",
"visit_date": "2020-07-01T01:23:34.458149"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
enum { room_for_sentinel = 1 };
typedef struct intset intset;
struct intset {
int* _set;
size_t maxelements;
size_t maxval;
size_t size;
};
intset* intset_new(size_t maxelements, size_t maxval) {
intset* is = malloc(sizeof *is);
*is = (intset){
._set = malloc((maxelements + room_for_sentinel) * sizeof(int)),
.maxelements = maxelements,
.maxval = maxval,
.size = 0,
};
is->_set[0] = maxval;
return is;
}
void intset_delete(intset is[static 1]) {
free(is[0]._set);
free(is);
}
size_t intset_size(intset is[static 1]) {
return is[0].size;
}
void intset_insert(intset is[static 1], int t) {
int i, j;
for (i = 0; is[0]._set[i] < t; ++i);
if (is[0]._set[i] == t) { return; }
for (j = is[0].size; j >= i; --j) {
is[0]._set[j+1] = is[0]._set[j];
}
is[0]._set[i] = t;
is[0].size += 1;
}
void intset_report(intset is[static 1], size_t len, int v[len]) {
if (is[0].size > len) { return; }
for (size_t i = 0; i < is[0].size; ++i) {
v[i] = is[0]._set[i];
}
}
int main(int argc, char* argv[argc+1]) {
size_t maxelem = 5;
size_t maxval = 100;
int* v = malloc(maxelem * sizeof *v);
intset* is = intset_new(maxelem, maxval);
intset_insert(is, 7);
intset_insert(is, 3);
intset_insert(is, 15);
intset_insert(is, 15);
intset_insert(is, 15);
intset_insert(is, 8);
intset_report(is, maxelem, v);
for (size_t i = 0; i < intset_size(is); ++i) {
printf("%lu: %d\n", i, v[i]);
}
intset_delete(is);
return EXIT_SUCCESS;
}
| 3.21875 | 3 |
2024-11-18T20:55:49.597370+00:00 | 2019-07-20T13:18:15 | 3e079e4a72dce7896f61696caab2d51796de4083 | {
"blob_id": "3e079e4a72dce7896f61696caab2d51796de4083",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-20T13:18:15",
"content_id": "4526bd4da4c4799ded2f1acfe936c39aab70af3a",
"detected_licenses": [
"MIT"
],
"directory_id": "bfe11cd2fec59542ef756f729ac169c1887b6e7f",
"extension": "h",
"filename": "sha256.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 196792689,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2283,
"license": "MIT",
"license_type": "permissive",
"path": "/sha/sha256.h",
"provenance": "stackv2-0092.json.gz:50640",
"repo_name": "JayStatham/sha",
"revision_date": "2019-07-20T13:18:15",
"revision_id": "a1b13d9cd0ccb261b056614f9e5d462ee12cf7bf",
"snapshot_id": "a813553cf7ba2b5534d0ebf1d8df130fe13cc143",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JayStatham/sha/a1b13d9cd0ccb261b056614f9e5d462ee12cf7bf/sha/sha256.h",
"visit_date": "2020-06-19T16:58:10.127556"
} | stackv2 | /*
The MIT License (MIT)
Copyright © 2019 JStatham
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.
Date: 2019/7/14
*/
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
//types
typedef uint32_t sha256_word;
//SHA256 hash: Big-Endian
//digest = hash = h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7
struct sha256_hash
{
sha256_word hash[8];
};
// sha256_checksum
// caculate SHA256 checksum
// buf* buffer in bytes
// size unit of byte
bool sha256_checksum(void* buf, size_t size, struct sha256_hash* hash);
// sha256_file_checksum
// caculate SHA256 checksum from files
// filepath the path of file
bool sha256_file_checksum(const char* filepath, struct sha256_hash* hash);
// sha256_hash_to_str
// convert sha256_hash to string format
// hash the sha256_hash pointer
// str the string for output
// ssize the size of string
// fmt the formula of the string, ex:
// hex aabbccddeeff0011 (lowercase)
// h:e:x aa:bb:cc:dd:...
// h-e-x aa-bb-cc-dd:...
// HEX AABBCCDDEEFF0011 (uppercase)
// H:E:X AA:BB:CC:DD:EE:...
// H-E-X AA-BB-CC-DD-EE:...
bool sha256_hash_to_str(struct sha256_hash* hash, char* str, size_t ssize, const char *fmt);
#ifdef __cplusplus
}
#endif | 2.25 | 2 |
2024-11-18T20:55:50.194599+00:00 | 2017-06-21T17:18:32 | d7ea1fd167e47c0d777d5a2eec379664ade44b59 | {
"blob_id": "d7ea1fd167e47c0d777d5a2eec379664ade44b59",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-21T17:18:32",
"content_id": "3a8888589abe28c4433416fe772cf1f4682ebaed",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5e7f6461f1677a5fa449b6abd7f4a735f864e5dd",
"extension": "c",
"filename": "avl_test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 70306015,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3877,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib_tests/avl_test.c",
"provenance": "stackv2-0092.json.gz:51283",
"repo_name": "ozdevguy/C-General-Library",
"revision_date": "2017-06-21T17:18:32",
"revision_id": "8e2cc206604e5c4f13df6e9c3e388b5902d00d9a",
"snapshot_id": "d4a0b0d1cce55235212dbda4e55f705dd46ea6a3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ozdevguy/C-General-Library/8e2cc206604e5c4f13df6e9c3e388b5902d00d9a/lib_tests/avl_test.c",
"visit_date": "2020-05-23T08:10:11.300975"
} | stackv2 | #include "../lib/genlib.h"
void main(){
int test = 1;
_lib_init();
standard_library_context* ctx = _ctx_init();
binary_search_tree* avl = _avl_tree_new(ctx);
printf("Insert 60\n");
_avl_tree_insert_e(avl, 60, &test);
_binary_search_tree_lookup_e(avl, 60);
printf("\n\n");
printf("Insert 55\n");
_avl_tree_insert_e(avl, 55, &test);
_binary_search_tree_lookup_e(avl, 55);
printf("\n\n");
printf("Insert 50\n");
_avl_tree_insert_e(avl, 50, &test);
_binary_search_tree_lookup_e(avl, 50);
printf("\n\n");
printf("Insert 53\n");
_avl_tree_insert_e(avl, 53, &test);
_binary_search_tree_lookup_e(avl, 53);
printf("\n\n");
printf("Insert 47\n");
_avl_tree_insert_e(avl, 47, &test);
_binary_search_tree_lookup_e(avl, 47);
printf("\n\n");
printf("Insert 46\n");
_avl_tree_insert_e(avl, 46, &test);
_binary_search_tree_lookup_e(avl, 46);
printf("\n\n");
printf("Insert 70\n");
_avl_tree_insert_e(avl, 70, &test);
_binary_search_tree_lookup_e(avl, 70);
printf("\n\n");
printf("Insert 71\n");
_avl_tree_insert_e(avl, 71, &test);
_binary_search_tree_lookup_e(avl, 71);
printf("\n\n");
printf("Insert 72\n");
_avl_tree_insert_e(avl, 72, &test);
_binary_search_tree_lookup_e(avl, 72);
printf("\n\n");
printf("Insert 48\n");
_avl_tree_insert_e(avl, 48, &test);
_binary_search_tree_lookup_e(avl, 48);
printf("\n\n");
printf("Insert 45\n");
_avl_tree_insert_e(avl, 45, &test);
_binary_search_tree_lookup_e(avl, 45);
printf("\n\n");
printf("Insert 52\n");
_avl_tree_insert_e(avl, 52, &test);
_binary_search_tree_lookup_e(avl, 52);
printf("\n\n");
printf("Insert 67\n");
_avl_tree_insert_e(avl, 67, &test);
_binary_search_tree_lookup_e(avl, 67);
printf("\n\n");
printf("Insert 83\n");
_avl_tree_insert_e(avl, 83, &test);
_binary_search_tree_lookup_e(avl, 83);
printf("\n\n");
printf("Insert 75\n");
_avl_tree_insert_e(avl, 75, &test);
_binary_search_tree_lookup_e(avl, 75);
printf("\n\n");
printf("Insert 77\n");
_avl_tree_insert_e(avl, 77, &test);
_binary_search_tree_lookup_e(avl, 77);
printf("\n\n");
printf("Insert 74\n");
_avl_tree_insert_e(avl, 74, &test);
_binary_search_tree_lookup_e(avl, 74);
printf("\n\n");
printf("Insert 76\n");
_avl_tree_insert_e(avl, 76, &test);
_binary_search_tree_lookup_e(avl, 76);
printf("\n\n");
printf("Insert 73\n");
_avl_tree_insert_e(avl, 73, &test);
_binary_search_tree_lookup_e(avl, 73);
printf("\n\n");
printf("Insert 31\n");
_avl_tree_insert_e(avl, 31, &test);
_binary_search_tree_lookup_e(avl, 31);
printf("\n\n");
printf("Insert 38\n");
_avl_tree_insert_e(avl, 38, &test);
_binary_search_tree_lookup_e(avl, 38);
printf("\n\n");
printf("Insert 37\n");
_avl_tree_insert_e(avl, 37, &test);
_binary_search_tree_lookup_e(avl, 37);
printf("\n\n");
printf("Insert 42\n");
_avl_tree_insert_e(avl, 42, &test);
_binary_search_tree_lookup_e(avl, 42);
printf("\n\n");
printf("Insert 40\n");
_avl_tree_insert_e(avl, 40, &test);
_binary_search_tree_lookup_e(avl, 40);
printf("\n\n");
printf("Insert 25\n");
_avl_tree_insert_e(avl, 25, &test);
_binary_search_tree_lookup_e(avl, 25);
printf("\n\n");
printf("Insert 43\n");
_avl_tree_insert_e(avl, 43, &test);
_binary_search_tree_lookup_e(avl, 43);
printf("\n\n");
_binary_search_tree_lookup_e(avl, 48);
printf("Delete 45\n");
printf("===IGNORE====\n");
_avl_tree_remove(avl, 45);
printf("===IGNORE=====\n");
printf("\n\n\n");
_binary_search_tree_lookup_e(avl, 25);
printf("\n\n");
printf("===IGNORE====\n");
_avl_tree_remove(avl, 42);
printf("===IGNORE=====\n");
printf("\n\n\n");
_binary_search_tree_lookup_e(avl, 46);
printf("\n\n");
printf("===IGNORE====\n");
_avl_tree_remove(avl, 50);
printf("===IGNORE=====\n");
printf("\n\n\n");
_binary_search_tree_lookup_e(avl, 47);
printf("\n\n");
_avl_tree_delete(avl);
_ctx_delete(ctx);
} | 2.078125 | 2 |
2024-11-18T20:55:51.857778+00:00 | 2019-04-14T17:33:11 | dd2d8448615e08e02333a7e509e8d3ca25e90b4a | {
"blob_id": "dd2d8448615e08e02333a7e509e8d3ca25e90b4a",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-14T17:33:11",
"content_id": "5e01914a8091d7aef595236c3be876a02a6dfbbd",
"detected_licenses": [
"MIT"
],
"directory_id": "f0608be0792ccc1427c74eb7c17c2892364bc238",
"extension": "c",
"filename": "my_put_nbr.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 181343795,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 557,
"license": "MIT",
"license_type": "permissive",
"path": "/my_put_nbr.c",
"provenance": "stackv2-0092.json.gz:52314",
"repo_name": "Sosotess93/my_ls",
"revision_date": "2019-04-14T17:33:11",
"revision_id": "5c1083f2f5bdfdd2d533197a01e4f6b556af82e7",
"snapshot_id": "48079ec991befb45930eec494c849633472e0f6c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Sosotess93/my_ls/5c1083f2f5bdfdd2d533197a01e4f6b556af82e7/my_put_nbr.c",
"visit_date": "2020-05-09T18:29:32.714534"
} | stackv2 | /*
** my_put_nbr.c for my_put_nbr in /home/charra_s/Piscine_C_J04
**
** Made by Sofiane Charrad
** Login <charra_s@epitech.net>
**
** Started on Fri Oct 3 22:54:07 2014 Sofiane Charrad
** Last update Sun Nov 30 16:22:27 2014 Sofiane Charrad
*/
#include "my_ls.h"
int my_put_nbr(int nb)
{
int rev;
int i;
rev = 1;
if (nb >= 0)
nb *= -1;
else
my_putchar('-');
while (nb / rev <= -10)
rev *= 10;
while (rev != 0)
{
my_putchar(((nb / rev) % 10) * (-1) + '0');
rev /= 10;
i = i + 1;
}
return (i);
}
| 2.953125 | 3 |
2024-11-18T20:55:52.709570+00:00 | 2020-03-03T18:51:33 | c5c8750fc7535e73ee5ebb7d6ebef3cac0737d8e | {
"blob_id": "c5c8750fc7535e73ee5ebb7d6ebef3cac0737d8e",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-03T18:51:33",
"content_id": "bfd16cec1a4036215859eaf2079b280dd8310470",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "aa5b169ec7f044e21f74e266b4e9b5d50e10da8b",
"extension": "c",
"filename": "wtdist.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": 34878,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/namespaces/arep/src/leon/src/wtdist.c",
"provenance": "stackv2-0092.json.gz:52443",
"repo_name": "fokx/spiral-software",
"revision_date": "2020-03-03T18:51:33",
"revision_id": "85c004113e5b94ad52f7c4c86c8a6b704250e53a",
"snapshot_id": "d740f5e66b4ec30dfabce5930779a5630db85372",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fokx/spiral-software/85c004113e5b94ad52f7c4c86c8a6b704250e53a/namespaces/arep/src/leon/src/wtdist.c",
"visit_date": "2022-04-22T15:43:49.104996"
} | stackv2 | /* File wtdist.c. */
/* Copyright (C) 1992 by Jeffrey S. Leon. This software may be used freely
for educational and research purposes. Any other use requires permission
from the author. */
/* Highly optimized main program to compute weight distribution
of a linear code The command format is
wtdist <options> <code> <weightToSave> <matrix>
or
wtdist <options> <code>
where in the second case all vectors of weight <weightToSave> (except
scalar multiples) are saved as a matrix whose rows are the vectors. If
the -1 option is coded, only one vector of this weight is saved. If there
are no vectors of the given weight, the matrix is not created.
For most binary codes, bit string operations on vectors are used.
For nonbinary codes (and for binary codes whose parameters fail to meet
certain constraints), several columns of each codeword are packed into a
single integer in order to make computations much faster, for large codes,
than would otherwise be possible. The number of columns packed into a
single integer is referred to as the "packing factor". It may be
specified explicitly by the -pf option (within limits) or allowed to
default. Optimal choice of the packing factor can improve performance
considerably.
Let the code be an (n,k) code over GF(q), where q = p^e. Let F(x) =
a[0] + a[1]*x + ... + a[e]*x^e be the irreducible polynomial over
GF(p) used to construct GF(q). The elements of GF(q) are represented
as integers in the range 0..q-1, where field element
g[0] + g[1]*x + ... + g[e-1]*x^(e-1) is represented by the integer
g[0] + g[1] * q + ... + g[e-1] * q^(e-1).
Let P denote the packing factor. In order to save space and time, up
to P components of a vector over GF(q) are represented as a single
integer in the range 0..(q^P-1). Specifically, the sequence of
components b[i],b[i+1],...,b[i+P-1] is represented by the integer
b[i] + b[i+1] * q + ... + b[i+P-1] * q^(P-1).
The integer representing a sequence of field elements (components) is
referred to as a "packed field sequence". The number of packed field
sequences required to represent one codeword is called the "packed
length" of the code; it equals ceil(n/P). The set of columns of the
code corresponding to a packed field sequence is referred to as a "packed column".
The packing factor P must satisfy the constraints
i) P <= MaxPackingFactor,
ii) FieldSize ^ P - 1 <= MaxPackedInteger,
iii) ceil(n/P) <= MaxPackedLength,
where MaxPackingFactor, MaxPackedInteger, and MaxPackedLength are
symbolic constant (see above).
In general, a large packing factor will increase memory requirements
and will increase the time required to initialize various tables, but
it will decrease the time required to compute the weight distribution,
once initialization has been completed. The largest single data
structure contains e * k * q^P * MaxPackedLength * r bytes,
where r is the number of bytes used to represent type
0..MaxPackedInteger.
In general, a relatively small packing factor (say 8 for binary codes)
is indicated for codes of moderate size. For large codes, a larger
packing factor (say 12 for binary codes) leads to lower execution times,
at the cost of a higher memory requirement.
The user may specify the value of the packing factor in the input,
subject to the limits specified above. An input value of 0 will cause
the program to choose a default value, which may not give as good
performance as a user-specified value.
*/
/* Note: BINARY_CUTOFF_DIMENSION must be at least 3. */
#define BINARY_CUTOFF_DIMENSION 12
#define DEFAULT_INIT_ALLOC_SIZE 10000
#include <stddef.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#ifdef HUGE
#include <alloc.h>
#endif
#define MAIN
#include "group.h"
#include "groupio.h"
#include "errmesg.h"
#include "field.h"
#include "readdes.h"
#include "storage.h"
#include "token.h"
#include "util.h"
GroupOptions options;
static void verifyOptions(void);
static void binaryWeightDist(
const Code *const C,
const Unsigned saveWeight,
const BOOLEAN oneCodeWordOnly,
Unsigned *const allocatedSize,
unsigned long *const freq,
Matrix_01 *const matrix);
static void generalWeightDist(
const Code *const C,
Unsigned saveWeight,
const BOOLEAN oneCodeWordOnly,
const Unsigned packingFactor,
const Unsigned largestPackedInteger,
const Unsigned packedLength,
Unsigned *const allocatedSize,
unsigned long *const freq,
Matrix_01 *matrix);
static void binaryCosetWeightDist(
const Code *const C,
const Unsigned maxCosetWeight,
const BOOLEAN oneCodeWordOnly,
const Unsigned passes,
Unsigned *const allocatedSize,
unsigned long *const freq,
Matrix_01 *const matrix);
int main( int argc, char *argv[])
{
char codeFileName[MAX_FILE_NAME_LENGTH] = "",
matrixFileName[MAX_FILE_NAME_LENGTH] = "";
Unsigned i, j, temp, optionCountPlus1, packingFactor, packedLength,
largestPackedInteger, saveWeight, allocatedSize,
maxCosetWeight, passes;
char matrixObjectName[MAX_NAME_LENGTH+1] = "",
codeLibraryName[MAX_NAME_LENGTH+1] = "",
matrixLibraryName[MAX_NAME_LENGTH+1] = "",
prefix[MAX_FILE_NAME_LENGTH],
suffix[MAX_NAME_LENGTH];
Code *C;
Matrix_01 *matrix;
BOOLEAN saveCodeWords, oneCodeWordOnly, defaultForBinaryProcedure,
useBinaryProcedure, cWtDistFlag;
char comment[100];
unsigned long *freq = malloc( (MAX_CODE_LENGTH+2) * sizeof(unsigned long));
/* Provide help if no arguments are specified. */
if ( argc == 1 ) {
printf( "\nUsage: wtdist [options] code [saveWeight matrix]\n");
return 0;
}
/* Check for limits option. If present in position 1, give limits and
return. */
if ( strcmp(argv[1], "-l") == 0 || strcmp(argv[1], "-L") == 0 ) {
showLimits();
return 0;
}
/* Check for verify option. If present in position 1, perform verify (Note
verifyOptions terminates program). */
if ( strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "-V") == 0 )
verifyOptions();
/* Check for exactly 1 or 3 parameters following options. */
for ( optionCountPlus1 = 1 ; optionCountPlus1 < argc &&
argv[optionCountPlus1][0] == '-' ; ++optionCountPlus1 )
;
if ( argc - optionCountPlus1 < 1 && argc - optionCountPlus1 > 3 ) {
ERROR( "main (wtdist)",
"1, 2 or 3 non-option parameters are required.");
exit(ERROR_RETURN_CODE);
}
saveCodeWords = (argc - optionCountPlus1 == 3);
/* Process options. */
prefix[0] = '\0';
suffix[0] = '\0';
options.inform = TRUE;
packingFactor = 0;
cWtDistFlag = FALSE;
oneCodeWordOnly = FALSE;
defaultForBinaryProcedure = TRUE;
allocatedSize = 0;
parseLibraryName( argv[optionCountPlus1+2], "", "", matrixFileName,
matrixLibraryName);
strncpy( options.genNamePrefix, matrixLibraryName, 4);
options.genNamePrefix[4] = '\0';
strcpy( options.outputFileMode, "w");
/* Retrieve command-line options. */
for ( i = 1 ; i < optionCountPlus1 ; ++i ) {
for ( j = 1 ; argv[i][j] != ':' && argv[i][j] != '\0' ; ++j )
#ifdef EBCDIC
argv[i][j] = ( argv[i][j] >= 'A' && argv[i][j] <= 'I' ||
argv[i][j] >= 'J' && argv[i][j] <= 'R' ||
argv[i][j] >= 'S' && argv[i][j] <= 'Z' ) ?
(argv[i][j] + 'a' - 'A') : argv[i][j];
#else
argv[i][j] = (argv[i][j] >= 'A' && argv[i][j] <= 'Z') ?
(argv[i][j] + 'a' - 'A') : argv[i][j];
#endif
errno = 0;
if ( strcmp( argv[i], "-a") == 0 )
strcpy( options.outputFileMode, "a");
else if ( strcmp( argv[i], "-cwtdist") == 0 ) {
cWtDistFlag = TRUE;
}
else if ( strncmp( argv[i], "-p:", 3) == 0 ) {
strcpy( prefix, argv[i]+3);
}
else if ( strncmp( argv[i], "-t:", 3) == 0 ) {
strcpy( suffix, argv[i]+3);
}
else if ( strncmp( argv[i], "-n:", 3) == 0 )
if ( isValidName( argv[i]+3) )
strcpy( matrixObjectName, argv[i]+3);
else
ERROR1s( "main (wtdist)", "Invalid name ", matrixObjectName,
" for codewords to be saved.")
else if ( strcmp( argv[i], "-q") == 0 )
options.inform = FALSE;
else if ( strcmp( argv[i], "-overwrite") == 0 )
strcpy( options.outputFileMode, "w");
else if ( strcmp( argv[i], "-b") == 0 ) {
defaultForBinaryProcedure = FALSE;
useBinaryProcedure = TRUE;
}
else if ( strcmp( argv[i], "-g") == 0 ) {
defaultForBinaryProcedure = FALSE;
useBinaryProcedure = FALSE;
}
else if ( strncmp( argv[i], "-pf:", 4) == 0 ) {
errno = 0;
packingFactor = (Unsigned) strtol(argv[i]+4,NULL,0);
if ( errno )
ERROR( "main (wtdist)", "Invalid syntax for -pf option")
}
else if ( strncmp( argv[i], "-s:", 3) == 0 ) {
errno = 0;
allocatedSize = (Unsigned) strtol(argv[i]+3,NULL,0);
if ( errno )
ERROR( "main (wtdist)", "Invalid syntax for -s option")
}
else if ( strcmp( argv[i], "-1") == 0 )
oneCodeWordOnly = TRUE;
else
ERROR1s( "main (compute subgroup)", "Invalid option ", argv[i], ".")
}
options.maxBaseSize = DEFAULT_MAX_BASE_SIZE;
options.maxWordLength = 200 + 5 * options.maxBaseSize;
options.maxDegree = MAX_INT - 2 - options.maxBaseSize;
if ( cWtDistFlag )
maxCosetWeight = saveWeight;
/* Compute names for files and name for matrix of codewords saved. Also
determine weight of codewords to save. */
parseLibraryName( argv[optionCountPlus1], prefix, suffix,
codeFileName, codeLibraryName);
if ( saveCodeWords ) {
errno = 0;
saveWeight = (Unsigned) strtol(argv[optionCountPlus1+1], NULL, 0);
if ( errno )
ERROR( "main (wtdist)", "Invalid syntax weight to save.")
parseLibraryName( argv[optionCountPlus1+2], prefix, suffix,
matrixFileName, matrixLibraryName);
if ( matrixObjectName[0] == '\0' )
strncpy( matrixObjectName, matrixLibraryName, MAX_NAME_LENGTH+1);
}
else
saveWeight = UNKNOWN;
/* Read in the code. */
C = readCode( codeFileName, codeLibraryName, TRUE, 0, 0, 0);
/* Partially allocate matrix for saving codewords. Compute initial
allocatedSize, unless specified as input. */
if ( saveCodeWords ) {
if ( allocatedSize == 0 )
allocatedSize = DEFAULT_INIT_ALLOC_SIZE;
matrix = (Matrix_01 *) malloc( sizeof(Matrix_01) );
if ( !matrix )
ERROR( "main (wtdist)", "Out of memory.")
matrix->unused = NULL;
matrix->field = NULL;
matrix->entry = (FieldElement **) malloc( sizeof(FieldElement *) *
(allocatedSize+2) );
if ( !matrix->entry )
ERROR( "main (wtdist)", "Out of memory.")
matrix->setSize = C->fieldSize;
matrix->numberOfRows = 0;
matrix->numberOfCols = C->length;
}
#ifdef xxxxxx
/* If a coset weight distribution is requested, check the size limits,
call cosetWeightDist if ok, and return. */
if ( cWtDistFlag ) {
if ( C->fieldSize != 2 || C->length > 128 || C->length - C->dimension > 32 )
ERROR( "main (wtdist)",
"Coset weight dist requires binary code, length <= 128, codimension <= 32.")
binaryCosetWeightDist( C, maxCosetWeight, oneCodeWordOnly, passes, &allocatedSize,
matrix);
return 0;
}
#endif
/* Decide whether to use binary or general procedure. The general
procedure is used on binary codes of small dimension. */
if ( defaultForBinaryProcedure )
useBinaryProcedure &= (C->fieldSize == 2 &&
C->length <= 128 &&
C->dimension > BINARY_CUTOFF_DIMENSION);
else if ( useBinaryProcedure && (C->fieldSize != 2 || C->length > 128 ||
C->dimension <= 3) ) {
useBinaryProcedure = FALSE;
if ( options.inform )
printf( "\n\n Special binary procedure cannot be used.\n");
}
/* If the general procedure is to be used, determine the packing factor if
one was not specified. Determine the packed length and the largest
packed integer. */
if ( !useBinaryProcedure ) {
if ( packingFactor == 0 ) {
packingFactor = 1;
largestPackedInteger = C->fieldSize;
while ( (largestPackedInteger <= 0x7fff / C->fieldSize) &&
(packingFactor <= C->dimension / 2) ) {
++packingFactor;
largestPackedInteger *= C->fieldSize;
}
--largestPackedInteger;
}
else {
temp = 1;
largestPackedInteger = C->fieldSize;
while ( (largestPackedInteger <= 0x7fff / C->fieldSize) &&
(temp < packingFactor) ) {
++temp;
largestPackedInteger *= C->fieldSize;
}
packingFactor = temp;
--largestPackedInteger;
}
packedLength = (C->length + packingFactor - 1) / packingFactor;
}
/* Compute the weight distribution. */
if ( useBinaryProcedure )
binaryWeightDist( C, saveWeight, oneCodeWordOnly, &allocatedSize, freq,
matrix);
else
generalWeightDist( C, saveWeight, oneCodeWordOnly, packingFactor,
largestPackedInteger, packedLength,
&allocatedSize, freq, matrix);
/* Write out the weight distribution. */
if ( options.inform ) {
printf( "\n\n Weight Distribution of code %s", C->name);
printf( "\n\n Weight Frequency");
printf( "\n ------ ---------");
for ( i = 0 ; i <= C->length ; ++i )
if ( freq[i] != 0 )
printf( "\n %3u %10lu", i, freq[i]);
printf( "\n");
}
/* Write out the codewords of weight saveWeight. */
if ( saveCodeWords && matrix->numberOfRows > 0 ) {
if ( oneCodeWordOnly )
sprintf( comment, "One codeword of weight %u in code %s.",
saveWeight, C->name);
else if ( C->fieldSize == 2 )
sprintf( comment, "The %u codewords of weight %u in code %s.",
matrix->numberOfRows, saveWeight, C->name);
else
sprintf( comment,
"%u of %u codewords of weight %u in code %s"
" (scalar multiples excluded).",
matrix->numberOfRows, matrix->numberOfRows * (C->fieldSize-1),
saveWeight, C->name);
strcpy( matrix->name, matrixObjectName);
write01Matrix( matrixFileName, matrixLibraryName, matrix, FALSE,
comment);
}
return 0;
}
/*-------------------------- packBinaryCodeWord ---------------------------*/
void packBinaryCodeWord(
const Unsigned length,
const FieldElement *const codeWordToPack,
unsigned long *const packedWord1,
unsigned long *const packedWord2,
unsigned long *const packedWord3,
unsigned long *const packedWord4)
{
Unsigned col;
*packedWord1 = *packedWord2 = *packedWord3 = *packedWord4 = 0;
for ( col = 1 ; col <= length ; ++col )
if ( col <= 32 )
*packedWord1 |= codeWordToPack[col] << (col-1);
else if (col <= 64 )
*packedWord2 |= codeWordToPack[col] << (col-33);
else if (col <= 96 )
*packedWord3 |= codeWordToPack[col] << (col-65);
else if (col <= 128 )
*packedWord4 |= codeWordToPack[col] << (col-97);
}
/*-------------------------- buildOnesCount -------------------------------*/
/* This function allocates and constructs an array of size 2^16 in which
entry i contains the number of ones in the binary representation of i,
0 <= i < 2^16. It returns (a pointer to) the array. It is assumed that
type short has length 16 bits. */
#ifdef HUGE
char huge *buildOnesCount(void)
#else
char *buildOnesCount(void)
#endif
{
long i, j;
#ifdef HUGE
char huge *onesCount = (char huge *) farmalloc( 65536L * sizeof(char) );
#else
char *onesCount = (char *) malloc( 65536L * sizeof(char) );
#endif
if ( !onesCount )
ERROR( "buildOnesCount",
"Not enough memory to run program. Program terminated.")
for ( i = 0 ; i <= 65535L ; ++i ) {
onesCount[i] = 0;
for ( j = 0 ; j <= 15 ; ++j )
onesCount[i] += ( i & (1 << j)) != 0;
}
return onesCount;
}
/*-------------------------- binaryWeightDist ----------------------------*/
/* Assumes length <= 128. */
#define SAVE if ( curWt == saveWeight ) { \
if ( ++matrix->numberOfRows > *allocatedSize ) { \
*allocatedSize *= 2; \
matrix->entry = (FieldElement **) realloc( matrix->entry, \
*allocatedSize); \
} \
if ( !matrix->entry ) \
ERROR( "binaryWeightDist", "Out of memory.") \
vec = matrix->entry[matrix->numberOfRows] = (FieldElement *) \
malloc( (C->length+1) * sizeof(FieldElement) ); \
if ( !vec ) \
ERROR( "binaryWeightDist", "Out of memory.") \
for ( j = 0 ; j < length ; ++j ) \
if ( j < 32 ) \
vec[j+1] = ((cw1 >> j) & 1); \
else if ( j < 64 ) \
vec[j+1] = ((cw2 >> j-32) & 1); \
else if ( j < 96 ) \
vec[j+1] = ((cw3 >> j-64) & 1); \
else if ( j < 128 ) \
vec[j+1] = ((cw4 >> j-96) & 1); \
if ( oneCodeWordOnly ) \
saveWeight = UNKNOWN; \
}
void binaryWeightDist(
const Code *const C,
Unsigned saveWeight,
const BOOLEAN oneCodeWordOnly,
Unsigned *const allocatedSize,
unsigned long *const freq,
Matrix_01 *const matrix)
{
Unsigned length = C->length,
dimension = C->dimension,
i, j, curWt;
FieldElement *vec;
unsigned long m;
#ifdef HUGE
char huge *onesCount = buildOnesCount();
#else
char *onesCount = buildOnesCount();
#endif
unsigned long basis1[35], basis2[35], basis3[35], basis4[35];
unsigned long cw1, cw2, cw3, cw4;
unsigned long loopIndex, lastPass, temp;
/* Initializations. */
for ( i = 0 ; i <=C->length ; ++i )
freq[i] = 0;
cw1 = cw2 = cw3 = cw4 = 0;
/* Pack the code words. */
for ( i = 1 ; i <= C->dimension ; ++i )
packBinaryCodeWord( C->length, C->basis[i], &basis1[i-1], &basis2[i-1],
&basis3[i-1], &basis4[i-1]);
/* Enumerate the codewords. */
lastPass = (1L << (dimension-3)) - 1;
if ( saveWeight == UNKNOWN ) {
if ( length <= 32 )
#define MAXLEN 32
#include "wt.h"
else if ( length <= 48 )
#define MAXLEN 48
#include "wt.h"
else if ( length <= 64 )
#define MAXLEN 64
#include "wt.h"
else if ( length <= 80 )
#define MAXLEN 80
#include "wt.h"
else if ( length <= 96 )
#define MAXLEN 96
#include "wt.h"
else if ( length <= 112 )
#define MAXLEN 112
#include "wt.h"
else if ( length <= 128 )
#define MAXLEN 128
#include "wt.h"
}
else
if ( length <= 32 )
#define MAXLEN 32
#include "swt.h"
else if ( length <= 48 )
#define MAXLEN 48
#include "swt.h"
else if ( length <= 64 )
#define MAXLEN 64
#include "swt.h"
else if ( length <= 80 )
#define MAXLEN 80
#include "swt.h"
else if ( length <= 96 )
#define MAXLEN 96
#include "swt.h"
else if ( length <= 112 )
#define MAXLEN 112
#include "swt.h"
else if ( length <= 128 )
#define MAXLEN 128
#include "swt.h"
}
/*-------------------------- buildWeightArray -------------------------------------*/
/* The procedure BuildWeightArray constructs the array Weight
of size 0..LargestPackedInteger. For t = 0,1,...,HighPackedInteger,
Weight[t] is set to the number of nonzero field elements in the
sequence of PackingFactor field elements represented by integer t. */
char *buildWeightArray(
const Unsigned fieldSize, /* Size of the field. */
const Unsigned packingFactor, /* No of cols packed into integer. */
const Unsigned largestPackedInteger)
{
Unsigned i, v;
char *weight;
weight = (char *) malloc( sizeof(char) * largestPackedInteger);
if ( !weight )
ERROR( "buildWeightArray", "Out of memory.");
for ( i = 0 ; i <= largestPackedInteger ; ++i ) {
weight[i] = 0;
v = i;
while ( v > 0 ) {
if ( v % fieldSize )
++weight[i];
v /= fieldSize;
}
}
return weight;
}
/*-------------------------- packNonBinaryCodeWord --------------------------------*/
/* This procedure packs a codeword over a field of size greater than 2.
(If the field size is 2, it works, but it returns an array of type
unsigned short, whereas type unsigned would be preferable.)
It returns a new packed code word which is obtained by packing the code
word supplied as a parameter. If p denotes the PackingFactor, then p
columns of the input codeword (Word) are packed into each integer of the
output packed codeword (PackedWord). If q denotes the field size and if
c(1),...,c(n) denotes the input codeword, then the output packed word will
have components
c(1)+c(2)*q+...+c(p)*q**(p-1), c(p+1)+c(p+2)*q+...+c(2*p)*q**(p-1), etc. */
unsigned short *packNonBinaryCodeWord(
const Unsigned fieldSize, /* Field size for codeword. */
const Unsigned length, /* Length of codeword to pack. */
const Unsigned packingFactor, /* No of cols packed into integer. */
const FieldElement *codeWord) /* The codeword to pack. */
{
Unsigned index = 0,
offset = 0,
col,
powerOfFieldSize = 1;
const Unsigned colsPerArrayElt = (length+packingFactor) / packingFactor;
unsigned short *packedCodeWord;
packedCodeWord = (unsigned short *)
malloc( colsPerArrayElt * sizeof(unsigned short *));
if ( !packedCodeWord )
ERROR( "packNonBinaryCodeWord", "Out of memory.");
packedCodeWord[0] = 0;
for ( col = 1 ; col <= length ; ++col ) {
if ( offset >= packingFactor ) {
packedCodeWord[++index] = 0;
offset = 0;
powerOfFieldSize = 1;
}
packedCodeWord[index] += codeWord[col] * powerOfFieldSize;
++offset;
powerOfFieldSize *= fieldSize;
}
return packedCodeWord;
}
/*-------------------------- unpackNonBinaryCodeWord --------------------------------*/
/* This procedure unpacks a codeword over a field of size greater than 2.
It performs the reverse of the packNonBinaryCodeword procedure above. */
void unpackNonBinaryCodeWord(
const Unsigned fieldSize, /* Field size for codeword. */
const Unsigned length, /* Length of codeword to unpack. */
const Unsigned packingFactor, /* No of cols packed into integer. */
const unsigned short *packedCodeWord, /* The codeword to unpack pack. */
FieldElement *const codeWord) /* Set to unpacked code word. */
{
Unsigned index = 0,
offset = 0,
col, temp;
temp = packedCodeWord[0];
for ( col = 1 ; col <= length ; ++col ) {
if ( offset >= packingFactor ) {
temp = packedCodeWord[++index];
offset = 0;
}
codeWord[col] = temp % fieldSize;
++offset;
temp /= fieldSize;
}
}
/*-------------------------- buildAddBasisElement -----------------------------------*/
/* This procedure constructs a data structure AddBasisElement which
specifies how to add a a prime-basis element to an arbitrary
codeword. addBasisElement[i][p][j] gives the sum of packed column j
of the i'th prime basis vector and packed field sequence k, for
1 <= i <= C->dimension * C->field->exponent,
0 <= j < packedLength,
0 <= p <= largestPackedInteger.
*/
unsigned short ***buildAddBasisElement(
const Code *const C,
const Unsigned packingFactor,
const Unsigned packedLength,
const Unsigned largestPackedInteger)
{
unsigned short ***addBasisElement;
Unsigned a, h, i, j, k, m, z, primeRow;
FieldElement s;
FieldElement *x, *y;
Unsigned *primeBasisVector;
const Unsigned fieldExponent = (C->fieldSize == 2) ? 1 : C->field->exponent;
const primeDimension = C->dimension * fieldExponent;
primeBasisVector = (Unsigned *) malloc( (C->length+1) * sizeof(Unsigned));
if ( !primeBasisVector )
ERROR( "buildAddBasisElement", "Out of memory.");
addBasisElement = (unsigned short ***)
malloc( primeDimension * sizeof(unsigned short **));
if ( !addBasisElement )
ERROR( "buildAddBasisElement", "Out of memory.");
x = (FieldElement *) malloc( (C->length+2) * sizeof(FieldElement));
if ( !x )
ERROR( "buildAddBasisElement", "Out of memory.");
y = (FieldElement *) malloc( (C->length+2) * sizeof(FieldElement));
if ( !y )
ERROR( "buildAddBasisElement", "Out of memory.");
for ( i = 1 , primeRow = 0 ; i <= C->dimension ; ++i )
for ( m = 0 ; m < fieldExponent ; ++m ) {
/* This part works only for prime fields or GF(4). */
s = (m == 0) ? 1 : 2;
++primeRow;
if ( m > 0 && C->fieldSize != 4 )
ERROR( "buildAddBasisElement", "Field whose order is not prime or 4.")
if ( C->fieldSize == 2 )
for ( k = 1 ; k <= C->length ; ++k )
primeBasisVector[k] = C->basis[i][k];
else
for ( k = 1 ; k <= C->length ; ++k )
primeBasisVector[k] = C->field->prod[C->basis[i][k]][s];
addBasisElement[primeRow] = (unsigned short **)
malloc( (largestPackedInteger+1) * sizeof(unsigned short **));
if ( !addBasisElement[primeRow] )
ERROR( "buildAddBasisElement", "Out of memory.")
for ( h = 1 ; h <= C->length ; ++h )
x[h] = 0;
for ( z = 0 ; z <= largestPackedInteger ; ++z ) {
if ( C->fieldSize == 2 )
for ( j = 1 ; j <= C->length ; ++j )
y[j] = primeBasisVector[j] ^ x[j];
else
for ( j = 1 ; j <= C->length ; ++j )
y[j] = C->field->sum[primeBasisVector[j]][x[j]];
addBasisElement[primeRow][z] = packNonBinaryCodeWord( C->fieldSize,
C->length, packingFactor, y);
a = 1;
while ( x[a] == C->fieldSize - 1 )
++a;
++x[a];
for ( h = 1; h < a ; ++h)
x[h] = 0;
for ( h = packingFactor+1 ; h <= C->length ; ++h )
x[h] = x[h-packingFactor];
}
}
return addBasisElement;
}
/*-------------------------- generalWeightDist ----------------------------*/
void generalWeightDist(
const Code *const C,
Unsigned saveWeight,
const BOOLEAN oneCodeWordOnly,
const Unsigned packingFactor,
const Unsigned largestPackedInteger,
const Unsigned packedLength,
Unsigned *const allocatedSize,
unsigned long *const freq,
Matrix_01 *matrix)
{
const Unsigned fieldExponent = (C->fieldSize == 2) ? 1 : C->field->exponent;
const Unsigned fieldCharacteristic =
(C->fieldSize == 2) ? 2 : C->field->characteristic;
const Unsigned primeDimension = C->dimension * fieldExponent;
Unsigned currentWeight, h, m, primeRow, packedCol, wt;
char *weight;
unsigned short ***addBasisElement;
unsigned short *currentWord; /* Array of size packedLength+1 */
Unsigned *x; /* Array of size primeDimension+1 */
FieldElement *vec;
/* Allocate the arrays x and currentWord. */
x = (Unsigned *) malloc( (primeDimension+1) * sizeof(Unsigned *));
if ( !x )
ERROR( "generalWeightDist", "Out of memory")
currentWord =
(unsigned short *) malloc( (packedLength+1) * sizeof(Unsigned *));
if ( !currentWord )
ERROR( "generalWeightDist", "Out of memory")
/* Construct the weight array. */
weight = buildWeightArray( C->fieldSize, packingFactor,
largestPackedInteger);
/* Construct structure AddBasisElement, used to add a prime basis codeword
to an arbitrary codeword. */
addBasisElement = buildAddBasisElement( C, packingFactor, packedLength,
largestPackedInteger);
/* Initialize freq and saveCount. Upon termination, freq will hold the
weight distribution. */
for ( wt = 1 ; wt <= C->length ; ++wt )
freq[wt] = 0;
freq[0] = 1;
/* Traverse the code. */
for ( h = C->dimension ; h >= 1 ; --h ) {
/* Traverse codewords of form 0*basis[1] +...+ 0*basis[h-1] +
1*basis[h] + (anything) * basis[h+1] +...+ (anything) * basis[k]),
where k is the dimension. */
for ( primeRow = 0 ; primeRow <= primeDimension ; ++primeRow )
x[primeRow] = 0;
for ( packedCol = 0 ; packedCol < packedLength ; ++packedCol )
currentWord[packedCol] = 0;
m = (h - 1) * fieldExponent + 1;
do {
/* Add prime basis codeword m to current word and find weight
of result. */
currentWeight = 0;
for ( packedCol = 0 ; packedCol < packedLength ; ++packedCol ) {
currentWord[packedCol] =
addBasisElement[m][currentWord[packedCol]][packedCol];
currentWeight += weight[currentWord[packedCol]];
}
/* Record weight. */
freq[currentWeight] += (C->fieldSize - 1);
/* Save the codeword, if appropriate. */
if ( currentWeight == saveWeight ) {
++matrix->numberOfRows;
if ( matrix->numberOfRows > *allocatedSize ) {
*allocatedSize *= 2;
matrix->entry = (FieldElement **) realloc( matrix->entry,
*allocatedSize);
if ( !matrix->entry )
ERROR( "binaryWeightDist", "Out of memory.")
}
vec = matrix->entry[matrix->numberOfRows] =
malloc( (C->length+1) * sizeof(FieldElement) );
if ( !vec )
ERROR( "binaryWeightDist", "Out of memory.")
unpackNonBinaryCodeWord( C->fieldSize, C->length, packingFactor,
currentWord, vec);
if ( oneCodeWordOnly )
saveWeight = UNKNOWN+1;
}
/* Find m such that prime basis codeword number X[m] is the
basis codeword to add next. */
m = primeDimension;
while ( x[m] == fieldCharacteristic - 1 )
--m;
/* Adjust array X, which determines which basis codeword to add
next. */
++x[m];
for ( primeRow = m+1 ; primeRow <= primeDimension ; ++primeRow )
x[primeRow] = 0;
} while ( m > h * fieldExponent );
}
}
#ifdef xxxxxx
/*-------------------------- binaryCosetWeightDist -----------------------*/
void binaryCosetWeightDist(
const Code *const C,
const Unsigned maxCosetWeight,
const BOOLEAN oneCodeWordOnly,
const Unsigned passes,
Unsigned *const allocatedSize,
unsigned long *const freq,
Matrix_01 *const matrix)
{
unsigned long sum;
const unsigned coDimension = C->length - C->dimension;
const unsigned long numberOfCosetsLess1 = (2L << coDimension) - 1;
const unsigned long maxCosetsPerPass = numberOfCosetsLess1 / passes + 1;
/* Initializations. */
for ( i = 0 ; i <=C->length ; ++i )
freq[i] = 0;
cw1 = cw2 = cw3 = cw4 = 0;
for ( wt = 1 ; wt <= maxCosetWeight && cosetsFound <= goal ; ++wt ) {
for ( i = 1 ; i <= wt ; ++i )
/* Write out the coset weight distribution. */
sumLess1 = 0;
if ( options.inform ) {
printf( "\n\n Coset Weight Distribution of code %s", C->name);
printf( "\n\n Coset Min Wt Number Of Cosets");
printf( "\n ------------ ----------------");
for ( i = 0 ; i <= maxCosetWeight ; ++i )
if ( freq[i] != 0 )
if ( i != 0 )
sumLess1 += freq[i];
printf( "\n %2u %10lu", i, freq[i]);
if ( sumLess1 < numberOfCosetsLess1 )
printf( "\n at least %2u %10lu", maxCosetWeight+1,
numberOfCosetsLess1 - sumLess1);
printf( "\n");
}
#endif
/*-------------------------- verifyOptions -------------------------------*/
static void verifyOptions(void)
{
CompileOptions mainOpts = { DEFAULT_MAX_BASE_SIZE, MAX_NAME_LENGTH,
MAX_PRIME_FACTORS,
MAX_REFINEMENT_PARMS, MAX_FAMILY_PARMS,
MAX_EXTRA, XLARGE, SGND, NFLT};
extern void xbitman( CompileOptions *cOpts);
extern void xcode ( CompileOptions *cOpts);
extern void xcopy ( CompileOptions *cOpts);
extern void xerrmes( CompileOptions *cOpts);
extern void xessent( CompileOptions *cOpts);
extern void xfactor( CompileOptions *cOpts);
extern void xfield ( CompileOptions *cOpts);
extern void xnew ( CompileOptions *cOpts);
extern void xpartn ( CompileOptions *cOpts);
extern void xpermut( CompileOptions *cOpts);
extern void xpermgr( CompileOptions *cOpts);
extern void xprimes( CompileOptions *cOpts);
extern void xreadde( CompileOptions *cOpts);
extern void xstorag( CompileOptions *cOpts);
extern void xtoken ( CompileOptions *cOpts);
extern void xutil ( CompileOptions *cOpts);
xbitman( &mainOpts);
xcode ( &mainOpts);
xcopy ( &mainOpts);
xerrmes( &mainOpts);
xessent( &mainOpts);
xfactor( &mainOpts);
xfield ( &mainOpts);
xnew ( &mainOpts);
xpartn ( &mainOpts);
xpermut( &mainOpts);
xpermgr( &mainOpts);
xprimes( &mainOpts);
xreadde( &mainOpts);
xstorag( &mainOpts);
xtoken ( &mainOpts);
xutil ( &mainOpts);
}
| 2.625 | 3 |
2024-11-18T20:55:53.046616+00:00 | 2019-02-24T21:21:02 | 8eef4ae8387e26c2bc81e127088589b52b850a67 | {
"blob_id": "8eef4ae8387e26c2bc81e127088589b52b850a67",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-24T21:21:02",
"content_id": "0a38b770475f2328735d98f301cac70042f4a185",
"detected_licenses": [
"MIT",
"SunPro"
],
"directory_id": "95e491ad81771f5959d738c5cebe3a3007efe215",
"extension": "h",
"filename": "stdio.h",
"fork_events_count": 0,
"gha_created_at": "2019-03-16T21:58:39",
"gha_event_created_at": "2019-03-16T21:58:39",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 176029341,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2398,
"license": "MIT,SunPro",
"license_type": "permissive",
"path": "/include/stdio.h",
"provenance": "stackv2-0092.json.gz:52830",
"repo_name": "vendu/hlibc",
"revision_date": "2019-02-24T21:21:02",
"revision_id": "597b96a83b0f84be152e53e55b30e60d705cfca1",
"snapshot_id": "c75f79d027779b4103d682e9dcda26974e60ffad",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/vendu/hlibc/597b96a83b0f84be152e53e55b30e60d705cfca1/include/stdio.h",
"visit_date": "2020-04-29T09:33:18.289299"
} | stackv2 | #ifndef _STDIO_H
#define _STDIO_H
#include <fcntl.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
/* for popen / pclose */
#include <sys/types.h>
#include <sys/wait.h>
#include <bits/types.h>
#define NULL ((void*)0)
#define EOF (-1)
#undef SEEK_SET
#undef SEEK_CUR
#undef SEEK_END
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
#define BUFSIZ 1024
#define FILENAME_MAX 4095
#define FOPEN_MAX 1000
#define TMP_MAX 10000
#define P_tmpdir "/tmp/"
#define L_tmpnam 11 /* this is 5 + 6 -- aka strlen("/tmp/") + NUM_RAND_CHARS */
/* The opaque stdio declaration */
typedef struct FILE FILE;
/* putc/getc */
int getc(FILE *);
int putc(int, FILE *);
int putchar(int);
int fputc(int, FILE *);
int ungetc(int, FILE *);
int fgetc(FILE *);
/* getline */
ssize_t getline (char **, size_t *, FILE *);
ssize_t getdelim(char **, size_t *, char, FILE *);
/* printf */
int printf(const char *, ...);
int sprintf(char *, const char *, ...);
int snprintf(char *, size_t, const char *, ...);
int dprintf(int, const char *, ...);
int fprintf(FILE *, const char *, ...);
int vprintf(const char *, va_list);
int vsprintf(char *, const char *, va_list);
int vsnprintf(char *, size_t, const char *, va_list);
int vdprintf(int, const char *, va_list); /* not implemented */
int vfprintf(FILE *, const char *, va_list);
/* fwrite */
size_t fread(void *, size_t, size_t, FILE *);
size_t fwrite(const void *, size_t, size_t, FILE *);
/* setbuf ( not implemented ) */
void setbuf(FILE *, char *);
void setbuffer(FILE *, char *, size_t);
void setlinebuf(FILE *);
int setvbuf(FILE *, char *, int, size_t);
/* popen */
FILE *popen(const char *, const char *);
int pclose(FILE *);
/* puts */
int fputs(const char *, FILE *);
int puts(const char *);
char *fgets(char *, int, FILE *);
FILE *fopen(const char *, const char *);
char *fgets(char *, int, FILE *);
int getchar(void);
int fclose(FILE *);
int fflush(FILE *);
int ferror(FILE *);
/* remove */
int remove(const char *);
/* rename */
int rename(const char *, const char *);
/* perror */
void perror(const char *);
/* scanf */
int scanf(const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
int sscanf(const char *str, const char *format, ...);
/* tmp */
char *tmpnam(char *);
FILE *tmpfile(void);
/* opaque objects */
extern FILE *stdin;
extern FILE *stdout;
extern FILE *stderr;
#endif
| 2.015625 | 2 |
2024-11-18T20:55:53.871340+00:00 | 2021-03-13T00:00:03 | 422becdf71f3c1a0833ae50e5deec71b3c7cd962 | {
"blob_id": "422becdf71f3c1a0833ae50e5deec71b3c7cd962",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-13T00:00:03",
"content_id": "06a47c9ed3567efdcfefe32ef3d05d44313788eb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0bdb3fbcae12abcd520ab482e466481092d73b3f",
"extension": "h",
"filename": "matrix_constructors.h",
"fork_events_count": 0,
"gha_created_at": "2020-04-11T04:48:33",
"gha_event_created_at": "2021-03-13T00:00:03",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 254794866,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1745,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Sources/simdFilamentC/include/simd/matrix_constructors.h",
"provenance": "stackv2-0092.json.gz:53089",
"repo_name": "PHIAR/simdFilament",
"revision_date": "2021-03-13T00:00:03",
"revision_id": "91c3456417f15559c2e57f1a5def0527f1c683b2",
"snapshot_id": "70acb1f73bdfe370d872af3bb36cb76bc9d388d4",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/PHIAR/simdFilament/91c3456417f15559c2e57f1a5def0527f1c683b2/Sources/simdFilamentC/include/simd/matrix_constructors.h",
"visit_date": "2023-03-20T18:24:15.883186"
} | stackv2 | #pragma once
#include "simd/types.h"
#define CONSTRUCT_2_COLUMNS(type, column_type) \
SWIFT_NAME("simd_" #type ".init(_:_:)") \
simd_ ## type SIMD_OVERLOADABLE \
simd_matrix(simd_ ## column_type col0, \
simd_ ## column_type col1) \
{ \
simd_ ## type result = {col0, col1}; \
return result; \
} \
#define CONSTRUCT_3_COLUMNS(type, column_type) \
SWIFT_NAME("simd_" #type ".init(_:_:_:)") \
simd_ ## type SIMD_OVERLOADABLE \
simd_matrix(simd_ ## column_type col0, \
simd_ ## column_type col1, \
simd_ ## column_type col2) \
{ \
simd_ ## type result = {col0, col1, col2}; \
return result; \
} \
#define CONSTRUCT_4_COLUMNS(type, column_type) \
SWIFT_NAME("simd_" #type ".init(_:_:_:_:)") \
simd_ ## type SIMD_OVERLOADABLE \
simd_matrix(simd_ ## column_type col0, \
simd_ ## column_type col1, \
simd_ ## column_type col2, \
simd_ ## column_type col3) \
{ \
simd_ ## type result = {col0, col1, col2, col3}; \
return result; \
} \
#define CONSTRUCT_ALL_COLUMNS(base_type, dims) \
CONSTRUCT_2_COLUMNS(base_type ## 2x ## dims, base_type ## dims) \
CONSTRUCT_3_COLUMNS(base_type ## 3x ## dims, base_type ## dims) \
CONSTRUCT_4_COLUMNS(base_type ## 4x ## dims, base_type ## dims)
#define CONSTRUCT_ALL(base_type) \
CONSTRUCT_ALL_COLUMNS(base_type, 2) \
CONSTRUCT_ALL_COLUMNS(base_type, 3) \
CONSTRUCT_ALL_COLUMNS(base_type, 4)
#ifdef __cplusplus
extern "C"
{
#endif
CONSTRUCT_ALL(float)
CONSTRUCT_ALL(double)
CONSTRUCT_ALL(int)
CONSTRUCT_ALL(uint)
CONSTRUCT_ALL(ushort)
#ifdef __cplusplus
}
#endif
| 2.1875 | 2 |
2024-11-18T20:55:53.932565+00:00 | 2022-11-29T17:12:25 | c663beb7a5d7898431504db629a8454bc6177670 | {
"blob_id": "c663beb7a5d7898431504db629a8454bc6177670",
"branch_name": "refs/heads/master",
"committer_date": "2022-11-29T22:24:38",
"content_id": "848148b782134231760152de16113b29ef1a9af9",
"detected_licenses": [
"MIT",
"BSD-1-Clause"
],
"directory_id": "5ec44ba3f31305336262c6d3e871312dbbe59259",
"extension": "c",
"filename": "urlparams.c",
"fork_events_count": 10,
"gha_created_at": "2011-08-26T21:50:08",
"gha_event_created_at": "2022-11-10T04:29:39",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 2276819,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6103,
"license": "MIT,BSD-1-Clause",
"license_type": "permissive",
"path": "/src/urlparams.c",
"provenance": "stackv2-0092.json.gz:53217",
"repo_name": "residuum/PuRestJson",
"revision_date": "2022-11-29T17:12:25",
"revision_id": "e6791ce9596ce21b7fcf864f3adb481643c4d11e",
"snapshot_id": "9087a663ef3a5ff0266fb46dbaa8a8ea2478c521",
"src_encoding": "UTF-8",
"star_events_count": 54,
"url": "https://raw.githubusercontent.com/residuum/PuRestJson/e6791ce9596ce21b7fcf864f3adb481643c4d11e/src/urlparams.c",
"visit_date": "2022-12-01T10:37:01.836771"
} | stackv2 | /*
Author:
Thomas Mayer <thomas@residuum.org>
Copyright (c) 2011-2015 Thomas Mayer
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.
*/
/*
* [urlparams] encodes data as JSON and outputs it as a symbol.
* */
#include "urlparams.h"
#include <math.h>
#include "uthash.h"
#include "inc/string.c"
#include "inc/kvp.c"
static t_class *urlparams_class;
struct _urlparams {
struct _kvp_store storage;
};
/* constructor */
static void *urlparams_new(const t_symbol *sel, const int argc, const t_atom *argv);
/* destructor */
static void urlparams_free(t_urlparams *x, const t_symbol *sel, const int argc, const t_atom *argv);
/** Functions called via Pd messages **/
/* bang and output */
static void urlparams_bang(t_urlparams *x);
/* add value */
static void urlparams_add(t_urlparams *x, const t_symbol *sel, const int argc, t_atom *argv);
/* clear stored values */
static void urlparams_clear(t_urlparams *x, const t_symbol *sel, const int argc, const t_atom *argv);
/* converts char to hex represenstation for url encoding */
static char urlp_tohex(const char code);
/* url encodes a string */
static char *urlp_encode(char *str, size_t *str_len);
/* begin implementations */
/* from http://www.geekhideout.com/urlcode.shtml */
static char urlp_tohex(const char code) {
static const char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/* from http://www.geekhideout.com/urlcode.shtml */
static char *urlp_encode(char *str, size_t *str_len) {
char *pstr = str;
char *buf;
char *pbuf;
(*str_len) = strlen(str) * 3 + 1;
buf = getbytes((*str_len) * sizeof(char));
pbuf = buf;
while (*pstr) {
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') {
*pbuf++ = *pstr;
} else {
*pbuf++ = '%', *pbuf++ = urlp_tohex(*pstr >> 4), *pbuf++ = urlp_tohex(*pstr & 15);
}
pstr++;
}
*pbuf = '\0';
return buf;
}
void urlparams_setup(void) {
urlparams_class = class_new(gensym("urlparams"), (t_newmethod)urlparams_new,
(t_method)urlparams_free, sizeof(t_urlparams), 0, A_GIMME, 0);
class_addbang(urlparams_class, (t_method)urlparams_bang);
class_addmethod(urlparams_class, (t_method)urlparams_add, gensym("add"), A_GIMME, 0);
class_addmethod(urlparams_class, (t_method)urlparams_clear, gensym("clear"), A_GIMME, 0);
}
void *urlparams_new(const t_symbol *const sel, const int argc, const t_atom *argv) {
t_urlparams *const urlp = (t_urlparams *)pd_new(urlparams_class);
(void) sel;
(void) argc;
(void) argv;
outlet_new(&urlp->storage.x_ob, NULL);
purest_json_lib_info("urlparams");
return (void *)urlp;
}
void urlparams_free (t_urlparams *const urlp, const t_symbol *const sel, const int argc, const t_atom *const argv) {
(void) sel;
(void) argc;
(void) argv;
kvp_store_free_memory((struct _kvp_store *)urlp);
}
void urlparams_bang(t_urlparams *const urlp) {
struct _kvp *it;
size_t output_len = 0;
char *output;
size_t encoded_key_len;
char *encoded_key_string = NULL;
size_t encoded_val_len;
char *encoded_val_string = NULL;
if (!HASH_COUNT(urlp->storage.data)) {
outlet_symbol(urlp->storage.x_ob.ob_outlet, gensym(""));
return;
}
for(it = urlp->storage.data; it != NULL; it = it->hh.next) {
encoded_key_string = urlp_encode(it->key, &encoded_key_len);
encoded_val_string = urlp_encode(it->value->val.s, &encoded_val_len);
output_len += encoded_key_len + encoded_val_len + 2;
string_free(encoded_key_string, &encoded_key_len);
string_free(encoded_val_string, &encoded_val_len);
}
output = getbytes(output_len * sizeof(char));
for(it = urlp->storage.data; it != NULL; it = it->hh.next) {
encoded_key_string = urlp_encode(it->key, &encoded_key_len);
encoded_val_string = urlp_encode(it->value->val.s, &encoded_val_len);
strcat(output, encoded_key_string);
strcat(output, "=");
strcat(output, encoded_val_string);
string_free(encoded_key_string, &encoded_key_len);
string_free(encoded_val_string, &encoded_val_len);
if (it->hh.next != NULL) {
strcat(output, "&");
}
}
outlet_symbol(urlp->storage.x_ob.ob_outlet, gensym(output));
string_free(output, &output_len);
}
void urlparams_add(t_urlparams *const urlp, const t_symbol *const sel, const int argc, t_atom *const argv) {
char key[MAXPDSTRING];
size_t value_len = 0;
char *value;
char temp_value[MAXPDSTRING];
(void) sel;
if (argc < 2) {
pd_error(urlp, "For method 'add' You need to specify a value.");
return;
}
atom_string(argv, key, MAXPDSTRING);
for (int i = 1; i < argc; i++) {
atom_string(argv + i, temp_value, MAXPDSTRING);
value_len += strlen(temp_value) + 1;
}
value = getbytes(value_len * sizeof(char));
atom_string(argv + 1, value, MAXPDSTRING);
for(int i = 2; i < argc; i++) {
atom_string(argv + i, temp_value, MAXPDSTRING);
strcat(value, " ");
strcat(value, temp_value);
}
kvp_add_simple((struct _kvp_store *)urlp, key, kvp_val_create(value, 0));
string_free(value, &value_len);
}
void urlparams_clear(t_urlparams *const urlp, const t_symbol *const sel, const int argc, const t_atom *const argv) {
(void) sel;
(void) argc;
(void) argv;
kvp_store_free_memory((struct _kvp_store *)urlp);
}
| 2.015625 | 2 |
2024-11-18T20:55:54.321262+00:00 | 2020-12-16T01:23:53 | 99d57d3997361de70d5be85aca9977a65a06003a | {
"blob_id": "99d57d3997361de70d5be85aca9977a65a06003a",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-16T01:23:53",
"content_id": "ce97d2861e96a51acf3bce6321778a56e28ce019",
"detected_licenses": [
"MIT"
],
"directory_id": "1f59e983476ccad5a39b7b00b0fc0eb2fab63d8c",
"extension": "c",
"filename": "ojparse.c",
"fork_events_count": 6,
"gha_created_at": "2014-05-22T19:51:11",
"gha_event_created_at": "2020-09-23T23:27:04",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 20074732,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4649,
"license": "MIT",
"license_type": "permissive",
"path": "/compare/oj/ojparse.c",
"provenance": "stackv2-0092.json.gz:53731",
"repo_name": "ohler55/ojc",
"revision_date": "2020-12-16T01:23:53",
"revision_id": "08f6420b34135a5017c1eefe142541b77748fd8f",
"snapshot_id": "d2ae70ff728e58b25cb0afb6a6611b4f9f66a346",
"src_encoding": "UTF-8",
"star_events_count": 28,
"url": "https://raw.githubusercontent.com/ohler55/ojc/08f6420b34135a5017c1eefe142541b77748fd8f/compare/oj/ojparse.c",
"visit_date": "2021-01-17T13:48:57.921292"
} | stackv2 | // Copyright (c) 2020 by Peter Ohler, ALL RIGHTS RESERVED
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "oj/oj.h"
#include "../helper.h"
typedef struct _mode {
const char *key;
void (*func)(const char *filename, long long iter);
} *Mode;
static void
form_result(long long iter, long long usec, ojErr err) {
if (OJ_OK == err->code) {
form_json_results("oj", iter, usec, NULL);
} else {
char msg[300];
snprintf(msg, sizeof(msg), "%s at %d:%d", err->msg, err->line, err->col);
form_json_results("oj", iter, usec, msg);
}
}
static int
walk(ojVal val) {
int cnt = 0;
switch (val->type) {
case OJ_NULL:
cnt++;
break;
case OJ_TRUE:
break;
case OJ_FALSE:
cnt++;
break;
case OJ_INT:
if (0 == val->num.fixnum) {
cnt++;
}
break;
case OJ_DECIMAL:
if (0.0 == val->num.dub) {
cnt++;
}
break;
case OJ_STRING:
if ('\0' == *val->str.raw) {
cnt++;
}
break;
case OJ_OBJECT:
if (OJ_OBJ_RAW == val->mod) {
for (ojVal v = val->list.head; NULL != v; v = v->next) {
cnt += walk(v);
}
} else {
ojVal *b = val->hash;
ojVal *bend = b + (sizeof(val->hash) / sizeof(*val->hash));
ojVal v;
for (; b < bend; b++) {
for (v = *b; NULL != v; v = v->next) {
cnt += walk(v);
}
}
}
break;
case OJ_ARRAY:
for (ojVal v = val->list.head; NULL != v; v = v->next) {
cnt += walk(v);
}
break;
}
return cnt;
}
// Single file parsing after loading into memory.
static void
validate(const char *filename, long long iter) {
int64_t dt;
char *buf = load_file(filename);
struct _ojErr err = OJ_ERR_INIT;
int64_t start = clock_micro();
for (int i = iter; 0 < i; i--) {
oj_validate_str(&err, buf);
}
dt = clock_micro() - start;
form_result(iter, dt, &err);
if (NULL != buf) {
free(buf);
}
}
static void
parse(const char *filename, long long iter) {
int64_t dt;
char *buf = load_file(filename);
int64_t start = clock_micro();
struct _ojReuser r;
struct _ojErr err = OJ_ERR_INIT;
for (int i = iter; 0 < i; i--) {
oj_parse_str(&err, buf, &r);
oj_reuse(&r);
}
dt = clock_micro() - start;
form_result(iter, dt, &err);
if (NULL != buf) {
free(buf);
}
}
typedef struct _cnt {
long long iter;
int depth;
} *Cnt;
static void
push_light(ojVal val, void *ctx) {
switch (val->type) {
case OJ_OBJECT:
case OJ_ARRAY:
((Cnt)ctx)->depth++;
break;
}
}
static void
pop_light(void *ctx) {
Cnt c = (Cnt)ctx;
c->depth--;
if (c->depth <= 0) {
c->iter++;
}
}
static void
parse_light(const char *filename, long long iter) {
int64_t dt;
struct _ojErr err = OJ_ERR_INIT;
struct _cnt c = { .depth = 0, .iter = 0 };
int64_t start = clock_micro();
oj_pp_parse_file(&err, filename, push_light, pop_light, &c);
dt = clock_micro() - start;
form_result(c.iter, dt, &err);
}
static ojCallbackOp
heavy_cb(ojVal val, void *ctx) {
int64_t done = clock_micro() + 8;
while (clock_micro() < done) {
continue;
}
walk(val);
*(long long*)ctx = *(long long*)ctx + 1;
return OJ_DESTROY;
}
static void
parse_heavy(const char *filename, long long iter) {
int64_t dt;
struct _ojErr err = OJ_ERR_INIT;
struct _ojCaller caller;
oj_caller_start(&err, &caller, heavy_cb, &iter);
oj_thread_safe = true;
iter = 0;
int64_t start = clock_micro();
oj_parse_file_call(&err, filename, &caller);
oj_caller_wait(&caller);
dt = clock_micro() - start;
form_result(iter, dt, &err);
}
static void
test(const char *filename, long long iter) {
char *buf = load_file(filename);
struct _ojErr err = OJ_ERR_INIT;
oj_validate_str(&err, buf);
// This also works:
//oj_destroy(oj_parse_str(&err, buf, NULL));
form_result(1, 0, &err);
if (NULL != buf) {
free(buf);
}
}
static struct _mode mode_map[] = {
{ .key = "validate", .func = validate },
{ .key = "parse", .func = parse },
{ .key = "multiple-light", .func = parse_light },
{ .key = "multiple-heavy", .func = parse_heavy },
{ .key = "test", .func = test },
{ .key = NULL },
};
int
main(int argc, char **argv) {
if (4 != argc) {
printf("{\"name\":\"oj\",\"err\":\"expected 3 arguments\"}\n");
exit(1);
}
const char *mode = argv[1];
const char *filename = argv[2];
long long iter = strtoll(argv[3], NULL, 10);
for (Mode m = mode_map; NULL != m->key; m++) {
if (0 == strcmp(mode, m->key)) {
m->func(filename, iter);
}
}
oj_cleanup();
return 0;
}
| 2.4375 | 2 |
2024-11-18T20:55:54.529965+00:00 | 2023-05-09T20:08:24 | b470ff6a86c86935b2fd0efb2523cb9e8fb788ef | {
"blob_id": "b470ff6a86c86935b2fd0efb2523cb9e8fb788ef",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-09T20:08:24",
"content_id": "e239d7398df9fde52af25e7c4827dac70a171658",
"detected_licenses": [
"MIT"
],
"directory_id": "b5d28de0f81d800758bc8234f265e5290bc303df",
"extension": "h",
"filename": "eepromType.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4457913,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 918,
"license": "MIT",
"license_type": "permissive",
"path": "/common/eeprom/eepromType.h",
"provenance": "stackv2-0092.json.gz:54121",
"repo_name": "f4deb/cen-electronic",
"revision_date": "2023-05-09T20:08:24",
"revision_id": "eadf1a839445b57bba0319ba54c30ce333f912f0",
"snapshot_id": "026c9b9d650487e70fde472cbbcf1a81ec9fe980",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/f4deb/cen-electronic/eadf1a839445b57bba0319ba54c30ce333f912f0/common/eeprom/eepromType.h",
"visit_date": "2023-05-09T23:58:02.262631"
} | stackv2 | #ifndef EEPROM_TYPE_H
#define EEPROM_TYPE_H
#include "../../common/io/outputStream.h"
/**
* Type of Eeprom.
*/
enum EepromType {
/**
* In Memory.
*/
EEPROM_TYPE_MEMORY,
/**
* Hardware Eeprom (Ex : 24C12).
*/
EEPROM_TYPE_HARDWARE,
/**
* File Eeprom (For PC for example)
*/
EEPROM_TYPE_FILE
};
/**
* Append the eeprom type as string in the outputStream.
* @param outputStream
* @param eepromType
* @return
*/
unsigned int appendEepromTypeAsString(OutputStream* outputStream, enum EepromType eepromType);
/**
* Append the eeprom type as string in the outputStream for a table data formatting.
* @param outputStream
* @param eepromType
* @param columnSize the size of the column
* @return
*/
unsigned int addEepromTypeTableData(OutputStream* outputStream, enum EepromType eepromType, int columnSize);
#endif | 2.203125 | 2 |
2024-11-18T20:55:54.945459+00:00 | 2023-07-24T19:33:23 | c665d69ae77bfde1ddb9c6c39eff5d92894fc0c1 | {
"blob_id": "c665d69ae77bfde1ddb9c6c39eff5d92894fc0c1",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-24T19:33:23",
"content_id": "378586e142d2b893b83797d2f77c7ca6b90e6695",
"detected_licenses": [
"MIT"
],
"directory_id": "8db4a0288bbf426b06e7081e06a622c1e5f3993c",
"extension": "c",
"filename": "objects.c",
"fork_events_count": 26,
"gha_created_at": "2014-06-15T18:44:10",
"gha_event_created_at": "2023-07-24T19:33:25",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 20862470,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14109,
"license": "MIT",
"license_type": "permissive",
"path": "/common/objects.c",
"provenance": "stackv2-0092.json.gz:54636",
"repo_name": "KnightOS/scas",
"revision_date": "2023-07-24T19:33:23",
"revision_id": "90a20d603e7c574843112ac98b34a659a612568b",
"snapshot_id": "61627f799c518c6fbe3d764dccfe66e90b020c73",
"src_encoding": "UTF-8",
"star_events_count": 28,
"url": "https://raw.githubusercontent.com/KnightOS/scas/90a20d603e7c574843112ac98b34a659a612568b/common/objects.c",
"visit_date": "2023-08-09T01:35:14.634264"
} | stackv2 | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include "list.h"
#include "stack.h"
#include "expression.h"
#include "objects.h"
#include "log.h"
#include "functions.h"
#include "readline.h"
#define SCASOBJ_VERSION 2
object_t *create_object(void) {
object_t *o = malloc(sizeof(object_t));
o->areas = create_list();
o->exports = create_list();
o->imports = create_list();
o->unresolved = create_list();
o->merged = false;
return o;
}
void object_free(object_t *o) {
for (unsigned int i = 0; i < o->areas->length; i += 1) {
area_t *area = (area_t*)o->areas->items[i];
if (o->merged) {
merged_area_free(area);
}
else {
area_free(area);
}
}
list_free(o->areas);
for (unsigned int i = 0; i < o->unresolved->length; i += 1) {
unresolved_symbol_t *u = (unresolved_symbol_t*)o->unresolved->items[i];
free(u->name);
free(u->line);
free(u->file_name);
free(u);
}
list_free(o->unresolved);
list_free(o->imports);
list_free(o->exports);
free(o);
}
area_t *create_area(const char *name) {
area_t *a = malloc(sizeof(area_t));
a->name = strdup(name);
a->late_immediates = create_list();
a->symbols = create_list();
a->source_map = create_list();
a->metadata = create_list();
a->final_address = 0;
a->data_length = 0;
a->data_capacity = 1024;
a->data = malloc(a->data_capacity);
return a;
}
void merged_area_free(area_t *area) {
for (unsigned int i = 0; i < area->metadata->length; ++i) {
metadata_t *meta = area->metadata->items[i];
free(meta->key);
free(meta->value);
free(meta);
}
list_free(area->metadata);
list_free(area->source_map);
list_free(area->symbols);
list_free(area->late_immediates);
free(area->name);
free(area->data);
free(area);
}
void area_free(area_t *area) {
for (unsigned int i = 0; i < area->metadata->length; ++i) {
metadata_t *meta = area->metadata->items[i];
free(meta->key);
free(meta->value);
free(meta);
}
list_free(area->metadata);
for (unsigned int i = 0; i < area->source_map->length; i += 1) {
source_map_free((source_map_t*)area->source_map->items[i]);
}
list_free(area->source_map);
for (unsigned int i = 0; i < area->symbols->length; i += 1) {
symbol_t *sym = (symbol_t*)area->symbols->items[i];
free(sym->name);
free(sym);
}
list_free(area->symbols);
for (unsigned int i = 0; i < area->late_immediates->length; i += 1) {
late_immediate_t *imm = (late_immediate_t *)area->late_immediates->items[i];
free_expression(imm->expression);
free(imm);
}
list_free(area->late_immediates);
free(area->name);
free(area->data);
free(area);
}
metadata_t *get_area_metadata(area_t *area, const char *key) {
for (unsigned int i = 0; i < area->metadata->length; ++i) {
metadata_t *meta = area->metadata->items[i];
if (strcmp(meta->key, key) == 0) {
return meta;
}
}
return NULL;
}
void set_area_metadata(area_t *area, const char *key, char *value, uint64_t value_length) {
bool dupe = true;
for (unsigned int i = 0; i < area->metadata->length; ++i) {
metadata_t *meta = area->metadata->items[i];
if (strcmp(meta->key, key) == 0) {
free(meta->key);
if (meta->value != value) {
free(meta->value);
}
else {
dupe = false;
}
free(meta);
list_del(area->metadata, i);
break;
}
}
metadata_t *newmeta = malloc(sizeof(metadata_t));
newmeta->key = strdup(key);
newmeta->value_length = value_length;
if (dupe) {
newmeta->value = malloc(value_length);
memcpy(newmeta->value, value, value_length);
}
else {
newmeta->value = value;
}
scas_log(L_DEBUG, "Set area metadata '%s' to new value with length %d", newmeta->key, newmeta->value_length);
list_add(area->metadata, newmeta);
}
void append_to_area(area_t *area, uint8_t *data, size_t length) {
while ((area->data_capacity - area->data_length) < length) {
/* Expand capacity */
area->data = realloc(area->data, area->data_capacity + 1024);
area->data_capacity += 1024;
}
memcpy(area->data + area->data_length, data, length);
area->data_length += length;
scas_log(L_DEBUG, "Added %d bytes to area '%s' (now %d bytes total)", length, area->name, area->data_length);
}
void insert_in_area(area_t *area, uint8_t *data, size_t length, size_t index) {
while (area->data_capacity < length + area->data_length) {
/* Expand capacity */
area->data = realloc(area->data, area->data_capacity + 1024);
area->data_capacity += 1024;
}
memmove(area->data + index + length, area->data + index, area->data_length - index);
memcpy(area->data + index, data, length);
area->data_length += length;
scas_log(L_DEBUG, "Inserted %d bytes in area '%s' (now %d bytes total)", length, area->name, area->data_length);
}
void delete_from_area(area_t *area, size_t index, size_t length) {
scas_log(L_DEBUG, "Removing %d bytes at %08X from area '%s'", length, index, area->name);
memmove(area->data + index, area->data + index + length, area->data_length - (index + length));
area->data_length -= length;
}
void write_area(FILE *f, area_t *a) {
uint32_t len;
uint64_t len64;
unsigned int i;
fprintf(f, "%s", a->name); fputc(0, f);
/* Symbols */
fwrite(&a->symbols->length, sizeof(uint32_t), 1, f);
for (i = 0; i < a->symbols->length; ++i) {
symbol_t *sym = a->symbols->items[i];
fputc(sym->exported, f);
len = strlen(sym->name);
fwrite(&len, sizeof(uint32_t), 1, f);
fprintf(f, "%s", sym->name);
fwrite(&sym->value, sizeof(uint64_t), 1, f);
fwrite(&sym->defined_address, sizeof(uint64_t), 1, f);
}
/* Imports (TODO) */
/* Expressions */
fwrite(&a->late_immediates->length, sizeof(uint32_t), 1, f);
for (i = 0; i < a->late_immediates->length; ++i) {
late_immediate_t *imm = a->late_immediates->items[i];
fputc(imm->type, f);
fputc(imm->width, f);
fwrite(&imm->instruction_address, sizeof(uint64_t), 1, f);
fwrite(&imm->base_address, sizeof(uint64_t), 1, f);
fwrite(&imm->address, sizeof(uint64_t), 1, f);
fwrite_tokens(f, imm->expression);
}
/* Machine code */
fwrite(&a->data_length, sizeof(uint64_t), 1, f);
fwrite(a->data, sizeof(uint8_t), a->data_length, f);
/* Metadata */
fwrite(&a->metadata->length, sizeof(uint64_t), 1, f);
for (i = 0; i < a->metadata->length; ++i) {
metadata_t *meta = a->metadata->items[i];
fputc((uint8_t)strlen(meta->key), f);
fwrite(meta->key, sizeof(char), strlen(meta->key), f);
fwrite(&meta->value_length, sizeof(uint64_t), 1, f);
fwrite(meta->value, sizeof(char), meta->value_length, f);
}
/* Source map */
fwrite(&a->source_map->length, sizeof(uint64_t), 1, f);
for (i = 0; i < a->source_map->length; ++i) {
source_map_t *map = a->source_map->items[i];
fwrite(map->file_name, sizeof(char), strlen(map->file_name), f);
fputc(0, f);
len64 = map->entries->length;
fwrite(&len64, sizeof(uint64_t), 1, f);
for (unsigned int j = 0; j < map->entries->length; ++j) {
source_map_entry_t *entry = map->entries->items[j];
fwrite(&entry->line_number, sizeof(uint64_t), 1, f);
fwrite(&entry->address, sizeof(uint64_t), 1, f);
fwrite(&entry->length, sizeof(uint64_t), 1, f);
fwrite(entry->source_code, sizeof(char), strlen(entry->source_code), f);
fputc(0, f);
}
}
}
void fwriteobj(FILE *f, object_t *o) {
/* Header */
fprintf(f, "SCASOBJ");
fputc(SCASOBJ_VERSION, f);
/* Areas */
uint32_t a_len = o->areas->length;
fwrite(&a_len, sizeof(uint32_t), 1, f);
for (unsigned int i = 0; i < o->areas->length; ++i) {
area_t *a = o->areas->items[i];
write_area(f, a);
}
fflush(f);
}
area_t *read_area(FILE *f) {
char *name = read_line(f);
area_t *area = create_area(name);
scas_log(L_DEBUG, "Reading area '%s' from file", name);
free(name);
uint32_t symbols, immediates;
if (fread(&symbols, 1, sizeof(uint32_t), f) != sizeof(uint32_t)) {
scas_log(L_ERROR, "Failed to read area from file");
area_free(area);
return NULL;
}
uint32_t len;
for (uint32_t i = 0; i < symbols; ++i) {
symbol_t *sym = malloc(sizeof(symbol_t));
sym->exported = fgetc(f);
if (fread(&len, sizeof(uint32_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
sym->name = calloc(len + 1, sizeof(char));
if (fread(sym->name, 1, len, f) != len) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
if (fread(&sym->value, 1, sizeof(uint64_t), f) != sizeof(uint64_t)) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
if (fread(&sym->defined_address, 1, sizeof(uint64_t), f) != sizeof(uint64_t)) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
sym->type = SYMBOL_LABEL;
list_add(area->symbols, sym);
scas_log(L_DEBUG, "Read symbol '%s' with value 0x%08X%08X", sym->name, (uint32_t)(sym->value >> 32), (uint32_t)sym->value);
}
/* TODO: Imports */
if (fread(&immediates, 1, sizeof(uint32_t), f) != sizeof(uint32_t)) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
for (uint32_t i = 0; i < immediates; ++i) {
late_immediate_t *imm = malloc(sizeof(late_immediate_t));
imm->type = fgetc(f);
imm->width = fgetc(f);
if (fread(&imm->instruction_address, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
if (fread(&imm->base_address, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
if (fread(&imm->address, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
imm->expression = fread_tokenized_expression(f);
list_add(area->late_immediates, imm);
scas_log(L_DEBUG, "Read immediate value at 0x%08X (width: %d)", imm->address, imm->width);
}
if (fread(&area->data_length, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
area->data_capacity = area->data_length;
free(area->data);
area->data = malloc(area->data_length);
if (fread(area->data, 1, area->data_length, f) != area->data_length) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
scas_log(L_DEBUG, "Read %d bytes of machine code", area->data_length);
uint64_t meta_length, meta_key;
if (fread(&meta_length, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
meta_length = (int)meta_length;
scas_log(L_DEBUG, "Reading %d metadata entries", meta_length);
for (uint64_t i = 0; i < meta_length; ++i) {
scas_log(L_DEBUG, "Reading metadata entry %lld of %lld", i, meta_length);
metadata_t *meta = malloc(sizeof(metadata_t));
meta_key = fgetc(f);
meta->key = malloc(meta_key + 1);
meta->key[meta_key] = 0;
if (fread(meta->key, sizeof(char), meta_key, f) != meta_key) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
if (fread(&meta->value_length, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
meta->value = malloc(meta->value_length + 1);
meta->value[meta->value_length] = 0;
if (fread(meta->value, sizeof(char), meta->value_length, f) != meta->value_length) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
list_add(area->metadata, meta);
scas_log(L_DEBUG, "Read metadata %s with value length %d", meta->key, meta->value_length);
}
uint64_t fileno, lineno;
if (fread(&fileno, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
fileno = (int)fileno;
for (uint64_t i = 0; i < fileno; ++i) {
source_map_t *map = malloc(sizeof(source_map_t));
map->file_name = read_line(f);
map->entries = create_list();
if (fread(&lineno, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
scas_log(L_DEBUG, "Reading source map for '%s', %d entries", map->file_name, lineno);
for (uint64_t j = 0; j < lineno; ++j) {
source_map_entry_t *entry = malloc(sizeof(source_map_entry_t));
if (fread(&entry->line_number, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
if (fread(&entry->address, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
if (fread(&entry->length, sizeof(uint64_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
entry->source_code = read_line(f);
list_add(map->entries, entry);
scas_log(L_DEBUG, "Read entry at 0x%08X%08X (line %d): %s", (uint32_t)(entry->address >> 32), (uint32_t)entry->address, entry->line_number, entry->source_code);
}
list_add(area->source_map, map);
}
return area;
}
object_t *freadobj(FILE *f, const char *name) {
char magic[7];
int len = fread(magic, sizeof(char), 7, f);
if (len != 7 || strncmp("SCASOBJ", magic, 7) != 0) {
scas_log(L_ERROR, "'%s' is not a valid object file.", name);
return NULL;
}
int ver = fgetc(f);
if (ver != SCASOBJ_VERSION) {
scas_log(L_ERROR, "'%s' was built with an incompatible version of scas.", name);
return NULL;
}
uint32_t area_count;
if (fread(&area_count, sizeof(uint32_t), 1, f) != 1) {
scas_log(L_ERROR, "Failed to read in data!");
return NULL;
}
object_t *o = create_object();
for (uint32_t i = 0; i < area_count; ++i) {
list_add(o->areas, read_area(f));
}
return o;
}
source_map_t *create_source_map(area_t *area, const char *file_name) {
source_map_t *map = malloc(sizeof(source_map_t));
map->file_name = strdup(file_name);
map->entries = create_list();
list_add(area->source_map, map);
return map;
}
void source_map_free(source_map_t *map) {
for (unsigned int i = 0; i < map->entries->length; i += 1) {
source_map_entry_t *entry = (source_map_entry_t*)map->entries->items[i];
free(entry->source_code);
free(entry);
}
list_free(map->entries);
free(map->file_name);
free(map);
}
void add_source_map(source_map_t *map, int line_number, const char *line, uint64_t address, uint64_t length) {
source_map_entry_t *entry = malloc(sizeof(source_map_entry_t));
entry->line_number = line_number;
entry->address = address;
entry->length = length;
entry->source_code = strdup(line);
list_add(map->entries, entry);
}
| 2.140625 | 2 |
2024-11-18T20:55:55.897625+00:00 | 2023-08-18T12:54:06 | 43914c95c6ae4eadc4450c8080308b76662a7a61 | {
"blob_id": "43914c95c6ae4eadc4450c8080308b76662a7a61",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-18T12:54:06",
"content_id": "1e05bcfd09350d928c34257c87255172f8d5e8b1",
"detected_licenses": [
"MIT"
],
"directory_id": "22446075c2e71ef96b4a4777fe966714ac96b405",
"extension": "c",
"filename": "main.c",
"fork_events_count": 68,
"gha_created_at": "2020-09-30T10:18:15",
"gha_event_created_at": "2023-09-08T12:56:11",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 299882138,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3331,
"license": "MIT",
"license_type": "permissive",
"path": "/clicks/dcmotor3/example/main.c",
"provenance": "stackv2-0092.json.gz:55417",
"repo_name": "MikroElektronika/mikrosdk_click_v2",
"revision_date": "2023-08-18T12:54:06",
"revision_id": "49ab937390bef126beb7b703d5345fa8cd6e3555",
"snapshot_id": "2cc2987869649a304763b0f9d27c920d42a11c16",
"src_encoding": "UTF-8",
"star_events_count": 77,
"url": "https://raw.githubusercontent.com/MikroElektronika/mikrosdk_click_v2/49ab937390bef126beb7b703d5345fa8cd6e3555/clicks/dcmotor3/example/main.c",
"visit_date": "2023-08-21T22:15:09.036635"
} | stackv2 | /*!
* @file
* @brief DcMotor3 Click example
*
* # Description
* This click has four operating modes: clockwise, counter-clockwise, short brake and stop.
* The operating mode is configured through IN1 and IN2 pins.
*
* The demo application is composed of two sections :
*
* ## Application Init
* Initialization driver enable's - GPIO,
* PWM initialization, set PWM duty cycle and PWM frequency, start PWM, enable the engine, and start write log.
*
* ## Application Task
* This is a example which demonstrates the use of DC Motor 3 Click board.
* DC Motor 3 Click communicates with register via PWM interface.
* It shows moving in the left direction from slow to fast speed
* and from fast to slow speed.
* Results are being sent to the Usart Terminal where you can track their changes.
*
*
* @author Nikola Peric
*
*/
// ------------------------------------------------------------------- INCLUDES
#include "board.h"
#include "log.h"
#include "dcmotor3.h"
// ------------------------------------------------------------------ VARIABLES
static dcmotor3_t dcmotor3;
static log_t logger;
uint8_t dcmotor3_direction = 1;
// ------------------------------------------------------ APPLICATION FUNCTIONS
void application_init ( void )
{
log_cfg_t log_cfg;
dcmotor3_cfg_t cfg;
/**
* Logger initialization.
* Default baud rate: 115200
* Default log level: LOG_LEVEL_DEBUG
* @note If USB_UART_RX and USB_UART_TX
* are defined as HAL_PIN_NC, you will
* need to define them manually for log to work.
* See @b LOG_MAP_USB_UART macro definition for detailed explanation.
*/
LOG_MAP_USB_UART( log_cfg );
log_init( &logger, &log_cfg );
log_info( &logger, "---- Application Init ----" );
// Click initialization.
dcmotor3_cfg_setup( &cfg );
DCMOTOR3_MAP_MIKROBUS( cfg, MIKROBUS_1 );
dcmotor3_init( &dcmotor3, &cfg );
dcmotor3_set_duty_cycle ( &dcmotor3, 0.0 );
dcmotor3_pwm_start( &dcmotor3 );
Delay_ms( 1000 );
dcmotor3_enable( &dcmotor3 );
Delay_ms( 1000 );
log_info( &logger, "---- Application Task ----" );
}
void application_task ( void )
{
static int8_t duty_cnt = 1;
static int8_t duty_inc = 1;
float duty = duty_cnt / 10.0;
if ( dcmotor3_direction == 1 )
{
dcmotor3_clockwise( &dcmotor3 );
log_printf( &logger, ">>>> CLOCKWISE " );
dcmotor3_enable ( &dcmotor3 );
}
else
{
dcmotor3_counter_clockwise( &dcmotor3 );
log_printf( &logger, "<<<< COUNTER CLOCKWISE " );
dcmotor3_enable ( &dcmotor3 );
}
dcmotor3_set_duty_cycle ( &dcmotor3, duty );
log_printf( &logger, "Duty: %d%%\r\n", ( uint16_t )( duty_cnt * 10 ) );
Delay_ms( 500 );
if ( 10 == duty_cnt )
{
duty_inc = -1;
}
else if ( 0 == duty_cnt )
{
duty_inc = 1;
if ( dcmotor3_direction == 1 )
{
dcmotor3_direction = 0;
}
else if ( dcmotor3_direction == 0 )
{
dcmotor3_direction = 1;
}
}
duty_cnt += duty_inc;
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
| 2.796875 | 3 |
2024-11-18T20:55:56.169384+00:00 | 2020-05-22T23:26:08 | 84a90c6d31f4cdb662bb89aa0bf1fc888fedf76e | {
"blob_id": "84a90c6d31f4cdb662bb89aa0bf1fc888fedf76e",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-22T23:26:08",
"content_id": "bdaa0ff5b4a806aa084993933b8e15499fbd2d80",
"detected_licenses": [
"MIT"
],
"directory_id": "e7f6780e525434e27c90617b8119cb9406b79970",
"extension": "c",
"filename": "ex9.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 264542293,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 454,
"license": "MIT",
"license_type": "permissive",
"path": "/lista1/ex9.c",
"provenance": "stackv2-0092.json.gz:55677",
"repo_name": "Vitao18/C-exercises",
"revision_date": "2020-05-22T23:26:08",
"revision_id": "121aec31978ee197523a2923ab26a37a38b768fd",
"snapshot_id": "86e0855ba4cc2b780f306d8ffd6b144cbcf4131b",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Vitao18/C-exercises/121aec31978ee197523a2923ab26a37a38b768fd/lista1/ex9.c",
"visit_date": "2022-08-16T14:34:26.533085"
} | stackv2 | #include <stdio.h>
int main() {
int n, i, j, cont = 0, atual = 0;
printf("Entre com um número n maior que zero: \n");
scanf("%d", &n);
printf("Entre com um número i maior que zero: \n");
scanf("%d", &i);
printf("Entre com um número j maior que zero: \n");
scanf("%d", &j);
printf("\n");
while(n > cont) {
if ((atual % i == 0) || (atual % j == 0)) {
cont++;
printf("%d\n", atual);
}
atual++;
}
return 0;
} | 3.578125 | 4 |
2024-11-18T20:55:56.243183+00:00 | 2019-08-11T03:44:42 | f2eb73bc2bbe68c98fa47ffdca279231ddb0875c | {
"blob_id": "f2eb73bc2bbe68c98fa47ffdca279231ddb0875c",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-11T03:44:42",
"content_id": "49ba21e317f17ae67659cbf3b17ee9c31e6b3af0",
"detected_licenses": [
"MIT"
],
"directory_id": "33965b05f7816f45a28757d9c7c59685366d29ea",
"extension": "h",
"filename": "oled.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": 1108,
"license": "MIT",
"license_type": "permissive",
"path": "/oled.h",
"provenance": "stackv2-0092.json.gz:55805",
"repo_name": "ksadil/stacx",
"revision_date": "2019-08-11T03:44:42",
"revision_id": "c1bcd21dc8f6d45fe1c4265b0da3df310f572080",
"snapshot_id": "2ae9dd0e463765f0bb0d786860b719f9b1875bfb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ksadil/stacx/c1bcd21dc8f6d45fe1c4265b0da3df310f572080/oled.h",
"visit_date": "2022-02-11T01:11:07.210215"
} | stackv2 | #pragma once
#include <SSD1306Wire.h>
SSD1306Wire *_oled = NULL;
int oled_textheight = 10;
void oled_text(int column, int row, const char *text) ;
void oled_setup(void)
{
NOTICE("OLED setup");
_oled = new SSD1306Wire(0x3c, 21, 22);
_oled->init();
Wire.setClock(100000);
_oled->clear();
_oled->display();
_oled->flipScreenVertically();
_oled->setFont(ArialMT_Plain_10);
_oled->setTextAlignment(TEXT_ALIGN_LEFT);
oled_text(0,0,"Accelerando.io Stacx");
}
void oled_text(int column, int row, const char *text)
{
INFO("TEXT @[%d,%d]: %s", row, column, text);
OLEDDISPLAY_COLOR textcolor = _oled->getColor();
_oled->setColor(BLACK);
int textwidth = _oled->getStringWidth(text);
INFO("blanking %d,%d %d,%d for %s", column, row, oled_textheight+1, textwidth, text);
_oled->fillRect(column, row, textwidth, oled_textheight);
_oled->setColor(textcolor);
_oled->drawString(column, row, text);
_oled->display();
}
void oled_text(int column, int row, String text)
{
oled_text(column, row, text.c_str());
}
// Local Variables:
// mode: C++
// c-basic-offset: 2
// End:
| 2.21875 | 2 |
2024-11-18T20:55:56.319134+00:00 | 2021-08-21T14:29:18 | d1b407744638d3b371c3d70046c53bef9028b3f0 | {
"blob_id": "d1b407744638d3b371c3d70046c53bef9028b3f0",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-21T14:29:18",
"content_id": "5cd4f0810c905dfd5cddd061cf75f0413612a42a",
"detected_licenses": [
"MIT"
],
"directory_id": "ea4da2134621c1dd84ba62d6a28aa98f47697196",
"extension": "h",
"filename": "Triangle.h",
"fork_events_count": 2,
"gha_created_at": "2021-06-30T09:26:36",
"gha_event_created_at": "2021-08-21T14:29:18",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 381646128,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2409,
"license": "MIT",
"license_type": "permissive",
"path": "/headers/Triangle.h",
"provenance": "stackv2-0092.json.gz:55934",
"repo_name": "WHN-We-Hate-Nisan/ourBetterGraphics_eyy_.h",
"revision_date": "2021-08-21T14:29:18",
"revision_id": "11d6a5e58b83f78b9a59012841674111aa153438",
"snapshot_id": "2628fdffd865134ef71f6154c19ddcc73911a8e3",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/WHN-We-Hate-Nisan/ourBetterGraphics_eyy_.h/11d6a5e58b83f78b9a59012841674111aa153438/headers/Triangle.h",
"visit_date": "2023-07-15T00:47:52.552198"
} | stackv2 | #pragma once
#include"Essentials.h"
#include "Texture.h"
struct Vertex {
Vec3 position;
Vec2 textureCood;
Vec3 normal;
float intensity;
Color color;
};
struct Triangle {
Vertex vertex[3];
Triangle operator+(const Vec3& right) {
Triangle tri(*this);
tri.vertex[0].position += right;
tri.vertex[1].position += right;
tri.vertex[2].position += right;
return tri;
}
Triangle& operator+=(const Vec3& right) {
this->vertex[0].position += right;
this->vertex[1].position += right;
this->vertex[2].position += right;
return *this;
}
Triangle operator*(const Vec3& right) {
Triangle tri(*this);
tri.vertex[0].position.multiplyEach(right);
tri.vertex[1].position.multiplyEach(right);
tri.vertex[2].position.multiplyEach(right);
return tri;
}
Triangle& operator*=(const Vec3& right) {
this->vertex[0].position.multiplyEach(right);
this->vertex[1].position.multiplyEach(right);
this->vertex[2].position.multiplyEach(right);
return *this;
}
Triangle operator/(const float& right) {
Triangle tri(*this);
tri.vertex[0].position /= right;
tri.vertex[1].position /= right;
tri.vertex[2].position /= right;
return tri;
}
Triangle& operator/=(const float& right) {
this->vertex[0].position /= right;
this->vertex[1].position /= right;
this->vertex[2].position /= right;
return *this;
}
Vec3 normal() {
return ((vertex[1].position - vertex[0].position) * (vertex[2].position - vertex[0].position)).normalize();
}
Color avgColor() {
return (vertex[0].color / 3 + vertex[1].color / 3 + vertex[2].color / 3);
}
Triangle& normalize() {
for (int i = 0; i < 3; i++)
vertex[i].position /= vertex[i].position.w;
return *this;
}
};
int ClipAgainstPlane(Vec3, Vec3, Triangle&, Triangle&, Triangle&);
void DrawTriangle(Triangle&, Color = 0xffffff);
void ColorTriangle(Triangle&, Color, Vec3 = { 0.0f,0.0f,0.0f });
void ShadeTriangle(Triangle&, Vec3 = { 0.0f,0.0f,0.0f });
void TextureTriangle(Triangle&, Texture*);
void DrawHorizLine(int, int, int, Color, Vec3 = { 0, 0, 0 });
void DrawHorizLineShaded(int, int, int, Triangle, Vec3 = { 0, 0, 0 });
//void DrawHorizLineShaded(int, int, int, unsigned char, unsigned char, Vec3 );
//void DrawHorizTexture(float, float, float, float&, float&, float, float, float, float, Texture*);
void DrawHorizTexture(float, float, float, float&, float&, float&, float, float, float, float,
float, float, Texture*); | 2.28125 | 2 |
2024-11-18T20:55:56.419479+00:00 | 2017-04-03T13:49:33 | 304e9af1289b9601bed36811b6bafd498ed989bd | {
"blob_id": "304e9af1289b9601bed36811b6bafd498ed989bd",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-03T13:49:33",
"content_id": "6f6757df028551847fcbaf068734a5dd9e5dd7b7",
"detected_licenses": [
"MIT"
],
"directory_id": "67256cb243ac85568dd351ee8ed843cc9d35cd95",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2017-04-04T15:54:36",
"gha_event_created_at": "2017-04-04T15:54:36",
"gha_language": null,
"gha_license_id": null,
"github_id": 87206759,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3651,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0092.json.gz:56062",
"repo_name": "gaca1111/GGButton",
"revision_date": "2017-04-03T13:49:33",
"revision_id": "c01676fe33e7269cce818a661546cac5df91869a",
"snapshot_id": "4c33ecee52bc5c79bd0ea70389e8a5b3357e0e7c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gaca1111/GGButton/c01676fe33e7269cce818a661546cac5df91869a/main.c",
"visit_date": "2021-01-19T00:44:41.730591"
} | stackv2 | #include "stm32f4xx_conf.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_tim.h"
#include "stm32f4xx_exti.h"
#include "stm32f4xx_syscfg.h"
#include "misc.h"
#include "stm32f4xx_spi.h"
#include "SPI.h"
#include "przyciski.h"
#include "debouncer.h"
#include "ff.h"
#include "diskio.h"
int main(void)
{
SystemInit();
//RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
Konfiguracja_SPI();
Konfiguracja_przyciskow();
Konfiguracja_debouncera();
FRESULT fresult;
FIL plik;
WORD zapisanych_bajtow;
FATFS fatfs;
disk_initialize(0);// inicjalizacja karty
fresult = f_mount( &fatfs, 1,1 );// zarejestrowanie dysku logicznego w systemie
// Tworzenie pliku
fresult = f_open (&plik,"xdd.txt", FA_CREATE_ALWAYS);
fresult = f_close (&plik);
// Tworzenie katalogu
fresult = f_mkdir("aaaaaa");
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
GPIO_InitTypeDef diody;
diody.GPIO_Pin = GPIO_Pin_12;
diody.GPIO_Mode = GPIO_Mode_OUT;
diody.GPIO_OType = GPIO_OType_PP;
diody.GPIO_Speed = GPIO_Speed_100MHz;
diody.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &diody);
//
while(1)
{
}
}
void EXTI1_IRQHandler ( void ){
if (EXTI_GetITStatus(EXTI_Line1) != RESET){
TIM_Cmd(TIM3, ENABLE);
}
}
void EXTI2_IRQHandler ( void ){
if (EXTI_GetITStatus(EXTI_Line2) != RESET){
TIM_Cmd(TIM3, ENABLE);
}
}
void EXTI3_IRQHandler ( void ){
if (EXTI_GetITStatus(EXTI_Line3) != RESET){
TIM_Cmd(TIM3, ENABLE);
}
}
void EXTI4_IRQHandler ( void ){
if (EXTI_GetITStatus(EXTI_Line4) != RESET){
TIM_Cmd(TIM3, ENABLE);
}
}
void EXTI9_5_IRQHandler ( void ){
if (EXTI_GetITStatus(EXTI_Line5) |
EXTI_GetITStatus(EXTI_Line6) |
EXTI_GetITStatus(EXTI_Line7) |
EXTI_GetITStatus(EXTI_Line8) |
EXTI_GetITStatus(EXTI_Line9) != RESET){
TIM_Cmd(TIM3, ENABLE);
}
}
void TIM3_IRQHandler ( void ){
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET){
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_2)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_3)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_4)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_6)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_7)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_9)){
GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
TIM_Cmd(TIM3, DISABLE);
TIM3->CNT = 0;
}
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
EXTI_ClearITPendingBit(EXTI_Line1);
EXTI_ClearITPendingBit(EXTI_Line2);
EXTI_ClearITPendingBit(EXTI_Line3);
EXTI_ClearITPendingBit(EXTI_Line4);
EXTI_ClearITPendingBit(EXTI_Line5);
EXTI_ClearITPendingBit(EXTI_Line6);
EXTI_ClearITPendingBit(EXTI_Line7);
EXTI_ClearITPendingBit(EXTI_Line8);
EXTI_ClearITPendingBit(EXTI_Line9);
}
}
| 2.234375 | 2 |
2024-11-18T20:55:56.599219+00:00 | 2020-02-26T09:38:51 | 144db15b09822e0eaabc5f2ba2e857abd9a3190b | {
"blob_id": "144db15b09822e0eaabc5f2ba2e857abd9a3190b",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-26T09:38:51",
"content_id": "d19a94dc91f69f9938864306d22b0599163a74bb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "453530eb47dacba94eb4fe04b14fb9d4a6e85375",
"extension": "c",
"filename": "cmdline(1812).c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 242489306,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6955,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/bsp/gd32403/SI/rt-thread.si4project/Backup/cmdline(1812).c",
"provenance": "stackv2-0092.json.gz:56320",
"repo_name": "lane-ehuandian/test",
"revision_date": "2020-02-26T09:38:51",
"revision_id": "9f717d8dab9e6fd3f66365046d1033b00cdfe26f",
"snapshot_id": "f79059f1240d6387d47da6b5fa5edf6c02eb2d70",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lane-ehuandian/test/9f717d8dab9e6fd3f66365046d1033b00cdfe26f/bsp/gd32403/SI/rt-thread.si4project/Backup/cmdline(1812).c",
"visit_date": "2021-01-13T20:52:20.180942"
} | stackv2 | #include "common.h"
#ifdef CONFIG_CMDLINE
#include "cmdline.h"
#include <stdarg.h>
extern int str_htoi(const char *s);
/*
支持的命令格式如下:
Test(1,2,3,4,5) 最多支持输入5个参数
Test(1,2,0x3,4,"str")
Test 1
Test 1 "str"
支持简写输入
*/
static CmdLine g_CmdLine;
#if 0
#define CmdLine_Strtok strtok
#else
char* CmdLine_Strtok(char* pSrc, const char* delim)
{
static char* p = 0;
char* pRet = Null;
if(pSrc)
{
p = pSrc;
}
if(*p == 0)
{
pRet = Null;
goto End;
}
pRet = p;
//优先把字符串找出来
if(*p == '"') //第一个'"'
{
p++;
while(*p++ != '"')
{
if(*p == 0)
{
pRet = Null;
goto End;
}
}
if(*p != 0)
{
*p++ = 0;
}
goto End;
}
while(*p)
{
const char* pByte = delim;
for(pByte = delim; *pByte != 0; pByte++)
{
if(*p == *pByte)
{
*p++ = 0;
goto End;
}
}
p++;
}
End:
return pRet;
}
#endif
int CmdLine_Printf(const char* lpszFormat, ...)
{
int nLen = 0;
va_list ptr;
char g_Pfbuffer[128];
//LOCK();
memset(g_Pfbuffer, 0, sizeof(g_Pfbuffer));
va_start(ptr, lpszFormat);
nLen = _vsnprintf(g_Pfbuffer, sizeof(g_Pfbuffer), lpszFormat, ptr);
va_end(ptr);
if(g_CmdLine.printf) g_CmdLine.printf(g_Pfbuffer);
//UNLOCK();
return nLen;
}
void CmdLine_Help()
{
int i = 0;
const FnDef* pFnDef = g_CmdLine.m_FnArray;
for(i = 0; i < g_CmdLine.m_FnCount; i++, pFnDef++)
{
CmdLine_Printf("\t %s\n", pFnDef->m_Title);
}
}
ArgType CmdLine_GetArgType(const char* argStr)
{
int nLen = strlen(argStr);
if(Null == argStr) return ARGT_NONE;
if(*argStr == '\"')
{
if('\"' == argStr[nLen-1])
{
return ARGT_STR;
}
else
{
return ARGT_ERROR;
}
}
else if(argStr[0] == '0' && (argStr[1] == 'x' || argStr[1] == 'X'))
{
return ARGT_HEX;
}
else
{
return ARGT_DEC;
}
}
Bool CmdLine_Parse(char* cmdLineStr, char** pFnName, char* pArgs[], int* argCount)
{
int maxArgCount = *argCount;
char *token;
char fnNameseps[] = " (\n";
char argSeps[] = ", )\n";
//Find function name
token = CmdLine_Strtok(cmdLineStr, fnNameseps);
if(Null == token) return False;
*pFnName = token;
*argCount= 0;
token = CmdLine_Strtok( NULL, argSeps);
while( token != NULL )
{
pArgs[(*argCount)++] = token;
if((*argCount) > maxArgCount)
{
CmdLine_Printf("PF_ERROR: Arg count is too many\n");
return False;
}
token = CmdLine_Strtok( NULL, argSeps);
}
return True;
}
Bool CmdLine_ArgConvert(char* pArgs[], int argCount, uint32 arg[])
{
int i = 0;
ArgType at = ARGT_NONE;
char* pChar = Null;
for(i = 0; i < argCount; i++)
{
at = CmdLine_GetArgType(pArgs[i]);
if(ARGT_DEC == at)
{
arg[i] = atoi(pArgs[i]);
}
else if(ARGT_HEX == at)
{
arg[i] = str_htoi(pArgs[i]);
}
else if(ARGT_STR == at)
{
pChar = pArgs[i];
pChar[strlen(pChar) - 1] = 0;
pChar++;
arg[i] = (uint32)pChar;
}
else
{
CmdLine_Printf("\tArg[%d](%s) error. \n", i+1, pArgs[i]);
return False;
}
}
return True;
}
void CmdLine_Exe(CmdLine* pCmdLine, const char* pFnName, uint32 arg[], int argCount)
{
Bool isFind = 0;
int i = 0;
const FnDef* pFnEntry = pCmdLine->m_FnArray;
const FnDef* pFoundEntry = Null;
#define FUN(n, funType, args) if(n == pFoundEntry->m_ArgCount) \
{ \
((funType)pFoundEntry->pFn) args; \
return; \
}
for(i = 0; i < pCmdLine->m_FnCount; i++, pFnEntry++)
{
if(strcmp(pFnName, "?") == 0)
{
CmdLine_Help();
return;
}
//和函数名部分比较
if(strstr(pFnEntry->m_Title, pFnName) == pFnEntry->m_Title)
{
char* str;
isFind++;
if(Null == pFoundEntry)
pFoundEntry = pFnEntry;
//查找函数名
str = strchr(pFnEntry->m_Title, '(');
if(Null == str)
str = strchr(pFnEntry->m_Title, ' ');
if(Null == str) continue;
//和函数名完全比较
if(memcmp(pFnEntry->m_Title, pFnName, str - pFnEntry->m_Title) == 0)
{
isFind = 1;
pFoundEntry = pFnEntry;
break;
}
}
}
if(0 == isFind)
{
CmdLine_Printf("Unknown: %s\n", pFnName);
return;
}
else if(isFind > 1)
{
//如果找出的函数名多于一个,则打印所有的部分比较正确的函数名
pFnEntry = pCmdLine->m_FnArray;
for(i = 0; i < pCmdLine->m_FnCount; i++, pFnEntry++)
{
if(strstr(pFnEntry->m_Title, pFnName) == pFnEntry->m_Title)
{
CmdLine_Printf("%s\n", pFnEntry->m_Title);
}
}
return;
}
FUN(0, FnArg0, ());
FUN(1, FnArg01, (arg[0]));
FUN(2, FnArg02, (arg[0], arg[1]));
FUN(3, FnArg03, (arg[0], arg[1], arg[2]));
FUN(4, FnArg04, (arg[0], arg[1], arg[2], arg[3]));
FUN(5, FnArg05, (arg[0], arg[1], arg[2], arg[3], arg[4]));
}
int CmdLine_GetArgCount(const char* str)
{
Bool bFlag = False;
int nArgCount = 0;
str = strchr(str, '(');
if(Null == str)
{
return 0;
}
while(*(++str) != '\0')
{
if(')' == *str)
{
break;
}
else if(!bFlag)
{
if(' ' != *str)
{
bFlag = True;
nArgCount++;
if(',' == *str)
{
nArgCount++;
}
}
}
else if(',' == *str)
{
nArgCount++;
}
}
return *str == ')' ? nArgCount : -1;
}
void CmdLine_Reset(CmdLine* pCmdLine)
{
if(pCmdLine->m_isEcho)
CmdLine_Printf("->");
memset(pCmdLine->m_CmdLineStr, 0, sizeof(pCmdLine->m_CmdLineStr));
pCmdLine->m_CmdLineStrLen = 0;
}
void CmdLine_AddStr(const char* str)
{
CmdLine_AddStrEx(str, strlen(str));
}
void CmdLine_AddStrEx(const char* str, int len)
{
int i = 0;
CmdLine* pCmdLine = &g_CmdLine;
char* pBuf = pCmdLine->m_CmdLineStr;
for(i = 0; i < len; i++, str++)
{
if(pCmdLine->m_CmdLineStrLen >= MAX_CMDLINE_LEN)
{
CmdLine_Reset(pCmdLine);
}
if(pCmdLine->m_isEcho)
{
CmdLine_Printf("%c", *str);
}
if(*str != KEY_CR && *str != KEY_LF)
{
pBuf[pCmdLine->m_CmdLineStrLen++] = *str;
}
if(KEY_CR == *str)// || ')' == *str)
{
char* pFnName = Null;
char* argStr[MAX_ARG_COUNT] = {0};
int argCount = MAX_ARG_COUNT;
if(('\r' == pBuf[0] && pCmdLine->m_CmdLineStrLen == 1) || 0 == pCmdLine->m_CmdLineStrLen)
{
CmdLine_Reset(pCmdLine);
return;
}
if(CmdLine_Parse(pBuf, &pFnName, argStr, &argCount))
{
uint32 arg[MAX_ARG_COUNT] = {0};
if(CmdLine_ArgConvert(argStr, argCount, arg))
{
CmdLine_Exe(pCmdLine, pFnName, arg, argCount);
}
}
CmdLine_Reset(pCmdLine);
}
}
}
void CmdLine_Init(FnDef* pCmdTable, uint8 cmdTableCount, Bool isEcho, OutPutFun printf)
{
int i = 0;
FnDef* pFnEntry = pCmdTable;
memset(&g_CmdLine, 0, sizeof(CmdLine));
g_CmdLine.m_isEcho = isEcho;
g_CmdLine.m_FnArray = pCmdTable;
g_CmdLine.m_FnCount = cmdTableCount;
g_CmdLine.printf = printf;
for(i = 0; i < cmdTableCount; i++, pFnEntry++)
{
int argCount = CmdLine_GetArgCount(pFnEntry->m_Title);
if(argCount < 0 || argCount > MAX_ARG_COUNT)
{
CmdLine_Printf("[%s] error, get arg count[%d] error.\n", pFnEntry->m_Title, pFnEntry->m_ArgCount);
}
pFnEntry->m_ArgCount = (int8)argCount;
}
}
#endif
| 2.578125 | 3 |
2024-11-18T20:55:56.675138+00:00 | 2021-03-14T20:30:38 | 5eb7d51204a1e9339bc6fae3457cdba418518790 | {
"blob_id": "5eb7d51204a1e9339bc6fae3457cdba418518790",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-14T20:30:38",
"content_id": "9dc6b4834e3bcd5221b4c44072460a258b66cf26",
"detected_licenses": [
"MIT"
],
"directory_id": "ca74a4341a95666a053af8633fbfcfa317c80b7d",
"extension": "c",
"filename": "wxp.test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 343750751,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4248,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/wxp.test.c",
"provenance": "stackv2-0092.json.gz:56449",
"repo_name": "abobija/cutils",
"revision_date": "2021-03-14T20:30:38",
"revision_id": "d9d403e61732645d4083098d6a25568ea057cff3",
"snapshot_id": "85feec75158f0dd9dd75ff50b6f853d1cb2a487f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/abobija/cutils/d9d403e61732645d4083098d6a25568ea057cff3/tests/wxp.test.c",
"visit_date": "2023-03-21T13:10:32.473446"
} | stackv2 | #include <stdlib.h>
#include <assert.h>
#include "estr.h"
#include "wxp.h"
int main() {
char** argv = NULL;
int argc;
assert(wxp(NULL, &argc, &argv) == CU_ERR_INVALID_ARG);
assert(wxp("a b", NULL, &argv) == CU_ERR_INVALID_ARG);
assert(wxp("a b", &argc, NULL) == CU_ERR_INVALID_ARG);
assert(wxp("", &argc, &argv) == CU_ERR_EMPTY_STRING);
assert(wxp("test a b c", &argc, &argv) == CU_OK);
assert(argc == 4);
assert(argv && estr_eq(argv[0], "test") && estr_eq(argv[1], "a") &&
estr_eq(argv[2], "b") && estr_eq(argv[3], "c"));
cu_list_free(argv, argc);
assert(wxp("a", &argc, &argv) == CU_OK);
assert(argc == 1);
assert(argv && estr_eq(argv[0], "a"));
cu_list_free(argv, argc);
assert(wxp("ab \"", &argc, &argv) == CU_ERR_SYNTAX_ERROR);
assert(wxp("\"ab\\\"c\" \"\\\\\" d", &argc, &argv) == CU_OK);
assert(argc == 3);
assert(argv && estr_eq(argv[0], "ab\"c") && estr_eq(argv[1], "\\") &&
estr_eq(argv[2], "d"));
cu_list_free(argv, argc);
assert(wxp("a\\\\\\\\b d\"e f\"g h", &argc, &argv) == CU_OK);
assert(argc == 5);
assert(argv && estr_eq(argv[0], "a\\\\b") && estr_eq(argv[1], "d") &&
estr_eq(argv[2], "e f") &&
estr_eq(argv[3], "g") &&
estr_eq(argv[4], "h"));
cu_list_free(argv, argc);
assert(wxp("a\\\\\\\"b c d", &argc, &argv) == CU_OK);
assert(argc == 3);
assert(argv && estr_eq(argv[0], "a\\\"b") && estr_eq(argv[1], "c") &&
estr_eq(argv[2], "d"));
cu_list_free(argv, argc);
assert(wxp("a\"b\"\" c d", &argc, &argv) == CU_ERR_SYNTAX_ERROR);
assert(wxp("a b\"", &argc, &argv) == CU_ERR_SYNTAX_ERROR);
assert(wxp("test ab \"c d\" e", &argc, &argv) == CU_OK);
assert(argc == 4);
assert(argv && estr_eq(argv[0], "test") && estr_eq(argv[1], "ab") &&
estr_eq(argv[2], "c d") && estr_eq(argv[3], "e"));
cu_list_free(argv, argc);
assert(wxp("test a \"b c\" \"\" d", &argc, &argv) == CU_OK);
assert(argc == 5);
assert(argv && estr_eq(argv[0], "test") && estr_eq(argv[1], "a") &&
estr_eq(argv[2], "b c") && estr_eq(argv[3], "") && estr_eq(argv[4], "d"));
cu_list_free(argv, argc);
assert(wxp(" \" a b c \" d e \"f\" ", &argc, &argv) == CU_OK);
assert(argc == 4);
assert(argv && estr_eq(argv[0], " a b c ") &&
estr_eq(argv[1], "d") && estr_eq(argv[2], "e") && estr_eq(argv[3], "f"));
cu_list_free(argv, argc);
assert(wxp("test a \"b c\" \"\" d \"\"", &argc, &argv) == CU_OK);
assert(argc == 6);
assert(argv && estr_eq(argv[0], "test") && estr_eq(argv[1], "a") &&
estr_eq(argv[2], "b c") &&
estr_eq(argv[3], "") &&
estr_eq(argv[4], "d") &&
estr_eq(argv[5], "")
);
cu_list_free(argv, argc);
assert(wxp("test a \"b c\" \"\" d \"x\"", &argc, &argv) == CU_OK);
assert(argc == 6);
assert(argv && estr_eq(argv[0], "test") && estr_eq(argv[1], "a") &&
estr_eq(argv[2], "b c") &&
estr_eq(argv[3], "") &&
estr_eq(argv[4], "d") && estr_eq(argv[5], "x"));
cu_list_free(argv, argc);
assert(wxp("\"\" test a \"b c\" \"\" \"d\" ", &argc, &argv) == CU_OK);
assert(argc == 6);
assert(argv && estr_eq(argv[0], "") && estr_eq(argv[1], "test") && estr_eq(argv[2], "a") &&
estr_eq(argv[3], "b c") && estr_eq(argv[4], "") && estr_eq(argv[5], "d"));
cu_list_free(argv, argc);
assert(wxp("a \"b \\\"c\\\" d\"", &argc, &argv) == CU_OK); // a "b \"c\" d"
assert(argc == 2);
assert(argv && estr_eq(argv[0], "a") && estr_eq(argv[1], "b \"c\" d"));
cu_list_free(argv, argc);
assert(wxp("a \\\"c\\\"", &argc, &argv) == CU_OK); // a \"c\"
assert(argc == 2);
assert(argv && estr_eq(argv[0], "a") && estr_eq(argv[1], "\"c\""));
cu_list_free(argv, argc);
assert(wxp("\\\"a\\\" b", &argc, &argv) == CU_OK); // \"a\" b
assert(argc == 2);
assert(argv && estr_eq(argv[0], "\"a\"") && estr_eq(argv[1], "b"));
cu_list_free(argv, argc);
assert(wxp("a \"\\\"b\\\"\"", &argc, &argv) == CU_OK);
assert(argc == 2);
assert(argv && estr_eq(argv[0], "a") && estr_eq(argv[1], "\"b\""));
cu_list_free(argv, argc);
return 0;
} | 2.625 | 3 |
2024-11-18T20:55:57.191940+00:00 | 2020-12-16T09:01:42 | 4c9939ca165ae9906ff29a6cccfa3c07bce184c0 | {
"blob_id": "4c9939ca165ae9906ff29a6cccfa3c07bce184c0",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-16T09:01:42",
"content_id": "73012392943dc9b193a4f4a865997b23d1664d09",
"detected_licenses": [
"MIT"
],
"directory_id": "c8b3ed8d538d7a0a0b1588476d7056e3e6fa1b5c",
"extension": "c",
"filename": "main.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 297957284,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3005,
"license": "MIT",
"license_type": "permissive",
"path": "/Labs/02-Leds_Night_rider/Night_rider/Night_rider/Night_rider/main.c",
"provenance": "stackv2-0092.json.gz:57603",
"repo_name": "xstupk04/Digital-electronics-2",
"revision_date": "2020-12-16T09:01:42",
"revision_id": "b3207a9441fb98cca259abd3b45bf21245bf9472",
"snapshot_id": "62edfc6e0117aa836f8f7026875dd91a5b20552d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xstupk04/Digital-electronics-2/b3207a9441fb98cca259abd3b45bf21245bf9472/Labs/02-Leds_Night_rider/Night_rider/Night_rider/Night_rider/main.c",
"visit_date": "2023-02-01T11:15:38.696319"
} | stackv2 | /***********************************************************************
*
* Alternately toggle two LEDs when a push button is pressed.
* ATmega328P (Arduino Uno), 16 MHz, AVR 8-bit Toolchain 3.6.2
*
* Copyright (c) 2018-2020 Tomas Fryza
* Dept. of Radio Electronics, Brno University of Technology, Czechia
* This work is licensed under the terms of the MIT license.
*
**********************************************************************/
/* Defines -----------------------------------------------------------*/
#define LED_01 PB1 // AVR pin where green LED is connected
#define LED_02 PB2
#define LED_03 PB3
#define LED_04 PB4
#define LED_05 PB5
#define BLINK_DELAY 250
#define BTN PD0
#ifndef F_CPU
#define F_CPU 16000000 // CPU frequency in Hz required for delay
#endif
/* Includes ----------------------------------------------------------*/
#include <util/delay.h> // Functions for busy-wait delay loops
#include <avr/io.h> // AVR device-specific IO definitions
/* Functions ---------------------------------------------------------*/
/**
* Main function where the program execution begins. Toggle two LEDs
* when a push button is pressed.
*/
int main(void)
{
// Set pin as output in Data Direction Register...
DDRB = DDRB | (1<<LED_01);
// ...and turn LED off in Data Register
PORTB = PORTB & ~(1<<LED_01);
// Set pin as output in Data Direction Register...
DDRB = DDRB | (1<<LED_02);
// ...and turn LED off in Data Register
PORTB = PORTB & ~(1<<LED_02);
// Set pin as output in Data Direction Register...
DDRB = DDRB | (1<<LED_03);
// ...and turn LED off in Data Register
PORTB = PORTB & ~(1<<LED_03);
// Set pin as output in Data Direction Register...
DDRB = DDRB | (1<<LED_04);
// ...and turn LED off in Data Register
PORTB = PORTB & ~(1<<LED_04);
// Set pin as output in Data Direction Register...
DDRB = DDRB | (1<<LED_05);
// ...and turn LED off in Data Register
PORTB = PORTB & ~(1<<LED_05);
//set pin as input in Data Direction Register
//button with pullup ressistor
DDRD = DDRD & ~(1<<BTN);
PORTD = PORTD | (1<<BTN);
// Infinite loop
while (1)
{
// Pause several milliseconds
if (bit_is_clear(PIND, 0));
{
// WRITE YOUR CODE HERE
PORTB = PORTB ^ (1<<LED_01);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_01);
PORTB = PORTB ^ (1<<LED_02);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_02);
PORTB = PORTB ^ (1<<LED_03);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_03);
PORTB = PORTB ^ (1<<LED_04);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_04);
PORTB = PORTB ^ (1<<LED_05);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_04);
PORTB = PORTB ^ (1<<LED_05);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_03);
PORTB = PORTB ^ (1<<LED_04);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_02);
PORTB = PORTB ^ (1<<LED_03);
_delay_ms(BLINK_DELAY);
PORTB = PORTB ^ (1<<LED_02);
}
}
// Will never reach this
return 0;
} | 2.53125 | 3 |
2024-11-18T20:55:57.259731+00:00 | 2021-05-06T01:44:37 | 58c23eedfc6b7a51e964473bc4d69707c8fe5f63 | {
"blob_id": "58c23eedfc6b7a51e964473bc4d69707c8fe5f63",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-06T01:44:37",
"content_id": "e6403792a9c1885cbe5dbe8f5a2a5a226b4340b7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "52b9570c4475a96c4915e8ad561139ef8aeaeddf",
"extension": "h",
"filename": "queue.h",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 166169292,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 27240,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libdispatch-187.10/dispatch/queue.h",
"provenance": "stackv2-0092.json.gz:57731",
"repo_name": "Kanthine/SourceCode",
"revision_date": "2021-05-06T01:44:37",
"revision_id": "1761b67c1f11f5f59727f252eceed5efa395e3d6",
"snapshot_id": "6266abc76fd4262428a66ce9d04e95028894eae1",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/Kanthine/SourceCode/1761b67c1f11f5f59727f252eceed5efa395e3d6/libdispatch-187.10/dispatch/queue.h",
"visit_date": "2021-06-10T13:00:17.265522"
} | stackv2 | #ifndef __DISPATCH_QUEUE__
#define __DISPATCH_QUEUE__
#ifndef __DISPATCH_INDIRECT__
#error "Please #include <dispatch/dispatch.h> instead of this file directly."
#include <dispatch/base.h> // for HeaderDoc
#endif
/*!
* @header
*
* Dispatch is an abstract model for expressing concurrency via simple but powerful API.
*
* At the core, dispatch provides serial FIFO queues to which blocks may be
* submitted. Blocks submitted to these dispatch queues are invoked on a pool
* of threads fully managed by the system. No guarantee is made regarding
* which thread a block will be invoked on; however, it is guaranteed that only
* one block submitted to the FIFO dispatch queue will be invoked at a time.
*
* When multiple queues have blocks to be processed, the system is free to
* allocate additional threads to invoke the blocks concurrently. When the
* queues become empty, these threads are automatically released.
*/
/*!
* @typedef dispatch_queue_t
*
* @abstract
* Dispatch queues invoke blocks submitted to them serially in FIFO order. A
* queue will only invoke one block at a time, but independent queues may each
* invoke their blocks concurrently with respect to each other.
*
* @discussion
* Dispatch queues are lightweight objects to which blocks may be submitted.
* The system manages a pool of threads which process dispatch queues and
* invoke blocks submitted to them.
*
* Conceptually a dispatch queue may have its own thread of execution, and
* interaction between queues is highly asynchronous.
*
* Dispatch queues are reference counted via calls to dispatch_retain() and
* dispatch_release(). Pending blocks submitted to a queue also hold a
* reference to the queue until they have finished. Once all references to a
* queue have been released, the queue will be deallocated by the system.
*/
//#define DISPATCH_DECL(name) typedef struct name##_s *name##_t
DISPATCH_DECL(dispatch_queue);
// typedef struct dispatch_queue_s *dispatch_queue_t;
//这行代码定义了一个 dispatch_queue_t 类型的指针,指向一个 dispatch_queue_s 类型的结构体。
/*!
* @typedef dispatch_queue_attr_t
*
* @abstract
* Attribute for dispatch queues.
*/
DISPATCH_DECL(dispatch_queue_attr);
/*!
* @typedef dispatch_block_t
*
* @abstract
* The prototype of blocks submitted to dispatch queues, which take no
* arguments and have no return value.
*
* @discussion
* The declaration of a block allocates storage on the stack. Therefore, this
* is an invalid construct:
*
* dispatch_block_t block;
*
* if (x) {
* block = ^{ printf("true\n"); };
* } else {
* block = ^{ printf("false\n"); };
* }
* block(); // unsafe!!!
*
* What is happening behind the scenes:
*
* if (x) {
* struct Block __tmp_1 = ...; // setup details
* block = &__tmp_1;
* } else {
* struct Block __tmp_2 = ...; // setup details
* block = &__tmp_2;
* }
*
* As the example demonstrates, the address of a stack variable is escaping the
* scope in which it is allocated. That is a classic C bug.
*/
#ifdef __BLOCKS__
typedef void (^dispatch_block_t)(void);
#endif
__BEGIN_DECLS
/*!
* @function dispatch_async
*
* @abstract
* Submits a block for asynchronous execution on a dispatch queue.
*
* @discussion
* The dispatch_async() function is the fundamental mechanism for submitting
* blocks to a dispatch queue.
*
* Calls to dispatch_async() always return immediately after the block has
* been submitted, and never wait for the block to be invoked.
*
* The target queue determines whether the block will be invoked serially or
* concurrently with respect to other blocks submitted to that same queue.
* Serial queues are processed concurrently with respect to each other.
*
* @param queue
* The target dispatch queue to which the block is submitted.
* The system will hold a reference on the target queue until the block
* has finished.
* The result of passing NULL in this parameter is undefined.
*
* @param block
* The block to submit to the target dispatch queue. This function performs
* Block_copy() and Block_release() on behalf of callers.
* The result of passing NULL in this parameter is undefined.
*/
#ifdef __BLOCKS__
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
#endif
/*!
* @function dispatch_async_f
*
* @abstract
* Submits a function for asynchronous execution on a dispatch queue.
*
* @discussion
* See dispatch_async() for details.
*
* @param queue
* The target dispatch queue to which the function is submitted.
* The system will hold a reference on the target queue until the function
* has returned.
* The result of passing NULL in this parameter is undefined.
*
* @param context
* The application-defined context parameter to pass to the function.
*
* @param work
* The application-defined function to invoke on the target queue. The first
* parameter passed to this function is the context provided to
* dispatch_async_f().
* The result of passing NULL in this parameter is undefined.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL1 DISPATCH_NONNULL3 DISPATCH_NOTHROW
void dispatch_async_f(dispatch_queue_t queue,void *context,dispatch_function_t work);
/*!
* @function dispatch_sync
*
* @abstract
* Submits a block for synchronous execution on a dispatch queue.
*
* @discussion
* Submits a block to a dispatch queue like dispatch_async(), however
* dispatch_sync() will not return until the block has finished.
*
* Calls to dispatch_sync() targeting the current queue will result
* in dead-lock. Use of dispatch_sync() is also subject to the same
* multi-party dead-lock problems that may result from the use of a mutex.
* Use of dispatch_async() is preferred.
*
* Unlike dispatch_async(), no retain is performed on the target queue. Because
* calls to this function are synchronous, the dispatch_sync() "borrows" the
* reference of the caller.
*
* As an optimization, dispatch_sync() invokes the block on the current
* thread when possible.
*
* @param queue
* The target dispatch queue to which the block is submitted.
* The result of passing NULL in this parameter is undefined.
*
* @param block
* The block to be invoked on the target dispatch queue.
* The result of passing NULL in this parameter is undefined.
*/
#ifdef __BLOCKS__
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
void dispatch_sync(dispatch_queue_t queue, dispatch_block_t block);
#endif
/*!
* @function dispatch_sync_f
*
* @abstract
* Submits a function for synchronous execution on a dispatch queue.
*
* @discussion
* See dispatch_sync() for details.
*
* @param queue
* The target dispatch queue to which the function is submitted.
* The result of passing NULL in this parameter is undefined.
*
* @param context
* The application-defined context parameter to pass to the function.
*
* @param work
* The application-defined function to invoke on the target queue. The first
* parameter passed to this function is the context provided to
* dispatch_sync_f().
* The result of passing NULL in this parameter is undefined.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL1 DISPATCH_NONNULL3 DISPATCH_NOTHROW
void dispatch_sync_f(dispatch_queue_t queue,void *context,dispatch_function_t work);
/*!
* @function dispatch_apply
*
* @abstract
* Submits a block to a dispatch queue for multiple invocations.
*
* @discussion
* Submits a block to a dispatch queue for multiple invocations. This function
* waits for the task block to complete before returning. If the target queue
* is concurrent, the block may be invoked concurrently, and it must therefore
* be reentrant safe.
*
* Each invocation of the block will be passed the current index of iteration.
*
* @param iterations
* The number of iterations to perform.
*
* @param queue
* The target dispatch queue to which the block is submitted.
* The result of passing NULL in this parameter is undefined.
*
* @param block
* The block to be invoked the specified number of iterations.
* The result of passing NULL in this parameter is undefined.
*/
#ifdef __BLOCKS__
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
void dispatch_apply(size_t iterations, dispatch_queue_t queue,void (^block)(size_t));
#endif
/*!
* @function dispatch_apply_f
*
* @abstract
* Submits a function to a dispatch queue for multiple invocations.
*
* @discussion
* See dispatch_apply() for details.
*
* @param iterations
* The number of iterations to perform.
*
* @param queue
* The target dispatch queue to which the function is submitted.
* The result of passing NULL in this parameter is undefined.
*
* @param context
* The application-defined context parameter to pass to the function.
*
* @param work
* The application-defined function to invoke on the target queue. The first
* parameter passed to this function is the context provided to
* dispatch_apply_f(). The second parameter passed to this function is the
* current index of iteration.
* The result of passing NULL in this parameter is undefined.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL2 DISPATCH_NONNULL4 DISPATCH_NOTHROW
void dispatch_apply_f(size_t iterations, dispatch_queue_t queue,void *context,void (*work)(void *, size_t));
/*! 获取当前正在运行的队列
*
* @abstract
* dispatch_queue 是按照层级结构来组织的,无论是串行还是并发队列,只要有targetq,都会一层层地向上追溯,直到线程池。 所以无法单用某个队列对象来描述 “当前队列” 这一概念的!
*
*
* @discussion 在 Block 之外调用 dispatch_get_current_queue() 时,默认返回全局并发队列
*
* @note 在 iOS 6 之后被废弃:无法返回期望的队列,可能造成死锁
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_PURE DISPATCH_WARN_RESULT DISPATCH_NOTHROW
dispatch_queue_t dispatch_get_current_queue(void);
/*!
* @function dispatch_get_main_queue
*
* @abstract
* Returns the default queue that is bound to the main thread.
*
* @discussion
* In order to invoke blocks submitted to the main queue, the application must
* call dispatch_main(), NSApplicationMain(), or use a CFRunLoop on the main
* thread.
*
* @result
* Returns the main queue. This queue is created automatically on behalf of
* the main thread before main() is called.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT struct dispatch_queue_s _dispatch_main_q;
#define dispatch_get_main_queue() (&_dispatch_main_q)
/*!
* @typedef dispatch_queue 队列优先级
* 数据类型为 dispatch_queue_priority ,即 long 类型
*
* @constant DISPATCH_QUEUE_PRIORITY_HIGH 最高优先级,该队列将在任何比它优先级低的队列之前调度执行;
* @constant DISPATCH_QUEUE_PRIORITY_DEFAULT 默认优先级
* @constant DISPATCH_QUEUE_PRIORITY_LOW 低优先级,队列将在所有默认优先级和高优先级队列被调度之后调度执行。
* @constant DISPATCH_QUEUE_PRIORITY_BACKGROUND 后台优先级,优先级被设置为最低
*/
#define DISPATCH_QUEUE_PRIORITY_HIGH 2
#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0
#define DISPATCH_QUEUE_PRIORITY_LOW (-2)
#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN
typedef long dispatch_queue_priority_t;
/** 获取全局队列
* @param priority 优先级
* @param flags 是否创建线程
* @discussion 不能修改全局并发队列。调用dispatch_suspend()、dispatch_resume()、dispatch_set_context()等函数对全局队列没有影响。
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_CONST DISPATCH_WARN_RESULT DISPATCH_NOTHROW
dispatch_queue_t dispatch_get_global_queue(dispatch_queue_priority_t priority,unsigned long flags);
/*!
* @const DISPATCH_QUEUE_SERIAL
* @discussion 串行队列,队列中的任务按先进先出的顺序连续执行
*/
#define DISPATCH_QUEUE_SERIAL NULL
/*!
* @const DISPATCH_QUEUE_CONCURRENT
* @discussion 并发队列;虽然它们同时执行任务,但可以使用 dispatch_barrier() 在队列中创建同步点
*/
#define DISPATCH_QUEUE_CONCURRENT (&_dispatch_queue_attr_concurrent)
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_3)
DISPATCH_EXPORT
struct dispatch_queue_attr_s _dispatch_queue_attr_concurrent;
/** 创建一个调度队列,默认优先级DISPATCH_QUEUE_PRIORITY_DEFAULT
* @param label 队列的标识,可以为 NULL
* @param attr DISPATCH_QUEUE_SERIAL or DISPATCH_QUEUE_CONCURRENT.
*
* @abstract 该函数主要执行了三个功能:
* 1、配置唯一标识,并拷贝至新队列;
* 2、分配内存并初始化队列,该队列是串行队列;
* 3、对于并发队列,需要额外设置 dq_width 、do_targetq ;
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_MALLOC DISPATCH_WARN_RESULT DISPATCH_NOTHROW
dispatch_queue_t dispatch_queue_create(const char *label, dispatch_queue_attr_t attr);
/** 获取队列的标识,可能为 NULL
* @param queue 指定的队列
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_PURE DISPATCH_WARN_RESULT
DISPATCH_NOTHROW const char * dispatch_queue_get_label(dispatch_queue_t queue);
/*! 传递给dispatch_set_target_queue()和dispatch_source_create()函数的常量,以指示应该使用给定对象类型的默认目标队列。
*/
#define DISPATCH_TARGET_QUEUE_DEFAULT NULL
/*!
* dispatch_queue_t 的优先级从其目标队列继承;
*
* 提交到目标队列是另一个串行队列的串行队列的块不会与提交到目标队列或具有相同目标队列的任何其他队列的块并发调用。
*
* 在目标队列的层次结构中引入循环的结果是未定义的。
*
* 分派源的目标队列指定将在何处提交其事件处理程序和取消处理程序块。
*
* Blocks submitted to a serial queue whose target queue is another serial queue will not be invoked concurrently with blocks submitted to the target queue or to any other queue with that same target queue.
*
* The result of introducing a cycle into the hierarchy of target queues is undefined.
*
* A dispatch source's target queue specifies where its event handler and cancellation handler blocks will be submitted.
*
* A dispatch I/O channel's target queue specifies where where its I/O
* operations are executed.
*
* For all other dispatch object types, the only function of the target queue
* is to determine where an object's finalizer function is invoked.
*
* @param object
* The object to modify.
* The result of passing NULL in this parameter is undefined.
*
* @param queue
* The new target queue for the object. The queue is retained, and the
* previous target queue, if any, is released.
* If queue is DISPATCH_TARGET_QUEUE_DEFAULT, set the object's target queue
* to the default target queue for the given object type.
*/
/** 设置指定对象的目标队列 -> 更改队列优先级
* @param object 要修改的对象,不能为空;
* @param queue 对象的新目标队列,不能为空。
* @note 该函数不仅可以设置优先级,还能够创建队列的层次体系;
* 当我们需要不同队列中的任务同步执行时,可以创建一个串行队列 queue_A ,然后将这些队列的 do_targetq 指向 queue_A
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NOTHROW // DISPATCH_NONNULL1
void dispatch_set_target_queue(dispatch_object_t object, dispatch_queue_t queue);
/*!
* @function dispatch_main
*
* @abstract
* Execute blocks submitted to the main queue.
*
* @discussion
* This function "parks" the main thread and waits for blocks to be submitted
* to the main queue. This function never returns.
*
* Applications that call NSApplicationMain() or CFRunLoopRun() on the
* main thread do not need to call dispatch_main().
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NOTHROW DISPATCH_NORETURN
void dispatch_main(void);
/*!
* @function dispatch_after
*
* @abstract
* Schedule a block for execution on a given queue at a specified time.
*
* @discussion
* Passing DISPATCH_TIME_NOW as the "when" parameter is supported, but not as
* optimal as calling dispatch_async() instead. Passing DISPATCH_TIME_FOREVER
* is undefined.
*
* @param when
* A temporal milestone returned by dispatch_time() or dispatch_walltime().
*
* @param queue
* A queue to which the given block will be submitted at the specified time.
* The result of passing NULL in this parameter is undefined.
*
* @param block
* The block of code to execute.
* The result of passing NULL in this parameter is undefined.
*/
/** 在指定的时间执行任务;不会堵塞当前线程的执行
* @param when 将任务添加到队列中的时间(不是在指定时间之后开始处理任务)
* 这个时间并不精准,只是大致延迟
* @param queue 处理任务的队列,不能为空
* @param block 要处理的任务,不能为空
*/
#ifdef __BLOCKS__
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL2 DISPATCH_NONNULL3 DISPATCH_NOTHROW
void dispatch_after(dispatch_time_t when,dispatch_queue_t queue,dispatch_block_t block);
#endif
/*!
* @function dispatch_after_f
*
* @abstract
* Schedule a function for execution on a given queue at a specified time.
*
* @discussion
* See dispatch_after() for details.
*
* @param when
* A temporal milestone returned by dispatch_time() or dispatch_walltime().
*
* @param queue
* A queue to which the given function will be submitted at the specified time.
* The result of passing NULL in this parameter is undefined.
*
* @param context
* The application-defined context parameter to pass to the function.
*
* @param work
* The application-defined function to invoke on the target queue. The first
* parameter passed to this function is the context provided to
* dispatch_after_f().
* The result of passing NULL in this parameter is undefined.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)
DISPATCH_EXPORT DISPATCH_NONNULL2 DISPATCH_NONNULL4 DISPATCH_NOTHROW
void dispatch_after_f(dispatch_time_t when,dispatch_queue_t queue,void *context,dispatch_function_t work);
/*!
* @functiongroup Dispatch Barrier API
* The dispatch barrier API is a mechanism for submitting barrier blocks to a
* dispatch queue, analogous to the dispatch_async()/dispatch_sync() API.
* It enables the implementation of efficient reader/writer schemes.
* Barrier blocks only behave specially when submitted to queues created with
* the DISPATCH_QUEUE_CONCURRENT attribute; on such a queue, a barrier block
* will not run until all blocks submitted to the queue earlier have completed,
* and any blocks submitted to the queue after a barrier block will not run
* until the barrier block has completed.
* When submitted to a a global queue or to a queue not created with the
* DISPATCH_QUEUE_CONCURRENT attribute, barrier blocks behave identically to
* blocks submitted with the dispatch_async()/dispatch_sync() API.
*/
/*!
* @function dispatch_barrier_async
*
* @abstract
* Submits a barrier block for asynchronous execution on a dispatch queue.
*
* @discussion
* Submits a block to a dispatch queue like dispatch_async(), but marks that block as a barrier (relevant only on DISPATCH_QUEUE_CONCURRENT queues).
* 类似 dispatch_async() 向 queue 提交一个 block,但将 block 标记为一个界线
* 仅仅与 DISPATCH_QUEUE_CONCURRENT 队列相关
*
* See dispatch_async() for details.
*
* @param queue
* The target dispatch queue to which the block is submitted.
* The system will hold a reference on the target queue until the block has finished.
* The result of passing NULL in this parameter is undefined.
*
* @param block
* The block to submit to the target dispatch queue. This function performs
* Block_copy() and Block_release() on behalf of callers.
* The result of passing NULL in this parameter is undefined.
*/
/** 设置 barrier:就好比在一条直线上添加了一个间隔点
* 针对队列 queue 的任务,系统会先执行 barrier 之前所有的任务;
* 执行完毕之后,执行 barrier 点的 代码块
* barrier 点的代码块执行完毕,执行 barrier 点之后的任务
* 设置 barrier 的两种方式:
* 同步设置 barrier: 会堵塞当前线程;barrier 代码块在当前线程执行;
* 异步设置 barrier:不会堵塞当前线程;barrier 代码块开辟新线程执行;
* @param queue 设置 barrier 的队列
* @param block barrier 点需要执行的代码
*/
#ifdef __BLOCKS__
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_3)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
void dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);
#endif
/*!
* @function dispatch_barrier_async_f
*
* @abstract
* Submits a barrier function for asynchronous execution on a dispatch queue.
*
* @discussion
* Submits a function to a dispatch queue like dispatch_async_f(), but marks
* that function as a barrier (relevant only on DISPATCH_QUEUE_CONCURRENT
* queues).
*
* See dispatch_async_f() for details.
*
* @param queue
* The target dispatch queue to which the function is submitted.
* The system will hold a reference on the target queue until the function
* has returned.
* The result of passing NULL in this parameter is undefined.
*
* @param context
* The application-defined context parameter to pass to the function.
*
* @param work
* The application-defined function to invoke on the target queue. The first
* parameter passed to this function is the context provided to
* dispatch_barrier_async_f().
* The result of passing NULL in this parameter is undefined.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_3)
DISPATCH_EXPORT DISPATCH_NONNULL1 DISPATCH_NONNULL3 DISPATCH_NOTHROW
void
dispatch_barrier_async_f(dispatch_queue_t queue,
void *context,
dispatch_function_t work);
/*!
* @function dispatch_barrier_sync
*
* @abstract
* Submits a barrier block for synchronous execution on a dispatch queue.
*
* @discussion
* Submits a block to a dispatch queue like dispatch_sync(), but marks that
* block as a barrier (relevant only on DISPATCH_QUEUE_CONCURRENT queues).
*
* See dispatch_sync() for details.
*
* @param queue
* The target dispatch queue to which the block is submitted.
* The result of passing NULL in this parameter is undefined.
*
* @param block
* The block to be invoked on the target dispatch queue.
* The result of passing NULL in this parameter is undefined.
*/
#ifdef __BLOCKS__
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_3)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_NOTHROW
void
dispatch_barrier_sync(dispatch_queue_t queue, dispatch_block_t block);
#endif
/*!
* @function dispatch_barrier_sync_f
*
* @abstract
* Submits a barrier function for synchronous execution on a dispatch queue.
*
* @discussion
* Submits a function to a dispatch queue like dispatch_sync_f(), but marks that
* fuction as a barrier (relevant only on DISPATCH_QUEUE_CONCURRENT queues).
*
* See dispatch_sync_f() for details.
*
* @param queue
* The target dispatch queue to which the function is submitted.
* The result of passing NULL in this parameter is undefined.
*
* @param context
* The application-defined context parameter to pass to the function.
*
* @param work
* The application-defined function to invoke on the target queue. The first
* parameter passed to this function is the context provided to
* dispatch_barrier_sync_f().
* The result of passing NULL in this parameter is undefined.
*/
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_3)
DISPATCH_EXPORT DISPATCH_NONNULL1 DISPATCH_NONNULL3 DISPATCH_NOTHROW
void
dispatch_barrier_sync_f(dispatch_queue_t queue,
void *context,
dispatch_function_t work);
/*! 怎么判断当前队列是指定队列?
* @functiongroup Dispatch queue-specific contexts
* 这个API允许不同的子系统将上下文关联到一个共享队列,而不存在冲突风险,并且可以从在该队列上执行的块或目标队列层次结构中的任何子队列中检索该上下文。
* This API allows different subsystems to associate context to a shared queue without risk of collision and to retrieve that context from blocks executing on that queue or any of its child queues in the target queue hierarchy.
*/
/*! 向指定队列里面设置一个标识
* @function dispatch_queue_set_specific
*
* @abstract 将任意数据以键值对的形式关联到队列中;
* 通过键值对,就可以判断当前执行的任务是否包含在某个队列中,因为系统会根据给定的键,沿着队列的层级体系(即父队列)进行查找键所对应的值,如果到根队列还没找到,就说明当前任务不包含在你要判断的队列中,进而可以避免(1)中描述的死锁问题
* 简单理解就是:给某个队列加个标记,找到这个标记就说明包含在这个队列中
*
* @param queue 待设置标记的调度队列;不能传递 NULL
* @param key 标记的键;通常是一个静态变量的指针
* @param context 标记的值,可能为 NULL。注意,这里键和值是指针,即地址,故context中可以放任何数据,但必须手动管理context的内存;
* @param destructor 析构函数,可能为 NULL!所在队列内存被回收,或者context值改变时,会被调用;
*/
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_5_0)
DISPATCH_EXPORT DISPATCH_NONNULL1 DISPATCH_NONNULL2 DISPATCH_NOTHROW
void dispatch_queue_set_specific(dispatch_queue_t queue, const void *key,void *context, dispatch_function_t destructor);
/*! 获取指定调度队列的键/值数据
*
* @param queue 要查询的调度队列;不能传递 NULL 。
* @param key 指定的键;
* @result 指定键的值,如果没有找到则为NULL。
*/
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_5_0)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_PURE DISPATCH_WARN_RESULT
DISPATCH_NOTHROW
void *dispatch_queue_get_specific(dispatch_queue_t queue, const void *key);
/*! 获取当前调度队列的键/值数据
* @param key 指定的键;
*
* @discussion 如果当前队列是主队列、或者全局并发队列 ,则返回NULL;
* @abstract 从当前队列开始,沿着目标队列 do_targetq 向上回溯,直到找到对应键的值;
* 如果找到主队列、或者全局并发队列,也没有找到对应键的值,则返回 NULL;
* 因为主队列、或者全局并发队列 的 do_targetq 为 NULL;
*/
__OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_5_0)
DISPATCH_EXPORT DISPATCH_NONNULL_ALL DISPATCH_PURE DISPATCH_WARN_RESULT
DISPATCH_NOTHROW
void *dispatch_get_specific(const void *key);
__END_DECLS
#endif
| 2.296875 | 2 |
2024-11-18T20:55:57.428364+00:00 | 2020-04-28T03:30:31 | ae5fa56147fc9112b41482366d835849fe82a3d8 | {
"blob_id": "ae5fa56147fc9112b41482366d835849fe82a3d8",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-28T03:30:31",
"content_id": "ad7cba1e1b801893230245d894521d768f96232b",
"detected_licenses": [
"MIT"
],
"directory_id": "9fee2d8a3b5f2ab69df3cafd64b928e14514bb4f",
"extension": "c",
"filename": "scene-ops.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 255218496,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3015,
"license": "MIT",
"license_type": "permissive",
"path": "/scene-ops.c",
"provenance": "stackv2-0092.json.gz:57987",
"repo_name": "ascent12/nori",
"revision_date": "2020-04-28T03:30:31",
"revision_id": "408249f340597c6a9cf8c471155c0ec35fa6558f",
"snapshot_id": "337f2a6006c2e5b2d886af788d13b30cd1d9cae2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ascent12/nori/408249f340597c6a9cf8c471155c0ec35fa6558f/scene-ops.c",
"visit_date": "2022-05-09T23:52:55.925766"
} | stackv2 | /* SPDX-License-Identifier: MIT */
#include "scene.h"
#include <assert.h>
#include <stddef.h>
#include <wayland-util.h>
static void
node_disconnect(struct scene_node *n)
{
wl_list_remove(&n->link);
wl_list_init(&n->link);
for (struct scene_layer *p = n->parent; p; p = p->base.parent) {
assert(p->base.decendent_views >= n->decendent_views);
p->base.decendent_views -= n->decendent_views;
}
n->parent = NULL;
}
static void
node_set_parent(struct scene_layer *p, struct scene_node *n)
{
n->parent = p;
p->base.decendent_views += n->decendent_views;
}
static void
node_set_root(struct scene *s, struct scene_node *n)
{
node_disconnect(n);
s->root = n;
}
static void
node_push(struct scene_layer *parent, struct scene_node *n)
{
node_disconnect(n);
node_set_parent(parent, n);
wl_list_insert(parent->children.prev, &n->link);
}
static void
node_above(struct scene_node *rel, struct scene_node *n)
{
assert(rel->parent);
node_disconnect(n);
node_set_parent(rel->parent, n);
wl_list_insert(&rel->link, &n->link);
}
static void
node_below(struct scene_node *rel, struct scene_node *n)
{
assert(rel->parent);
node_disconnect(n);
node_set_parent(rel->parent, n);
wl_list_insert(rel->link.prev, &n->link);
}
static void
node_set_pos(struct scene_node *n, int x, int y)
{
n->x = x;
n->y = y;
}
void
scene_disconnect_view(struct scene_view *v)
{
node_disconnect(&v->base);
}
void
scene_disconnect_layer(struct scene_layer *l)
{
node_disconnect(&l->base);
}
void
scene_set_root_view(struct scene *s, struct scene_view *v)
{
node_set_root(s, &v->base);
}
void
scene_set_root_layer(struct scene *s, struct scene_layer *l)
{
node_set_root(s, &l->base);
}
void
scene_push_view(struct scene_layer *parent, struct scene_view *v)
{
node_push(parent, &v->base);
}
void
scene_push_layer(struct scene_layer *parent, struct scene_layer *l)
{
node_push(parent, &l->base);
}
void
scene_view_above_view(struct scene_view *rel, struct scene_view *v)
{
node_above(&rel->base, &v->base);
}
void
scene_view_above_layer(struct scene_layer *rel, struct scene_view *v)
{
node_above(&rel->base, &v->base);
}
void
scene_layer_above_view(struct scene_view *rel, struct scene_layer *l)
{
node_above(&rel->base, &l->base);
}
void
scene_layer_above_layer(struct scene_layer *rel, struct scene_layer *l)
{
node_above(&rel->base, &l->base);
}
void
scene_view_below_view(struct scene_view *rel, struct scene_view *v)
{
node_below(&rel->base, &v->base);
}
void
scene_view_below_layer(struct scene_layer *rel, struct scene_view *v)
{
node_below(&rel->base, &v->base);
}
void
scene_layer_below_view(struct scene_view *rel, struct scene_layer *l)
{
node_below(&rel->base, &l->base);
}
void
scene_layer_below_layer(struct scene_layer *rel, struct scene_layer *l)
{
node_below(&rel->base, &l->base);
}
void
scene_set_pos_view(struct scene_view *v, int x, int y)
{
node_set_pos(&v->base, x, y);
}
void
scene_set_pos_layer(struct scene_layer *l, int x, int y)
{
node_set_pos(&l->base, x, y);
}
| 2.5625 | 3 |
2024-11-18T20:55:57.613753+00:00 | 2016-08-29T04:30:57 | 329a61f5898531c9da303edf45beb1f6138d528a | {
"blob_id": "329a61f5898531c9da303edf45beb1f6138d528a",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-29T04:30:57",
"content_id": "7d3775700e3b7126c8401dd8cdb63c7ef7485e19",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "27f22fde64cc9634cc5f78d963a6c368ec1158a2",
"extension": "c",
"filename": "client_rules.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": 16813,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/client_rules.c",
"provenance": "stackv2-0092.json.gz:58116",
"repo_name": "kaowul/zerod",
"revision_date": "2016-08-29T04:30:57",
"revision_id": "e07b261890d74884008fb4cb0c6c0b6c35c7e48a",
"snapshot_id": "a6e0d23ed2ba9ce612860f1c454ca97465395ac1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kaowul/zerod/e07b261890d74884008fb4cb0c6c0b6c35c7e48a/src/client_rules.c",
"visit_date": "2021-04-15T07:22:31.858364"
} | stackv2 | #include <assert.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <event2/util.h>
#include "client_rules.h"
#include "util_string.h"
#include "util_pcre.h"
// predefined strings for rule identification
#define CLIENT_RULE_IDENTITY "identity."
#define CLIENT_RULE_BW "bw."
#define CLIENT_RULE_PORTS "ports."
#define CLIENT_RULE_RMPORTS "rmports."
#define CLIENT_RULE_FWD "fwd."
#define CLIENT_RULE_RMFWD "rmfwd."
#define CLIENT_RULE_DEFERRED "deferred."
#define CLIENT_RULE_RMDEFERRED "rmdeferred"
// predefined string parts
#define STR_ALLOW "allow"
#define STR_DENY "deny"
#define STR_TCP "tcp"
#define STR_UDP "udp"
#define STR_SPEED "speed"
#define STR_SESSION "session"
#define STR_DOWN "down"
#define STR_UP "up"
#define STR_BOTH "both"
struct zclient_rule_parser_struct
{
pcre *re_bw;
pcre_extra *re_bw_extra;
pcre *re_identity;
pcre_extra *re_identity_extra;
pcre *re_ports;
pcre_extra *re_ports_extra;
pcre *re_fwd;
pcre_extra *re_fwd_extra;
pcre *re_deferred;
pcre_extra *re_deferred_extra;
};
/**
*
*/
zclient_rule_parser_t *zclient_rule_parser_new(void)
{
zclient_rule_parser_t *parser = malloc(sizeof(*parser));
if (unlikely(!parser)) {
return NULL;
}
memset(parser, 0, sizeof(*parser));
int erroffset;
const char *errptr;
parser->re_bw = pcre_compile("^bw\\.(\\d+)([kmgtpe])?bit\\.(up|down)$", PCRE_CASELESS, &errptr, &erroffset, NULL);
if (unlikely(!parser->re_bw)) {
assert(false);
goto error;
}
parser->re_bw_extra = pcre_study(parser->re_bw, 0, &errptr);
parser->re_identity = pcre_compile("^identity\\.(\\d+)\\.([^\\s]+)$", PCRE_CASELESS, &errptr, &erroffset, NULL);
if (unlikely(!parser->re_identity)) {
assert(false);
goto error;
}
parser->re_identity_extra = pcre_study(parser->re_identity, 0, &errptr);
parser->re_ports = pcre_compile("^(rm)?ports\\.(allow|deny).(tcp|udp)(?:\\.\\d+)+$", PCRE_CASELESS, &errptr, &erroffset, NULL);
if (unlikely(!parser->re_ports)) {
assert(false);
goto error;
}
parser->re_ports_extra = pcre_study(parser->re_ports, 0, &errptr);
parser->re_fwd = pcre_compile("^(rm)?fwd\\.(tcp|udp).(\\d+)(?:\\.((?:\\d{1,3}.){3}\\d{1,3}(?::\\d+)?))?$", PCRE_CASELESS, &errptr, &erroffset, NULL);
if (unlikely(!parser->re_fwd)) {
assert(false);
goto error;
}
parser->re_fwd_extra = pcre_study(parser->re_fwd, 0, &errptr);
parser->re_deferred = pcre_compile("^deferred\\.(\\d+)\\.([^\\s]+)$", PCRE_CASELESS, &errptr, &erroffset, NULL);
if (unlikely(!parser->re_deferred)) {
assert(false);
goto error;
}
parser->re_deferred_extra = pcre_study(parser->re_deferred, 0, &errptr);
return parser;
error:
zclient_rule_parser_free(parser);
return NULL;
}
/**
*
*/
void zclient_rule_parser_free(zclient_rule_parser_t *parser)
{
assert(parser);
if (parser->re_bw_extra) pcre_free_study(parser->re_bw_extra);
if (parser->re_bw) pcre_free(parser->re_bw);
if (parser->re_identity_extra) pcre_free_study(parser->re_identity_extra);
if (parser->re_identity) pcre_free(parser->re_identity);
if (parser->re_ports_extra) pcre_free_study(parser->re_ports_extra);
if (parser->re_ports) pcre_free(parser->re_ports);
if (parser->re_fwd_extra) pcre_free_study(parser->re_fwd_extra);
if (parser->re_fwd) pcre_free(parser->re_fwd);
if (parser->re_deferred_extra) pcre_free_study(parser->re_deferred_extra);
if (parser->re_deferred) pcre_free(parser->re_deferred);
free(parser);
}
/**
* Parse bandwidth rule.
* @param[in] rules
* @param[in] str
* @return Zero on success.
*/
static bool parse_bw(const zclient_rule_parser_t *parser, zclient_rules_t *rules, const char *str)
{
int ovec[ZPCRE_DECL_SIZE(1+3)];
int rc = pcre_exec(parser->re_bw, parser->re_bw_extra, str, (int)strlen(str), 0, 0, ovec, ARRAYSIZE(ovec));
if (unlikely(rc < 0)) {
return false;
}
const char *speed_str = str + ZPCRE_SO(ovec, 1);
const char *prefix_str = (ZPCRE_SO(ovec, 2) != -1) ? (str + ZPCRE_SO(ovec, 2)) : NULL;
const char *dir_str = str + ZPCRE_SO(ovec, 3);
uint64_t speed = 0;
if (0 != str_to_u64(speed_str, &speed)) {
return false;
}
uint64_t mul = 1;
if (prefix_str) {
mul = str_parse_si_unit(*prefix_str, 1024);
}
if ('U' == toupper(*dir_str)) {
rules->bw_up = speed * mul / 8;
rules->have.bw_up = 1;
} else {
rules->bw_down = speed * mul / 8;
rules->have.bw_down = 1;
}
return true;
}
/*
* Parse identity rule.
* @param[in] rules
* @param[in] str
* @return Zero on success.
*/
static bool parse_identity(const zclient_rule_parser_t *parser, zclient_rules_t *rules, const char *str)
{
int ovec[ZPCRE_DECL_SIZE(1+2)];
int rc = pcre_exec(parser->re_identity, parser->re_identity_extra, str, (int)strlen(str), 0, 0, ovec, ARRAYSIZE(ovec));
if (unlikely(rc < 0)) {
return false;
}
const char *id_str = str + ZPCRE_SO(ovec, 1);
const char *login_str = str + ZPCRE_SO(ovec, 2);
uint32_t user_id = 0;
if (0 != str_to_u32(id_str, &user_id)) {
return false;
}
if (!user_id) {
return false;
}
rules->user_id = user_id;
rules->have.user_id = 1;
rules->login = strdup(login_str);
strtoupper(rules->login);
rules->have.login = 1;
return true;
}
/**
* Parse ports rule.
* @param[in] rules
* @param[in] str
* @return Zero on success.
*/
static bool parse_ports(const zclient_rule_parser_t *parser, zclient_rules_t *rules, const char *str)
{
int ovec[ZPCRE_DECL_SIZE(1+3)];
int rc = pcre_exec(parser->re_ports, parser->re_ports_extra, str, (int)strlen(str), 0, 0, ovec, ARRAYSIZE(ovec));
if (unlikely(rc < 0)) {
return false;
}
bool add = true;
if (ZPCRE_SO(ovec, 1) != -1) { // "rm" prefix
add = false;
}
const char *policy_str = str + ZPCRE_SO(ovec, 2);
const char *proto_str = str + ZPCRE_SO(ovec, 3);
zfwall_policy_t policy = ('A' == toupper(*policy_str)) ? ACCESS_ALLOW : ACCESS_DENY;
zip_proto_t proto = ('T' == toupper(*proto_str)) ? PROTO_TCP : PROTO_UDP ;
str += ZPCRE_EO(ovec, 3);
size_t pushed_cnt = 0;
while (NULL != (str = strchr(str, '.'))) {
str++;
zcr_port_t *item = malloc(sizeof(*item));
item->proto = proto;
item->policy = policy;
if (0 != str_to_u16(str, &item->port)) {
free(item);
goto error;
}
item->port = htons(item->port);
item->add = add;
utarray_push_back(&rules->port_rules, &item);
pushed_cnt++;
}
rules->have.port_rules = 1;
return true;
error:
while (pushed_cnt--) {
free(*(struct zcr_port **) utarray_back(&rules->port_rules));
utarray_pop_back(&rules->port_rules);
}
return false;
}
/**
* Parse forwarding rule.
* @param[in] rules
* @param[in] str
* @return Zero on success.
*/
static bool parse_fwd(const zclient_rule_parser_t *parser, zclient_rules_t *rules, const char *str)
{
int ovec[ZPCRE_DECL_SIZE(1+4)];
int rc = pcre_exec(parser->re_fwd, parser->re_fwd_extra, str, (int)strlen(str), 0, 0, ovec, ARRAYSIZE(ovec));
if (unlikely(rc < 0)) {
return false;
}
bool add = true;
if (ZPCRE_SO(ovec, 1) != -1) { // "rm" prefix
add = false;
}
const char *proto_str = str + ZPCRE_SO(ovec, 2);
const char *port_str = str + ZPCRE_SO(ovec, 3);
const char *ipport_str = (-1 != ZPCRE_SO(ovec, 4)) ? (str + ZPCRE_SO(ovec, 4)) : NULL;
zip_proto_t proto = ('T' == toupper(*proto_str)) ? PROTO_TCP : PROTO_UDP;
uint16_t port = 0;
if (0 != str_to_u16(port_str, &port)) {
return false;
}
port = htons(port);
struct sockaddr_in sa;
if (add) {
if (!ipport_str) {
return false;
}
int sa_len = sizeof(sa);
if (0 != evutil_parse_sockaddr_port(ipport_str, (struct sockaddr *) &sa, &sa_len)) {
return false;
}
} else if (ipport_str) {
return false;
}
zcr_forward_t *item = malloc(sizeof(*item));
item->add = add;
item->proto = proto;
item->port = port;
if (add) {
item->fwd_ip = sa.sin_addr.s_addr;
item->fwd_port = sa.sin_port;
} else {
item->fwd_ip = 0;
item->fwd_port = 0;
}
utarray_push_back(&rules->fwd_rules, &item);
rules->have.fwd_rules = 1;
return true;
}
/**
* Parse deferred rule.
* @param[in] rules
* @param[in] str
* @return Zero on success.
*/
static bool parse_deferred(const zclient_rule_parser_t *parser, zclient_rules_t *rules, const char *str)
{
int ovec[ZPCRE_DECL_SIZE(1+2)];
int rc = pcre_exec(parser->re_deferred, parser->re_deferred_extra, str, (int)strlen(str), 0, 0, ovec, ARRAYSIZE(ovec));
if (unlikely(rc < 0)) {
return false;
}
const char *when_str = str + ZPCRE_SO(ovec, 1);
const char *rule_str = str + ZPCRE_SO(ovec, 2);
uint64_t when = 0;
if (0 != str_to_u64(when_str, &when)) {
return false;
}
zcr_deferred_t *def_rule = NULL;
def_rule = malloc(sizeof(*def_rule));
def_rule->when = when;
def_rule->rule = strdup(rule_str);
utarray_push_back(&rules->deferred_rules, &def_rule);
rules->have.deferred_rules = 1;
return true;
}
/**
* Parse rmdeferred rule.
* @param[in] rules
* @param[in] str
* @return Zero on success.
*/
static bool parse_rmdeferred(const zclient_rule_parser_t *parser, zclient_rules_t *rules, const char *str)
{
(void)parser;
(void)str;
rules->have.rmdeferred = 1;
return true;
}
/**
* Parse client rule.
* @param[in] rules
* @param[in] str
* @return Zero on success.
*/
bool zclient_rule_parse(const zclient_rule_parser_t *parser, zclient_rules_t *rules, const char *str)
{
bool ok = false;
// identity.<userid>.<login>
if (0 == strncmp(str, CLIENT_RULE_IDENTITY, STRLEN_STATIC(CLIENT_RULE_IDENTITY))) {
ok = parse_identity(parser, rules, str);
}
// bw.<speed>KBit.<up|down>
else if (0 == strncmp(str, CLIENT_RULE_BW, STRLEN_STATIC(CLIENT_RULE_BW))) {
ok = parse_bw(parser, rules, str);
}
// ports.<allow|deny>.<tcp|udp>.<port1>[.<port2>]
else if (0 == strncmp(str, CLIENT_RULE_PORTS, STRLEN_STATIC(CLIENT_RULE_PORTS))) {
ok = parse_ports(parser, rules, str);
}
// rmports.<allow|deny>.<tcp|udp>.<port1>[.<port2>]
else if (0 == strncmp(str, CLIENT_RULE_RMPORTS, STRLEN_STATIC(CLIENT_RULE_RMPORTS))) {
ok = parse_ports(parser, rules, str);
}
// fwd.<tcp|udp>.<port>.<ip>[:<port>]
else if (0 == strncmp(str, CLIENT_RULE_FWD, STRLEN_STATIC(CLIENT_RULE_FWD))) {
ok = parse_fwd(parser, rules, str);
}
// rmfwd.<tcp|udp>.<port>
else if (0 == strncmp(str, CLIENT_RULE_RMFWD, STRLEN_STATIC(CLIENT_RULE_RMFWD))) {
ok = parse_fwd(parser, rules, str);
}
// deferred.<seconds>.<rule>
else if (0 == strncmp(str, CLIENT_RULE_DEFERRED, STRLEN_STATIC(CLIENT_RULE_DEFERRED))) {
ok = parse_deferred(parser, rules, str);
}
// rmdeferred
else if (0 == strcmp(str, CLIENT_RULE_RMDEFERRED)) {
ok = parse_rmdeferred(parser, rules, str);
}
return ok;
}
/**
* Initialize client rules.
* @param[in,out] rules
*/
void zclient_rules_init(zclient_rules_t *rules)
{
memset(rules, 0, sizeof(*rules));
utarray_init(&rules->fwd_rules, &ut_ptr_icd);
utarray_init(&rules->port_rules, &ut_ptr_icd);
utarray_init(&rules->deferred_rules, &ut_ptr_icd);
}
/**
* Free internally allocated memory for client config.
* @param[in] cfg
*/
void zclient_rules_destroy(zclient_rules_t *rules)
{
if (rules->login) free(rules->login);
for (size_t i = 0; i < utarray_len(&rules->port_rules); i++) {
zcr_port_t *rule = *(zcr_port_t **) utarray_eltptr(&rules->port_rules, i);
free(rule);
}
utarray_done(&rules->port_rules);
for (size_t i = 0; i < utarray_len(&rules->fwd_rules); i++) {
zcr_forward_t *rule = *(zcr_forward_t **) utarray_eltptr(&rules->fwd_rules, i);
free(rule);
}
utarray_done(&rules->fwd_rules);
for (size_t i = 0; i < utarray_len(&rules->deferred_rules); i++) {
zcr_deferred_t *rule = *(zcr_deferred_t **) utarray_eltptr(&rules->deferred_rules, i);
free(rule->rule);
free(rule);
}
utarray_done(&rules->deferred_rules);
}
/**
* Make rule "identity".
* @param[in,out] string Output buffer.
* @param[in] user_id User id.
* @param[in] login Login.
*/
void zclient_rules_make_identity(UT_string *string, uint32_t user_id, const char *login)
{
// identity.<user_id>.<login>
utstring_printf(string, "%s%" PRIu32 ".%s", CLIENT_RULE_IDENTITY, user_id, login);
}
/**
* Make rule "bw".
* @param[in,out] string Output buffer.
* @param[in] speed Speed limit.
* @param[in] flow_dir Flow direction.
*/
void zclient_rules_make_bw(UT_string *string, uint64_t bw, zflow_dir_t flow_dir)
{
// bw.<bw>KBit.<up|down>
bw = bw * 8 / 1024;
const char *dir = (DIR_UP == flow_dir) ? STR_UP : STR_DOWN;
utstring_printf(string, "%s%" PRIu64 "KBit.%s", CLIENT_RULE_BW, bw, dir);
}
/**
* Make rule "ports".
* @param[in,out] string Output buffer.
* @param[in] proto Protocol.
* @param[in] type Rule type.
* @param[in] ports Array of ports (network order).
* @param[in] count Number of elements in ports array.
*/
void zclient_rules_make_ports(UT_string *string, zip_proto_t proto, zfwall_policy_t policy, const uint16_t *ports,
size_t count)
{
// ports.<allow|deny>.<tcp|udp>.<port1>[.<port2>]
const char *proto_str = PROTO_TCP == proto ? STR_TCP : STR_UDP;
const char *rule_str = ACCESS_ALLOW == policy ? STR_ALLOW : STR_DENY;
utstring_printf(string, "%s%s.%s", CLIENT_RULE_PORTS, rule_str, proto_str);
for (size_t i = 0; i < count; i++) {
utstring_printf(string, ".%" PRIu16, ntohs(ports[i]));
}
}
/**
* Make rule "forward".
* @param[in,out] string Output buffer.
* @param[in] proto Protocol.
* @param[in] fwd_rule Forwarding rule.
*/
void zclient_rules_make_fwd(UT_string *string, zip_proto_t proto, const zfwd_rule_t *fwd_rule)
{
// forward.<tcp|udp>.<port>.<ip>[:<port>]
char fwd_ip_str[INET_ADDRSTRLEN];
const char *proto_str = PROTO_TCP == proto ? STR_TCP : STR_UDP;
ipv4_to_str(fwd_rule->fwd_ip, fwd_ip_str, sizeof(fwd_ip_str));
utstring_printf(string, "%s%s.%" PRIu16 ".%s", CLIENT_RULE_FWD, proto_str, ntohs(fwd_rule->port), fwd_ip_str);
if (fwd_rule->fwd_port) {
utstring_printf(string, ":%" PRIu16, ntohs(fwd_rule->fwd_port));
}
}
/**
* Make rule "speed".
* @param[in,out] string Output buffer.
* @param speed Speed.
* @param flow_dir Flow direction.
*/
void zclient_rules_make_speed(UT_string *string, uint64_t speed, zflow_dir_t flow_dir)
{
static const char *prefixes[] = {"bps", "Kbps", "Mbps", "Gbps", "Tbps", "Pbps", "Ebps", "Zbps"};
const char *dir = (DIR_UP == flow_dir) ? STR_UP : STR_DOWN;
size_t i = 0;
while (speed >= 1024) {
i++;
speed /= 1024;
}
utstring_printf(string, "%s.%" PRIu64 ".%s.%s", STR_SPEED, speed, prefixes[i], dir);
}
/**
* Make rule "session".
* @param[in,out] string Output buffer.
* @param[in] ip Session IP address.
*/
void zclient_rules_make_session(UT_string *string, const char *ip)
{
utstring_printf(string, "%s.%s", STR_SESSION, ip);
}
/**
* Make deferred rule.
* @param[in,out] string Output buffer.
* @param[in] def_rule Deferred rule.
*/
void zclient_rules_make_deferred(UT_string *string, const zcr_deferred_t *def_rule)
{
zclock_t cur_clock = zclock();
uint64_t when = (def_rule->when > cur_clock) ? USEC2SEC(def_rule->when - cur_clock) : 0;
utstring_printf(string, "%s%" PRIu64 ".%s", CLIENT_RULE_DEFERRED, when, def_rule->rule);
}
/**
* Deferred rule time comparator.
* @param[in] arg1
* @param[in] arg2
* @return Same as strcmp with inversion.
*/
int zcr_deferred_cmp(const void *arg1, const void *arg2)
{
const zcr_deferred_t *rule1 = *(const zcr_deferred_t **) arg1, *rule2 = *(const zcr_deferred_t **) arg2;
if (rule1->when > rule2->when) return -1;
if (rule1->when < rule2->when) return 1;
return 0;
}
/**
* Duplicate deferred rule.
* @param[in] Source deferred rules.
* @return Duplicate.
*/
zcr_deferred_t *zcr_deferred_dup(const zcr_deferred_t *src)
{
zcr_deferred_t *dup = malloc(sizeof(*src));
if (!dup) {
return NULL;
}
dup->when = src->when;
dup->rule = strdup(src->rule);
return dup;
}
| 2 | 2 |
2024-11-18T20:55:57.686529+00:00 | 2016-10-16T13:53:21 | 239536c3befef1a9222090ee5108bc97a176b034 | {
"blob_id": "239536c3befef1a9222090ee5108bc97a176b034",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-16T13:53:21",
"content_id": "12c5c4681cd10e37413fa0c540ab64b1d0bb54b0",
"detected_licenses": [
"MIT"
],
"directory_id": "49e3814e0a7f9b354675b1828fe2d207fcaa857c",
"extension": "c",
"filename": "tabulation.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 71052935,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2177,
"license": "MIT",
"license_type": "permissive",
"path": "/src/termcap_interface/key_tools/tabulation.c",
"provenance": "stackv2-0092.json.gz:58245",
"repo_name": "KASOGIT/42sh",
"revision_date": "2016-10-16T13:53:21",
"revision_id": "3f494e8f2e636951e041157b8e123cdf3f308c61",
"snapshot_id": "a03be71f6220fe359813b1a6cc54981785a73300",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/KASOGIT/42sh/3f494e8f2e636951e041157b8e123cdf3f308c61/src/termcap_interface/key_tools/tabulation.c",
"visit_date": "2021-01-11T01:09:53.401617"
} | stackv2 | /*
** tab.c for 42sh in /home/benjamin/rendu/C/PSU/PSU_2014_42sh
**
** Made by Benjamin Rascol
** Login <rascol_b@epitech.net>
**
** Started on Thu May 21 19:57:18 2015 Benjamin Rascol
** Last update Sun May 24 14:20:37 2015 Manuel Trambert
*/
#include "42sh.h"
static int display_tabulation(char **wordtab,
int nb_col, int max_word_len)
{
int i;
int nb_put;
i = 0;
nb_put = 0;
while (wordtab[i])
{
my_putstr(wordtab[i]);
if (nb_put == nb_col)
{
nb_put = 0;
my_putchar('\n');
}
else
putnchar(' ', max_word_len - strlen(wordtab[i]) + 7);
nb_put++;
i++;
}
return (SUCCESS);
}
static int get_pos_end_str(char *str, int i_buffer)
{
int i;
i = i_buffer;
while (i != 0 && str[i] != ' ')
i -= 1;
return (i);
}
static char *add_end_str(char *str, char *end, int i_buffer)
{
int i;
int e;
int to_copy;
char *tmp;
i = 0;
e = 0;
if ((tmp = malloc(sizeof(*tmp) * (strlen(str) + strlen(end) + 2))) == NULL)
return (NULL);
to_copy = get_pos_end_str(str, i_buffer);
while (str[i] != '\0' && i != to_copy)
{
tmp[i] = str[i];
i += 1;
}
tmp[i++] = ' ';
while (end[e] != '\0')
{
tmp[i] = end[e];
i += 1;
e += 1;
}
tmp[i] = '\0';
free(str);
return (tmp);
}
int tabulation(char **command_buffer, int *i_buffer)
{
int max_word_len;
int nb_word;
int nb_col;
char **wordtab;
t_winsize *win_size;
wordtab = tabulation_gen(command_buffer, i_buffer);
my_putchar('\n');
if (wordtab != NULL && (nb_word = size_tab(wordtab)) == 1)
*command_buffer = add_end_str(*command_buffer, wordtab[0], *i_buffer);
else if (wordtab != NULL && nb_word > 1)
{
if ((win_size = termcap_get_win_size(GET_SIZE)) == NULL)
return (ERROR_MYSH);
max_word_len = get_max_word_len(wordtab);
if ((nb_col = win_size->x / (max_word_len + 8)) == 0)
nb_col = 1;
display_tabulation(wordtab, nb_col, max_word_len);
}
my_putchar('\n');
display_prompt();
my_putstr(*command_buffer);
*i_buffer = strlen(*command_buffer);
termcap_cursor_placing(*command_buffer, *i_buffer);
return (SUCCESS);
}
| 2.75 | 3 |
2024-11-18T20:55:57.797881+00:00 | 2018-05-23T06:55:18 | 3474686fef5ae3a8bff5ab9387acbc601a8709f9 | {
"blob_id": "3474686fef5ae3a8bff5ab9387acbc601a8709f9",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-23T06:55:18",
"content_id": "1ef906474cb38da5b7ee72cbd7c8036b96d75784",
"detected_licenses": [
"MIT"
],
"directory_id": "2bc3398063fd7251c46a2d93d2e301cd063befcd",
"extension": "c",
"filename": "juesha.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134525191,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2023,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/kungfu/skill/tianzhu-juedao/juesha.c",
"provenance": "stackv2-0092.json.gz:58373",
"repo_name": "HKMUD/NT6",
"revision_date": "2018-05-23T06:55:18",
"revision_id": "bb518e2831edc6a83d25eccd99271da06eba8176",
"snapshot_id": "ae6a3c173ea07c156e8dc387b3ec21f3280ee0be",
"src_encoding": "GB18030",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/HKMUD/NT6/bb518e2831edc6a83d25eccd99271da06eba8176/nitan/kungfu/skill/tianzhu-juedao/juesha.c",
"visit_date": "2020-03-18T08:44:12.400598"
} | stackv2 | // tie@fengyun
#include <ansi.h>
#include <combat.h>
inherit F_SSERVER;
int perform(object me, object target)
{
string msg;
int extra;
object weapon;
extra = me->query_skill("tianzhu-juedao",1);
if ( extra < 150) return notify_fail("你的天竺绝刀还不够纯熟!\n");
if( !target ) target = offensive_target(me);
if( !target || !me->is_fighting(target) )
return notify_fail("[天竺绝杀]只能对战斗中的对手使用。\n");
if( !objectp(weapon=query_temp("weapon", me) )
|| query("skill_type", weapon) != "blade" )
return notify_fail("你使用的武器不对。\n");
if (me->query_skill_mapped("blade") != "tianzhu-juedao")
return notify_fail("你还没有准备天竺绝刀!\n");
if( query("max_neili", me)<1600 )
return notify_fail("你内力修为不足!\n");
if( query("neili", me)<600 )
return notify_fail("你内力不够!\n");
weapon=query_temp("weapon", me);
addn("neili", -400, me);
addn("jingli", -100, me);
msg = HIY "$N使出天竺绝刀中的[天竺绝杀],一招连环三式,手中的"+
weapon->name()+ HIY"闪电般向$n攻出!\n"
"第一刀!" NOR;
message_vision(msg,me,target);
addn_temp("apply/damage", 200, me);
addn_temp("apply/attack", 400, me);
COMBAT_D->do_attack(me,target,query_temp("weapon", me),TYPE_REGULAR,msg);
msg = HIY "第二刀!" NOR;
message_vision(msg,me,target);
COMBAT_D->do_attack(me,target,query_temp("weapon", me),TYPE_REGULAR,msg);
msg = HIY "第三刀!" NOR;
message_vision(msg,me,target);
COMBAT_D->do_attack(me,target,query_temp("weapon", me),TYPE_REGULAR,msg);
me->start_busy(3);
addn_temp("apply/damage", -200, me);
addn_temp("apply/attack", -400, me);
return 1;
} | 2.125 | 2 |
2024-11-18T20:55:57.892291+00:00 | 2020-05-17T10:29:07 | b6b1250a7c64763a499813549238353b58c92bb4 | {
"blob_id": "b6b1250a7c64763a499813549238353b58c92bb4",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-17T10:29:07",
"content_id": "d0cf413246737fa58888ef76de2eb541a7930cf6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "edd70f42e11d41f7b58993c098fd147128e9a083",
"extension": "h",
"filename": "vfs.h",
"fork_events_count": 3,
"gha_created_at": "2019-10-08T04:23:16",
"gha_event_created_at": "2020-01-29T14:50:16",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 213548224,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1504,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/vfs.h",
"provenance": "stackv2-0092.json.gz:58502",
"repo_name": "tc17/lfs-tool",
"revision_date": "2020-05-17T10:29:07",
"revision_id": "4516ece8352c8bb3122e57deb49263c3153b544e",
"snapshot_id": "e80d413b4d49b954881ee15210b0bd99b11405ab",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/tc17/lfs-tool/4516ece8352c8bb3122e57deb49263c3153b544e/src/vfs.h",
"visit_date": "2020-08-07T18:16:51.859404"
} | stackv2 | // Copyright 2019 Sergey Tyultyaev
//
// 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.
#pragma once
#include <stdint.h>
#include <stdlib.h>
#define VFS_MAX_NAME_LEN 512
typedef enum {
VFS_TYPE_END = 0,
VFS_TYPE_FILE,
VFS_TYPE_DIR
} vfs_dirent_type_t;
struct vfs_dirent {
char name[VFS_MAX_NAME_LEN];
vfs_dirent_type_t type;
};
struct vfs
{
void *opaque;
void *(*open)(struct vfs *vfs, const char *pathname, int flags);
int (*close)(struct vfs *vfs, void *fd);
int32_t (*read)(struct vfs *vfs, void *fd, void *buf, size_t count);
int32_t (*write)(struct vfs *vfs, void *fd, const void *buf, size_t count);
int (*mount)(struct vfs *vfs);
int (*unmount)(struct vfs *vfs);
void *(*opendir)(struct vfs *vfs, const char *path);
int (*closedir)(struct vfs *vfs, void *dir);
struct vfs_dirent *(*readdir)(struct vfs *vfs, void *dir);
int (*mkdir)(struct vfs *vfs, const char *pathname);
};
| 2.125 | 2 |
2024-11-18T20:55:58.612540+00:00 | 2023-08-30T23:07:48 | 4e77054ce74b6274371908829c4e4b9e79aa7306 | {
"blob_id": "4e77054ce74b6274371908829c4e4b9e79aa7306",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T23:07:48",
"content_id": "4a1629cad512e1124bbf848503cce09a2762d6cc",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "8a51a96f61699f0318315ccc89cef39f6866f2b5",
"extension": "c",
"filename": "hstore_plperl.c",
"fork_events_count": 4807,
"gha_created_at": "2010-09-21T11:35:45",
"gha_event_created_at": "2023-09-09T13:59:15",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 927442,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3942,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/contrib/hstore_plperl/hstore_plperl.c",
"provenance": "stackv2-0092.json.gz:58632",
"repo_name": "postgres/postgres",
"revision_date": "2023-08-30T23:07:48",
"revision_id": "b5934bfd6071fed3a38cea0cfaa93afda63d9c0c",
"snapshot_id": "979febf2b41c00090d1256228f768f33e7ef3b6f",
"src_encoding": "UTF-8",
"star_events_count": 13691,
"url": "https://raw.githubusercontent.com/postgres/postgres/b5934bfd6071fed3a38cea0cfaa93afda63d9c0c/contrib/hstore_plperl/hstore_plperl.c",
"visit_date": "2023-08-31T00:10:01.373472"
} | stackv2 | #include "postgres.h"
#include "fmgr.h"
#include "hstore/hstore.h"
#include "plperl.h"
PG_MODULE_MAGIC;
/* Linkage to functions in hstore module */
typedef HStore *(*hstoreUpgrade_t) (Datum orig);
static hstoreUpgrade_t hstoreUpgrade_p;
typedef int (*hstoreUniquePairs_t) (Pairs *a, int32 l, int32 *buflen);
static hstoreUniquePairs_t hstoreUniquePairs_p;
typedef HStore *(*hstorePairs_t) (Pairs *pairs, int32 pcount, int32 buflen);
static hstorePairs_t hstorePairs_p;
typedef size_t (*hstoreCheckKeyLen_t) (size_t len);
static hstoreCheckKeyLen_t hstoreCheckKeyLen_p;
typedef size_t (*hstoreCheckValLen_t) (size_t len);
static hstoreCheckValLen_t hstoreCheckValLen_p;
/*
* Module initialize function: fetch function pointers for cross-module calls.
*/
void
_PG_init(void)
{
/* Asserts verify that typedefs above match original declarations */
AssertVariableIsOfType(&hstoreUpgrade, hstoreUpgrade_t);
hstoreUpgrade_p = (hstoreUpgrade_t)
load_external_function("$libdir/hstore", "hstoreUpgrade",
true, NULL);
AssertVariableIsOfType(&hstoreUniquePairs, hstoreUniquePairs_t);
hstoreUniquePairs_p = (hstoreUniquePairs_t)
load_external_function("$libdir/hstore", "hstoreUniquePairs",
true, NULL);
AssertVariableIsOfType(&hstorePairs, hstorePairs_t);
hstorePairs_p = (hstorePairs_t)
load_external_function("$libdir/hstore", "hstorePairs",
true, NULL);
AssertVariableIsOfType(&hstoreCheckKeyLen, hstoreCheckKeyLen_t);
hstoreCheckKeyLen_p = (hstoreCheckKeyLen_t)
load_external_function("$libdir/hstore", "hstoreCheckKeyLen",
true, NULL);
AssertVariableIsOfType(&hstoreCheckValLen, hstoreCheckValLen_t);
hstoreCheckValLen_p = (hstoreCheckValLen_t)
load_external_function("$libdir/hstore", "hstoreCheckValLen",
true, NULL);
}
/* These defines must be after the module init function */
#define hstoreUpgrade hstoreUpgrade_p
#define hstoreUniquePairs hstoreUniquePairs_p
#define hstorePairs hstorePairs_p
#define hstoreCheckKeyLen hstoreCheckKeyLen_p
#define hstoreCheckValLen hstoreCheckValLen_p
PG_FUNCTION_INFO_V1(hstore_to_plperl);
Datum
hstore_to_plperl(PG_FUNCTION_ARGS)
{
dTHX;
HStore *in = PG_GETARG_HSTORE_P(0);
int i;
int count = HS_COUNT(in);
char *base = STRPTR(in);
HEntry *entries = ARRPTR(in);
HV *hv;
hv = newHV();
for (i = 0; i < count; i++)
{
const char *key;
SV *value;
key = pnstrdup(HSTORE_KEY(entries, base, i),
HSTORE_KEYLEN(entries, i));
value = HSTORE_VALISNULL(entries, i) ? newSV(0) :
cstr2sv(pnstrdup(HSTORE_VAL(entries, base, i),
HSTORE_VALLEN(entries, i)));
(void) hv_store(hv, key, strlen(key), value, 0);
}
return PointerGetDatum(newRV((SV *) hv));
}
PG_FUNCTION_INFO_V1(plperl_to_hstore);
Datum
plperl_to_hstore(PG_FUNCTION_ARGS)
{
dTHX;
SV *in = (SV *) PG_GETARG_POINTER(0);
HV *hv;
HE *he;
int32 buflen;
int32 i;
int32 pcount;
HStore *out;
Pairs *pairs;
/* Dereference references recursively. */
while (SvROK(in))
in = SvRV(in);
/* Now we must have a hash. */
if (SvTYPE(in) != SVt_PVHV)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot transform non-hash Perl value to hstore")));
hv = (HV *) in;
pcount = hv_iterinit(hv);
pairs = palloc(pcount * sizeof(Pairs));
i = 0;
while ((he = hv_iternext(hv)))
{
char *key = sv2cstr(HeSVKEY_force(he));
SV *value = HeVAL(he);
pairs[i].key = pstrdup(key);
pairs[i].keylen = hstoreCheckKeyLen(strlen(pairs[i].key));
pairs[i].needfree = true;
if (!SvOK(value))
{
pairs[i].val = NULL;
pairs[i].vallen = 0;
pairs[i].isnull = true;
}
else
{
pairs[i].val = pstrdup(sv2cstr(value));
pairs[i].vallen = hstoreCheckValLen(strlen(pairs[i].val));
pairs[i].isnull = false;
}
i++;
}
pcount = hstoreUniquePairs(pairs, pcount, &buflen);
out = hstorePairs(pairs, pcount, buflen);
PG_RETURN_POINTER(out);
}
| 2.140625 | 2 |
2024-11-18T20:55:59.756798+00:00 | 2023-04-08T00:57:44 | 5c3fd82f31f9b9a4e4127731ad58f6c8feb3d316 | {
"blob_id": "5c3fd82f31f9b9a4e4127731ad58f6c8feb3d316",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-08T00:57:44",
"content_id": "40e9d078f01e72dcfed8c774ec8e8241523155a2",
"detected_licenses": [
"MIT"
],
"directory_id": "b01497ea522e7db5987ae2b9a506e4b7e3926266",
"extension": "c",
"filename": "i2c_util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 158279658,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 870,
"license": "MIT",
"license_type": "permissive",
"path": "/i2c_util.c",
"provenance": "stackv2-0092.json.gz:58760",
"repo_name": "viktorradnai/bluepilljs",
"revision_date": "2023-04-08T00:57:44",
"revision_id": "c3a16e6d5a1f42030809aa03958f72a972a1a6a3",
"snapshot_id": "5d7e85f831755a6ec342a417514eae677924a4a8",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/viktorradnai/bluepilljs/c3a16e6d5a1f42030809aa03958f72a972a1a6a3/i2c_util.c",
"visit_date": "2023-04-17T14:22:13.974516"
} | stackv2 | #include "hal.h"
#include "ch.h"
#include "chprintf.h"
#include "i2c_util.h"
extern SerialUSBDriver SDU1;
bool_t i2c_write(I2CDriver *device, uint8_t addr, uint8_t *tx, uint8_t txsize, uint8_t *rx, uint8_t rxsize)
{
msg_t res;
i2cAcquireBus(device);
res = i2cMasterTransmitTimeout(device, addr, tx, txsize, rx, rxsize, 100);
i2cReleaseBus(device);
switch (res) {
case MSG_OK:
return TRUE;
case MSG_RESET:
chprintf((BaseSequentialStream *)&SDU1, "I2C Reset, addr: %02x\r\n", addr);
return FALSE;
case MSG_TIMEOUT:
chprintf((BaseSequentialStream *)&SDU1, "I2C timeout, addr: %02x\r\n", addr);
return FALSE;
default:
chprintf((BaseSequentialStream *)&SDU1, "I2C unknown result: %x, addr: %02x\r\n", res, addr);
return FALSE;
}
}
| 2.140625 | 2 |
2024-11-18T20:55:59.829275+00:00 | 2023-06-21T09:22:57 | 8303399ea6f7bc9fef3ebddc8b355852e188243a | {
"blob_id": "8303399ea6f7bc9fef3ebddc8b355852e188243a",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-15T03:50:17",
"content_id": "4ea38505a7cbefa65e2fb43bf64478c1585df798",
"detected_licenses": [
"MIT"
],
"directory_id": "5fdaec353b93b273d117c5ef1ca7d2352f4bad4b",
"extension": "h",
"filename": "papi_defs.h",
"fork_events_count": 68,
"gha_created_at": "2016-12-09T09:35:40",
"gha_event_created_at": "2023-07-15T03:50:18",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 76021818,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1481,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/mvt/papi_defs.h",
"provenance": "stackv2-0092.json.gz:58890",
"repo_name": "bondhugula/pluto",
"revision_date": "2023-06-21T09:22:57",
"revision_id": "eddc38537d61cd49d55e454831086848d51473d7",
"snapshot_id": "1ddf0bf53dc8a9c50f895018b2810558441e85f3",
"src_encoding": "UTF-8",
"star_events_count": 242,
"url": "https://raw.githubusercontent.com/bondhugula/pluto/eddc38537d61cd49d55e454831086848d51473d7/examples/mvt/papi_defs.h",
"visit_date": "2023-07-21T19:53:05.377621"
} | stackv2 | #ifdef PERFCTR
#define PERF_INIT \
int err, EventSet = PAPI_NULL; \
int papi_events[2] = {PAPI_L1_DCM, PAPI_L2_TCM}; \
long long CtrValues[4]; \
\
/* --- SETUP --- Configure PAPI events ------------------ */ \
printf("Initializing PAPI Hardware Performance Counters:\n"); \
err = PAPI_library_init(PAPI_VER_CURRENT); \
if (err != PAPI_VER_CURRENT) { \
fprintf(stderr, "Error initializing PAPI: Version mismatch. Expected %d, got %d\n", PAPI_VER_CURRENT, err); \
perror("System error (mostly a perfctr device permission problem)\n"); \
exit(1); \
} \
\
/* Create Event Set */ \
if (PAPI_create_eventset(&EventSet) != PAPI_OK) { \
printf("Failed to create PAPI Event Set\n"); \
exit(1); \
} \
\
/* Add Total Instructions Executed to our EventSet */ \
if (PAPI_query_event(PAPI_L1_DCM) == PAPI_OK) { \
printf(" * PAPI will count L1 misses\n"); \
err = PAPI_add_event(EventSet, papi_events[0]); \
} \
if (err != PAPI_OK) { \
printf("Failed to add PAPI event\n"); \
exit(1); \
} \
if (PAPI_query_event(PAPI_L2_TCM) == PAPI_OK) { \
printf(" * PAPI will count L2 misses\n"); \
err = PAPI_add_event(EventSet, papi_events[1]); \
} \
if (err != PAPI_OK) { \
printf("Failed to add PAPI event\n"); \
exit(1); \
} \
PAPI_start(EventSet);
#define PERF_EXIT \
PAPI_stop(EventSet, &CtrValues[0]); \
printf("L1 D cache misses: %ld\n", CtrValues[0]); \
printf("L2 (total) cache misses: %ld\n", CtrValues[1]);
#endif
| 2.59375 | 3 |
2024-11-18T20:56:00.194816+00:00 | 2017-12-14T10:03:09 | dab791878b758fa041845030b36a05e9135d01b9 | {
"blob_id": "dab791878b758fa041845030b36a05e9135d01b9",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-14T10:03:09",
"content_id": "7237df7b14dc7ccd2a4ae53c0f020b526f69bfc7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "32114e480a0e24788bb6ca7392270f5e7a53ae8a",
"extension": "c",
"filename": "fapp_sntp.c",
"fork_events_count": 1,
"gha_created_at": "2018-01-17T01:48:27",
"gha_event_created_at": "2018-01-17T01:48:27",
"gha_language": null,
"gha_license_id": null,
"github_id": 117767661,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4761,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/fnet_demos/common/fnet_application/fapp_sntp.c",
"provenance": "stackv2-0092.json.gz:59019",
"repo_name": "lianzeng/FNET",
"revision_date": "2017-12-14T10:03:09",
"revision_id": "9a8b44a17f65783899464dc4e9f78f1db9d419e6",
"snapshot_id": "a8b4dd6ce9fcb8ad037908c1456d4e89cb43ef6b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lianzeng/FNET/9a8b44a17f65783899464dc4e9f78f1db9d419e6/fnet_demos/common/fnet_application/fapp_sntp.c",
"visit_date": "2021-05-11T16:30:23.488416"
} | stackv2 | /**************************************************************************
*
* Copyright 2017 by Andrey Butok. FNET Community.
*
***************************************************************************
*
* 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.
*
***************************************************************************
*
* FNET Shell Demo implementation (SNTP client).
*
***************************************************************************/
#include "fapp.h"
#include "fapp_prv.h"
#include "fapp_sntp.h"
#include "fnet.h"
#if FAPP_CFG_SNTP_CMD && FNET_CFG_SNTP
/************************************************************************
* Definitions.
*************************************************************************/
#define FNET_SNTP_RESOLUTION_FAILED "Time resolution is FAILED"
#define FNET_SNTP_UNKNOWN "SNTP server is unknown"
/************************************************************************
* Function Prototypes
*************************************************************************/
static void fapp_sntp_callback_resolved (const fnet_sntp_timestamp_t *timestamp, void *cookie);
static void fapp_sntp_on_ctrlc(fnet_shell_desc_t desc, void *cookie);
/************************************************************************
* DESCRIPTION: Event handler callback on resolved time over SNTP.
************************************************************************/
static void fapp_sntp_callback_resolved (const fnet_sntp_timestamp_t *timestamp, void *cookie)
{
fnet_shell_desc_t desc = (fnet_shell_desc_t) cookie;
fnet_sntp_utc_t utc;
fnet_shell_unblock((fnet_shell_desc_t)cookie); /* Unblock the shell. */
if(timestamp)
{
fnet_sntp_timestamp2utc(timestamp, &utc);
fnet_shell_println(desc, " UTC: %u-%u-%u %u:%u:%u.%u", utc.year, utc.month, utc.day, utc.hour, utc.minute, utc.second, utc.millisecond);
}
else
{
fnet_shell_println(desc, FNET_SNTP_RESOLUTION_FAILED);
}
}
/************************************************************************
* DESCRIPTION: Ctr+C termination handler.
************************************************************************/
static void fapp_sntp_on_ctrlc(fnet_shell_desc_t desc, void *cookie)
{
/* Terminate SNTP service. */
fnet_sntp_release();
fnet_shell_println( desc, FAPP_CANCELLED_STR);
}
/************************************************************************
* DESCRIPTION: Start SNTP client.
************************************************************************/
void fapp_sntp_cmd( fnet_shell_desc_t desc, fnet_index_t argc, fnet_char_t **argv )
{
struct fnet_sntp_params sntp_params;
fnet_char_t ip_str[FNET_IP_ADDR_STR_SIZE];
fnet_index_t error_param;
FNET_COMP_UNUSED_ARG(argc);
/* Set SNTP client parameters.*/
fnet_memset_zero(&sntp_params, sizeof(struct fnet_sntp_params));
/* Set SNTP server address.*/
if(fnet_inet_ptos(argv[1], &sntp_params.sntp_server_addr) == FNET_ERR)
{
error_param = 1u;
goto ERROR_PARAMETER;
}
sntp_params.callback = fapp_sntp_callback_resolved; /* Callback function.*/
sntp_params.cookie = desc; /* Application-specific parameter
which will be passed to fapp_sntp_callback_resolved().*/
/* Run SNTP client. */
if(fnet_sntp_init(&sntp_params) != FNET_ERR)
{
fnet_shell_println(desc, FAPP_DELIMITER_STR);
fnet_shell_println(desc, " SNTP Resolving");
fnet_shell_println(desc, FAPP_SHELL_INFO_FORMAT_S, "SNTP Server",
fnet_inet_ntop(sntp_params.sntp_server_addr.sa_family, sntp_params.sntp_server_addr.sa_data, ip_str, sizeof(ip_str)));
fnet_shell_println(desc, FAPP_TOCANCEL_STR);
fnet_shell_println(desc, FAPP_DELIMITER_STR);
fnet_shell_block(desc, fapp_sntp_on_ctrlc, FNET_NULL); /* Block the shell input.*/
}
else
{
fnet_shell_println(desc, FAPP_INIT_ERR, "SNTP");
}
return;
ERROR_PARAMETER:
fnet_shell_println(desc, FAPP_PARAM_ERR, argv[error_param]);
return;
}
#endif /* FAPP_CFG_SNTP_CMD && FNET_CFG_SNTP */
| 2.015625 | 2 |
2024-11-18T20:56:00.512446+00:00 | 2018-07-03T06:40:29 | 1415b5fedb8d97bbfc7b5c56747dadb98f6cc7a0 | {
"blob_id": "1415b5fedb8d97bbfc7b5c56747dadb98f6cc7a0",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-03T06:40:29",
"content_id": "ada6dd836e97926e31f034a469e79b779be42547",
"detected_licenses": [
"MIT"
],
"directory_id": "f05dbadaba9541f31f6e3db01535dbbbd328d85d",
"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": 1816,
"license": "MIT",
"license_type": "permissive",
"path": "/ig/igtoolbox/main.c",
"provenance": "stackv2-0092.json.gz:59276",
"repo_name": "ishine/NuPyTools",
"revision_date": "2018-07-03T06:40:29",
"revision_id": "4c8180d850fff175e24c302757ae745d62258bc0",
"snapshot_id": "e3daf40449dfcb5f8446188cc7130fd9e3a69785",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ishine/NuPyTools/4c8180d850fff175e24c302757ae745d62258bc0/ig/igtoolbox/main.c",
"visit_date": "2020-08-28T07:09:20.733823"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
extern char * igtest (char * szInput);
void PrintOutput (char *szOutput)
{
char *ptr;
if (strchr (szOutput, ' ') == NULL) // no spaces --> result comes from an igtree, not a nigtree
printf ("%s\n",szOutput);
else
{
ptr=strtok(szOutput, " ");
while (ptr!=NULL)
{
printf ("Candidate %s:", ptr);
ptr=strtok(NULL, " ");
if (ptr != NULL)
{ printf ("\t%s", ptr);
ptr=strtok(NULL, " ");
if (ptr != NULL)
{
printf ("\t%s\n", ptr);
ptr=strtok(NULL, " ");
}
}
}
}
}
void main (int argc, char **argv)
{
char input[256];
long position;
int argno;
char *szOutput;
if (argc==1)
{
position=ftell(stdin);
do
{
if (position==-1)
fprintf(stderr,"\nigtest:> ");
if (fgets ((char *)input, 256, stdin)!=NULL)
{
if (input[strlen((char *)input)-1] == '\n')
(input[strlen((char *)input)-1] = '\0');
if (strlen (input) == 0)\
break;
szOutput=igtest (input);
if (szOutput != NULL)
PrintOutput (szOutput);
else
printf("wrong input format\n");
}
else
break;
}
while (1);
}
else
{
strcpy(input,"");
for (argno = 1; argno < argc; argno++)
{
strcat(input,argv[argno]);
strcat(input," ");
}
input[strlen((char *)input)-1] = '\0';
szOutput=igtest (input);
if (szOutput != NULL)
PrintOutput (szOutput);
else
printf("wrong input format\n");
}
exit(0);
}
| 3.0625 | 3 |
2024-11-18T20:56:00.650196+00:00 | 2023-07-07T14:19:43 | cb131948699573557b13d13d6d3501168d0083f0 | {
"blob_id": "cb131948699573557b13d13d6d3501168d0083f0",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-07T14:19:43",
"content_id": "9504535189397b6ddc74bdbfa816cf023b6e97b2",
"detected_licenses": [
"MIT"
],
"directory_id": "a00712528fef854d2c6fbe8c8c9a940ee88035bf",
"extension": "c",
"filename": "Font.c",
"fork_events_count": 199,
"gha_created_at": "2017-03-04T11:57:24",
"gha_event_created_at": "2023-03-28T23:01:15",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 83890107,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10623,
"license": "MIT",
"license_type": "permissive",
"path": "/Engine/Extension/Font.c",
"provenance": "stackv2-0092.json.gz:59405",
"repo_name": "scottcgi/Mojoc",
"revision_date": "2023-07-07T14:19:43",
"revision_id": "097dde01cad6111acc5e3015ad13c12c1f140243",
"snapshot_id": "c7f43344dfeeb604d8500024c34ac66d3567df1a",
"src_encoding": "UTF-8",
"star_events_count": 1209,
"url": "https://raw.githubusercontent.com/scottcgi/Mojoc/097dde01cad6111acc5e3015ad13c12c1f140243/Engine/Extension/Font.c",
"visit_date": "2023-07-20T14:15:05.546293"
} | stackv2 | /*
* Copyright (c) scott.cgi All Rights Reserved.
*
* This source code belongs to project Mojoc, which is a pure C Game Engine hosted on GitHub.
* The Mojoc Game Engine is licensed under the MIT License, and will continue to be iterated with coding passion.
*
* License : https://github.com/scottcgi/Mojoc/blob/master/LICENSE
* GitHub : https://github.com/scottcgi/Mojoc
* CodeStyle: https://github.com/scottcgi/Mojoc/blob/master/Docs/CodeStyle.md
*
* Since : 2016-7-27
* Update : 2021-2-8
* Author : scott.cgi
*/
#include <stdio.h>
#include <string.h>
#include "Engine/Toolkit/Utils/ArrayIntSet.h"
#include "Engine/Extension/Font.h"
#include "Engine/Toolkit/Platform/Log.h"
#include "Engine/Graphics/OpenGL/SubMesh.h"
static ArrayList(Font*) fontCacheList[1] = AArrayList_Init(Font*, 5);
static ArrayList(FontText*) textCacheList[1] = AArrayList_Init(FontText*, 30);
static Font* Get(const char* filePath)
{
TextureAtlas* textureAtlas = ATextureAtlas->Get(filePath);
ALog_A
(
textureAtlas->textureList->size == 1,
"Font not support TextureAtlas has multiple texture"
);
Font* font = AArrayList_Pop(fontCacheList, Font*);
if (font == NULL)
{
font = malloc(sizeof(Font));
AMesh->InitWithCapacity
(
AArrayList_Get(textureAtlas->textureList, 0, Texture*),
50,
font->mesh
);
AArrayIntSet->Init(font->fontTextSet);
AArrayList ->Init(sizeof(SubMesh*), font->unusedSubMeshList);
}
else
{
AArrayIntSet->Clear(font->fontTextSet);
AArrayList ->Clear(font->unusedSubMeshList);
AMesh ->Clear(font->mesh);
}
font->textureAtlas = textureAtlas;
return font;
}
static FontText* GetText(Font* font)
{
FontText* text = AArrayList_Pop(textCacheList, FontText*);
if (text == NULL)
{
text = malloc(sizeof(FontText));
AArrayList->Init(sizeof(SubMesh*), text->usedSubMeshList);
text->usedSubMeshList->increase = 10;
}
else
{
AArrayList->Clear(text->usedSubMeshList);
}
// reset drawable
ADrawable->Init(text->drawable);
text->alignment = FontTextAlignment_HorizontalLeft;
text->charSpacing = 0.0f;
text->font = font;
AArrayIntSet->TryAdd(font->fontTextSet, (intptr_t) text);
return text;
}
static void Draw(Font* font)
{
for (int i = 0; i < font->fontTextSet->elementList->size; ++i)
{
ADrawable->Draw(AArrayList_Get(font->fontTextSet->elementList, i, FontText*)->drawable);
}
AMesh_Draw(font->mesh);
}
static inline TextureAtlasQuad* GetAtlasQuad(FontText* text, const char* str, int index)
{
TextureAtlasQuad* atlasQuad = ATextureAtlas_GetQuad(text->font->textureAtlas, (char[2]) {str[index], '\0'});
ALog_A
(
atlasQuad != NULL,
"AFont SetString not found char = %c in TextureAtlas quads = %s",
str[index],
text->font->textureAtlas->filePath
);
return atlasQuad;
}
static inline void SetNewChar(FontText* text, const char* str, int len)
{
// set text new char
for (int i = 0; i < len; ++i)
{
TextureAtlasQuad* atlasQuad = GetAtlasQuad(text, str, i);
SubMesh* subMesh = AArrayList_Get(text->usedSubMeshList, i, SubMesh*);
ASubMesh->SetUVWithQuad
(
subMesh,
atlasQuad->quad
);
}
}
static void SetString(FontText* text, const char* str)
{
ArrayList* children = text->font->mesh->childList;
int len = (int) strlen(str);
text->drawable->height = 0.0f;
text->drawable->width = 0.0f;
if (len == text->usedSubMeshList->size)
{
SetNewChar(text, str, len);
}
else if (len > text->usedSubMeshList->size)
{
SetNewChar(text, str, text->usedSubMeshList->size);
int originalSize = children->size;
// add chars more than text has
for (int i = text->usedSubMeshList->size; i < len; ++i)
{
TextureAtlasQuad* atlasQuad = GetAtlasQuad(text, str, i);
SubMesh* subMesh;
if (text->font->unusedSubMeshList->size > 0)
{
subMesh = AArrayList_Pop(text->font->unusedSubMeshList, SubMesh*);
ADrawable_SetVisible(subMesh->drawable);
ADrawable_SetPositionSame2(subMesh->drawable, 0.0f);
ADrawable_SetColor(subMesh->drawable, COLOR_WHITE_ARRAY);
ASubMesh->SetUVWithQuad
(
subMesh,
atlasQuad->quad
);
if (subMesh->drawable->parent != text->drawable)
{
ADrawable_SetParent(subMesh->drawable, text->drawable);
}
}
else
{
// not enough SubMesh for text char so add SubMesh
subMesh = AMesh->AddChildWithQuad(text->font->mesh, atlasQuad->quad);
ADrawable_SetParent(subMesh->drawable, text->drawable);
}
AArrayList_Add(text->usedSubMeshList, subMesh);
}
if (originalSize != children->size)
{
// if regenerate the SubMesh's drawable the parent must visible,
// or parent property will lost
AMesh->GenerateBuffer(text->font->mesh);
}
}
else
{
SetNewChar(text, str, len);
// text has more chars remove it
for (int i = text->usedSubMeshList->size - 1; i >= len; --i)
{
SubMesh* subMesh = AArrayList_Get(text->usedSubMeshList, i, SubMesh*);
if (ADrawable_CheckVisible(subMesh->drawable))
{
ADrawable_SetInvisible(subMesh->drawable);
}
AArrayList->Remove(text->usedSubMeshList, i);
AArrayList_Add(text->font->unusedSubMeshList, subMesh);
}
}
// set text size arrangement and alignment
// set each char position
switch (text->alignment)
{
case FontTextAlignment_HorizontalLeft:
{
for (int i = 0; i < text->usedSubMeshList->size; ++i)
{
SubMesh* subMesh = AArrayList_Get(text->usedSubMeshList, i, SubMesh*);
if (subMesh->drawable->height > text->drawable->height)
{
text->drawable->height = subMesh->drawable->height;
}
ADrawable_SetPositionX(subMesh->drawable, text->drawable->width + subMesh->drawable->width / 2);
text->drawable->width += subMesh->drawable->width + text->charSpacing;
}
// remove the end space
text->drawable->width -= text->charSpacing;
break;
}
case FontTextAlignment_HorizontalRight:
{
for (int i = text->usedSubMeshList->size - 1; i > -1; --i)
{
SubMesh* subMesh = AArrayList_Get(text->usedSubMeshList, i, SubMesh*);
if (subMesh->drawable->height > text->drawable->height)
{
text->drawable->height = subMesh->drawable->height;
}
ADrawable_SetPositionX(subMesh->drawable, -text->drawable->width - subMesh->drawable->width / 2);
text->drawable->width += subMesh->drawable->width + text->charSpacing;
}
// remove the end space
text->drawable->width -= text->charSpacing;
break;
}
case FontTextAlignment_VerticalTop:
{
for (int i = 0; i < text->usedSubMeshList->size; ++i)
{
SubMesh* subMesh = AArrayList_Get(text->usedSubMeshList, i, SubMesh*);
if (subMesh->drawable->width > text->drawable->width)
{
text->drawable->width = subMesh->drawable->width;
}
ADrawable_SetPositionY(subMesh->drawable, -text->drawable->height - subMesh->drawable->height / 2);
text->drawable->height += subMesh->drawable->height + text->charSpacing;
}
// remove the end space
text->drawable->height -= text->charSpacing;
break;
}
case FontTextAlignment_VerticalBottom:
{
for (int i = text->usedSubMeshList->size - 1; i > -1; --i)
{
SubMesh* subMesh = AArrayList_Get(text->usedSubMeshList, i, SubMesh*);
if (subMesh->drawable->width > text->drawable->width)
{
text->drawable->width = subMesh->drawable->width;
}
ADrawable_SetPositionY(subMesh->drawable, text->drawable->height + subMesh->drawable->height / 2);
text->drawable->height += subMesh->drawable->height + text->charSpacing;
}
// remove the end space
text->drawable->height -= text->charSpacing;
break;
}
}
}
static void SetInt(FontText* text, int num)
{
// max int digits count
char buffer[12];
sprintf (buffer, "%d", num);
SetString(text, buffer);
}
static void SetFloat(FontText* text, float num)
{
// max float digits count
char buffer[20];
sprintf (buffer, "%.1f", num);
SetString(text, buffer);
}
static void Release(Font* font)
{
ALog_A(font->textureAtlas != NULL, "AFont Release font %p already Released", font);
for (int i = 0; i < font->fontTextSet->elementList->size; ++i)
{
FontText* text = AArrayList_Get(font->fontTextSet->elementList, i, FontText*);
text->font = NULL;
AArrayList_Add(textCacheList, text);
}
font->textureAtlas = NULL;
AArrayList_Add(fontCacheList, font);
}
static void ReleaseText(FontText* text)
{
ALog_A(text->font != NULL, "AFont ReleaseText text %p already Released", text);
for (int i = 0; i < text->usedSubMeshList->size; ++i)
{
SubMesh* subMesh = AArrayList_Get(text->usedSubMeshList, i, SubMesh*);
ADrawable_SetInvisible(subMesh->drawable);
AArrayList_Add(text->font->unusedSubMeshList, subMesh);
}
AArrayIntSet->TryRemove(text->font->fontTextSet, (intptr_t) text);
ADrawable_SetColor(text->drawable, COLOR_WHITE_ARRAY);
text->font = NULL;
AArrayList_Add(textCacheList, text);
}
struct AFont AFont[1] =
{{
Get,
GetText,
Draw,
SetString,
SetInt,
SetFloat,
Release,
ReleaseText,
}};
| 2.359375 | 2 |
2024-11-18T20:56:00.828132+00:00 | 2019-03-21T07:09:22 | 42673364e3b6c5e4c70ae5b42fffd91198f4a853 | {
"blob_id": "42673364e3b6c5e4c70ae5b42fffd91198f4a853",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-21T07:09:22",
"content_id": "7ef0a9f2191c4bbc69e82da292a872c1020384b8",
"detected_licenses": [
"MIT"
],
"directory_id": "2c32261b06117195010496f58f02f7bf41dae5e8",
"extension": "h",
"filename": "lmice_ring.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 165335829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5392,
"license": "MIT",
"license_type": "permissive",
"path": "/eal/lmice_ring.h",
"provenance": "stackv2-0092.json.gz:59664",
"repo_name": "LMiceOrg/lmalpha",
"revision_date": "2019-03-21T07:09:22",
"revision_id": "b5d647f1c1cea588841b866c2b9c47b2799c0f68",
"snapshot_id": "850da6c74c2bad43141692e7b954626ad363d110",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/LMiceOrg/lmalpha/b5d647f1c1cea588841b866c2b9c47b2799c0f68/eal/lmice_ring.h",
"visit_date": "2020-04-16T06:11:06.809555"
} | stackv2 | #ifndef LMICE_RING_H
#define LMICE_RING_H
#include <lmice_eal_align.h>
#include <lmice_eal_shm.h>
#include <stdint.h>
/* 容器的内存块最大数量 */
#define MAX_MEMORY_BLOCK_COUNT 16
/**
name: "LMiced shared memory block one"
hash: 36EE99391CA8AE12
*/
#define LMBLK_GID 0x36EE99391CA8AE12ULL
#define LMBLK_DEFAULT_SIZE (4096*16)
#define LMBLK_PAGE_SIZE 4096
/**
*@brief 共享内存块:
* MBlock
*
* OS isolate memory and other resources for security and general purpose,
* here for performance purpose and in one publisher multiple subscribers perspective
* SO shared memroy and spin-lock
*
* Identity(name, id, index):
* user: a specified name [string]
*
* platform: fixed length id [uint64]
* id = fnv1a(name), the unique value by FNV-1a hash function, in the public SP-Ring
*
* app: the index in the table [uint32]
* index = the order in app's private SP-Ring
*/
/**
*@brief 发布订阅环形状态容器:
* SP-Ring
*
* The Subscribe-Publish Ring container(SP-Ring) presents the way of message sharing with many subscribers, publishers and one maintainer.
*
* The maintainer is unique in each computer(or VM).
*
* Subscribers and publishers are in different processes different computers(or VMs).
*
* Subers and Pubers use their SP-Ring to communicate with the maintainer, and vice versa.
* Event be used for invoking others to work (one-to-one model).
*
* suber to mainter
*/
struct lmice_mblock_s {
uint64_t id; /* 标识符 */
uint32_t size; /* 大小(Bytes) */
#ifdef _WIN32
uint32_t reserved1;
#endif
shmfd_t fd; /* OS资源描述符 */
addr_t addr; /* 映射的进程地址 */
};
typedef struct lmice_mblock_s lmblk_t;
struct lmice_mblock_info_s {
uint64_t id; /* unique identity */
uint32_t size; /* size of bytes */
volatile int32_t rcount; /* reference count */
};
typedef struct lmice_mblock_info_s lmblk_info;
/**
* @brief The lmice_mesg_desc_status_enum_s enum 消息在队列中的状态
*/
enum lmice_spring_status_e {
LMSPR_WRONLY = 0,
LMSPR_RDWR = 1,
LMSPR_RDONLY /* 2, 3, ... */
};
struct lmice_spring_status_s {
int64_t timestamp;
volatile int32_t status; /* value lmice_spring_status_e */
uint32_t flag; /* reserved */
uint32_t blkindex;
uint32_t offset;
};
typedef struct lmice_spring_status_s lmspr_st;
struct lmice_spring_info_s {
/* description */
volatile int64_t lock; /* sync-purpose spinlock */
uint64_t id; /* identity */
uint32_t rcount; /* reference count */
uint32_t blkcount;
lmblk_info block[MAX_MEMORY_BLOCK_COUNT]; /* memory blocks*/
uint32_t blbcount; /* 当前数据块数量 */
uint32_t blbsize; /* 数据块大小(bytes) */
uint32_t capacity; /* 最大可读队列长度 */
uint32_t length; /* 当前可读队列长度 */
/* status list (fixed size) */
lmspr_st st[1]; /* capacity spr_sts */
/* blobs of data(optional) */
};
typedef struct lmice_spring_info_s lmspr_info;
struct lmice_spring_s {
uint32_t blkcount;
lmblk_t block[MAX_MEMORY_BLOCK_COUNT];
};
typedef struct lmice_spring_s lmspr_t;
int lmspr_readn(lmspr_t* spr, uint32_t n, lmspr_st **ppst, uint32_t* pn);
int lmspr_readp(lmspr_t* spr, int64_t ts, int64_t period, lmspr_st **ppst, uint32_t *pn);
int lmspr_release(lmspr_t* spr, lmspr_st* st, uint32_t n);
int lmspr_write(lmspr_t* spr, int64_t ts, void* blob, uint32_t size);
/** resource maintainer viewport */
/* Create a new Shared memory block */
int lmblk_create(lmblk_info*info, lmblk_t* blk);
int lmblk_open(lmblk_info* info, lmblk_t* blk);
int lmblk_close(lmblk_t* blk);
int lmblk_delete(lmblk_t* blk);
/* Create the SP-Ring container in the given memory block */
int lmspr_create(lmblk_info* info, uint64_t id, uint32_t blbcount, uint32_t blbsize,
uint32_t capacity, lmspr_t **pps);
int lmspr_delete(lmspr_t* ps);
int lmspr_open(lmblk_info* blk, lmspr_t ** pps);
#define lmspr_close(ps) do{ \
lmspr_delete(ps); \
} while(0);
/** worker(sub and pub) viewport */
/* initialize api */
int lmspr_init(int flag); /* initialize resource, thread only or not */
int lmspr_exit(); /* deallocate resources */
/* session api */
int lmspr_set_session_id(uint64_t session);
uint64_t lmspr_get_session_id();
/* register api */
int lmspr_register_publish_id(uint64_t instance, uint64_t type, uint32_t max_size);
int lmspr_register_subscribe_instance_id(uint64_t instance, uint64_t type, uint32_t capacity);
int lmspr_register_subscribe_type_id(uint64_t type, uint32_t capacity);
int lmspr_register_subscribe_topic_id(uint64_t topic, uint32_t capacity);
/* type api */
int lmspr_type_create_id(uint64_t type, uint32_t max_size);
/* topic api */
int lmspr_topic_create_id(uint64_t topic, const char* address, const char* port);
int lmspr_topic_add_instance_id(uint64_t topic, uint64_t instance, uint64_t type);
int lmspr_topic_add_type_id(uint64_t topic, uint64_t type);
#endif /** LMICE_RING_H */
| 2.0625 | 2 |
2024-11-18T20:56:01.174205+00:00 | 2023-09-03T15:11:13 | 592fd630dba10d4106280cbd62376d2a612c07ef | {
"blob_id": "592fd630dba10d4106280cbd62376d2a612c07ef",
"branch_name": "refs/heads/main",
"committer_date": "2023-09-03T15:11:13",
"content_id": "19991bd964b1d52171cc8d41fe87cfa9c1c4debd",
"detected_licenses": [
"Zlib"
],
"directory_id": "9eedaea06306b20520151321854f989a73c7daf8",
"extension": "c",
"filename": "gen_audio_resampler_filter.c",
"fork_events_count": 1605,
"gha_created_at": "2021-01-15T19:55:54",
"gha_event_created_at": "2023-09-13T19:12:26",
"gha_language": "C",
"gha_license_id": "Zlib",
"github_id": 330008801,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5475,
"license": "Zlib",
"license_type": "permissive",
"path": "/build-scripts/gen_audio_resampler_filter.c",
"provenance": "stackv2-0092.json.gz:59924",
"repo_name": "libsdl-org/SDL",
"revision_date": "2023-09-03T15:11:13",
"revision_id": "8387fae698745969ce366c4de9bcc1b4a364a7dd",
"snapshot_id": "cf56bdc8a9e198e9735201674118c822d0e3edf3",
"src_encoding": "UTF-8",
"star_events_count": 6912,
"url": "https://raw.githubusercontent.com/libsdl-org/SDL/8387fae698745969ce366c4de9bcc1b4a364a7dd/build-scripts/gen_audio_resampler_filter.c",
"visit_date": "2023-09-04T06:58:34.316952"
} | stackv2 | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/*
Built with:
gcc -o genfilter build-scripts/gen_audio_resampler_filter.c -lm && ./genfilter > src/audio/SDL_audio_resampler_filter.h
*/
/*
SDL's resampler uses a "bandlimited interpolation" algorithm:
https://ccrma.stanford.edu/~jos/resample/
This code pre-generates the kaiser tables so we don't have to do this at
run time, at a cost of about 20 kilobytes of static data in SDL. This code
used to be part of SDL itself and generated the tables on the first use,
but that was expensive to produce on platforms without floating point
hardware.
*/
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define RESAMPLER_ZERO_CROSSINGS 5
#define RESAMPLER_BITS_PER_SAMPLE 16
#define RESAMPLER_BITS_PER_ZERO_CROSSING ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1)
#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << RESAMPLER_BITS_PER_ZERO_CROSSING)
#define RESAMPLER_FILTER_SIZE (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS)
/* This is a "modified" bessel function, so you can't use POSIX j0() */
static double
bessel(const double x)
{
const double xdiv2 = x / 2.0;
double i0 = 1.0;
double f = 1.0;
int i = 1;
while (1) {
const double diff = pow(xdiv2, i * 2) / pow(f, 2);
if (diff < 1.0e-21) {
break;
}
i0 += diff;
i++;
f *= (double) i;
}
return i0;
}
/* build kaiser table with cardinal sine applied to it, and array of differences between elements. */
static void
kaiser_and_sinc(double *table, const int tablelen, const double beta)
{
const double bessel_beta = bessel(beta);
int i;
table[0] = 1.0;
for (i = 1; i < tablelen; i++) {
const double kaiser = bessel(beta * sqrt(1.0 - pow((double)i / (double)(tablelen), 2.0))) / bessel_beta;
const double x = (((double) i) / ((double) RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) * M_PI;
table[i] = kaiser * (sin(x) / x);
}
}
static double ResamplerFilter[RESAMPLER_FILTER_SIZE];
static void
PrepareResampleFilter(void)
{
/* if dB > 50, beta=(0.1102 * (dB - 8.7)), according to Matlab. */
const double dB = 80.0;
const double beta = 0.1102 * (dB - 8.7);
kaiser_and_sinc(ResamplerFilter, RESAMPLER_FILTER_SIZE, beta);
}
int main(void)
{
int i, j;
PrepareResampleFilter();
printf(
"/*\n"
" Simple DirectMedia Layer\n"
" Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>\n"
"\n"
" This software is provided 'as-is', without any express or implied\n"
" warranty. In no event will the authors be held liable for any damages\n"
" arising from the use of this software.\n"
"\n"
" Permission is granted to anyone to use this software for any purpose,\n"
" including commercial applications, and to alter it and redistribute it\n"
" freely, subject to the following restrictions:\n"
"\n"
" 1. The origin of this software must not be misrepresented; you must not\n"
" claim that you wrote the original software. If you use this software\n"
" in a product, an acknowledgment in the product documentation would be\n"
" appreciated but is not required.\n"
" 2. Altered source versions must be plainly marked as such, and must not be\n"
" misrepresented as being the original software.\n"
" 3. This notice may not be removed or altered from any source distribution.\n"
"*/\n"
"\n"
"/* DO NOT EDIT, THIS FILE WAS GENERATED BY build-scripts/gen_audio_resampler_filter.c */\n"
"\n"
"#define RESAMPLER_ZERO_CROSSINGS %d\n"
"#define RESAMPLER_BITS_PER_SAMPLE %d\n"
"#define RESAMPLER_BITS_PER_ZERO_CROSSING ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1)\n"
"#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << RESAMPLER_BITS_PER_ZERO_CROSSING)\n"
"#define RESAMPLER_FILTER_SIZE (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS)\n"
"\n", RESAMPLER_ZERO_CROSSINGS, RESAMPLER_BITS_PER_SAMPLE
);
printf("static const float ResamplerFilter[RESAMPLER_FILTER_SIZE] = {");
for (i = 0; i < RESAMPLER_FILTER_SIZE; i++) {
j = (i % RESAMPLER_ZERO_CROSSINGS) * RESAMPLER_SAMPLES_PER_ZERO_CROSSING + (i / RESAMPLER_ZERO_CROSSINGS);
printf("%s%12.9ff,", (i % RESAMPLER_ZERO_CROSSINGS) ? "" : "\n ", ResamplerFilter[j]);
}
printf("\n};\n\n");
return 0;
}
| 2.40625 | 2 |
2024-11-18T20:56:01.347340+00:00 | 2021-10-10T18:36:25 | 0f7f5a72a6d2e74c4e3d3da68275c14b3bab1c5d | {
"blob_id": "0f7f5a72a6d2e74c4e3d3da68275c14b3bab1c5d",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-10T18:36:25",
"content_id": "650122e6ed7cae08eac3f10237d586490cd3f230",
"detected_licenses": [
"MIT"
],
"directory_id": "4ef81c26110bc475ab08ac34843b486fa4c305fb",
"extension": "c",
"filename": "test_3.c",
"fork_events_count": 0,
"gha_created_at": "2019-02-01T14:29:17",
"gha_event_created_at": "2019-07-10T18:20:35",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 168709565,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 494,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test_3.c",
"provenance": "stackv2-0092.json.gz:60054",
"repo_name": "Vicken-Ghoubiguian/heure_monde",
"revision_date": "2021-10-10T18:36:25",
"revision_id": "ee305bd281545d75b03bd5c83413f324db4db0e1",
"snapshot_id": "95f32dd2de42fb62162518ef18f388c8137f824d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Vicken-Ghoubiguian/heure_monde/ee305bd281545d75b03bd5c83413f324db4db0e1/test/test_3.c",
"visit_date": "2021-10-20T23:29:10.693982"
} | stackv2 | /* Inclusion des bibliothéques internes à l'API */
#include "../src/fonction_pour_l_affichage_des_changements_d_heures/fonction_pour_l_affichage_des_changements_d_heures.h"
//Fonction de test des passages heure d'été <=> heure d'hiver, pour les zones géographques qui les comportes
int main(int argc, char* argv[])
{
//
fonction_pour_l_affichage_des_changements_d_heures(argc, argv);
//La fonction main retourne 0, signe que ce programme s'est exécuté sans probléme
return 0;
}
| 2.390625 | 2 |
2024-11-18T20:56:02.393332+00:00 | 2020-12-13T02:49:34 | 82bc37040353e86e0880198cfaf2ab73a6d2b3ca | {
"blob_id": "82bc37040353e86e0880198cfaf2ab73a6d2b3ca",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-13T02:49:34",
"content_id": "07229a1bd08e27957f17318162523811fac66207",
"detected_licenses": [
"MIT"
],
"directory_id": "ba83243c7aa60622baf104501df6e2de234899d1",
"extension": "h",
"filename": "simon.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 319627407,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5613,
"license": "MIT",
"license_type": "permissive",
"path": "/arduino/TheSheetzNanoModded/simon.h",
"provenance": "stackv2-0092.json.gz:60441",
"repo_name": "zvikapika/HanukiyaIOT",
"revision_date": "2020-12-13T02:49:34",
"revision_id": "6f54e3d2d945962e9c1ff65d282269ae60898246",
"snapshot_id": "2a1b3887aabe43c91effb2583c5f0018bc0a2256",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zvikapika/HanukiyaIOT/6f54e3d2d945962e9c1ff65d282269ae60898246/arduino/TheSheetzNanoModded/simon.h",
"visit_date": "2023-01-30T15:38:00.662126"
} | stackv2 | #define MAX_SIMON_TURNS 100
#define SIMON_PLAY_DURATION 400
#define SIMON_MIN_PLAY_DURATION 50
#define SIMON_STATE_ADD_NOTE 10
#define SIMON_STATE_PLAYBACK 20
#define SIMON_STATE_RECORD 30
#define SIMON_STATE_FAILED 40
#define SIMON_RECORD_TIMEOUT 1500
void turnCandle(int candle, int intensity);
void turnCandle(int candle, int intensity, long col);
int getLitCandle(int candles);
long simonRecordStartedTstamp = 0;
int simonNotes[CANDLE_COUNT] = { // major pentatonic scale
NOTE_C4,
NOTE_D4,
NOTE_E4,
NOTE_G4,
NOTE_A4,
NOTE_C5,
NOTE_D5,
NOTE_E5
};
byte simonSequence[MAX_SIMON_TURNS] = {0};
int simonState = SIMON_STATE_ADD_NOTE;
int simonIndex = 0;
int simonLevel = 0;
int simonRecordIndex = 0;
boolean simonCandleStates[CANDLE_COUNT] = {false};
long getSimonCandleColor(int candle) {
return strip.gamma32(strip.ColorHSV(65536L / CANDLE_COUNT * candle));
}
float majScale[] = {
14080, 15804, 17739, 18794, 21096, 23679, 26579, 28160, 31608, 35479, 37589, 42192, 47359, 53159, 56320
};
void simonCheesyEffect() {
int ptime;
int k, x, dur, freq, t;
int i, j;
float ps; // variable for pow pitchShift routine
float noteval;
//note values
for (i = 0; i <= 4; i++) {
ps = (float)i / 12; // choose new transpose interval every loop
turnCandle(i, MAX_INTENSITY, getSimonCandleColor(i));
turnCandle(i + 4, MAX_INTENSITY, getSimonCandleColor(i));
for (x = 0; x <= 15; x++) {
noteval = (majScale[x] / 64) * pow(2, ps); // transpose scale up 12 tones - pow function generates transpostion
dur = 50 - i * 8 - x;
tone(SPEAKER_PIN, (int)noteval, dur);
delay(dur * 1.1);
}
turnCandle(i, MIN_INTENSITY);
turnCandle(i + 4, MIN_INTENSITY);
}
for (i = 0; i <= 6; i++) {
ps = (float)i / 12; // choose new transpose interval every loop
turnCandle(i % 4, MAX_INTENSITY, getSimonCandleColor(i));
turnCandle(i % 4 + 4, MAX_INTENSITY, getSimonCandleColor(i));
for (x = 0; x <= 15; x++) {
noteval = (majScale[x] / 64) * pow(2, ps); // transpose scale up 12 tones - pow function generates transpostion
dur = 5;
tone(SPEAKER_PIN, (int)noteval, dur);
delay(dur * 1.1);
}
turnCandle(i % 4, MIN_INTENSITY);
turnCandle(i % 4 + 4, MIN_INTENSITY);
}
for (i = 0; i <= CANDLE_COUNT; i++) {
turnCandle(i, MIN_INTENSITY);
}
}
void simonFailureSound() {
int i = 0;
// for(int t = 0; t < 3; ++t) {
for (int i = 0; i < 4; ++i) {
int j;
for (j = 50; j > 0; j--) {
if (j % 5 == 0) {
int fsoundCandleIndex = j % CANDLE_COUNT;
simonCandleStates[fsoundCandleIndex] = !simonCandleStates[fsoundCandleIndex];
turnCandle(
fsoundCandleIndex,
simonCandleStates[fsoundCandleIndex] ? MIN_INTENSITY : MAX_INTENSITY,
getSimonCandleColor(fsoundCandleIndex));
}
tone(SPEAKER_PIN, (5 - i) * 200 + j * 20);
// delayMicroseconds(500*(4-t));
delay(7);
}
}
for (int candle = 0; candle < CANDLE_COUNT; ++candle) {
turnCandle(candle, MIN_INTENSITY);
}
noTone(SPEAKER_PIN);
}
void simonPlayNote(int index, boolean withDelay) {
int candle = index;
int delayDuration = constrain(SIMON_PLAY_DURATION - simonLevel * (SIMON_PLAY_DURATION / 10), SIMON_MIN_PLAY_DURATION, SIMON_PLAY_DURATION);
turnCandle(candle, MAX_INTENSITY, getSimonCandleColor(candle));
tone(SPEAKER_PIN, simonNotes[candle]);
delay(delayDuration);
turnCandle(candle, MIN_INTENSITY);
noTone(SPEAKER_PIN);
if (withDelay) {
delay(delayDuration / 5);
}
}
void simonPlayNote(int index) {
simonPlayNote(index, true);
}
void signalSimonMode() {
simonLevel = 5;
for (int candle = 0; candle < CANDLE_COUNT; ++candle) {
simonPlayNote(candle, false);
}
simonLevel = 0;
delay(1000);
}
void resetSimon() {
for (int i = 0; i < MAX_SIMON_TURNS; ++i) {
simonSequence[i] = 0;
}
simonIndex = 0;
simonLevel = 0;
simonRecordStartedTstamp = 0;
simonRecordIndex = 0;
}
void handleSimon() {
switch (simonState) {
case SIMON_STATE_ADD_NOTE:
simonSequence[simonIndex++] = random(0, CANDLE_COUNT);
if ((simonIndex % 5) == 0) {
simonCheesyEffect();
simonLevel++;
delay(500);
}
simonState = SIMON_STATE_PLAYBACK;
break;
case SIMON_STATE_PLAYBACK:
for (int i = 0; i < simonIndex; ++i) {
simonPlayNote(simonSequence[i]);
}
simonState = SIMON_STATE_RECORD;
simonRecordStartedTstamp = millis();
simonRecordIndex = 0;
break;
case SIMON_STATE_RECORD:
if ((millis() - simonRecordStartedTstamp) < SIMON_RECORD_TIMEOUT) {
int lit = getLitCandle(CANDLE_COUNT);
if (lit > -1) {
if (lit == simonSequence[simonRecordIndex++]) {
simonPlayNote(lit);
if (simonRecordIndex == simonIndex) {
simonState = SIMON_STATE_ADD_NOTE;
delay(500);
}
else {
simonRecordStartedTstamp = millis();
}
}
else {
simonState = SIMON_STATE_FAILED;
}
}
}
else {
simonState = SIMON_STATE_FAILED;
}
break;
case SIMON_STATE_FAILED:
simonFailureSound();
delay(500);
// show correct sequence
for (int i = 0; i < simonIndex; ++i) {
simonPlayNote(simonSequence[i]);
}
// allow player remorse time
delay(1000);
// start again
resetSimon();
simonState = SIMON_STATE_ADD_NOTE;
break;
}
}
| 2.046875 | 2 |
2024-11-18T20:56:02.454447+00:00 | 2014-01-15T19:37:03 | bfd6c39529dd0a7eb8071ab35bce4c2cbf3ad587 | {
"blob_id": "bfd6c39529dd0a7eb8071ab35bce4c2cbf3ad587",
"branch_name": "refs/heads/master",
"committer_date": "2014-01-19T15:45:38",
"content_id": "5a3124e29fb9b37b667b670ab16311c37e051e84",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ab8ef0cf7c895dc510bb9ed9540fe830563a7ed7",
"extension": "c",
"filename": "debug.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": 3734,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/zcl/core/debug/debug.c",
"provenance": "stackv2-0092.json.gz:60570",
"repo_name": "clach04/RaleighSL",
"revision_date": "2014-01-15T19:37:03",
"revision_id": "c0479296201a34ea647534ed8cbc523494776da2",
"snapshot_id": "d9539971fbc29ad5cde51027b5033b024b01be14",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/clach04/RaleighSL/c0479296201a34ea647534ed8cbc523494776da2/src/zcl/core/debug/debug.c",
"visit_date": "2023-03-15T20:53:50.410681"
} | stackv2 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <execinfo.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <zcl/locking.h>
#include <zcl/debug.h>
struct debug_conf {
z_mutex_t lock;
int log_level;
};
#define __DEFAULT_LOG_LEVEL 5
static struct debug_conf __current_debug_conf;
static const char __weekday_name[7][3] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char __month_name[12][3] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static const char *__log_level[6] = {
"FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE",
};
static void __date_time (char buffer[25]) {
struct tm datetime;
time_t t;
t = time(NULL);
localtime_r(&t, &datetime);
snprintf(buffer, 25, "%.3s %.3s %.2d %d %.2d:%.2d:%.2d ",
__weekday_name[datetime.tm_wday],
__month_name[datetime.tm_mon],
datetime.tm_mday, 1900 + datetime.tm_year,
datetime.tm_hour, datetime.tm_min, datetime.tm_sec);
}
void __z_log (FILE *fp, int level,
const char *file, int line, const char *func,
const char *format, ...)
{
char datetime[25];
va_list ap;
if (level > __current_debug_conf.log_level)
return;
z_mutex_lock(&(__current_debug_conf.lock));
__date_time(datetime);
fprintf(stderr, "[%s] %-5s %s:%d %s() - ",
datetime, __log_level[level], file, line, func);
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
fprintf(stderr, "\n");
z_mutex_unlock(&(__current_debug_conf.lock));
}
void __z_assert (const char *file, int line, const char *func,
int vcond, const char *condition,
const char *format, ...)
{
char datetime[25];
va_list ap;
z_mutex_lock(&(__current_debug_conf.lock));
__date_time(datetime);
fprintf(stderr, "[%s] ASSERTION (%s) at %s:%d in function %s() failed. ",
datetime, condition, file, line, func);
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
fprintf(stderr, "\n");
z_mutex_unlock(&(__current_debug_conf.lock));
abort();
}
void z_dump_stack_trace (FILE *fp, unsigned int levels) {
void *trace[64];
char **symbols;
size_t i, size;
if (Z_UNLIKELY(levels == 0 || levels > 64))
levels = 64;
size = backtrace(trace, levels);
if ((symbols = backtrace_symbols(trace, size)) == NULL) {
perror("backtrace_symbols()");
return;
}
z_mutex_lock(&(__current_debug_conf.lock));
fprintf(fp, "Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++) {
fprintf(fp, "%s\n", symbols[i]);
}
z_mutex_unlock(&(__current_debug_conf.lock));
free(symbols);
}
void z_debug_open (void) {
z_mutex_alloc(&(__current_debug_conf.lock));
__current_debug_conf.log_level = __DEFAULT_LOG_LEVEL;
}
void z_debug_close (void) {
z_mutex_free(&(__current_debug_conf.lock));
}
int z_debug_get_log_level (void) {
return(__current_debug_conf.log_level);
}
void z_debug_set_log_level (int level) {
z_mutex_lock(&(__current_debug_conf.lock));
__current_debug_conf.log_level = level;
z_mutex_unlock(&(__current_debug_conf.lock));
}
| 2.1875 | 2 |
2024-11-18T20:56:02.778719+00:00 | 2009-02-20T04:14:19 | bec71f8939cfcf17e1387b4d07249052a874caf5 | {
"blob_id": "bec71f8939cfcf17e1387b4d07249052a874caf5",
"branch_name": "refs/heads/master",
"committer_date": "2009-02-20T04:14:19",
"content_id": "c7002eb0ecaadcccd23f935ff72e9ff8af9fad9a",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "058d0fca23239f363ebf042608297654ad75a082",
"extension": "c",
"filename": "run.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127958,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4286,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/vm/run.c",
"provenance": "stackv2-0092.json.gz:60955",
"repo_name": "jwmerrill/factor",
"revision_date": "2009-02-20T04:14:19",
"revision_id": "a146fc7485a342628b87814e47f3e9c43c03c0ba",
"snapshot_id": "6cc3f1940dfd279d5db9f7b196c098668b471117",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/jwmerrill/factor/a146fc7485a342628b87814e47f3e9c43c03c0ba/vm/run.c",
"visit_date": "2021-01-10T20:35:49.633789"
} | stackv2 | #include "master.h"
void reset_datastack(void)
{
ds = ds_bot - CELLS;
}
void reset_retainstack(void)
{
rs = rs_bot - CELLS;
}
#define RESERVED (64 * CELLS)
void fix_stacks(void)
{
if(ds + CELLS < ds_bot || ds + RESERVED >= ds_top) reset_datastack();
if(rs + CELLS < rs_bot || rs + RESERVED >= rs_top) reset_retainstack();
}
/* called before entry into foreign C code. Note that ds and rs might
be stored in registers, so callbacks must save and restore the correct values */
void save_stacks(void)
{
if(stack_chain)
{
stack_chain->datastack = ds;
stack_chain->retainstack = rs;
}
}
F_CONTEXT *alloc_context(void)
{
F_CONTEXT *context;
if(unused_contexts)
{
context = unused_contexts;
unused_contexts = unused_contexts->next;
}
else
{
context = safe_malloc(sizeof(F_CONTEXT));
context->datastack_region = alloc_segment(ds_size);
context->retainstack_region = alloc_segment(rs_size);
}
return context;
}
void dealloc_context(F_CONTEXT *context)
{
context->next = unused_contexts;
unused_contexts = context;
}
/* called on entry into a compiled callback */
void nest_stacks(void)
{
F_CONTEXT *new_stacks = alloc_context();
new_stacks->callstack_bottom = (F_STACK_FRAME *)-1;
new_stacks->callstack_top = (F_STACK_FRAME *)-1;
/* note that these register values are not necessarily valid stack
pointers. they are merely saved non-volatile registers, and are
restored in unnest_stacks(). consider this scenario:
- factor code calls C function
- C function saves ds/cs registers (since they're non-volatile)
- C function clobbers them
- C function calls Factor callback
- Factor callback returns
- C function restores registers
- C function returns to Factor code */
new_stacks->datastack_save = ds;
new_stacks->retainstack_save = rs;
/* save per-callback userenv */
new_stacks->current_callback_save = userenv[CURRENT_CALLBACK_ENV];
new_stacks->catchstack_save = userenv[CATCHSTACK_ENV];
new_stacks->next = stack_chain;
stack_chain = new_stacks;
reset_datastack();
reset_retainstack();
}
/* called when leaving a compiled callback */
void unnest_stacks(void)
{
ds = stack_chain->datastack_save;
rs = stack_chain->retainstack_save;
/* restore per-callback userenv */
userenv[CURRENT_CALLBACK_ENV] = stack_chain->current_callback_save;
userenv[CATCHSTACK_ENV] = stack_chain->catchstack_save;
F_CONTEXT *old_stacks = stack_chain;
stack_chain = old_stacks->next;
dealloc_context(old_stacks);
}
/* called on startup */
void init_stacks(CELL ds_size_, CELL rs_size_)
{
ds_size = ds_size_;
rs_size = rs_size_;
stack_chain = NULL;
unused_contexts = NULL;
}
bool stack_to_array(CELL bottom, CELL top)
{
F_FIXNUM depth = (F_FIXNUM)(top - bottom + CELLS);
if(depth < 0)
return false;
else
{
F_ARRAY *a = allot_array_internal(ARRAY_TYPE,depth / CELLS);
memcpy(a + 1,(void*)bottom,depth);
dpush(tag_object(a));
return true;
}
}
void primitive_datastack(void)
{
if(!stack_to_array(ds_bot,ds))
general_error(ERROR_DS_UNDERFLOW,F,F,NULL);
}
void primitive_retainstack(void)
{
if(!stack_to_array(rs_bot,rs))
general_error(ERROR_RS_UNDERFLOW,F,F,NULL);
}
/* returns pointer to top of stack */
CELL array_to_stack(F_ARRAY *array, CELL bottom)
{
CELL depth = array_capacity(array) * CELLS;
memcpy((void*)bottom,array + 1,depth);
return bottom + depth - CELLS;
}
void primitive_set_datastack(void)
{
ds = array_to_stack(untag_array(dpop()),ds_bot);
}
void primitive_set_retainstack(void)
{
rs = array_to_stack(untag_array(dpop()),rs_bot);
}
void primitive_getenv(void)
{
F_FIXNUM e = untag_fixnum_fast(dpeek());
drepl(userenv[e]);
}
void primitive_setenv(void)
{
F_FIXNUM e = untag_fixnum_fast(dpop());
CELL value = dpop();
userenv[e] = value;
}
void primitive_exit(void)
{
exit(to_fixnum(dpop()));
}
void primitive_micros(void)
{
box_unsigned_8(current_micros());
}
void primitive_sleep(void)
{
sleep_micros(to_cell(dpop()));
}
void primitive_set_slot(void)
{
F_FIXNUM slot = untag_fixnum_fast(dpop());
CELL obj = dpop();
CELL value = dpop();
set_slot(obj,slot,value);
}
void primitive_load_locals(void)
{
F_FIXNUM count = untag_fixnum_fast(dpop());
memcpy((CELL *)(rs + CELLS),(CELL *)(ds - CELLS * (count - 1)),CELLS * count);
ds -= CELLS * count;
rs += CELLS * count;
}
| 2.46875 | 2 |
2024-11-18T20:56:02.879090+00:00 | 2016-07-29T18:51:54 | a26cccb148e2477e642e289ea9b8fa38a53c8773 | {
"blob_id": "a26cccb148e2477e642e289ea9b8fa38a53c8773",
"branch_name": "refs/heads/master",
"committer_date": "2016-07-29T18:51:54",
"content_id": "c0f4a7e362152eae56ebf8077f91564341b985ac",
"detected_licenses": [
"MIT"
],
"directory_id": "132dbc84f18396d73227c0b5afda5d448eec50c7",
"extension": "c",
"filename": "hrm-activity-tutorial.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": 9696,
"license": "MIT",
"license_type": "permissive",
"path": "/src/hrm-activity-tutorial.c",
"provenance": "stackv2-0092.json.gz:61083",
"repo_name": "safety-mirror/hrm-activity-example",
"revision_date": "2016-07-29T18:51:54",
"revision_id": "e98303b54e743a0fb9c04b63c66f1a5af142efcc",
"snapshot_id": "c7c50f81222be8ce67292771d34ff3336ce37128",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/safety-mirror/hrm-activity-example/e98303b54e743a0fb9c04b63c66f1a5af142efcc/src/hrm-activity-tutorial.c",
"visit_date": "2020-06-10T21:27:46.028425"
} | stackv2 | #include <pebble.h>
const char START_ACTIVITY_STRING[] = "Press SELECT\n to START activity";
const char END_ACTIVITY_STRING[] = "Press SELECT\n to END activity";
typedef enum ActivityState {
STATE_NOT_STARTED,
STATE_IN_PROGRESS,
STATE_FINISHED
} ActivityState;
static Window *s_window;
static TextLayer *s_status_text_layer;
static TextLayer *s_time_text_layer;
static TextLayer *s_bpm_text_layer;
static TextLayer *s_title_text_layer;
static TextLayer *s_total_time_text_layer;
static TextLayer *s_min_bpm_text_layer;
static TextLayer *s_max_bpm_text_layer;
static TextLayer *s_avg_bpm_text_layer;
static ActivityState s_app_state = STATE_NOT_STARTED;
static time_t s_start_time, s_end_time;
static uint16_t s_curr_hr = 0;
static uint16_t s_min_hr = 65535; // max uint16_t
static uint16_t s_max_hr = 0;
static uint32_t s_hr_samples = 0;
static uint32_t s_hr_total = 0;
int16_t get_min_hr() {
return s_min_hr;
}
int16_t get_max_hr() {
return s_max_hr;
}
int16_t get_avg_hr() {
if (s_hr_samples == 0) return 0;
return s_hr_total / s_hr_samples;
}
static void prv_on_health_data(HealthEventType type, void *context) {
// If the update was from the Heart Rate Monitor, update it
if (type == HealthEventHeartRateUpdate) {
s_curr_hr = (int16_t) health_service_peek_current_value(HealthMetricHeartRateBPM);
// Update our metrics
if (s_curr_hr < s_min_hr) s_min_hr = s_curr_hr;
if (s_curr_hr > s_max_hr) s_max_hr = s_curr_hr;
s_hr_samples++;
s_hr_total += s_curr_hr;
}
}
static void prv_on_activity_tick(struct tm *tick_time, TimeUnits units_changed) {
// Update Time
time_t diff = time(NULL) - s_start_time;
struct tm *diff_time = gmtime(&diff);
static char s_time_buffer[9];
if (diff > SECONDS_PER_HOUR) {
strftime(s_time_buffer, sizeof(s_time_buffer), "%H:%M:%S", diff_time);
} else {
strftime(s_time_buffer, sizeof(s_time_buffer), "%M:%S", diff_time);
}
text_layer_set_text(s_time_text_layer, s_time_buffer);
// Update BPM
static char s_hrm_buffer[8];
snprintf(s_hrm_buffer, sizeof(s_hrm_buffer), "%lu BPM", (uint32_t) s_curr_hr);
text_layer_set_text(s_bpm_text_layer, s_hrm_buffer);
}
static void prv_start_activity(void) {
// Update application state
s_app_state = STATE_IN_PROGRESS;
s_start_time = time(NULL);
// Set min heart rate sampling period (i.e. fastest sampling rate)
#if PBL_API_EXISTS(health_service_set_heart_rate_sample_period)
health_service_set_heart_rate_sample_period(1);
#endif
// Subscribe to tick handler to update display
tick_timer_service_subscribe(SECOND_UNIT, prv_on_activity_tick);
// Subscribe to health handler
health_service_events_subscribe(prv_on_health_data, NULL);
// Update UI
text_layer_set_text(s_status_text_layer, END_ACTIVITY_STRING);
layer_set_hidden(text_layer_get_layer(s_time_text_layer), false);
layer_set_hidden(text_layer_get_layer(s_bpm_text_layer), false);
}
static void prv_end_activity(void) {
// Update application state
s_app_state = STATE_FINISHED;
s_end_time = time(NULL);
// Set default heart rate sampling period
#if PBL_API_EXISTS(health_service_set_heart_rate_sample_period)
health_service_set_heart_rate_sample_period(0);
#endif
// Unsubscribe from tick handler
tick_timer_service_unsubscribe();
// Unsubscribe from health handler
health_service_events_unsubscribe();
// Update UI
layer_set_hidden(text_layer_get_layer(s_status_text_layer), true);
layer_set_hidden(text_layer_get_layer(s_time_text_layer), true);
layer_set_hidden(text_layer_get_layer(s_bpm_text_layer), true);
static char s_time_buffer[16];
time_t diff = s_end_time - s_start_time;
struct tm *diff_time = gmtime(&diff);
if (diff > SECONDS_PER_HOUR) {
strftime(s_time_buffer, sizeof(s_time_buffer), "Time: %H:%M:%S", diff_time);
} else {
strftime(s_time_buffer, sizeof(s_time_buffer), "Time: %M:%S", diff_time);
}
text_layer_set_text(s_total_time_text_layer, s_time_buffer);
static char s_avg_bpm_buffer[16];
snprintf(s_avg_bpm_buffer, sizeof(s_avg_bpm_buffer), "Avg: %u BPM", get_avg_hr());
text_layer_set_text(s_avg_bpm_text_layer, s_avg_bpm_buffer);
static char s_max_bpm_buffer[16];
snprintf(s_max_bpm_buffer, sizeof(s_max_bpm_buffer), "Max: %u BPM", get_max_hr());
text_layer_set_text(s_max_bpm_text_layer, s_max_bpm_buffer);
static char s_min_bpm_buffer[16];
snprintf(s_min_bpm_buffer, sizeof(s_min_bpm_buffer), "Min: %u BPM", get_min_hr());
text_layer_set_text(s_min_bpm_text_layer, s_min_bpm_buffer);
layer_set_hidden(text_layer_get_layer(s_title_text_layer), false);
layer_set_hidden(text_layer_get_layer(s_total_time_text_layer), false);
layer_set_hidden(text_layer_get_layer(s_avg_bpm_text_layer), false);
layer_set_hidden(text_layer_get_layer(s_min_bpm_text_layer), false);
layer_set_hidden(text_layer_get_layer(s_max_bpm_text_layer), false);
}
static void prv_select_click_handler(ClickRecognizerRef recognizer, void *context) {
switch (s_app_state) {
case STATE_NOT_STARTED:
// Display activity
prv_start_activity();
break;
case STATE_IN_PROGRESS:
// Display Metrics
prv_end_activity();
break;
default:
// Quit
window_stack_pop(true);
break;
}
}
static void prv_click_config_provider(void *context) {
window_single_click_subscribe(BUTTON_ID_SELECT, prv_select_click_handler);
}
static void prv_window_load(Window *window) {
Layer *window_layer = window_get_root_layer(window);
GRect bounds = layer_get_bounds(window_layer);
// Determin how we launched (automaticaly start activity on quick launch)
bool quick_launch = launch_reason() == APP_LAUNCH_QUICK_LAUNCH;
// Status
s_status_text_layer = text_layer_create(GRect(0, 67, bounds.size.w, 40));
text_layer_set_text(s_status_text_layer, quick_launch ? END_ACTIVITY_STRING
: START_ACTIVITY_STRING);
text_layer_set_text_alignment(s_status_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_status_text_layer), false);
layer_add_child(window_layer, text_layer_get_layer(s_status_text_layer));
// Time in activity (Hidden)
s_time_text_layer = text_layer_create(GRect(0, 27, bounds.size.w, 20));
text_layer_set_text(s_time_text_layer, "00:00");
text_layer_set_text_alignment(s_time_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_time_text_layer), !quick_launch);
layer_add_child(window_layer, text_layer_get_layer(s_time_text_layer));
// Curr BPM (hidden)
s_bpm_text_layer = text_layer_create(GRect(0, 117, bounds.size.w, 20));
text_layer_set_text(s_bpm_text_layer, "??? BPM");
text_layer_set_text_alignment(s_bpm_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_bpm_text_layer), !quick_launch);
layer_add_child(window_layer, text_layer_get_layer(s_bpm_text_layer));
// "Workout Summay" (Hidden)
s_title_text_layer = text_layer_create(GRect(0, 10, bounds.size.w, 20));
text_layer_set_text(s_title_text_layer, "Workout Summary");
text_layer_set_text_alignment(s_title_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_title_text_layer), true);
layer_add_child(window_layer, text_layer_get_layer(s_title_text_layer));
// Total Time (Hidden)
s_total_time_text_layer = text_layer_create(GRect(0, 35, bounds.size.w, 20));
text_layer_set_text_alignment(s_total_time_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_total_time_text_layer), true);
layer_add_child(window_layer, text_layer_get_layer(s_total_time_text_layer));
// Avg BPM (Hidden)
s_avg_bpm_text_layer = text_layer_create(GRect(0, 85, bounds.size.w, 20));
text_layer_set_text_alignment(s_avg_bpm_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_avg_bpm_text_layer), true);
layer_add_child(window_layer, text_layer_get_layer(s_avg_bpm_text_layer));
// Max BPM (Hidden)
s_max_bpm_text_layer = text_layer_create(GRect(0, 110, bounds.size.w, 20));
text_layer_set_text_alignment(s_max_bpm_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_max_bpm_text_layer), true);
layer_add_child(window_layer, text_layer_get_layer(s_max_bpm_text_layer));
// Min BPM (Hidden)
s_min_bpm_text_layer = text_layer_create(GRect(0, 135, bounds.size.w, 20));
text_layer_set_text_alignment(s_min_bpm_text_layer, GTextAlignmentCenter);
layer_set_hidden(text_layer_get_layer(s_min_bpm_text_layer), true);
layer_add_child(window_layer, text_layer_get_layer(s_min_bpm_text_layer));
if(quick_launch) prv_start_activity();
}
static void prv_window_unload(Window *window) {
text_layer_destroy(s_status_text_layer);
text_layer_destroy(s_time_text_layer);
text_layer_destroy(s_bpm_text_layer);
text_layer_destroy(s_title_text_layer);
text_layer_destroy(s_avg_bpm_text_layer);
text_layer_destroy(s_max_bpm_text_layer);
text_layer_destroy(s_min_bpm_text_layer);
}
static void prv_init(void) {
s_window = window_create();
window_set_click_config_provider(s_window, prv_click_config_provider);
window_set_window_handlers(s_window, (WindowHandlers) {
.load = prv_window_load,
.unload = prv_window_unload,
});
window_stack_push(s_window, true);
}
static void prv_deinit(void) {
window_destroy(s_window);
// Reset Heart Rate Sampling
#if PBL_API_EXISTS(health_service_set_heart_rate_sample_period)
health_service_set_heart_rate_sample_period(0);
#endif
}
int main(void) {
prv_init();
APP_LOG(APP_LOG_LEVEL_DEBUG, "Done initializing, pushed window: %p", s_window);
app_event_loop();
prv_deinit();
}
| 2.25 | 2 |
2024-11-18T20:56:03.894841+00:00 | 2021-05-18T09:59:48 | 10c65f639a13276d87c5cfeee3912f9f2d26cba9 | {
"blob_id": "10c65f639a13276d87c5cfeee3912f9f2d26cba9",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-18T09:59:48",
"content_id": "5896f3fa88d3c5262452136e0622066520dba67f",
"detected_licenses": [
"MIT"
],
"directory_id": "d392b9f74799ea40bc1cb5a358fcaff2f33ecd3c",
"extension": "c",
"filename": "courseWork1Bzahov.c",
"fork_events_count": 3,
"gha_created_at": "2017-12-19T20:38:27",
"gha_event_created_at": "2021-01-20T20:29:43",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 114808920,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18925,
"license": "MIT",
"license_type": "permissive",
"path": "/C- PIK I/CourseWork 1/courseWork1Bzahov.c",
"provenance": "stackv2-0092.json.gz:61211",
"repo_name": "Bzahov98/TU-University-Tasks",
"revision_date": "2021-05-18T09:59:48",
"revision_id": "9d8e86e059e36356276b8e69579735b188b72634",
"snapshot_id": "ea319aa935e9b878a6a0806118bedf567738dab1",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Bzahov98/TU-University-Tasks/9d8e86e059e36356276b8e69579735b188b72634/C- PIK I/CourseWork 1/courseWork1Bzahov.c",
"visit_date": "2021-07-23T22:45:38.693828"
} | stackv2 | #include<stdio.h>
#include<string.h>
const int ARRAY_SIZE = 1024 ; // don't work with more than that amount of lines {Malloc use restriction}
const int ARRAY_LINE_SIZE = 1256; // don't work with more than that amount of symbols per line {Malloc use restriction}
const int FILENAME_SIZE = 100;
#define STR_QUIT_Q "Q"
#define STR_QUIT_q "q"
#define C_FILE_EXTENTION "c"
int DEBUG = 0; // 1 for showing debug information on screen, 6 for full info
#define ALL_OPERATORS 7 // number operators for which program will check
//operators for which program will check, add more operators and increase ALL_OPERATORS
const char* operatorsStr[ALL_OPERATORS] = {"if", "else", "switch", "goto", "while", "do", "for"};
enum states { TEXT, //For Text
SAW_SLASH, // For
SAW_STAR,
SAW_APOSTROPHE,
SAW_QUOTE,
SINGLE_COMMENT,
MULTI_COMMENT,
NEXT_LINE
} state = TEXT;
// read functions
int readFromFile (char allLines[][ARRAY_LINE_SIZE]); // DONE
int readFromKeyboard(char allLines[][ARRAY_LINE_SIZE]); // DONE
// task functions
int lineWithLessSymbols(char allLines[][ARRAY_LINE_SIZE],char allLinesMeaningSymbols[][ARRAY_LINE_SIZE]); // DONE
int operatorsInProgram (char allLines[][ARRAY_LINE_SIZE], int* operationsResult); // DONE
// write functions
int writeToFile (char allLines[][ARRAY_LINE_SIZE], int minSymbolsLineNumber, int* operatorsNumberArr); // DONE
void writeToScreen(char allLines[][ARRAY_LINE_SIZE], int minSymbolsLineNumber, int* operatorsNumberArr); // DONE
// support functions
void loadMenu(char allLines[][ARRAY_LINE_SIZE]); //DONE
int scanForSubStr(char* currentLine, const char* sub); //DONE
int checkFileExtention(char FileName[], const char extention[]); // DONE
int checkCharForLetter(char ch); // DONE
void zeroDoubleArray(char allLines[][ARRAY_LINE_SIZE]); // DONE
//debug functions
void printDoubleArray (char allLines[][ARRAY_LINE_SIZE]); // DONE
char* cleanExtraWhiteSpaces(char line[]); // DONE
//*****************************************************************************************
int main(){
char allLines[ARRAY_SIZE][ARRAY_LINE_SIZE];
zeroDoubleArray(allLines);
loadMenu(allLines);
return 0;
}
//*****************************************************************************************
void loadMenu(char allLines[][ARRAY_LINE_SIZE]){
char choice;
int minSymbolsLineNumber = 0;
do{
printf("\n>------------------------------------------------------------<\n");
printf(">Моля изберете номер на опция: <\n");
printf(">1. Четене от Файл и запис във файл <\n");
printf(">2. Четене от Файл и извеждане на резултата на екрана <\n");
printf(">3. Четене от клавиатурата и извеждане във Файл <\n");
printf(">4. Четене от клавиатурата и извеждане на резултата на екрана<\n");
printf(">5. Изход от програмата ( 'Q' or 'q' ) <\n");
printf(">------------------------------------------------------------<\n");
int operationResult[ALL_OPERATORS] = {0}; //reset each cicle, data result
char allLinesMeaningSymbols[ARRAY_SIZE][ARRAY_LINE_SIZE];
zeroDoubleArray(allLinesMeaningSymbols);
scanf(" %c",&choice); // space before the %; this consumes the whitespace, so that the next scanf call should work
switch(choice){
//Menu options;
case '1':
printf(">>Избрахте: 1. Четене от Файл и запис във файл<\n");
if (readFromFile(allLines)) break;
minSymbolsLineNumber = lineWithLessSymbols(allLines,allLinesMeaningSymbols);
if (minSymbolsLineNumber==-1) break;
if (operatorsInProgram(allLinesMeaningSymbols, operationResult)) break;
writeToFile(allLines, minSymbolsLineNumber, operationResult);
break;
case '2':
printf(">>Избрахте: 2. Четене от Файл и извеждане на резултата на екрана<\n");
if (readFromFile(allLines)) break;
minSymbolsLineNumber = lineWithLessSymbols(allLines,allLinesMeaningSymbols);
if (minSymbolsLineNumber==-1) break;
if (operatorsInProgram(allLinesMeaningSymbols, operationResult)) break;
writeToScreen(allLines, minSymbolsLineNumber,operationResult);
break;
case '3':
printf(">>Избрахте: 3. Четене от клавиатурата и извеждане във Файл<\n");
if (readFromKeyboard(allLines)) break;
minSymbolsLineNumber = lineWithLessSymbols(allLines, allLinesMeaningSymbols);
if (minSymbolsLineNumber==-1) break;
if (operatorsInProgram( allLinesMeaningSymbols, operationResult)) break;
writeToFile(allLines, minSymbolsLineNumber,operationResult);
break;
case '4':
printf(">>Избрахте: 4. Четене от клавиатурата и извеждане на резултата на екрана\n");
readFromKeyboard(allLines);
minSymbolsLineNumber = lineWithLessSymbols(allLines,allLinesMeaningSymbols);
if (minSymbolsLineNumber==-1) break;
if (operatorsInProgram(allLinesMeaningSymbols, operationResult)) break;
printDoubleArray(allLinesMeaningSymbols); //TEMP
writeToScreen(allLines, minSymbolsLineNumber,operationResult);
break;
//Quit program options;
case 'Q':
case 'q':
case '5':
printf(">>Изход\n");
return;
default:
zeroDoubleArray(allLines);
printf(">>Невалиден избор, моля въведете пак!\n");
break;
}
} while (1);
}
//Read functions ******************************************************************************
int readFromFile(char allLines[][ARRAY_LINE_SIZE]){
char inputFileName[FILENAME_SIZE];char line[ARRAY_LINE_SIZE];
int i = 0;
FILE *inputFile;
do { /* open inputFile and check it until get right extention*/
printf("Моля въведете името на файла, от който искате да четете!, 'Q' за връщане към менюто\n");
scanf("%s", &inputFileName[0]);
if (!(strcmp(inputFileName, STR_QUIT_Q) == 0 || strcmp(inputFileName, STR_QUIT_q))) {
return 1; // return to Menu
}else if (!checkFileExtention(inputFileName, C_FILE_EXTENTION)) {
continue; // ask for new path
} inputFile = fopen (inputFileName, "r");
if ( inputFile == NULL ){ // check file for wrong
printf("\n!!!Грешка с файла!!!\n");
perror (inputFileName);
}else break; // file is fine, continues to read it
}while(1);
while (fgets(line, ARRAY_LINE_SIZE, inputFile) != NULL){ // read data from array and write it to array
//printf(">Line number:%d-> %s ",i, line);
if (i < ARRAY_SIZE-1) {
strcpy(allLines[i++], line);
}else {
printf("Файлът е твърде дълъг!!! Ще се обработи до ред: %d\n", i);
break;
}
}
strcpy(allLines[i],"\0"); // add termination sign in end
fclose (inputFile);
return 0;
};
int readFromKeyboard(char allLines[][ARRAY_LINE_SIZE]){
char str[ARRAY_LINE_SIZE];
int i,x= -1,y = 0;
while (fgets(str,ARRAY_LINE_SIZE,stdin) != NULL) {
for (i = 0; str[i] != '\0'; i ++) {
char currentChar = str[i];
if (currentChar == '\n'){//} || ((y-1) <= ARRAY_LINE_SIZE)) {
y = 0;
x++;
if (!(x < ARRAY_SIZE-1)) {
printf("Файлът е твърде дълъг!!! Ще се обработи до ред: %d\n", i);
break;
}
}else{
if (y < ARRAY_LINE_SIZE-1){
allLines[x][y] = currentChar;
y++;
}else {
allLines[x][y] = '\0';
x++; y = 0;
}
}
}
} y = 0;
return 0;
};
// Task functions ******************************************************************************
int lineWithLessSymbols(char allLines[][ARRAY_LINE_SIZE],char allLinesMeaningSymbols[][ARRAY_LINE_SIZE]){
int i,j,jNew=0,minSymbolsLineNumber,minMeanfulSymbols;
if (!strlen(allLines[0]) && !strlen(allLines[1])) {
printf("Грешка - Липса на данни! \n");
return -1; // with error
}
for (i = 0; strlen(allLines[i]); i++) {
int lineMeanfulSymbols = 0,firstNote = 1;
char currentLine[ARRAY_LINE_SIZE];
strcpy(currentLine,allLines[i]);
char str[22];
DEBUG>5?printf("––line: <!>> %s <<!> number: %d ––\n",allLines[i], i+1):sprintf(str,"do Nothing");
for (j = 0;/*checked down*/; j++){
char currentChar = currentLine[j];
if (currentChar == '\0' || currentChar == '\n' || state == SINGLE_COMMENT) { // go to next line
if (state != MULTI_COMMENT ) {
state = TEXT;
}
if (firstNote && lineMeanfulSymbols !=0) { // first time is minimal meanful symbols
firstNote = 0;
minMeanfulSymbols = lineMeanfulSymbols;
minSymbolsLineNumber = i;
} else if (minMeanfulSymbols > lineMeanfulSymbols && lineMeanfulSymbols!=0) { //compare and update minimum meanful symbols
minMeanfulSymbols = lineMeanfulSymbols;
minSymbolsLineNumber = i;
}
if (!strcmp(allLinesMeaningSymbols[i],"") || !strcmp(allLinesMeaningSymbols[i],"\n")) { // check if haven't meanful symbols and add space to save line
allLinesMeaningSymbols[i][0]= ' ';
allLinesMeaningSymbols[i][1]= '\0';
}
jNew = 0; // reset output array's line position to begginig
break; // go to next line
}
switch(state){
case TEXT : // normal text and whitespaces, count meanful symbols
DEBUG>5?printf("\n--TEXT-- %c at %s--\n",currentChar,currentLine):sprintf(str,"do Nothing");
switch(currentChar){
case '/' : state = SAW_SLASH; break;
case '\"' : state = SAW_QUOTE; break;
case '\'' : state = SAW_APOSTROPHE; break;
case ' ' : // Don't count white spaces
case '\t' : // but add them at array
if (allLinesMeaningSymbols[i][jNew-1] != ' ' || allLinesMeaningSymbols[i][jNew-1] != '\t') { // remove extra whitespaces
allLinesMeaningSymbols[i][jNew] = currentChar;
jNew++; // if it's text
}
break;
default : if (state == TEXT) {
allLinesMeaningSymbols[i][jNew] = currentChar; //save only meanful symbols
lineMeanfulSymbols++ ; // count meanful symbols
jNew++; // if it's text
}break;
} break;
case SAW_SLASH : // saw / , link to single or multi comment functionality
DEBUG>5?printf("\n--SAW SWASH-- %c--\n",currentChar):sprintf(str,"do Nothing");
switch(currentChar){
case '/' : state = SINGLE_COMMENT; break;
case '*' : state = MULTI_COMMENT; break;
default : state = TEXT; break;
} break;
case SAW_STAR : // saw *
DEBUG>5?printf("\n--SAW STAR-- %c--\n",currentChar):sprintf(str,"do Nothing");
switch(currentChar){
case '/' : state = TEXT; break;
case '*' : break; // Stay at SAW_STAR state
default : state = MULTI_COMMENT; break;
} break;
case SAW_QUOTE : // saw ""
DEBUG>5?printf("\n--SAW QUOTE-- %c--\n",currentChar):sprintf(str,"do Nothing");
switch (currentChar){
case '\"' : state = TEXT; break;
default : break; // under quote;
} break;
case SAW_APOSTROPHE :
DEBUG>5?(printf("\n--SAW APOSTROPHE-- %c--\n",currentChar)):sprintf(str,"do Nothing");
switch (currentChar){
case '\'' : state = TEXT; break;
default : break; // under apostrophe;
}break;
case SINGLE_COMMENT :
DEBUG>5?printf("\n--COMMENT-- %c--\n",currentChar):sprintf(str,"do Nothing");;
break; // skip to next line at if up
case MULTI_COMMENT :
DEBUG>5?(printf("\n--MULTI_COMMENT-- %c--\n",currentChar)):sprintf(str,"do Nothing");
switch(currentChar){
case '*' : state = SAW_STAR; break;
default : break;
}break;
default: break; // ERROR
} DEBUG>5?printf("\nline number: %d length: %d\n", i, lineMeanfulSymbols):sprintf(str,"do Nothing");
}
}
//DEBUG?printf("%d %s\n", minSymbolsLineNumber, allLines[minSymbolsLineNumber]):sprintf(str,"do Nothing");
return minSymbolsLineNumber;
}
int operatorsInProgram(char allLines[][ARRAY_LINE_SIZE],int operationsResult[ALL_OPERATORS-1]){
unsigned int i=0;
if (!strlen(allLines[0]) && !strlen(allLines[1])) {
printf("Грешка - Липса на данни или няма значещи символи! >%s< %zu\n",allLines[0],strlen(allLines[0]));
return 1; // with error
}
for (i = 0; strlen(allLines[i]); i++) {
char currentLine[ARRAY_LINE_SIZE];
strcpy(currentLine,allLines[i]);
//DEBUG >5?printf("––line: <!>> %s <<!> number: %d ––\n",allLines[i], i+1):sprintf(str,"do Nothing");
for (int operatorNumber = 0; operatorNumber < ALL_OPERATORS; operatorNumber++) {
operationsResult[operatorNumber] += scanForSubStr(currentLine,operatorsStr[operatorNumber]);
//printf("operator: '%s' was found %d times\n", operatorsStr[operatorNumber], result);
}
}
for (int operatorNumber = 0; operatorNumber < ALL_OPERATORS-1; operatorNumber++) { //DEBUG
char str[22];
DEBUG?printf("DEBUG-->operator: '%s' was found %d times\n", operatorsStr[operatorNumber], operationsResult[operatorNumber]):sprintf(str,"do Nothing");;
}
return 0;
}
// Write functions
void writeToScreen(char allLines[][ARRAY_LINE_SIZE], int minSymbolsLineNumber, int operatorsNumberArr[ALL_OPERATORS-1]){
int operatorNumber;
printf("Редът с най-малкък брой значещи символи е номер: %d \"%s\"\n", minSymbolsLineNumber+1, allLines[minSymbolsLineNumber]);
for (operatorNumber = 0; operatorNumber < ALL_OPERATORS; operatorNumber++) {
printf("operator: '%7s' was found %d times\n", operatorsStr[operatorNumber], operatorsNumberArr[operatorNumber]);
}
}
int writeToFile(char inputAllLines[][ARRAY_LINE_SIZE], int minSymbolsLineNumber, int operatorsNumberArr[ALL_OPERATORS-1]){
char outputFileName[FILENAME_SIZE];
FILE *outputFile;
do{ /* open output File and check it until get right extention*/
printf("Моля въведете името на файла, в който искате да запишете резултата!, 'Q' за връщане към менюто\n");
scanf("%s", &outputFileName[0]);
if (!(strcmp(outputFileName, STR_QUIT_Q) == 0 || strcmp(outputFileName, STR_QUIT_q))) {
return 1; // return to Menu
}
outputFile = fopen (outputFileName, "w");
if ( outputFile == NULL ){ // check file for wrong
printf("\n!!!Грешка с файла!!!\n");
perror (outputFileName);
}else break; // file is fine, continues to write in it
}while(1);
char stringForWrite[sizeof inputAllLines[minSymbolsLineNumber] + 100];
sprintf(stringForWrite, "Редът с най-малкък брой значещи символи е номер: %d \"%s\"\n", minSymbolsLineNumber+1, inputAllLines[minSymbolsLineNumber]);
fprintf(outputFile, "%s", stringForWrite);
int operatorNumber;
for (operatorNumber = 0; operatorNumber < ALL_OPERATORS; operatorNumber++) {
char stringForWrite2[sizeof operatorsStr[operatorNumber] + 100];
sprintf(stringForWrite2,"operator: '%7s' was found %d times\n", operatorsStr[operatorNumber], operatorsNumberArr[operatorNumber]);
fprintf(outputFile,"%s", stringForWrite2);
}
fclose (outputFile);
return 0;
}
// Support functions ***************************************************************************
int scanForSubStr(char* currentLine, const char* sub){
int foundMatches = 0;
char currentLine_cpy[ARRAY_LINE_SIZE];
strcpy(currentLine_cpy,currentLine);
for (char *p = currentLine_cpy; (p = strstr(p, sub)) != NULL; p++) {
char chBefore = *(p-1);
char chAfter = *(p+strlen(sub));
//printf("sub: '%s', line: %s,times:%d\n",sub, p, foundMatches);
// for 'do': XdoX, doX, Xdo are ignored!!
if ( checkCharForLetter(chBefore) || checkCharForLetter(chAfter)) {
continue; // it's part of a word, don't count it
//printf("IGNORED: sub: '%s', line: %s,chBefore: %c,chAfter: %c\n",sub, p, chBefore,chAfter);
} foundMatches++; // substring found at offset
//DEBUG==2?printf("DEBUG: Found at: %s pos: %tu count:%d\n", currentLine_cpy, p - currentLine_cpy, foundMatches):sprintf(str,"do Nothing");
if (*p == '\0') break;
}
//DEBUG==2?printf("DEBUG: %s = %d\n",sub, foundMatches):sprintf(str,"do Nothing");;
return foundMatches;
}
// return 1 for alfabet, 0 for other symbol
int checkCharForLetter(char ch){
return (ch > 'a' && ch < 'z') || (ch > 'A' && ch < 'Z');
}
int checkFileExtention(char FileName[], const char extention[]){
int i = 0;
char tempFileName[FILENAME_SIZE];
char *splitedArray[FILENAME_SIZE];
strcpy(tempFileName,FileName);
splitedArray[i] = strtok(tempFileName,".");
while(splitedArray[i]!=NULL){
splitedArray[++i] = strtok(NULL, ".");
}
if(!strcmp(extention, splitedArray[i-1]) == 0) { //get extention
printf("'%s' не е правилното окончание: '%s'\n", splitedArray[i-1], extention);
return 0; // false Not ending with .c (extention[])
}else return 1; // for true ending with .c (extention[])
}
void zeroDoubleArray(char allLines[][ARRAY_LINE_SIZE]){
int i,j;
for(i = 0; i < ARRAY_SIZE; i++){ //allLines[i+1] != 0
for(j = 0; j < ARRAY_LINE_SIZE; j++){
allLines[i][j] = '\0';
}
}
}
// Debug functions *****************************************************************************
void printDoubleArray(char allLines[][ARRAY_LINE_SIZE]){
int i,j;
printf("DEBUG:\n%s\n", "VVVVVVVV");
for (i = 0; ; i++){
if (!strlen(allLines[i]) && !strlen(allLines[i+1])) {
break;
}
for (j = 0; allLines[i][j] != '\0'; j++)
printf("DEBUG: [%d][%d]>> '%c' <<\n",i,j,allLines[i][j]);
}printf("DEBUG: %s\n","^^^^^^^^^^");
}
char* cleanExtraWhiteSpaces(char line[]){ //UNUSED FUNCTION
int i=0,length=0,k=0;
length=strlen(line);
for(i=0;i<length;){
if((line[i]==' ')&&(line[i+1]==' ')){
for(k=i+1;k<length;k++){
line[k]=line[k+1];
}
length= length - 1;
}else i++;
}
return line;
}
| 2.515625 | 3 |
2024-11-18T20:56:04.135964+00:00 | 2023-02-08T08:05:17 | 24941d4226ecd1e44083207d1261f33e5d3eb0d2 | {
"blob_id": "24941d4226ecd1e44083207d1261f33e5d3eb0d2",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-08T08:05:17",
"content_id": "7432273bf3c1db3e179672f06a78a1d8652ee1d0",
"detected_licenses": [
"MIT"
],
"directory_id": "0e311f3197baac2efea92039be9fce5d648a8969",
"extension": "c",
"filename": "stat11.c",
"fork_events_count": 1,
"gha_created_at": "2017-10-30T05:18:40",
"gha_event_created_at": "2023-02-08T08:05:20",
"gha_language": "Fortran",
"gha_license_id": null,
"github_id": 108805048,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 507,
"license": "MIT",
"license_type": "permissive",
"path": "/stat11.c",
"provenance": "stackv2-0092.json.gz:61468",
"repo_name": "iajzenszmi/CodeCode",
"revision_date": "2023-02-08T08:05:17",
"revision_id": "b3c58357f346c49025291f28b94fee2666523b55",
"snapshot_id": "dbd6e600e14886879836259fab7bed1fc63578f9",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/iajzenszmi/CodeCode/b3c58357f346c49025291f28b94fee2666523b55/stat11.c",
"visit_date": "2023-02-16T23:03:40.956645"
} | stackv2 | //
// is_on_physical_device - returns a positive
// integer if 'fd' resides on a physical device,
// 0 if the file resides on a nonphysical or
// virtual device (e.g., on an NFS mount), and
// -1 on error./
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
//int main(int fd)
int is_on_physical_device(int fd){
struct stat sb;
int ret;
ret = fstat(fd, &sb);
if (ret) {
perror ("fstat");
return -1;
}
printf("\n%d%d%ld", gnu_dev_major(sb.st_dev),ret,sb.st_dev);
return gnu_dev_major(sb.st_dev);
}
| 2.640625 | 3 |
2024-11-18T20:56:05.027125+00:00 | 2017-12-25T23:49:50 | 56cd65ab4a21c59791b6112dd825762ca113323c | {
"blob_id": "56cd65ab4a21c59791b6112dd825762ca113323c",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-25T23:49:50",
"content_id": "7ee569010f3985b3308fc60bee128634f7ef08c1",
"detected_licenses": [
"MIT"
],
"directory_id": "1220ce36d958949f19db6d8dc081b8871a3d711d",
"extension": "c",
"filename": "encoding.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115045718,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2211,
"license": "MIT",
"license_type": "permissive",
"path": "/src/encoding.c",
"provenance": "stackv2-0092.json.gz:61856",
"repo_name": "Yamakaja/ping-responder",
"revision_date": "2017-12-25T23:49:50",
"revision_id": "bbe40cd8c7001559ce22530ecbe1d2d3526b331b",
"snapshot_id": "a1f86ae7b84b173fc2da3f4c1067aef5aa76a3e8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Yamakaja/ping-responder/bbe40cd8c7001559ce22530ecbe1d2d3526b331b/src/encoding.c",
"visit_date": "2021-05-06T05:05:42.323777"
} | stackv2 | #include <string.h>
#include "encoding.h"
size_t required_var_int_bytes(int value) {
if (value < 0)
return 5;
if (value < 1 << 7)
return 1;
if (value < 1 << 14)
return 2;
if (value < 1 << 21)
return 3;
if (value < 1 << 28)
return 4;
return 5;
}
int read_var_int(uint8_t *buffer, size_t buffer_size, size_t *offset, int32_t *target) {
int result = 0;
int round = 0;
uint8_t cur;
do {
if (*offset >= buffer_size || round == 5)
return -1;
result |= ((cur = buffer[(*offset)++]) & 0x7F) << 7 * round;
} while (round++, cur & 0x80);
*target = result;
return 0;
}
void write_var_int(uint8_t *buffer, size_t buffer_size, size_t *offset, int32_t value) {
for (int i = 0; i < 5 && *offset < buffer_size && (i == 0 || (value >> i * 7)); i++)
buffer[(*offset)++] = (unsigned char) (((value >> i * 7) & 0x7F) | ((value >> (i + 1) * 7) ? 0x80 : 0x0));
}
void write_string(uint8_t *buffer, size_t buffer_size, size_t *offset, char *str, size_t len) {
if (buffer_size - *offset - len - 4 < 0)
return;
write_var_int(buffer, buffer_size, offset, len);
memcpy(buffer + *offset, str, len);
*offset += len;
}
int read_string(uint8_t *buffer, size_t buffer_size, size_t *offset, char *target_buffer, size_t target_buffer_size) {
int size;
if (read_var_int(buffer, buffer_size, offset, &size))
return -1;
if (size + 1 > target_buffer_size)
return -1;
if (size > buffer_size - *offset)
return -1;
memcpy(target_buffer, buffer + *offset, size);
*offset += size;
target_buffer[size] = 0;
return 0;
}
void write_short(uint8_t *buffer, size_t buffer_size, size_t *offset, uint16_t value) {
if (buffer_size - *offset < 2)
return;
*((uint16_t*) (buffer + *offset)) = value;
*offset += 2;
}
int read_short(uint8_t *buffer, size_t buffer_size, size_t *offset, uint16_t *target) {
if (buffer_size - *offset < 2)
return -1;
uint8_t a = *(buffer + (*offset)++);
uint8_t b = *(buffer + (*offset)++);
*target = (uint16_t) (0x0U | a << 8 | b);
return 0;
}
| 2.6875 | 3 |
2024-11-18T20:56:06.732790+00:00 | 2018-09-04T19:47:12 | 67fb5eea8a4162809c5679ec3ce26b8d3acd8332 | {
"blob_id": "67fb5eea8a4162809c5679ec3ce26b8d3acd8332",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-04T19:47:12",
"content_id": "dcdd9199d466e2ff28b4ebe2c04aca21be268a2c",
"detected_licenses": [
"MIT"
],
"directory_id": "72d43eca7f3cbbb78f535374c9d12e3e254baf91",
"extension": "c",
"filename": "square_cover_optimized.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147230286,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7538,
"license": "MIT",
"license_type": "permissive",
"path": "/samples/square_cover_optimized.c",
"provenance": "stackv2-0092.json.gz:62112",
"repo_name": "JoeNiesforny/RendevzousProblem",
"revision_date": "2018-09-04T19:47:12",
"revision_id": "2277fd69d91f627d3c2e8de5bda226c1eaf991f1",
"snapshot_id": "5d12e05db218abd060f591ed85d1cb781830c6b5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JoeNiesforny/RendevzousProblem/2277fd69d91f627d3c2e8de5bda226c1eaf991f1/samples/square_cover_optimized.c",
"visit_date": "2020-03-27T22:25:47.596796"
} | stackv2 | #include <cmath>
#include <iostream>
#define PI 3.14159265
#include "rendezvous.h"
void initSquareCoverOpt(player*, player*);
void moveSquareCoverOpt(player*, player*);
algorithm squareCoverOptAlgorithm = {
"Square Cover Optimized",
initSquareCoverOpt,
moveSquareCoverOpt
};
static int layerLimit;
static struct squareCoverPlayer {
bool onGrid;
struct position grid;
int layerIter;
int layerDirection;
struct position sourceSquare;
int squareIter;
int squareDirection;
int vertexIter;
int connectorD;
} ps[] = {{
0
}, {
0
}
};
#define psc(p) ps[(p->id - 1)]
static struct position getClosestParentPoint(player* p) {
struct position newGrid;
auto width = 2;
newGrid.x = p->pos.x - fmod(p->pos.x, width);
if (fmod(p->pos.x, width) > 1)
newGrid.x += width;
newGrid.y = p->pos.y - fmod(p->pos.y, width);
if (fmod(p->pos.y, width) > 1)
newGrid.y += width;
return newGrid;
}
static void _initSquareCoverOpt(player* p) {
psc(p) = {0};
psc(p).layerDirection = 1;
psc(p).squareDirection = 1;
psc(p).grid = getClosestParentPoint(p);
psc(p).sourceSquare = psc(p).grid;
}
void initSquareCoverOpt(player* p1, player* p2) {
auto d = getDistance(&p1->pos, &p2->pos);
layerLimit = 0;
while (d > pow(2, layerLimit)){
layerLimit++;
};
layerLimit = layerLimit - floor(layerLimit / 8) + 1; // Optimized version
#ifdef DEBUG
printf("Set layer limit to %i\n", layerLimit);
#endif
_initSquareCoverOpt(p1);
_initSquareCoverOpt(p2);
}
static void _moveSquareCoverOpt(player*);
void moveSquareCoverOpt(player* p1, player* p2) {
_moveSquareCoverOpt(p1);
auto d = getDistance(&p1->pos, &p2->pos);
if (d <= p1->sight || d <= p2->sight)
return;
_moveSquareCoverOpt(p2);
}
static void movePlayerToGrid(player* p);
static struct position getVertex(int layer, struct position square, int vertex);
static void movePlayerToVertex(player* p, struct position vertex);
static void computeNewLayerOpt(player* p);
static void _moveSquareCoverOpt(player* p) {
if (p->speed != 0){
if (psc(p).onGrid == false) {
movePlayerToGrid(p);
} else {
struct position vertex = getVertex(psc(p).layerIter, psc(p).grid, psc(p).vertexIter);
movePlayerToVertex(p, vertex);
// Check if need to get new vertex
if (p->pos.x == vertex.x && p->pos.y == vertex.y) {
psc(p).vertexIter++;
if (psc(p).vertexIter > 4) {
psc(p).vertexIter = 0;
psc(p).squareIter += psc(p).squareDirection;
psc(p).grid = getVertex(psc(p).layerIter, psc(p).sourceSquare, psc(p).squareIter);
if (psc(p).squareIter > 4) {
computeNewLayerOpt(p);
}
}
}
}
}
}
static void movePlayerToGrid(player* p) {
if (fmod(p->pos.x, 1) != 0 || fmod(p->pos.y, 1) != 0) { // ToDo Check
if (p->pos.x != psc(p).grid.x || p->pos.y != psc(p).grid.y) {
auto old = p->pos;
auto x1 = fabs(psc(p).grid.x - p->pos.x);
auto y1 = fabs(psc(p).grid.y - p->pos.y);
auto sum = x1 + y1;
auto speed = p->speed * p->speed;
auto speedX = sqrt(speed * (x1 / sum));
if (speedX != 0 && p->pos.x < psc(p).grid.x) {
p->pos.x += speedX;
if (p->pos.x > psc(p).grid.x)
p->pos.x = psc(p).grid.x;
}
else {
p->pos.x -= speedX;
if (p->pos.x < psc(p).grid.x)
p->pos.x = psc(p).grid.x;
}
auto speedY = sqrt(speed * (y1 / sum));
if (speedY != 0 && p->pos.y < psc(p).grid.y) {
p->pos.y += speedY;
if (p->pos.y > psc(p).grid.y)
p->pos.y = psc(p).grid.y;
}
else {
p->pos.y -= speedY;
if (p->pos.y < psc(p).grid.y)
p->pos.y = psc(p).grid.y;
}
#ifdef WARNING
if (getDistance(&old, &p->pos) != p->speed)
printf("Warning! Player%i: distance = %f, speed = %f, old x:%f, y:%f, new x:%f, y:%f\n",
p->id, getDistance(&old, &p->pos), p->speed, old.x, old.y, p->pos.x, p->pos.y);
#endif
p->road += p->speed;
}
}
else {
psc(p).onGrid = true;
}
}
static int computeLayerOpt(int layer) {
return layer - (floor((layer - (layer % 8)) / 4)) - (floor(layer % 8) > 3 ? (floor(layer % 8) > 5 ? 2 : 1) : 0);
}
// Get vertex from square
// vertex counts from top left to left bottom (clockwise)
static struct position getVertex(int layer, struct position square, int vertex) {
auto squareLayer = computeLayerOpt(layer);
if (vertex < 0 && vertex > 4)
return {-1};
struct position pt = {square.x, square.y};
switch(vertex) {
//case 0 and case 4 are pointing at the left top corner of square
case 1:
pt.x += pow(2, squareLayer);
break;
case 2:
pt.x += pow(2, squareLayer);
pt.y += pow(2, squareLayer);
break;
case 3:
pt.y += pow(2, squareLayer);
break;
}
return pt;
}
static void movePlayerToVertex(player* p, struct position vertex) {
struct position old = {p->pos.x, p->pos.y};
if (p->pos.x != vertex.x) {
if (p->pos.x < vertex.x) {
p->pos.x += p->speed;
if (p->pos.x > vertex.x)
p->pos.x = vertex.x;
}
else {
p->pos.x -= p->speed;
if (p->pos.x < vertex.x)
p->pos.x = vertex.x;
}
}
if (p->pos.y != vertex.y) {
if (p->pos.y < vertex.y) {
p->pos.y += p->speed;
if (p->pos.y > vertex.y)
p->pos.y = vertex.y;
}
else {
p->pos.y -= p->speed;
if (p->pos.y < vertex.y)
p->pos.y = vertex.y;
}
}
// Add road that player did in this move
p->road += fabs(old.x - p->pos.x) + fabs(old.y - p->pos.y);
}
static void connectorD(player* p) {
if (psc(p).connectorD == 0) {
psc(p).sourceSquare.x = psc(p).sourceSquare.x +
pow(2, computeLayerOpt(psc(p).layerIter)) / 2 * psc(p).layerDirection;
psc(p).connectorD = 1;
}
else if (psc(p).connectorD == 1) {
psc(p).sourceSquare.y = psc(p).sourceSquare.y +
pow(2, computeLayerOpt(psc(p).layerIter)) / 2 * psc(p).layerDirection;
psc(p).connectorD = 2;
}
psc(p).grid = psc(p).sourceSquare;
psc(p).squareIter = 4;
psc(p).vertexIter = 4;
}
static void computeNewLayerOpt(player* p) {
if (psc(p).layerIter % 8 > 3) { // Optimized for block sequence (z+4) = 8
if (psc(p).layerIter % 2 == 0 && psc(p).layerIter != 0 && psc(p).connectorD < 2) {
connectorD(p);
return;
}
}
psc(p).connectorD = 0;
psc(p).squareIter = 0;
psc(p).grid = psc(p).sourceSquare;
psc(p).layerIter += psc(p).layerDirection;
if (psc(p).layerIter > layerLimit) {
psc(p).layerDirection = -1;
psc(p).layerIter += psc(p).layerDirection;
} else if (psc(p).layerIter < 0) {
psc(p).layerDirection = 1;
psc(p).layerIter += psc(p).layerDirection;
}
} | 2.671875 | 3 |
2024-11-18T20:56:06.823338+00:00 | 2018-08-13T12:20:33 | de5f97ede1dde62aabc216faa5891bb5810413b6 | {
"blob_id": "de5f97ede1dde62aabc216faa5891bb5810413b6",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-13T12:20:33",
"content_id": "affb4b3fd8886dba86ad253d9b734ce8ed09d56f",
"detected_licenses": [
"MIT"
],
"directory_id": "ceb687c69c8b806359253cea86997cc730464285",
"extension": "c",
"filename": "ft_tools.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 129691916,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2264,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ft_tools.c",
"provenance": "stackv2-0092.json.gz:62241",
"repo_name": "jalloulik/raytracer",
"revision_date": "2018-08-13T12:20:33",
"revision_id": "27154810da57146359c7b608ca128a99c345d2f6",
"snapshot_id": "f1a75b9492819cb79742f09a9793b491a450b180",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jalloulik/raytracer/27154810da57146359c7b608ca128a99c345d2f6/src/ft_tools.c",
"visit_date": "2020-03-11T01:27:10.258770"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_tools.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kjalloul <kjalloul@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/22 11:28:51 by kjalloul #+# #+# */
/* Updated: 2018/06/22 14:07:23 by kjalloul ### ########.fr */
/* */
/* ************************************************************************** */
#include "rtv1.h"
t_prim *ft_add_lst_file(t_prim *list, int type)
{
t_prim *start;
if (list == NULL)
{
if ((list = (t_prim*)malloc(sizeof(*list))) == NULL)
ft_error(ERROR);
start = list;
}
else
{
start = list;
while (list->next != NULL)
list = list->next;
if (((list->next) = (t_prim*)malloc(sizeof(*list))) == NULL)
ft_error(ERROR);
list = list->next;
}
list->type = type;
ft_intialise_primitives(list);
list->next = NULL;
return (start);
}
t_cut *ft_add_lst_cut(t_cut *cut)
{
t_cut *tmp;
if (!cut)
{
cut = ft_malloc(sizeof(*cut));
cut->next = NULL;
return (cut);
}
tmp = cut;
cut = ft_malloc(sizeof(*cut));
cut->next = tmp;
return (cut);
}
t_light *ft_add_lst_light(t_light *list, int type)
{
t_light *start;
if (list == NULL)
{
if ((list = (t_light*)malloc(sizeof(*list))) == NULL)
ft_error(ERROR);
start = list;
}
else
{
start = list;
while (list->next != NULL)
list = list->next;
if (((list->next) = (t_light*)malloc(sizeof(*list))) == NULL)
ft_error(ERROR);
list = list->next;
}
list->type = type;
list->next = NULL;
return (start);
}
int ft_count_tab(char **tab)
{
int i;
i = 0;
if (tab == NULL)
ft_error(ERROR);
while (tab[i] != 0)
i++;
return (i);
}
void ft_free_tab(char **tab)
{
int i;
i = 0;
while (tab[i] != 0)
{
free(tab[i]);
i++;
}
free(tab);
}
| 2.53125 | 3 |
2024-11-18T21:20:01.418890+00:00 | 2017-05-19T01:23:40 | b9b77c1b7f444d9138a3ad08e6ebd6158e8248b3 | {
"blob_id": "b9b77c1b7f444d9138a3ad08e6ebd6158e8248b3",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-19T01:23:40",
"content_id": "6cd501b4269a7b3ecf2832997f4892d7cbf8ef96",
"detected_licenses": [
"MIT"
],
"directory_id": "d64a58f2535aaa6f1fee0d2971b363cbda920588",
"extension": "c",
"filename": "nodes_asm.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87768806,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10253,
"license": "MIT",
"license_type": "permissive",
"path": "/src/nodes_asm.c",
"provenance": "stackv2-0094.json.gz:422",
"repo_name": "Miouyouyou/refactored-octo-enigma",
"revision_date": "2017-05-19T01:23:40",
"revision_id": "0d306e0c052958234d81ab171040bd0e54de8196",
"snapshot_id": "b923d0c79c1db4b0bbd7b6674c751204f6d611ab",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Miouyouyou/refactored-octo-enigma/0d306e0c052958234d81ab171040bd0e54de8196/src/nodes_asm.c",
"visit_date": "2021-01-19T09:35:31.401826"
} | stackv2 | #include <src/nodes_asm.h>
#include <myy/helpers/memory.h>
#include <myy/helpers/log.h>
enum {
arg_cat_invalid,
arg_cat_condition,
arg_cat_register,
arg_cat_immediate,
arg_cat_negative_immediate,
arg_cat_immediate_or_address,
arg_cat_data_address,
arg_cat_frame_address_pc_relative,
arg_cat_regmask
};
static uint8_t const mnemonics_args_type[n_known_instructions][MAX_ARGS] =
{
[inst_add_immediate] =
{arg_cat_register, arg_cat_register, arg_cat_immediate},
[inst_b_address] =
{arg_cat_condition, arg_cat_frame_address_pc_relative, 0},
[inst_bl_address] =
{arg_cat_condition, arg_cat_frame_address_pc_relative, 0},
[inst_blx_address] =
{arg_cat_condition, arg_cat_frame_address_pc_relative, 0},
[inst_blx_register] = {arg_cat_condition, arg_cat_register, 0},
[inst_bx_register] = {arg_cat_condition, arg_cat_register, 0},
[inst_mov_immediate] = {arg_cat_register, arg_cat_immediate, 0},
[inst_mov_register] = {arg_cat_register, arg_cat_register, 0},
[inst_movt_immediate] = {arg_cat_register, arg_cat_immediate, 0},
[inst_movw_immediate] =
{arg_cat_register, arg_cat_immediate_or_address, 0},
[inst_mvn_immediate] =
{arg_cat_register, arg_cat_negative_immediate, 0},
[inst_pop_regmask] = {arg_cat_regmask, 0, 0},
[inst_push_regmask] = {arg_cat_regmask, 0, 0},
[inst_sub_immediate] =
{arg_cat_register, arg_cat_register, arg_cat_immediate},
[inst_svc_immediate] = {arg_cat_immediate, 0, 0},
};
static uint8_t const * const mnemonics[n_known_instructions] = {
[inst_add_immediate] = "add",
[inst_b_address] = "b",
[inst_bl_address] = "bl",
[inst_blx_address] = "blx",
[inst_blx_register] = "blx",
[inst_bx_register] = "bx",
[inst_mov_immediate] = "mov",
[inst_mov_register] = "mov",
[inst_movt_immediate] = "movt",
[inst_movw_immediate] = "movw",
[inst_mvn_immediate] = "mvn",
[inst_pop_regmask] = "pop",
[inst_push_regmask] = "push",
[inst_sub_immediate] = "sub",
[inst_svc_immediate] = "svc"
};
static uint8_t const * const
mnemonics_full_desc[n_known_instructions] = {
[inst_add_immediate] = "ADD (Immediate)",
[inst_b_address] = "B",
[inst_bl_address] = "BL",
[inst_blx_address] = "BLX",
[inst_blx_register] = "BLX (Register)",
[inst_bx_register] = "BX (Register)",
[inst_mov_immediate] = "MOV",
[inst_mov_register] = "MOV (Register)",
[inst_movt_immediate] = "MOVT",
[inst_movw_immediate] = "MOVW",
[inst_mvn_immediate] = "MVN",
[inst_pop_regmask] = "POP",
[inst_push_regmask] = "PUSH",
[inst_sub_immediate] = "SUB (Immediate)",
[inst_svc_immediate] = "SVC"
};
static uint8_t mnemonic_args[n_known_instructions] = {
[inst_add_immediate] = 3,
[inst_b_address] = 2,
[inst_bl_address] = 2,
[inst_blx_address] = 2,
[inst_blx_register] = 2,
[inst_bx_register] = 2,
[inst_mov_immediate] = 2,
[inst_mov_register] = 2,
[inst_movt_immediate] = 2,
[inst_movw_immediate] = 2,
[inst_mvn_immediate] = 2,
[inst_pop_regmask] = 1,
[inst_push_regmask] = 1,
[inst_sub_immediate] = 3,
[inst_svc_immediate] = 1,
};
static uint8_t const * conditions_strings[15] = {
[cond_eq] = "eq",
[cond_ne] = "ne",
[cond_cs] = "cs",
[cond_cc] = "cc",
[cond_mi] = "mi",
[cond_pl] = "pl",
[cond_vs] = "vs",
[cond_vc] = "vc",
[cond_hi] = "hi",
[cond_ls] = "ls",
[cond_ge] = "ge",
[cond_lt] = "lt",
[cond_gt] = "gt",
[cond_le] = "le",
[cond_al] = "al"
};
uint8_t const * register_names[] = {
[r0] = "r0",
[r1] = "r1",
[r2] = "r2",
[r3] = "r3",
[r4] = "r4",
[r5] = "r5",
[r6] = "r6",
[r7] = "r7",
[r8] = "r8",
[r9] = "r9",
[r10] = "r10",
[r11] = "r11",
[r12] = "ip",
[r13] = "sp",
[r14] = "lr",
[r15] = "pc"
};
extern uint8_t scratch_buffer[];
struct quads_and_size node_asm_generate_title
(nodes const * __restrict const nodes,
void const * __restrict const uncasted_frame,
struct glyph_infos const * __restrict const fonts_glyphs,
buffer_t buffer)
{
struct quads_and_size text_quads_and_size = {
.quads = {.size = 0, .count = 0},
.size = {.x = 0, .y = -24}
};
struct armv7_text_frame const * __restrict const armv7_frame =
(struct armv7_text_frame const * __restrict) uncasted_frame;
struct generated_quads quads = myy_single_string_to_quads(
fonts_glyphs, armv7_frame->metadata.name, buffer, &text_quads_and_size.size
);
text_quads_and_size.quads.size = quads.size;
text_quads_and_size.quads.count = quads.count;
return text_quads_and_size;
}
static struct quads_and_size generate_instruction_quads
(struct glyph_infos const * __restrict const glyph_infos,
struct instruction_representation const * __restrict const instruction,
uint8_t * __restrict const cpu_buffer, int16_t const y_offset)
{
uint8_t * __restrict buffer = cpu_buffer;
struct quads_and_size total = {0};
struct generated_quads string_quads;
position_S text_pos = position_S_struct(0, y_offset);
// Arbitrary defined. Ugly but should do the trick for the PoC.
uint8_t const * __restrict const mnemonic =
mnemonics[instruction->mnemonic_id];
unsigned int n_mnemonic_args =
mnemonic_args[instruction->mnemonic_id];
string_quads = myy_single_string_to_quads(
glyph_infos, mnemonic, buffer, &text_pos
);
total.quads.count += string_quads.count;
total.quads.size += string_quads.size;
buffer += string_quads.size;
text_pos.x = 60;
uint8_t empty_buffer = '\0';
uint8_t to_string_buffer[64];
uint8_t const * current_string;
unsigned int a = 0;
while (a < n_mnemonic_args) {
struct instruction_args_infos arg = instruction->args[a];
switch(arg.type) {
case arg_invalid:
current_string = &empty_buffer; break;
case arg_condition:
current_string = conditions_strings[arg.value];
break;
case arg_register:
current_string = register_names[arg.value];
break;
case arg_immediate:
snprintf((char *) to_string_buffer, 31, "%d", arg.value);
current_string = to_string_buffer;
break;
case arg_address:
snprintf((char *) to_string_buffer, 11, "0x%08x", arg.value);
current_string = to_string_buffer;
break;
case arg_data_symbol_address:
case arg_data_symbol_address_top16:
case arg_data_symbol_address_bottom16:
case arg_data_symbol_size:
case arg_frame_address:
case arg_frame_address_pc_relative:
snprintf((char *) to_string_buffer, 31, "%d", arg.value);
current_string = to_string_buffer;
break;
case arg_regmask:
snprintf((char *) to_string_buffer, 34, "%b", arg.value);
current_string = to_string_buffer;
break;
}
int current_x = text_pos.x;
string_quads = myy_single_string_to_quads(
glyph_infos, current_string, buffer, &text_pos
);
total.quads.count += string_quads.count;
total.quads.size += string_quads.size;
buffer += string_quads.size;
text_pos.x += 12;
a++;
}
while (a < MAX_ARGS) {
/*add_invalid_hitbox();*/
a++;
}
total.size = text_pos;
return total;
}
struct quads_and_size node_asm_generate_content
(nodes const * __restrict const nodes,
void const * __restrict const uncasted_frame,
struct glyph_infos const * __restrict const fonts_glyphs,
buffer_t buffer)
{
struct armv7_text_frame const * __restrict const text_frame =
(struct armv7_text_frame const * __restrict) uncasted_frame;
unsigned int const y_offset = 20;
unsigned int n_instructions =
text_frame->metadata.stored_instructions;
uint32_t text_pos_y = 0; // Start after the title
struct quads_and_size total = {0};
struct quads_and_size instruction_quads;
unsigned int cpu_buffer_offset = 0;
for (unsigned int i = 0; i < n_instructions; i++) {
instruction_quads = generate_instruction_quads(
fonts_glyphs, text_frame->instructions+i,
buffer+cpu_buffer_offset, text_pos_y
);
total.quads.count += instruction_quads.quads.count;
total.quads.size += instruction_quads.quads.size;
if (instruction_quads.size.x > total.size.x)
total.size.x = instruction_quads.size.x;
cpu_buffer_offset += instruction_quads.quads.size;
text_pos_y += y_offset;
}
total.size.y = text_pos_y;
return total;
}
static void dropdown_menu_hit_func
(struct dropdown_menus const * __restrict const menus,
unsigned int i)
{
menus->current_dropdown_callback(
menus->current_dropdown_callback_data,
i
);
LOG("%d\n", i);
}
void nodes_asm_setup_dropdowns_menus
(nodes * __restrict const nodes,
struct dropdown_menus * __restrict const menus)
{
nodes->current_menus = menus;
dropdowns_menu_setup_menu(
menus, ga_dropdown_menu_instructions, mnemonics_full_desc,
n_known_instructions, dropdown_menu_hit_func
);
dropdowns_menu_setup_menu(
menus, ga_dropdown_menu_registers, register_names,
16, dropdown_menu_hit_func
);
dropdowns_menu_setup_menu(
menus, ga_dropdown_menu_frame_names, register_names, 0,
dropdown_menu_hit_func
);
dropdowns_menu_setup_menu(
menus, ga_dropdown_menu_conditions, conditions_strings, 15,
dropdown_menu_hit_func
);
}
unsigned int selected_line = 0;
extern struct glyph_infos myy_glyph_infos;
void nodes_set_selected_instruction
(void * __restrict const uncasted_nodes, unsigned int instruction_id)
{
/*struct nodes_display_data * __restrict const nodes =
(struct nodes_display_data *) uncasted_nodes;
unsigned int node_id = nodes_get_selected_id(nodes);
struct armv7_text_frame * current_frame =
(struct armv7_text_frame *) nodes->associated_data[node_id];
struct instruction_representation * instruction =
current_frame->instructions+selected_line;
instruction_mnemonic_id(instruction, instruction_id);
generate_frames_quads(
(struct armv7_text_frame **) nodes->associated_data, 2, nodes,
&myy_glyph_infos
);
generate_and_store_nodes_containers_in_gpu(nodes, scratch_buffer);*/
LOG("Meow\n");
}
void nodes_asm_onclick_handler
(nodes const * __restrict const nodes,
unsigned int index, position_S const pos)
{
struct dropdown_menus * __restrict const menus =
nodes->current_menus;
dropdown_menus_set_current(menus, ga_dropdown_menu_instructions);
dropdown_menus_set_current_callback(
menus, nodes_set_selected_instruction, (void *) nodes
);
enable_context_menu();
LOG(
"Meep : %d - rel_x: %d, rel_y: %d (%d)\n",
index, pos.x, pos.y, (pos.y-6)/20
);
selected_line = (pos.y-6)/20;
}
| 2.203125 | 2 |
2024-11-18T22:23:03.262420+00:00 | 2022-01-18T13:18:10 | a8c27769b2c652e5de0a5c93ed2ccaeaa3808fe1 | {
"blob_id": "a8c27769b2c652e5de0a5c93ed2ccaeaa3808fe1",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-18T13:18:10",
"content_id": "e5c84146bbf91d5578c98d457e5a21a2f7ac7466",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "080ce6fe886a3485dc87d274d865443c61e21b99",
"extension": "h",
"filename": "commons.h",
"fork_events_count": 2,
"gha_created_at": "2018-07-13T18:17:42",
"gha_event_created_at": "2020-12-09T19:12:35",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 140879632,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 578,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libjnc/src/commons.h",
"provenance": "stackv2-0099.json.gz:255",
"repo_name": "java-native-call/jnc",
"revision_date": "2022-01-18T13:18:10",
"revision_id": "804232beaa280cccc9fc0fdd1ff5d377438d1916",
"snapshot_id": "6cd3e6ca73f4318c43ff4372d3f23e119a442a73",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/java-native-call/jnc/804232beaa280cccc9fc0fdd1ff5d377438d1916/libjnc/src/commons.h",
"visit_date": "2022-02-11T06:02:42.068466"
} | stackv2 | #ifndef JNC_COMMONS_H
#define JNC_COMMONS_H
#include <jni.h>
#include <stdint.h> // NOLINT(modernize-deprecated-headers)
#include "jnc_type_traits.h"
// limit should not be negative
// usually should be checked before pass to this function
// or this function will return true
inline bool is_sizet_large_enough(jlong value) {
// maybe the value here we got is calculated by minus something.
// treat it as unlimited if the value is greater than a quart of the whole memory can be presented.
return value >> (8 * sizeof (size_t) - 2);
}
#endif /* JNC_COMMONS_H */
| 2.046875 | 2 |
2024-11-18T22:23:03.706520+00:00 | 2021-06-13T14:08:53 | 469f5116469ca22f42ab146674c53669fd2df7f3 | {
"blob_id": "469f5116469ca22f42ab146674c53669fd2df7f3",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-13T14:08:53",
"content_id": "d832d57231caa2cec5b51aabd5b5a20d37eab4f8",
"detected_licenses": [
"MIT"
],
"directory_id": "80f1fdf22e5efffea93449d668ea1ed83dd27aaf",
"extension": "c",
"filename": "acoustics_alg.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 309816312,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5697,
"license": "MIT",
"license_type": "permissive",
"path": "/wave-propagation/openmp/acoustics_alg.c",
"provenance": "stackv2-0099.json.gz:643",
"repo_name": "filipmanole/wave-propagation",
"revision_date": "2021-06-13T14:08:53",
"revision_id": "9170ab0a7742b45cf8d3209ed2c2a5673f8dab5b",
"snapshot_id": "7d139d0fc148f56d0b4617a7ba08abdaaff8bd5e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/filipmanole/wave-propagation/9170ab0a7742b45cf8d3209ed2c2a5673f8dab5b/wave-propagation/openmp/acoustics_alg.c",
"visit_date": "2023-05-30T20:50:59.707129"
} | stackv2 | /*
* Student: Trascau Mihai
* Grupa: 344C4
*
* Lucrare: Ecuatia undelor pentru acustica 2D
* Fisier: acoustics_alg.h
* Descriere: Fisier sursa care contine implementarile pentru algoritmul utilizat (in cazul nostru MDF pentru ecuatia propagarii undei)
*/
#include "acoustics.h"
int on_edge(int x, int y)
{
if(x == 0 && y != 0 && y != nx-1)
return N_EDGE;
if(x == ny-1 && y != 0 && y != nx-1)
return S_EDGE;
if(y == 0 && x != 0 && x != ny-1)
return W_EDGE;
if(y == nx-1 && x != 0 && x != ny-1)
return E_EDGE;
return 0;
}
int on_corner(int x, int y)
{
if(x == 0 && y == 0)
return NW_CORNER;
if(x == 0 && y == nx-1)
return NE_CORNER;
if(x == ny-1 && y == 0)
return SW_CORNER;
if(x == ny-1 && y == nx-1)
return SE_CORNER;
return 0;
}
int on_structure_edge(int x, int y)
{
int i;
for(i=0;i<scenario[scn_index].nr_struct;i++)
{
if(y > scenario[scn_index].structure[i].c_points[0][1] && y < scenario[scn_index].structure[i].c_points[1][1])
if(x == scenario[scn_index].structure[i].c_points[0][0])
return N_EDGE;
if(x > scenario[scn_index].structure[i].c_points[1][0] && x < scenario[scn_index].structure[i].c_points[2][0])
if(y == scenario[scn_index].structure[i].c_points[1][1])
return E_EDGE;
if(y > scenario[scn_index].structure[i].c_points[3][1] && y < scenario[scn_index].structure[i].c_points[2][1])
if(x == scenario[scn_index].structure[i].c_points[3][0])
return S_EDGE;
if(x > scenario[scn_index].structure[i].c_points[0][0] && x < scenario[scn_index].structure[i].c_points[3][0])
if(y == scenario[scn_index].structure[i].c_points[0][1])
return W_EDGE;
}
return 0;
}
int on_structure_corner(int x, int y)
{
int i;
for(i=0;i<scenario[scn_index].nr_struct;i++)
{
if(x == scenario[scn_index].structure[i].c_points[0][0] && y == scenario[scn_index].structure[i].c_points[0][1])
return NW_CORNER;
if(x == scenario[scn_index].structure[i].c_points[1][0] && y == scenario[scn_index].structure[i].c_points[1][1])
return NE_CORNER;
if(x == scenario[scn_index].structure[i].c_points[2][0] && y == scenario[scn_index].structure[i].c_points[2][1])
return SE_CORNER;
if(x == scenario[scn_index].structure[i].c_points[3][0] && y == scenario[scn_index].structure[i].c_points[3][1])
return SW_CORNER;
}
return 0;
}
int in_structure(int x, int y)
{
int i;
for(i=0;i<scenario[scn_index].nr_struct;i++)
{
if(x > scenario[scn_index].structure[i].c_points[0][0] && x < scenario[scn_index].structure[i].c_points[3][0])
if(y > scenario[scn_index].structure[i].c_points[0][1] && y < scenario[scn_index].structure[i].c_points[1][1])
return 1;
}
return 0;
}
double compute_node(int x, int y)
{
return (2*ub[x][y] - ua[x][y] + pow(TIME_STEP,2)/pow(H,2) * (ub[x+1][y] - 4*ub[x][y] + ub[x-1][y] + ub[x][y+1] + ub[x][y-1]));
}
double compute_edge_node(int i, int j, int side)
{
switch(side)
{
case N_EDGE:
return ub[i+1][j];
case E_EDGE:
return ub[i][j-1];
case S_EDGE:
return ub[i-1][j];
case W_EDGE:
return ub[i][j+1];
default:
return 0;
}
}
double compute_corner_node(int i, int j, int corner)
{
switch(corner)
{
case NW_CORNER:
return (ub[i][j+1]+ub[i+1][j])/2;
case NE_CORNER:
return (ub[i+1][j]+ub[i][j-1])/2;
case SE_CORNER:
return (ub[i][j-1]+ub[i-1][j])/2;
case SW_CORNER:
return (ub[i-1][j]+ub[i][j+1])/2;
default:
return 0;
}
}
double compute_structure_corner_node(int i, int j, int corner)
{
switch(corner)
{
case NW_CORNER:
return (ub[i][j-1]+ub[i-1][j])/2;
case NE_CORNER:
return (ub[i-1][j]+ub[i][j+1])/2;
case SE_CORNER:
return (ub[i][j+1]+ub[i+1][j])/2;
case SW_CORNER:
return (ub[i+1][j]+ub[i][j-1])/2;
default:
return 0;
}
}
double compute_structure_edge_node(int i, int j, int side)
{
switch(side)
{
case N_EDGE:
return ub[i-1][j];
case E_EDGE:
return ub[i][j+1];
case S_EDGE:
return ub[i+1][j];
case W_EDGE:
return ub[i][j-1];
default:
return 0;
}
}
int is_source(int x, int y, int radius, int source_active)
{
if(!source_active)
return 0;
if(sqrt(pow(scenario[scn_index].source.x-x,2)+pow(scenario[scn_index].source.y-y,2)) <= radius)
return 1;
return 0;
}
void pulse_source(int radius, int step, double amp)
{
int i,j;
for(i=0;i<ny;i++)
for(j=0;j<nx;j++)
if(is_source(i,j,radius,1))
uc[i][j] = amp*fabs(sin(step*M_PI/4));
}
void s_compute_acoustics()
{
int i,j;
int step = 0;
int source_active = 1;
int place;
int radius = scenario[scn_index].source.radius;
while(step < (int)(MAX_TIME/TIME_STEP))
{
if(step < (int)(MAX_TIME/TIME_STEP)/2)
pulse_source(radius,step,scenario[scn_index].source.p_amp);
else if(source_active)
{
#pragma omp parallel for private(i,j)
for(i=0;i<ny;i++)
for(j=0;j<nx;j++)
{
if(is_source(i,j,radius,source_active))
uc[i][j] = ub[i][j] = ua[i][j] = 0;
}
source_active = 0;
}
#pragma omp parallel for private(i,j,place)
for(i=0;i<ny;i++)
for(j=0;j<nx;j++)
{
if(!on_corner(i,j) && !on_edge(i,j) && !is_source(i,j,radius,source_active) && !on_structure_edge(i,j) && !on_structure_corner(i,j) && !in_structure(i,j))
uc[i][j] = compute_node(i,j);
else if((place = on_edge(i,j)))
uc[i][j] = compute_edge_node(i,j,place);
else if((place = on_corner(i,j)))
uc[i][j] = compute_corner_node(i,j,place);
else if((place = on_structure_edge(i,j)))
uc[i][j] = compute_structure_edge_node(i,j,place);
else if((place = on_structure_corner(i,j)))
uc[i][j] = compute_structure_corner_node(i,j,place);
ua[i][j] = 0;
}
if(step%SAVE_TIME == 0)
export_to_vtk(step);
xchg = ua;
ua = ub;
ub = uc;
uc = xchg;
step++;
}
}
| 2.640625 | 3 |
2024-11-18T22:23:03.986418+00:00 | 2021-06-19T08:58:32 | c83b3fcea14961fe55ccf211eeb60cea128ec813 | {
"blob_id": "c83b3fcea14961fe55ccf211eeb60cea128ec813",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-19T08:58:32",
"content_id": "5006f93422a6cdbb3e852f32e15a4e9c85812483",
"detected_licenses": [
"MIT"
],
"directory_id": "82d22c32aad603524b43da630264fe450b2bc871",
"extension": "h",
"filename": "Random.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 192639867,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3104,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Random.h",
"provenance": "stackv2-0099.json.gz:1029",
"repo_name": "favorov/SeSiMCMC",
"revision_date": "2021-06-19T08:58:32",
"revision_id": "263f001f2b5a75617047522b7c0d622ea412dee1",
"snapshot_id": "5fdac6f60db1cca8f1e45ba59945d472b9d0d611",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/favorov/SeSiMCMC/263f001f2b5a75617047522b7c0d622ea412dee1/src/Random.h",
"visit_date": "2021-08-10T18:12:34.079024"
} | stackv2 | //$Id$
//The name "ultra is for the memory of fsultra library - the base of this code
//
//Changes: the initilizer has got two lines
// ij=ij%31328;
// kl=kl%30081;
// which allow to use it with any start numbers.
// array returned by rnmar() in now 0-based.
//
// added ultra-like
// void rinit(long,long) and
// float uni()
//
// 21.09.2000. A.Favorov.
//
/*
C This random number generator originally appeared in "Toward a Universal
C Random Number Generator" by George Marsaglia and Arif Zaman.
C Florida State University Report: FSU-SCRI-87-50 (1987)
C
C It was later modified by F. James and published in "A Review of Pseudo-
C random Number Generators"
C
C THIS IS THE BEST KNOWN RANDOM NUMBER GENERATOR AVAILABLE.
C (However, a newly discovered technique can yield
C a period of 10^600. But that is still in the development stage.)
C
C It passes ALL of the tests for random number generators and has a period
C of 2^144, is completely portable (gives bit identical results on all
C machines with at least 24-bit mantissas in the floating point
C representation).
C
C The algorithm is a combination of a Fibonacci sequence (with lags of 97
C and 33, and operation "subtraction plus one, modulo one") and an
C "arithmetic sequence" (using subtraction).
C========================================================================
This C language version was written by Jim Butler, and was based on a
FORTRAN program posted by David LaSalle of Florida State University.
*/
void rmarin(int ij, int kl);
/*
C This is the initialization routine for the random number generator RANMAR()
C NOTE: The seed variables can have values between: 0 <= IJ <= 31328
C 0 <= KL <= 30081
C The random number sequences created by these two seeds are of sufficient
C length to complete an entire calculation with. For example, if sveral
C different groups are working on different parts of the same calculation,
C each group could be assigned its own IJ seed. This would leave each group
C with 30000 choices for the second seed. That is to say, this random
C number generator can create 900 million different subsequences -- with
C each subsequence having a length of approximately 10^30.
C
C Use IJ = 1802 & KL = 9373 to test the random number generator. The
C subroutine RANMAR should be used to generate 20000 random numbers.
C Then display the next six random numbers generated multiplied by 4096*4096
C If the random number generator is working properly, the random numbers
C should be:
C 6533892.0 14220222.0 7275067.0
C 6172232.0 8354498.0 10633180.0
*/
void ranmar(float rvec[], int len);
/*
C This is the random number generator proposed by George Marsaglia in
C Florida State University Report: FSU-SCRI-87-50
C It was slightly modified by F. James to produce an array of pseudorandom
C numbers.
*/
void rinit(unsigned long seed1,unsigned long seed2);
float uni();
//these two interfaces are added by A. Favorov to
//maintain ultra-based code.
| 2.453125 | 2 |
2024-11-18T22:23:04.360329+00:00 | 2015-07-11T13:42:43 | 9b466a8e3de0988eb2ba078338c701763904fc4c | {
"blob_id": "9b466a8e3de0988eb2ba078338c701763904fc4c",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-11T13:42:43",
"content_id": "084825d68e314be0e75a08e00ce3d37fe064daa5",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "83092741d1c1c23bdc140a219e5b9c6a451e8c0e",
"extension": "c",
"filename": "flash_sec.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": 450,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/msp430/flash_sec.c",
"provenance": "stackv2-0099.json.gz:1673",
"repo_name": "lyplcr/stm32-config",
"revision_date": "2015-07-11T13:42:43",
"revision_id": "862d30cbf3f107a3a15593e94419a7f0a7a6d8ee",
"snapshot_id": "493970a40e29a89fe081feebb1022c252293ad55",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lyplcr/stm32-config/862d30cbf3f107a3a15593e94419a7f0a7a6d8ee/msp430/flash_sec.c",
"visit_date": "2021-01-12T06:22:46.715885"
} | stackv2 | #include "flash_sec.h"
#include "flash.h"
int flash_sec_erase(struct flash_sec const* sec)
{
flash_erase(sec->base, 1);
return 0;
}
int flash_sec_write(struct flash_sec const* sec, unsigned off, void const* data, unsigned sz)
{
flash_write(sec->base + off, data, sz);
return 0;
}
int flash_sec_write_bytes(struct flash_sec const* sec, unsigned off, void const* data, unsigned sz)
{
flash_write_bytes(sec->base + off, data, sz);
return 0;
}
| 2.171875 | 2 |
2024-11-18T22:23:04.696189+00:00 | 2015-04-17T17:56:20 | 4d7223617a1ba7f060905b9fc9743e4c203654fc | {
"blob_id": "4d7223617a1ba7f060905b9fc9743e4c203654fc",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-17T17:56:20",
"content_id": "c66a887b06467bebe87b26ef571e414206a219f8",
"detected_licenses": [
"ISC"
],
"directory_id": "66bdc05e3e7e0a2069cbf59a8dad1fdf7a52caef",
"extension": "c",
"filename": "_iob.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7389536,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 824,
"license": "ISC",
"license_type": "permissive",
"path": "/gcc/stdio/_iob.c",
"provenance": "stackv2-0099.json.gz:2061",
"repo_name": "razzlefratz/MotleyTools",
"revision_date": "2015-04-17T17:56:20",
"revision_id": "3c69c574351ce6f4b7e687c13278d4b6cbb200f3",
"snapshot_id": "5e44f1315baa1be6fe5221916ccc834a96b59ca6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/razzlefratz/MotleyTools/3c69c574351ce6f4b7e687c13278d4b6cbb200f3/gcc/stdio/_iob.c",
"visit_date": "2020-05-19T05:01:58.992424"
} | stackv2 | /*====================================================================*
*
* _iob[]
*
* _stdio.h
*
* allocate and initialize the i/o buffers for STDIN, STDOUT and STDERR.
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#include "_stdio.h"
char _sibuf [_BUFSIZE] =
{
NUL
};
char _sobuf [_BUFSIZE] =
{
NUL
};
char _sebuf [_BUFSIZE] =
{
NUL
};
char _unbuf [_NFILE] =
{
NUL,
NUL,
NUL
};
FILE _iob [_NFILE] =
{
{
STDIN,
_IOREAD |_IOTEXT,
_sibuf,
_sibuf,
0
},
{
STDOUT,
_IOWRITE|_IOTEXT,
_sobuf,
_sobuf,
_BUFSIZE
},
{
STDERR,
_IOWRITE|_IOTEXT,
_sebuf,
_sebuf,
_BUFSIZE
}
};
| 2 | 2 |
2024-11-18T22:23:04.848828+00:00 | 2017-03-16T18:03:32 | 3fe273e37db26058a70effd6d5f199f98b9d1cce | {
"blob_id": "3fe273e37db26058a70effd6d5f199f98b9d1cce",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-16T18:03:32",
"content_id": "730acf729b10b9e4d7a4e93a24070f05e841be3d",
"detected_licenses": [
"MIT"
],
"directory_id": "b17d9745b1d0cf1e149f777a49cb1841f5440cef",
"extension": "h",
"filename": "os_kernel.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": 1667,
"license": "MIT",
"license_type": "permissive",
"path": "/core/os_kernel.h",
"provenance": "stackv2-0099.json.gz:2317",
"repo_name": "arhiv6/coop_test",
"revision_date": "2017-03-16T18:03:32",
"revision_id": "02b7582d82df06c241a191f1875b21651ae8c632",
"snapshot_id": "61cf995f5ef224bd5037bd74aae89e31f320f153",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/arhiv6/coop_test/02b7582d82df06c241a191f1875b21651ae8c632/core/os_kernel.h",
"visit_date": "2021-06-12T19:50:36.329780"
} | stackv2 | #pragma once
#ifndef _OS_KERNEL_H
#define _OS_KERNEL_H
typedef void (*pFunction)(void) ; // тип pFunction - указатель на функцию.
//==================================================================================================
// ПРОТОТИПЫ ФУНКЦИЙ
//--------------------------------------------------------------------------------------------------
// Системные сервисы
void os_run(); // Запускает ядро операционки в работу. Вызывается в конце main
void os_delay(uint32_t ticks); // Выдерживаем паузу внутри задачи Разрешен вызов только в контексте задачи Переключает контекст Использует системный таймер
void os_yield(); // Передача управления планировщику Разрешен вызов только в контексте задачи Переключает контекст
void os_sysTimer_isr(); // Обработка всех таймеров, вызывается из прерывания // TODO //#define SCMRTOS_USE_CUSTOM_TIMER 0
//--------------------------------------------------------------------------------------------------
// Управление задачами
void os_setTask(pFunction function, uint8_t priority); // Инициализируем конкретную задачу. Нельзя вызывать из прерывания
#endif // _OS_KERNEL_H
| 2.078125 | 2 |
2024-11-18T22:23:05.300412+00:00 | 2020-01-31T19:54:15 | 3396919cf155747fda900ff508302d28dbe80415 | {
"blob_id": "3396919cf155747fda900ff508302d28dbe80415",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-31T19:54:15",
"content_id": "27ae301cb670f56f33704c3459d2f9ef778b8bc7",
"detected_licenses": [
"MIT"
],
"directory_id": "4eed2f5de09c708e777e541fd30747f9e0f12fbc",
"extension": "c",
"filename": "trocaelem.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 237505370,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1480,
"license": "MIT",
"license_type": "permissive",
"path": "/trocaelem.c",
"provenance": "stackv2-0099.json.gz:2708",
"repo_name": "welyngton/Exercicios-Linguagem-C",
"revision_date": "2020-01-31T19:54:15",
"revision_id": "9d781a8499d74898e123935052ddb57b83b83929",
"snapshot_id": "3172f814f931bd05b7372a25b6a7ddbe706eb71c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/welyngton/Exercicios-Linguagem-C/9d781a8499d74898e123935052ddb57b83b83929/trocaelem.c",
"visit_date": "2020-12-26T12:12:27.003980"
} | stackv2 | #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
void print_matriz (int **m, int dim) {
int i, j;
puts("");
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++)
printf ("%3d ", m[i][j]); //imprime cada elemento da linha
printf ("\n"); //termina uma linha da matriz
}
}
int le_matriz (int **m) {
int i, j, dim, max, maxj, swap;
printf ("Entre com a dimensao da matriz quadrada: ");
scanf ("%d", &dim);
m = (int **) malloc (dim * sizeof (int*)); //aloca dinamicamente uma matriz de inteiros
for (i = 0; i<= dim; i++)
m[i] = (int *) malloc (dim * sizeof (int));
printf ("Entre com os elementos da matriz separados por espaco:\n");
for (i = 0; i < dim; i++) {
printf ("Linha [%2d]: ", i);
max = INT_MIN; //menor valor possivel de um inteiro
for (j = 0; j < dim; j++) {
scanf ("%d", &m[i][j]);
if (m[i][j] > max) { //calcula maior valor da linha
max = m[i][j]; //armazena o maior valor da linha em max
maxj = j; //armazena posicao do maior valor da linha em maxj
}
}
//troca o maior elemento da linha com o elemento da diagonal
swap = m[i][i];
m[i][i] = m[i][maxj];
m[i][maxj] = swap;
}
//system("clear"); //chama o sistema e limpa a tela do terminal
print_matriz(m,dim);
return(0); //retorna o ponteiro para a matriz de inteiros (nao funciona)
}
int main () {
int i, j, dim, max, maxj, swap;
int **m = NULL; //cria e inicializa uma matriz vazia
le_matriz(m);
return 0;
}
| 3.75 | 4 |
2024-11-18T22:23:05.368618+00:00 | 2019-12-01T06:22:25 | 6636f5bab7d10f4f3a4b3b2057e6a37d75d224a8 | {
"blob_id": "6636f5bab7d10f4f3a4b3b2057e6a37d75d224a8",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-01T06:22:25",
"content_id": "a6baff1d7d693a9f72195ea72dacaecbbb5aa0d2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f0ee972868e2899e42be0252fe4e8320f7237bd8",
"extension": "c",
"filename": "deh_thing.c",
"fork_events_count": 1,
"gha_created_at": "2022-11-20T13:08:07",
"gha_event_created_at": "2022-11-20T13:08:08",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 568412305,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3465,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/emulator/emul_doom/src/ap/doom/deh_thing.c",
"provenance": "stackv2-0099.json.gz:2837",
"repo_name": "chcbaram/oroca_boy3",
"revision_date": "2019-12-01T06:22:25",
"revision_id": "6947545baff0d73f15523abb222053c3e5c6ac18",
"snapshot_id": "b3d5f82e2233697cfc5d9532961de2b3649891e6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chcbaram/oroca_boy3/6947545baff0d73f15523abb222053c3e5c6ac18/emulator/emul_doom/src/ap/doom/deh_thing.c",
"visit_date": "2023-03-16T02:55:41.988393"
} | stackv2 | //
// Copyright(C) 2005-2014 Simon Howard
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//
// Parses "Thing" sections in dehacked files
//
#include <stdio.h>
#include <stdlib.h>
#include "doomtype.h"
#include "deh_defs.h"
#include "deh_main.h"
#include "deh_mapping.h"
#include "info.h"
DEH_BEGIN_MAPPING(thing_mapping, mobjinfo_t)
DEH_MAPPING("ID #", doomednum)
DEH_MAPPING("Initial frame", spawnstate)
DEH_MAPPING("Hit points", spawnhealth)
DEH_MAPPING("First moving frame", seestate)
DEH_MAPPING("Alert sound", seesound)
DEH_MAPPING("Reaction time", reactiontime)
DEH_MAPPING("Attack sound", attacksound)
DEH_MAPPING("Injury frame", painstate)
DEH_MAPPING("Pain chance", painchance)
DEH_MAPPING("Pain sound", painsound)
DEH_MAPPING("Close attack frame", meleestate)
DEH_MAPPING("Far attack frame", missilestate)
DEH_MAPPING("Death frame", deathstate)
DEH_MAPPING("Exploding frame", xdeathstate)
DEH_MAPPING("Death sound", deathsound)
DEH_MAPPING("Speed", speed)
DEH_MAPPING("Width", radius)
DEH_MAPPING("Height", height)
DEH_MAPPING("Mass", mass)
DEH_MAPPING("Missile damage", damage)
DEH_MAPPING("Action sound", activesound)
DEH_MAPPING("Bits", flags)
DEH_MAPPING("Respawn frame", raisestate)
DEH_END_MAPPING
static void *DEH_ThingStart(deh_context_t *context, char *line)
{
int thing_number = 0;
mobjinfo_t *mobj;
if (sscanf(line, "Thing %i", &thing_number) != 1)
{
DEH_Warning(context, "Parse error on section start");
return NULL;
}
// dehacked files are indexed from 1
--thing_number;
if (thing_number < 0 || thing_number >= NUMMOBJTYPES)
{
DEH_Warning(context, "Invalid thing number: %i", thing_number);
return NULL;
}
mobj = &mobjinfo[thing_number];
return mobj;
}
static void DEH_ThingParseLine(deh_context_t *context, char *line, void *tag)
{
mobjinfo_t *mobj;
char *variable_name, *value;
int ivalue;
if (tag == NULL)
return;
mobj = (mobjinfo_t *) tag;
// Parse the assignment
if (!DEH_ParseAssignment(line, &variable_name, &value))
{
// Failed to parse
DEH_Warning(context, "Failed to parse assignment");
return;
}
// printf("Set %s to %s for mobj\n", variable_name, value);
// all values are integers
ivalue = atoi(value);
// Set the field value
DEH_SetMapping(context, &thing_mapping, mobj, variable_name, ivalue);
}
static void DEH_ThingSHA1Sum(sha1_context_t *context)
{
int i;
for (i=0; i<NUMMOBJTYPES; ++i)
{
DEH_StructSHA1Sum(context, &thing_mapping, &mobjinfo[i]);
}
}
deh_section_t deh_section_thing =
{
"Thing",
NULL,
DEH_ThingStart,
DEH_ThingParseLine,
NULL,
DEH_ThingSHA1Sum,
};
| 2.25 | 2 |
2024-11-18T22:23:06.730902+00:00 | 2023-09-02T14:55:31 | fe59b3a58b0b6c0391d45b5a4fcc13c71cf26ff8 | {
"blob_id": "fe59b3a58b0b6c0391d45b5a4fcc13c71cf26ff8",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-02T14:55:31",
"content_id": "560c7293ee24db4689ded07af44c7aab8a2c0fe3",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "8838eb997879add5759b6dfb23f9a646464e53ca",
"extension": "c",
"filename": "lthread_sched_wait_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": 4274,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/tests/kernel/lthread/lthread_sched_wait_test.c",
"provenance": "stackv2-0099.json.gz:3741",
"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/lthread/lthread_sched_wait_test.c",
"visit_date": "2023-09-04T03:02:20.165042"
} | stackv2 | /**
* @file
* @brief
*
* @author Vita Loginova
* @date 12.08.2014
*/
#include <util/err.h>
#include <embox/test.h>
#include <kernel/sched.h>
#include <kernel/sched/waitq.h>
#include <kernel/sched/schedee_priority.h>
#include <kernel/lthread/lthread.h>
#include <kernel/lthread/lthread_sched_wait.h>
#include <kernel/thread.h>
#include <kernel/time/ktime.h>
#include <kernel/sched/sync/mutex.h>
#include <kernel/lthread/sync/mutex.h>
#include <kernel/thread/sync/mutex.h>
EMBOX_TEST_SUITE("sched_wait_*_lthread test");
struct lt_test {
struct lthread lt;
int timeout;
int res;
};
static int done = 0, ready = 0;
static int sched_wait_timeout_run(struct lthread *self) {
int res;
struct lt_test *lt_test = (struct lt_test *)self;
sched_wait_prepare_lthread(self, lt_test->timeout);
if ((res = sched_wait_timeout_lthread(self, NULL)) == -EAGAIN) {
return 0;
}
sched_wait_cleanup_lthread(self);
lt_test->res = res;
done = 1;
return 0;
}
TEST_CASE("sched_wait_timeout: timeout is exceeded") {
struct lt_test lt_test;
lt_test.timeout = 20;
done = 0;
lthread_init(&(lt_test.lt), sched_wait_timeout_run);
lthread_launch(&(lt_test.lt));
/* Spin, wait till lthread finished */
while(1) {
if(done == 1) break;
ksleep(lt_test.timeout);
}
test_assert_equal(done, 1);
test_assert_equal(lt_test.res, -ETIMEDOUT);
lthread_join(&(lt_test.lt));
}
TEST_CASE("sched_wait_timeout: wakeup before timeout is exceeded") {
struct lt_test lt_test;
lt_test.timeout = 200;
done = 0;
lthread_init(<_test.lt, sched_wait_timeout_run);
lthread_launch(<_test.lt);
lthread_launch(<_test.lt);
test_assert_equal(done, 1);
test_assert_equal(lt_test.res, 0);
lthread_join(<_test.lt);
}
TEST_CASE("sched_wait_timeout: SCHED_TIMEOUT_INFINITE") {
struct lt_test lt_test;
lt_test.timeout = SCHED_TIMEOUT_INFINITE;
done = 0;
lthread_init(<_test.lt, sched_wait_timeout_run);
lthread_launch(<_test.lt);
lthread_launch(<_test.lt);
ksleep(0);
test_assert_equal(done, 1);
test_assert_equal(lt_test.res, 0);
lthread_join(<_test.lt);
}
static int sched_wait_timeout_macro_run(struct lthread *self) {
struct lt_test *lt_test = (struct lt_test *)self;
lt_test->res = SCHED_WAIT_TIMEOUT_LTHREAD(self, ready, lt_test->timeout);
if (lt_test->res == -EAGAIN) {
return 0;
}
done = 1;
return 0;
}
TEST_CASE("SCHED_WAIT_TIMEOUT_LTHREAD: wakeup before timeout is exceeded") {
struct lt_test lt_test;
int wakeup_times = 5;
lt_test.timeout = 150;
done = 0;
ready = 0;
lthread_init(<_test.lt, sched_wait_timeout_macro_run);
/* Check for proceeding waiting in case the lthread is waken up before
the condition becomes true. */
while(!done && wakeup_times--) {
lthread_launch(<_test.lt);
ksleep(20);
test_assert_equal(lt_test.res, -EAGAIN);
}
ready = 1;
lthread_launch(<_test.lt);
ksleep(0);
test_assert_equal(done, 1);
test_assert_equal(lt_test.res, 0);
lthread_join(<_test.lt);
}
TEST_CASE("SCHED_WAIT_TIMEOUT_LTHREAD: timeout exceeded") {
struct lt_test lt_test;
int wakeup_times;
int sleep_period = 20;
lt_test.timeout = 150;
wakeup_times = lt_test.timeout/sleep_period;
done = 0;
ready = 0;
lthread_init(<_test.lt, sched_wait_timeout_macro_run);
/* Check for proceeding waiting in case the lthread is waken up before
the condition becomes true. */
while(!done && wakeup_times--) {
lthread_launch(<_test.lt);
ksleep(sleep_period);
}
/* Since sleep_period*wakeup_times covers timeout, the lthread is
supposed to finish its routine. */
test_assert_equal(done, 1);
test_assert_equal(lt_test.res, -ETIMEDOUT);
lthread_join(<_test.lt);
}
TEST_CASE("SCHED_WAIT_TIMEOUT_LTHREAD: SCHED_TIMEOUT_INFINITE") {
struct lt_test lt_test;
int wakeup_times = 5;
lt_test.timeout = SCHED_TIMEOUT_INFINITE;
done = 0;
ready = 0;
lthread_init(<_test.lt, sched_wait_timeout_macro_run);
/* Check for proceeding waiting in case the lthread is waken up before
the condition becomes true. */
while(wakeup_times--) {
lthread_launch(<_test.lt);
ksleep(0);
test_assert_equal(lt_test.res, -EAGAIN);
}
ready = 1;
lthread_launch(<_test.lt);
ksleep(0);
test_assert_equal(done, 1);
test_assert_equal(lt_test.res, 0);
lthread_join(<_test.lt);
}
| 2.609375 | 3 |
2024-11-18T22:23:06.802473+00:00 | 2023-08-12T08:24:27 | c442755c9463fd809080203f965bceceb5464c13 | {
"blob_id": "c442755c9463fd809080203f965bceceb5464c13",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-12T08:24:27",
"content_id": "f40d0172962529b8398f8d95d345d4a8202c9c1c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cbe8756c4068574f2f1cf8f0ce6f11632622eccb",
"extension": "c",
"filename": "strlen.c",
"fork_events_count": 24,
"gha_created_at": "2016-10-29T19:32:29",
"gha_event_created_at": "2022-06-06T18:26:23",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 72305253,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 254,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/compilers/pcc-e1kb/ipmce/tst/libtst/strlen.c",
"provenance": "stackv2-0099.json.gz:3870",
"repo_name": "sergev/vak-opensource",
"revision_date": "2023-08-12T08:24:27",
"revision_id": "a7e0fc4289cafc1a344d8a1bcbc5e26c8b03c6ff",
"snapshot_id": "78b063c6e139c6c8b57735780120c042a759ffdc",
"src_encoding": "UTF-8",
"star_events_count": 44,
"url": "https://raw.githubusercontent.com/sergev/vak-opensource/a7e0fc4289cafc1a344d8a1bcbc5e26c8b03c6ff/compilers/pcc-e1kb/ipmce/tst/libtst/strlen.c",
"visit_date": "2023-08-14T07:50:30.069410"
} | stackv2 | /*
* $Log: strlen.c,v $
* Revision 1.1 86/04/21 20:06:54 root
* Initial revision
*
*/
/*
* Returns the number of
* non-NULL bytes in string argument.
*/
strlen(s)
register char *s;
{
register n;
n = 0;
while (*s++)
n++;
return(n);
}
| 2.59375 | 3 |
2024-11-18T22:23:06.890182+00:00 | 2021-10-25T17:06:06 | 1051969f14ca3139f47d7c99b1011ce24b48759b | {
"blob_id": "1051969f14ca3139f47d7c99b1011ce24b48759b",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-25T17:06:06",
"content_id": "07a0561ac733a3b9b8995f1a46cc3a353d19c59d",
"detected_licenses": [
"NCSA",
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "6dd2d509d44ea035da9d2a9f6cc9797724c12484",
"extension": "c",
"filename": "Grid_ClearParticleMassFlaggingField.C",
"fork_events_count": 1,
"gha_created_at": "2019-12-17T05:50:12",
"gha_event_created_at": "2019-12-17T05:50:13",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 228542764,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1133,
"license": "NCSA,BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/enzo/Grid_ClearParticleMassFlaggingField.C",
"provenance": "stackv2-0099.json.gz:3998",
"repo_name": "appolloford/enzo-dev",
"revision_date": "2021-10-25T17:06:06",
"revision_id": "2b20d1c9ee5b9b4ee6706a73e32d2e4a8b7fc8f5",
"snapshot_id": "ea9ebc98036c6e5be0c98ebb903448a354cb4aaf",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/appolloford/enzo-dev/2b20d1c9ee5b9b4ee6706a73e32d2e4a8b7fc8f5/src/enzo/Grid_ClearParticleMassFlaggingField.C",
"visit_date": "2023-08-06T01:18:34.631354"
} | stackv2 | /***********************************************************************
/
/ GRID CLASS (CLEAR THE PARTICLE MASS FLAGGING FIELD)
/
/ written by: Greg Bryan
/ date: November, 1994
/ modified1: May, 2009 by John Wise: for particles
/
/ PURPOSE:
/
************************************************************************/
// Allocate and clear the particle mass flagging field.
#include <stdio.h>
#include "ErrorExceptions.h"
#include "macros_and_parameters.h"
#include "typedefs.h"
#include "global_data.h"
#include "Fluxes.h"
#include "GridList.h"
#include "ExternalBoundary.h"
#include "Grid.h"
void grid::ClearParticleMassFlaggingField()
{
/* error check */
if (ParticleMassFlaggingField != NULL) {
fprintf(stderr, "ClearParticleMassFlaggingField: Warning, field not deleted.\n");
delete [] ParticleMassFlaggingField;
}
/* compute size and allocate */
int i, dim, size = 1;
for (dim = 0; dim < GridRank; dim++)
size *= GridDimension[dim];
ParticleMassFlaggingField = new float[size];
/* Clear it */
for (i = 0; i < size; i++)
ParticleMassFlaggingField[i] = 0.0;
}
| 2.015625 | 2 |
2024-11-18T22:23:08.719545+00:00 | 2015-10-23T16:43:41 | 7bd40242a94f73dfa66fe34dfb0588ab283dc096 | {
"blob_id": "7bd40242a94f73dfa66fe34dfb0588ab283dc096",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-23T16:43:41",
"content_id": "96307ab8580ffc98ed60b29b8dd851f0e2c05a61",
"detected_licenses": [
"ISC"
],
"directory_id": "2dadd691bc751bf6028d825514a2a6ce555ca6c7",
"extension": "h",
"filename": "mb_common.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 200861315,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1372,
"license": "ISC",
"license_type": "permissive",
"path": "/modbus/include/mb_common.h",
"provenance": "stackv2-0099.json.gz:4514",
"repo_name": "ai22ai22/w7500_modbustcp",
"revision_date": "2015-10-23T16:43:41",
"revision_id": "dc9fef13efef16809fef59578ddb1ce1673054fc",
"snapshot_id": "c2dbb5f444f6decfb5ab896145f131829ac59b10",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ai22ai22/w7500_modbustcp/dc9fef13efef16809fef59578ddb1ce1673054fc/modbus/include/mb_common.h",
"visit_date": "2020-06-30T14:47:32.171463"
} | stackv2 | /**
* @file mb_common.h
*
* Common Modbus data structures and definitions
*
*/
#ifndef _MB_COMMON_H
#define _MB_COMMON_H
#include <stdint.h>
typedef enum {
MB_SUCCESS,
MB_ERR_ADDRESS
} mb_retval_t;
typedef union {
uint16_t u16;
uint8_t u8[2];
} mb_word_t;
typedef struct {
uint8_t function_code;
uint8_t data[252];
} mb_pdu_t;
typedef struct {
mb_word_t transaction_id;
mb_word_t protocol_id;
mb_word_t length;
uint8_t unit_id;
mb_pdu_t pdu;
} mb_tcp_adu_t;
/* Class 0 commands */
#define MB_FC_READ_HOLDING_REGISTERS 0x03
#define MB_FC_WRITE_HOLDING_REGISTERS 0x10
#define MB_FC_EXCEPTION_READ_HOLDING_REGISTERS 0x83
#define MB_FC_EXCEPTION_WRITE_HOLDING_REGISTERS 0x90
/* Class 1 commands */
#define MB_FC_READ_COILS 0x01
#define MB_FC_WRITE_COIL 0x05
#define MB_FC_READ_INPUT_DISCRETES 0x02
#define MB_FC_READ_INPUT_REGISTERS 0x04
#define MB_FC_WRITE_SINGLE_HOLDING_REGISTER 0x06
#define MB_FC_EXCEPTION_WRITE_SINGLE_HOLDING_REGISTER 0x86
#define MB_FC_EXCEPTION_WRITE_COIL 0x85
#define MB_FC_EXCEPTION_READ_COILS 0x81
#define MB_FC_EXCEPTION_READ_INPUT_DISCRETES 0x82
#define MB_FC_EXCEPTION_READ_INPUT_REGISTERS 0x84
/* Exception codes */
#define MB_EXCEPTION_ILLEGAL_FUNCTION 0x01
#define MB_EXCEPTION_ILLEGAL_DATA_ADDRESS 0x02
#define MB_EXCEPTION_ILLEGAL_DATA_VALUE 0x03
#endif /* _MB_COMMON_H */
| 2.15625 | 2 |
2024-11-18T22:23:08.783881+00:00 | 2017-04-29T06:17:24 | 5f46a0cb233da1a0a103aded1f8cd4a3eb83d04c | {
"blob_id": "5f46a0cb233da1a0a103aded1f8cd4a3eb83d04c",
"branch_name": "refs/heads/lab-general",
"committer_date": "2017-04-29T06:17:24",
"content_id": "ba80ef613e3ca8747dbc98de12311aba637a3f98",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "b725ba18b99398ce8459b8877691135e0cdf4d51",
"extension": "c",
"filename": "kss_emu.c",
"fork_events_count": 16,
"gha_created_at": "2011-04-04T06:19:32",
"gha_event_created_at": "2019-03-21T03:45:53",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 1565842,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 19914,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/lib/rbcodec/codecs/libgme/kss_emu.c",
"provenance": "stackv2-0099.json.gz:4642",
"repo_name": "Rockbox-Chinese-Community/Rockbox-RCC",
"revision_date": "2017-04-29T06:17:24",
"revision_id": "a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2",
"snapshot_id": "8d3069271d14144281a40694c60128cac852cd3a",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/Rockbox-Chinese-Community/Rockbox-RCC/a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2/lib/rbcodec/codecs/libgme/kss_emu.c",
"visit_date": "2020-12-01T22:59:14.427025"
} | stackv2 | // Game_Music_Emu 0.6-pre. http://www.slack.net/~ant/
#include "kss_emu.h"
#include "blargg_endian.h"
/* Copyright (C) 2006 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details. You should have received a copy of the GNU Lesser General Public
License along with this module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
#include "blargg_source.h"
int const clock_rate = 3579545;
const char gme_wrong_file_type [] = "Wrong file type for this emulator";
static void clear_track_vars( struct Kss_Emu* this )
{
this->current_track = -1;
track_stop( &this->track_filter );
}
static blargg_err_t init_opl_apu( enum opl_type_t type, struct Opl_Apu* out )
{
blip_time_t const period = 72;
int const rate = clock_rate / period;
return Opl_init( out, rate * period, rate, period, type );
}
void Kss_init( struct Kss_Emu* this )
{
this->sample_rate = 0;
this->mute_mask_ = 0;
this->tempo = (int)(FP_ONE_TEMPO);
this->gain = (int)FP_ONE_GAIN;
this->chip_flags = 0;
// defaults
this->tfilter = *track_get_setup( &this->track_filter );
this->tfilter.max_initial = 2;
this->tfilter.lookahead = 6;
this->track_filter.silence_ignored_ = false;
memset( this->unmapped_read, 0xFF, sizeof this->unmapped_read );
// Init all stuff
Buffer_init( &this->stereo_buf );
Z80_init( &this->cpu );
Rom_init( &this->rom, page_size );
// Initialize all apus just once (?)
Sms_apu_init( &this->sms.psg);
Ay_apu_init( &this->msx.psg );
Scc_init( &this->msx.scc );
#ifndef KSS_EMU_NO_FMOPL
init_opl_apu( type_smsfmunit, &this->sms.fm );
init_opl_apu( type_msxmusic, &this->msx.music );
init_opl_apu( type_msxaudio, &this->msx.audio );
#endif
this->voice_count = 0;
this->voice_types = 0;
clear_track_vars( this );
}
// Track info
static blargg_err_t check_kss_header( void const* header )
{
if ( memcmp( header, "KSCC", 4 ) && memcmp( header, "KSSX", 4 ) )
return gme_wrong_file_type;
return 0;
}
// Setup
static void update_gain_( struct Kss_Emu* this )
{
int g = this->gain;
if ( msx_music_enabled( this ) || msx_audio_enabled( this )
|| sms_fm_enabled( this ) )
{
g = (g*3) / 4; //g *= 0.75;
}
else
{
if ( this->scc_accessed )
g = (g*6) / 5; //g *= 1.2;
}
if ( sms_psg_enabled( this ) ) Sms_apu_volume( &this->sms.psg, g );
if ( sms_fm_enabled( this ) ) Opl_volume( &this->sms.fm, g );
if ( msx_psg_enabled( this ) ) Ay_apu_volume( &this->msx.psg, g );
if ( msx_scc_enabled( this ) ) Scc_volume( &this->msx.scc, g );
if ( msx_music_enabled( this ) ) Opl_volume( &this->msx.music, g );
if ( msx_audio_enabled( this ) ) Opl_volume( &this->msx.audio, g );
}
static void update_gain( struct Kss_Emu* this )
{
if ( this->scc_accessed )
{
/* dprintf( "SCC accessed\n" ); */
update_gain_( this );
}
}
blargg_err_t Kss_load_mem( struct Kss_Emu* this, const void* data, long size )
{
/* warning( core.warning() ); */
memset( &this->header, 0, sizeof this->header );
assert( offsetof (header_t,msx_audio_vol) == header_size - 1 );
RETURN_ERR( Rom_load( &this->rom, data, size, header_base_size, &this->header, 0 ) );
RETURN_ERR( check_kss_header( this->header.tag ) );
this->chip_flags = 0;
this->header.last_track [0] = 255;
if ( this->header.tag [3] == 'C' )
{
if ( this->header.extra_header )
{
this->header.extra_header = 0;
/* warning( "Unknown data in header" ); */
}
if ( this->header.device_flags & ~0x0F )
{
this->header.device_flags &= 0x0F;
/* warning( "Unknown data in header" ); */
}
}
else if ( this->header.extra_header )
{
if ( this->header.extra_header != header_ext_size )
{
this->header.extra_header = 0;
/* warning( "Invalid extra_header_size" ); */
}
else
{
memcpy( this->header.data_size, this->rom.file_data, header_ext_size );
}
}
#ifndef NDEBUG
{
int ram_mode = this->header.device_flags & 0x84; // MSX
if ( this->header.device_flags & 0x02 ) // SMS
ram_mode = (this->header.device_flags & 0x88);
if ( ram_mode )
blargg_dprintf_( "RAM not supported\n" ); // TODO: support
}
#endif
this->track_count = get_le16( this->header.last_track ) + 1;
this->m3u.size = 0;
this->scc_enabled = false;
if ( this->header.device_flags & 0x02 ) // Sega Master System
{
int const osc_count = sms_osc_count + opl_osc_count;
// sms.psg
this->voice_count = sms_osc_count;
static int const types [sms_osc_count + opl_osc_count] = {
wave_type+1, wave_type+3, wave_type+2, mixed_type+1, wave_type+0
};
this->voice_types = types;
this->chip_flags |= sms_psg_flag;
// sms.fm
if ( this->header.device_flags & 0x01 )
{
this->voice_count = osc_count;
this->chip_flags |= sms_fm_flag;
}
}
else // MSX
{
int const osc_count = ay_osc_count + opl_osc_count;
// msx.psg
this->voice_count = ay_osc_count;
static int const types [ay_osc_count + opl_osc_count] = {
wave_type+1, wave_type+3, wave_type+2, wave_type+0
};
this->voice_types = types;
this->chip_flags |= msx_psg_flag;
/* if ( this->header.device_flags & 0x10 )
warning( "MSX stereo not supported" ); */
// msx.music
if ( this->header.device_flags & 0x01 )
{
this->voice_count = osc_count;
this->chip_flags |= msx_music_flag;
}
#ifndef KSS_EMU_NO_FMOPL
// msx.audio
if ( this->header.device_flags & 0x08 )
{
this->voice_count = osc_count;
this->chip_flags |= msx_audio_flag;
}
#endif
if ( !(this->header.device_flags & 0x80) )
{
if ( !(this->header.device_flags & 0x84) )
this->scc_enabled = scc_enabled_true;
// msx.scc
this->chip_flags |= msx_scc_flag;
this->voice_count = ay_osc_count + scc_osc_count;
static int const types [ay_osc_count + scc_osc_count] = {
wave_type+1, wave_type+3, wave_type+2,
wave_type+0, wave_type+4, wave_type+5, wave_type+6, wave_type+7,
};
this->voice_types = types;
}
}
this->tfilter.lookahead = 6;
if ( sms_fm_enabled( this ) || msx_music_enabled( this ) || msx_audio_enabled( this ) )
{
if ( !Opl_supported() )
; /* warning( "FM sound not supported" ); */
else
this->tfilter.lookahead = 3; // Opl_Apu is really slow
}
this->clock_rate_ = clock_rate;
Buffer_clock_rate( &this->stereo_buf, clock_rate );
RETURN_ERR( Buffer_set_channel_count( &this->stereo_buf, this->voice_count, this->voice_types ) );
this->buf_changed_count = Buffer_channels_changed_count( &this->stereo_buf );
Sound_set_tempo( this, this->tempo );
Sound_mute_voices( this, this->mute_mask_ );
return 0;
}
static void set_voice( struct Kss_Emu* this, int i, struct Blip_Buffer* center, struct Blip_Buffer* left, struct Blip_Buffer* right )
{
if ( sms_psg_enabled( this ) ) // Sega Master System
{
i -= sms_osc_count;
if ( i < 0 )
{
Sms_apu_set_output( &this->sms.psg, i + sms_osc_count, center, left, right );
return;
}
if ( sms_fm_enabled( this ) && i < opl_osc_count )
Opl_set_output( &this->sms.fm, center );
}
else if ( msx_psg_enabled( this ) ) // MSX
{
i -= ay_osc_count;
if ( i < 0 )
{
Ay_apu_set_output( &this->msx.psg, i + ay_osc_count, center );
return;
}
if ( msx_scc_enabled( this ) && i < scc_osc_count ) Scc_set_output( &this->msx.scc, i, center );
if ( msx_music_enabled( this ) && i < opl_osc_count ) Opl_set_output( &this->msx.music, center );
if ( msx_audio_enabled( this ) && i < opl_osc_count ) Opl_set_output( &this->msx.audio, center );
}
}
// Emulation
void jsr( struct Kss_Emu* this, byte const addr [] )
{
this->ram [--this->cpu.r.sp] = idle_addr >> 8;
this->ram [--this->cpu.r.sp] = idle_addr & 0xFF;
this->cpu.r.pc = get_le16( addr );
}
static void set_bank( struct Kss_Emu* this, int logical, int physical )
{
int const bank_size = (16 * 1024L) >> (this->header.bank_mode >> 7 & 1);
int addr = 0x8000;
if ( logical && bank_size == 8 * 1024 )
addr = 0xA000;
physical -= this->header.first_bank;
if ( (unsigned) physical >= (unsigned) this->bank_count )
{
byte* data = this->ram + addr;
Z80_map_mem( &this->cpu, addr, bank_size, data, data );
}
else
{
int offset, phys = physical * bank_size;
for ( offset = 0; offset < bank_size; offset += page_size )
Z80_map_mem( &this->cpu, addr + offset, page_size,
this->unmapped_write, Rom_at_addr( &this->rom, phys + offset ) );
}
}
void cpu_write( struct Kss_Emu* this, addr_t addr, int data )
{
*Z80_write( &this->cpu, addr ) = data;
if ( (addr & this->scc_enabled) == 0x8000 ) {
// TODO: SCC+ support
data &= 0xFF;
switch ( addr )
{
case 0x9000:
set_bank( this, 0, data );
return;
case 0xB000:
set_bank( this, 1, data );
return;
case 0xBFFE: // selects between mapping areas (we just always enable both)
if ( data == 0 || data == 0x20 )
return;
}
int scc_addr = (addr & 0xDFFF) - 0x9800;
if ( msx_scc_enabled( this ) && (unsigned) scc_addr < 0xB0 )
{
this->scc_accessed = true;
//if ( (unsigned) (scc_addr - 0x90) < 0x10 )
// scc_addr -= 0x10; // 0x90-0x9F mirrors to 0x80-0x8F
if ( scc_addr < scc_reg_count )
Scc_write( &this->msx.scc, Z80_time( &this->cpu ), addr, data );
return;
}
}
}
void cpu_out( struct Kss_Emu* this, kss_time_t time, kss_addr_t addr, int data )
{
data &= 0xFF;
switch ( addr & 0xFF )
{
case 0xA0:
if ( msx_psg_enabled( this ) )
Ay_apu_write_addr( &this->msx.psg, data );
return;
case 0xA1:
if ( msx_psg_enabled( this ) )
Ay_apu_write_data( &this->msx.psg, time, data );
return;
case 0x06:
if ( sms_psg_enabled( this ) && (this->header.device_flags & 0x04) )
{
Sms_apu_write_ggstereo( &this->sms.psg, time, data );
return;
}
break;
case 0x7E:
case 0x7F:
if ( sms_psg_enabled( this ) )
{
Sms_apu_write_data( &this->sms.psg, time, data );
return;
}
break;
#define OPL_WRITE_HANDLER( base, name, opl )\
case base : if ( name##_enabled( this ) ) { Opl_write_addr( opl, data ); return; } break;\
case base+1: if ( name##_enabled( this ) ) { Opl_write_data( opl, time, data ); return; } break;
OPL_WRITE_HANDLER( 0x7C, msx_music, &this->msx.music )
OPL_WRITE_HANDLER( 0xC0, msx_audio, &this->msx.audio )
OPL_WRITE_HANDLER( 0xF0, sms_fm, &this->sms.fm )
case 0xFE:
set_bank( this, 0, data );
return;
#ifndef NDEBUG
case 0xA8: // PPI
return;
#endif
}
/* cpu_out( time, addr, data ); */
}
int cpu_in( struct Kss_Emu* this, kss_time_t time, kss_addr_t addr )
{
switch ( addr & 0xFF )
{
case 0xC0:
case 0xC1:
if ( msx_audio_enabled( this ) )
return Opl_read( &this->msx.audio, time, addr & 1 );
break;
case 0xA2:
if ( msx_psg_enabled( this ) )
return Ay_apu_read( &this->msx.psg );
break;
#ifndef NDEBUG
case 0xA8: // PPI
return 0;
#endif
}
/* return cpu_in( time, addr ); */
return 0xFF;
}
static blargg_err_t run_clocks( struct Kss_Emu* this, blip_time_t* duration_ )
{
blip_time_t duration = *duration_;
RETURN_ERR( end_frame( this, duration ) );
if ( sms_psg_enabled( this ) ) Sms_apu_end_frame( &this->sms.psg, duration );
if ( sms_fm_enabled( this ) ) Opl_end_frame( &this->sms.fm, duration );
if ( msx_psg_enabled( this ) ) Ay_apu_end_frame( &this->msx.psg, duration );
if ( msx_scc_enabled( this ) ) Scc_end_frame( &this->msx.scc, duration );
if ( msx_music_enabled( this ) ) Opl_end_frame( &this->msx.music, duration );
if ( msx_audio_enabled( this ) ) Opl_end_frame( &this->msx.audio, duration );
return 0;
}
blargg_err_t end_frame( struct Kss_Emu* this, kss_time_t end )
{
while ( Z80_time( &this->cpu ) < end )
{
kss_time_t next = min( end, this->next_play );
run_cpu( this, next );
if ( this->cpu.r.pc == idle_addr )
Z80_set_time( &this->cpu, next );
if ( Z80_time( &this->cpu ) >= this->next_play )
{
this->next_play += this->play_period;
if ( this->cpu.r.pc == idle_addr )
{
if ( !this->gain_updated )
{
this->gain_updated = true;
update_gain( this );
}
jsr( this, this->header.play_addr );
}
}
}
this->next_play -= end;
check( this->next_play >= 0 );
Z80_adjust_time( &this->cpu, -end );
return 0;
}
// MUSIC
blargg_err_t Kss_set_sample_rate( struct Kss_Emu* this, int rate )
{
require( !this->sample_rate ); // sample rate can't be changed once set
RETURN_ERR( Buffer_set_sample_rate( &this->stereo_buf, rate, 1000 / 20 ) );
// Set bass frequency
Buffer_bass_freq( &this->stereo_buf, 180 );
this->sample_rate = rate;
RETURN_ERR( track_init( &this->track_filter, this ) );
this->tfilter.max_silence = 6 * stereo * this->sample_rate;
return 0;
}
void Sound_mute_voice( struct Kss_Emu* this, int index, bool mute )
{
require( (unsigned) index < (unsigned) this->voice_count );
int bit = 1 << index;
int mask = this->mute_mask_ | bit;
if ( !mute )
mask ^= bit;
Sound_mute_voices( this, mask );
}
void Sound_mute_voices( struct Kss_Emu* this, int mask )
{
require( this->sample_rate ); // sample rate must be set first
this->mute_mask_ = mask;
int i;
for ( i = this->voice_count; i--; )
{
if ( mask & (1 << i) )
{
set_voice( this, i, 0, 0, 0 );
}
else
{
struct channel_t ch = Buffer_channel( &this->stereo_buf, i );
assert( (ch.center && ch.left && ch.right) ||
(!ch.center && !ch.left && !ch.right) ); // all or nothing
set_voice( this, i, ch.center, ch.left, ch.right );
}
}
}
void Sound_set_tempo( struct Kss_Emu* this, int t )
{
require( this->sample_rate ); // sample rate must be set first
int const min = (int)(FP_ONE_TEMPO*0.02);
int const max = (int)(FP_ONE_TEMPO*4.00);
if ( t < min ) t = min;
if ( t > max ) t = max;
this->tempo = t;
blip_time_t period =
(this->header.device_flags & 0x40 ? clock_rate / 50 : clock_rate / 60);
this->play_period = (blip_time_t) ((period * FP_ONE_TEMPO) / t);
}
blargg_err_t Kss_start_track( struct Kss_Emu* this, int track )
{
clear_track_vars( this );
// Remap track if playlist available
if ( this->m3u.size > 0 ) {
struct entry_t* e = &this->m3u.entries[track];
track = e->track;
}
this->current_track = track;
Buffer_clear( &this->stereo_buf );
if ( sms_psg_enabled( this ) ) Sms_apu_reset( &this->sms.psg, 0, 0 );
if ( sms_fm_enabled( this ) ) Opl_reset( &this->sms.fm );
if ( msx_psg_enabled( this ) ) Ay_apu_reset( &this->msx.psg );
if ( msx_scc_enabled( this ) ) Scc_reset( &this->msx.scc );
if ( msx_music_enabled( this ) ) Opl_reset( &this->msx.music );
if ( msx_audio_enabled( this ) ) Opl_reset( &this->msx.audio );
this->scc_accessed = false;
update_gain_( this );
memset( this->ram, 0xC9, 0x4000 );
memset( this->ram + 0x4000, 0, sizeof this->ram - 0x4000 );
// copy driver code to lo RAM
static byte const bios [] = {
0xD3, 0xA0, 0xF5, 0x7B, 0xD3, 0xA1, 0xF1, 0xC9, // $0001: WRTPSG
0xD3, 0xA0, 0xDB, 0xA2, 0xC9 // $0009: RDPSG
};
static byte const vectors [] = {
0xC3, 0x01, 0x00, // $0093: WRTPSG vector
0xC3, 0x09, 0x00, // $0096: RDPSG vector
};
memcpy( this->ram + 0x01, bios, sizeof bios );
memcpy( this->ram + 0x93, vectors, sizeof vectors );
// copy non-banked data into RAM
int load_addr = get_le16( this->header.load_addr );
int orig_load_size = get_le16( this->header.load_size );
int load_size = min( orig_load_size, (int) this->rom.file_size );
load_size = min( load_size, (int) mem_size - load_addr );
/* if ( load_size != orig_load_size )
warning( "Excessive data size" ); */
memcpy( this->ram + load_addr, this->rom.file_data + this->header.extra_header, load_size );
Rom_set_addr( &this->rom, -load_size - this->header.extra_header );
// check available bank data
int const bank_size = (16 * 1024L) >> (this->header.bank_mode >> 7 & 1);
int max_banks = (this->rom.file_size - load_size + bank_size - 1) / bank_size;
this->bank_count = this->header.bank_mode & 0x7F;
if ( this->bank_count > max_banks )
{
this->bank_count = max_banks;
/* warning( "Bank data missing" ); */
}
//dprintf( "load_size : $%X\n", load_size );
//dprintf( "bank_size : $%X\n", bank_size );
//dprintf( "bank_count: %d (%d claimed)\n", bank_count, this->header.bank_mode & 0x7F );
this->ram [idle_addr] = 0xFF;
Z80_reset( &this->cpu, this->unmapped_write, this->unmapped_read );
Z80_map_mem( &this->cpu, 0, mem_size, this->ram, this->ram );
this->cpu.r.sp = 0xF380;
this->cpu.r.b.a = track;
this->cpu.r.b.h = 0;
this->next_play = this->play_period;
this->gain_updated = false;
jsr( this, this->header.init_addr );
// convert filter times to samples
struct setup_t s = this->tfilter;
s.max_initial *= this->sample_rate * stereo;
#ifdef GME_DISABLE_SILENCE_LOOKAHEAD
s.lookahead = 1;
#endif
track_setup( &this->track_filter, &s );
return track_start( &this->track_filter );
}
// Tell/Seek
static int msec_to_samples( int msec, int sample_rate )
{
int sec = msec / 1000;
msec -= sec * 1000;
return (sec * sample_rate + msec * sample_rate / 1000) * stereo;
}
int Track_tell( struct Kss_Emu* this )
{
int rate = this->sample_rate * stereo;
int sec = track_sample_count( &this->track_filter ) / rate;
return sec * 1000 + (track_sample_count( &this->track_filter ) - sec * rate) * 1000 / rate;
}
blargg_err_t Track_seek( struct Kss_Emu* this, int msec )
{
int time = msec_to_samples( msec, this->sample_rate );
if ( time < track_sample_count( &this->track_filter ) )
RETURN_ERR( Kss_start_track( this, this->current_track ) );
return Track_skip( this, time - track_sample_count( &this->track_filter ) );
}
blargg_err_t skip_( void *emu, int count )
{
struct Kss_Emu* this = (struct Kss_Emu*) emu;
// for long skip, mute sound
const int threshold = 32768;
if ( count > threshold )
{
int saved_mute = this->mute_mask_;
Sound_mute_voices( this, ~0 );
int n = count - threshold/2;
n &= ~(2048-1); // round to multiple of 2048
count -= n;
RETURN_ERR( skippy_( &this->track_filter, n ) );
Sound_mute_voices( this, saved_mute );
}
return skippy_( &this->track_filter, count );
}
blargg_err_t Track_skip( struct Kss_Emu* this, int count )
{
require( this->current_track >= 0 ); // start_track() must have been called already
return track_skip( &this->track_filter, count );
}
void Track_set_fade( struct Kss_Emu* this, int start_msec, int length_msec )
{
track_set_fade( &this->track_filter, msec_to_samples( start_msec, this->sample_rate ),
length_msec * this->sample_rate / (1000 / stereo) );
}
blargg_err_t Kss_play( struct Kss_Emu* this, int out_count, sample_t* out )
{
require( this->current_track >= 0 );
require( out_count % stereo == 0 );
return track_play( &this->track_filter, out_count, out );
}
blargg_err_t play_( void *emu, int count, sample_t* out )
{
struct Kss_Emu* this = (struct Kss_Emu*) emu;
int remain = count;
while ( remain )
{
Buffer_disable_immediate_removal( &this->stereo_buf );
remain -= Buffer_read_samples( &this->stereo_buf, &out [count - remain], remain );
if ( remain )
{
if ( this->buf_changed_count != Buffer_channels_changed_count( &this->stereo_buf ) )
{
this->buf_changed_count = Buffer_channels_changed_count( &this->stereo_buf );
// Remute voices
Sound_mute_voices( this, this->mute_mask_ );
}
int msec = Buffer_length( &this->stereo_buf );
blip_time_t clocks_emulated = msec * this->clock_rate_ / 1000 - 100;
RETURN_ERR( run_clocks( this, &clocks_emulated ) );
assert( clocks_emulated );
Buffer_end_frame( &this->stereo_buf, clocks_emulated );
}
}
return 0;
}
| 2 | 2 |
2024-11-18T22:23:09.121238+00:00 | 2021-08-23T04:22:09 | 0097b0b1116fe9b370b0459a82615ca9893ee693 | {
"blob_id": "0097b0b1116fe9b370b0459a82615ca9893ee693",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-23T04:22:09",
"content_id": "1c1b0628ec861d071c0498b3545f5c7d7d548ff5",
"detected_licenses": [
"Unlicense"
],
"directory_id": "d68034d0a36c59d25fc81a9bf4647c2db7194cb3",
"extension": "h",
"filename": "float4.func.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 141048688,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11704,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/submodules/functions/float4.func.h",
"provenance": "stackv2-0099.json.gz:4906",
"repo_name": "maihd/hlslmath",
"revision_date": "2021-08-23T04:22:09",
"revision_id": "63dfc2b2de8d2e47e87282d7006b44a6b37401be",
"snapshot_id": "b8693b87aed1ee902dcbbe85d6bd16fe6d2b800b",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/maihd/hlslmath/63dfc2b2de8d2e47e87282d7006b44a6b37401be/src/submodules/functions/float4.func.h",
"visit_date": "2021-09-02T12:41:09.985665"
} | stackv2 | /* Computes sign of 'x'
*/
inline int4 sign(const float4& v)
{
return int4(sign(v.x),
sign(v.y),
sign(v.z),
sign(v.w));
}
/* Computes absolute value
*/
inline float4 abs(const float4& v)
{
return float4(abs(v.x),
abs(v.y),
abs(v.z),
abs(v.w));
}
/* Computes cosine
*/
inline float4 cos(const float4& v)
{
return float4(cos(v.x),
cos(v.y),
cos(v.z),
cos(v.w));
}
/* Computes sine
*/
inline float4 sin(const float4& v)
{
return float4(sin(v.x),
sin(v.y),
sin(v.z),
sin(v.w));
}
/* Computes tangent
*/
inline float4 tan(const float4& v)
{
return float4(tan(v.x),
tan(v.y),
tan(v.z),
tan(v.w));
}
/* Computes hyperbolic cosine
*/
inline float4 cosh(const float4& v)
{
return float4(cosh(v.x),
cosh(v.y),
cosh(v.z),
cosh(v.w));
}
/* Computes hyperbolic sine
*/
inline float4 sinh(const float4& v)
{
return float4(sinh(v.x),
sinh(v.y),
sinh(v.z),
sinh(v.w));
}
/* Computes hyperbolic tangent
*/
inline float4 tanh(const float4& v)
{
return float4(tanh(v.x),
tanh(v.y),
tanh(v.z),
tanh(v.w));
}
/* Computes inverse cosine
*/
inline float4 acos(const float4& v)
{
return float4(acos(v.x),
acos(v.y),
acos(v.z),
acos(v.w));
}
/* Computes inverse sine
*/
inline float4 asin(const float4& v)
{
return float4(asin(v.x),
asin(v.y),
asin(v.z),
asin(v.w));
}
/* Computes inverse tangent
*/
inline float4 atan(const float4& v)
{
return float4(atan(v.x),
atan(v.y),
atan(v.z),
atan(v.w));
}
/* Computes inverse tangent with 2 args
*/
inline float4 atan2(const float4& a, const float4& b)
{
return float4(atan2(a.x, b.x),
atan2(a.y, b.y),
atan2(a.z, b.z),
atan2(a.w, b.w));
}
/* Computes Euler number raised to the power 'x'
*/
inline float4 exp(const float4& v)
{
return float4(exp(v.x),
exp(v.y),
exp(v.z),
exp(v.w));
}
/* Computes 2 raised to the power 'x'
*/
inline float4 exp2(const float4& v)
{
return float4(exp2(v.x),
exp2(v.y),
exp2(v.z),
exp2(v.w));
}
/* Computes the base Euler number logarithm
*/
inline float4 log(const float4& v)
{
return float4(log(v.x),
log(v.y),
log(v.z),
log(v.w));
}
/* Computes the base 2 logarithm
*/
inline float4 log2(const float4& v)
{
return float4(log2(v.x),
log2(v.y),
log2(v.z),
log2(v.w) );
}
/* Computes the base 10 logarithm
*/
inline float4 log10(const float4& v)
{
return float4(log10(v.x),
log10(v.y),
log10(v.z),
log10(v.w));
}
/* Computes the value of base raised to the power exponent
*/
inline float4 pow(const float4& a, const float4& b)
{
return float4(pow(a.x, b.x),
pow(a.y, b.y),
pow(a.z, b.z),
pow(a.w, b.w));
}
/* Get the fractal part of floating point
*/
inline float4 frac(const float4& v)
{
return float4(frac(v.x),
frac(v.y),
frac(v.z),
frac(v.w));
}
/* Computes the floating-point remainder of the division operation x/y
*/
inline float4 fmod(const float4& a, const float4& b)
{
return float4(fmod(a.x, b.x),
fmod(a.y, b.y),
fmod(a.z, b.z),
fmod(a.w, b.w));
}
/* Computes the smallest integer value not less than 'x'
*/
inline float4 ceil(const float4& v)
{
return float4(ceil(v.x),
ceil(v.y),
ceil(v.z),
ceil(v.w));
}
/* Computes the largest integer value not greater than 'x'
*/
inline float4 floor(const float4& v)
{
return float4(floor(v.x),
floor(v.y),
floor(v.z),
floor(v.w));
}
/* Computes the nearest integer value
*/
inline float4 round(const float4& v)
{
return float4(round(v.x),
round(v.y),
round(v.z),
round(v.w));
}
/* Computes the nearest integer not greater in magnitude than 'x'
*/
inline float4 trunc(const float4& v)
{
return float4(trunc(v.x),
trunc(v.y),
trunc(v.z),
trunc(v.w));
}
/* Get the smaller value
*/
inline float4 min(const float4& a, const float4& b)
{
return float4(min(a.x, b.x),
min(a.y, b.y),
min(a.z, b.z),
min(a.w, b.w));
}
/* Get the larger value
*/
inline float4 max(const float4& a, const float4& b)
{
return float4(max(a.x, b.x),
max(a.y, b.y),
max(a.z, b.z),
max(a.w, b.w));
}
/* Clamps the 'x' value to the [min, max].
*/
inline float4 clamp(const float4& v, const float4& min, const float4& max)
{
return float4(clamp(v.x, min.x, max.x),
clamp(v.y, min.y, max.y),
clamp(v.z, min.z, max.z),
clamp(v.w, min.w, max.w));
}
/* Clamps the specified value within the range of 0 to 1
*/
inline float4 saturate(const float4& v)
{
return float4(saturate(v.x),
saturate(v.y),
saturate(v.z),
saturate(v.w));
}
/* Compares two values, returning 0 or 1 based on which value is greater.
*/
inline float4 step(const float4& a, const float4& b)
{
return float4(step(a.x, b.x),
step(a.y, b.y),
step(a.z, b.z),
step(a.w, b.w));
}
/* Performs a linear interpolation.
*/
inline float4 lerp(const float4& a, const float4& b, const float4& t)
{
return float4(lerp(a.x, b.x, t.x),
lerp(a.y, b.y, t.y),
lerp(a.z, b.z, t.z),
lerp(a.w, b.w, t.w));
}
/* Performs a linear interpolation.
*/
inline float4 lerp(const float4& a, const float4& b, float t)
{
return float4(lerp(a.x, b.x, t),
lerp(a.y, b.y, t),
lerp(a.z, b.z, t),
lerp(a.w, b.w, t));
}
/* Compute a smooth Hermite interpolation
*/
inline float4 smoothstep(const float4& a, const float4& b, const float4& t)
{
return float4(smoothstep(a.x, b.x, t.x),
smoothstep(a.y, b.y, t.y),
smoothstep(a.z, b.z, t.z),
smoothstep(a.w, b.w, t.w));
}
/* Computes square root of 'x'.
*/
inline float4 sqrt(const float4& v)
{
return float4(sqrt(v.x),
sqrt(v.y),
sqrt(v.z),
sqrt(v.w));
}
/* Computes inverse square root of 'x'.
*/
inline float4 rsqrt(const float4& v)
{
return float4(rsqrt(v.x),
rsqrt(v.y),
rsqrt(v.z),
rsqrt(v.w));
}
/* Computes fast inverse square root of 'x'.
*/
inline float4 fsqrt(const float4& v)
{
return float4(fsqrt(v.x),
fsqrt(v.y),
fsqrt(v.z),
fsqrt(v.w));
}
/* Computes fast inverse square root of 'x'.
*/
inline float4 frsqrt(const float4& v)
{
return float4(frsqrt(v.x),
frsqrt(v.y),
frsqrt(v.z),
frsqrt(v.w));
}
//
// @region: Graphics functions
//
/* Compute dot product of two vectors
*/
inline float dot(const float4& a, const float4& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
/* Compute squared length of vector
*/
inline float lensqr(const float4& v)
{
return dot(v, v);
}
/* Compute length of vector
*/
inline float length(const float4& v)
{
return sqrt(lensqr(v));
}
/* Compute distance from 'a' to b
*/
inline float distance(const float4& a, const float4& b)
{
return length(a - b);
}
/* Compute squared distance from 'a' to b
*/
inline float distsqr(const float4& a, const float4& b)
{
return lensqr(a - b);
}
/* Compute normalized vector
*/
inline float4 normalize(const float4& v)
{
const float lsqr = lensqr(v);
if (lsqr > 0.0f)
{
const float f = rsqrt(lsqr);
return float4(v.x * f, v.y * f, v.z * f, v.w * f);
}
else
{
return v;
}
}
/* Compute reflection vector
*/
inline float4 reflect(const float4& v, const float4& n)
{
return v - 2.0f * dot(v, n) * n;
}
/* Compute refraction vector
*/
inline float4 refract(const float4& v, const float4& n, float eta)
{
const float k = 1.0f - eta * eta * (1.0f - dot(v, n) * dot(v, n));
return k < 0.0f
? float4(0.0f)
: eta * v - (eta * dot(v, n) + sqrt(k)) * n;
}
/* Compute faceforward vector
*/
inline float4 faceforward(const float4& n, const float4& i, const float4& nref)
{
return dot(i, nref) < 0.0f ? n : -n;
}
/* Quaternion multiplication
*/
inline float4 qmul(const float4& a, const float4& b)
{
const float3 a3 = float3(a.x, a.y, a.z);
const float3 b3 = float3(b.x, b.y, b.z);
float3 xyz = a3 * b.w + b3 * a.w + cross(a3, b3);
float w = a.w * b.w - dot(a3, b3);
return float4(xyz, w);
}
inline float4 qinverse(const float4& q)
{
return float4(q.x, q.y, q.z, -q.w);
}
inline float4 qconj(const float4& q)
{
return float4(-q.x, -q.y, -q.z, q.w);
}
inline float4 quatFromAxisAngle(const float3& axis, float angle)
{
if (lensqr(axis) == 0.0f)
{
return float4(0, 0, 0, 1);
}
return float4(normalize(axis) * sin(angle * 0.5f), cosf(angle * 0.5f));
}
inline float4 float4::quat(const float3& axis, float angle)
{
return quatFromAxisAngle(axis, angle);
}
inline float4 quatToAxisAngle(const float4& quat)
{
float4 c = quat;
if (c.w != 0.0f)
{
c = normalize(quat);
}
const float den = sqrtf(1.0f - c.w * c.w);
const float3 axis = (den > 0.0001f)
? float3(c.x, c.y, c.z) / den
: float3(1, 0, 0);
const float angle = 2.0f * cosf(c.w);
return float4(axis, angle);
}
inline void quatToAxisAngle(const float4& quat, float3* axis, float* angle)
{
float4 axisAngle = quatToAxisAngle(quat);
if (axis) *axis = (float3)axisAngle;
if (angle) *angle = axisAngle.w;
}
inline float4 float4::toaxis(const float4& quat)
{
return quatToAxisAngle(quat);
}
/* Convert quaternion to axisangle
* @note: xyz is axis, w is angle
*/
inline void float4::toaxis(const float4& quat, float3* axis, float* angle)
{
quatToAxisAngle(quat, axis, angle);
}
inline float4 quatFromEuler(float x, float y, float z)
{
float r;
float p;
r = z * 0.5f;
p = x * 0.5f;
y = y * 0.5f; // Now y mean yaw
const float c1 = cos(y);
const float c2 = cos(p);
const float c3 = cos(r);
const float s1 = sin(y);
const float s2 = sin(p);
const float s3 = sin(r);
return float4(
s1 * s2 * c3 + c1 * c2 * s3,
s1 * c2 * c3 + c1 * s2 * s3,
c1 * s2 * c3 - s1 * c2 * s3,
c1 * c2 * c3 - s1 * s2 * s3
);
}
inline float4 float4::euler(float x, float y, float z)
{
return quatFromEuler(x, y, z);
}
/* Quaternion from euler
*/
inline float4 float4::euler(const float3& v)
{
return quatFromEuler(v.x, v.y, v.z);
} | 3.078125 | 3 |
2024-11-18T22:23:09.253923+00:00 | 2022-10-03T19:40:05 | 810ec91dd3d11ed1a37108918c7c76f501de608f | {
"blob_id": "810ec91dd3d11ed1a37108918c7c76f501de608f",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-03T19:40:05",
"content_id": "3cc987ed979e0f3fae7b6fa07ce4cccf81248270",
"detected_licenses": [
"MIT"
],
"directory_id": "1885ce333f6980ab6aad764b3f8caf42094d9f7d",
"extension": "h",
"filename": "SkColorSpacePriv.h",
"fork_events_count": 26,
"gha_created_at": "2014-02-08T12:20:01",
"gha_event_created_at": "2023-06-26T13:44:32",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 16642636,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3768,
"license": "MIT",
"license_type": "permissive",
"path": "/test/e2e/test_master/skia/src/core/SkColorSpacePriv.h",
"provenance": "stackv2-0099.json.gz:5035",
"repo_name": "satya-das/cppparser",
"revision_date": "2022-10-03T19:40:05",
"revision_id": "f9a4cfac1a3af7286332056d7c661d86b6c35eb3",
"snapshot_id": "1dbccdeed4287c36c61edc30190c82de447e415b",
"src_encoding": "UTF-8",
"star_events_count": 194,
"url": "https://raw.githubusercontent.com/satya-das/cppparser/f9a4cfac1a3af7286332056d7c661d86b6c35eb3/test/e2e/test_master/skia/src/core/SkColorSpacePriv.h",
"visit_date": "2023-07-06T00:55:23.382303"
} | stackv2 | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkColorSpacePriv_DEFINED
# define SkColorSpacePriv_DEFINED
# include <math.h>
# include "include/core/SkColorSpace.h"
# include "include/private/SkFixed.h"
# define SkColorSpacePrintf(...)
// A gamut narrower than sRGB, useful for testing.
static constexpr skcms_Matrix3x3 gNarrow_toXYZD50 = {{{0.190974f, 0.404865f, 0.368380f}, {0.114746f, 0.582937f, 0.302318f}, {0.032925f, 0.153615f, 0.638669f}}};
static bool color_space_almost_equal(float a, float b)
{
return SkTAbs(a - b) < 0.01f;
}
// Let's use a stricter version for transfer functions. Worst case, these are encoded
// in ICC format, which offers 16-bits of fractional precision.
static bool transfer_fn_almost_equal(float a, float b)
{
return SkTAbs(a - b) < 0.001f;
}
static bool is_valid_transfer_fn(const skcms_TransferFunction& coeffs)
{
if (SkScalarIsNaN(coeffs.a) || SkScalarIsNaN(coeffs.b) || SkScalarIsNaN(coeffs.c) || SkScalarIsNaN(coeffs.d) || SkScalarIsNaN(coeffs.e) || SkScalarIsNaN(coeffs.f) || SkScalarIsNaN(coeffs.g))
{
return false;
}
if (coeffs.d < 0.0f)
{
return false;
}
if (coeffs.d == 0.0f)
{
// Y = (aX + b)^g + e for always
if (0.0f == coeffs.a || 0.0f == coeffs.g)
{
SkColorSpacePrintf("A or G is zero, constant transfer function "
"is nonsense");
return false;
}
}
if (coeffs.d >= 1.0f)
{
// Y = cX + f for always
if (0.0f == coeffs.c)
{
SkColorSpacePrintf("C is zero, constant transfer function is "
"nonsense");
return false;
}
}
if ((0.0f == coeffs.a || 0.0f == coeffs.g) && 0.0f == coeffs.c)
{
SkColorSpacePrintf("A or G, and C are zero, constant transfer function "
"is nonsense");
return false;
}
if (coeffs.c < 0.0f)
{
SkColorSpacePrintf("Transfer function must be increasing");
return false;
}
if (coeffs.a < 0.0f || coeffs.g < 0.0f)
{
SkColorSpacePrintf("Transfer function must be positive or increasing");
return false;
}
return true;
}
static bool is_almost_srgb(const skcms_TransferFunction& coeffs)
{
return transfer_fn_almost_equal(SkNamedTransferFn::kSRGB.a, coeffs.a) && transfer_fn_almost_equal(SkNamedTransferFn::kSRGB.b, coeffs.b) && transfer_fn_almost_equal(SkNamedTransferFn::kSRGB.c, coeffs.c) && transfer_fn_almost_equal(SkNamedTransferFn::kSRGB.d, coeffs.d) && transfer_fn_almost_equal(SkNamedTransferFn::kSRGB.e, coeffs.e) && transfer_fn_almost_equal(SkNamedTransferFn::kSRGB.f, coeffs.f) && transfer_fn_almost_equal(SkNamedTransferFn::kSRGB.g, coeffs.g);
}
static bool is_almost_2dot2(const skcms_TransferFunction& coeffs)
{
return transfer_fn_almost_equal(1.0f, coeffs.a) && transfer_fn_almost_equal(0.0f, coeffs.b) && transfer_fn_almost_equal(0.0f, coeffs.e) && transfer_fn_almost_equal(2.2f, coeffs.g) && coeffs.d <= 0.0f;
}
static bool is_almost_linear(const skcms_TransferFunction& coeffs)
{
// OutputVal = InputVal ^ 1.0f
const bool linearExp = transfer_fn_almost_equal(1.0f, coeffs.a) && transfer_fn_almost_equal(0.0f, coeffs.b) && transfer_fn_almost_equal(0.0f, coeffs.e) && transfer_fn_almost_equal(1.0f, coeffs.g) && coeffs.d <= 0.0f;
// OutputVal = 1.0f * InputVal
const bool linearFn = transfer_fn_almost_equal(1.0f, coeffs.c) && transfer_fn_almost_equal(0.0f, coeffs.f) && coeffs.d >= 1.0f;
return linearExp || linearFn;
}
// Return raw pointers to commonly used SkColorSpaces.
// No need to ref/unref these, but if you do, do it in pairs.
SkColorSpace* sk_srgb_singleton();
SkColorSpace* sk_srgb_linear_singleton();
#endif
| 2.171875 | 2 |
2024-11-18T22:23:09.524185+00:00 | 2018-01-12T07:29:32 | 60f951383f0c32f372ab29d79627dcec83032472 | {
"blob_id": "60f951383f0c32f372ab29d79627dcec83032472",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-12T07:29:32",
"content_id": "52349cab2c7709961035271cb238fdcc56c94b94",
"detected_licenses": [
"MIT"
],
"directory_id": "1da92ec23213926ac65d37ff7181dfe581f3b0c6",
"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": 117174603,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 829,
"license": "MIT",
"license_type": "permissive",
"path": "/orig/main.c",
"provenance": "stackv2-0099.json.gz:5291",
"repo_name": "Ap4ep25/Semest-Lena-C",
"revision_date": "2018-01-12T07:29:32",
"revision_id": "768d7d3c88201c26dc5b296004f1ef12730da58d",
"snapshot_id": "3770ad0ba8b0199163c58c10eef2583a1fd776ec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ap4ep25/Semest-Lena-C/768d7d3c88201c26dc5b296004f1ef12730da58d/orig/main.c",
"visit_date": "2021-09-03T21:41:30.462363"
} | stackv2 | #include "qdbmp.h"
#include <stdio.h>
int main()
{
BMP* bmp;
UCHAR r, g, b;
UINT width, height;
UINT x, y;
bmp = BMP_ReadFile("/home/ap4ep25/CLionProjects/untitled11/lena.bmp");
BMP_CHECK_ERROR( stderr, -1 ); /* If an error has occurred, notify and exit */
width = BMP_GetWidth( bmp );
height = BMP_GetHeight( bmp );
for ( x = 0 ; x < width ; ++x )
{
for ( y = 0 ; y < height ; ++y )
{
/* Get pixel's RGB values */
BMP_GetPixelRGB( bmp, x, y, &r, &g, &b );
/* Invert RGB values */
BMP_SetPixelRGB( bmp, x, y, 255 - r, 255 - g, 255 - b );
}
}
BMP_WriteFile( bmp, "/home/ap4ep25/CLionProjects/untitled11/lena_orig.bmp");
BMP_CHECK_ERROR( stderr, -2 );
BMP_Free( bmp );
return 0;
} | 2.59375 | 3 |
2024-11-18T22:23:09.758719+00:00 | 2019-02-02T11:38:25 | a726aff2d879bdb0a582276c727ac2d1c8536af8 | {
"blob_id": "a726aff2d879bdb0a582276c727ac2d1c8536af8",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-02T11:38:25",
"content_id": "f3386f75ed487f5f5a32ba889d716df039c149ef",
"detected_licenses": [
"MIT"
],
"directory_id": "86e5af8987793f425bc88b781f8f8ac401e4a1ef",
"extension": "c",
"filename": "quad.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 168825307,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 674,
"license": "MIT",
"license_type": "permissive",
"path": "/day3/quad.c",
"provenance": "stackv2-0099.json.gz:5420",
"repo_name": "Harshakhubwani/c-files",
"revision_date": "2019-02-02T11:38:25",
"revision_id": "5e8e1c63d1de9ace3c2095ab34d4d931cbb6cd83",
"snapshot_id": "d5a3084f4395e509db557873526c62bfa1924705",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Harshakhubwani/c-files/5e8e1c63d1de9ace3c2095ab34d4d931cbb6cd83/day3/quad.c",
"visit_date": "2020-04-20T11:45:14.088586"
} | stackv2 | #include<stdio.h>
#include<math.h>
int main()
{
float a,b,c;
float r2,r1, d;
printf("\nEnter the co-efficients of the quadratic equation : ");
scanf("%f%f%f",&a,&b,&c);
if(a==0&&b==0&&c==0)
printf("\nThe equation is not valid.");
else if(a==0)
printf("\nThe equation is a linear equation.\nThe root is %f\n",-(c/b));
else
{
d=b*b-4*a*c;
if(d==0)
printf("\nIt has equal roots.\nThe root is %f\n",-b/(2*a));
else if (d<0)
printf("\nThe roots are imaginary.\n");
else
{
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf("\nThe roots are %f and %f\n",r1,r2);
}
}
return 0;
}
| 3.375 | 3 |
2024-11-18T20:22:50.215989+00:00 | 2021-03-13T05:19:08 | 55101198b2897f989826e3a40aaf1b8766d64805 | {
"blob_id": "55101198b2897f989826e3a40aaf1b8766d64805",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-13T05:19:08",
"content_id": "d427be3901845f9b732414382c58715bb990fc96",
"detected_licenses": [
"MIT"
],
"directory_id": "b75c9e8171d8ca63caa38c16d5096bf8f9bad530",
"extension": "c",
"filename": "complete_function.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 294732075,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2213,
"license": "MIT",
"license_type": "permissive",
"path": "/hw1/debug-b/complete_function.c",
"provenance": "stackv2-0100.json.gz:270013",
"repo_name": "sheilsarda/SoC_Programming",
"revision_date": "2021-03-13T05:19:08",
"revision_id": "50852515700e24a657f6359c0a231e55c5c9f59e",
"snapshot_id": "de5c0aeb727826bc8ce1184571f18f9f8f99d2fe",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sheilsarda/SoC_Programming/50852515700e24a657f6359c0a231e55c5c9f59e/hw1/debug-b/complete_function.c",
"visit_date": "2023-03-23T22:32:52.760314"
} | stackv2 | #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
/*
* definition of linked list node
* the value is the element in the list
* the pointer points to the next element in the list
* if it exists
*/
typedef struct node_struct {
int8_t value;
struct node_struct* next;
} node_struct;
// when the list is not empty, this variable will always contain
// the element in the first position in the list (the “head” of the list)
static node_struct* head;
// This function will perform the insertion sort and maintain the linked list
// you will need to maintain the links and properly place the new element
void insert_in_order(node_struct* new_element) {
if(new_element == NULL){
printf("invalid insert\n");
return;
}
if(!head)
{
head = new_element;
return;
}
if(new_element->value < head->value)
{
new_element->next = head;
head = new_element;
} else {
node_struct* temp_head = head;
while((temp_head->next != NULL) && (new_element->value > temp_head->next->value))
temp_head = temp_head->next;
new_element->next = temp_head->next;
temp_head->next = new_element;
}
}
// this function creates a new entry into the list to be inserted
void add_element(int8_t value) {
// create a new element in our list
node_struct* new_element = (node_struct*)malloc(sizeof(node_struct));
if (new_element == NULL) {
printf("malloc failed \n");
return;
}
// assign our values
new_element->value = value;
new_element->next = NULL;
insert_in_order(new_element);
}
// prints the entirety of our list
void print_list() {
if (head == NULL) {
printf("list is empty \n");
return;
}
node_struct* element = head;
while (element != NULL) {
printf("value in list %d \n", element->value);
element = element->next;
}
}
int main() {
int8_t a = 20;
int8_t b = 5;
int8_t c = 10;
int8_t d = 21;
int8_t e = 41;
int8_t f = 2;
head = NULL;
add_element(a);
add_element(b);
add_element(c);
add_element(d);
add_element(e);
add_element(f);
print_list();
return 0;
}
| 4.21875 | 4 |
2024-11-18T20:48:30.009710+00:00 | 2020-06-19T12:14:10 | 5ed7539ec979460043f19536aecbbea160631689 | {
"blob_id": "5ed7539ec979460043f19536aecbbea160631689",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-19T12:14:10",
"content_id": "99d7ecc3ceb04cc3b25ca1ee7c06653c5a93457b",
"detected_licenses": [
"MIT"
],
"directory_id": "d6174fded22dbe1c3b647bb724f3fdb10026632a",
"extension": "c",
"filename": "queueADT.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 251598053,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3109,
"license": "MIT",
"license_type": "permissive",
"path": "/Queue/queueADT.c",
"provenance": "stackv2-0102.json.gz:63495",
"repo_name": "donghankim/DataStructure-with-C",
"revision_date": "2020-06-19T12:14:10",
"revision_id": "8733e9eeb9fdc4ada8ccddd72623cf4dc3bc9526",
"snapshot_id": "7775ce6d15ee247c8d648c1c0eb7e6502dc3e2ec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/donghankim/DataStructure-with-C/8733e9eeb9fdc4ada8ccddd72623cf4dc3bc9526/Queue/queueADT.c",
"visit_date": "2021-05-19T08:07:44.939583"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
typedef struct node{
void* data;
struct node* next;
} Node;
typedef struct head{
int count;
Node* head_node;
Node* tail_node;
} Queue;
Queue* create_queue(void);
void enqueue(Queue* Queue_ptr, void* new_data);
void dequeue(Queue* Queue_ptr);
void* head_peak(Queue* Queue_ptr);
void* tail_peak(Queue* Queue_ptr);
void int_print_queue(Queue* Queue_ptr);
void destroy_queue(Queue* Queue_ptr);
int main(void){
Queue* Queue_ptr = create_queue();
int data1 = 10;
enqueue(Queue_ptr, &data1);
int data2 = 20;
enqueue(Queue_ptr, &data2);
int data3 = 30;
enqueue(Queue_ptr, &data3);
int data4 = 40;
enqueue(Queue_ptr, &data4);
int_print_queue(Queue_ptr);
void* head_data = head_peak(Queue_ptr);
void* tail_data = tail_peak(Queue_ptr);
printf("head node data: %d\n", *(int*)head_data);
printf("tail node data: %d\n", *(int*)tail_data);
destroy_queue(Queue_ptr);
return 0;
}
Queue* create_queue(void){
Queue* Queue_ptr = (Queue*) malloc(sizeof(Queue));
Queue_ptr->count = 0;
Queue_ptr->head_node = NULL;
Queue_ptr->tail_node = NULL;
return Queue_ptr;
}
void enqueue(Queue* Queue_ptr, void* new_data){
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->data = new_data;
new_node->next = NULL;
if(Queue_ptr->count == 0){
Queue_ptr->head_node = new_node;
Queue_ptr->tail_node = new_node;
Queue_ptr->head_node->next = Queue_ptr->tail_node;
(Queue_ptr->count)++;
} else{
Node* old_tail = Queue_ptr->tail_node;
old_tail->next = new_node;
Queue_ptr->tail_node = new_node;
(Queue_ptr->count)++;
}
}
void dequeue(Queue* Queue_ptr){
if(Queue_ptr->count == 0){
printf("Queue is empty...\n");
} else{
Node* new_head = Queue_ptr->head_node->next;
Node* del_node = Queue_ptr->head_node;
free(del_node);
Queue_ptr->head_node = new_head;
(Queue_ptr->count)--;
}
}
void* head_peak(Queue* Queue_ptr){
if(Queue_ptr->count == 0){
printf("Queue is empty...\n");
return NULL;
} else{
return Queue_ptr->head_node->data;
}
}
void* tail_peak(Queue* Queue_ptr){
if(Queue_ptr->count == 0){
printf("Queue is empty...\n");
return NULL;
} else{
return Queue_ptr->tail_node->data;
}
}
void int_print_queue(Queue* Queue_ptr){
if(Queue_ptr->count == 0){
printf("Queue is empty...\n");
} else{
Node* traverse = Queue_ptr->head_node;
while(traverse->next != NULL){
printf("%d ", *(int*)traverse->data);
traverse = traverse->next;
} printf("%d\n", *(int*)traverse->data);
}
}
void destroy_queue(Queue* Queue_ptr){
Node* head = Queue_ptr->head_node;
Node* traverse;
while(head){
traverse = head;
head = traverse->next;
free(traverse);
}
Queue_ptr->count = 0;
Queue_ptr->head_node = NULL;
Queue_ptr->tail_node = NULL;
free(Queue_ptr);
}
| 3.625 | 4 |
2024-11-18T20:48:30.190279+00:00 | 2020-11-23T04:07:15 | 30e09b8de83e000fc92f2723dc59ac461211f505 | {
"blob_id": "30e09b8de83e000fc92f2723dc59ac461211f505",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-23T04:07:15",
"content_id": "5af6c9f25bcf96be43b2ceaf625af7307d24e28d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "29749e71062f58d44067d37281fd577bb5374b05",
"extension": "h",
"filename": "rtc_time.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": 7891,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/iris-fsw-softconsole/include/drivers/device/rtc/rtc_time.h",
"provenance": "stackv2-0102.json.gz:63753",
"repo_name": "aminya/IrisSat-Flight-Software",
"revision_date": "2020-11-23T04:07:15",
"revision_id": "0516887aa6127ee9b2c3848b4dff04368c5ccf1e",
"snapshot_id": "1834621c697d9f2052fa9c49332c0da34da938b9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aminya/IrisSat-Flight-Software/0516887aa6127ee9b2c3848b4dff04368c5ccf1e/iris-fsw-softconsole/include/drivers/device/rtc/rtc_time.h",
"visit_date": "2023-01-13T05:44:13.812277"
} | stackv2 | #ifndef RTC_TIME_H_
#define RTC_TIME_H_
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// UMSATS 2018-2020
//
// License:
// Available under MIT license.
//
// Repository:
// Github: https://github.com/UMSATS/cdh-tsat5
//
// File Description:
// User-facing RTC module for reading, writing, and validating the internal and external RTC.
//
// History
// 2019-04-18 by Tamkin Rahman
// - Created.
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// DEFINITIONS AND MACROS
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// The internal RTC runs off of the 50 MHz RC clock.
#define TICKS_TO_SECONDS 50000000u
// Rough conversions for the helper macro below.
#define SECONDS_IN_MINUTE 60
#define MINUTES_IN_HOUR 60
#define HOURS_IN_DAY 24
#define DAYS_IN_MONTH 31
#define MONTHS_IN_YEAR 12
#define SECONDS_IN_HOUR (SECONDS_IN_MINUTE * MINUTES_IN_HOUR)
#define SECONDS_IN_MONTH (SECONDS_IN_HOUR * HOURS_IN_DAY * DAYS_IN_MONTH)
#define SECONDS_IN_YEAR (SECONDS_IN_MONTH * MONTHS_IN_YEAR)
// Helper macro used to convert a Calendar_t object to an unsigned long (for comparison operations). Note that it
// does not correlate one to one into seconds since epoch.
#define CALENDAR_TO_LONG(time) (time)->second \
+ (time)->minute * SECONDS_IN_MINUTE \
+ (time)->hour * SECONDS_IN_HOUR \
+ (time)->month * SECONDS_IN_MONTH \
+ (time)->year * SECONDS_IN_YEAR
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// INCLUDES
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "board_definitions.h"
#include "rtc_common.h"
#include "rtc_ds1393.h"
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// DEFINITIONS AND MACROS
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// These should be used to acquire the lock for the RTC SPI core for the "set_rtc" and "resync_rtc" operations
// in FreeRTOS threads.
#define WAIT_FOR_RTC_CORE(delay) WAIT_FOR_CORE(RTC_SPI_CORE, (delay))
#define WAIT_FOR_RTC_CORE_MAX_DELAY() WAIT_FOR_CORE_MAX_DELAY(RTC_SPI_CORE)
#define RELEASE_RTC_CORE() RELEASE_CORE(RTC_SPI_CORE)
// Use to read from the RTC.
#define read_rtc(buffer) MSS_RTC_get_calendar_count(buffer)
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// ENUMERATIONS AND ENUMERATION TYPEDEFS
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
typedef enum
{
TIME_SUCCESS,
TIME_SECONDS_INVALID,
TIME_MINUTES_INVALID,
TIME_HOURS_INVALID,
TIME_DAYS_INVALID,
TIME_MONTHS_INVALID,
TIME_YEARS_INVALID,
TIME_UNKNOWN_ERROR
} ErrCodesRTC_t;
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// FUNCTION PROTOTYPES
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// Description:
// Initialize the internal and external RTC (without resync). It should only be initialized once the SPI driver has been initialized.
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
void init_rtc();
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// Description:
// Write the date from the external RTC to the internal RTC.
//
// Returns:
// TIME_SUCCESS, on success,
// TIME_UNKNOWN_ERROR, otherwise.
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
ErrCodesRTC_t resync_rtc();
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// Description:
// Write the given date to the external RTC, and then resync.
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
void set_rtc(
Calendar_t * time // Object containing the calendar time to write.
);
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// Description:
// Indicate whether the given calendar time is a valid time.
//
// Returns:
// TIME_SUCCESS if the time is valid, or else the following errors in order of priority:
// TIME_SECONDS_INVALID, if the seconds are invalid,
// TIME_MINUTES_INVALID, if the minutes are invalid,
// TIME_HOURS_INVALID, if the hours are invalid,
// TIME_DAYS_INVALID, if the days are invalid,
// TIME_MONTHS_INVALID, if the months are invalid,
// TIME_YEARS_INVALID, if the years are invalid,
// TIME_UNKNOWN_ERROR, otherwise.
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
ErrCodesRTC_t time_valid(
Calendar_t * time // Object containing the calendar time to check.
);
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// Description:
// Convert a Calendar_t object to an unsigned long (for comparison operations).
// Note: conversion does not correlate one to one into seconds since epoch.
//
// Returns:
// unsigned long - calendar time converted to seconds
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
unsigned long calendar_to_long(Calendar_t * time);
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
// Description:
// Compare two calendar times, and check which is later than the other. The times are assumed to be valid.
//
// Returns:
// -1, if time1 is earlier than time2
// 0, if time1 is equal to time2
// 1, if time1 is later than time2
//-------------------------------------------------------------------------------------------------------------------------------------------------------------
int compare_time(
Calendar_t * time1, // The first calendar time to compare.
Calendar_t * time2 // The second calendar time to compare.
);
#endif /* RTC_TIME_H_ */
| 2.234375 | 2 |
2024-11-18T20:48:30.321505+00:00 | 2019-10-04T03:56:27 | 463192ec28ed0441093a3da1c60771c3590ecb34 | {
"blob_id": "463192ec28ed0441093a3da1c60771c3590ecb34",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-04T03:56:27",
"content_id": "c453c082558ac4f3a77655aa153a0ba8872a89e2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7958ba70a603c0af7ae933f50416cb002c9de51b",
"extension": "c",
"filename": "test_comu_04.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-07T19:56:33",
"gha_event_created_at": "2020-03-07T19:56:34",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 245696552,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2270,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/bsp/ls1cdev/applications/test_comu_04.c",
"provenance": "stackv2-0102.json.gz:63882",
"repo_name": "ghsecuritylab/Hackthon_weatherStation_RTT",
"revision_date": "2019-10-04T03:56:27",
"revision_id": "fdb8a5127b0e11e6c452985a0b8b2660feb4b686",
"snapshot_id": "af7ff30d104cd07ac726a60915874640ce67a23a",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ghsecuritylab/Hackthon_weatherStation_RTT/fdb8a5127b0e11e6c452985a0b8b2660feb4b686/bsp/ls1cdev/applications/test_comu_04.c",
"visit_date": "2021-02-28T12:21:19.428726"
} | stackv2 | #include <rthw.h>
static rt_thread_t tid1 = RT_NULL;
static rt_thread_t tid2 = RT_NULL;
static rt_thread_t worker = RT_NULL;
static rt_sem_t sem = RT_NULL;
#define THREAD_PRIORITY 25
#define THREAD_STACK_SIZE 512
#define THREAD_TIMESLICE 5
rt_uint32_t worker_count, t1_count, t2_count;
static void thread1_entry(void* parameter)
{
rt_err_t result;
result = rt_sem_take(sem, RT_WAITING_FOREVER);
for(t1_count = 0; t1_count < 10; t1_count ++)
{
rt_kprintf("thread1: got semaphore, count: %d\n", t1_count);
rt_thread_delay(RT_TICK_PER_SECOND);
}
rt_kprintf("thread1: release semaphore\n");
rt_sem_release(sem);
}
static void thread2_entry(void* parameter)
{
rt_err_t result;
while (1)
{
result = rt_sem_take(sem, RT_WAITING_FOREVER);
rt_kprintf("thread2: got semaphore\n");
if (result != RT_EOK)
{
return;
}
rt_kprintf("thread2: release semaphore\n");
rt_sem_release(sem);
rt_thread_delay(5);
result = rt_sem_take(sem, RT_WAITING_FOREVER);
t2_count ++;
rt_kprintf("thread2: got semaphore, count: %d\n", t2_count);
}
}
static void worker_thread_entry(void* parameter)
{
rt_thread_delay(5);
for(worker_count = 0; worker_count < 10; worker_count++)
{
rt_kprintf("worker: count: %d\n", worker_count);
}
rt_thread_delay(RT_TICK_PER_SECOND);
}
void test_comu_04(void)
{
sem = rt_sem_create("sem", 1, RT_IPC_FLAG_PRIO);
if (sem == RT_NULL)
{
return ;
}
tid1 = rt_thread_create("thread1",
thread1_entry, RT_NULL,
THREAD_STACK_SIZE, THREAD_PRIORITY + 2, THREAD_TIMESLICE);
if (tid1 != RT_NULL)
rt_thread_startup(tid1);
tid2 = rt_thread_create("thread2",
thread2_entry, RT_NULL,
THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);
if (tid2 != RT_NULL)
rt_thread_startup(tid2);
worker = rt_thread_create("worker",
worker_thread_entry, RT_NULL,
THREAD_STACK_SIZE, THREAD_PRIORITY+1, THREAD_TIMESLICE);
if (worker != RT_NULL)
rt_thread_startup(worker);
}
#include <finsh.h>
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(test_comu_04, comu test); | 2.59375 | 3 |
2024-11-18T20:48:30.510225+00:00 | 2017-02-23T04:38:11 | f6a7d3455b4b0e08a14fb4c05a4e7d92b8f45b50 | {
"blob_id": "f6a7d3455b4b0e08a14fb4c05a4e7d92b8f45b50",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-23T04:38:11",
"content_id": "6118f7aa6afcd35796e6e9a94a17e76113c8906a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e4a9b85cb53dc2f3f27fd437121255cf497b8518",
"extension": "c",
"filename": "cstat.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": 1117,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lcfs/cstat.c",
"provenance": "stackv2-0102.json.gz:64011",
"repo_name": "bgrissin/lcfs",
"revision_date": "2017-02-23T04:38:11",
"revision_id": "4ad1e457dc4af35bc2fb1c04c5fc329b80a3cfe8",
"snapshot_id": "d9c62145ec85cda58486918c7361c6a8f5557068",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bgrissin/lcfs/4ad1e457dc4af35bc2fb1c04c5fc329b80a3cfe8/lcfs/cstat.c",
"visit_date": "2020-04-06T04:46:01.095606"
} | stackv2 | #include "includes.h"
#include <sys/ioctl.h>
#include "version/version.h"
/* Display usage and exit */
static void
usage(char *name) {
fprintf(stderr, "usage: %s <id> [-c]\n", name);
fprintf(stderr, "\t id - layer name\n");
fprintf(stderr, "\t [-c] - clear stats (optional)\n");
fprintf(stderr, "Specify . as id for displaying stats for all layers\n");
fprintf(stderr, "Run this command from the layer root directory\n");
exit(EINVAL);
}
/* Display (and optionally clear) stats of a layer.
* Issue the command from the layer root directory.
*/
int
main(int argc, char *argv[]) {
char name[256];
int fd, err;
if ((argc != 2) && (argc != 3)) {
usage(argv[0]);
}
if ((argc == 3) && strcmp(argv[2], "-c")) {
usage(argv[0]);
}
fd = open(".", O_DIRECTORY);
if (fd < 0) {
perror("open");
exit(errno);
}
printf("%s %s\n", Build, Release);
err = ioctl(fd, _IOW(0, argc == 2 ? LAYER_STAT : CLEAR_STAT, name),
argv[1]);
if (err) {
perror("ioctl");
exit(errno);
}
return 0;
}
| 2.515625 | 3 |
2024-11-18T20:48:30.609022+00:00 | 2019-02-03T16:46:14 | 4779bc01d86e3d8f59c37e11d83ab1f1fb53c1bf | {
"blob_id": "4779bc01d86e3d8f59c37e11d83ab1f1fb53c1bf",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-03T16:46:14",
"content_id": "f0c84671f9b2bcbecb91b29cea2b3d408f1a7a34",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9c5f08012c2d06b9ff5521f5c93d92cbb56d1d9f",
"extension": "c",
"filename": "replicate.c",
"fork_events_count": 0,
"gha_created_at": "2019-04-11T18:38:45",
"gha_event_created_at": "2019-04-11T18:38:46",
"gha_language": null,
"gha_license_id": null,
"github_id": 180855899,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13187,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/replicate.c",
"provenance": "stackv2-0102.json.gz:64141",
"repo_name": "sollyucko/iteration_utilities",
"revision_date": "2019-02-03T16:46:14",
"revision_id": "b99af218061e6e678b807075950b916f4eb23a94",
"snapshot_id": "bbe2ae060af619bd0afd8b2e777144d7bb479b44",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sollyucko/iteration_utilities/b99af218061e6e678b807075950b916f4eb23a94/src/replicate.c",
"visit_date": "2020-05-07T20:21:06.354359"
} | stackv2 | /******************************************************************************
* Licensed under Apache License Version 2.0 - see LICENSE
*****************************************************************************/
typedef struct {
PyObject_HEAD
PyObject *iterator;
PyObject *current;
Py_ssize_t repeattotal;
Py_ssize_t repeatcurrent;
} PyIUObject_Replicate;
static PyTypeObject PyIUType_Replicate;
/******************************************************************************
* New
*****************************************************************************/
static PyObject *
replicate_new(PyTypeObject *type,
PyObject *args,
PyObject *kwargs)
{
static char *kwlist[] = {"iterable", "times", NULL};
PyIUObject_Replicate *self;
PyObject *iterable;
PyObject *iterator = NULL;
Py_ssize_t times;
/* Parse arguments */
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "On:replicate", kwlist,
&iterable, ×)) {
goto Fail;
}
if (times <= 1) {
PyErr_Format(PyExc_ValueError,
"`times` argument for `replicate` must be greater "
"than 1, not `%zd`", times);
goto Fail;
}
/* Create and fill struct */
iterator = PyObject_GetIter(iterable);
if (iterator == NULL) {
goto Fail;
}
self = (PyIUObject_Replicate *)type->tp_alloc(type, 0);
if (self == NULL) {
goto Fail;
}
self->iterator = iterator;
self->current = NULL;
self->repeattotal = times;
self->repeatcurrent = 0;
return (PyObject *)self;
Fail:
Py_XDECREF(iterator);
return NULL;
}
/******************************************************************************
* Destructor
*****************************************************************************/
static void
replicate_dealloc(PyIUObject_Replicate *self)
{
PyObject_GC_UnTrack(self);
Py_XDECREF(self->iterator);
Py_XDECREF(self->current);
Py_TYPE(self)->tp_free(self);
}
/******************************************************************************
* Traverse
*****************************************************************************/
static int
replicate_traverse(PyIUObject_Replicate *self,
visitproc visit,
void *arg)
{
Py_VISIT(self->iterator);
Py_VISIT(self->current);
return 0;
}
/******************************************************************************
* Clear
*****************************************************************************/
static int
replicate_clear(PyIUObject_Replicate *self)
{
Py_CLEAR(self->iterator);
Py_CLEAR(self->current);
return 0;
}
/******************************************************************************
* Next
*****************************************************************************/
static PyObject *
replicate_next(PyIUObject_Replicate *self)
{
/* First time around we need to get the first element of the iterator
to fill the current.
*/
if (self->current == NULL) {
self->current = Py_TYPE(self->iterator)->tp_iternext(self->iterator);
/* If we had x repeats then we also need to get the next element, and
dereference the old one.
*/
} else if (self->repeatcurrent == self->repeattotal) {
PyObject *oldcurrent = self->current;
self->current = Py_TYPE(self->iterator)->tp_iternext(self->iterator);
Py_DECREF(oldcurrent);
self->repeatcurrent = 0;
}
/* In case something unexpected happened or the iterator finished we can
stop now.
*/
if (self->current == NULL) {
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_StopIteration)) {
PyErr_Clear();
}
return NULL;
}
/* Otherwise just return the current item. */
self->repeatcurrent++;
Py_INCREF(self->current);
return self->current;
}
/******************************************************************************
* Reduce
*****************************************************************************/
static PyObject *
replicate_reduce(PyIUObject_Replicate *self)
{
/* Seperate cases depending on current == NULL because otherwise "None"
would be ambiguous. It could mean that we did not had a current item or
that the current item was None.
Better to make an "if" than to introduce another variable depending on
current == NULL.
*/
if (self->current == NULL) {
return Py_BuildValue("O(On)", Py_TYPE(self),
self->iterator,
self->repeattotal);
} else {
return Py_BuildValue("O(On)(On)", Py_TYPE(self),
self->iterator,
self->repeattotal,
self->current,
self->repeatcurrent);
}
}
/******************************************************************************
* Setstate
*****************************************************************************/
static PyObject *
replicate_setstate(PyIUObject_Replicate *self,
PyObject *state)
{
PyObject *current;
Py_ssize_t repeatcurrent;
if (!PyTuple_Check(state)) {
PyErr_Format(PyExc_TypeError,
"`%.200s.__setstate__` expected a `tuple`-like argument"
", got `%.200s` instead.",
Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
return NULL;
}
if (!PyArg_ParseTuple(state, "On:replicate.__setstate__",
¤t, &repeatcurrent)) {
return NULL;
}
if (repeatcurrent < 0 || repeatcurrent > self->repeattotal) {
PyErr_Format(PyExc_ValueError,
"`%.200s.__setstate__` expected a that the second item "
"in the `state` is greater or equal to zero and below "
"the `times` (%zd), not `%zd`.",
Py_TYPE(self)->tp_name, self->repeattotal, repeatcurrent);
return NULL;
}
Py_CLEAR(self->current);
self->current = current;
Py_INCREF(self->current);
self->repeatcurrent = repeatcurrent;
Py_RETURN_NONE;
}
/******************************************************************************
* LengthHint
*****************************************************************************/
#if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4)
static PyObject *
replicate_lengthhint(PyIUObject_Replicate *self)
{
Py_ssize_t len = PyObject_LengthHint(self->iterator, 0);
if (len == -1) {
return NULL;
}
/* Check if it is safe (no overflow) to multiply it. */
if (len > PY_SSIZE_T_MAX / self->repeattotal) {
PyErr_SetString(PyExc_OverflowError,
"cannot fit 'int' into an index-sized "
"integer");
return NULL;
}
len *= self->repeattotal;
if (self->current != NULL) {
/* We need to avoid signed integer overflow so do the operation on
size_t instead. "repeattotal" >= "repeatcurrent" so we only
deal with positive values here and we're overflow safe when doing
the operation on (size_t) because 2*PY_SSIZE_T_MAX is still
below SIZE_T_MAX. We also don't need to check for overflow because
we can simply return "PyLong_FromSize_t", which will fail when
someone else wants it as Py_ssize_t (later).
*/
size_t ulen = (size_t)len;
ulen += (size_t)(self->repeattotal - self->repeatcurrent);
return PyLong_FromSize_t(ulen);
}
return PyLong_FromSsize_t(len);
}
#endif
/******************************************************************************
* Type
*****************************************************************************/
static PyMethodDef replicate_methods[] = {
#if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4)
{"__length_hint__", /* ml_name */
(PyCFunction)replicate_lengthhint, /* ml_meth */
METH_NOARGS, /* ml_flags */
PYIU_lenhint_doc /* ml_doc */
},
#endif
{"__reduce__", /* ml_name */
(PyCFunction)replicate_reduce, /* ml_meth */
METH_NOARGS, /* ml_flags */
PYIU_reduce_doc /* ml_doc */
},
{"__setstate__", /* ml_name */
(PyCFunction)replicate_setstate, /* ml_meth */
METH_O, /* ml_flags */
PYIU_setstate_doc /* ml_doc */
},
{NULL, NULL} /* sentinel */
};
#define OFF(x) offsetof(PyIUObject_Replicate, x)
static PyMemberDef replicate_memberlist[] = {
{"times", /* name */
T_PYSSIZET, /* type */
OFF(repeattotal), /* offset */
READONLY, /* flags */
replicate_prop_times_doc /* doc */
},
{"timescurrent", /* name */
T_PYSSIZET, /* type */
OFF(repeatcurrent), /* offset */
READONLY, /* flags */
replicate_prop_timescurrent_doc /* doc */
},
{"current", /* name */
T_OBJECT_EX, /* type */
OFF(current), /* offset */
READONLY, /* flags */
replicate_prop_current_doc /* doc */
},
{NULL} /* sentinel */
};
#undef OFF
static PyTypeObject PyIUType_Replicate = {
PyVarObject_HEAD_INIT(NULL, 0)
(const char *)"iteration_utilities.replicate", /* tp_name */
(Py_ssize_t)sizeof(PyIUObject_Replicate), /* tp_basicsize */
(Py_ssize_t)0, /* tp_itemsize */
/* methods */
(destructor)replicate_dealloc, /* tp_dealloc */
(printfunc)0, /* tp_print */
(getattrfunc)0, /* tp_getattr */
(setattrfunc)0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)0, /* tp_repr */
(PyNumberMethods *)0, /* tp_as_number */
(PySequenceMethods *)0, /* tp_as_sequence */
(PyMappingMethods *)0, /* tp_as_mapping */
(hashfunc)0, /* tp_hash */
(ternaryfunc)0, /* tp_call */
(reprfunc)0, /* tp_str */
(getattrofunc)PyObject_GenericGetAttr, /* tp_getattro */
(setattrofunc)0, /* tp_setattro */
(PyBufferProcs *)0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE, /* tp_flags */
(const char *)replicate_doc, /* tp_doc */
(traverseproc)replicate_traverse, /* tp_traverse */
(inquiry)replicate_clear, /* tp_clear */
(richcmpfunc)0, /* tp_richcompare */
(Py_ssize_t)0, /* tp_weaklistoffset */
(getiterfunc)PyObject_SelfIter, /* tp_iter */
(iternextfunc)replicate_next, /* tp_iternext */
replicate_methods, /* tp_methods */
replicate_memberlist, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
(descrgetfunc)0, /* tp_descr_get */
(descrsetfunc)0, /* tp_descr_set */
(Py_ssize_t)0, /* tp_dictoffset */
(initproc)0, /* tp_init */
(allocfunc)PyType_GenericAlloc, /* tp_alloc */
(newfunc)replicate_new, /* tp_new */
(freefunc)PyObject_GC_Del, /* tp_free */
};
| 2.703125 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.