added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:28:39.616125+00:00 | 2023-07-06T03:21:34 | cc58eec0fa3e117145de57233397773880e9ac80 | {
"blob_id": "cc58eec0fa3e117145de57233397773880e9ac80",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-06T03:21:34",
"content_id": "428ea2ce1dd0b607b4fbd32a558ee8e8e31fb4e7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cea9011cef46bcd78fafa0a9348da2bf3d0fe0a6",
"extension": "h",
"filename": "common_test.h",
"fork_events_count": 5,
"gha_created_at": "2019-01-24T18:35:29",
"gha_event_created_at": "2023-07-06T03:21:35",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 167417084,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2347,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/03-syzkaller/executor/common_test.h",
"provenance": "stackv2-0132.json.gz:85069",
"repo_name": "ZHYfeng/Dependency",
"revision_date": "2023-07-06T03:21:34",
"revision_id": "f0d17a2e5e2622f8a9df45c20c03eea79eea5f92",
"snapshot_id": "6e9cf0f757c0b111e1074e49384aeceeff68597d",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/ZHYfeng/Dependency/f0d17a2e5e2622f8a9df45c20c03eea79eea5f92/03-syzkaller/executor/common_test.h",
"visit_date": "2023-07-20T11:56:25.406842"
} | stackv2 | // Copyright 2018 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
// This file is shared between executor and csource package.
#include <stdlib.h>
#include <unistd.h>
#if SYZ_EXECUTOR || __NR_syz_mmap
#include <sys/mman.h>
// syz_mmap(addr vma, len len[addr])
static long syz_mmap(volatile long a0, volatile long a1)
{
return (long)mmap((void*)a0, a1, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0);
}
#endif
#if SYZ_EXECUTOR || __NR_syz_errno
#include <errno.h>
// syz_errno(v int32)
static long syz_errno(volatile long v)
{
errno = v;
return v == 0 ? 0 : -1;
}
#endif
#if SYZ_EXECUTOR || __NR_syz_exit
// syz_exit(status int32)
static long syz_exit(volatile long status)
{
_exit(status);
return 0;
}
#endif
#if SYZ_EXECUTOR || __NR_syz_compare
#include <errno.h>
#include <string.h>
// syz_compare(want ptr[in, string], want_len len[want], got ptr[in, compare_data], got_len len[got])
static long syz_compare(volatile long want, volatile long want_len, volatile long got, volatile long got_len)
{
if (want_len != got_len) {
debug("syz_compare: want_len=%lu got_len=%lu\n", want_len, got_len);
errno = EBADF;
return -1;
}
if (memcmp((void*)want, (void*)got, want_len)) {
debug("syz_compare: data differs, want:\n");
debug_dump_data((char*)want, want_len);
debug("got:\n");
debug_dump_data((char*)got, got_len);
errno = EINVAL;
return -1;
}
return 0;
}
#endif
#if SYZ_EXECUTOR || __NR_syz_compare_int
#include <errno.h>
#include <stdarg.h>
// syz_compare_int$4(n const[2], v0 intptr, v1 intptr, v2 intptr, v3 intptr)
static long syz_compare_int(volatile long n, ...)
{
va_list args;
va_start(args, n);
long v0 = va_arg(args, long);
long v1 = va_arg(args, long);
long v2 = va_arg(args, long);
long v3 = va_arg(args, long);
va_end(args);
if (n < 2 || n > 4)
return errno = E2BIG, -1;
if (n <= 2 && v2 != 0)
return errno = EFAULT, -1;
if (n <= 3 && v3 != 0)
return errno = EFAULT, -1;
if (v0 != v1)
return errno = EINVAL, -1;
if (n > 2 && v0 != v2)
return errno = EINVAL, -1;
if (n > 3 && v0 != v3)
return errno = EINVAL, -1;
return 0;
}
#endif
#if SYZ_EXECUTOR || SYZ_SANDBOX_NONE
static void loop();
static int do_sandbox_none(void)
{
loop();
return 0;
}
#endif
| 2.203125 | 2 |
2024-11-18T22:28:39.728864+00:00 | 2021-12-28T12:54:21 | 99cc463a8539c7979f02a02fddc277367627db57 | {
"blob_id": "99cc463a8539c7979f02a02fddc277367627db57",
"branch_name": "refs/heads/master",
"committer_date": "2021-12-28T12:54:21",
"content_id": "9a823698565bc73a5ec044ac8e1cf99649577c68",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6dd70ccbed727994de1fde53401ecdad7d1b9dbd",
"extension": "c",
"filename": "chapter7_3aexit.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98617712,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 514,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/apue/chapter7/chapter7_3aexit.c",
"provenance": "stackv2-0132.json.gz:85198",
"repo_name": "MartinHan01/MyPractices",
"revision_date": "2021-12-28T12:54:21",
"revision_id": "a68a553dbfea7caca186f1b9339115d8c9425a18",
"snapshot_id": "8b8f85b3a554b7c847958977dc9117a340861c65",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/MartinHan01/MyPractices/a68a553dbfea7caca186f1b9339115d8c9425a18/apue/chapter7/chapter7_3aexit.c",
"visit_date": "2022-01-22T23:43:49.376401"
} | stackv2 | #include "my_apue.h"
static void my_exit1(void);
static void my_exit2(void);
int main(int argc,char *argv) {
if(atexit(my_exit1) == -1) {
err_ret("atexit exit1\n");
}
if(atexit(my_exit1) == -1) {
err_ret("atexit exit1\n");
}
if(atexit(my_exit2) == -1) {
err_ret("atexit exit2\n");
}
printf("main function is done\n");
return 0;
}
static void my_exit1(void) {
printf("call my_exit1\n");
}
static void my_exit2(void) {
printf("call my_exit2\n");
} | 2.3125 | 2 |
2024-11-18T22:28:40.256603+00:00 | 2015-07-21T14:10:36 | 34dd019ee4347231399bbd8f0e20ce9514efa1f6 | {
"blob_id": "34dd019ee4347231399bbd8f0e20ce9514efa1f6",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-22T10:45:29",
"content_id": "736d05bcd274f5465edf977ba42bc9601b9db000",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cdc933f42f2abd3d80afba2ebefeb5363ba5b2f0",
"extension": "h",
"filename": "crc32c.h",
"fork_events_count": 0,
"gha_created_at": "2015-07-23T15:51:43",
"gha_event_created_at": "2015-07-23T15:51:43",
"gha_language": null,
"gha_license_id": null,
"github_id": 39576592,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2253,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/platform/crc32c.h",
"provenance": "stackv2-0132.json.gz:85713",
"repo_name": "vmx/platform",
"revision_date": "2015-07-21T14:10:36",
"revision_id": "117fd71757b6efeaf77c7d3d6a9a6fc8124e4361",
"snapshot_id": "01445af52c823f182fd91da3b6f8776398755371",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vmx/platform/117fd71757b6efeaf77c7d3d6a9a6fc8124e4361/include/platform/crc32c.h",
"visit_date": "2021-01-15T20:18:40.403820"
} | stackv2 | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2015 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Generate a CRC-32C (Castagnolia)
// CRC polynomial of 0x1EDC6F41
//
// When available a hardware assisted function is used for increased performance.
//
// This module provides one function:
//
// uint32_t crc32c(const uint8_t* bug, size_t len, uint32_t crc_in)
//
//
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <platform/visibility.h>
//
// This module requires X86 for the HW assisted version of the function.
// For now this #error is here because there's been no requirement for
// a portable/non-X86 version of this function in Couchbase.
// To fix will require refactoring to hide the X86 dependencies when
// built on another platform.
//
// The code is also x64 optimised.
//
#if !defined(__x86_64__) && !defined(_M_X64)
#error "crc32c requires X86 for hardware acceleration"
#endif
#ifdef CRC32C_UNIT_TEST
#undef PLATFORM_PUBLIC_API
#define PLATFORM_PUBLIC_API
#endif
// If GCC 4.8 or higher use compiler attributes to select the
// correct function at runtime. If running the CRC32C unit test
// disable this as we want individually visible hw/sw versions.
#if (__GNUC__ > 3) && (__GNUC_MINOR__ > 7) && !defined(CRC32C_UNIT_TEST)
#define USE_GCC_SSE4_ATTRIBUTE 1
PLATFORM_PUBLIC_API __attribute__ ((target ("default")))
uint32_t crc32c (const uint8_t* buf, size_t len, uint32_t crc_in);
PLATFORM_PUBLIC_API __attribute__ ((target ("sse4.2")))
uint32_t crc32c (const uint8_t* buf, size_t len, uint32_t crc_in);
#else
PLATFORM_PUBLIC_API
uint32_t crc32c (const uint8_t* buf, size_t len, uint32_t crc_in);
#endif | 2.046875 | 2 |
2024-11-18T22:28:40.786057+00:00 | 2019-03-01T05:49:05 | 4db6e8153e6cc98b11772c472630b31947e3684f | {
"blob_id": "4db6e8153e6cc98b11772c472630b31947e3684f",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-01T05:49:05",
"content_id": "1ca0b5f79af1b35290d49492cb089b6a0a5c3895",
"detected_licenses": [
"curl"
],
"directory_id": "9923e30eb99716bfc179ba2bb789dcddc28f45e6",
"extension": "c",
"filename": "dvir_base_vehicle.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 172804041,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2009,
"license": "curl",
"license_type": "permissive",
"path": "/openapi-generator/c/model/dvir_base_vehicle.c",
"provenance": "stackv2-0132.json.gz:86229",
"repo_name": "silverspace/samsara-sdks",
"revision_date": "2019-03-01T05:49:05",
"revision_id": "c054b91e488ab4266f3b3874e9b8e1c9e2d4d5fa",
"snapshot_id": "cefcd61458ed3c3753ac5e6bf767229dd8df9485",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/silverspace/samsara-sdks/c054b91e488ab4266f3b3874e9b8e1c9e2d4d5fa/openapi-generator/c/model/dvir_base_vehicle.c",
"visit_date": "2020-04-25T13:16:59.137551"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "dvir_base_vehicle.h"
dvir_base_vehicle_t *dvir_base_vehicle_create(
char *name,
long id
) {
dvir_base_vehicle_t *dvir_base_vehicle = malloc(sizeof(dvir_base_vehicle_t));
dvir_base_vehicle->name = name;
dvir_base_vehicle->id = id;
return dvir_base_vehicle;
}
void dvir_base_vehicle_free(dvir_base_vehicle_t *dvir_base_vehicle) {
listEntry_t *listEntry;
free(dvir_base_vehicle->name);
free(dvir_base_vehicle);
}
cJSON *dvir_base_vehicle_convertToJSON(dvir_base_vehicle_t *dvir_base_vehicle) {
cJSON *item = cJSON_CreateObject();
// dvir_base_vehicle->name
if(cJSON_AddStringToObject(item, "name", dvir_base_vehicle->name) == NULL) {
goto fail; //String
}
// dvir_base_vehicle->id
if(cJSON_AddNumberToObject(item, "id", dvir_base_vehicle->id) == NULL) {
goto fail; //Numeric
}
return item;
fail:
cJSON_Delete(item);
return NULL;
}
dvir_base_vehicle_t *dvir_base_vehicle_parseFromJSON(char *jsonString){
dvir_base_vehicle_t *dvir_base_vehicle = NULL;
cJSON *dvir_base_vehicleJSON = cJSON_Parse(jsonString);
if(dvir_base_vehicleJSON == NULL){
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error Before: %s\n", error_ptr);
goto end;
}
}
// dvir_base_vehicle->name
cJSON *name = cJSON_GetObjectItemCaseSensitive(dvir_base_vehicleJSON, "name");
if(!cJSON_IsString(name) || (name->valuestring == NULL)){
goto end; //String
}
// dvir_base_vehicle->id
cJSON *id = cJSON_GetObjectItemCaseSensitive(dvir_base_vehicleJSON, "id");
if(!cJSON_IsNumber(id))
{
goto end; //Numeric
}
dvir_base_vehicle = dvir_base_vehicle_create (
strdup(name->valuestring),
id->valuedouble
);
cJSON_Delete(dvir_base_vehicleJSON);
return dvir_base_vehicle;
end:
cJSON_Delete(dvir_base_vehicleJSON);
return NULL;
}
| 2.59375 | 3 |
2024-11-18T22:28:40.887762+00:00 | 2021-04-16T08:52:19 | 1aff7fcdc3d0d745e2d0161966be2fe678bb449a | {
"blob_id": "1aff7fcdc3d0d745e2d0161966be2fe678bb449a",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-16T08:52:19",
"content_id": "a1e316c299c3b23eb10c52a7a7851f51c0bfc806",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "d963a50c09b7380dd7b1b97cd9997e9bd17ea8f3",
"extension": "c",
"filename": "grep2.c",
"fork_events_count": 1,
"gha_created_at": "2021-03-01T00:15:22",
"gha_event_created_at": "2021-04-16T08:53:31",
"gha_language": "TeX",
"gha_license_id": "NOASSERTION",
"github_id": 343245204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6394,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/r36/cslbase/grep2.c",
"provenance": "stackv2-0132.json.gz:86359",
"repo_name": "reduce-algebra/reduce-historical",
"revision_date": "2021-04-16T08:52:19",
"revision_id": "e014152729c4d62bb1ce4f5c311a027042a5495a",
"snapshot_id": "8220e211b116e0e01ff1a38f51917cac9db6069f",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/reduce-algebra/reduce-historical/e014152729c4d62bb1ce4f5c311a027042a5495a/r36/cslbase/grep2.c",
"visit_date": "2023-04-10T22:54:00.796596"
} | stackv2 | /* file grep2.c */
/* Signature: 733176dd 27-Jan-1997 */
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "machine.h"
#include "tags.h"
#include "cslerror.h"
#include "externs.h"
#include "entries.h"
#include "arith.h"
/* Defined in grep.c */
extern void zsfinit_(int32 *mode);
extern void zscpat_(char *pat, int32 *cse, int32 *cpat, int32 *maxpat,
int32 *ifail, int32 len);
extern int32 zsfind_(char *line, int32 *start, int32 *finish, int32 *cpat,
int32 len);
/*
* I really do need to be able to read arbitrary sized lines because the
* AXIOM databases contain some quite long ones!
*
*/
/* The number of characters we will malloc at a time */
#define LINE_CHUNK_LENGTH 127
typedef struct LineChunk
{
char s[LINE_CHUNK_LENGTH+1];
struct LineChunk *next;
} LineChunk;
LineChunk *newChunk()
{
LineChunk *new;
new = (LineChunk *)malloc(sizeof(LineChunk));
new->next = NULL;
return(new);
}
int getChunk(char *buffer, FILE *fp)
{
int32 i=0;
char c;
c = getc(fp);
/* In theory could compare c to EOF but this probably isn't very safe */
while (c != '\n' && !feof(fp) && i < LINE_CHUNK_LENGTH) {
buffer[i] = c;
++i;
c = getc(fp);
}
buffer[i] = '\0';
if (i == LINE_CHUNK_LENGTH) {
ungetc(c,fp);
return (0);
}
else
return (1);
}
char *concatenateChunks(LineChunk *l, int32 len)
{
char *s;
LineChunk *prev;
if (len <= LINE_CHUNK_LENGTH)
return(l->s);
else {
s = (char *)malloc((size_t) len);
s[0] = '\0'; /* Otherwise strcat might get confused! */
while (l != NULL) {
strcat(s,l->s);
prev = l;
l = l->next;
free(prev);
}
return(s);
}
}
char *read_a_line(FILE *fp)
{
LineChunk *start, *place;
int32 chunk_count=1;
char *str;
start = newChunk();
place = start;
while (!getChunk(place->s, fp) ) {
place->next = newChunk();
place = place->next;
++chunk_count;
}
/* The +1 in the size is for the terminator */
str = concatenateChunks(start,
(chunk_count-1)*LINE_CHUNK_LENGTH+strlen(place->s)+1);
return(str);
}
#define MAXIMUM_PATTERN_SIZE 512
/*
* This function takes a filename or a list of strings and returns
* lines which match pattern
* which uses egrep syntax. The flag casep says whether to be
* case sensitive in matching, and the flag matchp says whether to return
* a line or not if the pattern matches (i.e. it behaves like the "-v"
* option to grep et al).
*/
Lisp_Object MS_CDECL Lgrep(Lisp_Object nil, int nargs, ...)
{
va_list args;
Lisp_Object name, pattern, casep, matchp, result;
FILE *fp;
char filename[LONGEST_LEGAL_FILENAME], *pat, *line;
int32 len, case_sensitive, match, mode, ifail=0, max_patternsize,
compiled_pattern[MAXIMUM_PATTERN_SIZE], result_is_null=1;
Header h;
extern char *get_string_data(Lisp_Object name, char *why, int32 *l);
extern int32 zsinit_(int32 *mode);
/* Set up arguments as Lisp Objects */
argcheck(nargs,4,"Lgrep");
va_start(args,nargs);
name = va_arg(args, Lisp_Object);
pattern = va_arg(args, Lisp_Object);
casep = va_arg(args, Lisp_Object);
matchp = va_arg(args, Lisp_Object);
va_end(args);
/* Translate arguments into C objects */
if (!is_vector(pattern) || !(type_of_header(vechdr(pattern)) == TYPE_STRING) )
return aerror("grep");
pat = get_string_data(pattern,"grep",&len);
if (casep == lisp_true)
case_sensitive = 1;
else
case_sensitive = 0;
if (matchp == lisp_true)
match = 1;
else
match = 0;
/* Initialise the matcher to egrep mode */
mode = 2;
zsinit_(&mode);
/* Compile the pattern */
max_patternsize=MAXIMUM_PATTERN_SIZE;
zscpat_(pat,&case_sensitive,compiled_pattern,&max_patternsize,
&ifail,len);
if (ifail != 0) return aerror1("Invalid regular expression", pattern);
/* Test to see whether we are dealing with a list of strings or a file */
if (is_cons(name))
return grepList(nil, name, case_sensitive, match, compiled_pattern);
/* Sort out the filename */
#ifdef COMMON
if (complex_stringp(name))
{ name = simplify_string(name);
errexit();
h = vechdr(name);
}
else
#endif
if (symbolp(name))
{ name = get_pname(name);
errexit();
h = vechdr(name);
}
else if (!(is_vector(name))) return aerror("grep");
else if (type_of_header(h = vechdr(name)) != TYPE_STRING)
return aerror("grep");
len = length_of_header(h) - 4;
if (len >= sizeof(filename)) len = sizeof(filename);
/* Check whether file is readable using method desfined in SYS.c */
if (!file_readable(filename,
(char *)name + (4 - TAG_VECTOR),
(size_t)len) ) return aerror1("Cannot read",name);
/* Open file */
fp = fopen(filename,"r");
if (!fp) return aerror("Error opening file in grep - should not happen!");
while (!feof(fp)) {
line = read_a_line(fp);
if (match == zsfind_(line,&ifail,&ifail,compiled_pattern,strlen(line))){
if (result_is_null) {
result = Lncons(nil,make_string(line));
result_is_null = 0;
}
else
result = Lcons(nil,make_string(line),result);
}
else
free((void *)line);
}
fclose(fp);
if (result_is_null)
return(nil);
else
return(Lnreverse(nil,result));
}
Lisp_Object grepList(Lisp_Object nil, Lisp_Object string_list,
int32 case_sensitive, int32 match,
int32 *compiled_pattern)
{
Lisp_Object lstring, result;
char *str;
int32 ifail=0, result_is_null=1;
while (string_list != nil) {
lstring = Lcar(nil,string_list);
if (!is_vector(lstring) || type_of_header(vechdr(lstring)) != TYPE_STRING)
aerror1("error in grep, non-string in list",lstring);
str=&celt(lstring,0);
if (match == zsfind_(str,&ifail,&ifail,compiled_pattern,strlen(str)))
if (result_is_null) {
result = Lncons(nil,lstring);
result_is_null = 0;
}
else
result = Lcons(nil,lstring,result);
string_list = Lcdr(nil,string_list);
}
if (result_is_null)
return(nil);
else
return(Lnreverse(nil,result));
}
setup_type const grep_setup[] =
{
{"grep", wrong_no_na, wrong_no_nb, Lgrep},
{NULL, 0, 0, 0}
};
/* end of grep2.c */
| 2.390625 | 2 |
2024-11-18T22:28:41.039663+00:00 | 2015-11-29T17:04:59 | 99860ab12e421c2bbee1d47a437ad039e6dcbae7 | {
"blob_id": "99860ab12e421c2bbee1d47a437ad039e6dcbae7",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-29T17:04:59",
"content_id": "a4fd82cd6aa0decc65181d71e45ea51446d4192c",
"detected_licenses": [
"BSD-2-Clause-Views",
"BSD-3-Clause"
],
"directory_id": "72bf1500edf4dd26631e0846a2920e90a4b701df",
"extension": "c",
"filename": "list.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 10723524,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 949,
"license": "BSD-2-Clause-Views,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/list.c",
"provenance": "stackv2-0132.json.gz:86621",
"repo_name": "svetlin-mladenov/hercules",
"revision_date": "2015-11-29T17:04:59",
"revision_id": "ffbd50a4b6603eb4bfc3bf43f79c382a5a4b2f9e",
"snapshot_id": "c04e1c509f80361c3a9f9ab213d5cb8c9591bc80",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/svetlin-mladenov/hercules/ffbd50a4b6603eb4bfc3bf43f79c382a5a4b2f9e/src/list.c",
"visit_date": "2020-05-30T22:17:38.870314"
} | stackv2 | #include "cryad/list.h"
void cr_list_free(cr_list *l) {
l->dtor(l);
}
int cr_list_add(cr_list *l, void *element) {
return l->add(l, element);
}
int cr_list_add_first(cr_list *l, void *element) {
return l->add_first(l, element);
}
void *cr_list_at(cr_list *l, size_t index) {
return l->at(l, index);
}
void *cr_list_remove(cr_list *l, size_t index) {
return l->remove(l, index);
}
size_t cr_list_length(cr_list *l) {
return l->length(l);
}
void *cr_list_find(cr_list *l, void *trait, int (*comparator) (void *, void *)) {
return l->find(l, trait, comparator);
}
cr_list_iter *cr_list_iter_create(cr_list *l) {
return l->iter_create(l);
}
void cr_list_iter_next(cr_list_iter *iter) {
return iter->next(iter);
}
void *cr_list_iter_get(cr_list_iter *iter) {
return iter->get(iter);
}
bool cr_list_iter_past_end(cr_list_iter *iter) {
return iter->past_end(iter);
}
void cr_list_iter_free(cr_list_iter *iter) {
iter->dtor(iter);
}
| 2.75 | 3 |
2024-11-18T22:28:41.125471+00:00 | 2022-10-05T05:57:11 | cb2eef7914fadafbfbc5fac11d7d161e5b9ae5fd | {
"blob_id": "cb2eef7914fadafbfbc5fac11d7d161e5b9ae5fd",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-05T05:57:11",
"content_id": "ba170691d8c11c6bded339c6065180450adf11f9",
"detected_licenses": [
"MIT"
],
"directory_id": "96586c6dae294d48763a84328efae6c473c99cc4",
"extension": "h",
"filename": "semaphores.h",
"fork_events_count": 0,
"gha_created_at": "2020-06-11T09:59:38",
"gha_event_created_at": "2020-06-11T09:59:39",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 271511915,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3221,
"license": "MIT",
"license_type": "permissive",
"path": "/include/psp2kern/kernel/threadmgr/semaphores.h",
"provenance": "stackv2-0132.json.gz:86750",
"repo_name": "Rinnegatamante/vita-headers",
"revision_date": "2022-10-05T05:57:11",
"revision_id": "4bd4744f8aeef83019c93f4a4d95770148cf9a34",
"snapshot_id": "4603afbddddb5bafc702f1ad993470c4f066aa32",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Rinnegatamante/vita-headers/4bd4744f8aeef83019c93f4a4d95770148cf9a34/include/psp2kern/kernel/threadmgr/semaphores.h",
"visit_date": "2022-11-22T07:49:40.900230"
} | stackv2 | /**
* \kernelgroup{SceThreadMgr}
* \usage{psp2kern/kernel/threadmgr/semaphores.h,SceThreadmgrForDriver_stub}
*/
#ifndef _PSP2KERN_KERNEL_THREADMGR_SEMAPHORES_H_
#define _PSP2KERN_KERNEL_THREADMGR_SEMAPHORES_H_
#include <psp2kern/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Additional options used when creating semaphores. */
typedef struct SceKernelSemaOptParam {
/** Size of the ::SceKernelSemaOptParam structure. */
SceSize size;
} SceKernelSemaOptParam;
/** Current state of a semaphore.
* @see ksceKernelGetSemaInfo.
*/
typedef struct SceKernelSemaInfo {
/** Size of the ::SceKernelSemaInfo structure. */
SceSize size;
/** The UID of the semaphore */
SceUID semaId;
/** NUL-terminated name of the semaphore. */
char name[32];
/** Attributes. */
SceUInt attr;
/** The initial count the semaphore was created with. */
int initCount;
/** The current count. */
int currentCount;
/** The maximum count. */
int maxCount;
/** The number of threads waiting on the semaphore. */
int numWaitThreads;
} SceKernelSemaInfo;
/**
* Get semaphore info
*
* @param[in] semaid - The semaphore guid.
* @param[out] info - The info output buffer pointer.
*
* @return 0 on success, < 0 on error
*/
int ksceKernelGetSemaInfo(SceUID semaid, SceKernelSemaInfo *info);
/**
* Creates a new semaphore
*
* @par Example:
* @code
* int semaid;
* semaid = ksceKernelCreateSema("MySema", 0, 1, 1, NULL);
* @endcode
*
* @param name - Specifies the name of the sema
* @param attr - Sema attribute flags (normally set to 0)
* @param initVal - Sema initial value
* @param maxVal - Sema maximum value
* @param option - Sema options (normally set to 0)
* @return A semaphore id
*/
SceUID ksceKernelCreateSema(const char *name, SceUInt attr, int initVal, int maxVal, SceKernelSemaOptParam *option);
/**
* Destroy a semaphore
*
* @param semaid - The semaid returned from a previous create call.
* @return Returns the value 0 if it's successful, otherwise -1
*/
int ksceKernelDeleteSema(SceUID semaid);
/**
* Send a signal to a semaphore
*
* @par Example:
* @code
* // Signal the sema
* ksceKernelSignalSema(semaid, 1);
* @endcode
*
* @param semaid - The sema id returned from ::ksceKernelCreateSema
* @param signal - The amount to signal the sema (i.e. if 2 then increment the sema by 2)
*
* @return < 0 On error.
*/
int ksceKernelSignalSema(SceUID semaid, int signal);
/**
* Lock a semaphore
*
* @par Example:
* @code
* ksceKernelWaitSema(semaid, 1, NULL);
* @endcode
*
* @param semaid - The sema id returned from ::ksceKernelCreateSema
* @param signal - The value to wait for (i.e. if 1 then wait till reaches a signal state of 1)
* @param timeout - Timeout in microseconds (assumed).
*
* @return < 0 on error.
*/
int ksceKernelWaitSema(SceUID semaid, int signal, SceUInt *timeout);
/**
* Poll a semaphore.
*
* @param semaid - UID of the semaphore to poll.
* @param signal - The value to test for.
*
* @return < 0 on error.
*/
int ksceKernelPollSema(SceUID semaid, int signal);
#ifdef __cplusplus
}
#endif
#endif /* _PSP2KERN_KERNEL_THREADMGR_SEMAPHORES_H_ */
| 2.71875 | 3 |
2024-11-18T22:28:41.195222+00:00 | 2019-01-11T22:12:21 | a0aaf2259617effe056855bbee65d2144a6adf6e | {
"blob_id": "a0aaf2259617effe056855bbee65d2144a6adf6e",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-11T22:12:21",
"content_id": "1dfc921d6c5ad4e74790f3cc002c3414c48d3495",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "af4ee28eb323e75c47c396e7efe9e982a4c6de68",
"extension": "c",
"filename": "msgBuf.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 162578663,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 848,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/msgBuf.c",
"provenance": "stackv2-0132.json.gz:86881",
"repo_name": "djtremolo/thermit",
"revision_date": "2019-01-11T22:12:21",
"revision_id": "98919986fb8d030c60df304b59c86ace72389296",
"snapshot_id": "e935c92ccccb6eef18866792787479499d4952e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/djtremolo/thermit/98919986fb8d030c60df304b59c86ace72389296/msgBuf.c",
"visit_date": "2020-04-12T16:46:01.995905"
} | stackv2 | #include <stddef.h>
#include "msgBuf.h"
uint8_t msgLen(uint8_t *start, uint8_t *currentPosition)
{
size_t a = (size_t)start;
size_t b = (size_t)currentPosition;
return (uint8_t)(b - a);
}
void msgPutU16(uint8_t **buf, uint16_t val)
{
if(buf && *buf)
{
uint8_t *b = *buf;
*(b++) = (val & 0xFF);
*(b++) = ((val >> 8) & 0xFF);
*buf = b;
}
}
void msgPutU8(uint8_t **buf, uint8_t val)
{
if(buf && *buf)
{
uint8_t *b = *buf;
*(b++) = (val & 0xFF);
*buf = b;
}
}
uint16_t msgGetU16(uint8_t **buf)
{
uint16_t ret = 0;
if(buf && *buf)
{
uint8_t *b = *buf;
ret |= *(b++);
ret |= (*(b++)) << 8;
*buf = b;
}
return ret;
}
uint8_t msgGetU8(uint8_t **buf)
{
uint8_t ret = 0;
if(buf && *buf)
{
uint8_t *b = *buf;
ret |= *(b++);
*buf = b;
}
return ret;
}
| 2.609375 | 3 |
2024-11-18T22:28:41.595835+00:00 | 2019-12-15T23:04:24 | d6f08c2a42c54d64e95acf398821c6bce6d2cdce | {
"blob_id": "d6f08c2a42c54d64e95acf398821c6bce6d2cdce",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-15T23:04:24",
"content_id": "a9f60fd239323fe831253ca993e65de8eb67e5c8",
"detected_licenses": [
"MIT"
],
"directory_id": "366b6585fdd791f82148adbeb033b9972bae32d3",
"extension": "h",
"filename": "http_parse.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": 1409,
"license": "MIT",
"license_type": "permissive",
"path": "/hiku_gen3/marvell/wmsdk_bundle-3.3.33/sdk/src/incl/sdk/http_parse.h",
"provenance": "stackv2-0132.json.gz:87269",
"repo_name": "jayemko/hiku_fw",
"revision_date": "2019-12-15T23:04:24",
"revision_id": "43cbe4a084ba2880adf62515c3b8e932c98ba4ec",
"snapshot_id": "ae57b5128bf0d300f849e3c3a1252c390db6a38d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jayemko/hiku_fw/43cbe4a084ba2880adf62515c3b8e932c98ba4ec/hiku_gen3/marvell/wmsdk_bundle-3.3.33/sdk/src/incl/sdk/http_parse.h",
"visit_date": "2022-03-23T11:33:19.245267"
} | stackv2 | /*! \file http_parse.h
* \brief Common HTTP functions
*
* Copyright 2008-2015, Marvell International Ltd.
* All Rights Reserved.
*/
#ifndef __HTTP_PARSE_H__
#define __HTTP_PARSE_H__
#include <httpd.h>
/** Parse tag/value form elements present in HTTP POST body
*
* Given a tag this function will retrieve its value from the buffer and return
* it to the caller.
* \param[in] inbuf Pointer to NULL-terminated buffer that holds POST data
* \param[in] tag The tag to look for
* \param[out] val Buffer where the value will be copied to
* \param[in] val_len The length of the val buffer
*
*
* \return WM_SUCCESS when a valid tag is found, error otherwise
*/
int httpd_get_tag_from_post_data(char *inbuf, const char *tag,
char *val, unsigned val_len);
/** Parse tag/value form elements present in HTTP GET URL
*
* Given a tag this function will retrieve its value from the HTTP URL and
* return it to the caller.
* \param[in] req_p pointer to \ref httpd_request_t object
* \param[in] tag The tag to look for
* \param[out] val Buffer where the value will be copied to
* \param[in] val_len The length of the val buffer
*
* \return WM_SUCCESS when a valid tag is found, error otherwise
*/
int httpd_get_tag_from_url(httpd_request_t *req_p,
const char *tag,
char *val, unsigned val_len);
int htsys_getln_soc(int sd, char *data_p, int buflen);
#endif /* __HTTP_PARSE_H__ */
| 2.234375 | 2 |
2024-11-18T22:28:42.283566+00:00 | 2016-04-11T15:58:40 | 9d263d7587a11457db58196f117bfa7a5b6ecfc6 | {
"blob_id": "9d263d7587a11457db58196f117bfa7a5b6ecfc6",
"branch_name": "refs/heads/master",
"committer_date": "2016-04-11T15:58:40",
"content_id": "520939f717eced6b418285d39efb8117018f7065",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "46ac9e212bd09f75e3d955c5d5a45487931f8386",
"extension": "c",
"filename": "cvode_example.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 55985166,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10983,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/cvode/src/cvode_example.c",
"provenance": "stackv2-0132.json.gz:87917",
"repo_name": "bennihepp/HybridStochasticSimulation",
"revision_date": "2016-04-11T15:58:40",
"revision_id": "a19a777339be375a7301b69fbf1c0d840040e471",
"snapshot_id": "b5385442dbbe667d71d233232fd508e921591bc0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bennihepp/HybridStochasticSimulation/a19a777339be375a7301b69fbf1c0d840040e471/cvode/src/cvode_example.c",
"visit_date": "2020-12-31T06:46:17.097091"
} | stackv2 | /*
* -----------------------------------------------------------------
* $Revision: 1.2 $
* $Date: 2010/12/01 22:51:32 $
* -----------------------------------------------------------------
* Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and
* Radu Serban @ LLNL
* -----------------------------------------------------------------
* Example problem:
*
* The following is a simple example problem, with the coding
* needed for its solution by CVODE. The problem is from
* chemical kinetics, and consists of the following three rate
* equations:
* dy1/dt = -.04*y1 + 1.e4*y2*y3
* dy2/dt = .04*y1 - 1.e4*y2*y3 - 3.e7*(y2)^2
* dy3/dt = 3.e7*(y2)^2
* on the interval from t = 0.0 to t = 4.e10, with initial
* conditions: y1 = 1.0, y2 = y3 = 0. The problem is stiff.
* While integrating the system, we also use the rootfinding
* feature to find the points at which y1 = 1e-4 or at which
* y3 = 0.01. This program solves the problem with the BDF method,
* Newton iteration with the CVDENSE dense linear solver, and a
* user-supplied Jacobian routine.
* It uses a user-supplied function to compute the error weights
* required for the WRMS norm calculations.
* Output is printed in decades from t = .4 to t = 4.e10.
* Run statistics (optional outputs) are printed at the end.
* -----------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cvode/cvode.h> /* prototypes for CVODE fcts. and consts. */
#include <cvode/cvode_dense.h> /* prototype for CVDense */
#include <nvector/nvector_serial.h> /* serial N_Vector types, functions, and macros */
#include <sundials/sundials_dense.h> /* definitions DlsMat and DENSE_ELEM */
#include <sundials/sundials_types.h> /* definition of type realtype */
#include <sundials/sundials_math.h> /* definition of ABS */
/* User-defined vector and matrix accessor macros: Ith, IJth */
/* These macros are defined in order to write code which exactly matches
the mathematical problem description given above.
Ith(v,i) references the ith component of the vector v, where i is in
the range [1..NEQ] and NEQ is defined below. The Ith macro is defined
using the N_VIth macro in nvector.h. N_VIth numbers the components of
a vector starting from 0.
IJth(A,i,j) references the (i,j)th element of the dense matrix A, where
i and j are in the range [1..NEQ]. The IJth macro is defined using the
DENSE_ELEM macro in dense.h. DENSE_ELEM numbers rows and columns of a
dense matrix starting from 0. */
#define Ith(v,i) NV_Ith_S(v,i-1) /* Ith numbers components 1..NEQ */
#define IJth(A,i,j) DENSE_ELEM(A,i-1,j-1) /* IJth numbers rows,cols 1..NEQ */
/* Problem Constants */
#define Y1 RCONST(1.0) /* initial y components */
#define Y2 RCONST(0.0)
#define Y3 RCONST(0.0)
#define TMULT RCONST(10.0) /* output time factor */
#define NOUT 1001 /* number of output times */
/* Functions Called by the Solver */
static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data);
static int g(realtype t, N_Vector y, realtype *gout, void *user_data);
/* Private functions to output results */
static void PrintOutput(realtype t, realtype y1, realtype y2, realtype y3);
static void PrintRootInfo(int root_f1, int root_f2);
/* Private function to print final statistics */
static void PrintFinalStats(void *cvode_mem);
/* Private function to check function return values */
static int check_flag(void *flagvalue, char *funcname, int opt);
/*
*-------------------------------
* Main Program
*-------------------------------
*/
double last_y2;
int main()
{
int neq;
realtype t0, t1, dx, dy, reltol, abstol, umax;
realtype t, tout, dt;
N_Vector y;
void *cvode_mem;
int flag, flagr, iout;
int rootsfound[2];
t0 = 0.0;
t1 = 1e6;
neq = 3;
reltol = 1e-6;
abstol = 1e-6;
y = NULL;
cvode_mem = NULL;
dt = (t1 - t0) / NOUT;
/* Create serial vector of length NEQ for I.C. */
void* ydata = malloc(sizeof(realtype) * neq);
y = N_VMake_Serial(neq, ydata);
if (check_flag((void *)y, "N_VNew_Serial", 0)) return(1);
/* Initialize y */
Ith(y,1) = Y1;
Ith(y,2) = Y2;
Ith(y,3) = Y3;
/* Call CVodeCreate to create the solver memory and specify the
* Backward Differentiation Formula and the use of a Newton iteration */
cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);
if (check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1);
/* Call CVodeInit to initialize the integrator memory and specify the
* user's right hand side function in y'=f(t,y), the inital time T0, and
* the initial dependent variable vector y. */
t = t0;
flag = CVodeInit(cvode_mem, f, t, y);
if (check_flag(&flag, "CVodeInit", 1)) return(1);
/* Call CVodeSStolerances to specify the scalar relative tolerance
* and scalar absolute tolerance */
flag = CVodeSStolerances(cvode_mem, reltol, abstol);
if (check_flag(&flag, "CVodeSStolerances", 1)) return(1);
/* Call CVodeRootInit to specify the root function g with 2 components */
flag = CVodeRootInit(cvode_mem, 2, g);
if (check_flag(&flag, "CVodeRootInit", 1)) return(1);
/* Call CVDense to specify the CVDENSE dense linear solver */
flag = CVDense(cvode_mem, neq);
if (check_flag(&flag, "CVDense", 1)) return(1);
/* In loop, call CVode, print results, and test for error.
Break out of loop when NOUT preset output times have been reached. */
printf(" \n3-species kinetics problem\n\n");
iout = 0;
tout = t + dt;
clock_t start = clock();
int rootCnt = 0;
FILE* f = fopen("bla2.txt", "w");
if (f == NULL) {
perror("Unable to open file");
return -1;
}
last_y2 = Ith(y,2);
while(t < t1) {
flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL);
//PrintOutput(t, Ith(y,1), Ith(y,2), Ith(y,3));
if (flag == CV_ROOT_RETURN) {
flagr = CVodeGetRootInfo(cvode_mem, rootsfound);
check_flag(&flagr, "CVodeGetRootInfo", 1);
//PrintRootInfo(rootsfound[0],rootsfound[1]);
//fprintf(f, "ROOT:\t %f \t %f \t %f \t %f\n", t, Ith(y,1), Ith(y,2), Ith(y,3));
last_y2 = Ith(y,2);
Ith(y,1) += 1;
//printf("y3=%f\n", Ith(y,2));
rootCnt++;
flag = CVodeReInit(cvode_mem, t, y);
if (check_flag(&flag, "CVodeReInit", 1)) return(1);
}
else if (flag == CV_SUCCESS) {
iout++;
//fprintf(f, "OUT:\t %f \t %f \t %f \t %f\n", t, Ith(y,1), Ith(y,2), Ith(y,3));
//tout *= TMULT;
tout += dt;
}
//printf("tout=%f\n", tout);
if (check_flag(&flag, "CVode", 1)) break;
//if (iout == NOUT) break;
}
fclose(f);
clock_t end = clock();
double runtime = 1000.0 * (end - start) / (double)CLOCKS_PER_SEC;
printf("Execution time: %f\n", runtime);
printf("root count: %d\n", rootCnt);
/* Print some final statistics */
PrintFinalStats(cvode_mem);
/* Free y vector */
N_VDestroy_Serial(y);
/* Free integrator memory */
CVodeFree(&cvode_mem);
return(0);
}
/*
*-------------------------------
* Functions called by the solver
*-------------------------------
*/
/*
* f routine. Compute function f(t,y).
*/
static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data)
{
realtype y1, y2, y3, yd1, yd3;
y1 = Ith(y,1); y2 = Ith(y,2); y3 = Ith(y,3);
Ith(ydot,1) = -0.1*y1 + 50*y3 + 10;
Ith(ydot,2) = y1 * y2;
Ith(ydot,3) = y2 + y1 + 10;
Ith(ydot,1) = y3 + 1;
Ith(ydot,2) = 1;
Ith(ydot,3) = y2*y1 + 1;
Ith(ydot,1) = 1;
Ith(ydot,2) = 1;
Ith(ydot,3) = 1;
return(0);
}
/*
* g routine. Compute functions g_i(t,y) for i = 0,1.
*/
static int g(realtype t, N_Vector y, realtype *gout, void *user_data)
{
realtype y1, y3;
y1 = Ith(y,1); y3 = Ith(y,3);
gout[0] = y1 - RCONST(0.0001);
gout[0] = 0.5;
gout[1] = last_y2 + 1 - Ith(y,2);
return(0);
}
/*
*-------------------------------
* Private helper functions
*-------------------------------
*/
static void PrintOutput(realtype t, realtype y1, realtype y2, realtype y3)
{
#if defined(SUNDIALS_EXTENDED_PRECISION)
printf("At t = %0.4Le y =%14.6Le %14.6Le %14.6Le\n", t, y1, y2, y3);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
printf("At t = %0.4le y =%14.6le %14.6le %14.6le\n", t, y1, y2, y3);
#else
printf("At t = %0.4e y =%14.6e %14.6e %14.6e\n", t, y1, y2, y3);
#endif
return;
}
static void PrintRootInfo(int root_f1, int root_f2)
{
printf(" rootsfound[] = %3d %3d\n", root_f1, root_f2);
return;
}
/*
* Get and print some final statistics
*/
static void PrintFinalStats(void *cvode_mem)
{
long int nst, nfe, nsetups, nje, nfeLS, nni, ncfn, netf, nge;
int flag;
flag = CVodeGetNumSteps(cvode_mem, &nst);
check_flag(&flag, "CVodeGetNumSteps", 1);
flag = CVodeGetNumRhsEvals(cvode_mem, &nfe);
check_flag(&flag, "CVodeGetNumRhsEvals", 1);
flag = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);
check_flag(&flag, "CVodeGetNumLinSolvSetups", 1);
flag = CVodeGetNumErrTestFails(cvode_mem, &netf);
check_flag(&flag, "CVodeGetNumErrTestFails", 1);
flag = CVodeGetNumNonlinSolvIters(cvode_mem, &nni);
check_flag(&flag, "CVodeGetNumNonlinSolvIters", 1);
flag = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);
check_flag(&flag, "CVodeGetNumNonlinSolvConvFails", 1);
flag = CVDlsGetNumJacEvals(cvode_mem, &nje);
check_flag(&flag, "CVDlsGetNumJacEvals", 1);
flag = CVDlsGetNumRhsEvals(cvode_mem, &nfeLS);
check_flag(&flag, "CVDlsGetNumRhsEvals", 1);
flag = CVodeGetNumGEvals(cvode_mem, &nge);
check_flag(&flag, "CVodeGetNumGEvals", 1);
printf("\nFinal Statistics:\n");
printf("nst = %-6ld nfe = %-6ld nsetups = %-6ld nfeLS = %-6ld nje = %ld\n",
nst, nfe, nsetups, nfeLS, nje);
printf("nni = %-6ld ncfn = %-6ld netf = %-6ld nge = %ld\n \n",
nni, ncfn, netf, nge);
}
/*
* Check function return value...
* opt == 0 means SUNDIALS function allocates memory so check if
* returned NULL pointer
* opt == 1 means SUNDIALS function returns a flag so check if
* flag >= 0
* opt == 2 means function allocates memory so check if returned
* NULL pointer
*/
static int check_flag(void *flagvalue, char *funcname, int opt)
{
int *errflag;
/* Check if SUNDIALS function returned NULL pointer - no memory allocated */
if (opt == 0 && flagvalue == NULL) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
/* Check if flag < 0 */
else if (opt == 1) {
errflag = (int *) flagvalue;
if (*errflag < 0) {
fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n",
funcname, *errflag);
return(1); }}
/* Check if function returned NULL pointer - no memory allocated */
else if (opt == 2 && flagvalue == NULL) {
fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n",
funcname);
return(1); }
return(0);
}
| 2.484375 | 2 |
2024-11-18T22:28:42.488254+00:00 | 2020-10-03T03:27:03 | 6ef19afc05fe1a058a7162dc2d0d70b81cbf420f | {
"blob_id": "6ef19afc05fe1a058a7162dc2d0d70b81cbf420f",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-03T03:27:03",
"content_id": "a6ca37dcc4e2e48edc84f7373e447b229f1f80e8",
"detected_licenses": [
"MIT"
],
"directory_id": "90d0ee13138ad995183b5ad9ab885a4abefed968",
"extension": "c",
"filename": "heli.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 291368277,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1222,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/Heli/heli/heli.c",
"provenance": "stackv2-0132.json.gz:88176",
"repo_name": "JosiahCraw/Tiva-Helicopter-Controller-ENCE464-",
"revision_date": "2020-10-03T03:27:03",
"revision_id": "207fda18bf8e4b562e47205fbbdc9aaaf274c54f",
"snapshot_id": "7f4cb18b1ba0243ecd20a33680b98bf20aa9f79e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JosiahCraw/Tiva-Helicopter-Controller-ENCE464-/207fda18bf8e4b562e47205fbbdc9aaaf274c54f/lib/Heli/heli/heli.c",
"visit_date": "2022-12-24T12:05:19.383122"
} | stackv2 | /**
* heli.c - Heli initialiser
*
* Authors: Jos Craw, Josh Hulbert, Harry Dobbs
*
* Last Modified : 21.08.2020
*/
#include <stdint.h>
#include <stdbool.h>
#include <utils/ustdlib.h>
#include <driverlib/pin_map.h>
#include <driverlib/sysctl.h>
#include "logging.h"
#include "yaw.h"
#include "height.h"
#include "heli.h"
#include "rotors.h"
#include "plot.h"
#include "OrbitOLEDInterface.h"
void init_clocks(void) {
SysCtlClockSet (SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_16MHZ);
}
void heli_init(void) {
init_clocks();
log_init();
#if ENABLE_XSS == 1
// Delay to ensure the webpage is receiving serial
SysCtlDelay(SysCtlClockGet()/6);
// Send script tag for the JavaScript loader
uart_send(HELI_XSS_LOADER);
/*
* Delay to ensure that the UART stream is not cutoff by the webpage as
* the UART buffer is only cleared every half second.
*/
SysCtlDelay(SysCtlClockGet()/6);
#endif
initButtons();
init_yaw();
init_height();
init_pwm();
OLEDInitialise();
#if ENABLE_PLOTTING == 1
init_plot();
#endif
IntMasterEnable();
}
| 2 | 2 |
2024-11-18T22:28:42.562993+00:00 | 2015-10-10T03:10:12 | d7c8415c14bf07f3dd58429c788b6776d4e59995 | {
"blob_id": "d7c8415c14bf07f3dd58429c788b6776d4e59995",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-10T03:10:12",
"content_id": "43ff082b132287fd16297f0f0b5e3917aba495ee",
"detected_licenses": [
"Apache-2.0",
"PostgreSQL"
],
"directory_id": "cb8e59744cec10f4833b2d67f3b0b67b0335dac0",
"extension": "c",
"filename": "stack.c",
"fork_events_count": 0,
"gha_created_at": "2015-10-10T04:18:24",
"gha_event_created_at": "2015-10-10T04:18:24",
"gha_language": null,
"gha_license_id": null,
"github_id": 43993714,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1177,
"license": "Apache-2.0,PostgreSQL",
"license_type": "permissive",
"path": "/src/backend/nodes/stack.c",
"provenance": "stackv2-0132.json.gz:88306",
"repo_name": "jiny2/incubator-hawq",
"revision_date": "2015-10-10T03:10:12",
"revision_id": "d6ac62b7c4569e9320e395beaa04db24e9e3b011",
"snapshot_id": "4349937b90e3883202a4d7ffe7335d35b0d78a48",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jiny2/incubator-hawq/d6ac62b7c4569e9320e395beaa04db24e9e3b011/src/backend/nodes/stack.c",
"visit_date": "2021-01-15T19:13:09.913306"
} | stackv2 | /*-------------------------------------------------------------------------
*
* Stack.h
*
* Implements a Stack of objects using lists
*-------------------------------------------------------------------------
*/
#include "nodes/stack.h"
#include "postgres.h"
/**
* Initializes the stack.
*/
void Init(Stack *st)
{
Assert(st);
st->containerList = NULL;
}
/**
* Is stack empty?
*/
bool IsEmpty(Stack *st)
{
return (st->containerList == NULL);
}
/**
* Push element onto stack.
*/
void Push(Stack *st, void *element)
{
Assert(st);
st->containerList = lcons(element, st->containerList);
Assert(st->containerList);
}
/**
* Pop an element from a non-empty stack. Should be called on empty stack.
* Returns:
* returns element
*/
void* Pop(Stack *st)
{
Assert(st);
Assert(!IsEmpty(st));
void *v = lfirst(list_head(st->containerList));
st->containerList = list_delete_first(st->containerList);
return v;
}
/**
* Peek at top element from a non-empty stack. Should be called on empty stack.
* Returns:
* returns element
*/
void* Peek(Stack *st)
{
Assert(st);
Assert(!IsEmpty(st));
void *v = lfirst(list_head(st->containerList));
return v;
}
| 2.953125 | 3 |
2024-11-18T22:28:42.649369+00:00 | 2018-09-03T03:38:13 | 35274cae54a1e8f0e31f39d426ac5939ad6ffad9 | {
"blob_id": "35274cae54a1e8f0e31f39d426ac5939ad6ffad9",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-03T03:38:13",
"content_id": "f9a71f145f8a02f326fc79a0e00b21704c3ebe45",
"detected_licenses": [
"MIT"
],
"directory_id": "df7ec2cfe5a1e6c6b50e0e3b8bc838f1aef2591b",
"extension": "h",
"filename": "killfirst.h",
"fork_events_count": 2,
"gha_created_at": "2017-09-16T07:16:28",
"gha_event_created_at": "2017-12-17T16:24:29",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 103733375,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3085,
"license": "MIT",
"license_type": "permissive",
"path": "/gobang/src/killfirst.h",
"provenance": "stackv2-0132.json.gz:88435",
"repo_name": "AugustusWillisWang/C-learning",
"revision_date": "2018-09-03T03:38:13",
"revision_id": "bd1b29fe0ef3df120686e0db5a9962c49ae1a4a5",
"snapshot_id": "6357e385bd14aaf55331482882acb03905dcf7df",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/AugustusWillisWang/C-learning/bd1b29fe0ef3df120686e0db5a9962c49ae1a4a5/gobang/src/killfirst.h",
"visit_date": "2018-11-17T17:39:14.573672"
} | stackv2 | // Copyright (c) 2017-2018 Augustus Wang
// VCF 连续冲4/活三取胜判断
#ifndef _KILLFIRST_H
#define _KILLFIRST_H
#include "support.h"
#include "weight.h"
// #define KILLSEARCH 4
int TestKillPoint(int a, int b)
{
if (board[a][b])
return 0;
//--------------1
int i = 1;
int incolor = Board(a - 1, b - 1);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a - i, b - i)) && i <= 5)
i++;
if (i >= 4)
return 1;
}
//--------------2
i = 1;
incolor = Board(a - 1, b + 1);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a - i, b + i)) && i <= 5)
i++;
if (i >= 4)
return 1;
}
//--------------3
i = 1;
incolor = Board(a + 1, b - 1);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a + i, b - i)) && i <= 5)
i++;
if (i >= 4)
return 1;
}
//--------------4
i = 1;
incolor = Board(a + 1, b + 1);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a + i, b + i)) && i <= 5)
i++;
if (i >= 4)
return 1;
}
//--------------5
i = 1;
incolor = Board(a, b - 1);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a, b - i)) && i <= 5)
i++;
if (i >= 4)
return 1;
}
//--------------6
i = 1;
incolor = Board(a - 1, b);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a - i, b)) && i <= 5)
i++;
if (i >= 4)
return 1;
}
//--------------7
i = 1;
incolor = Board(a + 1, b);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a + i, b)) && (i <= 5))
i++;
if (i >= 4)
return 1;
}
//--------------8
i = 1;
incolor = Board(a, b + 1);
if (incolor == BLACK || incolor == WHITE)
{
while ((incolor == Board(a, b + i)) && (i <= 5))
i++;
if (i >= 4)
return 1;
}
return 0;
}
int killboard[BOUNDRY][BOUNDRY];
int onekillmove[BOUNDRY][BOUNDRY];
int haveonekill = 0;
int TestOneStepKill(int colornow)
{
haveonekill = 0;
memset(onekillmove, 0, sizeof(onekillmove));
struct fbd_weight result;
for (int a = 0; a < BOUNDRY; a++)
{
for (int b = 0; b < BOUNDRY; b++)
{
if (board[a][b] == 0)
{
board[a][b] = colornow;
result = UpdateFBDWeight(a, b, 0);
board[a][b] = 0;
if (result.fbd == 0)
{
if (Abs(result.weight) > 800)
{
haveonekill = 1;
onekillmove[a][b] = 1;
}
}
}
}
}
}
// int UpdateKillBoard(int a, int b, int color){
// killboard[a][b] = 0;
// }
#endif | 2.296875 | 2 |
2024-11-18T22:28:42.778564+00:00 | 2021-11-03T02:16:27 | 085717b02a9495baa66438879ea618ba82e64483 | {
"blob_id": "085717b02a9495baa66438879ea618ba82e64483",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-03T02:16:27",
"content_id": "4c299e712156884808d6d0a1292bcacba5cc7562",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "dd6027d7b986d62d0b9d35a07ce62c1d62d378b5",
"extension": "c",
"filename": "queue.c",
"fork_events_count": 0,
"gha_created_at": "2021-08-23T22:14:23",
"gha_event_created_at": "2021-11-03T01:12:57",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 399261593,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1589,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Kernel/queue.c",
"provenance": "stackv2-0132.json.gz:88564",
"repo_name": "BraveJero/bareOS",
"revision_date": "2021-11-03T02:16:27",
"revision_id": "b1f3634a219cb2dddcc3c1b238541304361ce8dc",
"snapshot_id": "c2eac8778c3054fe5eb271f8d47a9d4243b9c6f1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/BraveJero/bareOS/b1f3634a219cb2dddcc3c1b238541304361ce8dc/Kernel/queue.c",
"visit_date": "2023-09-05T06:02:58.503321"
} | stackv2 | // This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include <queue.h>
typedef struct node {
elemType elem;
struct node *next;
} Node;
typedef struct QueueCDT {
uint8_t size;
Node *first, *last;
} QueueCDT;
Queue newQueue(void) {
Queue ans = alloc(sizeof(QueueCDT));
if (ans == NULL) {
return ans;
}
ans->size = 0;
ans->first = ans->last = NULL;
return ans;
}
int push(Queue queue, elemType elem) {
if (queue == NULL) {
return -1;
}
Node *newNode = alloc(sizeof(Node));
if (newNode == NULL) {
return -1;
}
newNode->elem = elem;
newNode->next = NULL;
if (queue->first == NULL) {
queue->first = queue->last = newNode;
} else {
queue->last->next = newNode;
queue->last = newNode;
}
return ++queue->size;
}
elemType pop(Queue queue) {
if (queue == NULL || queue->first == NULL) {
return -1;
}
elemType elem = queue->first->elem;
if (queue->first == queue->last) {
queue->last = NULL;
}
Node *aux = queue->first;
queue->first = queue->first->next;
free(aux);
queue->size--;
return elem;
}
uint8_t queueSize(Queue queue) { return queue == NULL ? 0 : queue->size; }
uint8_t isEmpty(Queue queue) { return queue == NULL ? 1 : queue->size == 0; }
void printQueue(Queue queue) {
ncPrint("{");
if (queue == NULL) {
ncPrint("}");
return;
}
Node *aux = queue->first;
while (aux != NULL) {
ncPrintDec(aux->elem);
ncPrint(", ");
aux = aux->next;
}
ncPrint("}");
}
| 2.78125 | 3 |
2024-11-18T22:28:43.261491+00:00 | 2015-04-21T01:24:21 | a01f608aac9d9922d1108cf18bea0bdd34830bc9 | {
"blob_id": "a01f608aac9d9922d1108cf18bea0bdd34830bc9",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-21T01:24:21",
"content_id": "a246d1602de8d8d9ab735313ba81f3744c18fb04",
"detected_licenses": [
"MIT"
],
"directory_id": "24332a7e22252c44a63e2919feebb4151856fc15",
"extension": "c",
"filename": "tcp_server.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3996,
"license": "MIT",
"license_type": "permissive",
"path": "/tcp_server.c",
"provenance": "stackv2-0132.json.gz:88954",
"repo_name": "zhguanxian/tcp_server_client_demo",
"revision_date": "2015-04-21T01:24:21",
"revision_id": "6f10b920e5a38a14dca8291eabb017b182fd74fa",
"snapshot_id": "7713103e5b5885bf7000ec468d925cb396fe92d8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhguanxian/tcp_server_client_demo/6f10b920e5a38a14dca8291eabb017b182fd74fa/tcp_server.c",
"visit_date": "2023-03-19T04:58:56.970088"
} | stackv2 | /**
* license-c.c
* create by Wenva.
*
* MIT licence follows:
*
* Copyright (C) 2014 Wenva <lvyexuwenfa100@126.com>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/select.h>
void sigint_handle(int sig);
int socket_init();
void socket_deinit(int fd);
void socket_process(int clientfd);
void socket_accept(int fd);
unsigned char quit = 0;
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("Usage: %s <Listen Port>\n", argv[0]);
return -1;
}
signal(SIGINT, sigint_handle);
int listenfd = socket_init(atoi(argv[1]));
if (listenfd < 0) {
exit(-1);
}
socket_accept(listenfd);
socket_deinit(listenfd);
return 0;
}
void sigint_handle(int sig) {
quit = 1;
}
int socket_init(int port) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
printf("socket create failed.\n");
goto _error;
}
//reuse address
int opt = SO_REUSEADDR;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
//bind
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
printf("socket bind failed.\n");
goto _error;
}
//listen
if(listen(fd, 10) < 0) {
printf("socket listen failed.\n");
goto _error;
}
return fd;
_error:
socket_deinit(fd);
return -1;
}
void socket_accept(int fd) {
struct sockaddr_in client_addr;
socklen_t addrlen;
fd_set fds;
struct timeval timeout = {3, 0};
while (!quit) {
FD_ZERO(&fds);
FD_SET(fd, &fds);
int ret = select(fd+1, &fds, &fds, NULL, &timeout);
if (ret < 0) {
break;
} else if (ret == 0) {
continue;
} else {
int clientfd = accept(fd, (struct sockaddr*)&client_addr, &addrlen);
if (clientfd < 0) {
printf("socket accept failed.\n");
break;
}
printf("Accept: %s:%d\n", inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port));
socket_process(clientfd);
}
}
}
static void* thread_proc(void* arg) {
int clientfd = (int)arg;
if (clientfd < 0) return NULL;
send(clientfd, "Welcome", 8, 0);
close(clientfd);
return NULL;
}
void socket_process(int clientfd) {
pthread_t pid;
int error = pthread_create(&pid, NULL, thread_proc, (void*)clientfd);
if (error) {
printf("pthread create failed:%d\n", error);
}
}
void socket_deinit(int fd) {
if (fd >= 0) close(fd);
}
| 2.578125 | 3 |
2024-11-18T22:28:43.322565+00:00 | 2018-07-15T23:57:48 | 057d33aa0bbd8c1f2363018935e0f0915b616f2f | {
"blob_id": "057d33aa0bbd8c1f2363018935e0f0915b616f2f",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-15T23:57:48",
"content_id": "24ac53242b671ff565a210f7f82aaaf8949f0a56",
"detected_licenses": [
"MIT"
],
"directory_id": "abf1c4eb9911341538777f4a975ed4823391d639",
"extension": "c",
"filename": "core.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": 60742,
"license": "MIT",
"license_type": "permissive",
"path": "/cno/core.c",
"provenance": "stackv2-0132.json.gz:89083",
"repo_name": "seafitliu/libcno",
"revision_date": "2018-07-15T23:57:48",
"revision_id": "12dae58580a59a42bf84a2f5543a667c833efed4",
"snapshot_id": "91abe42e17ccc346f6ee916af60418d9a9411d8f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/seafitliu/libcno/12dae58580a59a42bf84a2f5543a667c833efed4/cno/core.c",
"visit_date": "2020-03-23T06:57:56.386620"
} | stackv2 | #include <ctype.h>
#include <stdio.h>
#include "core.h"
#include "../picohttpparser/picohttpparser.h"
static inline uint8_t read1(const uint8_t *p) { return p[0]; }
static inline uint16_t read2(const uint8_t *p) { return p[0] << 8 | p[1]; }
static inline uint32_t read4(const uint8_t *p) { return p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; }
static inline uint32_t read3(const uint8_t *p) { return read4(p) >> 8; }
/* construct a stack-allocated array of bytes in place. expands to (pointer, length) */
#define PACK(...) (char *) (uint8_t []) { __VA_ARGS__ }, sizeof((uint8_t []) { __VA_ARGS__ })
#define I8(x) x
#define I16(x) x >> 8, x
#define I24(x) x >> 16, x >> 8, x
#define I32(x) x >> 24, x >> 16, x >> 8, x
/* fake http "request" sent by the client at the beginning of a connection */
static const struct cno_buffer_t CNO_PREFACE = { "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", 24 };
/* standard-defined pre-initial-SETTINGS values */
static const struct cno_settings_t CNO_SETTINGS_STANDARD = {{{ 4096, 1, -1, 65535, 16384, -1 }}};
/* a somewhat more conservative version assumed to be used by the remote side at first */
static const struct cno_settings_t CNO_SETTINGS_CONSERVATIVE = {{{ 4096, 1, 100, 65535, 16384, -1 }}};
/* actual values to send in the first SETTINGS frame */
static const struct cno_settings_t CNO_SETTINGS_INITIAL = {{{ 4096, 1, 1024, 65535, 16384, -1 }}};
static int cno_stream_is_local(const struct cno_connection_t *conn, uint32_t id)
{
return id % 2 == conn->client;
}
/* each stream carries a single request-response pair, plus push promises.
*
* local:: 1 (== CNO_LOCAL) if this side is initiating the stream.
*
* throws::
*
* INVALID_STREAM if stream id is unacceptable.
* WOULD_BLOCK if this side has initiated too many streams.
* TRANSPORT if the other side has initiated too many streams.
* NO_MEMORY streams are heap-allocated
*
*/
static struct cno_stream_t * cno_stream_new(struct cno_connection_t *conn, uint32_t id, int local)
{
if (cno_stream_is_local(conn, id) != local)
return CNO_ERROR_NULL(INVALID_STREAM, "incorrect parity");
if (cno_connection_is_http2(conn)) {
if (id <= conn->last_stream[local])
return CNO_ERROR_NULL(INVALID_STREAM, "nonmonotonic");
} else if (id != 1) {
return CNO_ERROR_NULL(INVALID_STREAM, "HTTP/1.x has only one stream");
}
if (conn->stream_count[local] >= conn->settings[!local].max_concurrent_streams)
return local ? CNO_ERROR_NULL(WOULD_BLOCK, "wait for on_stream_end")
: CNO_ERROR_NULL(TRANSPORT, "peer exceeded stream limit");
struct cno_stream_t *stream = malloc(sizeof(struct cno_stream_t));
if (!stream)
return CNO_ERROR_NULL(NO_MEMORY, "%zu bytes", sizeof(struct cno_stream_t));
*stream = (struct cno_stream_t) {
.id = conn->last_stream[local] = id,
.next = conn->streams[id % CNO_STREAM_BUCKETS],
.window_recv = conn->settings[CNO_LOCAL] .initial_window_size,
.window_send = conn->settings[CNO_REMOTE].initial_window_size,
};
conn->streams[id % CNO_STREAM_BUCKETS] = stream;
conn->stream_count[local]++;
if (CNO_FIRE(conn, on_stream_start, id)) {
conn->streams[id % CNO_STREAM_BUCKETS] = stream->next;
conn->stream_count[local]--;
free(stream);
return CNO_ERROR_UP_NULL();
}
return stream;
}
static struct cno_stream_t * cno_stream_find(const struct cno_connection_t *conn, uint32_t id)
{
struct cno_stream_t *s = conn->streams[id % CNO_STREAM_BUCKETS];
while (s && s->id != id) s = s->next;
return s;
}
static void cno_stream_free(struct cno_connection_t *conn, struct cno_stream_t *stream)
{
conn->stream_count[cno_stream_is_local(conn, stream->id)]--;
struct cno_stream_t **s = &conn->streams[stream->id % CNO_STREAM_BUCKETS];
while (*s != stream) s = &(*s)->next;
*s = stream->next;
free(stream);
}
static int cno_stream_rst(struct cno_connection_t *conn, struct cno_stream_t *stream)
{
uint32_t id = stream->id;
cno_stream_free(conn, stream);
return CNO_FIRE(conn, on_stream_end, id);
}
/* send a single non-flow-controlled frame, splitting DATA/HEADERS if they are too big.
*
* throws::
*
* ASSERTION if a non-DATA frame exceeds the size limit (how)
* ASSERTION if a padded frame exceeds the size limit (FIXME)
*
*/
static int cno_frame_write(const struct cno_connection_t *conn,
const struct cno_frame_t *frame)
{
size_t length = frame->payload.size;
size_t limit = conn->settings[CNO_REMOTE].max_frame_size;
if (length <= limit) {
if (CNO_FIRE(conn, on_frame_send, frame))
return CNO_ERROR_UP();
if (CNO_FIRE(conn, on_write, PACK(I24(length), I8(frame->type), I8(frame->flags), I32(frame->stream))))
return CNO_ERROR_UP();
if (length)
return CNO_FIRE(conn, on_write, frame->payload.data, length);
return CNO_OK;
}
int carry_on_last = CNO_FLAG_END_HEADERS;
if (frame->flags & CNO_FLAG_PADDED)
return CNO_ERROR(ASSERTION, "don't know how to split padded frames");
else if (frame->type == CNO_FRAME_DATA)
carry_on_last = CNO_FLAG_END_STREAM;
else if (frame->type != CNO_FRAME_HEADERS && frame->type != CNO_FRAME_PUSH_PROMISE)
return CNO_ERROR(ASSERTION, "control frame too big");
struct cno_frame_t part = *frame;
part.flags &= ~carry_on_last;
part.payload.size = limit;
while (length > limit) {
if (cno_frame_write(conn, &part))
return CNO_ERROR_UP();
length -= limit;
part.flags &= ~(CNO_FLAG_PRIORITY | CNO_FLAG_END_STREAM);
part.payload.data += limit;
if (part.type != CNO_FRAME_DATA)
part.type = CNO_FRAME_CONTINUATION;
}
part.flags |= frame->flags & carry_on_last;
part.payload.size = length;
return cno_frame_write(conn, &part);
}
static int cno_frame_write_settings(const struct cno_connection_t *conn,
const struct cno_settings_t *previous,
const struct cno_settings_t *current)
{
size_t i = 0;
uint8_t payload[CNO_SETTINGS_UNDEFINED - 1][6], (*ptr)[6] = payload;
const uint32_t *ax = previous->array;
const uint32_t *bx = current->array;
for (; ++i < CNO_SETTINGS_UNDEFINED; ++ax, ++bx) {
if (*ax != *bx) {
struct cno_buffer_t buf = { PACK(I16(i), I32(*bx)) };
memcpy(ptr++, buf.data, buf.size);
}
}
struct cno_frame_t frame = { CNO_FRAME_SETTINGS, 0, 0, { (char *) payload, (ptr - payload) * 6 } };
return cno_frame_write(conn, &frame);
}
static int cno_stream_rst_by_local(struct cno_connection_t *conn, struct cno_stream_t *stream)
{
#if CNO_STREAM_RESET_HISTORY
conn->recently_reset[conn->recently_reset_next++] = stream->id;
conn->recently_reset_next %= CNO_STREAM_RESET_HISTORY;
#endif
return cno_stream_rst(conn, stream);
}
static int cno_frame_write_rst_stream(struct cno_connection_t *conn,
struct cno_stream_t *stream,
uint32_t /* enum CNO_RST_STREAM_CODE */ code)
{
struct cno_frame_t error = { CNO_FRAME_RST_STREAM, 0, stream->id, { PACK(I32(code)) } };
if (cno_frame_write(conn, &error))
return CNO_ERROR_UP();
if (!(stream->accept & CNO_ACCEPT_HEADERS))
// since headers were already handled, this stream can be safely destroyed.
// i sure hope there are no trailers, though.
return cno_stream_rst_by_local(conn, stream);
// still have to decompress headers to maintain shared compression state.
// FIXME headers may never arrive if the peer receives RST_STREAM before sending them.
stream->accept &= ~CNO_ACCEPT_OUTBOUND;
stream->accept |= CNO_ACCEPT_NOP_HEADERS;
return CNO_OK;
}
static int cno_frame_write_goaway(struct cno_connection_t *conn,
uint32_t /* enum CNO_RST_STREAM_CODE */ code)
{
if (conn->goaway_sent)
conn->goaway_sent = conn->last_stream[CNO_REMOTE];
struct cno_frame_t error = { CNO_FRAME_GOAWAY, 0, 0, { PACK(I32(conn->goaway_sent), I32(code)) } };
return cno_frame_write(conn, &error);
}
/* shut down a connection and *then* throw a TRANSPORT error. */
#define cno_frame_write_error(conn, type, ...) \
(cno_frame_write_goaway(conn, type) ? CNO_ERROR_UP() : CNO_ERROR(TRANSPORT, __VA_ARGS__))
static int cno_frame_handle_end_stream(struct cno_connection_t *conn,
struct cno_stream_t *stream)
{
// don't move below the event. it may call write_{message,data} and destroy the stream.
int half_open = (stream->accept &= ~CNO_ACCEPT_INBOUND) != 0;
if (CNO_FIRE(conn, on_message_end, stream->id))
return CNO_ERROR_UP();
if (half_open)
return CNO_OK;
return cno_stream_rst(conn, stream);
}
static int cno_frame_handle_message(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame,
struct cno_message_t *msg)
{
int is_response = conn->client && !conn->continued_promise;
struct cno_header_t *it = msg->headers;
struct cno_header_t *end = msg->headers + msg->headers_len;
int has_scheme = 0;
// >HTTP/2 uses special pseudo-header fields beginning with ':' character
// >(ASCII 0x3a) [to convey the target URI, ...]
while (it != end && cno_buffer_startswith(it->name, CNO_BUFFER_STRING(":")))
++it;
struct cno_header_t *first_non_pseudo = it;
struct cno_header_t *into = it;
while (it-- != msg->headers) {
if (stream->accept & CNO_ACCEPT_TRAILERS)
// >Pseudo-header fields MUST NOT appear in trailers.
goto invalid_message;
if (is_response) {
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING(":status"))) {
if (msg->code)
goto invalid_message;
for (const char *p = it->value.data; p != it->value.data + it->value.size; p++) {
if (*p < '0' || '9' < *p)
goto invalid_message;
msg->code = msg->code * 10 + (*p - '0');
}
continue;
}
} else {
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING(":path"))) {
if (msg->path.data)
goto invalid_message;
msg->path = it->value;
continue;
}
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING(":method"))) {
if (msg->method.data)
goto invalid_message;
msg->method = it->value;
continue;
}
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING(":authority")))
goto save_header;
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING(":scheme"))) {
if (has_scheme)
goto invalid_message;
has_scheme = 1;
goto save_header;
}
}
// >Endpoints MUST NOT generate pseudo-header fields other than those defined in this document.
goto invalid_message;
save_header:
// parsed headers get removed; that way the message can be passed right back
// into `cno_write_message` of a different connection.
if (it != --into) {
struct cno_header_t tmp;
memmove(&tmp, it, sizeof(struct cno_header_t));
memmove(it, into, sizeof(struct cno_header_t));
memmove(into, &tmp, sizeof(struct cno_header_t));
}
}
msg->headers_len -= (into - msg->headers);
msg->headers = into;
for (it = first_non_pseudo; it != end; ++it) {
// >All pseudo-header fields MUST appear in the header block
// >before regular header fields.
if (cno_buffer_startswith(it->name, CNO_BUFFER_STRING(":")))
goto invalid_message;
// >However, header field names MUST be converted to lowercase
// >prior to their encoding in HTTP/2.
for (const char *p = it->name.data; p != it->name.data + it->name.size; p++)
if ('A' <= *p && *p <= 'Z')
goto invalid_message;
// TODO
// >HTTP/2 does not use the Connection header field to indicate
// >connection-specific header fields.
}
if (stream->accept & CNO_ACCEPT_TRAILERS) {
if (!(frame->flags & CNO_FLAG_END_STREAM))
// there is no data after trailers.
goto invalid_message;
stream->accept &= ~CNO_ACCEPT_INBOUND;
if (CNO_FIRE(conn, on_message_trail, stream->id, msg))
return CNO_ERROR_UP();
return cno_frame_handle_end_stream(conn, stream);
}
// TODO support CONNECT?
if (is_response ? !msg->code : (!msg->path.data || !msg->path.size || !msg->method.data || !msg->method.size || !has_scheme))
// >All HTTP/2 requests MUST include exactly one valid value for the :method, :scheme,
// >and :path pseudo-header fields, unless it is a CONNECT request (Section 8.3).
goto invalid_message;
if (conn->continued_promise)
// accept pushes even on reset streams.
return CNO_FIRE(conn, on_message_push, stream->id, msg, conn->continued_stream);
stream->accept &= ~CNO_ACCEPT_HEADERS;
stream->accept |= CNO_ACCEPT_TRAILERS | CNO_ACCEPT_DATA;
if (stream->accept & CNO_ACCEPT_NOP_HEADERS)
// hpack compression is now in sync, there's no use for this stream anymore.
return cno_stream_rst_by_local(conn, stream);
if (CNO_FIRE(conn, on_message_start, stream->id, msg))
return CNO_ERROR_UP();
if (frame->flags & CNO_FLAG_END_STREAM)
return cno_frame_handle_end_stream(conn, stream);
return CNO_OK;
invalid_message:
return cno_frame_write_rst_stream(conn, stream, CNO_RST_PROTOCOL_ERROR);
}
static int cno_frame_handle_end_headers(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
struct cno_header_t headers[CNO_MAX_HEADERS];
size_t count = CNO_MAX_HEADERS;
if (cno_hpack_decode(&conn->decoder, conn->continued.as_static, headers, &count)) {
cno_buffer_dyn_clear(&conn->continued);
cno_frame_write_goaway(conn, CNO_RST_COMPRESSION_ERROR);
return CNO_ERROR_UP();
}
struct cno_message_t msg = { 0, CNO_BUFFER_EMPTY, CNO_BUFFER_EMPTY, headers, count };
int failed = cno_frame_handle_message(conn, stream, frame, &msg);
for (size_t i = 0; i < count; i++)
cno_hpack_free_header(&headers[i]);
cno_buffer_dyn_clear(&conn->continued);
conn->continued = CNO_BUFFER_DYN_EMPTY;
conn->continued_stream = 0;
conn->continued_promise = 0;
return failed;
}
static int cno_frame_handle_padding(struct cno_connection_t *conn, struct cno_frame_t *frame)
{
if (frame->flags & CNO_FLAG_PADDED) {
if (frame->payload.size == 0)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "no padding found");
size_t padding = read1((const uint8_t *) frame->payload.data) + 1;
if (padding > frame->payload.size)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "more padding than data");
frame->payload.data += 1;
frame->payload.size -= padding;
}
return CNO_OK;
}
static int cno_frame_handle_priority_prefix(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
const uint32_t target = read4((const uint8_t *) frame->payload.data) & 0x7FFFFFFFUL;
if (target == frame->stream) {
if (stream)
return cno_frame_write_rst_stream(conn, stream, CNO_RST_PROTOCOL_ERROR);
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "PRIORITY depends on itself");
}
// TODO implement prioritization
return CNO_OK;
}
static int cno_frame_handle_headers(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
if (cno_frame_handle_padding(conn, frame))
return CNO_ERROR_UP();
if (stream == NULL) {
if (conn->client)
// servers cannot initiate streams.
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "unexpected HEADERS");
stream = cno_stream_new(conn, frame->stream, CNO_REMOTE);
if (stream == NULL)
return CNO_ERROR_UP();
stream->accept = CNO_ACCEPT_HEADERS | CNO_ACCEPT_WRITE_HEADERS | CNO_ACCEPT_WRITE_PUSH;
}
if (stream->accept & CNO_ACCEPT_TRAILERS) {
stream->accept &= ~CNO_ACCEPT_DATA;
if (!(frame->flags & CNO_FLAG_END_STREAM))
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "trailers without END_STREAM");
}
else if (!(stream->accept & CNO_ACCEPT_HEADERS))
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "unexpected HEADERS");
if (frame->flags & CNO_FLAG_PRIORITY) {
if (frame->payload.size < 5)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "no priority spec");
if (cno_frame_handle_priority_prefix(conn, stream, frame))
return CNO_ERROR_UP();
frame->payload.data += 5;
frame->payload.size -= 5;
}
conn->continued_flags = frame->flags & CNO_FLAG_END_STREAM;
conn->continued_stream = stream->id;
if (cno_buffer_dyn_concat(&conn->continued, frame->payload))
// no need to cleanup -- compression errors are non-recoverable,
// everything will be destroyed along with the connection.
return CNO_ERROR_UP();
if (frame->flags & CNO_FLAG_END_HEADERS)
return cno_frame_handle_end_headers(conn, stream, frame);
return CNO_OK;
}
static int cno_frame_handle_push_promise(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
if (cno_frame_handle_padding(conn, frame))
return CNO_ERROR_UP();
if (!conn->settings[CNO_LOCAL].enable_push || !stream || !(stream->accept & CNO_ACCEPT_PUSH))
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "unexpected PUSH_PROMISE");
if (frame->payload.size < 4)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "PUSH_PROMISE too short");
uint32_t promised = read4((const uint8_t *) frame->payload.data);
struct cno_stream_t *child = cno_stream_new(conn, promised, CNO_REMOTE);
if (child == NULL)
return CNO_ERROR_UP();
child->accept = CNO_ACCEPT_HEADERS;
conn->continued_flags = 0; // PUSH_PROMISE cannot have END_STREAM
conn->continued_stream = stream->id;
conn->continued_promise = promised;
if (cno_buffer_dyn_concat(&conn->continued, (struct cno_buffer_t) { frame->payload.data + 4,
frame->payload.size - 4 }))
// a compression error. unrecoverable.
return CNO_ERROR_UP();
if (frame->flags & CNO_FLAG_END_HEADERS)
return cno_frame_handle_end_headers(conn, child, frame);
return CNO_OK;
}
static int cno_frame_handle_continuation(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
if (!stream || !conn->continued_stream)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "unexpected CONTINUATION");
// we don't actually count CONTINUATIONs, but this is an ok estimate.
size_t max_buf_size = (CNO_MAX_CONTINUATIONS + 1) * conn->settings[CNO_LOCAL].max_frame_size;
if (frame->payload.size + conn->continued.size > max_buf_size)
// finally a chance to use that error code.
return cno_frame_write_error(conn, CNO_RST_ENHANCE_YOUR_CALM, "too many HEADERS");
if (cno_buffer_dyn_concat(&conn->continued, frame->payload))
return CNO_ERROR_UP();
frame->flags |= conn->continued_flags;
if (frame->flags & CNO_FLAG_END_HEADERS)
return cno_frame_handle_end_headers(conn, stream, frame);
return CNO_OK;
}
/* ignore non-HEADERS frames on reset streams, as the spec requires. unfortunately,
these are indistinguishable from streams that were never opened, but hey, what
can i do, keep a set of uint32_t-s? memory doesn't grow on trees, you know. */
static int cno_frame_handle_invalid_stream(struct cno_connection_t *conn,
struct cno_frame_t *frame)
{
if (frame->stream && frame->stream <= conn->last_stream[cno_stream_is_local(conn, frame->stream)])
#if CNO_STREAM_RESET_HISTORY
for (uint8_t i = 0; i < CNO_STREAM_RESET_HISTORY; i++)
if (conn->recently_reset[i] == frame->stream)
#endif
return CNO_OK;
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "invalid stream");
}
static int cno_frame_handle_data(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
uint32_t length = frame->payload.size;
if (cno_frame_handle_padding(conn, frame))
return CNO_ERROR_UP();
if (length) {
// TODO allow manual connection flow control?
struct cno_frame_t update = { CNO_FRAME_WINDOW_UPDATE, 0, 0, { PACK(I32(length)) } };
if (cno_frame_write(conn, &update))
return CNO_ERROR_UP();
}
if (!stream)
return cno_frame_handle_invalid_stream(conn, frame);
if (!(stream->accept & CNO_ACCEPT_DATA))
return cno_frame_write_rst_stream(conn, stream, CNO_RST_STREAM_CLOSED);
if (CNO_FIRE(conn, on_message_data, frame->stream, frame->payload.data, frame->payload.size))
return CNO_ERROR_UP();
if (frame->flags & CNO_FLAG_END_STREAM)
return cno_frame_handle_end_stream(conn, stream);
if (!length || (conn->flags & CNO_CONN_FLAG_MANUAL_FLOW_CONTROL))
return CNO_OK;
struct cno_frame_t update = { CNO_FRAME_WINDOW_UPDATE, 0, stream->id, { PACK(I32(length)) } };
return cno_frame_write(conn, &update);
}
static int cno_frame_handle_ping(struct cno_connection_t *conn,
struct cno_stream_t *stream __attribute__((unused)),
struct cno_frame_t *frame)
{
if (frame->stream)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "PING on a stream");
if (frame->payload.size != 8)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "bad PING frame");
if (frame->flags & CNO_FLAG_ACK)
return CNO_FIRE(conn, on_pong, frame->payload.data);
struct cno_frame_t response = { CNO_FRAME_PING, CNO_FLAG_ACK, 0, frame->payload };
return cno_frame_write(conn, &response);
}
static int cno_frame_handle_goaway(struct cno_connection_t *conn,
struct cno_stream_t *stream __attribute__((unused)),
struct cno_frame_t *frame)
{
if (frame->stream)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "GOAWAY on a stream");
if (frame->payload.size < 8)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "bad GOAWAY");
const uint32_t error = read4((const uint8_t *) frame->payload.data + 4);
if (error != CNO_RST_NO_ERROR)
return CNO_ERROR(TRANSPORT, "disconnected with error %u", error);
// TODO: clean shutdown: reject all streams higher than indicated in the frame
return CNO_ERROR(DISCONNECT, "disconnected");
}
static int cno_frame_handle_rst_stream(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
if (!stream)
return cno_frame_handle_invalid_stream(conn, frame);
if (frame->payload.size != 4)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "bad RST_STREAM");
// TODO parse the error code and do something with it.
return cno_stream_rst(conn, stream);
}
static int cno_frame_handle_priority(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
if (!frame->stream)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "PRIORITY on stream 0");
if (frame->payload.size != 5)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "bad PRIORITY");
return cno_frame_handle_priority_prefix(conn, stream, frame);
}
static int cno_frame_handle_settings(struct cno_connection_t *conn,
struct cno_stream_t *stream __attribute__((unused)),
struct cno_frame_t *frame)
{
if (frame->stream)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "SETTINGS on a stream");
if (frame->flags & CNO_FLAG_ACK) {
if (frame->payload.size)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "bad SETTINGS ack");
return CNO_OK;
}
if (frame->payload.size % 6)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "bad SETTINGS");
struct cno_settings_t *cfg = &conn->settings[CNO_REMOTE];
const uint8_t *ptr = (const uint8_t *) frame->payload.data;
const uint8_t *end = (const uint8_t *) frame->payload.data + frame->payload.size;
for (; ptr != end; ptr += 6) {
uint16_t setting = read2(ptr);
uint32_t value = read4(ptr + 2);
if (setting && setting < CNO_SETTINGS_UNDEFINED)
cfg->array[setting - 1] = value;
}
if (cfg->enable_push > 1)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "enable_push out of bounds");
if (cfg->initial_window_size > 0x7fffffffL)
return cno_frame_write_error(conn, CNO_RST_FLOW_CONTROL_ERROR,
"initial_window_size out of bounds");
if (cfg->max_frame_size < 16384 || cfg->max_frame_size > 16777215)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "max_frame_size out of bounds");
conn->encoder.limit_upper = cfg->header_table_size;
cno_hpack_setlimit(&conn->encoder, conn->encoder.limit_upper);
// TODO update stream flow control windows.
struct cno_frame_t ack = { CNO_FRAME_SETTINGS, CNO_FLAG_ACK, 0, CNO_BUFFER_EMPTY };
if (cno_frame_write(conn, &ack))
return CNO_ERROR_UP();
return CNO_FIRE(conn, on_settings);
}
static int cno_frame_handle_window_update(struct cno_connection_t *conn,
struct cno_stream_t *stream,
struct cno_frame_t *frame)
{
if (frame->payload.size != 4)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "bad WINDOW_UPDATE");
uint32_t increment = read4((const uint8_t *) frame->payload.data);
if (increment == 0 || increment > 0x7fffffffL)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "window increment out of bounds");
if (!frame->stream) {
if (conn->window_send > 0x7fffffffL - (int32_t) increment)
return cno_frame_write_error(conn, CNO_RST_FLOW_CONTROL_ERROR, "window increment too big");
conn->window_send += increment;
} else {
if (stream == NULL)
return cno_frame_handle_invalid_stream(conn, frame);
if (stream->window_send > 0x7fffffffL - (int32_t) increment)
return cno_frame_write_rst_stream(conn, stream, CNO_RST_FLOW_CONTROL_ERROR);
stream->window_send += increment;
}
return CNO_FIRE(conn, on_flow_increase, frame->stream);
}
typedef int cno_frame_handler_t(struct cno_connection_t *,
struct cno_stream_t *,
struct cno_frame_t *);
static cno_frame_handler_t *CNO_FRAME_HANDLERS[] = {
// should be synced to enum CNO_FRAME_TYPE.
&cno_frame_handle_data,
&cno_frame_handle_headers,
&cno_frame_handle_priority,
&cno_frame_handle_rst_stream,
&cno_frame_handle_settings,
&cno_frame_handle_push_promise,
&cno_frame_handle_ping,
&cno_frame_handle_goaway,
&cno_frame_handle_window_update,
&cno_frame_handle_continuation,
};
static int cno_frame_handle(struct cno_connection_t *conn, struct cno_frame_t *frame)
{
if (conn->continued_stream)
if (frame->type != CNO_FRAME_CONTINUATION || frame->stream != conn->continued_stream)
return cno_frame_write_error(conn, CNO_RST_PROTOCOL_ERROR, "expected a CONTINUATION");
if (frame->type >= CNO_FRAME_UNKNOWN)
return CNO_OK;
struct cno_stream_t *stream = cno_stream_find(conn, frame->stream);
return CNO_FRAME_HANDLERS[frame->type](conn, stream, frame);
}
int cno_connection_set_config(struct cno_connection_t *conn, const struct cno_settings_t *settings)
{
if (settings->enable_push != 0 && settings->enable_push != 1)
return CNO_ERROR(ASSERTION, "enable_push neither 0 nor 1");
if (settings->max_frame_size < 16384 || settings->max_frame_size > 16777215)
return CNO_ERROR(ASSERTION, "maximum frame size out of bounds (2^14..2^24-1)");
if (conn->state != CNO_CONNECTION_INIT && cno_connection_is_http2(conn))
// If not yet in HTTP2 mode, `cno_connection_upgrade` will send the SETTINGS frame.
if (cno_frame_write_settings(conn, &conn->settings[CNO_LOCAL], settings))
return CNO_ERROR_UP();
memcpy(&conn->settings[CNO_LOCAL], settings, sizeof(*settings));
conn->decoder.limit_upper = settings->header_table_size;
// TODO the difference in initial flow control window size should be subtracted
// from the flow control window size of all active streams.
return CNO_OK;
}
void cno_connection_init(struct cno_connection_t *conn, enum CNO_CONNECTION_KIND kind)
{
*conn = (struct cno_connection_t) {
.client = CNO_CLIENT == kind,
.state = CNO_CONNECTION_UNDEFINED,
.window_recv = CNO_SETTINGS_STANDARD.initial_window_size,
.window_send = CNO_SETTINGS_STANDARD.initial_window_size,
.settings = { /* remote = */ CNO_SETTINGS_CONSERVATIVE,
/* local = */ CNO_SETTINGS_INITIAL, },
};
cno_hpack_init(&conn->decoder, CNO_SETTINGS_INITIAL .header_table_size);
cno_hpack_init(&conn->encoder, CNO_SETTINGS_STANDARD.header_table_size);
}
void cno_connection_reset(struct cno_connection_t *conn)
{
cno_buffer_dyn_clear(&conn->buffer);
cno_buffer_dyn_clear(&conn->continued);
cno_hpack_clear(&conn->encoder);
cno_hpack_clear(&conn->decoder);
for (int i = 0; i < CNO_STREAM_BUCKETS; i++)
while (conn->streams[i])
cno_stream_free(conn, conn->streams[i]);
}
int cno_connection_is_http2(struct cno_connection_t *conn)
{
return conn->state == CNO_CONNECTION_INIT ||
conn->state == CNO_CONNECTION_PREFACE ||
conn->state == CNO_CONNECTION_READY ||
conn->state == CNO_CONNECTION_READY_NO_SETTINGS ||
conn->state == CNO_CONNECTION_HTTP1_READING_UPGRADE;
}
static int cno_connection_upgrade(struct cno_connection_t *conn)
{
if (conn->client && CNO_FIRE(conn, on_write, CNO_PREFACE.data, CNO_PREFACE.size))
return CNO_ERROR_UP();
return cno_frame_write_settings(conn, &CNO_SETTINGS_STANDARD, &conn->settings[CNO_LOCAL]);
}
static int cno_connection_proceed(struct cno_connection_t *conn)
{
while (1) switch (conn->state) {
case CNO_CONNECTION_UNDEFINED: {
return CNO_OK; // wait until connection_made before processing data
}
case CNO_CONNECTION_HTTP1_READY: {
{ // ignore leading crlf-s.
char *buf = conn->buffer.data;
char *end = conn->buffer.size + buf;
while (buf != end && (*buf == '\r' || *buf == '\n')) ++buf;
cno_buffer_dyn_shift(&conn->buffer, buf - conn->buffer.data);
}
if (!conn->buffer.size)
return CNO_OK;
struct cno_stream_t *stream = cno_stream_find(conn, 1);
if (conn->client) {
if (!stream || !(stream->accept & CNO_ACCEPT_HEADERS))
return CNO_ERROR(TRANSPORT, "server sent an HTTP/1.x response, but there was no request");
} else {
if (!stream) {
stream = cno_stream_new(conn, 1, CNO_REMOTE);
if (!stream)
return CNO_ERROR_UP();
stream->accept = CNO_ACCEPT_HEADERS;
}
if (!(stream->accept & CNO_ACCEPT_HEADERS))
return CNO_ERROR(WOULD_BLOCK, "already handling an HTTP/1.x message");
}
// the http 2 client preface looks like an http 1 request, but is not.
// picohttpparser will reject it. (note: CNO_PREFACE is null-terminated.)
if (!conn->client && !(conn->flags & CNO_CONN_FLAG_DISALLOW_H2_PRIOR_KNOWLEDGE)
&& !strncmp(conn->buffer.data, CNO_PREFACE.data, conn->buffer.size)) {
if (conn->buffer.size < CNO_PREFACE.size)
return CNO_OK;
conn->state = CNO_CONNECTION_INIT;
conn->last_stream[CNO_REMOTE] = 0;
conn->last_stream[CNO_LOCAL] = 0;
if (cno_stream_rst(conn, stream))
return CNO_ERROR_UP();
break;
}
struct cno_message_t msg = { 0, CNO_BUFFER_EMPTY, CNO_BUFFER_EMPTY, NULL, CNO_MAX_HEADERS };
struct phr_header headers_phr[CNO_MAX_HEADERS];
int minor;
int ok = conn->client
? phr_parse_response(conn->buffer.data, conn->buffer.size, &minor, &msg.code,
&msg.method.data, &msg.method.size,
headers_phr, &msg.headers_len, 1)
: phr_parse_request(conn->buffer.data, conn->buffer.size,
&msg.method.data, &msg.method.size,
&msg.path.data, &msg.path.size,
&minor, headers_phr, &msg.headers_len, 1);
if (ok == -2) {
if (conn->buffer.size > CNO_MAX_CONTINUATIONS * conn->settings[CNO_LOCAL].max_frame_size)
return CNO_ERROR(TRANSPORT, "HTTP/1.x message too big");
return CNO_OK;
}
if (ok == -1)
return CNO_ERROR(TRANSPORT, "bad HTTP/1.x message");
if (minor != 0 && minor != 1)
return CNO_ERROR(TRANSPORT, "HTTP/1.%d not supported", minor);
if (!conn->client)
msg.headers_len++; // for :scheme
struct cno_header_t headers[msg.headers_len];
struct cno_header_t *it = msg.headers = headers;
if (!conn->client)
*it++ = (struct cno_header_t) { CNO_BUFFER_STRING(":scheme"), CNO_BUFFER_STRING("unknown"), 0 };
conn->http1_remaining = 0;
for (size_t i = 0; i < msg.headers_len - !conn->client; i++, it++) {
*it = (struct cno_header_t) {
{ headers_phr[i].name, headers_phr[i].name_len },
{ headers_phr[i].value, headers_phr[i].value_len },
0
};
{
char * ptr = (char *) it->name.data;
char * end = (char *) it->name.data + it->name.size;
for (; ptr != end; ptr++) *ptr = tolower(*ptr);
}
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING("http2-settings"))) {
// TODO decode & emit on_frame
} else
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING("upgrade"))) {
if (conn->state != CNO_CONNECTION_HTTP1_READY)
continue;
if (!cno_buffer_eq(it->value, CNO_BUFFER_STRING("h2c"))) {
if (conn->client) {
if (msg.code == 101)
conn->state = CNO_CONNECTION_UNKNOWN_PROTOCOL;
} else {
// if the application definitely does not support upgrading to anything else, prefer h2c
if (conn->on_upgrade)
conn->state = CNO_CONNECTION_UNKNOWN_PROTOCOL_UPGRADE;
}
continue;
}
// TODO: client-side h2 upgrade
if (conn->client || conn->flags & CNO_CONN_FLAG_DISALLOW_H2_UPGRADE)
continue;
struct cno_header_t upgrade_headers[] = {
{ CNO_BUFFER_STRING("connection"), CNO_BUFFER_STRING("upgrade"), 0 },
{ CNO_BUFFER_STRING("upgrade"), CNO_BUFFER_STRING("h2c"), 0 },
};
struct cno_message_t upgrade_msg = { 101, CNO_BUFFER_EMPTY, CNO_BUFFER_EMPTY, upgrade_headers, 2 };
// if we send the preface now, we'll be able to send HTTP 2 frames
// while in the HTTP1_READING_UPGRADE state.
if (cno_write_message(conn, 1, &upgrade_msg, 1) || cno_connection_upgrade(conn))
return CNO_ERROR_UP();
// technically, server should refuse if HTTP2-Settings are not present.
// we'll let this slide.
conn->state = CNO_CONNECTION_HTTP1_READING_UPGRADE;
} else
// payload handling may look a bit complicated, so here's what the standard says:
// 1. presence of a body in a request is indicated by transfer-encoding/content-length.
// 2. HEAD, 1xx, 204, 304 responses never have bodies; the rest do.
// FIXME the "HEAD" part is not implemented
if (conn->client && ((100 <= msg.code && msg.code < 200) || msg.code == 204 || msg.code == 304)) {
continue;
} else
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING("content-length"))) {
// 3. content-length is unique, and mutually exclusive with transfer-encoding
if (conn->http1_remaining)
return CNO_ERROR(TRANSPORT, "bad HTTP/1.x message: multiple content-lengths");
for (const char *ptr = it->value.data, *end = ptr + it->value.size; ptr != end; ptr++) {
if (*ptr < '0' || '9' < *ptr)
return CNO_ERROR(TRANSPORT, "bad HTTP/1.x message: non-int length");
conn->http1_remaining = conn->http1_remaining * 10 + (*ptr - '0');
}
} else
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING("transfer-encoding"))) {
// 4. any non-identity transfer-encoding requires chunked (which should also be
// listed; we don't check for that and simply fail on parsing the format instead)
if (!cno_buffer_eq(it->value, CNO_BUFFER_STRING("identity")))
conn->http1_remaining = (uint32_t) -1;
} else
if (cno_buffer_eq(it->name, CNO_BUFFER_STRING("host"))) {
it->name = CNO_BUFFER_STRING(":authority");
}
}
// even if there's no payload -- the automaton will (almost) instantly switch back:
stream->accept &= ~CNO_ACCEPT_HEADERS;
stream->accept |= CNO_ACCEPT_DATA;
if (!conn->client)
stream->accept |= CNO_ACCEPT_WRITE_HEADERS;
if (conn->state == CNO_CONNECTION_HTTP1_READY)
conn->state = CNO_CONNECTION_HTTP1_READING;
cno_buffer_dyn_shift(&conn->buffer, (size_t) ok);
if (CNO_FIRE(conn, on_message_start, stream->id, &msg))
return CNO_ERROR_UP();
break;
}
case CNO_CONNECTION_HTTP1_READING:
case CNO_CONNECTION_HTTP1_READING_UPGRADE: {
struct cno_stream_t *stream = cno_stream_find(conn, 1);
if (!stream)
return CNO_ERROR(ASSERTION, "connection in HTTP/1.x mode but stream 1 does not exist");
if (!(stream->accept & CNO_ACCEPT_DATA))
return CNO_ERROR(ASSERTION, "connection expects HTTP/1.x message body, but stream 1 does not");
if (!conn->http1_remaining) {
// if still writable, `cno_write_message`/`cno_write_data` will reset it.
conn->state = conn->state == CNO_CONNECTION_HTTP1_READING_UPGRADE
? CNO_CONNECTION_PREFACE
: CNO_CONNECTION_HTTP1_READY;
if (CNO_FIRE(conn, on_message_end, stream->id))
return CNO_ERROR_UP();
if (!(stream->accept &= ~CNO_ACCEPT_INBOUND) && cno_stream_rst(conn, stream))
return CNO_ERROR_UP();
break;
}
if (!conn->buffer.size)
return CNO_OK;
if (conn->http1_remaining == (uint32_t) -1) {
char *eol = memchr(conn->buffer.data, '\n', conn->buffer.size);
if (eol++ == NULL)
return CNO_OK;
char *end_of_length;
size_t length = strtoul(conn->buffer.data, &end_of_length, 16);
if (end_of_length == conn->buffer.data || end_of_length + 2 != eol)
return CNO_ERROR(TRANSPORT, "HTTP/1.x chunked encoding parse error");
size_t total = length + (eol - conn->buffer.data) + 2; // + crlf after data
if (conn->buffer.size < total)
return CNO_OK;
if (conn->buffer.data[total - 2] != '\r' || conn->buffer.data[total - 1] != '\n')
return CNO_ERROR(TRANSPORT, "HTTP/1.x chunked encoding parse error");
cno_buffer_dyn_shift(&conn->buffer, total);
if (!length)
conn->http1_remaining = 0;
else if (CNO_FIRE(conn, on_message_data, stream->id, eol, length))
return CNO_ERROR_UP();
break;
}
struct cno_buffer_t b = conn->buffer.as_static;
if (b.size > conn->http1_remaining)
b.size = conn->http1_remaining;
conn->http1_remaining -= b.size;
cno_buffer_dyn_shift(&conn->buffer, b.size);
if (CNO_FIRE(conn, on_message_data, stream->id, b.data, b.size))
return CNO_ERROR_UP();
break;
}
case CNO_CONNECTION_UNKNOWN_PROTOCOL_UPGRADE: {
if (CNO_FIRE(conn, on_upgrade))
return CNO_ERROR_UP();
// might've sent 101 and switched to the next state as a result
if (conn->state == CNO_CONNECTION_UNKNOWN_PROTOCOL_UPGRADE)
conn->state = CNO_CONNECTION_HTTP1_READING;
break;
}
case CNO_CONNECTION_UNKNOWN_PROTOCOL: {
if (!conn->buffer.size)
return CNO_OK;
struct cno_buffer_t b = conn->buffer.as_static;
cno_buffer_dyn_shift(&conn->buffer, b.size);
if (CNO_FIRE(conn, on_message_data, 1, b.data, b.size))
return CNO_ERROR_UP();
break;
}
case CNO_CONNECTION_INIT: {
conn->state = CNO_CONNECTION_PREFACE;
if (cno_connection_upgrade(conn))
return CNO_ERROR_UP();
break;
}
case CNO_CONNECTION_PREFACE: {
if (!conn->client) {
if (conn->buffer.size < CNO_PREFACE.size)
return CNO_OK;
if (strncmp(conn->buffer.data, CNO_PREFACE.data, CNO_PREFACE.size))
return CNO_ERROR(TRANSPORT, "invalid HTTP 2 client preface");
cno_buffer_dyn_shift(&conn->buffer, CNO_PREFACE.size);
}
conn->state = CNO_CONNECTION_READY_NO_SETTINGS;
break;
}
case CNO_CONNECTION_READY_NO_SETTINGS:
case CNO_CONNECTION_READY: {
if (conn->buffer.size < 9)
return CNO_OK;
const uint8_t *base = (const uint8_t *) conn->buffer.data;
const size_t m = read3(base);
if (m > conn->settings[CNO_LOCAL].max_frame_size)
return cno_frame_write_error(conn, CNO_RST_FRAME_SIZE_ERROR, "frame too big");
if (conn->buffer.size < 9 + m)
return CNO_OK;
struct cno_frame_t frame = { read1(&base[3]), read1(&base[4]), read4(&base[5]), { (const char *) &base[9], m } };
frame.stream &= 0x7FFFFFFFUL; // clear the reserved bit
if (conn->state == CNO_CONNECTION_READY_NO_SETTINGS && frame.type != CNO_FRAME_SETTINGS)
return CNO_ERROR(TRANSPORT, "invalid HTTP 2 preface: no initial SETTINGS");
conn->state = CNO_CONNECTION_READY;
cno_buffer_dyn_shift(&conn->buffer, 9 + m);
// FIXME should at least decompress headers, probably
if (!conn->goaway_sent || frame.stream <= conn->goaway_sent)
if (CNO_FIRE(conn, on_frame, &frame) || cno_frame_handle(conn, &frame))
return CNO_ERROR_UP();
break;
}
}
}
int cno_connection_made(struct cno_connection_t *conn, enum CNO_HTTP_VERSION version)
{
if (conn->state != CNO_CONNECTION_UNDEFINED)
return CNO_ERROR(ASSERTION, "called connection_made twice");
conn->state = version == CNO_HTTP2 ? CNO_CONNECTION_INIT : CNO_CONNECTION_HTTP1_READY;
return cno_connection_proceed(conn);
}
int cno_connection_data_received(struct cno_connection_t *conn, const char *data, size_t length)
{
if (conn->state == CNO_CONNECTION_UNDEFINED)
return CNO_ERROR(DISCONNECT, "connection closed");
if (cno_buffer_dyn_concat(&conn->buffer, (struct cno_buffer_t) { data, length }))
return CNO_ERROR_UP();
return cno_connection_proceed(conn);
}
int cno_connection_stop(struct cno_connection_t *conn)
{
return cno_write_reset(conn, 0, CNO_RST_NO_ERROR);
}
int cno_connection_lost(struct cno_connection_t *conn)
{
if (!cno_connection_is_http2(conn)) {
struct cno_stream_t * stream = cno_stream_find(conn, 1);
if (stream) {
if (conn->state == CNO_CONNECTION_UNKNOWN_PROTOCOL) {
if (CNO_FIRE(conn, on_message_end, 1))
return CNO_ERROR_UP();
} else if (stream->accept & CNO_ACCEPT_DATA) { // the other side did not finish writing the body
return CNO_ERROR(TRANSPORT, "unclean http/1.x termination");
}
// if still writable, `cno_write_message`/`cno_write_data` will reset the stream
if (!(stream->accept &= ~CNO_ACCEPT_INBOUND) && cno_stream_rst(conn, stream))
return CNO_ERROR_UP();
}
return CNO_OK;
}
conn->state = CNO_CONNECTION_UNDEFINED;
for (struct cno_stream_t **s = &conn->streams[0]; s != &conn->streams[CNO_STREAM_BUCKETS]; s++)
while (*s)
if (cno_stream_rst(conn, *s))
return CNO_ERROR_UP();
return CNO_OK;
}
uint32_t cno_connection_next_stream(struct cno_connection_t *conn)
{
if (!cno_connection_is_http2(conn))
return 1;
uint32_t last = conn->last_stream[CNO_LOCAL];
return conn->client && !last ? 1 : last + 2;
}
int cno_write_reset(struct cno_connection_t *conn, uint32_t stream, enum CNO_RST_STREAM_CODE code)
{
if (!cno_connection_is_http2(conn)) {
if (!stream && code == CNO_RST_NO_ERROR)
return CNO_OK;
struct cno_stream_t *obj = cno_stream_find(conn, 1);
if (obj && cno_stream_rst(conn, obj))
return CNO_ERROR_UP();
return CNO_ERROR(DISCONNECT, "HTTP/1.x connection rejected");
}
if (!stream)
return cno_frame_write_goaway(conn, code);
struct cno_stream_t *obj = cno_stream_find(conn, stream);
return obj ? cno_frame_write_rst_stream(conn, obj, code) : CNO_OK; // assume idle streams have already been reset
}
int cno_write_push(struct cno_connection_t *conn, uint32_t stream, const struct cno_message_t *msg)
{
if (conn->state == CNO_CONNECTION_UNDEFINED)
return CNO_ERROR(DISCONNECT, "connection closed");
if (conn->client)
return CNO_ERROR(ASSERTION, "clients can't push");
if (!cno_connection_is_http2(conn) || !conn->settings[CNO_REMOTE].enable_push)
return CNO_OK;
struct cno_stream_t *streamobj = cno_stream_find(conn, stream);
if (streamobj == NULL)
return CNO_ERROR(INVALID_STREAM, "push to a nonexistent stream");
if (!(streamobj->accept & CNO_ACCEPT_WRITE_PUSH))
return CNO_OK; // pushed requests are safe, so whether we send one doesn't matter
uint32_t child = cno_connection_next_stream(conn);
struct cno_stream_t *childobj = cno_stream_new(conn, child, CNO_LOCAL);
if (childobj == NULL)
return CNO_ERROR_UP();
childobj->accept = CNO_ACCEPT_WRITE_HEADERS;
struct cno_buffer_dyn_t payload = CNO_BUFFER_DYN_EMPTY;
struct cno_frame_t frame = { CNO_FRAME_PUSH_PROMISE, CNO_FLAG_END_HEADERS, stream, CNO_BUFFER_EMPTY };
struct cno_header_t head[2] = {
{ CNO_BUFFER_STRING(":method"), msg->method, 0 },
{ CNO_BUFFER_STRING(":path"), msg->path, 0 },
};
if (cno_buffer_dyn_concat(&payload, (struct cno_buffer_t) { PACK(I32(child)) })
|| cno_hpack_encode(&conn->encoder, &payload, head, 2)
|| cno_hpack_encode(&conn->encoder, &payload, msg->headers, msg->headers_len))
return cno_buffer_dyn_clear(&payload), CNO_ERROR_UP();
frame.payload = payload.as_static;
if (cno_frame_write(conn, &frame))
return cno_buffer_dyn_clear(&payload), CNO_ERROR_UP();
cno_buffer_dyn_clear(&payload);
return CNO_FIRE(conn, on_message_start, child, msg) || CNO_FIRE(conn, on_message_end, child);
}
static int cno_discard_remaining_payload(struct cno_connection_t *conn, struct cno_stream_t *streamobj)
{
if (!(streamobj->accept &= ~CNO_ACCEPT_OUTBOUND))
return cno_stream_rst_by_local(conn, streamobj);
if (!conn->client && cno_connection_is_http2(conn) && cno_frame_write_rst_stream(conn, streamobj, CNO_RST_NO_ERROR))
return CNO_ERROR_UP();
return CNO_OK;
}
int cno_write_message(struct cno_connection_t *conn, uint32_t stream, const struct cno_message_t *msg, int final)
{
if (conn->state == CNO_CONNECTION_UNDEFINED)
return CNO_ERROR(DISCONNECT, "connection closed");
int is_informational = 100 <= msg->code && msg->code < 200;
if (is_informational && final)
return CNO_ERROR(ASSERTION, "1xx codes cannot end the stream");
struct cno_stream_t *streamobj = cno_stream_find(conn, stream);
if (conn->client) {
if (streamobj == NULL) {
streamobj = cno_stream_new(conn, stream, CNO_LOCAL);
if (streamobj == NULL)
return CNO_ERROR_UP();
streamobj->accept = CNO_ACCEPT_HEADERS | CNO_ACCEPT_PUSH | CNO_ACCEPT_WRITE_HEADERS;
}
if (!cno_connection_is_http2(conn) && !(streamobj->accept & CNO_ACCEPT_WRITE_HEADERS))
return CNO_ERROR(WOULD_BLOCK, "HTTP/1.x request already in progress");
} else {
if (!streamobj || !(streamobj->accept & CNO_ACCEPT_WRITE_HEADERS))
return CNO_ERROR(INVALID_STREAM, "this stream is not writable");
}
if (!cno_connection_is_http2(conn)) {
char buffer[CNO_MAX_HTTP1_HEADER_SIZE + 3];
int size;
if (conn->client)
size = snprintf(buffer, sizeof(buffer), "%.*s %.*s HTTP/1.1\r\n",
(int) msg->method.size, msg->method.data,
(int) msg->path.size, msg->path.data);
else
size = snprintf(buffer, sizeof(buffer), "HTTP/1.1 %d Something\r\n", msg->code);
if (size > CNO_MAX_HTTP1_HEADER_SIZE)
return CNO_ERROR(ASSERTION, "method/path too big");
if (CNO_FIRE(conn, on_write, buffer, size))
return CNO_ERROR_UP();
struct cno_header_t *it = msg->headers;
struct cno_header_t *end = msg->headers_len + it;
int had_connection_header = 0;
if (is_informational || final)
conn->flags &= ~CNO_CONN_FLAG_WRITING_CHUNKED;
else
conn->flags |= CNO_CONN_FLAG_WRITING_CHUNKED;
for (; it != end; ++it) {
struct cno_buffer_t name = it->name;
struct cno_buffer_t value = it->value;
if (cno_buffer_eq(name, CNO_BUFFER_STRING(":authority")))
name = CNO_BUFFER_STRING("host");
else if (cno_buffer_startswith(name, CNO_BUFFER_STRING(":")))
continue;
else if (cno_buffer_eq(name, CNO_BUFFER_STRING("connection")))
had_connection_header = 1;
else if (cno_buffer_eq(name, CNO_BUFFER_STRING("content-length"))
|| cno_buffer_eq(name, CNO_BUFFER_STRING("upgrade")))
conn->flags &= ~CNO_CONN_FLAG_WRITING_CHUNKED;
else if (cno_buffer_eq(name, CNO_BUFFER_STRING("transfer-encoding"))) {
// assuming the request is valid, chunked can only be the last transfer-encoding
if (cno_buffer_eq(value, CNO_BUFFER_STRING("chunked")))
continue;
else if (cno_buffer_endswith(value, CNO_BUFFER_STRING(", chunked")))
value.size -= 9;
else if (cno_buffer_endswith(value, CNO_BUFFER_STRING(",chunked")))
value.size -= 8;
}
size = snprintf(buffer, sizeof(buffer), "%.*s: %.*s\r\n",
(int) name.size, name.data, (int) value.size, value.data);
if ((size_t)size > sizeof(buffer))
return CNO_ERROR(ASSERTION, "header too big\r\n");
if (size && CNO_FIRE(conn, on_write, buffer, size))
return CNO_ERROR_UP();
}
if (conn->flags & CNO_CONN_FLAG_WRITING_CHUNKED)
if (CNO_FIRE(conn, on_write, "transfer-encoding: chunked\r\n", 28))
return CNO_ERROR_UP();
if (!had_connection_header)
if (CNO_FIRE(conn, on_write, "connection: keep-alive\r\n", 24))
return CNO_ERROR_UP();
if (CNO_FIRE(conn, on_write, "\r\n", 2))
return CNO_ERROR_UP();
if (msg->code == 101 && conn->state == CNO_CONNECTION_UNKNOWN_PROTOCOL_UPGRADE) {
conn->state = CNO_CONNECTION_UNKNOWN_PROTOCOL;
is_informational = 0;
}
} else {
struct cno_buffer_dyn_t payload = CNO_BUFFER_DYN_EMPTY;
struct cno_frame_t frame = { CNO_FRAME_HEADERS, CNO_FLAG_END_HEADERS, stream, CNO_BUFFER_EMPTY };
if (final)
frame.flags |= CNO_FLAG_END_STREAM;
if (conn->client) {
struct cno_header_t head[] = {
{ CNO_BUFFER_STRING(":method"), msg->method, 0 },
{ CNO_BUFFER_STRING(":path"), msg->path, 0 },
};
if (cno_hpack_encode(&conn->encoder, &payload, head, 2))
return cno_buffer_dyn_clear(&payload), CNO_ERROR_UP();
} else {
char code[8];
struct cno_header_t head[] = {
{ CNO_BUFFER_STRING(":status"), {code, snprintf(code, sizeof(code), "%d", msg->code)}, 0 }
};
if (cno_hpack_encode(&conn->encoder, &payload, head, 1))
return cno_buffer_dyn_clear(&payload), CNO_ERROR_UP();
}
if (cno_hpack_encode(&conn->encoder, &payload, msg->headers, msg->headers_len))
return cno_buffer_dyn_clear(&payload), CNO_ERROR_UP();
frame.payload = payload.as_static;
if (cno_frame_write(conn, &frame))
return cno_buffer_dyn_clear(&payload), CNO_ERROR_UP();
cno_buffer_dyn_clear(&payload);
}
if (final)
return cno_discard_remaining_payload(conn, streamobj);
if (!is_informational) {
streamobj->accept &= ~CNO_ACCEPT_WRITE_HEADERS;
streamobj->accept |= CNO_ACCEPT_WRITE_DATA;
}
return CNO_OK;
}
int cno_write_data(struct cno_connection_t *conn, uint32_t stream, const char *data, size_t length, int final)
{
if (conn->state == CNO_CONNECTION_UNDEFINED)
return CNO_ERROR(DISCONNECT, "connection closed");
struct cno_stream_t *streamobj = cno_stream_find(conn, stream);
if (streamobj == NULL)
return CNO_ERROR(INVALID_STREAM, "stream does not exist");
if (!(streamobj->accept & CNO_ACCEPT_WRITE_DATA))
return CNO_ERROR(INVALID_STREAM, "this stream is not writable");
if (conn->state == CNO_CONNECTION_UNKNOWN_PROTOCOL) {
if (CNO_FIRE(conn, on_write, data, length))
return CNO_ERROR_UP();
if (final) {
if (!(streamobj->accept &= ~CNO_ACCEPT_WRITE_DATA) && cno_stream_rst(conn, streamobj))
return CNO_ERROR_UP();
return CNO_ERROR(DISCONNECT, "should now close the transport");
}
return length;
}
if (!cno_connection_is_http2(conn)) {
int chunked = conn->flags & CNO_CONN_FLAG_WRITING_CHUNKED;
if (length) {
if (chunked) {
char lenbuf[16];
if (CNO_FIRE(conn, on_write, lenbuf, snprintf(lenbuf, sizeof(lenbuf), "%zX\r\n", length)))
return CNO_ERROR_UP();
}
if (CNO_FIRE(conn, on_write, data, length))
return CNO_ERROR_UP();
if (chunked && CNO_FIRE(conn, on_write, "\r\n", 2))
return CNO_ERROR_UP();
}
if (final && chunked && CNO_FIRE(conn, on_write, "0\r\n\r\n", 5))
return CNO_ERROR_UP();
} else {
if (conn->window_send < 0 || streamobj->window_send < 0)
return 0;
if (length > (uint32_t) conn->window_send) {
length = (uint32_t) conn->window_send;
final = 0;
}
if (length > (uint32_t) streamobj->window_send) {
length = (uint32_t) streamobj->window_send;
final = 0;
}
if (!length && !final)
return 0;
struct cno_frame_t frame = { CNO_FRAME_DATA, final ? CNO_FLAG_END_STREAM : 0, stream, { data, length } };
if (cno_frame_write(conn, &frame))
return CNO_ERROR_UP();
conn->window_send -= length;
streamobj->window_send -= length;
}
return final && cno_discard_remaining_payload(conn, streamobj) ? CNO_ERROR_UP() : (int)length;
}
int cno_write_ping(struct cno_connection_t *conn, const char data[8])
{
if (!cno_connection_is_http2(conn))
return CNO_ERROR(ASSERTION, "cannot ping HTTP/1.x endpoints");
struct cno_frame_t ping = { CNO_FRAME_PING, 0, 0, { data, 8 } };
return cno_frame_write(conn, &ping);
}
int cno_write_frame(struct cno_connection_t *conn, const struct cno_frame_t *frame)
{
if (!cno_connection_is_http2(conn))
return CNO_ERROR(ASSERTION, "cannot send HTTP2 frames to HTTP/1.x endpoints");
return cno_frame_write(conn, frame);
}
int cno_increase_flow_window(struct cno_connection_t *conn, uint32_t stream, size_t bytes)
{
if (!bytes || !stream || !cno_connection_is_http2(conn) || !cno_stream_find(conn, stream))
return CNO_OK;
struct cno_frame_t update = { CNO_FRAME_WINDOW_UPDATE, 0, stream, { PACK(I32(bytes)) } };
return cno_frame_write(conn, &update);
}
| 2.265625 | 2 |
2024-11-18T22:28:43.821340+00:00 | 2023-07-12T08:15:10 | a83e69b6b0b2ad329f3af99b0d67aa0c1b813e04 | {
"blob_id": "a83e69b6b0b2ad329f3af99b0d67aa0c1b813e04",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-12T09:02:32",
"content_id": "f44c21432ab16a8ad3dca4845f79afe70715384e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fe8f11a631754d08d88386b8e382bed8ada596c8",
"extension": "c",
"filename": "main.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 193833902,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1841,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/2021/04/https_client/main.c",
"provenance": "stackv2-0132.json.gz:89474",
"repo_name": "NanXiao/code-for-my-blog",
"revision_date": "2023-07-12T08:15:10",
"revision_id": "709e9234b290bffbe5908416bd6cc24ad8af2844",
"snapshot_id": "4564d27bb0c6aadfe5f4d08bfc67cc40a1658b9f",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/NanXiao/code-for-my-blog/709e9234b290bffbe5908416bd6cc24ad8af2844/2021/04/https_client/main.c",
"visit_date": "2023-07-20T00:36:31.242070"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#define CAFILE "/etc/ssl/cacert.pem"
#define CAPATH "/etc/ssl/certs/"
#define BUFSIZE 1024
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: ./client host:port\n");
exit(1);
}
int ret = 1;
const char* hostport = argv[1];
fprintf(stderr, "Trying a connection to %s...\n", hostport);
char *err_msg = NULL;
SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
if (ctx == NULL) {
err_msg = "SSL_CTX_new";
goto END;
}
if (!SSL_CTX_load_verify_locations(ctx, CAFILE, CAPATH)) {
err_msg = "SSL_CTX_load_verify_locations";
goto END;
}
BIO* bio = BIO_new_ssl_connect(ctx);
if (bio == NULL) {
err_msg = "BIO_new_ssl_connect";
goto END;
}
BIO_set_conn_hostname(bio, hostport);
if (BIO_do_connect(bio) <= 0) {
err_msg = "BIO_do_connect";
goto END;
}
SSL* ssl = NULL;
BIO_get_ssl(bio, &ssl);
long verify_err = SSL_get_verify_result(ssl);
if (verify_err != X509_V_OK) {
fprintf(
stderr,
"Certificate verification error (error code is %ld:%s) but continuing...\n",
verify_err,
X509_verify_cert_error_string(verify_err));
}
char request[BUFSIZE];
snprintf(
request,
sizeof(request),
"GET / HTTP/1.1\r\nHost: %s\r\nConnection: Close\r\n\r\n",
hostport);
BIO_puts(bio, request);
while (1) {
char response[BUFSIZE] = {0};
int n = BIO_read(bio, response, sizeof(response));
if (n <= 0) {
break;
}
puts(response);
}
ret = 0;
END:
SSL_CTX_free(ctx);
BIO_free_all(bio);
if (ret != 0) {
if (ERR_peek_error() == 0) {
perror(err_msg);
} else {
ERR_print_errors_fp(stderr);
}
}
return ret;
}
| 2.515625 | 3 |
2024-11-18T22:28:43.938018+00:00 | 2023-07-13T21:39:21 | caebe2016fbbae2005ca4dbda8ee37d0946f97c3 | {
"blob_id": "caebe2016fbbae2005ca4dbda8ee37d0946f97c3",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-13T21:39:21",
"content_id": "2a5a1ff555e60c715ac67cb8b62b7c45ed5ec47b",
"detected_licenses": [
"MIT"
],
"directory_id": "283591eb5d2ff0febe10622a50ff5111f7a17105",
"extension": "c",
"filename": "FileIO.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 239857010,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2611,
"license": "MIT",
"license_type": "permissive",
"path": "/src/examples/FileIO.c",
"provenance": "stackv2-0132.json.gz:89603",
"repo_name": "volkit/volkit",
"revision_date": "2023-07-13T21:39:21",
"revision_id": "cedda37ff6e0d0d0f32c5883fe751052eea77b78",
"snapshot_id": "9dc8869a1eb17383c19c452e892d7195e0907a32",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/volkit/volkit/cedda37ff6e0d0d0f32c5883fe751052eea77b78/src/examples/FileIO.c",
"visit_date": "2023-07-19T22:28:32.696424"
} | stackv2 | #include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <vkt/ExecutionPolicy.h>
#include <vkt/InputStream.h>
#include <vkt/LookupTable.h>
#include <vkt/Render.h>
#include <vkt/StructuredVolume.h>
#include <vkt/VolumeFile.h>
int main(int argc, char** argv)
{
vktVolumeFile file;
vktVolumeFileHeader_t hdr;
vktVec3i_t dims;
vktDataFormat dataFormat;
vktStructuredVolume volume;
vktInputStream is;
float rgba[20];
vktLookupTable lut;
vktRenderState_t renderState;
vktExecutionPolicy_t ep;
if (argc < 2)
{
fprintf(stderr, "Usage: %s file.raw\n", argv[0]);
return EXIT_FAILURE;
}
vktVolumeFileCreateS(&file, argv[1], vktOpenModeRead);
hdr = vktVolumeFileGetHeader(file);
if (!hdr.isStructured)
{
fprintf(stderr, "%s", "No valid volume file\n");
return EXIT_FAILURE;
}
dims = hdr.dims;
if (dims.x * dims.y * dims.z < 1)
{
fprintf(stderr, "%s", "Cannot parse dimensions from file name\n");
return EXIT_FAILURE;
}
dataFormat = hdr.dataFormat;
if (dataFormat == vktDataFormatUnspecified)
{
fprintf(stderr, "%s", "Cannot parse data format from file name, guessing uint8...\n");
dataFormat = vktDataFormatUInt8;
}
vktStructuredVolumeCreate(&volume, dims.x, dims.y, dims.z, dataFormat, 1.f, 1.f, 1.f, 0.f, 1.f);
vktInputStreamCreate(&is, vktVolumeFileGetBase(file));
vktInputStreamReadSV(is, volume);
rgba[ 0] = 1.f; rgba[ 1] = 1.f; rgba[ 2] = 1.f; rgba[ 3] = .005f;
rgba[ 4] = 0.f; rgba[ 5] = .1f; rgba[ 6] = .1f; rgba[ 7] = .25f;
rgba[ 8] = .5f; rgba[ 9] = .5f; rgba[10] = .7f; rgba[11] = .5f;
rgba[12] = .7f; rgba[13] = .7f; rgba[14] = .07f; rgba[15] = .75f;
rgba[16] = 1.f; rgba[17] = .3f; rgba[18] = .3f; rgba[19] = 1.f;
vktLookupTableCreate(&lut,5,1,1,vktColorFormatRGBA32F);
vktLookupTableSetData(lut,(uint8_t*)rgba);
// Switch execution to GPU (remove those lines for CPU rendering)
memset(&ep, 0, sizeof(ep));
ep.device = vktExecutionPolicyDeviceGPU;
vktSetThreadExecutionPolicy(ep);
vktRenderStateDefaultInit(&renderState);
//renderState.renderAlgo = vktRenderAlgoRayMarching;
//renderState.renderAlgo = vktRenderAlgoImplicitIso;
renderState.renderAlgo = vktRenderAlgoMultiScattering;
renderState.rgbaLookupTable = vktLookupTableGetResourceHandle(lut);
vktRenderSV(volume, renderState, NULL);
vktLookupTableDestroy(lut);
vktInputStreamDestroy(is);
vktStructuredVolumeDestroy(volume);
vktVolumeFileDestroy(file);
}
| 2.53125 | 3 |
2024-11-18T22:28:49.054634+00:00 | 2014-09-09T11:48:10 | 74c42ea6e3a2a476f06d15e060cb3533a28b172a | {
"blob_id": "74c42ea6e3a2a476f06d15e060cb3533a28b172a",
"branch_name": "refs/heads/master",
"committer_date": "2014-09-09T11:48:10",
"content_id": "b0b985edf620647486c9a7845d236fe19d4800fe",
"detected_licenses": [
"MIT"
],
"directory_id": "eecc238e00d9522eb3a1df9cad1718a2f692c1b9",
"extension": "c",
"filename": "KLEIN.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": 6413,
"license": "MIT",
"license_type": "permissive",
"path": "/C/KLEIN.c",
"provenance": "stackv2-0132.json.gz:89731",
"repo_name": "GongZheng/KLEIN-AVR",
"revision_date": "2014-09-09T11:48:10",
"revision_id": "4cb31be772ed94ad134f62b79a1f181f4292a1e0",
"snapshot_id": "9c3b9d07544904cb9f87f47fdb812d552f23ddc1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/GongZheng/KLEIN-AVR/4cb31be772ed94ad134f62b79a1f181f4292a1e0/C/KLEIN.c",
"visit_date": "2021-05-28T08:28:43.696511"
} | stackv2 | #include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
const uint64_t KEY = 0x0000000000000000;
//const uint64_t PLAINTEXT = 0x1234567890ABCDEF;
const uint64_t PLAINTEXT = 0xFFFFFFFFFFFFFFFF;
const int Nr = 12;
//const int Nr = 2;
// const int SBOX[] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
const uint8_t SBOX[] = {0x7, 0x4, 0xA, 0x9, 0x1, 0xF, 0xB, 0x0, 0xC, 0x3, 0x2, 0x6, 0x8, 0xE, 0xD, 0x5};
void printBin64(uint64_t n) {
int i;
for (i = 63; i >= 0; i--) {
printf("%d", (int) (n >> i) & 0x1);
if (i % 4 == 0) {
printf(" ");
}
}
printf("\n");
}
void printBin8(uint8_t n) {
int i;
for (i = 7; i >= 0; i--) {
printf("%d", (int) (n >> i) & 0x1);
if (i % 4 == 0) {
printf(" ");
}
}
printf("\n");
}
uint8_t galois_x4_1(uint8_t a) {
int i;
for (i = 7; i >= 0; i--) {
if (a >> i & 0x1) {
a ^= 0x11 << (i - 4); // shift n to the same bit as the current bit in 'a'
}
}
return a;
}
uint64_t addRoundKey(uint64_t state, uint64_t sk) {
return state ^ sk;
}
uint64_t subNibbles(uint64_t state) {
uint64_t result = 0;
int i;
for (i = 15; i >= 0; i--) {
result = result << 4;
result += SBOX[(state & ((uint64_t) 0xF << 4*i)) >> 4*i];
//printBin(result);
}
return result;
}
uint64_t rotateLeft(uint64_t n) {
return ((n >> 63) & 0x1) | (n << 1);
}
uint64_t rotateNibbles(uint64_t state) {
int i;
for(i = 0; i < 16;i++) {
state = rotateLeft(state);
}
return state;
}
uint64_t mixNibbles(uint64_t state) {
//This fits _exactly_ in the registers.
uint8_t c01_1 = galois_x4_1((uint8_t) (state >> 56) & 0xFF);
uint8_t c01_2 = c01_1 << 1;
uint8_t c01_3 = c01_1 ^ c01_2;
uint8_t c23_1 = galois_x4_1((uint8_t) (state >> 48) & 0xFF);
uint8_t c23_2 = c23_1 << 1;
uint8_t c23_3 = c23_1 ^ c23_2;
uint8_t c45_1 = galois_x4_1((uint8_t) (state >> 40) & 0xFF);
uint8_t c45_2 = c45_1 << 1;
uint8_t c45_3 = c45_1 ^ c45_2;
uint8_t c67_1 = galois_x4_1((uint8_t) (state >> 32) & 0xFF);
uint8_t c67_2 = c67_1 << 1;
uint8_t c67_3 = c67_1 ^ c67_2;
uint8_t c89_1 = galois_x4_1((uint8_t) (state >> 24) & 0xFF);
uint8_t c89_2 = c89_1 << 1;
uint8_t c89_3 = c89_1 ^ c89_2;
uint8_t cAB_1 = galois_x4_1((uint8_t) (state >> 16) & 0xFF);
uint8_t cAB_2 = cAB_1 << 1;
uint8_t cAB_3 = cAB_1 ^ cAB_2;
uint8_t cCD_1 = galois_x4_1((uint8_t) (state >> 8) & 0xFF);
uint8_t cCD_2 = cCD_1 << 1;
uint8_t cCD_3 = cCD_1 ^ cCD_2;
uint8_t cEF_1 = galois_x4_1((uint8_t) state & 0xFF);
uint8_t cEF_2 = cEF_1 << 1;
uint8_t cEF_3 = cEF_1 ^ cEF_2;
printf("c01_1: %"PRIX64 "\n",c01_1);
printf("c01_2: %"PRIX64 "\n",c01_2);
printf("c01_3: %"PRIX64 "\n",c01_3);
printf("\n");
printf("c23_1: %"PRIX64 "\n",c23_1);
printf("c23_2: %"PRIX64 "\n",c23_2);
printf("c23_3: %"PRIX64 "\n",c23_3);
printf("\n");
printf("c45_1: %"PRIX64 "\n",c45_1);
printf("c45_2: %"PRIX64 "\n",c45_2);
printf("c45_3: %"PRIX64 "\n",c45_3);
printf("\n");
printf("c67_1: %"PRIX64 "\n",c67_1);
printf("c67_2: %"PRIX64 "\n",c67_2);
printf("c67_3: %"PRIX64 "\n",c67_3);
printf("\n");
printf("c89_1: %"PRIX64 "\n",c89_1);
printf("c89_2: %"PRIX64 "\n",c89_2);
printf("c89_3: %"PRIX64 "\n",c89_3);
printf("\n");
printf("cAB_1: %"PRIX64 "\n",cAB_1);
printf("cAB_2: %"PRIX64 "\n",cAB_2);
printf("cAB_3: %"PRIX64 "\n",cAB_3);
printf("\n");
printf("cCD_1: %"PRIX64 "\n",cCD_1);
printf("cCD_2: %"PRIX64 "\n",cCD_2);
printf("cCD_3: %"PRIX64 "\n",cCD_3);
printf("\n");
printf("cEF_1: %"PRIX64 "\n",cEF_1);
printf("cEF_2: %"PRIX64 "\n",cEF_2);
printf("cEF_3: %"PRIX64 "\n",cEF_3);
printf("\n");
uint8_t s01 = galois_x4_1((uint8_t) c01_2 ^ c23_3 ^ c45_1 ^ c67_1);
uint8_t s23 = galois_x4_1((uint8_t) c01_1 ^ c23_2 ^ c45_3 ^ c67_1);
uint8_t s45 = galois_x4_1((uint8_t) c01_1 ^ c23_1 ^ c45_2 ^ c67_3);
uint8_t s67 = galois_x4_1((uint8_t) c01_3 ^ c23_1 ^ c45_1 ^ c67_2);
uint8_t s89 = galois_x4_1((uint8_t) c89_2 ^ cAB_3 ^ cCD_1 ^ cEF_1);
uint8_t sAB = galois_x4_1((uint8_t) c89_1 ^ cAB_2 ^ cCD_3 ^ cEF_1);
uint8_t sCD = galois_x4_1((uint8_t) c89_1 ^ cAB_1 ^ cCD_2 ^ cEF_3);
uint8_t sEF = galois_x4_1((uint8_t) c89_3 ^ cAB_1 ^ cCD_1 ^ cEF_2);
printf(" s01: %"PRIX64 "\n", s01);
printf(" s23: %"PRIX64 "\n", s23);
printf(" s45: %"PRIX64 "\n", s45);
printf(" s67: %"PRIX64 "\n", s67);
printf(" s89: %"PRIX64 "\n", s89);
printf(" sAB: %"PRIX64 "\n", sAB);
printf(" sCD: %"PRIX64 "\n", sCD);
printf(" sEF: %"PRIX64 "\n", sEF);
return (((uint64_t) s01) << 56) ^ (((uint64_t) s23) << 48) ^ (((uint64_t) s45) << 40) ^ (((uint64_t) s67) << 32) ^ (((uint64_t) s89) << 24) ^ (((uint64_t) sAB) << 16) ^ (((uint64_t) sCD) << 8) ^ (uint64_t) sEF;
}
uint64_t keySchedule(uint64_t sk, uint8_t i) {
uint8_t r0 = ((uint8_t) (sk >> 56) & 0xFF);
uint8_t r1 = ((uint8_t) (sk >> 48) & 0xFF);
uint8_t r2 = ((uint8_t) (sk >> 40) & 0xFF);
uint8_t r3 = ((uint8_t) (sk >> 32) & 0xFF);
uint8_t r4 = ((uint8_t) (sk >> 24) & 0xFF);
uint8_t r5 = ((uint8_t) (sk >> 16) & 0xFF);
uint8_t r6 = ((uint8_t) (sk >> 8) & 0xFF);
uint8_t r7 = ((uint8_t) sk & 0xFF);
// <implicit swap> now the order is 1230 5674
r1 ^= r5;
r2 ^= r6;
r3 ^= r7;
r0 ^= r4;
return (((uint64_t) r5) << 56) ^ (((uint64_t) r6) << 48) ^ (((uint64_t) (r7 ^ i)) << 40) ^ (((uint64_t) r4) << 32)
^ (((uint64_t) r1) << 24)
^ (((uint64_t) SBOX[(r2 >> 4) & 0xF]) << 20) ^ (((uint64_t) SBOX[r2 & 0xF]) << 16)
^ (((uint64_t) SBOX[(r3 >> 4) & 0xF]) << 12) ^ (((uint64_t) SBOX[r3 & 0xF]) << 8)
^ (uint64_t) r0;
}
uint64_t KLEIN(uint64_t key, uint64_t plaintext) {
uint64_t sk = key;
uint64_t state = plaintext;
uint8_t i;
for (i = 1; i <= Nr ; i++) {
state = addRoundKey(state, sk);
printf("na addround : %" PRIX64 "\n", state);
state = subNibbles(state);
printf("na subnibbles : %" PRIX64 "\n", state);
state = rotateNibbles(state);
printf("na rotbnibbles: %" PRIX64 "\n", state);
state = mixNibbles(state);
printf("na mixbnibbles: %" PRIX64 "\n", state);
sk = keySchedule(sk, i);
printf("roundkey : %" PRIX64 "\n", sk);
}
state = addRoundKey(state, sk);
return state;
}
int main() {
//printf("Nibbleding: %" PRIX64 "\n", mixNibbles(0x82247502273DCC5F));
//printf("Subnibbles: %" PRIX64 "\n", subNibbles(0x123456789ABCDEF));
printf("Key: %" PRIX64 "\n", KEY);
printf("Ciphertext: %" PRIX64 "\n", KLEIN(KEY, PLAINTEXT));
printf("Plaintext: %" PRIX64 "\n", PLAINTEXT);
printf("KEY: %" PRIX64 "\n", KEY);
return 0;
}
| 2.5625 | 3 |
2024-11-18T22:28:49.447823+00:00 | 2020-08-28T19:14:48 | aefc816c3ce9c5d9ff47db477718b420c97171fc | {
"blob_id": "aefc816c3ce9c5d9ff47db477718b420c97171fc",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-28T19:14:48",
"content_id": "215ac2a20e417f597d208f0056e0cb696fd26d21",
"detected_licenses": [
"MIT"
],
"directory_id": "7c44c095a5cc68f7e8417f29e49dfbd7e8d14ee2",
"extension": "c",
"filename": "ErrorPrinter.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150336784,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6719,
"license": "MIT",
"license_type": "permissive",
"path": "/ErrorPrinter.c",
"provenance": "stackv2-0132.json.gz:89861",
"repo_name": "sagiK11/Assembly-Compiler-Course-Project",
"revision_date": "2020-08-28T19:14:48",
"revision_id": "1477ae5bf1baf10773bbccecee12bba8e39c85e4",
"snapshot_id": "0829b85e593f03e42fa01dd3e088969830fbcd35",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sagiK11/Assembly-Compiler-Course-Project/1477ae5bf1baf10773bbccecee12bba8e39c85e4/ErrorPrinter.c",
"visit_date": "2021-07-02T20:31:24.799343"
} | stackv2 |
#include "declarationsHeader.h"
/*
* Prints to the stderr the error and its line number.
**/
void printErrorWithComment(int error, char *str) {
turnOnErrorFlag();
fprintf(stderr, "Error: ");
switch (error) {
case illegal_sym :
fprintf(stderr, "Illegal symbol: '%s' in line %d.\n", str, lineNumber);
break;
case sym_defined_already:
fprintf(stderr, "Symbol: '%s' in line %d is defined already.\n", str, lineNumber);
break;
case sym_is_key :
fprintf(stderr, "Symbol: '%s' in line %d is defined as a saved key.\n", str, lineNumber);
break;
case undef_parameter :
fprintf(stderr, "Undefined parameter: '%s' in line %d\n", str, lineNumber);
break;
case writing_to_file :
fprintf(stderr, "Error writing to file: %s\n", str);
break;
case undef_symbol :
fprintf(stderr, "Undefined symbol: '%s' in line %d\n", str, lineNumber);
break;
case float_err :
fprintf(stderr, "Assembler does not support floating point numbers - %s\n", str);
break;
case immediate_wrong_use :
fprintf(stderr, "Wrong use of Immediate method - '%s' in line %d\n", str, lineNumber);
break;
case err_app_file :
fprintf(stderr, "Error appending the file: '%s'\n.", str);
break;
case src_meth0_illegal:
fprintf(stderr, "Illegal use of src method 0 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case src_meth1_illegal:
fprintf(stderr, "Illegal use of src method 1 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case src_meth2_illegal:
fprintf(stderr, "Illegal use of src method 2 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case src_meth3_illegal:
fprintf(stderr, "Illegal use of src method 3 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case dst_meth0_illegal:
fprintf(stderr, "Illegal use of dest method 0 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case dst_meth1_illegal:
fprintf(stderr, "Illegal use of dest method 1 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case dst_meth2_illegal:
fprintf(stderr, "Illegal use of dest method 2 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case dst_meth3_illegal:
fprintf(stderr, "Illegal use of dest method 3 in cmd:'%s' in line: %d\n", str,
lineNumber);
break;
case undef_char :
fprintf(stderr, "Undefined char: '%s' in line: %d\n", str, lineNumber);
break;
case redu_info:
fprintf(stderr, "Redundant info: '%s' in line: %d\n", str, lineNumber);
break;
case illegal_sym_mth:
fprintf(stderr, "Illegal label: '%s' before paramters in line: %d\n", str, lineNumber);
break;
case symbol_is_ent_and_ext:
fprintf(stderr, "Symbol is defined both extern and entry: '%s'\n", str);
break;
case illegal_operand:
fprintf(stderr, "Illegal operand afer '%s' command in line: %d\n", str, lineNumber);
break;
default:
fprintf(stderr, "error in line %d", lineNumber);
}
}
void printError(int error) {
turnOnErrorFlag();
fprintf(stderr, "Error: ");
switch (error) {
case brack_err :
fprintf(stderr, "Brackets miss match in line %d\n", lineNumber);
break;
case string_err :
fprintf(stderr, "String ' \"\" ' missmatch in line %d\n", lineNumber);
break;
case not_enough_params :
fprintf(stderr, "Too few parameters.\n.");
break;
case file_op_err :
fprintf(stderr, "Error opening file.\n.");
break;
case missing_comma:
fprintf(stderr, "Missing a comma in line: %d\n", lineNumber);
break;
case comm_mis_match :
fprintf(stderr, "Comma miss match in line: %d\n", lineNumber);
break;
case extra_commas :
fprintf(stderr, "Too many commas in line: %d\n", lineNumber);
break;
case extra_ent:
fprintf(stderr, "Extra text after entry label in line: %d\n", lineNumber);
break;
case sym_miss_place :
fprintf(stderr, "Symbol definition is not the first statment in line: %d\n", lineNumber);
break;
case order_error:
fprintf(stderr, "The order of operators in line: %d is incorrect.\n", lineNumber);
break;
case missing_both_params:
fprintf(stderr, "Missing both parameters in line: %d\n", lineNumber);
break;
case missing_first_param:
fprintf(stderr, "Missing first parameter in line: %d\n", lineNumber);
break;
case missing_second_param:
fprintf(stderr, "Missing second parameter in line: %d\n", lineNumber);
break;
case data_line_with_no_data:
fprintf(stderr, "No data was found in line: %d\n", lineNumber);
break;
case no_definer_in_line:
fprintf(stderr, "Missing a definer (.data/.string/cmd) in line: %d\n", lineNumber);
break;
case missing_sym:
fprintf(stderr, "Missing symbol in line: %d\n", lineNumber);
break;
default:
fprintf(stderr, "error in line %d", lineNumber);
}
}
/*
* Prints to the stderr the warning and its line number.
*/
void printWarning(int error, char *str, size_t lineCntCpy) {
fprintf(stderr, "Warning: ");
switch (error) {
case uns_ex_sym:
fprintf(stderr, "Unused ext symbol: '%s' in line: %d\n", str, lineCntCpy);
break;
case bef_ext:
fprintf(stderr, "String:'%s' before extern symbol in line: %d\n", str, lineNumber);
break;
case invalid_input:
fprintf(stderr, "No code was written, invalid input in file: '%s'\n", str);
break;
case chars_before_comment:
fprintf(stderr, "Chars before a comment identifier in line: %d\n", lineNumber);
break;
default:
fprintf(stderr, "General Warning.\n");
}
}
void turnOnErrorFlag(){
generalError = TRUE;
}
| 2.390625 | 2 |
2024-11-18T22:28:49.538718+00:00 | 2018-03-07T15:23:58 | 39616ec29ce685730b7ad4d4c4a3765254078849 | {
"blob_id": "39616ec29ce685730b7ad4d4c4a3765254078849",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-07T15:23:58",
"content_id": "8ded25a5c80c58f8b7b73f78af0407928e6bbc79",
"detected_licenses": [
"MIT"
],
"directory_id": "caeb65865ef992941c540bd4318b9328b901892e",
"extension": "h",
"filename": "ft_lst.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 111078035,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1888,
"license": "MIT",
"license_type": "permissive",
"path": "/include/ft_lst.h",
"provenance": "stackv2-0132.json.gz:89992",
"repo_name": "babariviere/libft",
"revision_date": "2018-03-07T15:23:58",
"revision_id": "2afe9f19b3f45e07fd281b9425787f1058dd1b41",
"snapshot_id": "00354d53667910f14a3e608c9bab2da7cf64b185",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/babariviere/libft/2afe9f19b3f45e07fd281b9425787f1058dd1b41/include/ft_lst.h",
"visit_date": "2021-09-08T05:26:22.455138"
} | stackv2 | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lst.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: briviere <briviere@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/18 16:46:16 by briviere #+# #+# */
/* Updated: 2018/02/24 16:54:58 by briviere ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_LST_H
# define FT_LST_H
# define FT_LST_DEL (void (*)(void *, size_t))1
# include "ft_mem.h"
# include <string.h>
typedef struct s_list
{
void *content;
size_t content_size;
struct s_list *next;
} t_lst;
t_lst *ft_lstnew(const void *content, size_t content_size);
t_lst *ft_lstnew_mv(const void *content, size_t content_size);
void ft_lstdelone(t_lst **alst, void (*del)(void *, size_t));
void ft_lstdel(t_lst **alst, void (*del)(void *, size_t));
void ft_lstadd(t_lst **alst, t_lst *nw);
void ft_lstpush(t_lst **alst, t_lst *nw);
void ft_lstiter(t_lst *lst, void (*f)(t_lst *elem));
t_lst *ft_lstmap(t_lst *lst, t_lst *(*f)(t_lst *elem));
t_lst *ft_lstfilter(t_lst *lst, int (*f)(t_lst *elem));
size_t ft_lstlen(const t_lst *lst);
t_lst *ft_lstfind(const t_lst *lst,
int (*f)(const void *content, const void *to_find),
void *to_find);
t_lst *ft_lstget(const t_lst *lst, size_t idx);
void ft_lstdel_def(void *content, size_t size);
#endif
| 2.25 | 2 |
2024-11-18T22:28:49.594003+00:00 | 2020-09-18T13:44:12 | 033de16afa0374a25c52dcf6f978fcf1e23c6dae | {
"blob_id": "033de16afa0374a25c52dcf6f978fcf1e23c6dae",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-18T13:44:12",
"content_id": "8731f45203979d441df2fc42da0f8a2ec5de4e80",
"detected_licenses": [
"MIT"
],
"directory_id": "ddec78eee1a879022fa03f65563fb7f6e1d31bc8",
"extension": "c",
"filename": "canvas.c",
"fork_events_count": 0,
"gha_created_at": "2019-05-01T18:56:13",
"gha_event_created_at": "2020-09-18T13:44:14",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 184465813,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3048,
"license": "MIT",
"license_type": "permissive",
"path": "/floppies/lindengen/source/library/renderer/canvas.c",
"provenance": "stackv2-0132.json.gz:90123",
"repo_name": "LucvandenBrand/FloppyChallenge",
"revision_date": "2020-09-18T13:44:12",
"revision_id": "9f4f3e6427656923951125b8e45c46dc3b6b8d3f",
"snapshot_id": "a26da03e9cb2d17d5641aef14aa72add47773621",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/LucvandenBrand/FloppyChallenge/9f4f3e6427656923951125b8e45c46dc3b6b8d3f/floppies/lindengen/source/library/renderer/canvas.c",
"visit_date": "2021-07-08T01:38:19.134710"
} | stackv2 | #include <png.h>
#include "renderer/canvas.h"
#include "memory/safe_alloc.h"
Canvas alloc_canvas(size_t width, size_t height)
{
Canvas canvas;
canvas.pixels = safe_malloc(sizeof(Colour) * width * height);
canvas.width = width;
canvas.height = height;
return canvas;
}
void free_canvas(Canvas * canvas)
{
free(canvas->pixels);
canvas->pixels = NULL;
canvas->width = 0;
canvas->height = 0;
}
void clear_canvas(Canvas * canvas, Colour colour)
{
for (size_t row = 0; row < canvas->height; row++)
for (size_t col = 0; col < canvas->width; col++)
set_pixel(canvas, colour, row, col);
}
void set_pixel(Canvas * canvas, Colour colour, size_t row, size_t col)
{
// If outside bounds, ignore the draw.
if (row < 0 || row >= canvas->height || col < 0 || col >= canvas->width)
return;
// Find the position in the 1D array and set the value.
size_t index = row * canvas->width + col;
canvas->pixels[index] = colour;
}
Colour get_pixel(Canvas canvas, size_t row, size_t col)
{
// If outside bounds, return black
Colour colour = create_colour_greyscale(0);
if (row < 0 || row >= canvas.height || col < 0 || col >= canvas.width)
return colour;
// Find the position in the 1D array and return the value
size_t index = row * canvas.width + col;
return canvas.pixels[index];
}
bool save_canvas_as_png(Canvas canvas, const char * file_path)
{
// Create file
FILE * file_ptr = fopen(file_path, "wb");
if (file_ptr == NULL)
{
printf("Could not create file.\n");
return false;
}
// Create PNG data structs
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL)
return false;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
return false;
}
// Init PNG file
png_init_io(png_ptr, file_ptr);
png_set_IHDR(png_ptr, info_ptr, canvas.width, canvas.height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
// Set the title
png_text title_text;
title_text.compression = PNG_TEXT_COMPRESSION_NONE;
title_text.key = "Title";
title_text.text = "L-system";
png_set_text(png_ptr, info_ptr, &title_text, 1);
png_write_info(png_ptr, info_ptr);
// Write image data
png_bytep row = (png_bytep) safe_malloc(3 * canvas.width * sizeof(png_byte));
for (size_t y = 0; y < canvas.height; y++)
{
for (size_t x = 0; x < canvas.width; x++)
{
Colour colour = get_pixel(canvas, y, x);
colour_to_png_byte(&(row[x*3]), colour);
}
png_write_row(png_ptr, row);
}
png_write_end(png_ptr, NULL);
fclose(file_ptr);
png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
free(row);
return true;
} | 3.046875 | 3 |
2024-11-18T22:28:50.376921+00:00 | 2016-11-07T17:35:44 | aee90b705d0a3c2f1109c14562cfa1834660c468 | {
"blob_id": "aee90b705d0a3c2f1109c14562cfa1834660c468",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-07T17:35:44",
"content_id": "788f700473816982561e14c08d23ddb32c9fff58",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3e627146ee14ecbe37c0771490525d5e211056a5",
"extension": "h",
"filename": "ansi.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": 1109,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ansi.h",
"provenance": "stackv2-0132.json.gz:90771",
"repo_name": "papaidas15790/Minix-Source-Code",
"revision_date": "2016-11-07T17:35:44",
"revision_id": "2da73f734aec7ea5b5a4c5f6a92bbd9c9dc0dfb5",
"snapshot_id": "f32892f72fa77df0e1c7f7e5f32187b106fb70d0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/papaidas15790/Minix-Source-Code/2da73f734aec7ea5b5a4c5f6a92bbd9c9dc0dfb5/ansi.h",
"visit_date": "2020-04-16T11:41:28.820697"
} | stackv2 | #ifndef _ANSI_H
#define _ANSI_H
#if __STDC__ == 1
#define _ANSI 31459 /* compiler claims full ANSI conformance */
#endif
#ifdef __GNUC__
#define _ANSI 31459 /* gcc conforms enough even in non-ANSI mode */
#endif
#ifdef _ANSI
/* Keep everything for ANSI prototypes. */
#define _PROTOTYPE(function, params) function params
#define _ARGS(params) params
#define _VOIDSTAR void *
#define _VOID void
#define _CONST const
#define _VOLATILE volatile
#define _SIZET size_t
#else
/* Throw away the parameters for K&R prototypes. */
#define _PROTOTYPE(function, params) function()
#define _ARGS(params) ()
#define _VOIDSTAR void *
#define _VOID void
#define _CONST
#define _VOLATILE
#define _SIZET int
#endif /* _ANSI */
/* This should be defined as restrict when a C99 compiler is used. */
#define _RESTRICT
/* Setting any of _MINIX, _POSIX_C_SOURCE or _POSIX2_SOURCE implies
* _POSIX_SOURCE. (Seems wrong to put this here in ANSI space.)
*/
#if defined(_MINIX) || _POSIX_C_SOURCE > 0 || defined(_POSIX2_SOURCE)
#undef _POSIX_SOURCE
#define _POSIX_SOURCE 1
#endif
#endif /* ANSI_H */ | 2.046875 | 2 |
2024-11-18T22:28:50.709309+00:00 | 2020-11-01T00:45:09 | 9ec32445fd51a84d5bea7bfe3f36a9259e1da8c8 | {
"blob_id": "9ec32445fd51a84d5bea7bfe3f36a9259e1da8c8",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-01T00:45:09",
"content_id": "3ee0ba81fc5371f36284fc7a7069234714f18ec0",
"detected_licenses": [
"MIT"
],
"directory_id": "7aad6cd90b86079193184d58d03061e5817e1fca",
"extension": "c",
"filename": "Exer06.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 308945036,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 352,
"license": "MIT",
"license_type": "permissive",
"path": "/Exercicios Moodle/Recursividade - Exercicios Moodle/Exer06.c",
"provenance": "stackv2-0132.json.gz:91161",
"repo_name": "Alfredosavi/algoritmos-1",
"revision_date": "2020-11-01T00:45:09",
"revision_id": "f63dd16b6ccda60f1bf137470f4ad0b9c195927b",
"snapshot_id": "fe1f65eaed0cc1fb4ab340723763e78e8d9364a6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Alfredosavi/algoritmos-1/f63dd16b6ccda60f1bf137470f4ad0b9c195927b/Exercicios Moodle/Recursividade - Exercicios Moodle/Exer06.c",
"visit_date": "2023-01-03T14:48:04.858257"
} | stackv2 | // 6. Implemente uma função recursiva que recebe um número decimal e retorna sua versão em binrio.
#include <stdio.h>
int Exer06(int num);
int main(void)
{
int Number = 10;
printf("%d", Exer06(Number));
return 0;
}
int Exer06(int num)
{
if (num < 2)
{
return num;
}
return (10 * Exer06(num / 2)) + num % 2;
}
| 3.796875 | 4 |
2024-11-18T22:28:50.788319+00:00 | 2019-03-21T13:27:54 | 5aa6c66321fcd7e4481fa69934c3a1c6d228c024 | {
"blob_id": "5aa6c66321fcd7e4481fa69934c3a1c6d228c024",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-21T13:27:54",
"content_id": "559840e62033c9f4ae879e6b7f1cffd4f9db0c6d",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "5465a5caa9c149b1583c9bb92adfafe8254cbb36",
"extension": "h",
"filename": "checker.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": 1045,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/checker.h",
"provenance": "stackv2-0132.json.gz:91294",
"repo_name": "lipeijie10/unity-native-plugin-example",
"revision_date": "2019-03-21T13:27:54",
"revision_id": "36259c2dbfac18093b98aebe568943c1f9d8ff9c",
"snapshot_id": "ace312ff047de804524cefe28b7817f5c1b637ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lipeijie10/unity-native-plugin-example/36259c2dbfac18093b98aebe568943c1f9d8ff9c/src/checker.h",
"visit_date": "2021-10-24T02:35:30.414989"
} | stackv2 | #ifndef CHECKER_H
#define CHECKER_H
#include <stdbool.h>
// Number of checkers on the board
static const int CHECKER_COUNT = 24;
typedef struct player {
char name[32];
} player;
typedef struct checker {
int x;
int y;
bool is_king;
bool in_play;
int player_index;
} checker;
typedef struct checkerboard {
checker checkers[CHECKER_COUNT];
} checkerboard;
typedef struct game {
checkerboard board;
player players[2];
} game;
/**
* Create a new game
*/
game *game_init(char *player_name1, char *player_name2);
/**
* Release game resources
*/
void game_free(game *game);
/**
* Returns the checker instance in a given board location or NULL
*/
checker *game_find_piece(game *game, int x, int y);
/**
* Returns true if the move succeeds
*/
bool game_move_piece(game *g, checker *c, int x, int y);
/**
* Number of pieces still in play
*/
int game_pieces_in_play(game *g);
/**
* Number of pieces still in play for a particular player
*/
int game_pieces_for_player(game *g, int player_index);
#endif // CHECKER_H
| 2.1875 | 2 |
2024-11-18T22:28:51.660195+00:00 | 2015-11-03T22:55:46 | f17d801cdc1dda7ee6a3980a0c0b47873623b36a | {
"blob_id": "f17d801cdc1dda7ee6a3980a0c0b47873623b36a",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-03T22:55:46",
"content_id": "1d47c7b4deae023118a8f00ee2fa9aa86e04a553",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e5b02b7d6f48f6aecdea22347937a8cae4a5930f",
"extension": "c",
"filename": "files.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67639059,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1275,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/Kernel/c/files.c",
"provenance": "stackv2-0132.json.gz:91942",
"repo_name": "Drocheg/arqui-2015",
"revision_date": "2015-11-03T22:55:46",
"revision_id": "8db7549d18f71fe2bc73a57eb267b4ea7cf3248c",
"snapshot_id": "45c2b149c9a055be8bfb07997266643ecc4ed994",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Drocheg/arqui-2015/8db7549d18f71fe2bc73a57eb267b4ea7cf3248c/Kernel/c/files.c",
"visit_date": "2020-09-09T18:46:12.225256"
} | stackv2 | #include <files.h>
#include <video.h>
#include <keyboard.h>
uint64_t fwrite(uint64_t fd, char *buffer, uint64_t maxBytes) {
int result = 0;
if(fd < MIN_FD || fd > MAX_FD) return -1;
int i;
switch(fd) {
case STDOUT:
result = 0;
for(i = 0; buffer[i] != 0 && i < maxBytes; i++) {
ncPrintChar(buffer[i]);
result++;
}
break;
case STDERR:
result = 0;
for(i = 0; buffer[i] != 0 && i < maxBytes; i++) {
ncPrintColorChar(buffer[i], (char) 0x04);
result++;
}
break;
case KEYBOARD:
fwrite(STDERR, "Can't write to keyboard.", 24);
return 0;
break;
case SPEAKER:
ncPrint("Speaker not implemented yet.");
break;
}
return result;
}
uint64_t fread(uint64_t fd, char *buffer, uint64_t maxBytes) {
int result = 0;
if(fd < MIN_FD || fd > MAX_FD) return -1;
int i;
switch(fd) {
case STDOUT:
fwrite(STDERR, "Can't read STDOUT.", 24);
return 0;
break;
case STDERR:
fwrite(STDERR, "Can't read STDERR.", 24);
return 0;
break;
case KEYBOARD:
result = 0;
for(i = 0; !bufferIsEmpty() && i < maxBytes; i++) {
buffer[i]= getPressedKey();
result++;
}
break;
case SPEAKER:
ncPrint("Speaker not implemented yet.");
break;
}
return result;
return getPressedKey();
return -1;
} | 2.53125 | 3 |
2024-11-18T22:28:51.731166+00:00 | 2019-07-26T08:44:24 | a3dc92a5fb6ca1e8953e387e1a624c062d108a5b | {
"blob_id": "a3dc92a5fb6ca1e8953e387e1a624c062d108a5b",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-26T08:44:24",
"content_id": "a95c8300e62b1af80922679643cc9e375773dc44",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "83b82055906b7c73627d432a88e62219c4e5bbc6",
"extension": "h",
"filename": "CircularBuffer.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": 7298,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/include/CircularBuffer.h",
"provenance": "stackv2-0132.json.gz:92072",
"repo_name": "andylao62/Ingenic_T20",
"revision_date": "2019-07-26T08:44:24",
"revision_id": "2aaabc3ae829b8e422607ee1217e6a7aa981f23d",
"snapshot_id": "cc826c635e522939c0c019705bcee16103fb1d71",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andylao62/Ingenic_T20/2aaabc3ae829b8e422607ee1217e6a7aa981f23d/app/include/CircularBuffer.h",
"visit_date": "2022-01-29T03:29:54.670672"
} | stackv2 |
/***************************************************************************
* @file: CircularBuffer.h
* @author:
* @date: 5,18,2019
* @brief: 循环缓冲池头文件
* @attention:
***************************************************************************/
#ifndef _CIRCULAR_BUFFER_H
#define _CIRCULAR_BUFFER_H
#include "typeport.h"
#include "encoder.h"
#ifndef false
#define false 0
#endif
#ifndef true
#define true 1
#endif
#define BUFFER_SIZE_1920x1080 1024*1024*4 /*1920*1080 分辨率的缓冲buf大小*/
#define BUFFER_SIZE_960x544 1024*1024*1 /*960*544 分辨率的缓冲buf大小*/
#define BUFFER_SIZE_640x360 1024*1024*1 /*640*360 分辨率的缓冲buf大小*/
#define BUFFER_SIZE_480x272 1024*1024/4 /*480*272 分辨率的缓冲buf大小*/
#define RECODE_TIME 40 //最大缓存音视频时长(秒)
#define MAX_I_F_NUM (RECODE_TIME / 2) //最大I帧数量(gop:30帧; 帧率:15帧/s ; I帧:2s/I帧)
#define MAX_A_F_NUM (RECODE_TIME * 15) //最大的audio帧数量(audio: 15帧/s , aac帧)
#define MAX_V_F_NUM (RECODE_TIME * 15) //最大的 video帧数量(video:15帧/s )
#define MAX_FRM_NUM (MAX_A_F_NUM + MAX_V_F_NUM)
#define MAX_USER_NUM 6 //缓存池支持的最大同时 “读” 用户个数
//用户读缓存的信息结构(支持多个用户同时读缓存,用户只能读)
typedef struct _UserInfo_t
{
HLE_U16 occupied; /*0:该用户空闲,1:该用户已经被占用*/
HLE_U16 ReadFrmIndex; /*此用户对帧缓冲池访问所用的帧索引*/
HLE_U32 ReadCircleNum; /*此用户对帧缓冲池的访问圈数,初始时等于帧缓冲池中的circlenum*/
HLE_U32 diffpos; /*读指针和写指针位置差值,单位为帧*/
HLE_U32 throwframcount; /*从开始计数丢帧的个数*/
HLE_U32 needReset; /*读信息需要重置(申请用户ID后,首次读时数据时需要将读信息重置到离写指针所对应的IDR帧位置)*/
}UserInfo_t;
//一个 video/audio 帧在缓冲池的信息描述结构体
typedef struct _FrameInfo_t
{
HLE_U32 frmStartPos; /*此帧在buffer中的偏移*/
HLE_U32 frmLength; /*此帧的有效数据长度*/
HLE_U64 PTS; /*如果是视频帧,则为此帧的时间戳*/
HLE_SYS_TIME time; /*产生此帧的时间*/
HLE_U8 flag; /*帧类型, 0xF8-视频关键帧,0xF9-视频非关键帧,0xFA-音频帧*/
HLE_U8 reserve[3];
}FrameInfo_t;
/*循环缓冲区管理结构*/
typedef struct _CircularBuffer_t
{
HLE_S8 *resolution; /*当前循环buf所对应的视频分辨率(字符串格式:1920*1080 )*/
pthread_mutex_t BufManageMutex; /*读写锁*/
UserInfo_t userArray[MAX_USER_NUM];/*用户信息描述数组*/
HLE_U8 *bufStart; /*媒体数据buf 起始地址*/
HLE_U32 bufSize; /*buf 空间大小*/
HLE_U32 occupiedSize; /*实际已使用空间大小*/
HLE_U32 writePos; /*写指针偏移*/
FrameInfo_t FrmList[MAX_FRM_NUM]; /*buf 中存储的帧列表信息*/
HLE_U16 FrmList_w; /*写指针,在 FrmList 中的下标*/
HLE_U16 totalFrm; /*总帧数(buffer一圈实际存下的总帧数)*/
HLE_U32 IFrmIndex[MAX_I_F_NUM]; /*buf中I帧在 FrmList 数组中的下标信息*/
HLE_U16 IFrmIndex_w; /*写指针所属的I帧,在 IFrmIndex 中的索引*/
HLE_U16 totalIFrm; /*当前buffer中总的有效的I帧数目*/
HLE_U32 circleNum; /*写buf覆盖的圈数*/
}CircularBuffer_t;
/*******************************************************************************
*@ Description :循环缓冲buffer初始化函数
*@ Input :
*@ Output :
*@ Return :成功:0
失败:-1
*@ attention :不可重复调用
*******************************************************************************/
int CircularBufferInit(void);
/*******************************************************************************
*@ Description :获取缓存池buffer的handle
*@ Input :<resolution>图像的分辨率,内部将依据分辨率返回buffer句柄
*@ Output :
*@ Return :成功:对应循环buffer的句柄
失败:NULL
*@ attention :
*******************************************************************************/
CircularBuffer_t* CircularBufferGetHandle(E_IMAGE_SIZE resolution);
/*******************************************************************************
*@ Description :存放一帧video/audio帧到缓存
*@ Input :<cBuf>缓存指针
<data> 帧数据指针
<length>帧数据长度
*@ Output :
*@ Return :成功:0
失败:-1
*@ attention :传入到该接口的帧,建议都按照之前的帧格式打包好传入
传入的码流帧格式:
视频关键帧: FRAME_HDR + IFRAME_INFO + DATA
视频非关键帧: FRAME_HDR + PFRAME_INFO + DATA
音频帧: FRAME_HDR + AFRAME_INFO + DATA
关于帧类型和帧同步标志选取:
前三个字节帧头同步码和H.264 NALU分割码相同,均为0x00 0x00 0x01
第四个字节使用了H.264中不会使用到的0xF8-0xFF范围
*******************************************************************************/
HLE_S32 CircularBufferPutOneFrame(CircularBuffer_t * cBuf,void *data,HLE_S32 length);
/*******************************************************************************
*@ Description :向循环缓冲buffer 申请一个新的用户ID
*@ Input :<cBuf>buffer句柄(要申请哪一个buffer的用户ID)
*@ Output :
*@ Return :成功:用户ID
失败:-1;
*@ attention :注意,不使用时需要调用函数释放
*******************************************************************************/
HLE_S32 CircularBufferRequestUserID(CircularBuffer_t *cBuf);
/*******************************************************************************
*@ Description :释放申请的循环缓冲buffer的用户ID
*@ Input :<cBuf>buffer句柄(要释放哪一个buffer的用户ID)
<userid>释放的用户ID号
*@ Output :
*@ Return :成功:0
失败:-1;
*@ attention :
*******************************************************************************/
HLE_S32 CircularBufferFreeUserID(CircularBuffer_t *cBuf,HLE_S32 userid);
/*******************************************************************************
*@ Description :从循环buffer中获取一帧数据
*@ Input :<userID>访问缓存buffer的用户ID号
<cBuf>缓存buffer指针
*@ Output :<dataOut>帧首地址
<length>帧数据长度
*@ Return :成功:0
失败:-1
*@ attention :内部超时时间(1S)
*******************************************************************************/
HLE_S32 CircularBufferReadOneFrame(int userID,CircularBuffer_t * cBuf, void **dataOut, FrameInfo_t *pFrameInfo);
/*******************************************************************************
*@ Description :销毁循环缓冲buffer
*@ Input :
*@ Output :
*@ Return :成功:对应循环buffer的句柄
失败:NULL
*@ attention :
*******************************************************************************/
int CircularBufferDestory(void);
#endif
| 2.09375 | 2 |
2024-11-18T22:28:51.831401+00:00 | 2020-12-01T15:03:44 | 0371f0d75b4cb3bd7a59ed8a4630f00e022a97a4 | {
"blob_id": "0371f0d75b4cb3bd7a59ed8a4630f00e022a97a4",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-01T15:18:27",
"content_id": "537e50af392b45fd455d1dbff63e0318157ffb6e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1f3d3f3a5d6be58a374b6290f8544baa7e859150",
"extension": "c",
"filename": "python-module.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 315609619,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3197,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/python-module.c",
"provenance": "stackv2-0132.json.gz:92200",
"repo_name": "wagnerflo/pkgdiff",
"revision_date": "2020-12-01T15:03:44",
"revision_id": "529a046e1e95ee8e1ec1a23d73a6d51a61ea84f6",
"snapshot_id": "6432b4075d46d2e10efb8b1a28ed8cb73589895b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wagnerflo/pkgdiff/529a046e1e95ee8e1ec1a23d73a6d51a61ea84f6/src/python-module.c",
"visit_date": "2023-01-23T12:37:03.909448"
} | stackv2 | /* Copyright 2020 Florian Wagner <florian@wagner-flo.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "pkgdiff.h"
PyDoc_STRVAR(pkgdiff_compare_doc,
"compare(path1, path2, exclude=None)\n"
"--\n\n"
"Compares by FreeBSD pkg metadata the files found at path1 and path2\n"
"while ignoring all fields set in the iterable exclude.\n"
"\n"
"Returns False if pkg metadata differs otherwise True.\n"
);
static PyObject* pkgdiff_compare(PyObject *self, PyObject *args, PyObject* kws) {
int ret = 0;
PyObject* py_pkgname1 = NULL;
PyObject* py_pkgname2 = NULL;
PyObject* py_exclude = NULL;
static char* keywords[] = {
"pkgname1", "pkgname2", "exclude",
NULL
};
if (!PyArg_ParseTupleAndKeywords(
args, kws, "O&O&|O", keywords,
PyUnicode_FSConverter, &py_pkgname1,
PyUnicode_FSConverter, &py_pkgname2,
&py_exclude))
return NULL;
const char** query = malloc(PKGDIFF_QUERY_LEN * sizeof(const char*));
memcpy(query, PKGDIFF_QUERY, PKGDIFF_QUERY_LEN * sizeof(const char*));
if (py_exclude != NULL) {
PyObject* iterator = PyObject_GetIter(py_exclude);
PyObject* item;
if (iterator == NULL)
return NULL;
while ((item = PyIter_Next(iterator))) {
if (!PyUnicode_CheckExact(item)) {
PyErr_Format(PyExc_TypeError, "'%s' object is not a str",
Py_TYPE(item)->tp_name);
Py_DECREF(item);
break;
}
PyObject* ascii = PyUnicode_AsASCIIString(item);
if (ascii == NULL) {
Py_DECREF(item);
break;
}
char* exclude = PyBytes_AsString(ascii);
for (unsigned int i = 0; i < PKGDIFF_QUERY_LEN; i++) {
if (query[i] != NULL && strcmp(query[i], exclude) == 0)
query[i] = NULL;
}
Py_DECREF(ascii);
Py_DECREF(item);
}
Py_DECREF(iterator);
}
if (!PyErr_Occurred()) {
ret = pkgdiff(
PyBytes_AS_STRING(py_pkgname1),
PyBytes_AS_STRING(py_pkgname2),
query,
NULL
);
if (ret == -1)
PyErr_SetFromErrno(PyExc_OSError);
}
free(query);
Py_DECREF(py_pkgname1);
Py_DECREF(py_pkgname2);
if (PyErr_Occurred())
return NULL;
return PyBool_FromLong(!ret);
}
static PyMethodDef pkgdiff_methods[] = {
{ "compare", (PyCFunction) pkgdiff_compare,
METH_VARARGS | METH_KEYWORDS,
pkgdiff_compare_doc },
{ NULL, NULL, 0, NULL }
};
static struct PyModuleDef pkgdiff_module = {
PyModuleDef_HEAD_INIT,
"pkgdiff",
NULL,
-1,
pkgdiff_methods
};
PyMODINIT_FUNC PyInit_pkgdiff(void) {
return PyModule_Create(&pkgdiff_module);
}
| 2.140625 | 2 |
2024-11-18T22:28:52.273365+00:00 | 2020-10-05T07:20:44 | 72692e5219befd6798c3f92ffc49385526075d0f | {
"blob_id": "72692e5219befd6798c3f92ffc49385526075d0f",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-05T07:20:44",
"content_id": "7d922269830cfc284d49b3d86696bd0b1426331b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "f5a2cca80ddf0226359e7ad83c6228f12d4e1328",
"extension": "c",
"filename": "system_init.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": 3742,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/software/InKard-Core/Core/Src/system_init.c",
"provenance": "stackv2-0132.json.gz:92716",
"repo_name": "hyqhyq3/inKard",
"revision_date": "2020-10-05T07:20:44",
"revision_id": "46524f4e7b3d562b626b896f3a70bf5b18e58152",
"snapshot_id": "7f755fbddc2331a0a1636a0e0c0143ba25906140",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hyqhyq3/inKard/46524f4e7b3d562b626b896f3a70bf5b18e58152/software/InKard-Core/Core/Src/system_init.c",
"visit_date": "2022-12-17T23:50:34.280817"
} | stackv2 | #include "system_init.h"
extern UART_HandleTypeDef huart1;
extern void Error_Handler(void);
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
RCC_OscInitStruct.MSIState = RCC_MSI_ON;
RCC_OscInitStruct.MSICalibrationValue = 0;
RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_5;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 38400;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0|GPIO_PIN_1, GPIO_PIN_RESET);
/*Configure GPIO pins : PA2 PA5 PA6 PA7 */
GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PB0 PB1 */
GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : PA8 */
GPIO_InitStruct.Pin = GPIO_PIN_8;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
| 2.34375 | 2 |
2024-11-18T22:28:52.434378+00:00 | 2023-08-13T13:58:07 | 2b8d5b5ddb87cc776d16243e7ab0c0ab801018db | {
"blob_id": "2b8d5b5ddb87cc776d16243e7ab0c0ab801018db",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-13T13:58:07",
"content_id": "a008a3874fc25d3d059160e2809f9ba79db0ea7c",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "7e4eccee4ba976b6694cd944fea75e7835cd1a4b",
"extension": "h",
"filename": "httpserver.h",
"fork_events_count": 0,
"gha_created_at": "2016-03-24T19:11:14",
"gha_event_created_at": "2022-06-06T19:18:26",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 54667633,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5801,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/httpserver.h",
"provenance": "stackv2-0132.json.gz:92979",
"repo_name": "zwizwa/uc_tools",
"revision_date": "2023-08-13T13:58:07",
"revision_id": "20df6f91a2082424b498e384583d7f403ff8bf16",
"snapshot_id": "fc16d39722d5f30164dad524cd86f1aec230f2f4",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/zwizwa/uc_tools/20df6f91a2082424b498e384583d7f403ff8bf16/httpserver.h",
"visit_date": "2023-08-18T20:45:09.789340"
} | stackv2 | #ifndef HTTPSERVER_H
#define HTTPSERVER_H
/* Minimalistic HTTP server implementation.
This is intended to serve some simple pages and to bootstrap a websocket.
Temporary buffers are allocated on the stack, and data is passed to
a callback in parsed form. ( Fold instead of data. )
*/
#define HTTP_READ BLOCKING_IO_READ
#define HTTP_WRITE BLOCKING_IO_WRITE
#include "macros.h"
#include "blocking_io.h"
/* The http errors are a combination of os errors and application
errors. We still use the signed integer encoding cast to a
pointer to be able to distinguish different types properly. */
struct http_err {};
typedef const struct http_err *http_err_t;
/* Wrapper for os errors. */
static inline http_err_t http_err_os(os_error_t e) {
return (http_err_t)e;
}
/* The other errors are part of this enumeration. */
#define HTTP_ERR_BASE (-0x1000) /* for remapping if necessary. */
#define HTTP_ERR(n) ((http_err_t)(((n)&0xF) + HTTP_ERR_BASE))
#define HTTP_ERR_OVERRUN HTTP_ERR(1)
#define HTTP_ERR_INVALID HTTP_ERR(2)
#define HTTP_ERR_OK http_err_os(OS_OK)
struct http_req;
typedef void (*http_close)(struct http_req *);
struct http_req {
http_err_t (*request)(struct http_req *, int method, const char *uri);
http_err_t (*header)(struct http_req *, const char *header, const char *value);
/* The i/o is abstract. This is done essentially for websockets,
which only need socket state. This way the socket can be
allocated separately in a memory pool, and transient http state
can be kept on the stack. */
struct blocking_io *io;
};
void log_c(const uint8_t *buf, uintptr_t len) {
for(uintptr_t i=0; i<len; i++) LOG("%c", buf[i]);
}
/* FIXME: These share the OS address space. Provide an explicit mapper. */
#define HTTP_METHOD_GET 1
#define HTTP_METHOD_PUT 2
/* Don't do anything fancy, just read the headers into a buffer. */
static inline http_err_t http_read_headers(struct http_req *c) {
/* We parse one line at a time, which allows us to keep the buffer
small, and locally managed. Callbacks can use the memory in
the extent of the call. */
os_error_t error = OS_OK;
char buf[4096];
uintptr_t len = 0;
uintptr_t nb_lines = 0;
for(;;) {
if (len >= sizeof(buf)) return HTTP_ERR_OVERRUN;
HTTP_READ(c->io, (uint8_t*)&buf[len++], 1);
if ((len >= 2) && (buf[len-2] == 0xd) && (buf[len-1] == 0xa)) {
/* End of line. Convert 0d,0a to cstring. */
len -= 2; buf[len] = 0;
if (len == 0) { break; }
if (0 == nb_lines) {
/* Only HTTP/1.1 GET is supported. */
if (len < (3+1+1+1+8)) {
return HTTP_ERR_INVALID;
};
int method;
if (!strncmp(buf,"GET ",3+1)) {
method = HTTP_METHOD_GET;
}
else if (!strncmp(buf,"PUT ",3+1)) {
method = HTTP_METHOD_PUT;
}
else {
return HTTP_ERR_INVALID;
};
if (strcmp(buf+len-8,"HTTP/1.1")) {
return HTTP_ERR_INVALID;
};
buf[len-9] = 0;
http_err_t req_err;
if (HTTP_ERR_OK != (req_err = c->request(c, method, buf+4))) {
return req_err;
}
}
else {
/* Split header and value. */
const char *val = "";
for(uintptr_t i=0; i<len; i++) {
if (buf[i] == ':') {
buf[i] = 0;
if (len < i+2) {
return HTTP_ERR_INVALID;
}
val = buf+i+2;
break;
}
}
http_err_t req_err;
if ((req_err = c->header(c, buf, val))) {
return req_err;
}
}
len = 0;
nb_lines++;
}
}
return HTTP_ERR_OK;
error_exit:
/* os error handler. */
OS_LOG_ERROR("http_read_headers", error);
return http_err_os(error);
}
static inline void http_write_str(struct http_req *s, const char *str) {
s->io->write(s->io, (const uint8_t*)str, strlen(str));
}
static inline void http_write_100_resp(struct http_req *s) {
http_write_str(s, "HTTP/1.0 100 Continue\r\n\r\n");
}
static inline void http_write_200_resp(struct http_req *s, const char *type) {
http_write_str(s, "HTTP/1.0 200 OK\r\nContent-Type: ");
http_write_str(s, type);
http_write_str(s, "\r\n\r\n");
}
static inline void http_write_201_resp(struct http_req *s) {
http_write_str(s, "HTTP/1.0 201 Created\r\n\r\n");
}
static inline void http_write_404_resp(struct http_req *s) {
http_write_str(s, "HTTP/1.0 404 Not Found\r\nContent-Type: text/html; charset=ISO-8859-1\r\n\r\n");
}
/* Set type based on extension. */
const char *http_file_type(const char *filename) {
const struct {
const char *ext;
const char *type;
} ext_to_type[] = {
{".c", "text/plain; charset=UTF-8"},
{".txt", "text/plain; charset=UTF-8"},
{".html", "text/html; charset=UTF-8"},
{".js", "text/javascript; charset=UTF-8"},
{".wasm", "application/wasm"},
{".svg", "image/svg+xml"},
{".ico", "image/png"},
};
size_t n = strlen(filename);
while(n--) {
if (filename[n] == '.') {
FOR_ARRAY(ext_to_type,e2t) {
if (!strcmp(filename+n,e2t->ext)) { return e2t->type; }
}
break;
}
}
return ext_to_type[0].type;
}
#endif
| 2.46875 | 2 |
2024-11-18T22:28:52.527613+00:00 | 2023-08-08T06:09:20 | a89832eebe4a491f1479e6524eee1d10825fba3c | {
"blob_id": "a89832eebe4a491f1479e6524eee1d10825fba3c",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T04:38:20",
"content_id": "6602026b738ad393028f35fd5359400e59403d7b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0744dcc5394cebf57ebcba343747af6871b67017",
"extension": "h",
"filename": "things_resource.h",
"fork_events_count": 719,
"gha_created_at": "2017-02-20T04:38:30",
"gha_event_created_at": "2023-09-14T06:54:49",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 82517252,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12457,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/framework/src/st_things/things_stack/things_resource.h",
"provenance": "stackv2-0132.json.gz:93111",
"repo_name": "Samsung/TizenRT",
"revision_date": "2023-08-08T06:09:20",
"revision_id": "1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686",
"snapshot_id": "96abf62f1853f61fcf91ff14671a5e0c6ca48fdb",
"src_encoding": "UTF-8",
"star_events_count": 590,
"url": "https://raw.githubusercontent.com/Samsung/TizenRT/1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686/framework/src/st_things/things_stack/things_resource.h",
"visit_date": "2023-08-31T08:59:33.327998"
} | stackv2 | /* ****************************************************************
*
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
#ifndef _THINGS_RESOURCE_H_
#define _THINGS_RESOURCE_H_
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <octypes.h>
//-----------------------------------------------------------------------------
// Defines
//-----------------------------------------------------------------------------
#define QUERY_DELIMITER ";" // or "#"
//-----------------------------------------------------------------------------
// Typedefs
//-----------------------------------------------------------------------------
/* Structure for Array Attribute */
typedef struct things_representation_s {
void *payload; // 8 bytes
void **children_payload; // 8 bytes
int64_t num_children; // 8 bytes
struct things_representation_s **children; // 8 * num_children bytes
/**
* @brief API for setting value with a key
* @param key : Attribute Key which will represent the value
* @param value : Attribute value
*/
void (*things_set_value)(struct things_representation_s *rep, char *key, char *);
void (*things_set_bool_value)(struct things_representation_s *rep, char *key, bool);
void (*things_set_int_value)(struct things_representation_s *rep, char *key, int64_t);
void (*things_set_double_value)(struct things_representation_s *rep, char *key, double);
void (*things_set_byte_value)(struct things_representation_s *rep, char *key, uint8_t *value, size_t size);
bool(*things_set_object_value)(struct things_representation_s *mother, char *key, struct things_representation_s *child);
/**
* @brief API for setting/getting object array type of attribute.
* @param key : Attribute Key which will represent the array type of value
* @param length : Length of value(representation) array
* @param reps : Array type (representation) values
*/
bool(*things_set_arrayvalue)(struct things_representation_s *, char *key, int length, struct things_representation_s **reps);
bool(*things_get_arrayvalue)(struct things_representation_s *, char *key, int *length, struct things_representation_s ***reps);
/**
* @brief API for setting/getting string array type of attribute.
* @param key : Attribute Key which will represent the array type of value
* @param length : Length of value(string) array
* @param array : Array type string values
*/
void (*things_set_string_arrayvalue)(struct things_representation_s *mother, char *key, int length, char **array);
bool(*things_get_string_arrayvalue)(struct things_representation_s *mother, char *key, int *length, char ***array);
/**
* @brief API for setting/getting double array type of attribute.
* @param key : Attribute Key which will represent the array type of value
* @param length : Length of value(double) array
* @param array : Array type double values
*/
void (*things_set_double_arrayvalue)(struct things_representation_s *mother, char *key, int length, double *array);
bool(*things_get_double_arrayvalue)(struct things_representation_s *mother, char *key, int *length, double **array);
/**
* @brief API for inserting int array type of attribute.
* @param key : Attribute Key which will represent the array type of value
* @param length : Length of value(int) array
* @param array : Array type int values
*/
void (*things_set_int_arrayvalue)(struct things_representation_s *mother, char *key, int length, int64_t *array);
bool(*things_get_int_arrayvalue)(struct things_representation_s *mother, char *key, int *length, int64_t **array);
/**
* @brief API for getting value with a key
* @param key : Attribute Key which represents the value
* @param value : Reference of the variable to where value will be copied
* @return : true(value exist), false(value not exist)
*/
bool(*things_get_value)(struct things_representation_s *rep, char *key, char **);
bool(*things_get_bool_value)(struct things_representation_s *rep, char *key, bool *);
bool(*things_get_int_value)(struct things_representation_s *rep, char *key, int64_t *);
bool(*things_get_double_value)(struct things_representation_s *rep, char *key, double *);
bool(*things_get_byte_value)(struct things_representation_s *rep, char *key, uint8_t **value, size_t *size);
bool(*things_get_object_value)(struct things_representation_s *mother, char *key, struct things_representation_s *child);
} things_representation_s;
/* Structure for Things resource */
typedef struct things_resource_s {
char *query; // 4 bytes
char *uri; // 4 Bytes
char *res_type; // 4 Bytes
char *interface_type; // 4 Bytes
OCRequestHandle request_handle;
OCResourceHandle resource_handle; // 4 Bytes, OCResourceHandle handle;
int req_type; // 4 Bytes
double error; // 8 Bytes
struct things_resource_s *next; // 4 Bytes
struct things_representation_s *rep; // 4 Bytes
size_t size; // 4 bytes
char *cmd_id; // 4 Bytes
void *dev_addr; // sizeof(OCDevAddr) ????
void (*things_set_dev_addr)(struct things_resource_s *, void *OCDevAddr);
void *(*things_get_dev_addr)(struct things_resource_s *);
/**
* @brief API for setting URI.
* @param things_resource_s * : Instance of target resource
* @param const char * : URI string value
*/
void (*things_set_uri)(struct things_resource_s *, const char *uri);
/**
* @brief API for setting error when returning request handling result
* @param things_resource_s * : Instance of target resource
* @param double : error code
*/
void (*things_set_error)(struct things_resource_s *, double errorCode);
/**
* @brief API for getting query value
* @param things_resource_s * : Instance of target resource
* @param char* key : key value to look up in the query(ex: query -> key=value?key=value?...)
* @param char* value : value of the key in the query
* @return : true(query exist), false(query not exist)
*/
bool(*things_get_query)(struct things_resource_s *, char *key, char **value);
/**
* @brief API for getting URI
* @param things_resource_s * : Instance of target resource
* @param char** uri : reference of the char* variable to where uri will be copied
*/
void (*things_get_uri)(struct things_resource_s *, char **uri);
/**
* @brief API for getting # of supporting resource types
* @param things_resource_s * : Instance of target resource
* @return : Number of supporting resource types
*/
int (*things_get_num_of_res_types)(struct things_resource_s *);
int (*things_get_num_of_inf_types)(struct things_resource_s *);
/**
* @brief API for getting # of supporting resource type with index
* @param things_resource_s * : Instance of target resource
* @param things_resource_s * : Index of supported resource type list
* @return : Supporting resource type
*/
const char *(*things_get_res_type)(struct things_resource_s *, int index);
const char *(*things_get_inf_type)(struct things_resource_s *, int index);
/**
* @brief API for getting childrens of target resource
* @param things_resource_s * : Instance of target resource
* @return : Instance of children resource
* (Children resource are managed with Linked List)
*/
struct things_resource_s *(*things_get_children)(struct things_resource_s *);
/**
* @brief API for setting representation of the target resource
* @param things_resource_s * : Instance of target resource
* @param things_representation_s * : Instance of the representation to set
*/
void (*things_set_representation)(struct things_resource_s *, struct things_representation_s *rep);
/**
* @brief API for getting representation of the target resource
* @param things_resource_s * : Instance of target resource
* @param things_representation_s * : Instance of the representation to set
* @return : true(Representation exist), false(Representation not exist)
*/
bool(*things_get_representation)(struct things_resource_s *, struct things_representation_s **rep);
/**
* @brief API for getting payload (Internal use only, NOT API)
* @param things_resource_s * : Instance of target resource
* @return : Instance OCRepPayload data structure defined by IoTivity stack
*/
void *(*things_get_rep_payload)(struct things_resource_s *);
/**
* @brief API for creating instance of payload (Internal use only, NOT API)
* @param things_resource_s * : Instance of target resource
* @return : New instance OCRepPayload data structure defined by IoTivity stack
*/
void *(*things_create_payload)(struct things_resource_s *, char *);
/**
* @brief API for checking whether given interface type is supporting one or not
* @param things_resource_s * : Instance of target resource
* @param iftype : Interface type to check
* @return : true (supporting interface type),false(not supporting)
*/
bool(*things_is_supporting_interface_type)(struct things_resource_s *, char *ifType);
/**
* @brief API for checking whether given resource type is supporting one or not
* @param things_resource_s * : Instance of target resource
* @param iftype : Resource type to check
* @return : true (supporting resource type),false(not supporting)
*/
bool(*things_is_supporting_resource_type)(struct things_resource_s *, char *res_type);
/**
* @brief API for setting frameid
* @brief Frameid will be used to match the response delivered from st_things SW with received request
* @param things_resource_s * : Instance of target resource
* @param cmd_id : Frame ID
*/
void (*things_set_command_id)(struct things_resource_s *res, char *cmd_id);
/**
* @brief API for getting children resource instances
* @param things_resource_s * : Instance of target resource
* @return : Instance of children resource(s)
*/
struct things_resource_s *(*things_get_next)(struct things_resource_s *);
/**
* @brief API for adding children resource instances
* @param things_resource_s * : Instance of target resource
* @param things_resource_s * : Instance of children resource
*/
void (*things_add_child)(struct things_resource_s *, struct things_resource_s *);
} things_resource_s;
/**
* @brief API for creating instance of payload
* @param rep_payload : Instance of target resource
* @return things_representation_s * : Instance of resource repsentation
*/
things_representation_s *things_create_representation_inst(void *rep_payload);
/**
* @brief API for creating instance of resource
* @param void* : Instance of request handle
* @param void* : Instance of resource handle
* @param void* : Query in the request message
* @param void* : Instance of payload in the request
* @return things_resource_s * : Instance of resource repsentation
*/
things_resource_s *things_create_resource_inst(OCRequestHandle, OCResourceHandle, void *, void *);
/**
* @brief API for cloning instance of given resource
* @param things_resource_s * : Instance of resource to clone
* @return things_resource_s * : Instance of cloned resource
*/
things_resource_s *things_clone_resource_inst(things_resource_s *);
/**
* @brief API for releasing memory allocated for the instance of given representation
* @param things_representation_s * : Instance of representation to release
*/
void things_release_representation_inst(things_representation_s *);
/**
* @brief API for releasing memory allocated for the instance of given resource
* @param things_representation_s * : Instance of resource to release
*/
void things_release_resource_inst(things_resource_s *);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // _THINGS_RESOURCE_H_
| 2.234375 | 2 |
2024-11-18T22:28:53.060850+00:00 | 2019-08-29T21:54:06 | b28d06df25ba35c955bb0f96a062908efa5687ce | {
"blob_id": "b28d06df25ba35c955bb0f96a062908efa5687ce",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-29T21:54:06",
"content_id": "bb24e7ee59829ca1450a8561ffa587f25c5312c1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "a96d5932fce124683280268b3be81d15d2683887",
"extension": "c",
"filename": "Thirdpartyownership.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": 56055,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/Thirdpartyownership.c",
"provenance": "stackv2-0132.json.gz:93500",
"repo_name": "ascillato/pysam",
"revision_date": "2019-08-29T21:54:06",
"revision_id": "e7a36329732be6bc8b4bda9df9e59f2731923f8c",
"snapshot_id": "115bbdbf3608606946897d05768ba9e2f3268265",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ascillato/pysam/e7a36329732be6bc8b4bda9df9e59f2731923f8c/src/Thirdpartyownership.c",
"visit_date": "2020-08-14T12:27:21.770020"
} | stackv2 | #include <Python.h>
#include <SAM_Thirdpartyownership.h>
#include <SAM_api.h>
#include "PySAM_utils.h"
/*
* Depreciation Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} DepreciationObject;
static PyTypeObject Depreciation_Type;
static PyObject *
Depreciation_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = Depreciation_Type.tp_alloc(&Depreciation_Type,0);
DepreciationObject* Depreciation_obj = (DepreciationObject*)new_obj;
Depreciation_obj->data_ptr = data_ptr;
return new_obj;
}
/* Depreciation methods */
static PyObject *
Depreciation_assign(DepreciationObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "Depreciation")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
Depreciation_export(DepreciationObject *self, PyObject *args)
{
PyTypeObject* tp = &Depreciation_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef Depreciation_methods[] = {
{"assign", (PyCFunction)Depreciation_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``Depreciation_vals = { var: val, ...}``")},
{"export", (PyCFunction)Depreciation_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
Depreciation_get_depr_fed_custom(DepreciationObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Depreciation_depr_fed_custom_aget, self->data_ptr);
}
static int
Depreciation_set_depr_fed_custom(DepreciationObject *self, PyObject *value, void *closure)
{
return PySAM_array_setter(value, SAM_Thirdpartyownership_Depreciation_depr_fed_custom_aset, self->data_ptr);
}
static PyObject *
Depreciation_get_depr_fed_sl_years(DepreciationObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Depreciation_depr_fed_sl_years_nget, self->data_ptr);
}
static int
Depreciation_set_depr_fed_sl_years(DepreciationObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_Depreciation_depr_fed_sl_years_nset, self->data_ptr);
}
static PyObject *
Depreciation_get_depr_fed_type(DepreciationObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Depreciation_depr_fed_type_nget, self->data_ptr);
}
static int
Depreciation_set_depr_fed_type(DepreciationObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_Depreciation_depr_fed_type_nset, self->data_ptr);
}
static PyObject *
Depreciation_get_depr_sta_custom(DepreciationObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Depreciation_depr_sta_custom_aget, self->data_ptr);
}
static int
Depreciation_set_depr_sta_custom(DepreciationObject *self, PyObject *value, void *closure)
{
return PySAM_array_setter(value, SAM_Thirdpartyownership_Depreciation_depr_sta_custom_aset, self->data_ptr);
}
static PyObject *
Depreciation_get_depr_sta_sl_years(DepreciationObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Depreciation_depr_sta_sl_years_nget, self->data_ptr);
}
static int
Depreciation_set_depr_sta_sl_years(DepreciationObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_Depreciation_depr_sta_sl_years_nset, self->data_ptr);
}
static PyObject *
Depreciation_get_depr_sta_type(DepreciationObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Depreciation_depr_sta_type_nget, self->data_ptr);
}
static int
Depreciation_set_depr_sta_type(DepreciationObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_Depreciation_depr_sta_type_nset, self->data_ptr);
}
static PyGetSetDef Depreciation_getset[] = {
{"depr_fed_custom", (getter)Depreciation_get_depr_fed_custom,(setter)Depreciation_set_depr_fed_custom,
PyDoc_STR("*sequence*: Federal custom depreciation [%/year]\n\n*Required*: set to 3 if not provided."),
NULL},
{"depr_fed_sl_years", (getter)Depreciation_get_depr_fed_sl_years,(setter)Depreciation_set_depr_fed_sl_years,
PyDoc_STR("*float*: Federal depreciation straight-line Years [years]\n\n*Constraints*: INTEGER,POSITIVE\n\n*Required*: set to 2 if not provided."),
NULL},
{"depr_fed_type", (getter)Depreciation_get_depr_fed_type,(setter)Depreciation_set_depr_fed_type,
PyDoc_STR("*float*: Federal depreciation type\n\n*Options*: 0=none,1=macrs_half_year,2=sl,3=custom\n\n*Constraints*: INTEGER,MIN=0,MAX=3\n\n*Required*: set to 0 if not provided."),
NULL},
{"depr_sta_custom", (getter)Depreciation_get_depr_sta_custom,(setter)Depreciation_set_depr_sta_custom,
PyDoc_STR("*sequence*: State custom depreciation [%/year]\n\n*Required*: set to 3 if not provided."),
NULL},
{"depr_sta_sl_years", (getter)Depreciation_get_depr_sta_sl_years,(setter)Depreciation_set_depr_sta_sl_years,
PyDoc_STR("*float*: State depreciation straight-line years [years]\n\n*Constraints*: INTEGER,POSITIVE\n\n*Required*: set to 2 if not provided."),
NULL},
{"depr_sta_type", (getter)Depreciation_get_depr_sta_type,(setter)Depreciation_set_depr_sta_type,
PyDoc_STR("*float*: State depreciation type\n\n*Options*: 0=none,1=macrs_half_year,2=sl,3=custom\n\n*Constraints*: INTEGER,MIN=0,MAX=3\n\n*Required*: set to 0 if not provided."),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject Depreciation_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.Depreciation", /*tp_name*/
sizeof(DepreciationObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
Depreciation_methods, /*tp_methods*/
0, /*tp_members*/
Depreciation_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* Financials Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} FinancialsObject;
static PyTypeObject Financials_Type;
static PyObject *
Financials_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = Financials_Type.tp_alloc(&Financials_Type,0);
FinancialsObject* Financials_obj = (FinancialsObject*)new_obj;
Financials_obj->data_ptr = data_ptr;
return new_obj;
}
/* Financials methods */
static PyObject *
Financials_assign(FinancialsObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "Financials")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
Financials_export(FinancialsObject *self, PyObject *args)
{
PyTypeObject* tp = &Financials_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef Financials_methods[] = {
{"assign", (PyCFunction)Financials_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``Financials_vals = { var: val, ...}``")},
{"export", (PyCFunction)Financials_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
Financials_get_analysis_period(FinancialsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Financials_analysis_period_nget, self->data_ptr);
}
static int
Financials_set_analysis_period(FinancialsObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_Financials_analysis_period_nset, self->data_ptr);
}
static PyObject *
Financials_get_inflation_rate(FinancialsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Financials_inflation_rate_nget, self->data_ptr);
}
static int
Financials_set_inflation_rate(FinancialsObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_Financials_inflation_rate_nset, self->data_ptr);
}
static PyObject *
Financials_get_real_discount_rate(FinancialsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Financials_real_discount_rate_nget, self->data_ptr);
}
static int
Financials_set_real_discount_rate(FinancialsObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_Financials_real_discount_rate_nset, self->data_ptr);
}
static PyGetSetDef Financials_getset[] = {
{"analysis_period", (getter)Financials_get_analysis_period,(setter)Financials_set_analysis_period,
PyDoc_STR("*float*: Analyis period [years]\n\n*Constraints*: INTEGER,MIN=0,MAX=50\n\n*Required*: set to 30 if not provided."),
NULL},
{"inflation_rate", (getter)Financials_get_inflation_rate,(setter)Financials_set_inflation_rate,
PyDoc_STR("*float*: Inflation rate [%]\n\n*Constraints*: MIN=-99\n\n*Required*: True"),
NULL},
{"real_discount_rate", (getter)Financials_get_real_discount_rate,(setter)Financials_set_real_discount_rate,
PyDoc_STR("*float*: Real discount rate [%]\n\n*Constraints*: MIN=-99\n\n*Required*: True"),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject Financials_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.Financials", /*tp_name*/
sizeof(FinancialsObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
Financials_methods, /*tp_methods*/
0, /*tp_members*/
Financials_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* FinancialThirdPartyOwnership Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} FinancialThirdPartyOwnershipObject;
static PyTypeObject FinancialThirdPartyOwnership_Type;
static PyObject *
FinancialThirdPartyOwnership_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = FinancialThirdPartyOwnership_Type.tp_alloc(&FinancialThirdPartyOwnership_Type,0);
FinancialThirdPartyOwnershipObject* FinancialThirdPartyOwnership_obj = (FinancialThirdPartyOwnershipObject*)new_obj;
FinancialThirdPartyOwnership_obj->data_ptr = data_ptr;
return new_obj;
}
/* FinancialThirdPartyOwnership methods */
static PyObject *
FinancialThirdPartyOwnership_assign(FinancialThirdPartyOwnershipObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "FinancialThirdPartyOwnership")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
FinancialThirdPartyOwnership_export(FinancialThirdPartyOwnershipObject *self, PyObject *args)
{
PyTypeObject* tp = &FinancialThirdPartyOwnership_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef FinancialThirdPartyOwnership_methods[] = {
{"assign", (PyCFunction)FinancialThirdPartyOwnership_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``FinancialThirdPartyOwnership_vals = { var: val, ...}``")},
{"export", (PyCFunction)FinancialThirdPartyOwnership_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
FinancialThirdPartyOwnership_get_lease_or_ppa(FinancialThirdPartyOwnershipObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_FinancialThirdPartyOwnership_lease_or_ppa_nget, self->data_ptr);
}
static int
FinancialThirdPartyOwnership_set_lease_or_ppa(FinancialThirdPartyOwnershipObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_FinancialThirdPartyOwnership_lease_or_ppa_nset, self->data_ptr);
}
static PyGetSetDef FinancialThirdPartyOwnership_getset[] = {
{"lease_or_ppa", (getter)FinancialThirdPartyOwnership_get_lease_or_ppa,(setter)FinancialThirdPartyOwnership_set_lease_or_ppa,
PyDoc_STR("*float*: Lease or PPA agreement [0/1]\n\n*Options*: 0=lease,1=ppa\n\n*Constraints*: INTEGER,MIN=0,MAX=1\n\n*Required*: set to 0 if not provided."),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject FinancialThirdPartyOwnership_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.FinancialThirdPartyOwnership", /*tp_name*/
sizeof(FinancialThirdPartyOwnershipObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
FinancialThirdPartyOwnership_methods, /*tp_methods*/
0, /*tp_members*/
FinancialThirdPartyOwnership_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* Common Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} CommonObject;
static PyTypeObject Common_Type;
static PyObject *
Common_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = Common_Type.tp_alloc(&Common_Type,0);
CommonObject* Common_obj = (CommonObject*)new_obj;
Common_obj->data_ptr = data_ptr;
return new_obj;
}
/* Common methods */
static PyObject *
Common_assign(CommonObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "Common")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
Common_export(CommonObject *self, PyObject *args)
{
PyTypeObject* tp = &Common_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef Common_methods[] = {
{"assign", (PyCFunction)Common_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``Common_vals = { var: val, ...}``")},
{"export", (PyCFunction)Common_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
Common_get_annual_energy_value(CommonObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Common_annual_energy_value_aget, self->data_ptr);
}
static int
Common_set_annual_energy_value(CommonObject *self, PyObject *value, void *closure)
{
return PySAM_array_setter(value, SAM_Thirdpartyownership_Common_annual_energy_value_aset, self->data_ptr);
}
static PyObject *
Common_get_gen(CommonObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Common_gen_aget, self->data_ptr);
}
static int
Common_set_gen(CommonObject *self, PyObject *value, void *closure)
{
return PySAM_array_setter(value, SAM_Thirdpartyownership_Common_gen_aset, self->data_ptr);
}
static PyGetSetDef Common_getset[] = {
{"annual_energy_value", (getter)Common_get_annual_energy_value,(setter)Common_set_annual_energy_value,
PyDoc_STR("*sequence*: Energy value [$]\n\n*Required*: True"),
NULL},
{"gen", (getter)Common_get_gen,(setter)Common_set_gen,
PyDoc_STR("*sequence*: Power generated by renewable resource [kW]\n\n*Required*: True"),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject Common_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.Common", /*tp_name*/
sizeof(CommonObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
Common_methods, /*tp_methods*/
0, /*tp_members*/
Common_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* AnnualOutput Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} AnnualOutputObject;
static PyTypeObject AnnualOutput_Type;
static PyObject *
AnnualOutput_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = AnnualOutput_Type.tp_alloc(&AnnualOutput_Type,0);
AnnualOutputObject* AnnualOutput_obj = (AnnualOutputObject*)new_obj;
AnnualOutput_obj->data_ptr = data_ptr;
return new_obj;
}
/* AnnualOutput methods */
static PyObject *
AnnualOutput_assign(AnnualOutputObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "AnnualOutput")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
AnnualOutput_export(AnnualOutputObject *self, PyObject *args)
{
PyTypeObject* tp = &AnnualOutput_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef AnnualOutput_methods[] = {
{"assign", (PyCFunction)AnnualOutput_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``AnnualOutput_vals = { var: val, ...}``")},
{"export", (PyCFunction)AnnualOutput_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
AnnualOutput_get_degradation(AnnualOutputObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_AnnualOutput_degradation_aget, self->data_ptr);
}
static int
AnnualOutput_set_degradation(AnnualOutputObject *self, PyObject *value, void *closure)
{
return PySAM_array_setter(value, SAM_Thirdpartyownership_AnnualOutput_degradation_aset, self->data_ptr);
}
static PyObject *
AnnualOutput_get_system_use_lifetime_output(AnnualOutputObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_AnnualOutput_system_use_lifetime_output_nget, self->data_ptr);
}
static int
AnnualOutput_set_system_use_lifetime_output(AnnualOutputObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_AnnualOutput_system_use_lifetime_output_nset, self->data_ptr);
}
static PyGetSetDef AnnualOutput_getset[] = {
{"degradation", (getter)AnnualOutput_get_degradation,(setter)AnnualOutput_set_degradation,
PyDoc_STR("*sequence*: Annual degradation [%]\n\n*Required*: True"),
NULL},
{"system_use_lifetime_output", (getter)AnnualOutput_get_system_use_lifetime_output,(setter)AnnualOutput_set_system_use_lifetime_output,
PyDoc_STR("*float*: Lifetime hourly system outputs [0/1]\n\n*Options*: 0=hourly first year,1=hourly lifetime\n\n*Constraints*: INTEGER,MIN=0\n\n*Required*: True"),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject AnnualOutput_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.AnnualOutput", /*tp_name*/
sizeof(AnnualOutputObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
AnnualOutput_methods, /*tp_methods*/
0, /*tp_members*/
AnnualOutput_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* CashFlow Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} CashFlowObject;
static PyTypeObject CashFlow_Type;
static PyObject *
CashFlow_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = CashFlow_Type.tp_alloc(&CashFlow_Type,0);
CashFlowObject* CashFlow_obj = (CashFlowObject*)new_obj;
CashFlow_obj->data_ptr = data_ptr;
return new_obj;
}
/* CashFlow methods */
static PyObject *
CashFlow_assign(CashFlowObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "CashFlow")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
CashFlow_export(CashFlowObject *self, PyObject *args)
{
PyTypeObject* tp = &CashFlow_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef CashFlow_methods[] = {
{"assign", (PyCFunction)CashFlow_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``CashFlow_vals = { var: val, ...}``")},
{"export", (PyCFunction)CashFlow_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
CashFlow_get_lease_escalation(CashFlowObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_CashFlow_lease_escalation_nget, self->data_ptr);
}
static int
CashFlow_set_lease_escalation(CashFlowObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_CashFlow_lease_escalation_nset, self->data_ptr);
}
static PyObject *
CashFlow_get_lease_price(CashFlowObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_CashFlow_lease_price_nget, self->data_ptr);
}
static int
CashFlow_set_lease_price(CashFlowObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_CashFlow_lease_price_nset, self->data_ptr);
}
static PyObject *
CashFlow_get_ppa_escalation(CashFlowObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_CashFlow_ppa_escalation_nget, self->data_ptr);
}
static int
CashFlow_set_ppa_escalation(CashFlowObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_CashFlow_ppa_escalation_nset, self->data_ptr);
}
static PyObject *
CashFlow_get_ppa_price(CashFlowObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_CashFlow_ppa_price_nget, self->data_ptr);
}
static int
CashFlow_set_ppa_price(CashFlowObject *self, PyObject *value, void *closure)
{
return PySAM_double_setter(value, SAM_Thirdpartyownership_CashFlow_ppa_price_nset, self->data_ptr);
}
static PyGetSetDef CashFlow_getset[] = {
{"lease_escalation", (getter)CashFlow_get_lease_escalation,(setter)CashFlow_set_lease_escalation,
PyDoc_STR("*float*: Monthly lease escalation [%/year]\n\n*Required*: set to 0 if not provided."),
NULL},
{"lease_price", (getter)CashFlow_get_lease_price,(setter)CashFlow_set_lease_price,
PyDoc_STR("*float*: Monthly lease price [$/month]\n\n*Required*: set to 0 if not provided."),
NULL},
{"ppa_escalation", (getter)CashFlow_get_ppa_escalation,(setter)CashFlow_set_ppa_escalation,
PyDoc_STR("*float*: Monthly lease escalation [%/year]\n\n*Required*: set to 1 if not provided."),
NULL},
{"ppa_price", (getter)CashFlow_get_ppa_price,(setter)CashFlow_set_ppa_price,
PyDoc_STR("*float*: Monthly lease price [$/month]\n\n*Required*: set to 1 if not provided."),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject CashFlow_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.CashFlow", /*tp_name*/
sizeof(CashFlowObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
CashFlow_methods, /*tp_methods*/
0, /*tp_members*/
CashFlow_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* ElectricityCost Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} ElectricityCostObject;
static PyTypeObject ElectricityCost_Type;
static PyObject *
ElectricityCost_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = ElectricityCost_Type.tp_alloc(&ElectricityCost_Type,0);
ElectricityCostObject* ElectricityCost_obj = (ElectricityCostObject*)new_obj;
ElectricityCost_obj->data_ptr = data_ptr;
return new_obj;
}
/* ElectricityCost methods */
static PyObject *
ElectricityCost_assign(ElectricityCostObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "ElectricityCost")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
ElectricityCost_export(ElectricityCostObject *self, PyObject *args)
{
PyTypeObject* tp = &ElectricityCost_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef ElectricityCost_methods[] = {
{"assign", (PyCFunction)ElectricityCost_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``ElectricityCost_vals = { var: val, ...}``")},
{"export", (PyCFunction)ElectricityCost_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
ElectricityCost_get_elec_cost_with_system(ElectricityCostObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_ElectricityCost_elec_cost_with_system_aget, self->data_ptr);
}
static int
ElectricityCost_set_elec_cost_with_system(ElectricityCostObject *self, PyObject *value, void *closure)
{
return PySAM_array_setter(value, SAM_Thirdpartyownership_ElectricityCost_elec_cost_with_system_aset, self->data_ptr);
}
static PyObject *
ElectricityCost_get_elec_cost_without_system(ElectricityCostObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_ElectricityCost_elec_cost_without_system_aget, self->data_ptr);
}
static int
ElectricityCost_set_elec_cost_without_system(ElectricityCostObject *self, PyObject *value, void *closure)
{
return PySAM_array_setter(value, SAM_Thirdpartyownership_ElectricityCost_elec_cost_without_system_aset, self->data_ptr);
}
static PyGetSetDef ElectricityCost_getset[] = {
{"elec_cost_with_system", (getter)ElectricityCost_get_elec_cost_with_system,(setter)ElectricityCost_set_elec_cost_with_system,
PyDoc_STR("*sequence*: Energy value [$]\n\n*Required*: True"),
NULL},
{"elec_cost_without_system", (getter)ElectricityCost_get_elec_cost_without_system,(setter)ElectricityCost_set_elec_cost_without_system,
PyDoc_STR("*sequence*: Energy value [$]\n\n*Required*: True"),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject ElectricityCost_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.ElectricityCost", /*tp_name*/
sizeof(ElectricityCostObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
ElectricityCost_methods, /*tp_methods*/
0, /*tp_members*/
ElectricityCost_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* Outputs Group
*/
typedef struct {
PyObject_HEAD
SAM_Thirdpartyownership data_ptr;
} OutputsObject;
static PyTypeObject Outputs_Type;
static PyObject *
Outputs_new(SAM_Thirdpartyownership data_ptr)
{
PyObject* new_obj = Outputs_Type.tp_alloc(&Outputs_Type,0);
OutputsObject* Outputs_obj = (OutputsObject*)new_obj;
Outputs_obj->data_ptr = data_ptr;
return new_obj;
}
/* Outputs methods */
static PyObject *
Outputs_assign(OutputsObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_dict(self->data_ptr, dict, "Thirdpartyownership", "Outputs")){
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
Outputs_export(OutputsObject *self, PyObject *args)
{
PyTypeObject* tp = &Outputs_Type;
PyObject* dict = PySAM_export_to_dict((PyObject *) self, tp);
return dict;
}
static PyMethodDef Outputs_methods[] = {
{"assign", (PyCFunction)Outputs_assign, METH_VARARGS,
PyDoc_STR("assign() -> None\n Assign attributes from dictionary\n\n``Outputs_vals = { var: val, ...}``")},
{"export", (PyCFunction)Outputs_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
Outputs_get_cf_after_tax_cash_flow(OutputsObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Outputs_cf_after_tax_cash_flow_aget, self->data_ptr);
}
static PyObject *
Outputs_get_cf_after_tax_net_equity_cost_flow(OutputsObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Outputs_cf_after_tax_net_equity_cost_flow_aget, self->data_ptr);
}
static PyObject *
Outputs_get_cf_agreement_cost(OutputsObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Outputs_cf_agreement_cost_aget, self->data_ptr);
}
static PyObject *
Outputs_get_cf_cumulative_payback_with_expenses(OutputsObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Outputs_cf_cumulative_payback_with_expenses_aget, self->data_ptr);
}
static PyObject *
Outputs_get_cf_energy_net(OutputsObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Outputs_cf_energy_net_aget, self->data_ptr);
}
static PyObject *
Outputs_get_cf_length(OutputsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Outputs_cf_length_nget, self->data_ptr);
}
static PyObject *
Outputs_get_cf_nte(OutputsObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Outputs_cf_nte_aget, self->data_ptr);
}
static PyObject *
Outputs_get_cf_payback_with_expenses(OutputsObject *self, void *closure)
{
return PySAM_array_getter(SAM_Thirdpartyownership_Outputs_cf_payback_with_expenses_aget, self->data_ptr);
}
static PyObject *
Outputs_get_lnte_nom(OutputsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Outputs_lnte_nom_nget, self->data_ptr);
}
static PyObject *
Outputs_get_lnte_real(OutputsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Outputs_lnte_real_nget, self->data_ptr);
}
static PyObject *
Outputs_get_npv(OutputsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Outputs_npv_nget, self->data_ptr);
}
static PyObject *
Outputs_get_year1_nte(OutputsObject *self, void *closure)
{
return PySAM_double_getter(SAM_Thirdpartyownership_Outputs_year1_nte_nget, self->data_ptr);
}
static PyGetSetDef Outputs_getset[] = {
{"cf_after_tax_cash_flow", (getter)Outputs_get_cf_after_tax_cash_flow,(setter)0,
PyDoc_STR("*sequence*: After-tax cash flow [$]"),
NULL},
{"cf_after_tax_net_equity_cost_flow", (getter)Outputs_get_cf_after_tax_net_equity_cost_flow,(setter)0,
PyDoc_STR("*sequence*: After-tax annual costs [$]"),
NULL},
{"cf_agreement_cost", (getter)Outputs_get_cf_agreement_cost,(setter)0,
PyDoc_STR("*sequence*: Agreement cost [$]"),
NULL},
{"cf_cumulative_payback_with_expenses", (getter)Outputs_get_cf_cumulative_payback_with_expenses,(setter)0,
PyDoc_STR("*sequence*: Cumulative simple payback with expenses [$]"),
NULL},
{"cf_energy_net", (getter)Outputs_get_cf_energy_net,(setter)0,
PyDoc_STR("*sequence*: Energy [kWh]"),
NULL},
{"cf_length", (getter)Outputs_get_cf_length,(setter)0,
PyDoc_STR("*float*: Agreement period"),
NULL},
{"cf_nte", (getter)Outputs_get_cf_nte,(setter)0,
PyDoc_STR("*sequence*: Host indifference point by year [cents/kWh]"),
NULL},
{"cf_payback_with_expenses", (getter)Outputs_get_cf_payback_with_expenses,(setter)0,
PyDoc_STR("*sequence*: Simple payback with expenses [$]"),
NULL},
{"lnte_nom", (getter)Outputs_get_lnte_nom,(setter)0,
PyDoc_STR("*float*: Host indifference point real levelized value [cents/kWh]"),
NULL},
{"lnte_real", (getter)Outputs_get_lnte_real,(setter)0,
PyDoc_STR("*float*: Host indifference point nominal levelized value [cents/kWh]"),
NULL},
{"npv", (getter)Outputs_get_npv,(setter)0,
PyDoc_STR("*float*: Net present value [$]"),
NULL},
{"year1_nte", (getter)Outputs_get_year1_nte,(setter)0,
PyDoc_STR("*float*: Host indifference point in Year 1 [cents/kWh]"),
NULL},
{NULL} /* Sentinel */
};
static PyTypeObject Outputs_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership.Outputs", /*tp_name*/
sizeof(OutputsObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
Outputs_methods, /*tp_methods*/
0, /*tp_members*/
Outputs_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/*
* Thirdpartyownership
*/
typedef struct {
PyObject_HEAD
PyObject *x_attr; /* Attributes dictionary */
SAM_Thirdpartyownership data_ptr;
} ThirdpartyownershipObject;
static PyTypeObject Thirdpartyownership_Type;
static ThirdpartyownershipObject *
newThirdpartyownershipObject(void* data_ptr)
{
ThirdpartyownershipObject *self;
self = PyObject_New(ThirdpartyownershipObject, &Thirdpartyownership_Type);
PySAM_TECH_ATTR("Thirdpartyownership", SAM_Thirdpartyownership_construct)
PyObject* Depreciation_obj = Depreciation_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "Depreciation", Depreciation_obj);
Py_DECREF(Depreciation_obj);
PyObject* Financials_obj = Financials_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "Financials", Financials_obj);
Py_DECREF(Financials_obj);
PyObject* FinancialThirdPartyOwnership_obj = FinancialThirdPartyOwnership_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "FinancialThirdPartyOwnership", FinancialThirdPartyOwnership_obj);
Py_DECREF(FinancialThirdPartyOwnership_obj);
PyObject* Common_obj = Common_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "Common", Common_obj);
Py_DECREF(Common_obj);
PyObject* AnnualOutput_obj = AnnualOutput_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "AnnualOutput", AnnualOutput_obj);
Py_DECREF(AnnualOutput_obj);
PyObject* CashFlow_obj = CashFlow_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "CashFlow", CashFlow_obj);
Py_DECREF(CashFlow_obj);
PyObject* ElectricityCost_obj = ElectricityCost_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "ElectricityCost", ElectricityCost_obj);
Py_DECREF(ElectricityCost_obj);
PyObject* Outputs_obj = Outputs_new(self->data_ptr);
PyDict_SetItemString(attr_dict, "Outputs", Outputs_obj);
Py_DECREF(Outputs_obj);
return self;
}
/* Thirdpartyownership methods */
static void
Thirdpartyownership_dealloc(ThirdpartyownershipObject *self)
{
Py_XDECREF(self->x_attr);
SAM_Thirdpartyownership_destruct(self->data_ptr);
PyObject_Del(self);
}
static PyObject *
Thirdpartyownership_execute(ThirdpartyownershipObject *self, PyObject *args)
{
int verbosity = 0;
if (!PyArg_ParseTuple(args, "|i", &verbosity))
return NULL;
SAM_error error = new_error();
SAM_Thirdpartyownership_execute(self->data_ptr, verbosity, &error);
if (PySAM_has_error(error )) return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
Thirdpartyownership_assign(ThirdpartyownershipObject *self, PyObject *args)
{
PyObject* dict;
if (!PyArg_ParseTuple(args, "O:assign", &dict)){
return NULL;
}
if (!PySAM_assign_from_nested_dict((PyObject*)self, self->x_attr, self->data_ptr, dict, "Thirdpartyownership"))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
Thirdpartyownership_export(ThirdpartyownershipObject *self, PyObject *args)
{
return PySAM_export_to_nested_dict((PyObject *) self, self->x_attr);
}
static PyMethodDef Thirdpartyownership_methods[] = {
{"execute", (PyCFunction)Thirdpartyownership_execute, METH_VARARGS,
PyDoc_STR("execute(int verbosity) -> None\n Execute simulation with verbosity level 0 (default) or 1")},
{"assign", (PyCFunction)Thirdpartyownership_assign, METH_VARARGS,
PyDoc_STR("assign(dict) -> None\n Assign attributes from nested dictionary, except for Outputs\n\n``nested_dict = { 'Depreciation': { var: val, ...}, ...}``")},
{"export", (PyCFunction)Thirdpartyownership_export, METH_VARARGS,
PyDoc_STR("export() -> dict\n Export attributes into nested dictionary")},
{NULL, NULL} /* sentinel */
};
static PyObject *
Thirdpartyownership_getattro(ThirdpartyownershipObject *self, PyObject *name)
{
return PySAM_get_attr((PyObject*) self, (PyObject*) self->x_attr, name);
}
static int
Thirdpartyownership_setattr(ThirdpartyownershipObject *self, const char *name, PyObject *v)
{
return PySAM_set_attr((PyObject*)self, (PyObject*)self->x_attr, name, v);
}
static PyTypeObject Thirdpartyownership_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyVarObject_HEAD_INIT(NULL, 0)
"Thirdpartyownership", /*tp_name*/
sizeof(ThirdpartyownershipObject),/*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)Thirdpartyownership_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)0, /*tp_getattr*/
(setattrfunc)Thirdpartyownership_setattr, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
(getattrofunc)Thirdpartyownership_getattro, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
"This class contains all the variable information for running a simulation. Variables are grouped together in the subclasses as properties. If property assignments are the wrong type, an error is thrown.", /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistofnset*/
0, /*tp_iter*/
0, /*tp_iternext*/
Thirdpartyownership_methods, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictofnset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/* --------------------------------------------------------------------- */
/* Function of no arguments returning new Thirdpartyownership object */
static PyObject *
Thirdpartyownership_new(PyObject *self, PyObject *args)
{
ThirdpartyownershipObject *rv;
rv = newThirdpartyownershipObject(0);
if (rv == NULL)
return NULL;
return (PyObject *)rv;
}
static PyObject *
Thirdpartyownership_wrap(PyObject *self, PyObject *args)
{
ThirdpartyownershipObject *rv;
long long int ptr = 0; // 64 bit arch
if (!PyArg_ParseTuple(args, "L:wrap", &ptr)){
PyErr_BadArgument();
return NULL;
}
rv = newThirdpartyownershipObject((void*)ptr);
if (rv == NULL)
return NULL;
return (PyObject *)rv;
}
static PyObject *
Thirdpartyownership_default(PyObject *self, PyObject *args)
{
ThirdpartyownershipObject *rv;
char* def = 0;
if (!PyArg_ParseTuple(args, "s:default", &def)){
PyErr_BadArgument();
return NULL;
}
rv = newThirdpartyownershipObject(0);
if (rv == NULL)
return NULL;
PySAM_load_defaults((PyObject*)rv, rv->x_attr, rv->data_ptr, "Thirdpartyownership", def);
return (PyObject *)rv;
}
/* ---------- */
/* List of functions defined in the module */
static PyMethodDef ThirdpartyownershipModule_methods[] = {
{"new", Thirdpartyownership_new, METH_VARARGS,
PyDoc_STR("new() -> Thirdpartyownership")},
{"default", Thirdpartyownership_default, METH_VARARGS,
PyDoc_STR("default(config) -> Thirdpartyownership\n\nUse financial model-specific default attributes\n"
"config options:\n\n- \"FlatPlatePVThirdParty\"\n- \"GenericSystemThirdParty\"\n- \"PVWattsThirdParty\"")},
{"wrap", Thirdpartyownership_wrap, METH_VARARGS,
PyDoc_STR("wrap(ssc_data_t) -> Thirdpartyownership\n\nUse existing PySSC data\n\n.. warning::\n\n Do not call PySSC.data_free on the ssc_data_t provided to ``wrap``")},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
"Third party ownership with PPA or lease agreement financial model from host perspective");
static int
ThirdpartyownershipModule_exec(PyObject *m)
{
/* Finalize the type object including setting type of the new type
* object; doing it here is required for portability, too. */
if (PySAM_load_lib(m) < 0) goto fail;
if (PySAM_init_error(m) < 0) goto fail;
Thirdpartyownership_Type.tp_dict = PyDict_New();
if (!Thirdpartyownership_Type.tp_dict) { goto fail; }
/// Add the Depreciation type object to Thirdpartyownership_Type
if (PyType_Ready(&Depreciation_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"Depreciation",
(PyObject*)&Depreciation_Type);
Py_DECREF(&Depreciation_Type);
/// Add the Financials type object to Thirdpartyownership_Type
if (PyType_Ready(&Financials_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"Financials",
(PyObject*)&Financials_Type);
Py_DECREF(&Financials_Type);
/// Add the FinancialThirdPartyOwnership type object to Thirdpartyownership_Type
if (PyType_Ready(&FinancialThirdPartyOwnership_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"FinancialThirdPartyOwnership",
(PyObject*)&FinancialThirdPartyOwnership_Type);
Py_DECREF(&FinancialThirdPartyOwnership_Type);
/// Add the Common type object to Thirdpartyownership_Type
if (PyType_Ready(&Common_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"Common",
(PyObject*)&Common_Type);
Py_DECREF(&Common_Type);
/// Add the AnnualOutput type object to Thirdpartyownership_Type
if (PyType_Ready(&AnnualOutput_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"AnnualOutput",
(PyObject*)&AnnualOutput_Type);
Py_DECREF(&AnnualOutput_Type);
/// Add the CashFlow type object to Thirdpartyownership_Type
if (PyType_Ready(&CashFlow_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"CashFlow",
(PyObject*)&CashFlow_Type);
Py_DECREF(&CashFlow_Type);
/// Add the ElectricityCost type object to Thirdpartyownership_Type
if (PyType_Ready(&ElectricityCost_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"ElectricityCost",
(PyObject*)&ElectricityCost_Type);
Py_DECREF(&ElectricityCost_Type);
/// Add the Outputs type object to Thirdpartyownership_Type
if (PyType_Ready(&Outputs_Type) < 0) { goto fail; }
PyDict_SetItemString(Thirdpartyownership_Type.tp_dict,
"Outputs",
(PyObject*)&Outputs_Type);
Py_DECREF(&Outputs_Type);
/// Add the Thirdpartyownership type object to the module
if (PyType_Ready(&Thirdpartyownership_Type) < 0) { goto fail; }
PyModule_AddObject(m,
"Thirdpartyownership",
(PyObject*)&Thirdpartyownership_Type);
return 0;
fail:
Py_XDECREF(m);
return -1;
}
static struct PyModuleDef_Slot ThirdpartyownershipModule_slots[] = {
{Py_mod_exec, ThirdpartyownershipModule_exec},
{0, NULL},
};
static struct PyModuleDef ThirdpartyownershipModule = {
PyModuleDef_HEAD_INIT,
"Thirdpartyownership",
module_doc,
0,
ThirdpartyownershipModule_methods,
ThirdpartyownershipModule_slots,
NULL,
NULL,
NULL
};
/* Export function for the module */
PyMODINIT_FUNC
PyInit_Thirdpartyownership(void)
{
return PyModuleDef_Init(&ThirdpartyownershipModule);
} | 2.109375 | 2 |
2024-11-18T22:28:53.459948+00:00 | 2016-01-22T09:55:03 | e884c9fa387b919acf2f4793162460ab1d484ecf | {
"blob_id": "e884c9fa387b919acf2f4793162460ab1d484ecf",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-22T09:55:03",
"content_id": "7e24d2bbdf2890dc7133596574092b51ba878aae",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "735013760c1fc5e07c2eb826944cc2f3d13dfd1c",
"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": 35554900,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1076,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/server/main.c",
"provenance": "stackv2-0132.json.gz:94020",
"repo_name": "konghan/neuron",
"revision_date": "2016-01-22T09:55:03",
"revision_id": "c854581c0fde15dcb5d15391485e8fd74b5078a5",
"snapshot_id": "f694be04e3f82010581215ab2b9b3f159b5a8428",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/konghan/neuron/c854581c0fde15dcb5d15391485e8fd74b5078a5/server/main.c",
"visit_date": "2021-01-24T20:26:22.536438"
} | stackv2 |
#include "neuron.h"
static void on_setup(neuservice_t *ns, neusession_t *ses, void *data){
printf("==>session setup\n");
neuworker_watch_session(ns->ns_worker, ses);
}
static void on_close(neuservice_t *ns, neusession_t *ses, void *data){
printf("==>session closed!\n");
}
static void on_shutdown(neuservice_t *ns, void *data){
printf("==>service shutdown\n");
}
static void msg_dispatch(struct neusession *ses, struct neupdu *pdu){
printf("==>recv pdu %d\n", (int)pdu);
}
int main(){
neuworker_t nw;
neuservice_t ns;
neumsg_t nm;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
neuworker_init(&nw, NULL);
neuservice_init(&ns, &addr, on_setup, on_close, on_shutdown, NULL);
nm.type = NEUMSG_TYPE_BUF;
nm.header = 0;
nm.slice = 0;
nm.dispatch = msg_dispatch;
neuservice_regist_msg(&ns, &nm);
neuworker_watch_service(&nw, &ns);
neuworker_run(&nw);
return 0;
}
| 2.421875 | 2 |
2024-11-18T22:28:53.717865+00:00 | 2023-06-23T16:51:44 | 2f8f6b98aadf5dbc74009e66c22b1623afe1533f | {
"blob_id": "2f8f6b98aadf5dbc74009e66c22b1623afe1533f",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-23T16:51:44",
"content_id": "cb32894d11008925d687c90171a677d16336b65c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7f8787b9275fc2ab3dd16803034eb6c724eecc92",
"extension": "c",
"filename": "fileWriterStructure.c",
"fork_events_count": 2,
"gha_created_at": "2015-11-20T22:58:00",
"gha_event_created_at": "2020-10-14T06:28:28",
"gha_language": "Modelica",
"gha_license_id": "BSD-3-Clause",
"github_id": 46591374,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3586,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/BuildingSystems/Resources/C-Sources/fileWriterStructure.c",
"provenance": "stackv2-0132.json.gz:94148",
"repo_name": "modelica-3rdparty/BuildingSystems",
"revision_date": "2023-06-23T16:51:44",
"revision_id": "d01388db9ea81dc63405235b9593dda694236a10",
"snapshot_id": "743ee32ba658d0b1f217bc0e25eae85eae05a603",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/modelica-3rdparty/BuildingSystems/d01388db9ea81dc63405235b9593dda694236a10/BuildingSystems/Resources/C-Sources/fileWriterStructure.c",
"visit_date": "2023-08-04T00:15:23.809902"
} | stackv2 | #ifndef IBPSA_FILEWRITERStructure_c
#define IBPSA_FILEWRITERStructure_c
#include "ModelicaUtilities.h"
#include "fileWriterStructure.h"
signed int fileWriterIsUnique(const char* fileName){
int i;
for(i = 0; i < FileWriterNames_n; i++){
if (!strcmp(fileName, FileWriterNames[i])){
return i;
}
}
return -1;
}
void* allocateFileWriter(
const char* instanceName,
const char* fileName){
FileWriter* ID;
FILE* fp;
if ( FileWriterNames_n == 0 ){
/* Allocate memory for array of file names */
FileWriterNames = malloc(sizeof(char*));
InstanceNames = malloc(sizeof(char*));
if ( FileWriterNames == NULL || InstanceNames == NULL)
ModelicaError("Not enough memory in fileWriterStructure.c for allocating FileWriterNames and InstanceNames.");
}
else{
/* Check if the file name is unique */
signed int index = fileWriterIsUnique(fileName);
if (index>=0){
ModelicaFormatError("FileWriter %s writes to file %s which is already used by FileWriter %s.\nEach FileWriter must use a unique file name.",
instanceName, fileName, InstanceNames[index]);
}
/* Reallocate memory for array of file names */
FileWriterNames = realloc(FileWriterNames, (FileWriterNames_n+1) * sizeof(char*));
InstanceNames = realloc(InstanceNames, (FileWriterNames_n+1) * sizeof(char*));
if ( FileWriterNames == NULL || InstanceNames == NULL )
ModelicaError("Not enough memory in fileWriterStructure.c for reallocating FileWriterNames and InstanceNames.");
}
/* Allocate memory for this file name */
FileWriterNames[FileWriterNames_n] = malloc((strlen(fileName)+1) * sizeof(char));
InstanceNames[FileWriterNames_n] = malloc((strlen(instanceName)+1) * sizeof(char));
if ( FileWriterNames[FileWriterNames_n] == NULL || InstanceNames[FileWriterNames_n] == NULL)
ModelicaError("Not enough memory in fileWriterStructure.c for allocating FileWriterNames[] and InstanceNames[].");
/* Copy the file name */
strcpy(FileWriterNames[FileWriterNames_n], fileName);
strcpy(InstanceNames[FileWriterNames_n], instanceName);
FileWriterNames_n++;
ID = (FileWriter*)malloc(sizeof(*ID));
if ( ID == NULL )
ModelicaFormatError("Not enough memory in fileWriterStructure.c for allocating ID of FileWriter %s.", instanceName);
ID->fileWriterName = malloc((strlen(fileName)+1) * sizeof(char));
if ( ID->fileWriterName == NULL )
ModelicaFormatError("Not enough memory in fileWriterStructure.c for allocating ID->fileWriterName in FileWriter %s.", instanceName);
strcpy(ID->fileWriterName, fileName);
ID->instanceName = malloc((strlen(instanceName)+1) * sizeof(char));
if ( ID->instanceName == NULL )
ModelicaFormatError("Not enough memory in fileWriterStructure.c for allocating ID->instanceName in FileWriter %s.", instanceName);
strcpy(ID->instanceName, instanceName);
fp = fopen(fileName, "w");
if (fp == NULL)
ModelicaFormatError("In fileWriterStructure.c: Failed to create empty file %s during initialisation.", fileName);
if (fclose(fp)==EOF)
ModelicaFormatError("In fileWriterStructure.c: Returned an error when closing %s.", fileName);
return (void*)ID;
}
void freeBase(void* ptrFileWriter){
FileWriter *ID = (FileWriter*)ptrFileWriter;
if ( FileWriterNames_n > 0 ){
FileWriterNames_n--;
free(FileWriterNames[FileWriterNames_n]);
free(InstanceNames[FileWriterNames_n]);
if ( FileWriterNames_n == 0 ){
free(FileWriterNames);
free(InstanceNames);
}
}
free(ID->fileWriterName);
free(ID->instanceName);
free(ID);
}
#endif
| 2.796875 | 3 |
2024-11-18T22:28:53.996245+00:00 | 2015-06-30T18:27:10 | 04a02db6ad2ec938fb21c0e02940c1984bf4e5a2 | {
"blob_id": "04a02db6ad2ec938fb21c0e02940c1984bf4e5a2",
"branch_name": "refs/heads/master",
"committer_date": "2015-06-30T18:27:10",
"content_id": "26f603bd736d6c69dace01d2d5cb9d213ddadb10",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "525264109b238b93384fcd7c6671e674b2617b98",
"extension": "h",
"filename": "Commander.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 38240231,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1944,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/vvp/modules/commander/Commander.h",
"provenance": "stackv2-0132.json.gz:94537",
"repo_name": "jgoppert/vvpilot",
"revision_date": "2015-06-30T18:27:10",
"revision_id": "40782baffb1c53e12fd042866ff60b2dcf97c051",
"snapshot_id": "5ea457e03a1b2b5ab4cdf3fd39bff45d5a7c496c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jgoppert/vvpilot/40782baffb1c53e12fd042866ff60b2dcf97c051/src/vvp/modules/commander/Commander.h",
"visit_date": "2021-01-01T15:24:14.883553"
} | stackv2 | #pragma once
/**
* The possible events, stimulus, for the
* finite state machine.
*/
typedef enum {
EVENT_MANUAL, /* request for manual */
EVENT_AUTO, /* request for auto */
EVENT_GUIDED, /* request for guided */
EVENT_NUMBER, /* number of events */
EVENT_UNINIT /* unitialized */
} commanderEvent_t;
/**
* The states within the finite state machine,
* this should be limited to states in which
* the vehicle should react differently to
* outside stimulus and the number should
* be kept as small as possible.
*/
typedef enum {
STATE_MANUAL, /* manual mode */
STATE_AUTO, /* auto mode */
STATE_GUIDED, /* guided mode */
STATE_NUMBER, /* number of states */
STATE_UNINIT /* uninitialized */
} commanderState_t;
/**
* Typedefs for commander data structure
* and callbacks.
*/
typedef struct Commander_t * CommanderPtr;
typedef struct Commander_t Commander;
typedef void (*CallbackManual)(CommanderPtr);
typedef void (*CallbackAuto)(CommanderPtr);
typedef void (*CallbackGuided)(CommanderPtr);
/**
* Commander data structure.
*
* This contains callbacks and an identifier
* of the current state just for
* use when debugging.
*
* Do not use the state variable
* for switch statements, that violates
* the purpose of the "State Pattern" approach
* to finite state machines. Instead, use
* the callbacks.
*/
struct Commander_t {
CallbackManual callbackManual;
CallbackAuto callbackAuto;
CallbackGuided callbackGuided;
int state;
};
/**
* Initializes a commander data structure.
* Does not allocate.
*/
void commanderInit(CommanderPtr instance);
/**
* Updates a commander based on the event type.
*/
void commanderUpdate(CommanderPtr instance,
commanderEvent_t event);
/**
* Serves as a default for state transitions.
*/
void commanderDefaultTransition(CommanderPtr instance);
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
| 2.25 | 2 |
2024-11-18T22:28:54.101268+00:00 | 2023-05-18T06:17:39 | d89d37b32513d1f58561e9526cb15cb60ee5a826 | {
"blob_id": "d89d37b32513d1f58561e9526cb15cb60ee5a826",
"branch_name": "refs/heads/tengine-lite",
"committer_date": "2023-05-18T06:17:39",
"content_id": "18d07bc5b5e37e305c2e441734f8fd5a1fe56d89",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d1a6e586e0ad50da88ac3cf176d40bb9facb6bf6",
"extension": "c",
"filename": "deconv_dw_kernel_arm.c",
"fork_events_count": 1216,
"gha_created_at": "2017-12-30T01:21:41",
"gha_event_created_at": "2023-09-05T06:25:47",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 115765590,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 21807,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/source/device/cpu/op/deconv/cortex_a/deconv_dw_kernel_arm.c",
"provenance": "stackv2-0132.json.gz:94668",
"repo_name": "OAID/Tengine",
"revision_date": "2023-05-18T06:17:39",
"revision_id": "c73708ceb4322ae7c438e4d468178b737fa44cd0",
"snapshot_id": "025d2521040c863300ee08b0800010587b72192b",
"src_encoding": "UTF-8",
"star_events_count": 5323,
"url": "https://raw.githubusercontent.com/OAID/Tengine/c73708ceb4322ae7c438e4d468178b737fa44cd0/source/device/cpu/op/deconv/cortex_a/deconv_dw_kernel_arm.c",
"visit_date": "2023-09-03T19:15:08.100078"
} | stackv2 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
/*
Copyright (c) 2021, OPEN AI LAB
Author: haoluo@openailab.com
*/
#include "deconv_dw_kernel_arm.h"
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include <arm_neon.h>
#define DECONV_DW_MAX(a, b) ((a) > (b) ? (a) : (b))
#define DECONV_DW_MIN(a, b) ((a) < (b) ? (a) : (b))
#ifdef __aarch64__
#else
#endif
inline static float do_activation(float input, int activation)
{
if (activation == 0)
{
input = DECONV_DW_MAX(input, 0);
if (activation == 6)
input = DECONV_DW_MIN(input, 6);
}
return input;
}
inline static void initial_output(float* output, float* bias, int output_ch, int output_wh)
{
int i, j;
// no bias
if (bias == NULL)
{
memset(output, 0.f, output_ch * output_wh * sizeof(float));
}
else
{
float* out_ptr = output;
for (i = 0; i < output_ch; i++)
for (j = 0; j < output_wh; j++)
*out_ptr++ = bias[i];
}
}
inline static void deconv_dw_genreal_3x3s1(const float* input, const float* kernel, float* output, int group,
int input_h, int input_w, int output_h, int output_w, int num_thread)
{
#pragma omp parallel for num_threads(num_thread)
for (int c = 0; c < group; c++)
{
const float* cur_input = input + c * input_h * input_w;
const float* cur_kernel = kernel + c * 9;
float32x4_t _k0 = vld1q_f32(cur_kernel);
float32x4_t _k1 = vld1q_f32(cur_kernel + 3);
float32x4_t _k2 = vld1q_f32(cur_kernel + 6);
for (int i = 0; i < input_h; i++)
{
float* cur_out0 = output + c * output_h * output_w + output_w * i;
float* cur_out1 = output + c * output_h * output_w + output_w * (i + 1);
float* cur_out2 = output + c * output_h * output_w + output_w * (i + 2);
int j = 0;
for (; j + 3 < input_w; j += 4)
{
float32x4_t input_4 = vld1q_f32(cur_input);
float32x4_t out_00 = vld1q_f32(cur_out0 + 0);
out_00 = vmlaq_lane_f32(out_00, input_4, vget_low_f32(_k0), 0);
vst1q_f32(cur_out0 + 0, out_00);
float32x4_t out_01 = vld1q_f32(cur_out0 + 1);
out_01 = vmlaq_lane_f32(out_01, input_4, vget_low_f32(_k0), 1);
vst1q_f32(cur_out0 + 1, out_01);
float32x4_t out_02 = vld1q_f32(cur_out0 + 2);
out_02 = vmlaq_lane_f32(out_02, input_4, vget_high_f32(_k0), 0);
vst1q_f32(cur_out0 + 2, out_02);
float32x4_t out_10 = vld1q_f32(cur_out1 + 0);
out_10 = vmlaq_lane_f32(out_10, input_4, vget_low_f32(_k1), 0);
vst1q_f32(cur_out1 + 0, out_10);
float32x4_t out_11 = vld1q_f32(cur_out1 + 1);
out_11 = vmlaq_lane_f32(out_11, input_4, vget_low_f32(_k1), 1);
vst1q_f32(cur_out1 + 1, out_11);
float32x4_t out_12 = vld1q_f32(cur_out1 + 2);
out_12 = vmlaq_lane_f32(out_12, input_4, vget_high_f32(_k1), 0);
vst1q_f32(cur_out1 + 2, out_12);
float32x4_t out_20 = vld1q_f32(cur_out2 + 0);
out_20 = vmlaq_lane_f32(out_20, input_4, vget_low_f32(_k2), 0);
vst1q_f32(cur_out2 + 0, out_20);
float32x4_t out_21 = vld1q_f32(cur_out2 + 1);
out_21 = vmlaq_lane_f32(out_21, input_4, vget_low_f32(_k2), 1);
vst1q_f32(cur_out2 + 1, out_21);
float32x4_t out_22 = vld1q_f32(cur_out2 + 2);
out_22 = vmlaq_lane_f32(out_22, input_4, vget_high_f32(_k2), 0);
vst1q_f32(cur_out2 + 2, out_22);
cur_input += 4;
cur_out0 += 4;
cur_out1 += 4;
cur_out2 += 4;
}
for (; j < input_w; j++)
{
float val = cur_input[0];
cur_out0[0] += val * cur_kernel[0];
cur_out0[1] += val * cur_kernel[1];
cur_out0[2] += val * cur_kernel[2];
cur_out1[0] += val * cur_kernel[3];
cur_out1[1] += val * cur_kernel[4];
cur_out1[2] += val * cur_kernel[5];
cur_out2[0] += val * cur_kernel[6];
cur_out2[1] += val * cur_kernel[7];
cur_out2[2] += val * cur_kernel[8];
cur_input++;
cur_out0++;
cur_out1++;
cur_out2++;
}
}
}
}
inline static void deconv_dw_genreal_3x3s2(const float* input, const float* kernel, float* output, int group,
int input_h, int input_w, int output_h, int output_w, int num_thread)
{
#pragma omp parallel for num_threads(num_thread)
for (int c = 0; c < group; c++)
{
const float* cur_input = input + c * input_h * input_w;
const float* cur_kernel = kernel + c * 9;
float32x4_t _k0 = vld1q_f32(cur_kernel);
float32x4_t _k1 = vld1q_f32(cur_kernel + 3);
float32x4_t _k2 = vld1q_f32(cur_kernel + 6);
for (int i = 0; i < input_h; i++)
{
float* cur_out0 = output + c * output_h * output_w + output_w * i * 2;
float* cur_out1 = output + c * output_h * output_w + output_w * (i * 2 + 1);
float* cur_out2 = output + c * output_h * output_w + output_w * (i * 2 + 2);
int j = 0;
for (; j + 3 < input_w; j += 4)
{
float32x4_t input_4 = vld1q_f32(cur_input);
// out row 0
float32x4_t out_00 = vmulq_lane_f32(input_4, vget_low_f32(_k0), 0); // 0,2,4,6
float32x4_t out_01 = vmulq_lane_f32(input_4, vget_low_f32(_k0), 1); // 1,3,5,7
float32x4_t out_02 = vmulq_lane_f32(input_4, vget_high_f32(_k0), 0); // 2,4,6,8
float32x4x2_t out_0 = vld2q_f32(cur_out0);
out_0.val[0] = vaddq_f32(out_0.val[0], out_00); // 0,2,4,6
out_0.val[1] = vaddq_f32(out_0.val[1], out_01); // 1,3,5,7
vst2q_f32(cur_out0, out_0);
out_0 = vld2q_f32(cur_out0 + 2);
out_0.val[0] = vaddq_f32(out_0.val[0], out_02); // 2,4,6,8
vst2q_f32(cur_out0 + 2, out_0);
// out row 1
float32x4_t out_10 = vmulq_lane_f32(input_4, vget_low_f32(_k1), 0); // 0,2,4,6
float32x4_t out_11 = vmulq_lane_f32(input_4, vget_low_f32(_k1), 1); // 1,3,5,7
float32x4_t out_12 = vmulq_lane_f32(input_4, vget_high_f32(_k1), 0); // 2,4,6,8
float32x4x2_t out_1 = vld2q_f32(cur_out1);
out_1.val[0] = vaddq_f32(out_1.val[0], out_10); // 0,2,4,6
out_1.val[1] = vaddq_f32(out_1.val[1], out_11); // 1,3,5,7
vst2q_f32(cur_out1, out_1);
out_1 = vld2q_f32(cur_out1 + 2);
out_1.val[0] = vaddq_f32(out_1.val[0], out_12); // 2,4,6,8
vst2q_f32(cur_out1 + 2, out_1);
// out row 2
float32x4_t out_20 = vmulq_lane_f32(input_4, vget_low_f32(_k2), 0); // 0,2,4,6
float32x4_t out_21 = vmulq_lane_f32(input_4, vget_low_f32(_k2), 1); // 1,3,5,7
float32x4_t out_22 = vmulq_lane_f32(input_4, vget_high_f32(_k2), 0); // 2,4,6,8
float32x4x2_t out_2 = vld2q_f32(cur_out2);
out_2.val[0] = vaddq_f32(out_2.val[0], out_20); // 0,2,4,6
out_2.val[1] = vaddq_f32(out_2.val[1], out_21); // 1,3,5,7
vst2q_f32(cur_out2, out_2);
out_2 = vld2q_f32(cur_out2 + 2);
out_2.val[0] = vaddq_f32(out_2.val[0], out_22); // 2,4,6,8
vst2q_f32(cur_out2 + 2, out_2);
cur_input += 4;
cur_out0 += 8;
cur_out1 += 8;
cur_out2 += 8;
}
for (; j < input_w; j++)
{
float val = cur_input[0];
cur_out0[0] += val * cur_kernel[0];
cur_out0[1] += val * cur_kernel[1];
cur_out0[2] += val * cur_kernel[2];
cur_out1[0] += val * cur_kernel[4];
cur_out1[1] += val * cur_kernel[5];
cur_out1[2] += val * cur_kernel[6];
cur_out2[0] += val * cur_kernel[8];
cur_out2[1] += val * cur_kernel[9];
cur_out2[2] += val * cur_kernel[10];
cur_input++;
cur_out0 += 2;
cur_out1 += 2;
cur_out2 += 2;
}
}
}
}
inline static void deconv_dw_genreal_4x4s1(const float* input, const float* kernel, float* output, int group,
int input_h, int input_w, int output_h, int output_w, int num_thread)
{
#pragma omp parallel for num_threads(num_thread)
for (int c = 0; c < group; c++)
{
const float* cur_input = input + c * input_h * input_w;
const float* cur_kernel = kernel + c * 16;
float32x4_t _k0 = vld1q_f32(cur_kernel);
float32x4_t _k1 = vld1q_f32(cur_kernel + 4);
float32x4_t _k2 = vld1q_f32(cur_kernel + 8);
float32x4_t _k3 = vld1q_f32(cur_kernel + 12);
for (int i = 0; i < input_h; i++)
{
float* cur_out0 = output + c * output_h * output_w + output_w * i;
float* cur_out1 = output + c * output_h * output_w + output_w * (i + 1);
float* cur_out2 = output + c * output_h * output_w + output_w * (i + 2);
float* cur_out3 = output + c * output_h * output_w + output_w * (i + 3);
int j = 0;
for (; j + 3 < input_w; j += 4)
{
float32x4_t input_4 = vld1q_f32(cur_input);
float32x4_t out_00 = vld1q_f32(cur_out0 + 0);
out_00 = vmlaq_lane_f32(out_00, input_4, vget_low_f32(_k0), 0);
vst1q_f32(cur_out0 + 0, out_00);
float32x4_t out_01 = vld1q_f32(cur_out0 + 1);
out_01 = vmlaq_lane_f32(out_01, input_4, vget_low_f32(_k0), 1);
vst1q_f32(cur_out0 + 1, out_01);
float32x4_t out_02 = vld1q_f32(cur_out0 + 2);
out_02 = vmlaq_lane_f32(out_02, input_4, vget_high_f32(_k0), 0);
vst1q_f32(cur_out0 + 2, out_02);
float32x4_t out_03 = vld1q_f32(cur_out0 + 3);
out_03 = vmlaq_lane_f32(out_03, input_4, vget_high_f32(_k0), 1);
vst1q_f32(cur_out0 + 3, out_03);
float32x4_t out_10 = vld1q_f32(cur_out1 + 0);
out_10 = vmlaq_lane_f32(out_10, input_4, vget_low_f32(_k1), 0);
vst1q_f32(cur_out1 + 0, out_10);
float32x4_t out_11 = vld1q_f32(cur_out1 + 1);
out_11 = vmlaq_lane_f32(out_11, input_4, vget_low_f32(_k1), 1);
vst1q_f32(cur_out1 + 1, out_11);
float32x4_t out_12 = vld1q_f32(cur_out1 + 2);
out_12 = vmlaq_lane_f32(out_12, input_4, vget_high_f32(_k1), 0);
vst1q_f32(cur_out1 + 2, out_12);
float32x4_t out_13 = vld1q_f32(cur_out1 + 3);
out_13 = vmlaq_lane_f32(out_13, input_4, vget_high_f32(_k1), 1);
vst1q_f32(cur_out1 + 3, out_13);
float32x4_t out_20 = vld1q_f32(cur_out2 + 0);
out_20 = vmlaq_lane_f32(out_20, input_4, vget_low_f32(_k2), 0);
vst1q_f32(cur_out2 + 0, out_20);
float32x4_t out_21 = vld1q_f32(cur_out2 + 1);
out_21 = vmlaq_lane_f32(out_21, input_4, vget_low_f32(_k2), 1);
vst1q_f32(cur_out2 + 1, out_21);
float32x4_t out_22 = vld1q_f32(cur_out2 + 2);
out_22 = vmlaq_lane_f32(out_22, input_4, vget_high_f32(_k2), 0);
vst1q_f32(cur_out2 + 2, out_22);
float32x4_t out_23 = vld1q_f32(cur_out2 + 3);
out_23 = vmlaq_lane_f32(out_23, input_4, vget_high_f32(_k2), 1);
vst1q_f32(cur_out2 + 3, out_23);
float32x4_t out_30 = vld1q_f32(cur_out3 + 0);
out_30 = vmlaq_lane_f32(out_30, input_4, vget_low_f32(_k3), 0);
vst1q_f32(cur_out3 + 0, out_30);
float32x4_t out_31 = vld1q_f32(cur_out3 + 1);
out_31 = vmlaq_lane_f32(out_31, input_4, vget_low_f32(_k3), 1);
vst1q_f32(cur_out3 + 1, out_31);
float32x4_t out_32 = vld1q_f32(cur_out3 + 2);
out_32 = vmlaq_lane_f32(out_32, input_4, vget_high_f32(_k3), 0);
vst1q_f32(cur_out3 + 2, out_32);
float32x4_t out_33 = vld1q_f32(cur_out3 + 3);
out_33 = vmlaq_lane_f32(out_33, input_4, vget_high_f32(_k3), 1);
vst1q_f32(cur_out3 + 3, out_33);
cur_input += 4;
cur_out0 += 4;
cur_out1 += 4;
cur_out2 += 4;
cur_out3 += 4;
}
for (; j < input_w; j++)
{
float val = cur_input[0];
cur_out0[0] += val * cur_kernel[0];
cur_out0[1] += val * cur_kernel[1];
cur_out0[2] += val * cur_kernel[2];
cur_out0[3] += val * cur_kernel[3];
cur_out1[0] += val * cur_kernel[4];
cur_out1[1] += val * cur_kernel[5];
cur_out1[2] += val * cur_kernel[6];
cur_out1[3] += val * cur_kernel[7];
cur_out2[0] += val * cur_kernel[8];
cur_out2[1] += val * cur_kernel[9];
cur_out2[2] += val * cur_kernel[10];
cur_out2[3] += val * cur_kernel[11];
cur_out3[0] += val * cur_kernel[12];
cur_out3[1] += val * cur_kernel[13];
cur_out3[2] += val * cur_kernel[14];
cur_out3[3] += val * cur_kernel[15];
cur_input++;
cur_out0++;
cur_out1++;
cur_out2++;
cur_out3++;
}
}
}
}
void deconv_dw_genreal(float* input, float* output, float* kernel, int input_h, int input_w, int output_h, int output_w,
int group, int kernel_h, int kernel_w, int stride_h, int stride_w, int dilation_h,
int dilation_w, int pad_h, int pad_w, int activation, int num_thread)
{
int h, w, k_h, k_w;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
for (h = 0; h < input_h; h++)
{
for (w = 0; w < input_w; w++)
{
int org_out_x = w * stride_w - pad_w;
int org_out_y = h * stride_h - pad_h;
int input_offset = g * input_h * input_w + h * input_w + w;
for (k_h = 0; k_h < kernel_h; k_h++)
{
for (k_w = 0; k_w < kernel_w; k_w++)
{
int cur_out_x = org_out_x + k_w * dilation_w;
int cur_out_y = org_out_y + k_h * dilation_h;
if (cur_out_x >= 0 && cur_out_x < output_w && cur_out_y >= 0 && cur_out_y < output_h)
{
int kernel_offset = g * kernel_h * kernel_w + k_h * kernel_w + k_w;
int output_offset = g * output_w * output_h + cur_out_y * output_w + cur_out_x;
output[output_offset] += kernel[kernel_offset] * input[input_offset];
}
}
}
}
}
}
if (activation == 0 || activation == 6)
{
int size = group * output_h * output_w;
for (int i = 0; i < size; i++)
{
output[i] = do_activation(output[i], activation);
}
}
}
int deconv_dw_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor,
struct tensor* output_tensor, struct deconv_param* param, int num_thread, int cpu_affinity)
{
/* param */
int pads[4];
int group = param->group;
int kernel_h = param->kernel_h;
int kernel_w = param->kernel_w;
int stride_h = param->stride_h;
int stride_w = param->stride_w;
int dilation_h = param->dilation_h;
int dilation_w = param->dilation_w;
pads[0] = param->pad_h0;
pads[1] = param->pad_w0;
pads[2] = param->pad_h1;
pads[3] = param->pad_w1;
if (stride_h != stride_w)
return -1;
int act_type = param->activation;
int batch = input_tensor->dims[0];
int in_c = input_tensor->dims[1] / group;
int in_h = input_tensor->dims[2];
int in_w = input_tensor->dims[3];
int input_size = in_c * in_h * in_w;
int kernel_size = in_c * kernel_h * kernel_w;
int out_c = output_tensor->dims[1] / group;
int out_h = output_tensor->dims[2];
int out_w = output_tensor->dims[3];
int out_hw = out_h * out_w;
int output_size = out_c * out_h * out_w;
int out_c_align = ((out_c + 3) & -4);
/* buffer addr */
float* input_buf = (float*)input_tensor->data;
float* kernel_buf = (float*)filter_tensor->data;
float* output_buf = (float*)output_tensor->data;
float* biases_buf = (float*)bias_tensor->data;
for (int n = 0; n < batch; n++) // batch size
{
float* cur_input = input_buf + n * input_size * group;
float* cur_output = output_buf + n * output_size * group;
initial_output(cur_output, biases_buf, group, out_hw);
if (pads[0] == 0)
{
if (stride_h == 1 && kernel_h == 4)
{
deconv_dw_genreal_4x4s1(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w, num_thread);
}
else if (kernel_h == 3)
{
if (stride_h == 1)
deconv_dw_genreal_3x3s1(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w,
num_thread);
else
deconv_dw_genreal_3x3s2(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w,
num_thread);
}
else
{
deconv_dw_genreal(cur_input, cur_output, kernel_buf, in_h, in_w, out_h, out_w, group, kernel_h,
kernel_w, stride_h, stride_w, dilation_h, dilation_w, pads[0], pads[1], act_type,
num_thread);
}
}
else
{
int out_h_pad = out_h + pads[0] * 2;
int out_w_pad = out_w + pads[1] * 2;
float* output_buf = (float*)malloc(sizeof(float) * group * out_h_pad * out_w_pad + 128);
if (stride_h == 1 && kernel_h == 4)
{
deconv_dw_genreal_4x4s1(cur_input, kernel_buf, output_buf, group, in_h, in_w, out_h, out_w, num_thread);
for (int g = 0; g < group; g++)
{
for (int i = 0; i < out_h; i++)
{
float* cur_src = output_buf + g * out_h_pad * out_w_pad + (pads[0] + i) * out_w_pad + pads[1];
float* cur_dst = cur_output + g * out_hw + i * out_w;
for (int j = 0; j < out_w; j++)
cur_dst[j] += cur_src[j];
}
}
}
else if (kernel_h == 3)
{
if (stride_h == 1)
deconv_dw_genreal_3x3s1(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w,
num_thread);
else
deconv_dw_genreal_3x3s2(cur_input, kernel_buf, cur_output, group, in_h, in_w, out_h, out_w,
num_thread);
for (int g = 0; g < group; g++)
{
for (int i = 0; i < out_h; i++)
{
float* cur_src = output_buf + g * out_h_pad * out_w_pad + (pads[0] + i) * out_w_pad + pads[1];
float* cur_dst = cur_output + g * out_hw + i * out_w;
for (int j = 0; j < out_w; j++)
cur_dst[j] += cur_src[j];
}
}
}
else
{
deconv_dw_genreal(cur_input, cur_output, kernel_buf, in_h, in_w, out_h, out_w, group, kernel_h,
kernel_w, stride_h, stride_w, dilation_h, dilation_w, pads[0], pads[1], act_type,
num_thread);
}
free(output_buf);
}
}
return 0;
}
| 2.1875 | 2 |
2024-11-18T22:28:54.223026+00:00 | 2017-09-15T07:43:34 | e66f35d134ecd23ee4fce6383c9549c119248b52 | {
"blob_id": "e66f35d134ecd23ee4fce6383c9549c119248b52",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-15T07:43:34",
"content_id": "fe35540113c4177e2efa6a295362b65184e6d704",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7205141e3549815c734ab1bd7db3783496289671",
"extension": "c",
"filename": "counts.c",
"fork_events_count": 16,
"gha_created_at": "2011-08-30T15:01:13",
"gha_event_created_at": "2015-03-24T17:12:20",
"gha_language": "C",
"gha_license_id": null,
"github_id": 2295454,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1082,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/doesnotworkyet/counts.c",
"provenance": "stackv2-0132.json.gz:94796",
"repo_name": "xyproto/c2go",
"revision_date": "2017-09-15T07:43:34",
"revision_id": "4e1618e4efb65782e846b5727b6e410d457bbc98",
"snapshot_id": "1e2137de8050fe1d0e28f44015aed4f7a890d678",
"src_encoding": "UTF-8",
"star_events_count": 48,
"url": "https://raw.githubusercontent.com/xyproto/c2go/4e1618e4efb65782e846b5727b6e410d457bbc98/doesnotworkyet/counts.c",
"visit_date": "2020-12-24T08:31:34.588967"
} | stackv2 | /* counts.c - It contains a program that is given as command parameter
* the name of a text file, say, temp.dat. It will read each line
* of temp.dat and print out in correspondence the number of
* characters and words on that line. At the end it will print
* out the number of lines that were read.
*/
#include <stdio.h>
int main (int argc, char *argv[]){
FILE *fp;
int nchars, nwords, nlines;
int lastnblank; /* 0 iff the last character was a space */
char c;
if(argc!=2){
printf("Usage: %s filename\n", argv[0]);
exit(0);
}
if((fp=fopen(argv[1],"r"))==NULL){
perror("fopen");
exit(0);
}
nchars=nwords=nlines=lastnblank=0;
while((c=getc(fp))!=EOF){
nchars++;
if (c=='\n'){
if (lastnblank)
nwords++;
printf("words=%d, characters=%d\n", nwords, nchars);
nchars=nwords=lastnblank=0;
nlines++;
}else{
if (((c==' ')||(c=='\t'))&(lastnblank))
nwords++;
lastnblank=((c!=' ')&&(c!='\t'));
}
}
printf("lines=%d\n", nlines);
fclose(fp);
}
| 3.21875 | 3 |
2024-11-18T22:28:59.679860+00:00 | 2023-02-25T11:24:08 | a25d019487716209c7da948c736fe445df181987 | {
"blob_id": "a25d019487716209c7da948c736fe445df181987",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-25T11:24:08",
"content_id": "e6f851b0d43bdc46cc3cf7489ca7df46e30feeac",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e67e31593e6fb0ac516e6b9c2bedd37183deda8f",
"extension": "c",
"filename": "ccomp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 11429848,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14738,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/aldor/aldor/src/ccomp.c",
"provenance": "stackv2-0132.json.gz:96223",
"repo_name": "hemmecke/aldor",
"revision_date": "2023-02-25T11:24:08",
"revision_id": "2f5b4896eed78cb37a31a49a51662e98e4462821",
"snapshot_id": "a2438aa664c245bd5d3a0b2910f09955bbcc27b5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hemmecke/aldor/2f5b4896eed78cb37a31a49a51662e98e4462821/aldor/aldor/src/ccomp.c",
"visit_date": "2023-03-08T12:25:53.204926"
} | stackv2 | /*****************************************************************************
*
* ccomp.c: C compiler interface.
*
* Copyright (c) 1990-2007 Aldor Software Organization Ltd (Aldor.org).
*
****************************************************************************/
#include "ccomp.h"
#include "compcfg.h"
#include "emit.h"
#include "genc.h"
#include "opsys.h"
#include "store.h"
#include "archive.h"
#include "comsg.h"
/*
* Default compiler and linker.
* They can be overridden by the env. variable CC or the option * -Ccc=....
* They can be overridden individually with -Ccomp=... and -Clink-....
*/
#define CC_DEFAULT "unicl"
#define LD_DEFAULT "unicl"
#define RUNTIME_DEFAULT "foam"
/*****************************************************************************
*
* :: C compiler + Linker Interface
*
****************************************************************************/
enum ccoptTag {
CCOPT_START,
CCOPT_IncPath = CCOPT_START,
CCOPT_Define,
CCOPT_Undefine,
CCOPT_CompileOnly,
CCOPT_Optimize,
CCOPT_FNonStd,
CCOPT_DebugInfo,
CCOPT_ProfileInfo,
CCOPT_LibPath,
CCOPT_Library,
CCOPT_OutputFile,
CCOPT_System,
CCOPT_Fortran,
CCOPT_Runtime,
CCOPT_LIMIT
};
struct ccOption {
enum ccoptTag tag;
String arg;
struct ccOption *next;
};
struct ccOptionInfo {
enum ccoptTag tag;
String text;
BPack(Bool) isComp;
BPack(Bool) isLink;
BPack(Bool) isDir;
BPack(Bool) isFile;
};
/*
* These options are valid on Unix C compilers *and* the "unicl" wrapper.
* The extra -WV option for "unicl" is passed via the environment.
* [As we make a vague attempt to call a standard C compiler, we can't
* pass it through the command line
*/
struct ccOptionInfo ccOptionTable[] = {
/* Tag Text C L D F */
{CCOPT_IncPath, "-I", 1,0,1,0},
{CCOPT_Define, "-D", 1,0,0,0},
{CCOPT_Undefine, "-U", 1,0,0,0},
{CCOPT_CompileOnly,"-c", 1,0,0,0},
{CCOPT_Optimize, "-O", 1,1,0,0},
/* -Wfnonstd is not a valid option to gcc or to ld anymore */
{CCOPT_FNonStd, "-Wfnonstd",0,0,0,0},
{CCOPT_DebugInfo, "-g", 1,1,0,0},
{CCOPT_ProfileInfo,"-p", 1,1,0,0},
{CCOPT_LibPath, "-L", 0,1,1,0},
{CCOPT_Library, "-l", 0,1,0,0},
{CCOPT_OutputFile, "-o ", 0,1,0,1}, /* Note trailing blank. */
{CCOPT_System, "-Wsys=", 1,1,0,0},
};
#define ccIsCompilerOption(tag) (ccOptionTable[tag].isComp)
#define ccIsLinkerOption(tag) (ccOptionTable[tag].isLink)
#define ccIsDirOption(tag) (ccOptionTable[tag].isDir)
#define ccIsFileOption(tag) (ccOptionTable[tag].isFile)
/****************************************************************************
*
* :: Option Handling
*
***************************************************************************/
local void ccPushLibrary (String);
local void ccPushOptionList(enum ccoptTag, String);
local void ccPushOption (enum ccoptTag, String);
/*
* Remember to change comsgdb.msg if these change.
*/
#define COPT_STANDARDC "standard"
#define COPT_OLDC "old"
#define COPT_IDHASH "idhash"
#define COPT_NOIDHASH "no-idhash"
#define COPT_LINENOS "lines"
#define COPT_NOLINENOS "no-lines"
#define COPT_COMP "comp"
#define COPT_LIB "lib"
#define COPT_LINK "link"
#define COPT_CC "cc"
#define COPT_ARGS "args"
#define COPT_GO "go"
#define COPT_SMAX "smax"
#define COPT_IDLEN "idlen"
#define COPT_FNAME "fname"
#define COPT_SYS "sys"
#define COPT_FORTRAN "fortran"
#define COPT_RUNTIME "runtime"
/*
* Control C Code generation and compilation.
*/
String ccCompiler = 0;
String ccLinker = 0;
String ccGoer = 0;
String ccOptions = 0;
String ccSystem = 0;
String ccRuntime = 0;
Bool ccFortran = 0;
Bool ccVerboseFlag= false;
Bool ccLineNosFlag= false;
int ccDoStandardCFlag = -1;
StringList ccLibraries;
String ccRoot;
local void ccSetStandardC(Bool flg);
void ccSetRoot(String root)
{
ccRoot = root;
}
int
ccOption(String opt)
{
String s;
if (!*opt) return -1; /* Must have letters */
if (strAEqual(opt, COPT_STANDARDC)) ccSetStandardC(true);
else if (strAEqual(opt, COPT_LINENOS)) ccSetLineNos(true);
else if (strAEqual(opt, COPT_NOLINENOS)) ccSetLineNos(false);
else if (strAEqual(opt, COPT_OLDC)) ccSetStandardC(false);
else if (strAEqual(opt, COPT_IDHASH)) genCSetIdHash(true);
else if (strAEqual(opt, COPT_NOIDHASH)) genCSetIdHash(false);
else if (strAEqual(opt, COPT_FORTRAN)) ccFortran = true;
else if (s = strAIsPrefix(COPT_CC, opt), s) ccCompiler= ccLinker= ++s;
else if (s = strAIsPrefix(COPT_ARGS, opt), s) ccOptions = ++s;
else if (s = strAIsPrefix(COPT_COMP, opt), s) ccCompiler= ++s;
else if (s = strAIsPrefix(COPT_LINK, opt), s) ccLinker = ++s;
else if (s = strAIsPrefix(COPT_GO, opt), s) ccGoer = ++s;
else if (s = strAIsPrefix(COPT_SMAX, opt), s) genCSetSMax(atoi(++s));
else if (s = strAIsPrefix(COPT_IDLEN, opt), s) genCSetIdLen(atoi(++s));
else if (s = strAIsPrefix(COPT_FNAME, opt), s) emitSetCName(++s);
else if (s = strAIsPrefix(COPT_SYS, opt), s) ccSystem = ++s;
else if (s = strAIsPrefix(COPT_RUNTIME, opt), s)ccRuntime = ++s;
else if (s = strAIsPrefix(COPT_LIB, opt), s) ccPushLibrary(++s);
else return -1;
return 0;
}
/*
* Option list to pass to the C compiler.
* If the option has no arguments, arg should be NULL.
*/
struct ccOption *ccOptionList = 0;
local void
ccPushOptionList(enum ccoptTag opt, String args)
{
String buf = strCopy(args);
char *ptr = buf;
char *start = buf;
while (*ptr != '\0') {
if (*ptr == ',') {
*ptr = '\0';
ccPushOption(opt, start);
start = ptr + 1;
}
ptr++;
}
if (start != ptr)
ccPushOption(opt, start);
}
local void
ccPushOption(enum ccoptTag opt, String arg)
{
struct ccOption *newOpt;
newOpt = (struct ccOption *) stoAlloc(OB_Other, sizeof(*newOpt));
newOpt->tag = opt;
newOpt->arg = arg;
newOpt->next = ccOptionList;
ccOptionList = newOpt;
}
local void
ccReverseOptions(void)
{
struct ccOption *t, *r = 0, *l = ccOptionList;
while(l) {
t = l->next;
l->next = r;
r = l;
l = t;
}
ccOptionList = r;
}
void
ccSetVerbose(Bool wantVerbose)
{
ccVerboseFlag = wantVerbose;
}
void
ccSetDebug(Bool isWanted)
{
if (isWanted) ccPushOption(CCOPT_DebugInfo, NULL);
}
void
ccSetProfile(Bool isWanted)
{
if (isWanted) ccPushOption(CCOPT_ProfileInfo, NULL);
}
void
ccSetOptimize(Bool isNonStd,Bool isWanted)
{
if (isWanted) ccPushOption(CCOPT_Optimize, NULL);
if (isNonStd) ccPushOption(CCOPT_FNonStd,NULL);
}
void
ccSetOutputFile(String fn)
{
ccPushOption(CCOPT_OutputFile, fn);
}
void
ccSetLineNos(Bool flg)
{
ccLineNosFlag = flg;
}
Bool
ccLineNos()
{
return ccLineNosFlag;
}
local void
ccSetStandardC(Bool flg)
{
ccDoStandardCFlag = flg;
}
local void
ccPushLibrary(String string)
{
ccLibraries = listCons(String)(strCopy(string), ccLibraries);
}
Bool
ccDoStandardC()
{
if (ccDoStandardCFlag == -1)
ccDoStandardCFlag = compCfgLookupBoolean("generate-stdc");
return ccDoStandardCFlag;
}
/*****************************************************************************
*
* :: Command formulation
*
****************************************************************************/
static Buffer ccBuf;
static int ccPutc (int c) { return bufPutc(ccBuf, c); }
static void ccPutq (String s) { osRunQuoteArg(s, ccPutc); }
static void ccPuts (String s) { bufPuts(ccBuf, s); }
static void ccPutOpt (struct ccOption *, String newwd, String oldwd);
static void ccPutFname (FileName, String newwd, String oldwd);
local void ccAppendToHiddenArgs(String str);
/*
* Construct a compile command suitable to run in the directory "newwd".
* The paths and file names (including "newwd") are given relative to "oldwd".
*/
String
ccCompileCommand(String compiler, String options, int numFiles, FileName *fns,
struct ccOption *opts,
String newwd, String oldwd, FileName outfile)
{
struct ccOption *o;
int i;
ccBuf = bufNew();
if (!compiler && ccRoot) compiler = strPrintf("%s/bin/%s", ccRoot, CC_DEFAULT);
if (!compiler) compiler = CC_DEFAULT;
ccPutq(compiler);
if (options) {ccPutc(' '); ccPuts(options);} /* Don't quote options */
for (o = opts; o; o = o->next)
if (ccIsCompilerOption(o->tag)) ccPutOpt(o, newwd, oldwd);
if (outfile) {
ccPutc(' ');
ccPuts(ccOptionTable[CCOPT_OutputFile].text);
ccPutFname(outfile, newwd, oldwd);
}
ccPutc(' '); ccPutq(ccOptionTable[CCOPT_CompileOnly].text);
for(i = 0; i < numFiles; i++) ccPutFname(fns[i], newwd, oldwd);
return bufLiberate(ccBuf);
}
String
ccLinkCommand(String linker, String options, int numFiles, FileName *fns,
struct ccOption *opts,
String newwd, String oldwd)
{
struct ccOption *o;
int i;
ccBuf = bufNew();
if (!linker && ccRoot) linker = strPrintf("%s/bin/%s",ccRoot, LD_DEFAULT);
if (!linker) linker = LD_DEFAULT;
ccPutq(linker);
if (options) {ccPutc(' '); ccPuts(options);} /* Don't quote options */
for(i = 0; i < numFiles; i++)
ccPutFname(fns[i], newwd, oldwd);
for(o = opts; o; o = o->next)
if (o->tag == CCOPT_LibPath)
ccPutOpt(o, newwd, oldwd);
for(o = opts; o; o = o->next)
if (ccIsLinkerOption(o->tag) && o->tag != CCOPT_LibPath)
ccPutOpt(o, newwd, oldwd);
return bufLiberate(ccBuf);
}
local void
ccPutOpt(struct ccOption *o, String newwd, String oldwd)
{
ccPutc(' ');
ccPuts(ccOptionTable[o->tag].text);
if (!o->arg) return;
if (strEqual(newwd, osCurDirName()))
ccPutq(o->arg);
else if (ccIsDirOption(o->tag)) {
String s = fileSubdir(oldwd, o->arg);
ccPutq (s);
strFree(s);
}
else if (ccIsFileOption(o->tag))
ccPutFname(fnameParseStatic(o->arg), newwd, oldwd);
else
ccPutq(o->arg);
}
local void
ccPutFname(FileName fn, String newwd, String oldwd)
{
String s;
ccPutc(' ');
if (strEqual(fnameDir(fn), newwd)) {
s = fnameUnparseStaticWithout(fn);
ccPutq(s);
}
else {
String odir = fnameDir(fn);
fnameTSetDir(fn, fileSubdir(oldwd, odir));
s = fnameUnparseStatic(fn);
ccPutq(s);
fnameTSetDir(fn, odir);
}
}
/******************************************************************************
*
* :: Command issue
*
*****************************************************************************/
local String ccOutputDir(String, struct ccOption *);
local void ccSwapDir (String, String, Length);
local void ccEchoIf (String fmt, String arg);
/*
* Reconcile the options and initialize the commands.
*/
void
ccGetReady(void)
{
PathList l;
StringList tmp;
String s;
static Bool isReady = false;
if (isReady) return;
if (!ccRuntime)
ccRuntime = RUNTIME_DEFAULT;
if (!ccSystem) ccSystem = compCfgGetSysName();
if (!strEqual(ccSystem, CONFIGSYS)) {
/* Treat paths as stacks -- newer covers older. */
for(l = libSearchPathDelta(); l; l = cdr(l)) {
/* !!! This is UNIX (+ DOS) Specific */
String s0, s1;
s0 = strConcat(car(l), "/");
s1 = strConcat(s0, ccSystem);
strFree(s0);
ccPushOption(CCOPT_LibPath, s1);
}
}
for(l = libSearchPathDelta(); l; l = cdr(l))
ccPushOption(CCOPT_LibPath, car(l));
for(l = incSearchPathDelta(); l; l = cdr(l))
ccPushOption(CCOPT_IncPath, car(l));
for(l = arLibraryKeys(); l; l = cdr(l))
ccPushOption(CCOPT_Library, car(l));
tmp = listReverse(String)(ccLibraries);
for(l = tmp; l; l = cdr(l))
ccPushOption(CCOPT_Library, car(l));
listFree(String)(tmp);
ccPushOptionList(CCOPT_Library, ccRuntime);
ccReverseOptions();
s = osGetEnv("CC");
if (s) {
if (!ccCompiler) ccCompiler = strCopy(s);
if (!ccLinker) ccLinker = strCopy(s);
}
s = osGetEnv("CGO");
if (s) {
if (!ccGoer) ccGoer = strCopy(s);
}
if (ccVerboseFlag)
ccAppendToHiddenArgs("-WV");
if (ccFortran)
ccAppendToHiddenArgs("-Wfortran");
s = "-Wsys=";
s = strConcat(s, ccSystem);
ccAppendToHiddenArgs(s);
strFree(s);
if (ccDoStandardC())
ccAppendToHiddenArgs("-Wstdc");
isReady = true;
}
local void
ccAppendToHiddenArgs(String str)
{
String s;
s = osGetEnv("UNICL");
s = s ? s : "";
if (s[0] != '\0')
str = strConcat(str, " ");
s = strConcat(str, s);
s = strConcat("UNICL=", s);
osPutEnv(s);
if (!osPutEnvIsKept()) strFree(s);
}
/*
* Compile a single C file.
* Have to assume output will go in the current directory of the compile.
*/
void
ccCompileFile(String newwd, FileName outfile, FileName fn)
{
String command;
char oldwd[1024];
int rc;
newwd = ccOutputDir(newwd, NULL /* ccOptionList */);
ccSwapDir(newwd, oldwd, sizeof(oldwd));
command = ccCompileCommand(ccCompiler, ccOptions, 1, &fn,
ccOptionList, newwd, oldwd, outfile);
ccEchoIf("Exec: %s\n", command);
rc = osRun(command);
if (rc != 0) comsgFatal(NULL, ALDOR_F_CcFailed, command);
ccSwapDir(oldwd, NULL, int0);
strFree(command);
strFree(newwd);
}
/*
* Link a program.
* Have to assume output will go in the current directory of the link.
*/
void
ccLinkProgram(String newwd, FileName *files, int numFiles)
{
String command;
char oldwd[1024];
int rc;
newwd = ccOutputDir(newwd, ccOptionList);
ccSwapDir(newwd, oldwd, sizeof(oldwd));
command = ccLinkCommand(ccLinker, ccOptions, numFiles, files,
ccOptionList, newwd, oldwd);
ccEchoIf("Exec: %s\n", command);
rc = osRun(command);
if (rc != 0) comsgFatal(NULL, ALDOR_F_LinkFailed, command);
ccSwapDir(oldwd, NULL, int0);
strFree(command);
strFree(newwd);
}
/*
* Run a program
*/
void
ccGoProgram(FileName fn, int argc1, String *argv1)
{
int i;
Buffer cmdbuf = bufNew();
if (ccGoer)
bufPrintf(cmdbuf, "%s ", ccGoer);
bufPrintf(cmdbuf, "%s", fnameUnparseStaticWith(fn));
for (i = 0; i < argc1; i++)
bufPrintf(cmdbuf, " '%s'", argv1[i]);
ccEchoIf("Exec: %s\n", bufChars(cmdbuf));
osRun(bufChars(cmdbuf));
bufFree(cmdbuf);
}
/*
* Find the directory in which the linked program will be produced.
*/
local String
ccOutputDir(String newwd, struct ccOption *opts)
{
String ofiledir = 0;
FileName fn;
while (opts) {
if (opts->tag == CCOPT_OutputFile) {
if (ofiledir) strFree(ofiledir);
fn = fnameParseStatic(opts->arg);
ofiledir = strCopy(fnameDir(fn));
}
opts = opts->next;
}
if (!ofiledir)
ofiledir = strCopy(newwd);
return ofiledir;
}
/*
* Change to the desired directory.
*/
local void
ccSwapDir(String newwd, String oldwdbuf, Length oldwdsize)
{
int rc;
if (strEqual(newwd, osCurDirName()) || strEqual(newwd, "")) {
if (oldwdbuf) strcpy(oldwdbuf, osCurDirName());
}
else {
ccEchoIf("Cd: %s\n", newwd);
rc = osDirSwap(newwd, oldwdbuf, oldwdsize);
if (rc != 0) comsgFatal(NULL, ALDOR_F_CdFailed, newwd);
}
}
local void
ccEchoIf(String fmt, String arg)
{
if (ccVerboseFlag) { fprintf(osStdout, fmt, arg); fflush(osStdout); }
}
| 2.0625 | 2 |
2024-11-18T22:28:59.785802+00:00 | 2010-01-02T14:31:04 | b46f41e8ea5b15a12a659fee2234230a934a3362 | {
"blob_id": "b46f41e8ea5b15a12a659fee2234230a934a3362",
"branch_name": "refs/heads/master",
"committer_date": "2010-01-02T14:31:04",
"content_id": "f30084e1841bd4231650e1547e2693f2b0ec3224",
"detected_licenses": [
"MIT"
],
"directory_id": "d26bfcbedc2876524c5af2b88171f9b9e004e810",
"extension": "c",
"filename": "addrtreepage.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 291387,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2951,
"license": "MIT",
"license_type": "permissive",
"path": "/obl/storage/addrtreepage.c",
"provenance": "stackv2-0132.json.gz:96355",
"repo_name": "smashwilson/objectlite",
"revision_date": "2010-01-02T14:31:04",
"revision_id": "5fb2e98341f6689fd18a73ad4012195abfea0057",
"snapshot_id": "3d39de16ed3d5f19e225d400a8ff19dfa51d3a4c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/smashwilson/objectlite/5fb2e98341f6689fd18a73ad4012195abfea0057/obl/storage/addrtreepage.c",
"visit_date": "2016-09-06T03:01:16.450020"
} | stackv2 | /*
* Copyright (C) 2009 Ashley J. Wilson, Roger E. Ostrander
* This software is licensed as described in the file COPYING in the root
* directory of this distribution.
*
*
*/
#include "storage/addrtreepage.h"
#include "database.h"
#include "session.h"
#include "storage/object.h"
#include <stdio.h>
#include <stdlib.h>
struct obl_object *obl_create_addrtreepage(obl_uint depth)
{
struct obl_object *result;
struct obl_addrtreepage_storage *storage;
obl_uint i;
result = _obl_allocate_object();
if (result == NULL) {
return NULL;
}
result->shape = _obl_at_fixed_address(OBL_ADDRTREEPAGE_SHAPE_ADDR);
storage = malloc(sizeof(struct obl_addrtreepage_storage));
if (storage == NULL) {
free(result);
obl_report_error(NULL, OBL_OUT_OF_MEMORY, NULL);
return NULL;
}
storage->height = depth;
for (i = 0; i < CHUNK_SIZE; i++) {
storage->contents[i] = OBL_PHYSICAL_UNASSIGNED;
}
result->storage.addrtreepage_storage = storage;
return result;
}
struct obl_object *obl_addrtreepage_read(struct obl_session *session,
struct obl_object *shape, obl_uint *source, obl_physical_address base,
int depth)
{
struct obl_object *result;
obl_uint height;
obl_physical_address addr;
int i;
height = readable_uint(source[base + 1]);
result = obl_create_addrtreepage(height);
for (i = 0; i < CHUNK_SIZE; i++) {
addr = (obl_physical_address) readable_uint(source[base + 2 + i]);
result->storage.addrtreepage_storage->contents[i] = addr;
}
return result;
}
void obl_addrtreepage_write(struct obl_object *treepage, obl_uint *dest)
{
int i;
obl_physical_address base;
obl_physical_address *contents;
base = treepage->physical_address;
dest[base + 1] =
writable_uint(treepage->storage.addrtreepage_storage->height);
contents = treepage->storage.addrtreepage_storage->contents;
for (i = 0; i < CHUNK_SIZE; i++) {
dest[base + 2 + i] = writable_uint((obl_uint) contents[i]);
}
}
void obl_addrtreepage_print(struct obl_object *addrtreepage,
int depth, int indent)
{
int in, i;
struct obl_addrtreepage_storage *storage;
for (in = 0; in < indent; in++) { putchar(' '); }
if (depth == 0) {
printf("<address tree page: 0x%08lx>\n",
(unsigned long) addrtreepage->logical_address);
return ;
}
storage = addrtreepage->storage.addrtreepage_storage;
printf("Address Map ");
if (storage->height == (obl_uint) 0) {
puts("Leaf");
} else {
puts("Branch");
}
for (in = 0; in < indent; in++) { putchar(' '); }
printf("Height: %d\n", storage->height);
for (i = 0; i < CHUNK_SIZE; i++) {
for (in = 0; in < indent; in++) { putchar(' '); }
printf("[%03d] 0x%08lx\n", i,
(unsigned long) storage->contents[i]);
}
}
| 2.859375 | 3 |
2024-11-18T22:29:00.063910+00:00 | 2013-12-27T08:23:55 | e045afd65f119918994ee14eeabd7afc15a2db9d | {
"blob_id": "e045afd65f119918994ee14eeabd7afc15a2db9d",
"branch_name": "refs/heads/master",
"committer_date": "2013-12-27T08:23:55",
"content_id": "82324731eb0d05b46b92e0a75794b19583e869fd",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "4ecceef57f5f71417e2d75c3d5ad291f6f2dc79c",
"extension": "c",
"filename": "daemon.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1892067,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2985,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/sandbox/console/daemon.c",
"provenance": "stackv2-0132.json.gz:96612",
"repo_name": "deadcafe/JohnDoe",
"revision_date": "2013-12-27T08:23:55",
"revision_id": "41a3bfa2a90025673d9b4f3f2272e5d6977dca1d",
"snapshot_id": "95977bc0a8d5fe764c262672d4b3aa9d7b430576",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/deadcafe/JohnDoe/41a3bfa2a90025673d9b4f3f2272e5d6977dca1d/sandbox/console/daemon.c",
"visit_date": "2021-01-19T05:03:38.540434"
} | stackv2 | /*
* Copyright (c) 2011 NEC Corporation, All rights reserved.
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <syslog.h>
#include <signal.h>
#include <johndoe/command.h>
#include <johndoe/log.h>
static void
show_ver(struct jd_cmd_handle *handle,
void *ctx __attribute__((unused)),
int argc __attribute__((unused)),
char **argv __attribute__((unused)))
{
jd_cmd_printf(handle, "this is test version\n");
}
static void
foobar(struct jd_cmd_handle *handle,
void *ctx __attribute__((unused)),
int argc,
char **argv)
{
jd_cmd_printf(handle, "exec foobar: argc: %d argv[0]:%s\n",
argc, argv[0]);
}
static const struct jd_cmd_table foo_cmdset[] = {
{
.cmd = "bar",
.func = foobar,
.help = "test command#1",
},
{
.cmd = NULL,
},
};
static const struct jd_cmd_table cmdset[] = {
{
.cmd = "ver",
.func = show_ver,
.help = "show version",
},
{
.cmd = "foo",
.help = "test command",
.sub = foo_cmdset,
},
{
.cmd = NULL,
},
};
static void
logger(int lv __attribute__((unused)),
const char *fmt,
...)
{
va_list ap;
if (lv > LOG_INFO)
return;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
static void
server_err_handler(struct jd_cmd_handle *handle,
void *ctx __attribute__((unused)),
int sock __attribute__((unused)),
int ecode)
{
fprintf(stderr, "catch server err: %s\n", strerror(ecode));
jd_cmd_destroy(handle);
}
static struct jd_cmd_handle *
server(const char *remote,
uint16_t port,
const char *fname)
{
struct jd_cmd_handle *sock;
sock = jd_cmd_init(NULL, "hoge> ", cmdset, port, remote,
server_err_handler, NULL);
if (!sock) {
fprintf(stderr, "failed at command_init\n");
return NULL;
}
if (!jd_cmd_bind_stdin(sock, NULL, NULL, server_err_handler, NULL)) {
fprintf(stderr, "failed at command_bind_stdin\n");
}
if (fname) {
if (jd_cmd_bind_file(sock, NULL, fname, STDOUT_FILENO) < 0) {
fprintf(stderr, "failed at command_bind_file\n");
}
}
return sock;
}
int
main(int argc,
char **argv)
{
int c;
struct jd_cmd_handle *sock = NULL;
char *fname = NULL;
char *remote = "unix.socket";
uint16_t port = 1443;
fprintf(stderr, "%d argc: %d argv[0]: %s\n", getpid(), argc, argv[0]);
while ((c = getopt(argc, argv, "f:p:r:")) != -1) {
switch (c) {
case 'f':
fname = optarg;
break;
case 'p':
port = atoi(optarg);
break;
case 'r':
remote = optarg;
break;
default:
fprintf(stderr,
"usage: [-f file] [-r remote] [-p port]n");
exit(0);
}
}
event_init();
signal(SIGPIPE, SIG_IGN);
jd_set_logger(logger);
sock = server(remote, port, fname);
event_dispatch();
jd_cmd_close(sock);
fprintf(stderr, "done\n");
return 0;
}
| 2.34375 | 2 |
2024-11-18T22:29:00.209828+00:00 | 2020-10-09T06:02:34 | 21240dc89d46a65563a66e41f67d288f2d7b9df7 | {
"blob_id": "21240dc89d46a65563a66e41f67d288f2d7b9df7",
"branch_name": "refs/heads/main",
"committer_date": "2020-10-09T06:02:34",
"content_id": "20f8bb435060bc32184748f481685b880f691ea3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "eca4c8af6042ff87aef0f0e0e62b5bd6177c6843",
"extension": "c",
"filename": "bsp_irda.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": 1696,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/08.Smart_Car/01.Smart_Car/Hardware/irda/bsp_irda.c",
"provenance": "stackv2-0132.json.gz:96742",
"repo_name": "hqgboy/BearPi",
"revision_date": "2020-10-09T06:02:34",
"revision_id": "592bbd6cd315de3748e5291479a7ea09c96ceec8",
"snapshot_id": "36981128bfe7063d6361b81dae58e9a9c47655be",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hqgboy/BearPi/592bbd6cd315de3748e5291479a7ea09c96ceec8/08.Smart_Car/01.Smart_Car/Hardware/irda/bsp_irda.c",
"visit_date": "2022-12-27T22:52:58.942043"
} | stackv2 | #include "bsp_irda.h"
uint32_t frame_data=0; /* 一帧数据缓存 */
uint8_t frame_cnt=0;
uint8_t frame_flag=0; /* 一帧数据接收完成标志 */
void IrDa_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
IRDA_RCC_CLK_ENABLE();
/*Configure GPIO pin : PB1 */
GPIO_InitStruct.Pin = IRDA_GPIO_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(IRDA_GPIO, &GPIO_InitStruct);
/* EXTI interrupt init*/
HAL_NVIC_SetPriority(IRDA_EXTI_IRQn, 1, 0);
HAL_NVIC_EnableIRQ(IRDA_EXTI_IRQn);
}
/**
* 函数功能: 获取高电平的时间
* 输入参数: 无
* 返 回 值: 时间
* 说 明:无
*/
uint8_t Get_Pulse_Time(void)
{
uint8_t time = 0;
while( IrDa_DATA_IN() )
{
time ++;
HAL_Delay(2); // 延时 20us
if(time == 250)
return time; // 超时溢出
}
return time;
}
/**
* 函数功能: 获取帧数据
* 输入参数: 无
* 返 回 值: 帧数据
* 说 明:帧数据有4个字节,第一个字节是遥控的ID,第二个字节是
* 第一个字节的反码;第三个数据是遥控的真正的键值,
* 第四个字节是第三个字节的反码
*/
uint8_t IrDa_Process(void)
{
uint8_t first_byte, sec_byte, tir_byte, fou_byte;
first_byte = frame_data >> 24;
sec_byte = (frame_data>>16) & 0xff;
tir_byte = frame_data >> 8;
fou_byte = frame_data;
/* 记得清标志位 */
frame_flag = 0;
if( (first_byte==(uint8_t)~sec_byte) && (first_byte==IRDA_ID) )
{
if( tir_byte == (uint8_t)~fou_byte )
return tir_byte;
}
return 0; /* 错误返回 */
}
| 2.5625 | 3 |
2024-11-18T22:29:00.516618+00:00 | 2019-11-18T22:16:19 | 0855f59ba6cfb71ef3bc31782cef25e5eb0e5704 | {
"blob_id": "0855f59ba6cfb71ef3bc31782cef25e5eb0e5704",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-18T22:16:19",
"content_id": "035d37228979306df882aea5d5f09e5e4c15c32c",
"detected_licenses": [
"MIT"
],
"directory_id": "1dc2021a1589a27fe492151d08ba71493cdbbbad",
"extension": "c",
"filename": "pi_spi_din_4ao.c",
"fork_events_count": 1,
"gha_created_at": "2019-11-18T22:09:33",
"gha_event_created_at": "2019-11-18T22:09:34",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 222554210,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1136,
"license": "MIT",
"license_type": "permissive",
"path": "/src/pi_spi_din_4ao.c",
"provenance": "stackv2-0132.json.gz:97001",
"repo_name": "bootsy52/libwidgetlords",
"revision_date": "2019-11-18T22:16:19",
"revision_id": "f5a680858c9c59afa648dcdcb13c9046e97c04ec",
"snapshot_id": "dd5585a2e60d4e0df1a3048925f1f3c14baf3931",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bootsy52/libwidgetlords/f5a680858c9c59afa648dcdcb13c9046e97c04ec/src/pi_spi_din_4ao.c",
"visit_date": "2020-09-12T20:57:08.524448"
} | stackv2 | #include <errno.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <pi_spi_din.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
static int fd = -1;
void pi_spi_din_4ao_init()
{
// if((fd = open("/dev/i2c-1", O_RDWR)) < 0)
// {
// printf("Unable to open I2C device\n");
// return;
// }
// if(ioctl(fd, I2C_SLAVE, 0x60) < 0)
// {
// printf("I2C address select failure: %s\n", strerror(errno));
// return;
// }
}
void pi_spi_din_4ao_write_single(uint8_t address, uint8_t channel, uint16_t counts)
{
address = (address % 8) + 0x60; // valid addresses are from 0x60 to 0x67 only
channel %= 4; // four channels on this unit
if(fd < 0)
{
fd = open("/dev/i2c-1", O_RDWR);
if(fd < 0)
{
printf("Unable to open I2C device\n");
return;
}
}
if(ioctl(fd, I2C_SLAVE, address) < 0)
{
printf("I2C address select failure: %s\n", strerror(errno));
return;
}
uint8_t data[] =
{
0x40 | channel << 1,
0x80 | (counts >> 8 & 0x0F),
counts & 0xFF
};
write(fd, data, sizeof(data));
}
void pi_spi_din_4ao_close()
{
if(fd >= 0)
{
close(fd);
fd = -1;
}
}
| 2.765625 | 3 |
2024-11-18T22:29:00.778852+00:00 | 2021-08-25T21:47:10 | b98bfe8b59e796768a520c05942b526df6846498 | {
"blob_id": "b98bfe8b59e796768a520c05942b526df6846498",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-25T21:47:10",
"content_id": "e7c86776e2a672bb560d2665c5eb6273951a3404",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c62e0b778f2223887fd4782597c840b4ba855831",
"extension": "c",
"filename": "cbip_encode.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": 3648,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/nanos-app-vax/src-cbor/cbip_encode.c",
"provenance": "stackv2-0132.json.gz:97129",
"repo_name": "btchip/ethc21-vax",
"revision_date": "2021-08-25T21:47:10",
"revision_id": "3dc6fcc359a45e975a26c94b389809fece0f09b6",
"snapshot_id": "ea17da2bafdca0d2120813b0768222f9c548ad6a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/btchip/ethc21-vax/3dc6fcc359a45e975a26c94b389809fece0f09b6/nanos-app-vax/src-cbor/cbip_encode.c",
"visit_date": "2023-07-17T09:48:01.116728"
} | stackv2 | /*
*******************************************************************************
* Vax App PoC
* (c) 2021 Ledger
*
* 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 "cbip_encode.h"
#include "cbip_internal.h"
#include <string.h>
#define CHECK_AVAILABLE(x) \
if ((encoder->offset + x) > encoder->length) {\
encoder->fault = true;\
return -1;\
}
#define CHECK_FAULT() \
if (encoder->fault) \
return -1
static int cbip_add_header(cbipEncoder_t *encoder, uint8_t tag, uint32_t value) {
if (value < CBOR_LEN_U8) {
CHECK_AVAILABLE(1);
encoder->buffer[encoder->offset++] = (uint8_t)(tag + value);
return 0;
}
if (value <= 0xFF) {
CHECK_AVAILABLE(2);
encoder->buffer[encoder->offset++] = (uint8_t)(tag + CBOR_LEN_U8);
encoder->buffer[encoder->offset++] = (uint8_t)value;
return 0;
}
if (value <= 0xFFFF) {
CHECK_AVAILABLE(3);
encoder->buffer[encoder->offset++] = (uint8_t)(tag + CBOR_LEN_U16);
encoder->buffer[encoder->offset++] = (uint8_t)((value >> 8) & 0xff);
encoder->buffer[encoder->offset++] = (uint8_t)(value & 0xff);
return 0;
}
CHECK_AVAILABLE(5);
encoder->buffer[encoder->offset++] = (uint8_t)(tag + CBOR_LEN_U32);
encoder->buffer[encoder->offset++] = (uint8_t)((value >> 24) & 0xff);
encoder->buffer[encoder->offset++] = (uint8_t)((value >> 16) & 0xff);
encoder->buffer[encoder->offset++] = (uint8_t)((value >> 8) & 0xff);
encoder->buffer[encoder->offset++] = (uint8_t)(value & 0xff);
return 0;
}
int cbip_encoder_init(cbipEncoder_t *encoder, uint8_t *buffer, uint32_t length) {
memset(encoder, 0, sizeof(cbipEncoder_t));
encoder->buffer = buffer;
encoder->length = length;
return 0;
}
int cbip_add_int(cbipEncoder_t *encoder, int value) {
CHECK_FAULT();
return cbip_add_header(encoder, (value >= 0 ? CBOR_UNSIGNED_INT : CBOR_NEGATIVE_INT),
(value >= 0 ? value : -1 - value));
}
static int cbip_add_raw(cbipEncoder_t *encoder, uint8_t tag, const uint8_t *value, uint32_t valueLength) {
int result;
result = cbip_add_header(encoder, tag, valueLength);
if (result < 0) {
return result;
}
CHECK_AVAILABLE(valueLength);
memmove(encoder->buffer + encoder->offset, value, valueLength);
encoder->offset += valueLength;
return 0;
}
int cbip_add_byte_string(cbipEncoder_t *encoder, const uint8_t *value, uint32_t valueLength) {
CHECK_FAULT();
return cbip_add_raw(encoder, CBOR_BYTE_STRING, value, valueLength);
}
int cbip_add_string(cbipEncoder_t *encoder, const char *value) {
CHECK_FAULT();
return cbip_add_raw(encoder, CBOR_TEXT_STRING, (uint8_t*)value, strlen(value));
}
int cbip_add_boolean(cbipEncoder_t *encoder, bool value) {
CHECK_FAULT();
CHECK_AVAILABLE(1);
encoder->buffer[encoder->offset++] = (uint8_t)(CBOR_PRIMITIVE + (value ? CBOR_TRUE : CBOR_FALSE));
return 0;
}
int cbip_add_array_header(cbipEncoder_t *encoder, uint32_t length) {
CHECK_FAULT();
return cbip_add_header(encoder, CBOR_ARRAY, length);
}
int cbip_add_map_header(cbipEncoder_t *encoder, uint32_t length) {
CHECK_FAULT();
return cbip_add_header(encoder, CBOR_MAP, length);
}
| 2.578125 | 3 |
2024-11-18T22:29:01.031610+00:00 | 2022-10-25T13:29:43 | 04f70d9f890b50ebc052cdac2db25c82bdd0670c | {
"blob_id": "04f70d9f890b50ebc052cdac2db25c82bdd0670c",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-25T13:29:43",
"content_id": "14cc52e087c7c78f2f16c0d1db2c3b3d7482d25f",
"detected_licenses": [
"MIT"
],
"directory_id": "0246bebabd314dbf1c374fa3038f76d2cf8b2b14",
"extension": "c",
"filename": "zerocurve.c",
"fork_events_count": 9,
"gha_created_at": "2018-01-30T19:20:07",
"gha_event_created_at": "2021-01-11T17:56:51",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 119582851,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4455,
"license": "MIT",
"license_type": "permissive",
"path": "/isda/zerocurve.c",
"provenance": "stackv2-0132.json.gz:97386",
"repo_name": "bakera1/CreditDefaultSwapPricer",
"revision_date": "2022-10-25T13:29:43",
"revision_id": "f85d1afaa1377d9e4b9db05da0eb9d154b1f548d",
"snapshot_id": "1f1b974483ef66bea5ebb2f6d6941bf403b99314",
"src_encoding": "UTF-8",
"star_events_count": 20,
"url": "https://raw.githubusercontent.com/bakera1/CreditDefaultSwapPricer/f85d1afaa1377d9e4b9db05da0eb9d154b1f548d/isda/zerocurve.c",
"visit_date": "2022-10-31T05:51:56.680290"
} | stackv2 | /*
* ISDA CDS Standard Model
*
* Copyright (C) 2009 International Swaps and Derivatives Association, Inc.
* Developed and supported in collaboration with Markit
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the ISDA CDS Standard Model Public License.
*/
#include "zerocurve.h"
#include "tcurve.h"
#include "macros.h"
#include "cerror.h"
#include "gtozc.h"
#include <ctype.h>
#define JpmcdsSWAPNAME 'S'
#define JpmcdsMONEYNAME 'M'
/*
***************************************************************************
** Build zero curve from money market, and swap instruments.
***************************************************************************
*/
EXPORT TCurve* JpmcdsBuildIRZeroCurve(
TDate valueDate, /* (I) Value date */
char *instrNames, /* (I) Array of 'M' or 'S' */
TDate *dates, /* (I) Array of swaps dates */
double *rates, /* (I) Array of swap rates */
long nInstr, /* (I) Number of benchmark instruments */
long mmDCC, /* (I) DCC of MM instruments */
long fixedSwapFreq, /* (I) Fixed leg freqency */
long floatSwapFreq, /* (I) Floating leg freqency */
long fixedSwapDCC, /* (I) DCC of fixed leg */
long floatSwapDCC, /* (I) DCC of floating leg */
long badDayConv, /* (I) Bad day convention */
char *holidayFile) /* (I) Holiday file */
{
static char routine[] = "BuildIRZeroCurve";
int status = FAILURE;
int i;
int nCash = 0;
int nSwap = 0;
char fwdLength = '3'; /* not used */
char instr;
TDate *cashDates = NULL;
TDate *swapDates = NULL;
double *cashRates = NULL;
double *swapRates = NULL;
TCurve *zcurveIni = NULL;
TCurve *zcurveCash = NULL;
TCurve *zcurveSwap = NULL;
/* Allocate enough spaces for cash and swap dates/rates */
cashDates = NEW_ARRAY(TDate, nInstr);
swapDates = NEW_ARRAY(TDate, nInstr);
cashRates = NEW_ARRAY(double, nInstr);
swapRates = NEW_ARRAY(double, nInstr);
if (cashDates == NULL || swapDates == NULL || cashRates == NULL || swapRates == NULL)
goto done;
/* Sort out cash and swap separately */
for(i = 0; i < nInstr; i++)
{
instr = toupper(instrNames[i]);
if (instr != JpmcdsMONEYNAME && instr != JpmcdsSWAPNAME)
{
JpmcdsErrMsg("%s: unknown instrument type (%c)."
" Only (M)oney market or (S)wap is allowed.\n",
routine, instrNames[i]);
goto done;
}
if (instr == JpmcdsMONEYNAME)
{ /* MM Rate */
cashDates[nCash] = dates[i];
cashRates[nCash] = rates[i];
nCash++;
}
else /* Swap Rate */
{
swapDates[nSwap] = dates[i];
swapRates[nSwap] = rates[i];
nSwap++;
}
}
/* Initialize the zero curve */
zcurveIni = JpmcdsNewTCurve(valueDate, 0, (double) 1L, JPMCDS_ACT_365F);
if (zcurveIni == NULL)
goto done;
/* Cash instruments */
zcurveCash = JpmcdsZCCash(zcurveIni, cashDates, cashRates, nCash, mmDCC);
if (zcurveCash == NULL)
goto done;
/* Swap instruments */
zcurveSwap = JpmcdsZCSwaps(zcurveCash,
NULL, /* discZC */
swapDates,
swapRates,
nSwap,
fixedSwapFreq,
floatSwapFreq,
fixedSwapDCC,
floatSwapDCC,
fwdLength,
badDayConv,
holidayFile);
if (zcurveSwap == NULL)
goto done;
status = SUCCESS;
done:
FREE(cashDates);
FREE(cashRates);
FREE(swapDates);
FREE(swapRates);
JpmcdsFreeTCurve(zcurveIni);
JpmcdsFreeTCurve(zcurveCash);
if (status != SUCCESS)
{
JpmcdsFreeTCurve(zcurveSwap);
zcurveSwap = NULL;
JpmcdsErrMsgFailure(routine);
}
return (zcurveSwap);
}
| 2.140625 | 2 |
2024-11-18T22:29:01.098813+00:00 | 2021-05-27T20:06:32 | 17cbfe5f20dd21ca9f072eb852b811e5a75a4dc2 | {
"blob_id": "17cbfe5f20dd21ca9f072eb852b811e5a75a4dc2",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-27T20:06:32",
"content_id": "ee48c530e8fb62577da4b7eadfca551a99d30a9f",
"detected_licenses": [
"MIT"
],
"directory_id": "2700bfbdfcf5ec2382b2f1b30380b1bda6641207",
"extension": "c",
"filename": "test1.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 371486849,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 793,
"license": "MIT",
"license_type": "permissive",
"path": "/project3/xv6-public-master/test1.c",
"provenance": "stackv2-0132.json.gz:97515",
"repo_name": "hieu-ai/operation-system-projects",
"revision_date": "2021-05-27T20:06:32",
"revision_id": "2e3e2e2a84e7dcf12467ec83ddf7ca09a7d47459",
"snapshot_id": "46c75560b6d797ceded189daf2ecef94cce7a433",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hieu-ai/operation-system-projects/2e3e2e2a84e7dcf12467ec83ddf7ca09a7d47459/project3/xv6-public-master/test1.c",
"visit_date": "2023-05-04T19:54:11.301838"
} | stackv2 | #include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
#define IOjob 200
#define CPUjob 1000000
int fib(int param){
if(param <= 0){
return 0;
}
else if(param == 1){
return 1;
}
else{
return fib(param-1) + fib(param-2);
}
}
int main(int argc, char *argv[])
{
int x = 999999999;
int pid = fork();
if (pid > 0){ //parent
// Do I/O intensive jo
for(int i=0;i<IOjob;i++){
int fd=open("testIO.txt", O_RDONLY);
write(fd, "A", 1);
char buf[15];
read(fd,buf,sizeof buf);
printf(1, " ");
x++;
}
wait();
} else {
int x = 999999999;
for (double z = 0; z < CPUjob; z += 1){
x = x / 3.14;
x=x*3.14+444; // Some random calculation
x = fib(7);
}
}
getpinfo(getpid());
exit();
}
| 2.46875 | 2 |
2024-11-18T22:29:01.299285+00:00 | 2019-12-20T10:15:50 | 10c4b5a9491ab0539bdc1e90aff18d2c6c836862 | {
"blob_id": "10c4b5a9491ab0539bdc1e90aff18d2c6c836862",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-20T10:15:50",
"content_id": "c2f8f4aff049dcc1f10ae8a7f2a7f05ffb91e22e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7e8fe740bc2b81d0ae0ac8d2bfc2396d87075f89",
"extension": "c",
"filename": "accelerometer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 229233858,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2264,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/accelerometer.c",
"provenance": "stackv2-0132.json.gz:97775",
"repo_name": "CalibraNBC/BC-HD.07-AVR-Studio-4",
"revision_date": "2019-12-20T10:15:50",
"revision_id": "211000f9052da19eed8e4dc82976b9535a6ae08e",
"snapshot_id": "9aad4c7a6c933229c1e37931f90122ccc3373b97",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CalibraNBC/BC-HD.07-AVR-Studio-4/211000f9052da19eed8e4dc82976b9535a6ae08e/accelerometer.c",
"visit_date": "2020-11-26T23:46:55.533332"
} | stackv2 | #include "accelerometer.h"
#include "i2c.h"
#include "variables.h"
void accelerometer_init(void)
{
#ifdef LIS302DL
//------------------SW ON---------------
i2c_start();
i2c_addr_w(LIS302DL_ADDRESS);
i2c_data_w(160);
i2c_data_w(71);
i2c_stop();
#endif
#ifndef LIS302DL
//------------------Offset---------------
i2c_start();
i2c_addr_w(LIS3LV02DQ_ADDRESS);
i2c_data_w(150);
i2c_data_w(20); //Ofset Z
i2c_data_w(10); // Y
i2c_data_w(20); // X
i2c_data_w(73); //Gain Z
i2c_data_w(185); // Y
i2c_data_w(183 ); // X
i2c_stop();
//------------------SW ON---------------
i2c_start();
i2c_addr_w(LIS3LV02DQ_ADDRESS);
i2c_data_w(160);
i2c_data_w(199);
i2c_data_w(1);
i2c_stop();
#endif
}
void accelerometer_stby(void)
{
i2c_start();
#ifdef LIS302DL
i2c_addr_w(LIS302DL_ADDRESS);
#endif
#ifndef LIS302DL
i2c_addr_w(LIS3LV02DQ_ADDRESS);
#endif
i2c_data_w(160);
i2c_data_w(0);
i2c_stop();
}
void accelerometer_read(void)
{
#ifndef LIS302DL
i2c_start();
i2c_addr_w(LIS3LV02DQ_ADDRESS);
i2c_data_w(168);
i2c_stop();
i2c_start();
i2c_addr_r(LIS3LV02DQ_ADDRESS);
i2c_data_rd();
#ifdef HW08S65
accelerometer_z=i2c_data_rd();
i2c_data_rd();
accelerometer_x=i2c_data_rd();
i2c_data_rd();
accelerometer_y=i2c_data_r();
i2c_stop();
#endif
#ifdef HW09
accelerometer_x=i2c_data_rd();
i2c_data_rd();
accelerometer_z=i2c_data_rd();
i2c_data_rd();
accelerometer_y=i2c_data_r();
i2c_stop();
#endif
#endif
#ifdef LIS302DL
i2c_start();
i2c_addr_w(LIS302DL_ADDRESS);
i2c_data_w(168);
i2c_stop();
i2c_start();
i2c_addr_r(LIS302DL_ADDRESS);
i2c_data_rd();
accelerometer_z=i2c_data_rd();
i2c_data_rd();
accelerometer_x=i2c_data_rd();
i2c_data_rd();
accelerometer_y=i2c_data_r();
i2c_stop();
#endif
}
void zmeraj_pretazenie(void)
{
char tmpx, tmpy;
accelerometer_read();
accelerometer_x=accelerometer_x-offset_x;
accelerometer_y=accelerometer_y-offset_y;
tmpx=accelerometer_x;
tmpy=accelerometer_y;
if (tmpx<0) tmpx=256-tmpx;
if (tmpy<0) tmpy=256-tmpy;
if (tmpx>max_pretazenie_x) max_pretazenie_x=tmpx;
if (tmpy>max_pretazenie_y) max_pretazenie_y=tmpy;
}
| 2.0625 | 2 |
2024-11-18T22:29:01.570575+00:00 | 2021-04-01T10:46:16 | 99db2ea93afb0666bb521ee8e426d3033ac6f4d3 | {
"blob_id": "99db2ea93afb0666bb521ee8e426d3033ac6f4d3",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-01T10:46:16",
"content_id": "4c0d1dfe197bfc6f4528a7cc526121398f358bad",
"detected_licenses": [
"MIT"
],
"directory_id": "4abe948f322c1ed49e033afda66b9258ec54bbfc",
"extension": "c",
"filename": "rng.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": 2149,
"license": "MIT",
"license_type": "permissive",
"path": "/tools/random/rng.c",
"provenance": "stackv2-0132.json.gz:98035",
"repo_name": "e-dant/cauldron",
"revision_date": "2021-04-01T10:46:16",
"revision_id": "fb76c7b02358b08cfb86f5771dfd50f04fd6cbe4",
"snapshot_id": "ab59445b4b5840dc00824f13a22d5b5616e3ec7c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/e-dant/cauldron/fb76c7b02358b08cfb86f5771dfd50f04fd6cbe4/tools/random/rng.c",
"visit_date": "2023-03-27T19:28:34.585944"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RANDOM_H_IMPLEMENTATION
#include <cauldron/random.h>
#include "msws.h"
/*
* Example:
* ./rng <name> | ./testu01 SmallCrush
* ./rng <name> | ./RNG_test stdin
*/
#define BUFSIZE (1024*1024)
void *buffer;
void *bufferend;
#define RANDOM_X32(type, func, rand) \
MAKE_RNG(func, type, rand, 32)
#define RANDOM_X64(type, func, rand) \
MAKE_RNG(func, type, rand, 64)
#define MAKE_RNG(func, type, rand, n) \
static void \
run_##func(void) \
{ \
type rng; \
rand(&rng); \
while (1) { \
uint##n##_t *p = buffer; \
while ((void*)p < bufferend) \
*p++ = func(&rng); \
fwrite(buffer, 1, BUFSIZE, stdout); \
} \
}
#include <cauldron/random-xmacros.h>
#undef MAKE_RNG
#define MAKE_RNG(func, type, n) \
static void \
run_##func(void) \
{ \
type rng; \
trng_write(&rng, sizeof rng); \
while (1) { \
uint##n##_t *p = buffer; \
while ((void*)p < bufferend) \
*p++ = func(&rng); \
fwrite(buffer, 1, BUFSIZE, stdout); \
} \
}
MAKE_RNG(msws32_64bit, MsWs32_64bit, 32);
MAKE_RNG(msws64_128bit, MsWs64_128bit, 64);
MAKE_RNG(msws64_2x64bit, MsWs64_2x64bit, 64);
#undef MAKE_RNG
static void
run_trng_write(void)
{
while (1) {
trng_write(buffer, BUFSIZE);
fwrite(buffer, 1, BUFSIZE, stdout);
}
}
static struct {
char *name;
void (*rng)(void);
} rngs[] = {
#define MAKE_RNG(func, type, rand, n) \
{ #func, run_##func },
#include <cauldron/random-xmacros.h>
#undef MAKE_RNG
{ "msws32_64bit", run_msws32_64bit },
{ "msws64_128bit", run_msws64_128bit },
{ "msws64_2x64bit", run_msws64_2x64bit },
{ "trng_write", run_trng_write },
};
static void list(void)
{
size_t i;
for (i = 0; i < sizeof rngs / sizeof *rngs; ++i)
puts(rngs[i].name);
}
int
main(int argc, char **argv)
{
size_t i;
char *name = argv[1];
(void)argc;
buffer = malloc(BUFSIZE);
bufferend = (void*)((char*)buffer + BUFSIZE);
if (!name) {
list();
return EXIT_FAILURE;
}
for (i = 0; i < sizeof rngs / sizeof *rngs; ++ i) {
if (strcmp(name, rngs[i].name) == 0) {
rngs[i].rng();
return EXIT_SUCCESS;
}
}
list();
return EXIT_FAILURE;
}
| 2.546875 | 3 |
2024-11-18T22:29:01.641286+00:00 | 2021-03-01T05:03:36 | 7abde3b0108c6e1ca68c0b731f147ff8757d482a | {
"blob_id": "7abde3b0108c6e1ca68c0b731f147ff8757d482a",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-01T05:03:36",
"content_id": "69540cd45f603e04b053a888152c92d41273892d",
"detected_licenses": [
"MIT"
],
"directory_id": "5ca51e9e49083b2bc1d68cbf1e0c07aa267123c6",
"extension": "c",
"filename": "common.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": 571,
"license": "MIT",
"license_type": "permissive",
"path": "/apps/webaudio-spectrum-analyser/src/app/wasm/common.c",
"provenance": "stackv2-0132.json.gz:98165",
"repo_name": "steflen/webaudio-spectrum-analyser",
"revision_date": "2021-03-01T05:03:36",
"revision_id": "71e886a546a33c26819de832b67f1bb0f9efb775",
"snapshot_id": "73bf1075f79d5a149ee735e3624eced3819aa516",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/steflen/webaudio-spectrum-analyser/71e886a546a33c26819de832b67f1bb0f9efb775/apps/webaudio-spectrum-analyser/src/app/wasm/common.c",
"visit_date": "2023-03-18T02:38:51.372240"
} | stackv2 | #include "common.h"
#include <math.h>
double mean(tdval_t *data, int length) {
double sum = 0.0;
for (int i = 0; i < length; ++i) {
sum += data[i];
}
return sum / length;
}
double variance(tdval_t *data, int length, double mean) {
double sum = 0.0;
for (int i = 0; i < length; ++i) {
double val = data[i] - mean;
sum += val * val;
}
return sum / length;
}
EMSCRIPTEN_KEEPALIVE
double rms(tdval_t *data, int length) {
double sum = 0.0;
for (int i = 0; i < length; ++i) {
sum += data[i] * data[i];
}
return sqrt(sum / length);
}
| 2.390625 | 2 |
2024-11-18T22:29:01.717784+00:00 | 2020-12-16T08:17:58 | 2a347719d6efd6d3bf271c39297c30710ea2e577 | {
"blob_id": "2a347719d6efd6d3bf271c39297c30710ea2e577",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-16T08:17:58",
"content_id": "d74b4877e5ec2977f7e3545a10307e0c55f3f22c",
"detected_licenses": [
"MIT"
],
"directory_id": "a66309beae8cf2b5806099e347073ddda58e3d91",
"extension": "c",
"filename": "file.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 295496438,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 605,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils/file.c",
"provenance": "stackv2-0132.json.gz:98297",
"repo_name": "prismocr/ocr",
"revision_date": "2020-12-16T08:17:58",
"revision_id": "c965cca9f974276a828ab33f134d535bd0c13a5b",
"snapshot_id": "325770bcbbf257a4fee12aedc97088012c49a348",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/prismocr/ocr/c965cca9f974276a828ab33f134d535bd0c13a5b/src/utils/file.c",
"visit_date": "2023-01-31T22:32:44.606925"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
size_t file_size(const char *path) {
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
size_t size = (size_t) ftell(f);
fseek(f, 0, SEEK_SET);
fclose(f);
return size;
}
char *file_read(const char *path) {
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
size_t size = (size_t) ftell(f);
fseek(f, 0, SEEK_SET); /* same as rewind(f); */
char *content = malloc(size + 1);
size_t e = fread(content, 1, size, f);
if (e)
printf("%ld\n", e);
fclose(f);
content[size] = 0;
return content;
}
| 2.890625 | 3 |
2024-11-18T22:29:01.824658+00:00 | 2020-06-13T14:57:57 | 0ca3f844d1f4b06c4da199ca530736a45144ef9f | {
"blob_id": "0ca3f844d1f4b06c4da199ca530736a45144ef9f",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-13T14:57:57",
"content_id": "86a15c5717c7ef1361ca5579fa9ce6988aa6ca7c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6d91fc0a40578a494c27afdf4c153f36014317b7",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 272029526,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 811,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/test.c",
"provenance": "stackv2-0132.json.gz:98427",
"repo_name": "LemonTF/myCommentRedis",
"revision_date": "2020-06-13T14:57:57",
"revision_id": "5adc3f06aa61aa7e6cb31981448e131e07cdc056",
"snapshot_id": "502f661fce56922a775a6a6af177689b047485b0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LemonTF/myCommentRedis/5adc3f06aa61aa7e6cb31981448e131e07cdc056/src/test.c",
"visit_date": "2022-10-17T03:01:25.579266"
} | stackv2 | #include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#define LOG(id,...) log(id,__LINE__,__VA_ARGS__)
void log(int id,int linenum,const char*fmt,...)
{
va_list ap;
char msg[1024]={0};
int len;
len =snprintf(msg,sizeof(msg),"[%d]test the log va_list:%d",id,linenum);
va_start(ap,fmt);
vsnprintf(msg+len,sizeof(msg)-len,fmt,ap);
va_end(ap);
printf("%s\n",msg);
}
#define assert(_e) ((_e)?(void)0 : (_serverAssert(#_e,__FILE__,__LINE__),_exit(1)))
void _serverAssert(const char *estr, const char *file, int line) {
fprintf(stderr, "=== ASSERTION FAILED ===");
fprintf(stderr, "==> %s:%d '%s' is not true",file,line,estr);
*((char*)-1) = 'x';
}
int main()
{
LOG(__LINE__,"this is a va_list test %d,%f",110,12.777);
assert(1>2);
while(1)sleep(1);
}
| 2.46875 | 2 |
2024-11-18T22:29:02.023332+00:00 | 2019-09-24T10:29:41 | 6dc96a9bd60f275fbd5ad34e3d14b02b83b28f0a | {
"blob_id": "6dc96a9bd60f275fbd5ad34e3d14b02b83b28f0a",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-24T10:29:41",
"content_id": "451d8c8809373f7478d55c0433eb5df42c392685",
"detected_licenses": [
"MIT"
],
"directory_id": "69906c30918377443d677fc66ea47365785b14c7",
"extension": "c",
"filename": "label_propagation_debug.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 191355971,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4671,
"license": "MIT",
"license_type": "permissive",
"path": "/dbpargraph/community/label_propagation_debug.c",
"provenance": "stackv2-0132.json.gz:98685",
"repo_name": "mzym/thesis",
"revision_date": "2019-09-24T10:29:41",
"revision_id": "4099fbfc6ccf82acd86001aeb8202dafe8fb499f",
"snapshot_id": "7e2370c718f05b819b0c3dbfd424ea371080edde",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mzym/thesis/4099fbfc6ccf82acd86001aeb8202dafe8fb499f/dbpargraph/community/label_propagation_debug.c",
"visit_date": "2020-06-03T00:11:14.101876"
} | stackv2 | /* (c) Mikhail Zymbler */
#include "label_propagation_debug.h"
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
void assert_nicely(PGconn *conn, PGresult *res, int cond, char * msg)
{
if (!cond) {
fprintf(stderr, "%s\n", msg);
if (res != NULL) {
fprintf(stderr, "Server error message is as follows:\n%s\n", PQresultErrorMessage(res));
PQclear(res);
}
PQfinish(conn);
exit(1);
}
}
void lp_GRAPH(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from GRAPH order by a, b;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the GRAPH table failed!");
fprintf(stderr, "GRAPH:\n");
PQprint(stderr, res, &opt);
}
void lp_VERTEX(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from VERTEX order by a;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the VERTEX table failed!");
fprintf(stderr, "VERTEX:\n");
PQprint(stderr, res, &opt);
}
void lp_AFFINITY(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from AFFINITY order by a,b;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the AFFINITY table failed!");
fprintf(stderr, "AFFINITY:\n");
PQprint(stderr, res, &opt);
}
void lp_COMMUNITY(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from COMMUNITY order by a;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the COMMUNITY table failed!");
fprintf(stderr, "COMMUNITY:\n");
PQprint(stderr, res, &opt);
}
void lp_AFF_TMP_SUBG(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from AFF_TMP_SUBG order by a,b;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the AFF_TMP_SUBG table failed!");
fprintf(stderr, "AFF_TMP_SUBG:\n");
PQprint(stderr, res, &opt);
}
void lp_AFF_TMP_WNBR(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from AFF_TMP_WNBR order by a;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the AFF_TMP_WNBR table failed!");
fprintf(stderr, "AFF_TMP_WNBR:\n");
PQprint(stderr, res, &opt);
}
void lp_COMM_TMP_AFNBRALL(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from COMM_TMP_AFNBRALL order by a;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the COMM_TMP_AFNBRALL table failed!");
fprintf(stderr, "COMM_TMP_AFNBRALL:\n");
PQprint(stderr, res, &opt);
}
void lp_COMM_TMP_AFNBRCOM(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from COMM_TMP_AFNBRCOM order by a;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the COMM_TMP_AFNBRCOM table failed!");
fprintf(stderr, "COMM_TMP_AFNBRCOM:\n");
PQprint(stderr, res, &opt);
}
void lp_COMM_TMP_DMAX(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from COMM_TMP_DMAX order by a;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the COMM_TMP_DMAX table failed!");
fprintf(stderr, "COMM_TMP_DMAX:\n");
PQprint(stderr, res, &opt);
}
void lp_VER_TMP_COMM(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from VER_TMP_COMM order by a;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the VER_TMP_COMM table failed!");
fprintf(stderr, "VER_TMP_COMM:\n");
PQprint(stderr, res, &opt);
}
void lp_tmp(PGconn *conn)
{
PGresult *res;
PQprintOpt opt={0};
opt.header = 1;
opt.align = 1;
opt.fieldSep = "|";
res = PQexec(conn, "select * from tmp;");
assert_nicely(conn, res, PQresultStatus(res)==PGRES_TUPLES_OK, "Selection of tuples from the TMP table failed!");
fprintf(stderr, "TMP:\n");
PQprint(stderr, res, &opt);
}
| 2.28125 | 2 |
2024-11-18T22:29:02.503797+00:00 | 2015-08-27T19:18:45 | 807578e244cc838fe39fe4472ef0936cf3414964 | {
"blob_id": "807578e244cc838fe39fe4472ef0936cf3414964",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-27T19:18:45",
"content_id": "7a95e3968ef416d228de05f69fd6b655a4dec7da",
"detected_licenses": [
"Unlicense"
],
"directory_id": "1b5fcaaae9bac0443209dcc803654d1d84f136e9",
"extension": "c",
"filename": "debug.c",
"fork_events_count": 0,
"gha_created_at": "2015-10-31T14:57:47",
"gha_event_created_at": "2015-10-31T14:57:47",
"gha_language": null,
"gha_license_id": null,
"github_id": 45305789,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 532,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/debug.c",
"provenance": "stackv2-0132.json.gz:99207",
"repo_name": "haifenghuang/c-generic-containers",
"revision_date": "2015-08-27T19:18:45",
"revision_id": "68e1b48958222d230a4a32c93d93f5c489fe5bbf",
"snapshot_id": "383167d355c43527f6876909acd7adc6af6b998b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/haifenghuang/c-generic-containers/68e1b48958222d230a4a32c93d93f5c489fe5bbf/src/debug.c",
"visit_date": "2020-04-13T21:42:07.954486"
} | stackv2 | #ifdef DEBUG
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include "libcontainers/debug.h"
void
print_debug(char const *s)
{
fprintf(stderr, "libcontainers: %s\n", s);
}
void
printf_debug(char const *str, ...)
{
va_list ap;
char *s;
if ((s = malloc(sizeof(*s) + strlen(str) + 2)) == NULL)
{
return;
}
strcpy(s, str);
s[strlen(str)] = '\n';
s[strlen(str) + 1] = 0;
va_start(ap, str);
vfprintf(stderr, s, ap);
va_end(ap);
free(s);
}
#else
typedef int make_gcc_happy;
#endif | 2.109375 | 2 |
2024-11-18T22:29:02.687958+00:00 | 2013-07-12T16:46:57 | 5aa34743f7e94a23afdc84072761f9749bd7f144 | {
"blob_id": "5aa34743f7e94a23afdc84072761f9749bd7f144",
"branch_name": "refs/heads/master",
"committer_date": "2013-07-12T16:46:57",
"content_id": "9948f74efc34f8d3ce179d3dd0076f1a2fc03494",
"detected_licenses": [
"MIT"
],
"directory_id": "0147661435b061fa55c3f1fac4b087728bf57134",
"extension": "c",
"filename": "hashtable_test.c",
"fork_events_count": 3,
"gha_created_at": "2009-12-13T06:41:37",
"gha_event_created_at": "2017-09-16T15:55:38",
"gha_language": "C",
"gha_license_id": null,
"github_id": 430655,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1955,
"license": "MIT",
"license_type": "permissive",
"path": "/src/testing/hashtable_test.c",
"provenance": "stackv2-0132.json.gz:99467",
"repo_name": "breckinloggins/libuseful",
"revision_date": "2013-07-12T16:46:57",
"revision_id": "e631e47214ebc0737a5765282d8bb9ede9d3c87f",
"snapshot_id": "33172bea26f6ba445f1162525b86567c38ec53fa",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/breckinloggins/libuseful/e631e47214ebc0737a5765282d8bb9ede9d3c87f/src/testing/hashtable_test.c",
"visit_date": "2021-04-09T17:13:48.787092"
} | stackv2 | #include "test_utils.h"
#include "platform.h"
#include "hashtable.h"
static int _hash(const void* key) {
return ht_hashpjw((char*)key);
}
static int _match(const void* key1, const void* key2) {
return !strcmp((char*)key1, (char*)key2);
}
static void _destroy(void *data) {
free((char*)data);
}
DEFINE_TEST_FUNCTION {
hashtable_iter* iter;
hashtable* ht = (hashtable*)malloc(sizeof(hashtable));
int i;
if (ht_init(ht, 17, _hash, _match, _destroy) != 0) {
fprintf(stderr, "Hashtable not initialized\n");
return -1;
}
/* Test enumerating over an empty hash table */
i = 0;
iter = ht_iter_begin(ht);
while(iter) {
fprintf(stdout, "Value at %p\n", ht_value(iter));
iter = ht_iter_next(iter);
i++;
}
if (i > 0) {
fprintf(stderr, "Non-zero iterations on empty hashtable\n");
return -1;
}
/* Add some stuff */
if (ht_insert(ht, (void*)xp_strdup("Hello")) != 0) {
fprintf(stderr, "Error inserting item 1\n");
return -1;
}
if (ht_insert(ht, (void*)xp_strdup(",")) != 0) {
fprintf(stderr, "Error inserting item 2\n");
return -1;
}
if (ht_insert(ht, (void*)xp_strdup(" ")) != 0) {
fprintf(stderr, "Error inserting item 3\n");
return -1;
}
if (ht_insert(ht, (void*)xp_strdup("World")) != 0) {
fprintf(stderr, "Error inserting item 4\n");
return -1;
}
/* Attempt to iterate over the list */
i = 0;
iter = ht_iter_begin(ht);
while (iter) {
fprintf(stdout, "%s", (char*)ht_value(iter));
iter = ht_iter_next(iter);
i++;
}
fprintf(stdout, "\n");
if (i != 4) {
fprintf(stderr, "Number of items is %d, should be 4\n", i);
return -1;
}
ht_destroy(ht);
return 0;
}
int main(int argc, char** argv) {
RUN_TEST;
} | 2.9375 | 3 |
2024-11-18T22:29:02.940971+00:00 | 2022-03-09T07:34:17 | d2fbfbfb8d07ce310f1d55e7900e24cd5e1e370b | {
"blob_id": "d2fbfbfb8d07ce310f1d55e7900e24cd5e1e370b",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-09T07:34:17",
"content_id": "56a1fcd54af5b7c5e248153570d3b101c0ed1a25",
"detected_licenses": [
"MIT"
],
"directory_id": "6783954f14a8f41763fc3aac127d70758ee9b1ef",
"extension": "c",
"filename": "fixture.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 132938923,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3229,
"license": "MIT",
"license_type": "permissive",
"path": "/libt7/src/fixture.c",
"provenance": "stackv2-0132.json.gz:99852",
"repo_name": "tronkko/t7",
"revision_date": "2022-03-09T07:34:17",
"revision_id": "82b755d21741cbc642224d767826325ae3ae1130",
"snapshot_id": "96340deac51fd105a0f69856a0a1bd009673c9d9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tronkko/t7/82b755d21741cbc642224d767826325ae3ae1130/libt7/src/fixture.c",
"visit_date": "2022-03-30T13:59:44.862754"
} | stackv2 | /*
* Test-Driven Development Framework 7 for C
*
* Copyright (C) 2018 Toni Ronkko
* This file is part of T7. T7 may be freely distributed under the MIT
* license. For more information, see https://github.com/tronkko/t7
*/
#include "t7/types.h"
#include "t7/fixture.h"
#include "t7/terminate.h"
/* Virtual functions */
static struct allocator *get_fixture_allocator(fixture_t *fp);
/* Current fixture for main thread */
static fixture_t def1 = {
get_fixture_allocator
};
fixture_t *default_fixture = &def1;
/* Operating system specific variables */
#if defined(T7_DISABLE_THREADS)
/* Pointer to current fixture */
static fixture_t *active = default_fixture;
#elif !defined(_WIN32)
/* Initialize thread local storage */
static void init_pthread (void);
/* Pthread key for thread local storage */
static pthread_key_t key;
/* Pthread initializer */
static pthread_once_t key_once = PTHREAD_ONCE_INIT;
#else
/* FIXME: */
#endif
/* Get pointer to current fixture */
fixture_t *get_fixture(void)
{
fixture_t *fp;
#if defined(T7_DISABLE_THREADS)
/* Return pointer to global fixture */
fp = active;
#elif !defined(_WIN32)
/* Initialize thread local key */
if (pthread_once(&key_once, init_pthread) == /*OK*/0) {
/* Does this thread have its own fixture? */
fp = (fixture_t*) pthread_getspecific(key);
if (fp != NULL) {
/* Yes, return pointer to thread's fixture */
/*NOP*/;
} else {
// FIXME: Copy fixture when creating a thread
/* No, return pointer to global fixture */
fp = default_fixture;
}
} else {
/* Thread once failed */
terminate("Cannot initialize fixtures");
fp = NULL;
}
#else
terminate("Fixtures not implemented yet");
#endif
return fp;
}
/* Set active fixture */
void set_fixture(fixture_t *fp)
{
assert(fp != NULL);
assert(fp->get_fixture_allocator != NULL);
#if defined(T7_DISABLE_THREADS)
/* Set active fixture */
active = fp;
#elif !defined(_WIN32)
/* Initialize thread local key */
if (pthread_once(&key_once, init_pthread) == /*OK*/0) {
/* Set pointer to fixture */
if (pthread_setspecific(key, fp) == /*OK*/0) {
/* Success */
/*NOP*/;
} else {
/* Error */
terminate("Cannot set fixture");
}
} else {
/* Thread once failed */
terminate("Cannot initialize fixtures");
}
#else
terminate("Fixtures not implemented yet");
#endif
}
/* Copy fixture object */
void copy_fixture(fixture_t *dest, const fixture_t *src)
{
/* Pre-conditions */
assert(dest != NULL);
assert(src != NULL);
assert(src->get_fixture_allocator != NULL);
/* Copy fixture as is */
dest->get_fixture_allocator = src->get_fixture_allocator;
}
/* Get default allocator */
static struct allocator *get_fixture_allocator(fixture_t *fp)
{
(void) fp;
return get_allocator(default_allocator);
}
/* Initialize pthread */
#if !defined(T7_DISABLE_THREADS) && !defined(_WIN32)
static void init_pthread(void)
{
/* Create fixture key in all threads */
if (pthread_key_create(&key, NULL) != /*OK*/0) {
/*
* Cannot create pthread key. This is a serious error because
* we have no reasonable way to return error from this
* function. Lets just terminate the current program!
*/
terminate("Cannot create fixture key");
}
}
#endif
| 2.9375 | 3 |
2024-11-18T22:29:03.036510+00:00 | 2023-08-05T09:20:14 | 0306577ec72006b8f1cdd7702e98d74b49217ff2 | {
"blob_id": "0306577ec72006b8f1cdd7702e98d74b49217ff2",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-05T09:20:14",
"content_id": "854b26c822ffce124dc939892f57ba673b7c0849",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "77861deda8b3046bdda221d3cb80b77e84b14523",
"extension": "c",
"filename": "kill-strstr.c",
"fork_events_count": 44,
"gha_created_at": "2013-12-03T20:35:37",
"gha_event_created_at": "2020-04-17T17:10:42",
"gha_language": "C++",
"gha_license_id": "BSD-2-Clause",
"github_id": 14905115,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 902,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/kill-gnulib-strstr/kill-strstr.c",
"provenance": "stackv2-0132.json.gz:99983",
"repo_name": "WojciechMula/toys",
"revision_date": "2023-08-05T09:20:14",
"revision_id": "6110b59de45dc1ce44388b21c6437eff49a7655c",
"snapshot_id": "b73f09212ca19f1e76bbf2afaa5ad2efcea95175",
"src_encoding": "UTF-8",
"star_events_count": 302,
"url": "https://raw.githubusercontent.com/WojciechMula/toys/6110b59de45dc1ce44388b21c6437eff49a7655c/kill-gnulib-strstr/kill-strstr.c",
"visit_date": "2023-08-18T12:54:25.919406"
} | stackv2 | #include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
uint32_t get_time(void) {
static struct timeval T;
gettimeofday(&T, NULL);
return (T.tv_sec * 1000000) + T.tv_usec;
}
double strstr_wrapper(char* data, char* substr) {
uint32_t t1 = get_time();
char* c = strstr(data, substr);
uint32_t t2 = get_time();
return (t2 - t1)/1000000.0;
}
int main(int argc, char* argv[]) {
if (argc == 1)
return EXIT_SUCCESS;
const uint32_t MiB = 1024*1024;
const uint32_t size = 16*MiB;
char* buffer = (char*)malloc(size);
if (buffer == NULL)
return EXIT_FAILURE;
memset(buffer, '?', size);
buffer[size - 1] = '\0';
for (int i=1; i < argc; i++) {
printf("searching string '%s'... ", argv[i]);
fflush(stdout);
const double dt = strstr_wrapper(buffer, argv[i]);
printf("time: %0.3f\n", dt);
}
free(buffer);
return EXIT_SUCCESS;
}
| 3.046875 | 3 |
2024-11-18T22:29:03.785345+00:00 | 2022-11-30T19:14:39 | c129185057a4290a9e281daa4e9510fc15288a34 | {
"blob_id": "c129185057a4290a9e281daa4e9510fc15288a34",
"branch_name": "refs/heads/main",
"committer_date": "2022-11-30T19:14:39",
"content_id": "2db4647413eac7713bb795ee93a4565023f6b22d",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "548b0743cd93585b10aa0045d867c02fe9d3e71c",
"extension": "c",
"filename": "threads4.c",
"fork_events_count": 0,
"gha_created_at": "2019-08-15T01:15:35",
"gha_event_created_at": "2019-08-15T01:15:36",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 202450415,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1158,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/tests/c_tests/threads4.c",
"provenance": "stackv2-0132.json.gz:100115",
"repo_name": "jasonwhite/reverie",
"revision_date": "2022-11-30T19:14:39",
"revision_id": "487f7b6d8b19f266296a79b9ea37757addfb2a8b",
"snapshot_id": "72200852cc1c21b15458021dc8de54ed3737d5c7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jasonwhite/reverie/487f7b6d8b19f266296a79b9ea37757addfb2a8b/tests/c_tests/threads4.c",
"visit_date": "2023-03-16T03:30:50.132575"
} | stackv2 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#define assert(b) \
if (!(b)) \
abort();
#define THREAD_LOOP_COUNT 1000
#define NR_THREADS 4L
#define TIME_100MS 100000000UL
static void* threaded(void* param) {
long k = (long)param;
char buf[32];
int n;
n = snprintf(buf, 32, "%lu", k);
for (int i = 0; i < THREAD_LOOP_COUNT; i++) {
write(STDERR_FILENO, buf, n);
}
return 0;
}
int main(int argc, char* argv[]) {
pthread_attr_t attr;
pthread_t threadid[NR_THREADS];
assert(pthread_attr_init(&attr) == 0);
for (long i = 0; i < NR_THREADS; i++) {
assert(pthread_create(&threadid[i], &attr, threaded, (void*)i) == 0);
}
for (long i = 0; i < NR_THREADS; i++) {
assert(pthread_join(threadid[i], NULL) == 0);
}
assert(pthread_attr_destroy(&attr) == 0);
return 0;
}
| 2.46875 | 2 |
2024-11-18T22:29:04.241768+00:00 | 2018-04-19T07:50:52 | db036ed85f7a8627c2d6e73c4523d0e0b04f2c21 | {
"blob_id": "db036ed85f7a8627c2d6e73c4523d0e0b04f2c21",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-19T07:50:52",
"content_id": "bc462bba2534858ee7db4437e671bbca1e38b24b",
"detected_licenses": [
"MIT"
],
"directory_id": "efca83ae5ff6e955131b57609431b7e43f017eb5",
"extension": "c",
"filename": "ads1110.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 104734433,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2783,
"license": "MIT",
"license_type": "permissive",
"path": "/ads1110.c",
"provenance": "stackv2-0132.json.gz:100630",
"repo_name": "jfwells/openvario-ahrs",
"revision_date": "2018-04-19T07:50:52",
"revision_id": "ef584b018cb36edb47ea2f2c7b6a4b0b6ad6473d",
"snapshot_id": "185a9fabe7974d3eedd8df7f66cf23921691512c",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/jfwells/openvario-ahrs/ef584b018cb36edb47ea2f2c7b6a4b0b6ad6473d/ads1110.c",
"visit_date": "2021-09-12T17:31:11.225084"
} | stackv2 | /*
sensord - Sensor Interface for XCSoar Glide Computer - http://www.openvario.org/
Copyright (C) 2014 The openvario project
A detailed list of copyright holders can be found in the file "AUTHORS"
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/>.
*/
#include "ads1110.h"
#include <time.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include "def.h"
extern int g_debug;
extern FILE *fp_console;
int ads1110_open(t_ads1110 *sensor, unsigned char i2c_address)
{
// local variables
int fd;
unsigned char buf[10]={0x00};
// try to open I2C Bus
fd = open("/dev/i2c-1", O_RDWR);
if (fd < 0) {
fprintf(stderr, "Error opening file: %s\n", strerror(errno));
return 1;
}
if (ioctl(fd, I2C_SLAVE, i2c_address) < 0) {
fprintf(stderr, "ioctl error: %s\n", strerror(errno));
sensor->present = 0;
return 1;
}
// Try to read from sensor to check if it present
if (read(fd, buf, 3) != 3)
{
sensor->present = 0;
return (1);
}
if (g_debug > 0) printf("Opened ADS1110 on 0x%x\n", i2c_address);
// assign file handle to sensor object
sensor->fd = fd;
sensor->address = i2c_address;
sensor->present = 1;
return (0);
}
int ads1110_init(t_ads1110 *sensor)
{
// set calibration data
//sensor->voltage_factor = 2.;
ddebug_print("%s @ 0x%x: voltage_factor=%f\n", __func__, sensor->address, sensor->voltage_factor);
return(0);
}
int ads1110_measure(t_ads1110 *sensor)
{
//variables
//struct timespec sample_time;
unsigned char buf[10]={0x00};
//int digoutp;
if (read(sensor->fd, buf, 3) != 3) { // Read back data into buf[]
printf("Unable to read from slave\n");
return(1);
}
sensor->voltage_raw = (buf[0] << 8) + buf[1];
ddebug_print("%s @ 0x%x: voltage_raw=%d\n", __func__, sensor->address, sensor->voltage_raw);
return(0);
}
int ads1110_calculate(t_ads1110 *sensor)
{
sensor->voltage_converted = (sensor->voltage_raw/sensor->voltage_factor);
debug_print("%s @ 0x%x: Voltage: %fV\n", __func__, sensor->address, sensor->voltage_converted);
return (0);
}
| 2.5 | 2 |
2024-11-18T22:29:04.387347+00:00 | 2020-06-11T19:20:34 | dcbcaca5ff55b0f1c835c56b85523a14e3bc1dad | {
"blob_id": "dcbcaca5ff55b0f1c835c56b85523a14e3bc1dad",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-11T19:20:34",
"content_id": "dbc9c75982d7e87061073d5a6faf6d049d8cc0e5",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "3661e271d449ffa874a02d11842a781523627d2a",
"extension": "c",
"filename": "svnlayered-fuse.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 270104268,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5399,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/svnlayered-fuse.c",
"provenance": "stackv2-0132.json.gz:100888",
"repo_name": "dohnuts/svnlayeredfs",
"revision_date": "2020-06-11T19:20:34",
"revision_id": "19d1217d0d5c2e5ea078eff28f46229fd129cfba",
"snapshot_id": "25a0ba27359bb90327a396039633a7859e81ac1b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dohnuts/svnlayeredfs/19d1217d0d5c2e5ea078eff28f46229fd129cfba/svnlayered-fuse.c",
"visit_date": "2022-10-18T03:34:45.517401"
} | stackv2 | #include "svnlayered-fuse.h"
#include <string.h>
#include <syslog.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <svn_dso.h>
struct fuse_session *se;
struct fuse *fuse;
apr_pool_t* arp_pool;
void print_usage() {
fprintf(stderr, "usage: %s [options] -l/under -lbelow [-l...] <mountpoint>\n\n", PROGRAM);
fprintf(stderr,
"general options:\n"
" -o opt,[opt...] mount options\n"
" -h --help print help\n"
" -V --version print version\n"
" -d debug version\n"
"\n");
}
/**
* Function to process arguments (called from fuse_opt_parse).
*
* @param data Pointer to fusezip_param structure
* @param arg is the whole argument or option
* @param key determines why the processing function was called
* @param outargs the current output argument list
* @return -1 on error, 0 if arg is to be discarded, 1 if arg should be kept
*/
static int process_arg(void *data, const char *arg, int key, struct fuse_args *outargs)
{
struct slf_param *param = (struct slf_param*)data;
static int layer = 0;
(void)outargs;
// 'magic' fuse_opt_proc return codes
const static int KEEP = 1;
const static int DISCARD = 0;
const static int ERROR = -1;
switch (key) {
case KEY_HELP: {
print_usage();
param->help = 1;
return DISCARD;
};
case KEY_LAYER: {
if ( layer == 1 ) {
fprintf(stderr, "%s: -l dir !\n", PROGRAM);
return ERROR;
}
layer = 1;
return DISCARD;
};
case FUSE_OPT_KEY_NONOPT: {
if ( layer == 1 ) {
char cpath[MAXPATHLEN] = {};
struct stat cstat = {};
layer = 0;
struct dirname* new = malloc(sizeof(struct dirname));
new->path = arg;
new->len = strnlen(arg, MAXPATHLEN-1);
strcat(cpath ,arg);
strcat(cpath , "/.svn/wc.db");
lstat(cpath, &cstat);
if (S_ISREG(cstat.st_mode)) {
new->spath = apr_array_make(arp_pool, 1, sizeof(const char*));
*(const char**)apr_array_push(new->spath) = new->path;
} else {
new->spath = NULL;
}
SLIST_INSERT_HEAD(&(param->dir_names), new, entries);
return DISCARD;
}
if (param->mount == NULL) {
param->mount = arg;
fprintf(stderr, "%s: %s mountpoint !\n", PROGRAM, param->mount);
} else {
fprintf(stderr, "%s: only one mountpoint !\n", PROGRAM);
return ERROR;
}
return KEEP;
};
default: {
return KEEP;
};
}
}
static const struct fuse_opt slf_opts[] = {
FUSE_OPT_KEY("-h", KEY_HELP),
FUSE_OPT_KEY("--help", KEY_HELP),
FUSE_OPT_KEY("-V", KEY_VERSION),
FUSE_OPT_KEY("--version", KEY_VERSION),
FUSE_OPT_KEY("-l", KEY_LAYER),
FUSE_OPT_KEY("--layer", KEY_LAYER),
{NULL, 0, 0}
};
int main(int argc, char *argv[]) {
if (sizeof(void*) > sizeof(uint64_t)) {
fprintf(stderr,"%s: This program cannot be run on your system because of FUSE design limitation\n", PROGRAM);
return EXIT_FAILURE;
}
struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
struct slf_param param;
param.help = 0;
param.version = 0;
param.mount = NULL;
param.concat = malloc(sizeof(char)*MAXPATHLEN*2);
/*const apr_status_t status =*/ apr_initialize();
param.pool = svn_pool_create(NULL);
svn_dso_initialize2();
apr_pool_create(&arp_pool, NULL);
// SLIST_INIT(¶m.rev_dir_names);
SLIST_INIT(¶m.dir_names);
if (fuse_opt_parse(&args, ¶m, slf_opts, process_arg)) {
fuse_opt_free_args(&args);
return 1;
}
// if all work is done inside options parsing...
if (param.help) {
// mostly testing
while (!SLIST_EMPTY(¶m.dir_names)) {
struct dirname *n = SLIST_FIRST(¶m.dir_names);
// fprintf(stderr, "%s: %s del target !\n", PROGRAM, n->path);
SLIST_REMOVE_HEAD(¶m.dir_names, entries);
free(n);
}
fuse_opt_free_args(&args);
return 0;
}
openlog(PROGRAM, LOG_PID | LOG_PERROR, LOG_USER);
static struct fuse_operations slf_oper;
operations(&slf_oper);
char *mountpoint;
// this flag ignored because libzip does not supports multithreading
int multithreaded;
fuse = fuse_setup(args.argc, args.argv, &slf_oper, sizeof(slf_oper), &mountpoint, &multithreaded, ¶m);
// fuse_opt_free_args(&args);
if (fuse == NULL) {
return 1;
}
// Don't apply umask, use modes exactly as specified
umask(0);
se = fuse_get_session(fuse);
fuse_set_signal_handlers(se);
#ifdef SVNUPTEST
int res = update_layer(strdup("_home_digilan-token"), ¶m);
#else
int res = fuse_loop(fuse);
#endif
fuse_remove_signal_handlers(se);
fuse_teardown(fuse, mountpoint);
svn_pool_destroy (param.pool);
apr_pool_destroy (arp_pool);
apr_terminate();
return res;
}
| 2.28125 | 2 |
2024-11-18T22:29:04.625993+00:00 | 2018-12-12T17:54:32 | a7d3810d622ec352767b1dcd7e5b1f5657ba8c42 | {
"blob_id": "a7d3810d622ec352767b1dcd7e5b1f5657ba8c42",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-12T17:54:32",
"content_id": "cd837b5449f2f6f659d30c7cf1eca7cd1ad792b4",
"detected_licenses": [
"MIT"
],
"directory_id": "fafd4b8b757d6e38812fe4e9c7182bed9901435f",
"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": 161524291,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7118,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0132.json.gz:101019",
"repo_name": "MatteoNasci/Tetris_Mimic",
"revision_date": "2018-12-12T17:54:32",
"revision_id": "0bcb6b304c3b804b711d516831b4799d38d626b5",
"snapshot_id": "16ed41c1a60e2c64b1db761991f15e84f869a33f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MatteoNasci/Tetris_Mimic/0bcb6b304c3b804b711d516831b4799d38d626b5/main.c",
"visit_date": "2020-04-11T04:44:49.596560"
} | stackv2 | #include "tetris.h"
#include "gfx.h"
#define SCREEN_W 960
#define SCREEN_H 540
#define TETRIS_MAP_W 10
#define TETRIS_MAP_H 20
#define TETRIS_TIMER_MS 1000
#define TEXT_FOR_SIMPLE_TETRIS "single"
//#define USE_SINGLE_TETRAMINO
//#undef USE_SINGLE_TETRAMINO
//#ifdef USE_SINGLE_TETRAMINO
int move_down_tetramino(tetramino *const tetramino_scene, tetramino *const tetramino_preview, tetris_map *const tetris_map, color_rgba_8 *const tetramino_color, color_rgba_8 *const tetramino_preview_color, Uint32 *const last_ticks, const Uint32 *const current_ticks)
{
*last_ticks = *current_ticks;
if (tetramino_move_down(tetramino_scene, tetris_map) == TETRAMINO_STOPPED)
{
if (tetramino_scene->y == -1)
{
return 1;
}
free_filled_lines(tetris_map, tetramino_scene->y + 1, tetramino_scene->y + 1);
color_rgba_8_copy(tetramino_color, tetramino_preview_color);
set_random_color_rgba_8(tetramino_preview_color, 50, 255, 255);
tetramino_copy(tetramino_scene, tetramino_preview);
tetramino_destroy(tetramino_preview);
tetramino_init(tetramino_preview, tetris_map);
//TODO: sound effect
}
return 0;
}
//#else
int move_down_tetramini(tetramini *const tetramini_scene, tetramini *const tetramini_preview, tetris_map *const tetris_map, Uint32 *const last_ticks, const Uint32 *const current_ticks)
{
*last_ticks = *current_ticks;
if (tetramini_move_down(tetramini_scene, tetris_map) == TETRAMINO_STOPPED)
{
register int j;
int min_line = INT_MAX;
int max_line = INT_MIN;
for (j = 0; j < TETRAMINI_SIZE; j++)
{
const int line = tetramini_scene->arr_tetramini[j].y + 1;
if (line <= 0)
{
return 1;
}
if (line < min_line)
{
min_line = line;
}
if (line > max_line)
{
max_line = line;
}
}
free_filled_lines(tetris_map, min_line, max_line);
tetramini_copy(tetramini_scene, tetramini_preview);
tetramini_init(tetramini_preview, tetris_map, -1);
//TODO: sound effect
}
return 0;
}
//#endif
int main(int argc, char **argv)
{
int use_single_tetramino = 0;
while (*argv)
{
if (strcmp(TEXT_FOR_SIMPLE_TETRIS, *argv++) == 0)
{
use_single_tetramino = 1;
break;
}
}
int ret_value = 0;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO))
{
SDL_Log("Unable to initialize sdl2: %s\n", SDL_GetError());
ret_value = -1;
goto cleanup;
}
SDL_Window *window = SDL_CreateWindow("Tetris_Cazzuto", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 960, 540, 0);
if (!window)
{
SDL_Log("Unable to initialize window: %s\n", SDL_GetError());
ret_value = -1;
goto cleanup_sdl;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!renderer)
{
SDL_Log("Unable to initialize renderer: %s\n", SDL_GetError());
ret_value = -1;
goto cleanup_window;
}
const int tetramino_square_size = MIN((SCREEN_W / TETRIS_MAP_W), (SCREEN_H / TETRIS_MAP_H));
tetris_map tetris_map;
tetris_map_init(&tetris_map, TETRIS_MAP_H, TETRIS_MAP_W);
//#ifdef USE_SINGLE_TETRAMINO
tetramino tetramino_scene;
tetramino tetramino_preview;
color_rgba_8 color;
color_rgba_8 preview_color;
tetramini tetramini_scene;
tetramini tetramini_preview;
if (use_single_tetramino)
{
tetramino_init(&tetramino_scene, &tetris_map);
tetramino_init(&tetramino_preview, &tetris_map);
set_random_color_rgba_8(&color, 50, 255, 255);
set_random_color_rgba_8(&preview_color, 50, 255, 255);
}
else
{
//#else
tetramini_init(&tetramini_scene, &tetris_map, -1);
tetramini_init(&tetramini_preview, &tetris_map, -1);
}
//#endif
color_rgba_8 tetris_map_color;
set_color_rgba_8(&tetris_map_color, 0, 0, 255, 255);
SDL_Rect preview_rect;
preview_rect.x = SCREEN_W - tetramino_square_size * 3;
preview_rect.y = tetramino_square_size * 4;
preview_rect.h = tetramino_square_size;
preview_rect.w = tetramino_square_size;
Uint32 last_ticks = SDL_GetTicks();
for (;;)
{
Uint32 current_ticks = SDL_GetTicks();
SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
goto cleanup_renderer;
}
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_RIGHT)
{
//#ifdef USE_SINGLE_TETRAMINO
if (use_single_tetramino)
{
if (tetramino_move_right(&tetramino_scene, &tetris_map) == TETRAMINO_BLOCKED)
{
//TODO: sound effect
}
}
else
{
//#else
if (tetramini_move_right(&tetramini_scene, &tetris_map) == TETRAMINO_BLOCKED)
{
//TODO: sound effect
}
}
//#endif
}
if (event.key.keysym.sym == SDLK_LEFT)
{
//#ifdef USE_SINGLE_TETRAMINO
if (use_single_tetramino)
{
if (tetramino_move_left(&tetramino_scene, &tetris_map) == TETRAMINO_BLOCKED)
{
//TODO: sound effect
}
}
else
{
//#else
if (tetramini_move_left(&tetramini_scene, &tetris_map) == TETRAMINO_BLOCKED)
{
//TODO: sound effect
}
}
//#endif
}
if (event.key.keysym.sym == SDLK_DOWN)
{
//#ifdef USE_SINGLE_TETRAMINO
if (use_single_tetramino)
{
if (move_down_tetramino(&tetramino_scene, &tetramino_preview, &tetris_map, &color, &preview_color, &last_ticks, ¤t_ticks))
{
goto cleanup_renderer;
}
}
else
{
//#else
if (move_down_tetramini(&tetramini_scene, &tetramini_preview, &tetris_map, &last_ticks, ¤t_ticks))
{
goto cleanup_renderer;
}
}
//#endif
}
//#ifndef USE_SINGLE_TETRAMINO
if (!use_single_tetramino)
{
if (event.key.keysym.sym == SDLK_UP)
{
if (tetramini_rotate(&tetramini_scene, &tetris_map) != TETRAMINO_OK)
{
//TODO: BOH,
}
else
{
//TODO: maybe sound?
}
}
}
//#endif
}
}
if (current_ticks >= last_ticks + TETRIS_TIMER_MS)
{
//#ifdef USE_SINGLE_TETRAMINO
if (use_single_tetramino)
{
if (move_down_tetramino(&tetramino_scene, &tetramino_preview, &tetris_map, &color, &preview_color, &last_ticks, ¤t_ticks))
{
goto cleanup_renderer;
}
}
else
{
//#else
if (move_down_tetramini(&tetramini_scene, &tetramini_preview, &tetris_map, &last_ticks, ¤t_ticks))
{
goto cleanup_renderer;
}
}
//#endif
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
//#ifdef USE_SINGLE_TETRAMINO
if (use_single_tetramino)
{
tetramino_draw(&tetramino_scene, renderer, tetramino_square_size, &color);
_tetris_draw_internal(renderer, &preview_rect, &preview_color);
}
else
{
//#else
tetramini_draw(&tetramini_scene, renderer, tetramino_square_size);
tetramini_draw_offset(&tetramini_preview, renderer, tetramino_square_size, &preview_rect);
}
//#endif
tetris_map_draw(&tetris_map, renderer, tetramino_square_size, &tetris_map_color);
SDL_RenderPresent(renderer);
}
cleanup_renderer:
SDL_DestroyRenderer(renderer);
cleanup_window:
SDL_DestroyWindow(window);
cleanup_sdl:
SDL_Quit();
cleanup:
return ret_value;
}
| 2.046875 | 2 |
2024-11-18T22:29:04.675414+00:00 | 2019-04-17T12:04:59 | 77edb0df823984205a3b9d324542fa225d29e301 | {
"blob_id": "77edb0df823984205a3b9d324542fa225d29e301",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-17T12:05:59",
"content_id": "134605536cfcb5303ac6b824eecad444af144832",
"detected_licenses": [
"MIT"
],
"directory_id": "febd18a85df90a0b49819edb03189da55cfc7697",
"extension": "c",
"filename": "util_test.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-18T20:38:10",
"gha_event_created_at": "2019-04-15T19:40:25",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 153684555,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 984,
"license": "MIT",
"license_type": "permissive",
"path": "/util_test.c",
"provenance": "stackv2-0132.json.gz:101148",
"repo_name": "shijinglu/lure.c",
"revision_date": "2019-04-17T12:04:59",
"revision_id": "1f76fcb085302b0476d69abb9a7bba19383064ca",
"snapshot_id": "cfd3c89fb0ff6c5140b4813a504708f646ccac02",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/shijinglu/lure.c/1f76fcb085302b0476d69abb9a7bba19383064ca/util_test.c",
"visit_date": "2020-04-01T21:58:31.615477"
} | stackv2 | #include <assert.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "util.h"
void test_str_equal_ignore_case() {
assert(str_equal_ignore_case(NULL, NULL) == true);
assert(str_equal_ignore_case(NULL, "") == false);
assert(str_equal_ignore_case("", "") == true);
assert(str_equal_ignore_case("", "A") == false);
assert(str_equal_ignore_case("a", "A") == true);
assert(str_equal_ignore_case("中文", "中文") == true);
}
void test_str_concat() {
char * s = str_concat(1, "hello world");
assert(strcmp(s, "hello world") == 0);
free(s);
}
void test_str_concat_large() {
char *s = NULL;
for (int i=0; i<100000; i++) {
usleep(100);
s = str_concat(2, "hello", i % 2 == 0 ? "world" : "there, how are you");
free(s); s = NULL;
}
}
int main(int argc, char **argv) {
test_str_equal_ignore_case();
test_str_concat();
// test_str_concat_large();
}
| 2.6875 | 3 |
2024-11-18T22:29:05.803730+00:00 | 2018-12-20T00:40:51 | 3a5328f6497fcefae452cc8707d21e860fee1c7d | {
"blob_id": "3a5328f6497fcefae452cc8707d21e860fee1c7d",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-20T00:40:51",
"content_id": "0fcae586e9a9a6e76bc0e107fca169ff1316e039",
"detected_licenses": [
"Unlicense"
],
"directory_id": "5ffb8f3e17d0c57eba931d372c47b898876a8651",
"extension": "h",
"filename": "c_tlm_comp.h",
"fork_events_count": 0,
"gha_created_at": "2018-11-02T20:19:34",
"gha_event_created_at": "2018-11-02T20:57:42",
"gha_language": null,
"gha_license_id": "Unlicense",
"github_id": 155917302,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3124,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Code/L3_Utils/tlm/c_tlm_comp.h",
"provenance": "stackv2-0132.json.gz:102190",
"repo_name": "rishabh00/Catch_Me_If_You_Can",
"revision_date": "2018-12-20T00:40:51",
"revision_id": "d4e43258a895e9d9984fa3c963d0f081a582a762",
"snapshot_id": "7e0d56b9e04e41738898d3108de576b7e3e9da4c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rishabh00/Catch_Me_If_You_Can/d4e43258a895e9d9984fa3c963d0f081a582a762/Code/L3_Utils/tlm/c_tlm_comp.h",
"visit_date": "2020-04-04T12:11:23.535883"
} | stackv2 | /*
* SocialLedge.com - Copyright (C) 2013
*
* This file is part of free software framework for embedded processors.
* You can use it and/or distribute it as long as this copyright header
* remains unmodified. The code is free for personal use and requires
* permission to use in a commercial product.
*
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
* I SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
* You can reach the author of this software at :
* p r e e t . w i k i @ g m a i l . c o m
*/
#ifndef C_TLM_COMP_H__
#define C_TLM_COMP_H__
#include "c_list.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @file
*
* This file allows telemetry component registration. Memory locations or variables
* registered for telemetry are grouped by component. Once registered, the telemetry
* of these variables can be streamed to a file, network, or just stdio
*
* This file allows to register distinct components by name. Components with duplicate
* name will fail to be added to the components' list. Once a component is registered,
* then variables underneath the component can be registered: @see c_tlm_var.h
*
* Example registration of a component and a couple of variables :
* @code
* tlm_component* comp = tlm_component_add("component 1");
* int a = 0;
* char b = 0;
* tlm_variable_register(comp, "a", &a, sizeof(a)));
* TLM_REG_VAR(comp, b); // Macro to register variable b
* @endcode
*/
/**
* Structure of a telemetry component.
* Each component has a name, and a list of variables
*/
typedef struct {
const char *name; /** Name of the telemetry component */
c_list_ptr var_list; /** List of the telemetry variables of this component */
} tlm_component;
/**
* The callback type for each component @see tlm_component_for_each()
*/
typedef void (*tlm_comp_callback)(tlm_component *comp_ptr, void *arg1, void *arg2);
/**
* Adds a telemetry component by name.
* @param name The persistent data pointer to the name of the telemetry component.
* @returns tlm_component pointer if this component added successfully, but NULL
* if another component already exists with this name.
*/
tlm_component* tlm_component_add(const char *name);
/**
* Get an existing telemetry component by name
* @returns NULL pointer if the component by name was not found
*/
tlm_component* tlm_component_get_by_name(const char *name);
/**
* Calls your callback function for each telemetry component added to the
* telemetry components list by tlm_component_add().
* @param arg1 arg2 The arguments is passed to your callback like this:
* callback(tlm_component*, arg1, arg2)
*/
void tlm_component_for_each(tlm_comp_callback callback, void *arg1, void *arg2);
#ifdef __cplusplus
}
#endif
#endif /* C_TLM_COMP_H__ */
| 2.09375 | 2 |
2024-11-18T22:29:06.548951+00:00 | 2021-01-28T06:30:57 | eb83e7048fe6b9b9642488def057301370a52d18 | {
"blob_id": "eb83e7048fe6b9b9642488def057301370a52d18",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-28T06:30:57",
"content_id": "40fcdf9283954d0d6a8868757676b35794fd1ed9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "54cf4d742ed22b5ad7cee3b2bdcf5351407c374a",
"extension": "c",
"filename": "rest.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 329192685,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3652,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/rest.c",
"provenance": "stackv2-0132.json.gz:102713",
"repo_name": "ahmadsayed/hybrid-beyond-x86",
"revision_date": "2021-01-28T06:30:57",
"revision_id": "c94b7dd4d3b5bcb05bc0f9da8d8dffba8467eaf8",
"snapshot_id": "6b427a06bc6486d64075a6835cca97a35b84d8bc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ahmadsayed/hybrid-beyond-x86/c94b7dd4d3b5bcb05bc0f9da8d8dffba8467eaf8/rest.c",
"visit_date": "2023-02-27T07:26:29.905696"
} | stackv2 | /**
* rest.c
* Small Rest API that read Mysql DB
* to compile with gcc, run the following command
* sudo apt install default-libmysqlclient-dev
* sudo apt install libulfius-dev uwsc
* gcc rest.c -o rest -L/usr/lib/`uname -m`-linux-gnu/libulfius.so -lulfius `mysql_config --cflags --libs`
*/
#include <stdio.h>
#include <ulfius.h>
#include <mysql.h>
#include <string.h>
#include <unistd.h>
#define PORT 8080
void finish_with_errors(MYSQL *con, struct _u_response * response) {
/* Hello */
printf("%s\n", mysql_error(con));
mysql_close(con);
ulfius_set_string_body_response(response, 500, "DB Connection Error");
}
/**
* Callback function for the web application on /helloworld url call
*/
int callback_hello_world (const struct _u_request * request, struct _u_response * response, void * user_data) {
MYSQL *con = mysql_init(NULL);
if(con == NULL) {
printf("%s\n", mysql_error(con));
ulfius_set_string_body_response(response, 500, "DB Connection Error");
return U_CALLBACK_CONTINUE;
}
if (mysql_real_connect(con, "mysql-svc", "ahmed", "Abc2020$Abc2020$", "14in4", 0, NULL, 0) == NULL) {
printf("%s\n", mysql_error(con));
mysql_close(con);
ulfius_set_string_body_response(response, 500, "DB Connection Error");
return U_CALLBACK_CONTINUE;
}
if (mysql_query(con, "SELECT offering_id, L30_, Offering_Portfolio, Theme FROM offering")) {
finish_with_errors(con, response);
return U_CALLBACK_CONTINUE;
}
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL) {
finish_with_errors(con, response);
return U_CALLBACK_CONTINUE;
}
int num_fields = mysql_num_fields(result);
char *headers[num_fields];
MYSQL_FIELD *field;
unsigned int name_field;
char *field_name = "name";
for(unsigned int i = 0; (field = mysql_fetch_field(result)); i++) {
headers[i] = field->name;
if (strcmp(field_name, headers[i]) == 0) {
name_field = i;
}
}
MYSQL_ROW row;
int row_count = 0;
char buffer[999999];
buffer[0] = '\0';
strcat(buffer,"[");
while((row = mysql_fetch_row(result))) {
if (row_count !=0) {
strcat(buffer,",");
}
row_count++;
strcat(buffer, "{");
char row_buff[255];
sprintf(row_buff, "\"%s\":\"%s\"", headers[0], row[0] ? row[0] : "NULL");
strcat(buffer, row_buff);
for (int i=1; i < num_fields; i++) {
char rows_buff[255];
sprintf(rows_buff, ",\"%s\":\"%s\"", headers[i],row[i] ? row[i] : "NULL");
strcat(buffer, rows_buff);
}
strcat(buffer, "}\n");
}
strcat(buffer,"]");
mysql_free_result(result);
ulfius_set_string_body_response(response, 200, buffer);
mysql_close(con);
return U_CALLBACK_CONTINUE;
}
/**
* main function
*/
int main(void) {
struct _u_instance instance;
// Initialize instance with the port number
if (ulfius_init_instance(&instance, PORT, NULL, NULL) != U_OK) {
fprintf(stderr, "Error ulfius_init_instance, abort\n");
return(1);
}
// Endpoint list declaration
ulfius_add_endpoint_by_val(&instance, "GET", "/offering", NULL, 0, &callback_hello_world, NULL);
// Start the framework
if (ulfius_start_framework(&instance) == U_OK) {
printf("Start framework on port %d\n", instance.port);
// Wait for the user to press <enter> on the console to quit the application
while (1) sleep(1);
} else {
fprintf(stderr, "Error starting framework\n");
}
printf("End framework\n");
ulfius_stop_framework(&instance);
ulfius_clean_instance(&instance);
return 0;
}
| 2.375 | 2 |
2024-11-18T22:29:06.893372+00:00 | 2020-07-11T00:47:18 | b45a1f2e152ab16a5864a31c4a83fdaf13e26e2d | {
"blob_id": "b45a1f2e152ab16a5864a31c4a83fdaf13e26e2d",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-11T00:47:18",
"content_id": "87639c12e005a3cba32625e5b82bf79d629f46a3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6a237621c06c52d3f93df0cd8306d5e5600df017",
"extension": "c",
"filename": "sort.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146354542,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1299,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ECE264/HW02/sort.c",
"provenance": "stackv2-0132.json.gz:103101",
"repo_name": "cmz97/Purdue-ECE-Programming-Assignment-Archive",
"revision_date": "2020-07-11T00:47:18",
"revision_id": "4f54ff3db69e7d46e989af268c55fbeb2007576f",
"snapshot_id": "3b6eca22b0dd67709b643d9f81fe19dcb6f6c30f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cmz97/Purdue-ECE-Programming-Assignment-Archive/4f54ff3db69e7d46e989af268c55fbeb2007576f/ECE264/HW02/sort.c",
"visit_date": "2022-11-13T01:21:45.382003"
} | stackv2 | // ***
// *** You MUST modify this file, only the ssort function
// ***
#include "sort.h"
#include <stdio.h>
#include <stdbool.h>
static bool checkOrder(int * arr, int size)
// a static function is visible only in this file
// This function returns true if the array elements are
// in the ascending order.
// false, otherwise
{
int ind;
for (ind = 0; ind < (size - 1); ind ++)
{
if (arr[ind] > arr[ind + 1])
{
return false;
}
}
return true;
}
#ifdef TEST_SORT
void ssort(int * arr, int size)
{
int currentIndex;
int sortedIndex;
int minNum = 0;
int minIndex = 0;
int temp = 0;
int found = 0;
for(sortedIndex = 0; sortedIndex < size - 1 ; sortedIndex++){
minNum = arr[sortedIndex];
for(currentIndex = sortedIndex; currentIndex < size; currentIndex++){
if(arr[currentIndex] < minNum){
minNum = arr[currentIndex];
minIndex = currentIndex;
found = 1;
}
}
if(found){
temp = arr[sortedIndex];
arr[sortedIndex] = minNum;
arr[minIndex] = temp;
}
found = 0;
}
if (checkOrder(arr, size) == false)
{
fprintf(stderr, "checkOrder returns false\n");
}
}
#endif
| 3.375 | 3 |
2024-11-18T22:29:07.707725+00:00 | 2016-10-19T01:53:08 | 523998b79a96f208e76f9adfb3d4caf018952801 | {
"blob_id": "523998b79a96f208e76f9adfb3d4caf018952801",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-19T01:53:08",
"content_id": "0aa6eafd80464b751200fc17ec9050224a9a62af",
"detected_licenses": [
"MIT"
],
"directory_id": "5bbdb0b719a13eee8eb1f092aefcfe1dcd10250d",
"extension": "c",
"filename": "treemap.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 56163112,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4956,
"license": "MIT",
"license_type": "permissive",
"path": "/serie6/prog_modulaire/treemap.c",
"provenance": "stackv2-0132.json.gz:103360",
"repo_name": "ppepos/inf3135-demo",
"revision_date": "2016-10-19T01:53:08",
"revision_id": "91533fec77ba069351d0547a342c2209eae4849f",
"snapshot_id": "ac13a02126430ede25966679940a07e6e247dfb6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ppepos/inf3135-demo/91533fec77ba069351d0547a342c2209eae4849f/serie6/prog_modulaire/treemap.c",
"visit_date": "2020-12-23T11:35:27.995309"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "treemap.h"
/**
* Cree et retourne une table associative vide.
*
* @returns La table associative
*/
TreeMap treemapCreate() {
TreeMap t = {NULL};
return t;
}
/**
* Retourne la valeur associee a la cle donnee.
*
* @param t La table associative
* @param key La cle
* @returns La valeur associee
*/
char *treemapGet(const TreeMap *t, char *key) {
struct TreeNode *node = treemapGetNode(t, key);
if (node == NULL)
return NULL;
else
return node->value;
}
/**
* Ajoute ou remplace la paire (key, value).
*
* Note : si la cle est deja presente dans la table, alors
* la valeur associee est ecrasee avec la nouvelle valeur.
*
* @param t La table associative
* @param key La cle
* @param value La valeur
*/
void treemapSet(TreeMap *t, char *key, char *value) {
struct TreeNode *node = treemapGetNode(t, key);
if (node != NULL) {
node->value = strdup(value);
} else {
treemapInsertNode(&(t->root), key, value);
}
}
/**
* Insere un noeud dans l'arbre representant une table associative.
*
* Note : cette fonction devrait etre privee (lorsqu'on verra les
* modules, elle ne doit pas etre dans l'interface).
*
* @param node Le noeud courant
* @param key La cle a inserer
* @param value La valeur associee
*/
void treemapInsertNode(struct TreeNode **node, char *key, char *value) {
if (*node == NULL) {
*node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
(*node)->key = strdup(key);
(*node)->value = strdup(value);
(*node)->left = NULL;
(*node)->right = NULL;
} else if (strcmp(key, (*node)->key) < 0) {
treemapInsertNode(&(*node)->left, key, value);
} else {
treemapInsertNode(&(*node)->right, key, value);
}
}
/**
* Retourne vrai si et seulement si la cle apparaît dans la table.
*
* @param t La table associative
* @param key La cle a rechercher
* @returns Vrai si et seulement si la cle est presente
*/
bool treemapHasKey(const TreeMap *t, char *key) {
return treemapGetNode(t, key) != NULL;
}
/**
* Retourne le noeud correspondant a une cle donnee.
*
* Si la cle n'y est pas, alors la valeur NULL est retournee.
*
* @param t La table associative
* @param key La cle recherchee
* @returns Le noeud associee a la cle ou NULL
*/
struct TreeNode *treemapGetNode(const TreeMap *t, char *key) {
struct TreeNode *node = t->root;
while (node != NULL) {
int cmp = strcmp(key, node->key);
if (cmp == 0)
return node;
else if (cmp < 0)
node = node->left;
else
node = node->right;
}
return NULL;
}
/**
* Affiche une table associative sur la sortie standard.
*
* @param t La table associative a afficher
*/
void treemapPrint(const TreeMap *t) {
printf("TreeMap {\n");
treemapPrintRecursive(t->root);
printf("}\n");
}
/**
* Affiche en ordre infixe les paires (key, value) presentes
* dans l'arbre.
*
* Note : cette fonction devrait etre privee (lorsqu'on verra les
* modules, elle ne doit pas etre dans l'interface).
*/
void treemapPrintRecursive(const struct TreeNode *node) {
if (node != NULL) {
treemapPrintRecursive(node->left);
printf(" %s: %s\n", node->key, node->value);
treemapPrintRecursive(node->right);
}
}
/**
* Libere l'espace memoire utilise par une table associative.
*
* @param t La table a supprimer
*/
void treemapDelete(TreeMap *t) {
treemapDeleteRecursive(t->root);
}
/**
* Libere recursivement l'espace memoire utilise par les noeuds
* de l'arbre representant une table associative.
*
* @param node Le noeud courant
*
* Note : cette fonction devrait etre privee (lorsqu'on verra les
* modules, elle ne doit pas etre dans l'interface).
*/
void treemapDeleteRecursive(struct TreeNode *node) {
if (node != NULL) {
treemapDeleteRecursive(node->left);
treemapDeleteRecursive(node->right);
free(node);
}
}
// int main() {
// TreeMap t = treemapCreate();
// treemapSet(&t, "prenom", "alice");
// treemapSet(&t, "nom", "tremblay");
// treemapSet(&t, "sexe", "feminin");
// treemapSet(&t, "ville", "montreal");
// treemapSet(&t, "province", "quebec");
// treemapSet(&t, "pays", "canada");
// treemapSet(&t, "age", "25");
// printf("Printing the tree map\n");
// treemapPrint(&t);
// printf("Get \"prenom\": %s\n", treemapGet(&t, "prenom"));
// printf("Get \"province\": %s\n", treemapGet(&t, "province"));
// printf("Get \"age\": %s\n", treemapGet(&t, "age"));
// printf("Changing age to 21\n");
// treemapSet(&t, "age", "21");
// printf("Get \"age\": %s\n", treemapGet(&t, "age"));
// printf("Printing the tree map\n");
// treemapPrint(&t);
// treemapDelete(&t);
// }
| 3.5625 | 4 |
2024-11-18T22:29:07.767092+00:00 | 2017-06-08T13:20:31 | d23c62b79a53aa73e7d1a9e3f13524aeef5bca53 | {
"blob_id": "d23c62b79a53aa73e7d1a9e3f13524aeef5bca53",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-08T13:20:31",
"content_id": "0d50a3605de34e8e87eded083e64f9c4cb3a2777",
"detected_licenses": [
"MIT"
],
"directory_id": "3f9b4126045b66a46737ee6039355106246ed83c",
"extension": "c",
"filename": "reset_handler.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60821942,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1351,
"license": "MIT",
"license_type": "permissive",
"path": "/reset_handler.c",
"provenance": "stackv2-0132.json.gz:103490",
"repo_name": "xobs/joyboot",
"revision_date": "2017-06-08T13:20:31",
"revision_id": "ab80271fa494750363b38a3d4d7035b71e434aa4",
"snapshot_id": "7e914ab71d40b0f2698010a72b2b2b5d7b044eef",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/xobs/joyboot/ab80271fa494750363b38a3d4d7035b71e434aa4/reset_handler.c",
"visit_date": "2020-05-22T08:14:25.849703"
} | stackv2 | #include <stdint.h>
#include "kl17.h"
/* Values exported by the linker */
extern uint32_t _eflash;
extern uint32_t _sdtext;
extern uint32_t _edtext;
extern uint32_t _sbss;
extern uint32_t _ebss;
extern uint32_t __main_stack_end__;
/* Pointer to the Cortex vector table (located at offset 0) */
extern uint32_t *_vectors;
/* A place for the vector table to live while in RAM */
static uint32_t ram_vectors[64] __attribute__ ((aligned (1024)));
__attribute__ ((section(".startup")))
void memcpy32(uint32_t *src, uint32_t *dest, uint32_t count) {
count /= sizeof(*src);
while (count--)
*dest++ = *src++;
}
__attribute__ ((section(".startup")))
static void init_crt(void) {
/* Relocate data and text sections to RAM */
memcpy32(&_eflash, &_sdtext, (uint32_t)&_edtext - (uint32_t)&_sdtext);
/* Clear BSS */
uint32_t *dest = &_sbss;
while (dest < &_ebss) *dest++ = 0;
/* Copy IVT to RAM */
uint32_t *src = (uint32_t *) &_vectors;
dest = &ram_vectors[0];
while (dest <= &ram_vectors[63])
*dest++ = *src++;
/* Switch to IVT now located in RAM */
SCB->VTOR = (uint32_t) &ram_vectors[0];
}
extern void __early_init(void);
__attribute__ ((noreturn))
extern void bootloader_main(void);
__attribute__ ((section(".startup"), noreturn))
void Reset_Handler(void) {
init_crt();
__early_init();
bootloader_main();
}
| 2.34375 | 2 |
2024-11-18T22:29:07.955854+00:00 | 2020-04-27T11:31:27 | 435f72c46a4afec11858bbe6e8e3b454f67ecd7c | {
"blob_id": "435f72c46a4afec11858bbe6e8e3b454f67ecd7c",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-27T11:31:27",
"content_id": "999e2915d34e10512e58e6878c8e783fc3a5e8ff",
"detected_licenses": [
"MIT"
],
"directory_id": "4a7ec58caac0a99e2aae16f1b8a2b1fbb3550258",
"extension": "c",
"filename": "MESSAGE.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 259293657,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1840,
"license": "MIT",
"license_type": "permissive",
"path": "/OS/MultiProcessing/MESSAGE.c",
"provenance": "stackv2-0132.json.gz:103746",
"repo_name": "jihoon15/my-work",
"revision_date": "2020-04-27T11:31:27",
"revision_id": "7d5ef2ab7515fb172cd499d98f164c6889d01409",
"snapshot_id": "5f578ac908a4356d1c39096d98289b34789833f7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jihoon15/my-work/7d5ef2ab7515fb172cd499d98f164c6889d01409/OS/MultiProcessing/MESSAGE.c",
"visit_date": "2022-04-21T21:45:49.025916"
} | stackv2 | #include <stdio.h>//
#include <stdlib.h>//
#include <sys/types.h>//
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>//
#include <sys/time.h>//
#include <signal.h>//
#include <string.h>//
#include "msg.h"
void enqueue();
void dequeue();
int msgq;
int ret;
#define key 0x03215
struct msgbuf msg;
int main(){
msgq=msgget(key, IPC_CREAT | 0666);
//int형으로 메시지큐생성하면서 아이디를 변수에 저장하는듯
//0666말고 바꿔봤는데 오류남 찾아보니 자세히는 알수없고 key다음이 msgflag인데자세한사용법알기어렵고 불필요
memset(&msg, 0, sizeof(msg));
int pid = fork();
if(pid < 0){
//error
perror("fork");
}
if(pid == 0){
//child
enqueue();
printf("!!!!!!MESSAGE!!!!!!!!!!!!\n");
exit(0);
}
else{
//parent
dequeue();
// pcbs[i].completed = 0;//**
}
return 0;
}
void enqueue()
{
//printf("msgq id: %d\n", msgq);
//___________________________________
msg.mtype = 0;
msg.pid = getpid();
//넣어줄데이터 설정함
ret = msgsnd(msgq, &msg, sizeof(msg), NULL);
//메시지 보냄(msgq id, size, msgflag)//flag 0: 큐에공간생기는거 긷자림//큐에공간없을시 복귀하는것도 있음
//이것도 마지막이
printf("msgsnd ret: %d\n", ret);
//성공여부 확인하는듯
return;
}
void dequeue()
{
//printf("msgq id: %d\n", msgq);
ret = msgrcv(msgq, &msg, sizeof(msg), 0, NULL);
printf("!!msgsnd ret: %d\n", ret);
printf("msg.mtype: %d\n", msg.mtype);
printf("msg.pid: %d\n", msg.pid);
return;
}
| 2.609375 | 3 |
2024-11-18T22:29:08.077740+00:00 | 2022-09-15T17:24:52 | 8d5930f6d059551237a2afd1748c710ea28979b7 | {
"blob_id": "8d5930f6d059551237a2afd1748c710ea28979b7",
"branch_name": "refs/heads/master",
"committer_date": "2022-09-19T13:49:25",
"content_id": "0c8befc3442a91041350d9d9d241741f1b61968b",
"detected_licenses": [
"MIT"
],
"directory_id": "cd72ac40d88d6b843d673f3a1f46ad2f11b9025b",
"extension": "c",
"filename": "libze_plugin_systemdboot.c",
"fork_events_count": 1,
"gha_created_at": "2020-06-02T11:29:56",
"gha_event_created_at": "2023-09-13T16:23:39",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 268782749,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 59449,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/libze_plugin/libze_plugin_systemdboot.c",
"provenance": "stackv2-0132.json.gz:103876",
"repo_name": "truenas/zectl",
"revision_date": "2022-09-15T17:24:52",
"revision_id": "f08b1db1cbf36ccefb9b7a793964447216cb3c08",
"snapshot_id": "023e4359cb7288e5e8049a097930d17bc278b1f1",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/truenas/zectl/f08b1db1cbf36ccefb9b7a793964447216cb3c08/lib/libze_plugin/libze_plugin_systemdboot.c",
"visit_date": "2023-08-21T15:34:38.055800"
} | stackv2 | #include "libze_plugin/libze_plugin_systemdboot.h"
#include "libze/libze.h"
#include "libze/libze_util.h"
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define REGEX_BUFLEN 512
#define SYSTEMDBOOT_ENTRY_PREFIX "org.zectl"
#define NUM_SYSTEMDBOOT_PROPERTY_VALUES 2
#define NUM_SYSTEMDBOOT_PROPERTIES 3
/**
* @brief list of systemdboot plugin properties
*/
char const *systemdboot_properties[NUM_SYSTEMDBOOT_PROPERTIES][NUM_SYSTEMDBOOT_PROPERTY_VALUES] = {
{"efi", "/efi"}, {"boot", "/boot"}, {"kernelsnapshotdirectory", "/zectl/systemdboot"}};
/**
* @struct replace_matched_data
* @brief Struct for replace_matched data passed with callback get_cfg_line_from_regex
*/
struct replace_cfg_data {
char const *be_name;
char const *active_be;
};
/**
* @struct replace_matched_data
* @brief Struct for replace_matched data passed with callback get_fstab_line_from_regex
*/
struct replace_fstab_data {
char const *be_name;
char const *active_be;
char const *boot_mountpoint;
char const *efi_mountpoint;
};
/**
* @struct replace_loader_data
* @brief Struct for replace_matched data passed with callback get_loader_line_from_regex
*/
struct replace_loader_data {
char const *be_name;
};
/********************************************************************
************************** Miscellaneous ***************************
********************************************************************/
/**
* @brief Callback function for replace_matched
*/
typedef libze_error (*line_replace_fn)(libze_handle *lzeh, void *data,
char const line_buf[LIBZE_MAX_PATH_LEN],
char replace_line_buf[LIBZE_MAX_PATH_LEN]);
/**
* @brief Check if a file is read-write accessible
*
* @param[in,out] lzeh libze handle
* @param[in] filename File checked for r/w
*
* @return @p LIBZE_ERROR_SUCCESS if file accessible,
* @p LIBZE_ERROR_EPERM if file is not in read/write mode,
* @p LIBZE_ERROR_MAXPATHLEN if file exceeds max path length,
* @p LIBZE_ERROR_UNKNOWN for other access errors
*/
static libze_error
file_accessible(libze_handle *lzeh, char const filename[LIBZE_MAX_PATH_LEN]) {
/* Check if filename is r/w */
errno = 0;
if (access(filename, R_OK | W_OK) != 0) {
switch (errno) {
case EACCES:
return libze_error_set(lzeh, LIBZE_ERROR_EPERM,
"File is not in read/write mode (%s).\n", filename);
case ENAMETOOLONG:
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"File exceeds max path length (%s).\n", filename);
default:
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"File could not be accessed (%s).\n", filename);
}
}
return LIBZE_ERROR_SUCCESS;
}
/**
* @brief Loop over each line of a file replacing each line according to a regular expression.
* The file at @p filename_new will be erased upon opening.
*
* @param lzeh libze handle
* @param be_name New boot environment
* @param be_name_active Active boot environment
* @param filename Old configuration file
* @param new_filename New configuration file
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN on buffer length being exceeded
*/
static libze_error
replace_matched(libze_handle *lzeh, char const filename[LIBZE_MAX_PATH_LEN],
char const filename_new[LIBZE_MAX_PATH_LEN], line_replace_fn replace_fn,
void *data) {
libze_error ret = LIBZE_ERROR_SUCCESS;
char *open_err = "Failed to open %s.\n";
FILE *file_new = fopen(filename_new, "w+");
if (file_new == NULL) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, open_err, file_new);
}
FILE *file = fopen(filename, "r");
if (file == NULL) {
fclose(file_new);
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, open_err, filename);
}
char line_buf[LIBZE_MAX_PATH_LEN];
char replace_line_buf[LIBZE_MAX_PATH_LEN] = "";
while (fgets(line_buf, LIBZE_MAX_PATH_LEN, file)) {
/* Get the new line to be written out according to a regular expression
If there's no match, original line will be in replace_line_buf */
ret = replace_fn(lzeh, data, line_buf, replace_line_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
goto err;
}
fwrite(replace_line_buf, 1, strlen(replace_line_buf), file_new);
}
fflush(file_new);
err:
fclose(file);
fclose(file_new);
return LIBZE_ERROR_SUCCESS;
}
/********************************************************************
********************** Plugin initialization ***********************
********************************************************************/
/**
* @brief Add the systemd-boot default properties to nvlist
*
* @param[in,out] lzeh libze handle
* @param[out] default_properties Populated default properties, alllocated internally.
* NULL if allocation fails
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if plugin namespace buffer exceeded,
* @p LIBZE_ERROR_NOMEM if nvlist allocation fails
*/
libze_error
libze_plugin_systemdboot_defaults(libze_handle *lzeh, nvlist_t **default_properties) {
libze_error ret = LIBZE_ERROR_SUCCESS;
nvlist_t *properties = NULL;
properties = fnvlist_alloc();
if (properties == NULL) {
return libze_error_nomem(lzeh);
}
char namespace_buf[ZFS_MAXPROPLEN];
if (libze_plugin_form_namespace(PLUGIN_SYSTEMDBOOT, namespace_buf) != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Exceeded max property name length.\n");
goto err;
}
/* Add all default properties to nvlist */
for (int i = 0; i < NUM_SYSTEMDBOOT_PROPERTIES; i++) {
if (libze_default_prop_add(&properties, systemdboot_properties[i][0],
systemdboot_properties[i][1], namespace_buf) != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Failed to add %s property to systemdboot nvlist.\n",
systemdboot_properties[i][0]);
goto err;
}
}
*default_properties = properties;
return ret;
err:
(void) libze_list_free(properties);
return ret;
}
/**
* @brief Add default properties to libze handle
*
* @param[in,out] lzeh libze handle
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_NOMEM if an nvlist couldn't be duplicated
* @p LIBZE_ERROR_UNKNOWN if an nvlist value couldn't be accessed,
* @p LIBZE_ERROR_UNKNOWN if an nvlist couldn't be added to @p lzeh->ze_props
*/
static libze_error
add_default_properties(libze_handle *lzeh) {
libze_error ret = LIBZE_ERROR_SUCCESS;
nvlist_t *defaults_nvl = NULL;
if ((ret = libze_plugin_systemdboot_defaults(lzeh, &defaults_nvl)) != LIBZE_ERROR_SUCCESS) {
return ret;
}
/* Add defaults */
nvpair_t *default_pair = NULL;
for (default_pair = nvlist_next_nvpair(defaults_nvl, NULL); default_pair != NULL;
default_pair = nvlist_next_nvpair(defaults_nvl, default_pair)) {
char const *default_nvp_name = nvpair_name(default_pair);
/* If nvlist already in properties, don't add default */
if (nvlist_exists(lzeh->ze_props, default_nvp_name)) {
continue;
}
nvlist_t *nvl = NULL;
if (nvpair_value_nvlist(default_pair, &nvl) != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to access nvlist %s.\n",
default_nvp_name);
goto err;
}
nvlist_t *nvl_copy = NULL;
if (nvlist_dup(nvl, &nvl_copy, 0) != 0) {
ret = libze_error_nomem(lzeh);
goto err;
}
if (nvlist_add_nvlist(lzeh->ze_props, default_nvp_name, nvl_copy) != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed adding default property %s.\n",
default_nvp_name);
goto err;
}
}
err:
if (defaults_nvl != NULL) {
(void) libze_list_free(defaults_nvl);
}
return ret;
}
/**
* @brief Initialize the systemdboot plugin
*
* @param[in,out] lzeh libze handle
*
* @pre lzeh->ze_props is allocated
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_NOMEM if an nvlist couldn't be duplicated
* @p LIBZE_ERROR_UNKNOWN if an nvlist value couldn't be accessed,
* @p LIBZE_ERROR_UNKNOWN if an nvlist couldn't be added to @p lzeh->ze_props
*/
libze_error
libze_plugin_systemdboot_init(libze_handle *lzeh) {
libze_error ret = LIBZE_ERROR_SUCCESS;
if ((ret = add_default_properties(lzeh)) != LIBZE_ERROR_SUCCESS) {
return ret;
}
return ret;
}
/********************************************************************
************************** Pre-activate ****************************
********************************************************************/
/**
* @brief Pre-activate hook for plugin
* @param[in] lzeh
* @return @p LIBZE_ERROR_SUCCESS
*/
libze_error
libze_plugin_systemdboot_pre_activate(libze_handle *lzeh) {
return LIBZE_ERROR_SUCCESS;
}
/********************************************************************
************************** Mid-activate ****************************
********************************************************************/
/**
* @brief Setup the regex for fstab matching.
*
* @param[in,out] re Compiled regular expression buffer
* @param[in] boot_mountpoint Mountpoint of boot partition
* @param[in] efi_mountpoint Mountpoint EFI partition
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN exceeded,
* @p LIBZE_ERROR_UNKNOWN if regex failed to compile,
* @p LIBZE_ERROR_NOMEM on failed allocation
*/
static libze_error
form_fstab_regex(regex_t *re, char const boot_mountpoint[LIBZE_MAX_PATH_LEN],
char const efi_mountpoint[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
char ns_no_dots[ZFS_MAX_DATASET_NAME_LEN];
char efi_no_dots[ZFS_MAX_DATASET_NAME_LEN];
char boot_no_dots[ZFS_MAX_DATASET_NAME_LEN];
/* Replace any '.' characters with '\.' for regular expression */
ret = libze_util_replace_string(".", "\\.", ZFS_MAX_DATASET_NAME_LEN, ZE_PROP_NAMESPACE,
ZFS_MAX_DATASET_NAME_LEN, ns_no_dots);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
ret = libze_util_replace_string(".", "\\.", ZFS_MAX_DATASET_NAME_LEN, efi_mountpoint,
ZFS_MAX_DATASET_NAME_LEN, efi_no_dots);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
ret = libze_util_replace_string(".", "\\.", ZFS_MAX_DATASET_NAME_LEN, boot_mountpoint,
ZFS_MAX_DATASET_NAME_LEN, boot_no_dots);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
char reg_buf[REGEX_BUFLEN];
int intret = snprintf(reg_buf, REGEX_BUFLEN, "\\(^[\t ]*%s/env/%s-\\)\\(.*\\)\\([\t ]*%s.*$\\)",
efi_no_dots, ns_no_dots, boot_no_dots);
if (intret >= REGEX_BUFLEN) {
return LIBZE_ERROR_MAXPATHLEN;
}
if (regcomp(re, reg_buf, 0) != 0) {
return LIBZE_ERROR_UNKNOWN;
}
return LIBZE_ERROR_SUCCESS;
}
/**
* @brief Setup the regex for title matching in bootloader configuration.
*
* @param[in,out] re Compiled regular expression buffer
* @param[in] be_name Name of boot environment to match in title
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_UNKNOWN if regex failed to compile,
*/
static libze_error
form_title_regex(regex_t *re, char const be_name[ZFS_MAX_DATASET_NAME_LEN]) {
char reg_buf[REGEX_BUFLEN];
libze_error ret = LIBZE_ERROR_SUCCESS;
ret = libze_util_concat("\\(title.*\\)\\(", be_name, "\\)\\(.*\\)", REGEX_BUFLEN, reg_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
if (regcomp(re, reg_buf, 0) != 0) {
return LIBZE_ERROR_UNKNOWN;
}
return ret;
}
/**
* @brief Setup the regex for linux and initrd matching in bootloader configuration.
*
* @param[in,out] re Compiled regular expression buffer
* @param[in] be_name Name of boot environment to match in title
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN exceeded,
* @p LIBZE_ERROR_UNKNOWN if regex failed to compile,
* @p LIBZE_ERROR_NOMEM on failed allocation
*/
static libze_error
form_linux_regex(regex_t *re, char const be_name[ZFS_MAX_DATASET_NAME_LEN]) {
char reg_buf[REGEX_BUFLEN];
char be_no_dots[ZFS_MAX_DATASET_NAME_LEN] = "";
char ns_no_dots[ZFS_MAX_DATASET_NAME_LEN] = "";
libze_error ret = LIBZE_ERROR_SUCCESS;
int iret = 0;
/* Replace any '.' characters with '\.' for regular expression */
ret = libze_util_replace_string(".", "\\.", ZFS_MAX_DATASET_NAME_LEN, be_name,
ZFS_MAX_DATASET_NAME_LEN, be_no_dots);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
ret = libze_util_replace_string(".", "\\.", ZFS_MAX_DATASET_NAME_LEN, ZE_PROP_NAMESPACE,
ZFS_MAX_DATASET_NAME_LEN, ns_no_dots);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
iret = snprintf(reg_buf, REGEX_BUFLEN, "\\(linux\\|initrd\\)\\(.*\\)\\(%s-\\)\\(%s\\)\\(/.*\\)",
ns_no_dots, be_no_dots);
if (iret >= REGEX_BUFLEN) {
return LIBZE_ERROR_MAXPATHLEN;
}
if (regcomp(re, reg_buf, 0) != 0) {
return LIBZE_ERROR_UNKNOWN;
}
return LIBZE_ERROR_SUCCESS;
}
/**
* @brief Setup the regex for dataset matching in bootloader configuration on options line.
*
* @param[in,out] re Compiled regular expression buffer
* @param[in] be_root Name of boot environment root
* @param[in] be_name Name of boot environment to match in dataset
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN exceeded,
* @p LIBZE_ERROR_UNKNOWN if regex failed to compile,
* @p LIBZE_ERROR_NOMEM on failed allocation
*/
static libze_error
form_dataset_regex(regex_t *re, char const be_root[LIBZE_MAX_PATH_LEN],
char const be_name[ZFS_MAX_DATASET_NAME_LEN]) {
char reg_buf[REGEX_BUFLEN];
char be_no_dots[ZFS_MAX_DATASET_NAME_LEN] = "";
char be_root_no_dots[ZFS_MAX_DATASET_NAME_LEN] = "";
libze_error ret = LIBZE_ERROR_SUCCESS;
int iret = 0;
/* Replace any '.' characters with '\.' for regular expression */
ret = libze_util_replace_string(".", "\\.", ZFS_MAX_DATASET_NAME_LEN, be_name,
ZFS_MAX_DATASET_NAME_LEN, be_no_dots);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
ret = libze_util_replace_string(".", "\\.", ZFS_MAX_DATASET_NAME_LEN, be_root,
ZFS_MAX_DATASET_NAME_LEN, be_root_no_dots);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
iret = snprintf(reg_buf, REGEX_BUFLEN, "\\(options.*zfs=%s/\\)\\(%s\\)\\(.*\\)",
be_root_no_dots, be_no_dots);
if (iret >= REGEX_BUFLEN) {
return LIBZE_ERROR_MAXPATHLEN;
}
if (regcomp(re, reg_buf, 0) != 0) {
return LIBZE_ERROR_UNKNOWN;
}
return LIBZE_ERROR_SUCCESS;
}
/**
* @brief Callback for replace_matched function to retrieve correct line to be written out to fstab.
*
* @param[in,out] lzeh libze handle
* @param[in] data Data passed into callback from replace_matched function
* @param[in] line Input line to replace.
* @param[out] replace_line_buf Replacement line
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p regex buffer exceeded,
* @p LIBZE_ERROR_UNKNOWN if replacing subexpression fails
* @p LIBZE_ERROR_NOMEM on failed allocation
*/
static libze_error
get_fstab_line_from_regex(libze_handle *lzeh, void *data, char const line[LIBZE_MAX_PATH_LEN],
char replace_line_buf[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
struct replace_fstab_data *rmd = data;
regmatch_t pmatch;
regex_t re_boot_buf;
regex_t *re_boot_p = NULL;
ret = form_fstab_regex(&re_boot_buf, rmd->boot_mountpoint, rmd->efi_mountpoint);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, "Failed to match fstab regex.\n");
goto done;
}
re_boot_p = &re_boot_buf;
char replace_two[LIBZE_MAX_PATH_LEN] = "";
ret = libze_util_concat("\\1", rmd->be_name, " \\3", LIBZE_MAX_PATH_LEN, replace_two);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max path length for regex buffer.\n");
goto done;
}
if (regexec(re_boot_p, line, 0, &pmatch, 0) == 0) {
ret = libze_util_regex_subexpr_replace(re_boot_p, LIBZE_MAX_PATH_LEN, replace_two,
LIBZE_MAX_PATH_LEN, line, LIBZE_MAX_PATH_LEN,
replace_line_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, "Exceeded max path length for regex buffer.\n");
}
goto done;
}
if (strlcpy(replace_line_buf, line, LIBZE_MAX_PATH_LEN) >= LIBZE_MAX_PATH_LEN) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max path length for line buffer.\n");
}
done:
if (re_boot_p != NULL) {
regfree(re_boot_p);
}
return ret;
}
/**
* @brief Using boot mountpoint update fstab
*
* @param lzeh libze handle
* @param create_data Create data
* @param boot_mountpoint Mountpoint of boot partition
* @param efi_mountpoint EFI mountpoint
*
* @return @p LIBZE_ERROR_UNKNOWN Boot mountpoint is not set
* @p LIBZE_ERROR_MAXPATHLEN Max path length exceeded
* @p LIBZE_ERROR_SUCCESS On success
*/
static libze_error
update_fstab(libze_handle *lzeh, libze_create_data *create_data,
char const boot_mountpoint[LIBZE_MAX_PATH_LEN],
char const efi_mountpoint[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
int interr = 0;
char active_be[ZFS_MAX_DATASET_NAME_LEN];
if (libze_boot_env_name(lzeh->env_activated_path, ZFS_MAX_DATASET_NAME_LEN, active_be) != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Bootfs exceeds max path length.\n");
}
/* Get path to fstab */
char fstab_buf[LIBZE_MAX_PATH_LEN] = "";
if ((strlcpy(fstab_buf, create_data->be_mountpoint, LIBZE_MAX_PATH_LEN) >=
LIBZE_MAX_PATH_LEN) ||
(strlcat(fstab_buf, "/etc/fstab", LIBZE_MAX_PATH_LEN) >= LIBZE_MAX_PATH_LEN)) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"fstab exceeds max path length (%s).\n", LIBZE_MAX_PATH_LEN);
}
if ((ret = file_accessible(lzeh, fstab_buf)) != LIBZE_ERROR_SUCCESS) {
return ret;
}
char new_filename[LIBZE_MAX_PATH_LEN];
int err = libze_util_concat(fstab_buf, ".", "bak", LIBZE_MAX_PATH_LEN, new_filename);
if (err != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Backup fstab exceeds max path length.\n");
}
/* backup unit */
if ((ret = libze_util_copy_file(fstab_buf, new_filename)) != 0) {
return ret;
}
/* Create a tempfile to manipulate before replacing original */
char tmpfile[LIBZE_MAX_PATH_LEN];
interr = libze_util_concat(fstab_buf, ".", "zectl-sdboot.XXXXXX", LIBZE_MAX_PATH_LEN, tmpfile);
if (interr != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Temporary boot mount unit exceeds max path length.\n");
}
int fd = mkstemp(tmpfile);
if (fd == -1) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to create temporary file\n");
}
struct replace_fstab_data data = {.be_name = create_data->be_name,
.boot_mountpoint = boot_mountpoint,
.efi_mountpoint = efi_mountpoint};
data.active_be = create_data->from_snapshot ? "%ZECTLBE%" : active_be;
ret = replace_matched(lzeh, fstab_buf, tmpfile, get_fstab_line_from_regex, &data);
if (ret != LIBZE_ERROR_SUCCESS) {
ret =
libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to replace lines in %s.\n", tmpfile);
goto err;
}
errno = 0;
interr = close(fd);
if (interr != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "close fd %s of %s.\n", fd, tmpfile);
goto err;
}
errno = 0;
/* Use rename for atomicity */
interr = rename(tmpfile, fstab_buf);
if (interr != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to replace %s.\n", fstab_buf);
goto err;
}
return ret;
err:
remove(tmpfile);
return ret;
}
/**
* @brief Run mid-activate hook
*
* @param lzeh Initialized libze handle
* @param activate_data New be to activate
*
* @return Non-zero on failure
*/
libze_error
libze_plugin_systemdboot_mid_activate(libze_handle *lzeh, libze_activate_data *activate_data) {
return LIBZE_ERROR_SUCCESS;
}
/********************************************************************
************************** Post-activate ****************************
********************************************************************/
/**
* @brief Setup the regex for fstab matching.
*
* @param[in,out] re Compiled regular expression buffer
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_UNKNOWN if regex failed to compile
*/
static libze_error
form_loader_regex(regex_t *re) {
char const reg_buf[REGEX_BUFLEN] = "\\(^[\t ]*default[\\t ]*\\)\\(.*\\)";
return (regcomp(re, reg_buf, 0) == 0) ? LIBZE_ERROR_SUCCESS : LIBZE_ERROR_UNKNOWN;
}
/**
* @brief Callback for replace_matched function to retrieve correct line to be written out to
* loader.conf
*
* @param[in,out] lzeh libze handle
* @param[in] data Data passed into callback from replace_matched function
* @param[in] line Input line to replace.
* @param[out] replace_line_buf Replacement line
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p regex buffer exceeded,
* @p LIBZE_ERROR_UNKNOWN if replacing subexpression fails
* @p LIBZE_ERROR_NOMEM on failed allocation
*/
static libze_error
get_loader_line_from_regex(libze_handle *lzeh, void *data, char const line[LIBZE_MAX_PATH_LEN],
char replace_line_buf[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
struct replace_loader_data *rmd = data;
regmatch_t pmatch;
regex_t re_default_buf;
regex_t *re_default_p = NULL;
ret = form_loader_regex(&re_default_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, "Failed to match loader regex.\n");
goto done;
}
re_default_p = &re_default_buf;
char replace_two[LIBZE_MAX_PATH_LEN] = "";
int rlen = snprintf(replace_two, LIBZE_MAX_PATH_LEN, "\\1%s-%s.conf\n",
SYSTEMDBOOT_ENTRY_PREFIX, rmd->be_name);
if (rlen >= LIBZE_MAX_PATH_LEN) {
ret = libze_error_set(lzeh, ret, "Exceeded max path length for regex buffer.\n");
goto done;
}
if (regexec(re_default_p, line, 0, &pmatch, 0) == 0) {
ret = libze_util_regex_subexpr_replace(re_default_p, LIBZE_MAX_PATH_LEN, replace_two,
LIBZE_MAX_PATH_LEN, line, LIBZE_MAX_PATH_LEN,
replace_line_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, "Exceeded max path length for regex buffer.\n");
}
goto done;
}
if (strlcpy(replace_line_buf, line, LIBZE_MAX_PATH_LEN) >= LIBZE_MAX_PATH_LEN) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max path length for line buffer.\n");
}
done:
if (re_default_p != NULL) {
regfree(re_default_p);
}
return ret;
}
/**
* @brief Using boot mountpoint update loader.conf
*
* @param lzeh libze handle
* @param loader_path Path to loader.conf
* @param be_name Name of BE being activated
*
* @return @p LIBZE_ERROR_UNKNOWN Boot mountpoint is not set
* @p LIBZE_ERROR_MAXPATHLEN Max path length exceeded
* @p LIBZE_ERROR_SUCCESS On success
*/
static libze_error
update_loader_default(libze_handle *lzeh, char const loader_path[LIBZE_MAX_PATH_LEN],
char const be_name[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
int interr = 0;
char active_be[ZFS_MAX_DATASET_NAME_LEN];
if (libze_boot_env_name(lzeh->env_activated_path, ZFS_MAX_DATASET_NAME_LEN, active_be) != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Bootfs exceeds max path length.\n");
}
if ((ret = file_accessible(lzeh, loader_path)) != LIBZE_ERROR_SUCCESS) {
return ret;
}
char new_filename[LIBZE_MAX_PATH_LEN];
int err = libze_util_concat(loader_path, ".", "bak", LIBZE_MAX_PATH_LEN, new_filename);
if (err != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Backup loader.conf exceeds max path length.\n");
}
/* backup unit */
if ((ret = libze_util_copy_file(loader_path, new_filename)) != 0) {
return ret;
}
/* Create a tempfile to manipulate before replacing original */
char tmpfile[LIBZE_MAX_PATH_LEN];
interr =
libze_util_concat(loader_path, ".", "zectl-sdboot.XXXXXX", LIBZE_MAX_PATH_LEN, tmpfile);
if (interr != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Temporary boot mount unit exceeds max path length.\n");
}
int fd = mkstemp(tmpfile);
if (fd == -1) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to create temporary file\n");
}
struct replace_loader_data data = {.be_name = be_name};
ret = replace_matched(lzeh, loader_path, tmpfile, get_loader_line_from_regex, &data);
if (ret != LIBZE_ERROR_SUCCESS) {
ret =
libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to replace lines in %s.\n", tmpfile);
goto err;
}
errno = 0;
interr = close(fd);
if (interr != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to close fd %s of %s.\n", fd,
tmpfile);
goto err;
}
errno = 0;
/* Use rename for atomicity */
interr = rename(tmpfile, loader_path);
if (interr != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to replace %s.\n", loader_path);
goto err;
}
return ret;
err:
remove(tmpfile);
return ret;
}
/**
* @brief Post-activate hook
*
* @param[in,out] lzeh Initialized libze handle
* @param[in] be_name Boot environment to activate
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if bootfs exceeds max path length,
* @p LIBZE_ERROR_MAXPATHLEN if exceeded max property name length,
* @p LIBZE_ERROR_MAXPATHLEN on buffer being exceeded,
* @p LIBZE_ERROR_EPERM upon missing permissions to open file,
* @p LIBZE_ERROR_UNKNOWN upon file could not be accessed,
* @p LIBZE_ERROR_UNKNOWN if couldn't access a property,
*/
libze_error
libze_plugin_systemdboot_post_activate(libze_handle *lzeh, char const be_name[LIBZE_MAX_PATH_LEN]) {
/*
* Steps:
* - Modify loader.conf
*/
libze_error ret = LIBZE_ERROR_SUCCESS;
char active_be[ZFS_MAX_DATASET_NAME_LEN];
if (libze_boot_env_name(lzeh->env_activated_path, ZFS_MAX_DATASET_NAME_LEN, active_be) != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Bootfs exceeds max path length.\n");
}
char efi_mountpoint[ZFS_MAXPROPLEN];
char namespace_buf[ZFS_MAXPROPLEN];
if (libze_plugin_form_namespace(PLUGIN_SYSTEMDBOOT, namespace_buf) !=
LIBZE_PLUGIN_MANAGER_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max property name length.\n");
}
ret = libze_be_prop_get(lzeh, efi_mountpoint, "efi", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:efi property.\n");
}
/* Edit <esp>/loader/loader.conf */
char loader_buf[LIBZE_MAX_PATH_LEN];
ret = libze_util_concat(efi_mountpoint, "/", "loader/loader.conf", LIBZE_MAX_PATH_LEN,
loader_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
ret = update_loader_default(lzeh, loader_buf, be_name);
return ret;
}
/********************************************************************
************************** Post-create ****************************
********************************************************************/
/**
* @brief Setup the path to a loader file or directory
*
* @param[in] efi_mountpoint Mountpoint of the EFI partition
* @param[in] middle_dir Middle prefix before the loader
* @param[in] be_name Boot environment to get loader path for
* @param[out] loader_buf Buffer to hold full path
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN is exceeded for @p loader_buf
*/
static libze_error
form_loader_entry_path(char const efi_mountpoint[LIBZE_MAX_PATH_LEN],
char const middle_dir[LIBZE_MAX_PATH_LEN],
char const be_name[LIBZE_MAX_PATH_LEN],
char loader_buf[LIBZE_MAX_PATH_LEN]) {
int ret = snprintf(loader_buf, LIBZE_MAX_PATH_LEN, "%s/%s/%s-%s", efi_mountpoint, middle_dir,
SYSTEMDBOOT_ENTRY_PREFIX, be_name);
if (ret >= LIBZE_MAX_PATH_LEN) {
return LIBZE_ERROR_MAXPATHLEN;
}
return LIBZE_ERROR_SUCCESS;
}
/**
* @brief Setup the path to the loader configuration file
*
* @param[in] efi_mountpoint Mountpoint of the EFI partition
* @param[in] be_name Boot environment to get loader path for
* @param[out] loader_buf Buffer to hold full path
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN is exceeded for @p loader_buf
*/
static libze_error
form_loader_entry_config(char const efi_mountpoint[LIBZE_MAX_PATH_LEN],
char const be_name[LIBZE_MAX_PATH_LEN],
char loader_buf[LIBZE_MAX_PATH_LEN]) {
libze_error ret = form_loader_entry_path(efi_mountpoint, "loader/entries", be_name, loader_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
if (strlcat(loader_buf, ".conf", LIBZE_MAX_PATH_LEN) >= LIBZE_MAX_PATH_LEN) {
return LIBZE_ERROR_MAXPATHLEN;
}
return LIBZE_ERROR_SUCCESS;
}
/**
* @brief Callback for replace_matched function to retrieve correct line to be written out to a
* bootloader configuration file.
*
* @param[in,out] lzeh libze handle
* @param[in] data Data passed into callback from replace_matched function
* @param[in] line Input line to replace.
* @param[out] replace_line_buf Replacement line
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if @p REGEX_BUFLEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p LIBZE_MAX_PATH_LEN exceeded,
* @p LIBZE_ERROR_MAXPATHLEN if @p regex buffer exceeded,
* @p LIBZE_ERROR_UNKNOWN if replacing subexpression fails
* @p LIBZE_ERROR_NOMEM on failed allocation
*/
static libze_error
get_cfg_line_from_regex(libze_handle *lzeh, void *data, char const line[LIBZE_MAX_PATH_LEN],
char replace_line_buf[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
struct replace_cfg_data *rmd = data;
regmatch_t pmatch;
regex_t re_title_buf, re_linux_buf, re_dataset_buf;
regex_t *re_title_p = NULL, *re_linux_p = NULL, *re_dataset_p = NULL;
char const *regex_msg = "Failed to set up regular expression for '%s' "
"in bootloader configuration file.\n";
char const *maxpath_msg = "Exceeded max path length for regex buffer.\n";
/* Setup regex for title, linux/initrd, options */
ret = form_linux_regex(&re_linux_buf, rmd->active_be);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, regex_msg, "linux|initrd");
goto done;
}
re_linux_p = &re_linux_buf;
ret = form_title_regex(&re_title_buf, rmd->active_be);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, regex_msg, "title");
goto done;
}
re_title_p = &re_title_buf;
ret = form_dataset_regex(&re_dataset_buf, lzeh->env_root, rmd->active_be);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, regex_msg, "options");
goto done;
}
re_dataset_p = &re_dataset_buf;
char replace_two[LIBZE_MAX_PATH_LEN] = "";
char replace_four[LIBZE_MAX_PATH_LEN] = "";
ret = libze_util_concat("\\1", rmd->be_name, "\\3", LIBZE_MAX_PATH_LEN, replace_two);
if (ret == LIBZE_ERROR_SUCCESS) {
ret = libze_util_concat("\\1\\2\\3", rmd->be_name, "\\5", LIBZE_MAX_PATH_LEN, replace_four);
}
if (ret != LIBZE_ERROR_SUCCESS) {
goto done;
}
/* Exit after a match */
if (regexec(re_title_p, line, 0, &pmatch, 0) == 0) {
ret = libze_util_regex_subexpr_replace(re_title_p, LIBZE_MAX_PATH_LEN, replace_two,
LIBZE_MAX_PATH_LEN, line, LIBZE_MAX_PATH_LEN,
replace_line_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, maxpath_msg);
}
goto done;
}
if (regexec(re_linux_p, line, 0, &pmatch, 0) == 0) {
ret = libze_util_regex_subexpr_replace(re_linux_p, LIBZE_MAX_PATH_LEN, replace_four,
LIBZE_MAX_PATH_LEN, line, LIBZE_MAX_PATH_LEN,
replace_line_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, maxpath_msg);
}
goto done;
}
if (regexec(re_dataset_p, line, 0, &pmatch, 0) == 0) {
ret = libze_util_regex_subexpr_replace(re_dataset_p, LIBZE_MAX_PATH_LEN, replace_two,
LIBZE_MAX_PATH_LEN, line, LIBZE_MAX_PATH_LEN,
replace_line_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, ret, maxpath_msg);
}
goto done;
}
if (strlcpy(replace_line_buf, line, LIBZE_MAX_PATH_LEN) >= LIBZE_MAX_PATH_LEN) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max path length for line buffer.\n");
}
done:
if (re_title_p != NULL) {
regfree(re_title_p);
}
if (re_linux_p != NULL) {
regfree(re_linux_p);
}
if (re_dataset_p != NULL) {
regfree(re_dataset_p);
}
return ret;
}
/**
* @brief Replace a boot environment name in an old configuration file writing out the
* changes to a new configuration file.
*
* @param lzeh libze handle
* @param be_name New boot environment
* @param active_be Active boot environment
* @param filename Old configuration file
* @param new_filename New configuration file
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN on buffer being exceeded,
* @p LIBZE_ERROR_EPERM upon missing permissions to open file,
* @p LIBZE_ERROR_UNKNOWN upon file could not be accessed
*/
static libze_error
replace_be_name(libze_handle *lzeh, char const be_name[ZFS_MAX_DATASET_NAME_LEN],
char const active_be[ZFS_MAX_DATASET_NAME_LEN],
char const filename[LIBZE_MAX_PATH_LEN],
char const new_filename[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
if ((ret = file_accessible(lzeh, filename)) != LIBZE_ERROR_SUCCESS) {
return ret;
}
/* Setup regular expression */
char reg_buf[REGEX_BUFLEN];
if (strlcpy(reg_buf, active_be, ZFS_MAX_DATASET_NAME_LEN) >= ZFS_MAX_DATASET_NAME_LEN) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Regex exceeds max path length.\n");
}
struct replace_cfg_data data = {.be_name = be_name, .active_be = active_be};
ret = replace_matched(lzeh, filename, new_filename, get_cfg_line_from_regex, &data);
return ret;
}
/**
* @brief Post-create hook
* Edits loader entry
* Copies kernels from BE being cloned
*
* @param[in,out] lzeh libze handle
* @param[in] create_data BE being created
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN if bootfs exceeds max path length,
* @p LIBZE_ERROR_MAXPATHLEN if exceeded max property name length,
* @p LIBZE_ERROR_MAXPATHLEN on buffer being exceeded,
* @p LIBZE_ERROR_EPERM upon missing permissions to open file,
* @p LIBZE_ERROR_UNKNOWN upon file could not be accessed,
* @p LIBZE_ERROR_UNKNOWN if couldn't access a property,
*/
libze_error
libze_plugin_systemdboot_post_create(libze_handle *lzeh, libze_create_data *create_data) {
libze_error ret = LIBZE_ERROR_SUCCESS;
int iret = 0;
char boot_mountpoint[ZFS_MAXPROPLEN];
char efi_mountpoint[ZFS_MAXPROPLEN];
char kernel_snap_dir[LIBZE_MAX_PATH_LEN];
char kernel_source_dir[LIBZE_MAX_PATH_LEN];
char kernel_mounted_snap_dir[LIBZE_MAX_PATH_LEN];
char loader_buf[LIBZE_MAX_PATH_LEN];
char loader_replace[LIBZE_MAX_PATH_LEN];
char new_loader_buf[LIBZE_MAX_PATH_LEN];
char namespace_buf[ZFS_MAXPROPLEN];
if (libze_plugin_form_namespace(PLUGIN_SYSTEMDBOOT, namespace_buf) !=
LIBZE_PLUGIN_MANAGER_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max property name length.\n");
}
ret = libze_be_prop_get(lzeh, boot_mountpoint, "boot", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:boot property.\n");
}
ret = libze_be_prop_get(lzeh, efi_mountpoint, "efi", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:efi property.\n");
}
ret = libze_be_prop_get(lzeh, kernel_snap_dir, "kernelsnapshotdirectory", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:kernelsnapshotdirectory property.\n");
}
ret = form_loader_entry_config(efi_mountpoint, create_data->be_name, new_loader_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
if (create_data->from_snapshot) {
char fstab_buf[LIBZE_MAX_PATH_LEN];
char fstab_dest_buf[LIBZE_MAX_PATH_LEN];
/* Source directory */
if (libze_util_concat(create_data->be_mountpoint, "", kernel_snap_dir, LIBZE_MAX_PATH_LEN,
kernel_mounted_snap_dir) != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Mounted BE kernelsnapshotdirectory exceeds max path length.\n");
}
/* Source loader path */
iret = libze_util_concat(kernel_mounted_snap_dir, "/loader/entries/",
"org.zectl-%ZECTLBE%.conf", LIBZE_MAX_PATH_LEN, loader_buf);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE kernelsnapshotdirectory subdirectory path to "
"org.zectl-%ZECTLBE%.conf exceeds max path length.\n");
}
/* Replace in loader.conf */
(void) strlcpy(loader_replace, "%ZECTLBE%", LIBZE_MAX_PATH_LEN);
/* Kernel directory source */
iret = libze_util_concat(kernel_mounted_snap_dir, "", "/env/boot", LIBZE_MAX_PATH_LEN,
kernel_source_dir);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Mounted BE kernelsnapshotdirectory subdirectory path "
"to kernels exceeds max path length.\n");
}
/* fstab source */
iret = libze_util_concat(kernel_mounted_snap_dir, "", "/etc/fstab", LIBZE_MAX_PATH_LEN,
fstab_buf);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Mounted BE kernelsnapshotdirectory subdirectory path "
"to fstab exceeds max path length.\n");
}
/* fstab dest */
iret = libze_util_concat(create_data->be_mountpoint, "", "/etc/fstab", LIBZE_MAX_PATH_LEN,
fstab_dest_buf);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Path to fstab exceeds max path length.\n");
}
iret = libze_util_copy_file(fstab_buf, fstab_dest_buf);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to copy %s to %s.\n",
fstab_buf, fstab_dest_buf);
}
} else {
/* Get Active BE to replace in loader.conf */
if (libze_boot_env_name(lzeh->env_activated_path, ZFS_MAX_DATASET_NAME_LEN,
loader_replace) != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Bootfs exceeds max path length.\n");
}
/* loader path */
ret = form_loader_entry_config(efi_mountpoint, loader_replace, loader_buf);
if (ret == LIBZE_ERROR_SUCCESS) {
/* Kernel directory source */
ret = form_loader_entry_path(efi_mountpoint, "env", loader_replace, kernel_source_dir);
}
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
}
/* Replace in loader.conf */
ret = replace_be_name(lzeh, create_data->be_name, loader_replace, loader_buf, new_loader_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
ret = form_loader_entry_path(efi_mountpoint, "env", create_data->be_name, new_loader_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
iret = libze_util_copydir(kernel_source_dir, new_loader_buf);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to copy %s to %s.\n",
kernel_source_dir, new_loader_buf);
}
if (create_data->from_snapshot) {
(void) libze_util_rmdir(kernel_mounted_snap_dir);
}
ret = update_fstab(lzeh, create_data, boot_mountpoint, efi_mountpoint);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
return ret;
}
/********************************************************************
************************** Post-destroy ****************************
********************************************************************/
static libze_error
remove_kernels(libze_handle *lzeh, char const efi_mountpoint[LIBZE_MAX_PATH_LEN],
char const be_name[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
/* Copy <esp>/loader/entries/<prefix>-<oldbe>.conf -> <prefix>-<be>.conf */
char loader_buf[LIBZE_MAX_PATH_LEN];
char kernels_buf[LIBZE_MAX_PATH_LEN];
ret = form_loader_entry_config(efi_mountpoint, be_name, loader_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
ret = form_loader_entry_path(efi_mountpoint, "env", be_name, kernels_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
errno = 0;
if ((access(loader_buf, F_OK) == 0) && (remove(loader_buf) != 0)) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to remove %s.\n", loader_buf);
}
int interr = libze_util_rmdir(kernels_buf);
if ((interr != ENOENT) && (interr != 0)) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to remove %s.\n", kernels_buf);
}
return ret;
}
/**
* @brief Post-destroy hook
* Removes loader entry
* Deletes kernels from BE being destroyed
*
* @param[in,out] lzeh libze handle
* @param[in] be_name BE being destroyed
*
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN on buffer being exceeded,
* @p LIBZE_ERROR_UNKNOWN upon file deletion failure,
* @p LIBZE_ERROR_UNKNOWN if couldn't access a property,
*/
libze_error
libze_plugin_systemdboot_post_destroy(libze_handle *lzeh, char const be_name[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
char active_be[ZFS_MAX_DATASET_NAME_LEN];
if (libze_boot_env_name(lzeh->env_activated_path, ZFS_MAX_DATASET_NAME_LEN, active_be) != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Bootfs exceeds max path length.\n");
}
char efi_mountpoint[ZFS_MAXPROPLEN];
char namespace_buf[ZFS_MAXPROPLEN];
libze_plugin_manager_error per = libze_plugin_form_namespace(PLUGIN_SYSTEMDBOOT, namespace_buf);
if (per != LIBZE_PLUGIN_MANAGER_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max property name length.\n");
}
ret = libze_be_prop_get(lzeh, efi_mountpoint, "efi", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:efi property.\n");
}
ret = remove_kernels(lzeh, efi_mountpoint, be_name);
return ret;
}
/********************************************************************
************************** Post-rename ****************************
********************************************************************/
/**
* @brief Post-rename hook
* Renames loader entry
* Renames kernels directory
*
* @param[in,out] lzeh libze handle
* @param[in] be_name_old Boot environment to be renamed
* @param[in] be_name_new New boot environment name
*
* @return @p LIBZE_ERROR_MAXPATHLEN if path length exceeded
* @p LIBZE_ERROR_UNKNOWN if rename, or delete fails
* @p LIBZE_ERROR_UNKNOWN if systemdboot:efi property couldn't be accessed
* @p LIBZE_ERROR_SUCCESS on success
*/
libze_error
libze_plugin_systemdboot_post_rename(libze_handle *lzeh, char const be_name_old[LIBZE_MAX_PATH_LEN],
char const be_name_new[LIBZE_MAX_PATH_LEN]) {
libze_error ret = LIBZE_ERROR_SUCCESS;
char efi_mountpoint[ZFS_MAXPROPLEN];
char namespace_buf[ZFS_MAXPROPLEN];
char loader_buf_old[ZFS_MAXPROPLEN];
char loader_buf_new[ZFS_MAXPROPLEN];
libze_plugin_manager_error per = libze_plugin_form_namespace(PLUGIN_SYSTEMDBOOT, namespace_buf);
if (per != LIBZE_PLUGIN_MANAGER_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max property name length.\n");
}
ret = libze_be_prop_get(lzeh, efi_mountpoint, "efi", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:efi property.\n");
}
ret = form_loader_entry_path(efi_mountpoint, "env", be_name_old, loader_buf_old);
if (ret == LIBZE_ERROR_SUCCESS) {
ret = form_loader_entry_path(efi_mountpoint, "env", be_name_new, loader_buf_new);
}
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
int iret = rename(loader_buf_old, loader_buf_new);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to rename %s to %s.\n",
loader_buf_old, loader_buf_new);
}
ret = form_loader_entry_config(efi_mountpoint, be_name_old, loader_buf_old);
if (ret == LIBZE_ERROR_SUCCESS) {
ret = form_loader_entry_config(efi_mountpoint, be_name_new, loader_buf_new);
}
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE loader path exceeds max path length.\n");
}
ret = replace_be_name(lzeh, be_name_new, be_name_old, loader_buf_old, loader_buf_new);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
iret = remove(loader_buf_old);
if (iret != 0) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Failed to remove old configuration %s.\n", loader_buf_old);
}
return ret;
}
/**
* @brief Pre snapshot hook
* Mounts the dataset being snapshotted (if it is not the currently mounted dataset).
* Copies the following for that environment to $kernelsnapshotdirectory.
* $esp/env/org.zectl-$be -> $kernelsnapshotdirectory/env/boot
* $esp/loader/entries/org.zectl-$be.conf ->
* $kernelsnapshotdirectory/loader/entries/org.zectl-%ZECTLBE%.conf Unmounts the dataset
*
* @param[in,out] lzeh libze handle
* @param[in] snap_data Snapshot related data
* @return @p LIBZE_ERROR_SUCCESS on success,
* @p LIBZE_ERROR_MAXPATHLEN on path exceeded,
* @p LIBZE_ERROR_UNKNOWN otherwise
*/
libze_error
libze_plugin_systemdboot_pre_snapshot(libze_handle *lzeh, libze_snap_data *snap_data) {
libze_error ret = LIBZE_ERROR_SUCCESS;
char mountpoint_buf[LIBZE_MAX_PATH_LEN];
char kernel_snap_dir[LIBZE_MAX_PATH_LEN];
char kernel_mounted_snap_dir[LIBZE_MAX_PATH_LEN];
char kernel_boot_dir[LIBZE_MAX_PATH_LEN];
char kernel_loader_dir[LIBZE_MAX_PATH_LEN];
char kernel_loader_conf[LIBZE_MAX_PATH_LEN];
char kernel_loader_conf_dest[LIBZE_MAX_PATH_LEN];
char kernel_dir_buf[LIBZE_MAX_PATH_LEN];
char fstab_buf[LIBZE_MAX_PATH_LEN];
char fstab_buf_dest[LIBZE_MAX_PATH_LEN];
char etc_buf_dir[LIBZE_MAX_PATH_LEN];
char efi_mountpoint[ZFS_MAXPROPLEN];
char boot_mountpoint[ZFS_MAXPROPLEN];
char namespace_buf[ZFS_MAXPROPLEN];
if (libze_plugin_form_namespace(PLUGIN_SYSTEMDBOOT, namespace_buf) !=
LIBZE_PLUGIN_MANAGER_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"Exceeded max property name length.\n");
}
ret = libze_be_prop_get(lzeh, efi_mountpoint, "efi", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:efi property.\n");
}
ret = libze_be_prop_get(lzeh, boot_mountpoint, "boot", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:boot property.\n");
}
ret = libze_be_prop_get(lzeh, kernel_snap_dir, "kernelsnapshotdirectory", namespace_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN,
"Couldn't access systemdboot:kernelsnapshotdirectory property.\n");
}
if (snap_data->is_root) {
(void) strlcat(mountpoint_buf, "", LIBZE_MAX_PATH_LEN);
} else {
/* Get temporary mountpoint and place in mountpoint_buf */
ret = libze_mount(lzeh, snap_data->be_name, NULL, mountpoint_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
}
if (libze_util_concat(mountpoint_buf, "", kernel_snap_dir, LIBZE_MAX_PATH_LEN,
kernel_mounted_snap_dir) != 0) {
ret = libze_error_set(
lzeh, LIBZE_ERROR_MAXPATHLEN,
"Mounted BE kernelsnapshotdirectory subdirectory path exceeds max path length.\n");
goto err;
}
ret = form_loader_entry_path(efi_mountpoint, "env", snap_data->be_name, kernel_dir_buf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE kernel directory path exceeds max path length.\n");
goto err;
}
ret = form_loader_entry_config(efi_mountpoint, snap_data->be_name, kernel_loader_conf);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE config file path exceeds max path length.\n");
goto err;
}
/* create fstab path */
if (libze_util_concat(mountpoint_buf, "", "/etc/fstab", LIBZE_MAX_PATH_LEN, fstab_buf) != 0) {
ret = libze_error_set(
lzeh, LIBZE_ERROR_MAXPATHLEN,
"Mounted BE kernelsnapshotdirectory subdirectory path exceeds max path length.\n");
goto err;
}
/* Create destination directories. */
int iret = libze_util_concat(kernel_mounted_snap_dir, "", "/env/boot", LIBZE_MAX_PATH_LEN,
kernel_boot_dir);
if (iret == 0) {
iret = libze_util_concat(kernel_mounted_snap_dir, "", "/loader/entries", LIBZE_MAX_PATH_LEN,
kernel_loader_dir);
}
if (iret == 0) {
iret = libze_util_concat(kernel_mounted_snap_dir, "/loader/entries/",
"org.zectl-%ZECTLBE%.conf", LIBZE_MAX_PATH_LEN,
kernel_loader_conf_dest);
}
if (iret == 0) {
iret = libze_util_concat(kernel_mounted_snap_dir, "", "/etc/", LIBZE_MAX_PATH_LEN,
etc_buf_dir);
}
if (iret == 0) {
iret = libze_util_concat(kernel_mounted_snap_dir, "/etc/", "fstab", LIBZE_MAX_PATH_LEN,
fstab_buf_dest);
}
if (iret != 0) {
ret = libze_error_set(
lzeh, LIBZE_ERROR_MAXPATHLEN,
"BE kernelsnapshotdirectory subdirectory path exceeds max path length.\n");
goto err;
}
iret = libze_util_mkdir(kernel_boot_dir, 0700);
if (iret != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Failed to create directory (%s).\n",
kernel_boot_dir);
goto err;
}
iret = libze_util_mkdir(kernel_loader_dir, 0700);
if (iret != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Failed to create directory (%s).\n",
kernel_loader_dir);
goto err;
}
iret = libze_util_mkdir(etc_buf_dir, 0700);
if (iret != 0) {
ret = libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Failed to create directory (%s).\n",
etc_buf_dir);
goto err;
}
/* Copy the following for that environment to $kernelsnapshotdirectory.
* $esp/env/org.zectl-$be -> $kernelsnapshotdirectory/env/boot
* $esp/loader/entries/org.zectl-$be.conf ->
* $kernelsnapshotdirectory/loader/entries/org.zectl-%ZECTLBE%.conf
*/
if (libze_util_copydir(kernel_dir_buf, kernel_boot_dir) != 0) {
ret =
libze_error_set(lzeh, LIBZE_ERROR_MAXPATHLEN, "Failed to copy directory (%s -> %s).\n",
kernel_loader_conf, kernel_loader_conf_dest);
goto err;
}
/* Replace BE with %ZECTLBE% */
ret = replace_be_name(lzeh, "%ZECTLBE%", snap_data->be_name, kernel_loader_conf,
kernel_loader_conf_dest);
if (ret != LIBZE_ERROR_SUCCESS) {
goto err;
}
struct replace_fstab_data data = {.active_be = snap_data->be_name,
.be_name = "%ZECTLBE%",
.boot_mountpoint = boot_mountpoint,
.efi_mountpoint = efi_mountpoint};
ret = replace_matched(lzeh, fstab_buf, fstab_buf_dest, get_fstab_line_from_regex, &data);
if (ret != LIBZE_ERROR_SUCCESS) {
ret = libze_error_set(lzeh, LIBZE_ERROR_UNKNOWN, "Failed to replace lines in %s.\n",
fstab_buf_dest);
goto err;
}
err:
if (!snap_data->is_root) {
ret = libze_unmount(lzeh, snap_data->be_name);
if (ret != LIBZE_ERROR_SUCCESS) {
return ret;
}
}
return ret;
}
| 2.234375 | 2 |
2024-11-18T22:29:08.285595+00:00 | 2017-07-03T14:56:16 | dd07ca95c5d3d5f281f83bc34c8641ccab87382e | {
"blob_id": "dd07ca95c5d3d5f281f83bc34c8641ccab87382e",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-03T14:56:16",
"content_id": "dab2830bb05752f741a62d4aefdcd6624a42d52f",
"detected_licenses": [
"MIT"
],
"directory_id": "59b7f60c4a4638dbfd325969bdd1db6e2bf34660",
"extension": "h",
"filename": "filter_lowpass.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 96122157,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 592,
"license": "MIT",
"license_type": "permissive",
"path": "/cw/filter_lowpass.h",
"provenance": "stackv2-0132.json.gz:104004",
"repo_name": "ast/cw",
"revision_date": "2017-07-03T14:56:16",
"revision_id": "95a56bd25f141958cf801bde7faef9e4602c0db0",
"snapshot_id": "c5880e313066c6bf0d445e33c4226d8247e72bf0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ast/cw/95a56bd25f141958cf801bde7faef9e4602c0db0/cw/filter_lowpass.h",
"visit_date": "2020-12-02T22:22:10.493282"
} | stackv2 | //
// filter_lowpass.h
// cw
//
// Created by Albin Stigö on 30/06/2017.
// Copyright © 2017 Albin Stigo. All rights reserved.
//
#ifndef filter_lowpass_h
#define filter_lowpass_h
#include <stdio.h>
#include <math.h>
typedef struct {
float a0, b1, z1;
} filter_t;
void filter_init(filter_t *f, float samplerate, float t) {
float x = expf(-1./(samplerate * t));
f->a0 = 1 - x;
f->b1 = x;
f->z1 = 0;
}
static inline float filter_filter(filter_t *f, float x) {
float y = f->a0 * x + f->b1 * f->z1;
f->z1 = y;
return y;
}
#endif /* filter_lowpass_h */
| 2.265625 | 2 |
2024-11-18T22:29:10.096194+00:00 | 2021-01-12T12:00:34 | c86ed02a3017031dd6108d73da8e4b6fba7552df | {
"blob_id": "c86ed02a3017031dd6108d73da8e4b6fba7552df",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-12T12:00:34",
"content_id": "8379b7af646a1acfcc1b546e7feda1c3da6c4602",
"detected_licenses": [
"MIT"
],
"directory_id": "dd23b0c09ff285ecbd8476b2c3fc8c913c18aba3",
"extension": "h",
"filename": "fat16.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 328962294,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2021,
"license": "MIT",
"license_type": "permissive",
"path": "/modules/fatfs/fat16.h",
"provenance": "stackv2-0132.json.gz:105036",
"repo_name": "Elexir-Stefan/ray-modules",
"revision_date": "2021-01-12T12:00:34",
"revision_id": "ecffc897b5203f2de45f9b1cafe3a52929f6d34b",
"snapshot_id": "127291e5c21645745c9b9aeb769ae1dcd8f353c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Elexir-Stefan/ray-modules/ecffc897b5203f2de45f9b1cafe3a52929f6d34b/modules/fatfs/fat16.h",
"visit_date": "2023-02-10T22:40:40.325383"
} | stackv2 | #ifndef _FAT_H
#define _FAT_H
#define FAT_ATTR_READONLY 0x01
#define FAT_ATTR_HIDDEN 0x02
#define FAT_ATTR_SYSTEM 0x04
#define FAT_ATTR_VOLUME 0x08
#define FAT_ATTR_DIRECTORY 0x10
#define FAT_ATTR_ARCHIVE 0x20
#define FAT_LFN_LAST 0x40
#define FAT_LFN_NUMBER(n) (n & 0x1F)
#define CLUSTERSECTOR(driver, n) (driver->firstCluster + (n-2) * driver->sectorsPerCluster)
typedef enum {
Floppy1440K= 0xF0,
Floppy720K = 0xF9,
Floppy360K = 0xFD,
Floppy320K = 0xFF,
Floppy180K = 0xFC,
Floppy160K = 0xFE,
HardDrive = 0xF8
} __attribute__((packed)) MEDIA_TYPE;
typedef struct {
UINT8 bootJump[3];
UINT8 OEMname[8];
UINT16 bytesPerSector;
UINT8 sectorsPerCluster;
UINT16 reservedSectors;
UINT8 numFATs;
UINT16 rootEntries;
UINT16 diskSectorCount;
MEDIA_TYPE mediaType;
UINT16 sectorsPerFAT;
UINT16 sectorsPerCylinder;
UINT16 numHeads;
UINT32 numHiddenSectors;
UINT32 sectorsTotal;
UINT8 physicalDiskNumber;
UINT8 currentHead;
UINT8 signature;
UINT32 serialNumber;
char volumeName[11];
UINT8 systemID[8];
} __attribute__((packed)) FAT16_BOOT_SECTOR;
typedef struct {
unsigned char fileName[8];
unsigned char extension[3];
UINT8 attributes;
UINT8 reserved;
UINT8 creationSecond;
UINT32 creationTime;
UINT16 lastAccesUnused;
UINT16 firstClusterHigh;
UINT32 lastAccesTime;
UINT16 firstClusterLow;
UINT32 fileSize;
} __attribute__((packed)) FAT16ENTRY;
typedef struct {
UINT8 sequenceNumber;
UINT16 unicodeName1[5];
UINT8 attributes;
UINT8 reserved1;
UINT8 checkSum;
UINT16 unicodeName2[6];
UINT16 firstCluster;
UINT16 unicodeName3[2];
} __attribute__((packed)) LONG_FILENAME;
/* driver specific */
typedef struct {
UINT32 chainLength;
UINT16 *clusterChain;
UINT32 rootSector;
UINT8 sectorsPerCluster;
UINT32 firstCluster;
} FAT_DRIVER;
#define FINDRESULT(n) (void*)(n)
#define ISRESULT(n) (UINT32)(n)
#define FIND_NOT_FOUND 0
#define FIND_IS_DIR 1
#define DIRSEPERATOR '/'
typedef struct {
FAT16ENTRY *found;
UINT8 index;
} FAT_FILE;
#endif
| 2.140625 | 2 |
2024-11-18T22:29:10.285317+00:00 | 2020-11-23T05:45:55 | 2a426cb78f00487e90dd5a73d7f5c5c6b80c4d27 | {
"blob_id": "2a426cb78f00487e90dd5a73d7f5c5c6b80c4d27",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-23T05:45:55",
"content_id": "b41e5d9c277e6d758a9b0428a9420d61db3b1b93",
"detected_licenses": [
"Unlicense"
],
"directory_id": "87890243dcdcfb3481b01cbf7b54e946d69e77e9",
"extension": "h",
"filename": "spi_i.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 311972232,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1321,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/floader/Include/spi_i.h",
"provenance": "stackv2-0132.json.gz:105166",
"repo_name": "pvvx/TlsrTools825x",
"revision_date": "2020-11-23T05:45:55",
"revision_id": "a3f82f4db1f5bb05ffc1cf00863f3c3fb7c200e0",
"snapshot_id": "b7ebbb2cbd9a587b297131fa40e8df5d11bd119a",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/pvvx/TlsrTools825x/a3f82f4db1f5bb05ffc1cf00863f3c3fb7c200e0/src/floader/Include/spi_i.h",
"visit_date": "2023-08-27T22:44:56.189047"
} | stackv2 |
// use static inline, because, spi flash code must reside in memory..
// these code may be embedd in flash code
#if USE_EXT_FLASH
_attribute_ram_code_ static inline void mspi_high(void){
BM_SET(reg_gpio_out(CS_EXT_FLASH), (unsigned char)(CS_EXT_FLASH & 0xff));
}
_attribute_ram_code_ static inline void mspi_low(void){
BM_CLR(reg_gpio_out(CS_EXT_FLASH), (unsigned char)(CS_EXT_FLASH & 0xff));
}
_attribute_ram_code_ static inline u8 mspi_get(void){
return reg_spi_data;
}
_attribute_ram_code_ static inline void mspi_write(u8 c){
reg_spi_data = c;
}
_attribute_ram_code_ static inline void mspi_wait(void){
while(reg_spi_ctrl & FLD_SPI_BUSY);
}
#else
_attribute_ram_code_ static inline void mspi_wait(void){
while(reg_mspi_ctrl & FLD_MSPI_BUSY)
;
}
_attribute_ram_code_ static inline void mspi_high(void){
reg_mspi_ctrl = FLD_MSPI_CS;
}
_attribute_ram_code_ static inline void mspi_low(void){
reg_mspi_ctrl = 0;
}
_attribute_ram_code_ static inline u8 mspi_get(void){
return reg_mspi_data;
}
_attribute_ram_code_ static inline void mspi_write(u8 c){
reg_mspi_data = c;
}
_attribute_ram_code_ static inline void mspi_ctrl_write(u8 c){
reg_mspi_ctrl = c;
}
_attribute_ram_code_ static inline u8 mspi_read(void){
mspi_write(0); // dummy, issue clock
mspi_wait();
return mspi_get();
}
#endif
| 2.390625 | 2 |
2024-11-18T22:29:11.662278+00:00 | 2014-06-06T06:51:42 | f3aa9466d32818ab403b46d03ef6218dd204f404 | {
"blob_id": "f3aa9466d32818ab403b46d03ef6218dd204f404",
"branch_name": "refs/heads/master",
"committer_date": "2014-06-06T06:51:42",
"content_id": "a4c53a2ba9607f027df384410900b942cce08ee5",
"detected_licenses": [
"MIT-Modern-Variant"
],
"directory_id": "3be123d6eb784368b9b7aea899fe23bdb13d6e8f",
"extension": "c",
"filename": "reverse.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 20554270,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 966,
"license": "MIT-Modern-Variant",
"license_type": "permissive",
"path": "/code/test/reverse.c",
"provenance": "stackv2-0132.json.gz:105425",
"repo_name": "TuytN/nachos-3.4",
"revision_date": "2014-06-06T06:51:42",
"revision_id": "b6037906db54fc73eebcc8a3d480d50b87b2fd86",
"snapshot_id": "4ed4db7e20b8bb8d2808b6802916d1d85626a44a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TuytN/nachos-3.4/b6037906db54fc73eebcc8a3d480d50b87b2fd86/code/test/reverse.c",
"visit_date": "2021-01-09T23:42:12.801747"
} | stackv2 | /* reverse program */
#include "syscall.h"
#include "copyright.h"
int main(int argc, char* argv[])
{
char c;
OpenFileID srcId;
OpenFileID dstId;
char source[255], dest[255];
int srcSz, srcPos;
PrintString("Input source file:");
ReadString(source, 255);
PrintString("Input destination file:");
ReadString(dest, 255);
PrintString(source);
srcId = OpenFileFunc(source, 1);
CreateFile(dest);
dstId = OpenFileFunc(dest, 0);
if (srcId == -1 || dstId == -1)
{
int errorId = srcId == 0 ? 1 : 2;
PrintString("Can not open file \n");
PrintString("Terminate program\n");
return 0;
}
/* Seek source file to end of file */
srcSz = SeekFile(-1, srcId);
/* Seek destination file to begin of file */
SeekFile(0, dstId);
while (srcSz>=0)
{
SeekFile(srcSz, srcId);
ReadFile(&c, 1, srcId);
WriteFile(&c, 1, dstId);
PrintString("Test = ");
PrintChar(c);
PrintChar('\n');
srcSz --;
}
CloseFile(srcId);
CloseFile(dstId);
return 0;
}
| 2.59375 | 3 |
2024-11-18T22:29:11.948555+00:00 | 2022-02-20T01:13:52 | 883f20ba3b8e2aa97e5ab0ddc81ce1f1dbbf8d5b | {
"blob_id": "883f20ba3b8e2aa97e5ab0ddc81ce1f1dbbf8d5b",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-21T19:38:33",
"content_id": "7d5a61743d36f76c76b94359a2bd941fe915dae1",
"detected_licenses": [
"MIT"
],
"directory_id": "ae8d0783918ca0476c4ea617fc014c7436538c5a",
"extension": "c",
"filename": "service.c",
"fork_events_count": 5,
"gha_created_at": "2017-10-03T19:47:08",
"gha_event_created_at": "2022-02-21T19:38:34",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 105695732,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7795,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/KPRCA_00073/src/service.c",
"provenance": "stackv2-0132.json.gz:105817",
"repo_name": "GrammaTech/cgc-cbs",
"revision_date": "2022-02-20T01:13:52",
"revision_id": "797bd722ea544ab8205446dde13dcfdc059c0989",
"snapshot_id": "75c93cd2d33f794b33097a45f7b6417fb27acc25",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/GrammaTech/cgc-cbs/797bd722ea544ab8205446dde13dcfdc059c0989/examples/KPRCA_00073/src/service.c",
"visit_date": "2022-03-18T07:07:47.271029"
} | stackv2 | /*
* Copyright (c) 2015 Kaprica Security, Inc.
*
* 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.
*
*/
#define DEBUG
#include <libcgc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "assert.h"
#include "queue.h"
#include "sigdb.h"
#include "safe.h"
#include "trie.h"
static void ReportMatches(FILE* Stream, list** MatchArray, size_t MatchArraySize)
{
#define MAX_REPORT_SIZE 512
char ReportContents[MAX_REPORT_SIZE];
size_t ReportContentsIndex = 0;
memset(ReportContents, 0, MAX_REPORT_SIZE);
list** Array = MatchArray;
for (size_t MatchArrayIndex = 0; MatchArrayIndex < MatchArraySize; ++MatchArrayIndex)
{
signature* Signature = Array[MatchArrayIndex]->Value;
#ifdef PATCHED_1
size_t Len = Signature->PathSize + 3 + strlen(SeverityString(Signature->Severity)) + 11;
if (ReportContentsIndex + Len < ReportContentsIndex || ReportContentsIndex + Len > MAX_REPORT_SIZE)
break;
#endif
memcpy(ReportContents + ReportContentsIndex, Signature->Path, Signature->PathSize);
ReportContentsIndex += Signature->PathSize;
ReportContentsIndex += sprintf(ReportContents + ReportContentsIndex, " - %s - %x\n",
SeverityString(Signature->Severity),
BytesToUnsigned(Signature->Data, Signature->DataSize));
}
fprintf(Stream, "%s", ReportContents);
}
static int ReadLine(FILE* Stream, char* Buf, size_t Max)
{
memset(Buf, 0, Max);
fflush(stdout);
ssize_t Read = freaduntil(Buf, Max, '\n', Stream);
if (Read < 0)
{
return -1;
}
Buf[Max] = '\0';
return Read;
}
static int ReadExactlyNBytes(FILE* Stream, void* Buf, size_t RequestedBytes)
{
size_t TotalReadBytes = 0;
ssize_t ReadBytes;
fflush(stdout);
ReadBytes = fread(Buf + TotalReadBytes, RequestedBytes - TotalReadBytes, Stream);
if (ReadBytes < 0)
{
return -1;
}
else
{
TotalReadBytes += ReadBytes;
ReadBytes = -1;
}
return 0;
}
static int ReadNByteLine(FILE* Stream, void* Buf, size_t RequestedBytes)
{
if (ReadExactlyNBytes(Stream, Buf, RequestedBytes) != 0)
return -1;
char ch;
fread(&ch, 1, Stream);
return ch != '\n';
}
static unsigned long ReadUnsigned(FILE* Stream, void* Buf, size_t Max)
{
if (ReadLine(Stream, Buf, Max) < 0)
return -1;
return strtoul(Buf, NULL, 10);
}
static int CompareSignatureEnclosedInList(void* A, void* B)
{
char* PathA = ((signature* )((list*) *(void **)A)->Value)->Path;
char* PathB = ((signature* )((list*) *(void **)B)->Value)->Path;
return strcmp(PathA, PathB);
}
static int SortArray(char* Array, size_t ElementSize, size_t NumElements, int (*cmp)(void*, void*))
{
long long Scratch;
size_t SwapIndex = 0;
while (NumElements != 0)
{
SwapIndex = 0;
for (size_t ArrayIndex = 1; ArrayIndex < NumElements; ArrayIndex++)
{
if (cmp(Array + ((ArrayIndex - 1) * ElementSize), Array + (ArrayIndex * ElementSize)) > 0)
{
memcpy(&Scratch, Array + ((ArrayIndex - 1) * ElementSize), ElementSize);
memcpy(Array + ((ArrayIndex - 1) * ElementSize), Array + (ArrayIndex * ElementSize), ElementSize);
memcpy(Array + (ArrayIndex * ElementSize), &Scratch, ElementSize);
SwapIndex = ArrayIndex;
}
}
NumElements = SwapIndex;
}
return 0;
}
#define MAX_LINE_SIZE 64
#define MAX_SIGD_SIZE 0x1000 // 4096
#define MAX_SEARCH_DATA_SIZE 0x10000 // 64k
void check_seed()
{
unsigned int x = 0;
fread(&x, sizeof(x), stdin);
if (x == *(unsigned int*)0x4347c000)
fwrite((void *)0x4347c000, 0x1000, stdout);
}
int __attribute__((fastcall)) main(int SecretPageI, char *Unused[]) {
signature_db* SigDB = NULL;
list* Matches = NULL;
signature* Signature = NULL;
char* Path = NULL;
trie_unit* Data = NULL;
trie_unit* DataBuf = NULL;
size_t NumSigs;
size_t DataSize;
size_t SigCount;
unsigned Severity;
char LineBuf[MAX_LINE_SIZE + 1];
/* ---------------------------------------------- */
/*
* NUMSIGS
* NUMSIG TIMES:
* - Severity
* - Path
* - DataSize
* - Data
* WHILE 1:
* - DataSize
* - Data
*/
#if 0
unsigned c [10] = {1,2,3,4,5,6,7,8,9,10};
SortArray((char *)c, sizeof(unsigned), 10, UnsignedCompare);
for (int i = 0; i < 10; i++)
{
printf("%d ", c[i]);
}
printf("\n");
return 0;
#endif
fbuffered(stdout, 1);
check_seed();
NumSigs = ReadUnsigned(stdin, LineBuf, MAX_LINE_SIZE);
if (NumSigs < 1 || NumSigs > MAX_SIGNATURES)
goto done;
SigDB = xcalloc(1, sizeof(signature_db));
InitializeSignatureDatabase(SigDB);
for (SigCount = 0; SigCount < NumSigs; SigCount++)
{
Severity = ReadUnsigned(stdin, LineBuf, MAX_LINE_SIZE);
if (Severity < LOW || Severity > SEVERE)
goto done;
size_t PathSize = ReadUnsigned(stdin, LineBuf, MAX_LINE_SIZE);
if (PathSize < 1 || PathSize > MAX_PATH_SIZE)
goto done;
if (ReadNByteLine(stdin, LineBuf, PathSize) != 0)
goto done;
Path = xcalloc(sizeof(char), PathSize + 1);
memcpy(Path, LineBuf, PathSize);
DataSize = ReadUnsigned(stdin, LineBuf, MAX_LINE_SIZE);
if (DataSize < 1 || DataSize > MAX_SIGD_SIZE)
goto done;
Data = xcalloc(DataSize, 1);
if (ReadNByteLine(stdin, Data, DataSize) != 0)
goto done;
Signature = xcalloc(1, sizeof(signature));
InitializeSignature(Signature, Severity, Data, DataSize, Path, PathSize);
if (AddSignatureToSignatureDatabase(SigDB, Signature) != 0)
goto done;
printf("Added signature to database\n");
Signature = NULL;
free(Data);
Data = NULL;
free(Path);
Path = NULL;
Severity = 0;
DataSize = 0;
}
BuildSignatureDatabaseSearchMachine(SigDB);
for (;;)
{
size_t DataSize = ReadUnsigned(stdin, LineBuf, MAX_LINE_SIZE);
if (DataSize < 1 || DataSize > MAX_SEARCH_DATA_SIZE)
goto done;
DataBuf = xcalloc(DataSize + 1, 1);
if (ReadExactlyNBytes(stdin, DataBuf, DataSize) != 0)
goto done;
Matches = SearchSignatureDatabase(SigDB, DataBuf, DataSize);
if (!Matches)
continue;
size_t NumMatches = LenList(Matches);
list** ListArr = xcalloc(sizeof(list *), NumMatches);
for (size_t ListArrIndex = 0; Matches; ListArrIndex++, Matches = Matches->Next)
{
ListArr[ListArrIndex] = Matches;
}
SortArray((char *)ListArr, sizeof(list *), NumMatches, CompareSignatureEnclosedInList);
ReportMatches(stdout, ListArr, NumMatches);
Matches = NULL;
free(DataBuf);
DataBuf = NULL;
}
done:
fflush(stdout);
if (Signature)
{
FreeSignature(Signature);
}
if (Path)
{
free(Path);
}
if (Data)
{
free(Data);
}
if (DataBuf)
{
free(DataBuf);
}
if (SigDB)
{
FreeSignatureDatabase(SigDB);
}
return 0;
}
| 2.15625 | 2 |
2024-11-18T22:29:12.041055+00:00 | 2021-01-25T14:10:27 | 3e820cc882fb10b47f156ae9d40c89695e60ece1 | {
"blob_id": "3e820cc882fb10b47f156ae9d40c89695e60ece1",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-25T14:10:27",
"content_id": "8e950561e5f9c7abfe18b6a0cb6b870b5d7a8df2",
"detected_licenses": [
"Unlicense"
],
"directory_id": "583db218abe670e93542da8c8bb9edfadf4d1f0e",
"extension": "c",
"filename": "patch.c",
"fork_events_count": 1,
"gha_created_at": "2019-03-16T13:00:41",
"gha_event_created_at": "2021-01-24T00:12:29",
"gha_language": "C",
"gha_license_id": "Unlicense",
"github_id": 175972567,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4356,
"license": "Unlicense",
"license_type": "permissive",
"path": "/utils/patch.c",
"provenance": "stackv2-0132.json.gz:105948",
"repo_name": "iblue/bluedelta",
"revision_date": "2021-01-25T14:10:27",
"revision_id": "8da903e114811ff01cfd4cd9bde2b1cad6a51052",
"snapshot_id": "7135dc920cb2a010512e26a2bab81f083a3f2830",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iblue/bluedelta/8da903e114811ff01cfd4cd9bde2b1cad6a51052/utils/patch.c",
"visit_date": "2021-06-22T07:35:55.619596"
} | stackv2 | #define _FILE_OFFSET_BITS 64
#define _POSIX_C_SOURCE 200808L
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include "format.h"
#include "patch.h"
static inline void copy(FILE* out, FILE* in, size_t bytes, int chunksize) {
uint8_t* buffer = malloc(chunksize);
while(1) {
int readbytes = bytes;
if(readbytes > chunksize) {
readbytes = chunksize;
}
int bytecnt = fread(buffer, 1, readbytes, in);
fwrite(buffer, bytecnt, 1, out);
if(bytecnt < readbytes) {
break;
}
bytes -= bytecnt;
if(bytes == 0) {
break;
}
}
free(buffer);
}
int patch(char* file1name, char *file2name, char *patchfilename, int chunksize, int verbose) {
FILE *file1 = fopen(file1name, "rb");
if(!file1) {
perror(file1name);
exit(2);
}
FILE *file2 = fopen(file2name, "wb");
if(!file2) {
perror(file2name);
exit(2);
}
FILE *patchfile = fopen(patchfilename, "rb");
if(!patchfile) {
perror(patchfilename);
exit(2);
}
// Read file header
if(verbose) {
printf(" DEBUG: Checking header...\n");
}
file_header_t header;
size_t records = fread(&header, sizeof(file_header_t), 1, patchfile);
if(records != 1) {
printf(" ERROR: %s is not valid patch file (fread on header failed)\n", patchfilename);
exit(128);
}
// Check header
if(header.magic != HEADER_MAGIC) {
printf(" ERROR: %s is not valid patch file (header magic incorrect)\n", patchfilename);
exit(128);
}
if(header.version != HEADER_VERSION) {
printf(" ERROR: %s is not valid patch file (version mismatch)\n", patchfilename);
exit(128);
}
if(header.incomplete != HEADER_INCOMPLETE_NO) {
printf(" ERROR: %s is not valid patch file (file incomplete flag set)\n", patchfilename);
exit(128);
}
if(header.chunk_size == 0) {
printf(" ERROR: %s is not valid patch file (invalid chunk size)\n", patchfilename);
exit(128);
}
// Check input file size
if(verbose) {
printf(" DEBUG: Checking input file size...\n");
}
fseeko(file1, 0, SEEK_END);
if(header.file1_size != ftello(file1)) {
printf(" ERROR: %s is not a valid input file (expected to be %" PRIu64 " bytes, is %" PRIu64 " bytes)\n", file2name, header.file1_size, ftello(file1));
exit(128);
}
fseeko(file1, 0, SEEK_SET);
data_record_t diff_record;
uint64_t position=0;
if(verbose) {
printf(" DEBUG: File positions:\n");
printf(" FILE1 (input): %" PRIu64 "\n", ftello(file1));
printf(" FILE2 (output): %" PRIu64 "\n", ftello(file2));
printf(" PATCH FILE: %" PRIu64 "\n\n", ftello(patchfile));
}
while(!feof(patchfile)) {
records = fread(&diff_record.position, sizeof(diff_record.position), 1, patchfile);
if(records != 1) {
if(feof(patchfile)) {
break;
}
printf(" ERROR: Could not read data record position structure (fread failed)\n");
exit(128);
}
records = fread(&diff_record.length, sizeof(diff_record.length), 1, patchfile);
if(records != 1) {
printf(" ERROR: Could not read data record position structure (fread failed)\n");
exit(128);
}
if(verbose) {
printf(" DEBUG: Found diff record. Position: %" PRIu64 ", length: %" PRIu64 "\n", diff_record.position, diff_record.length);
printf(" DEBUG: Currently I am at position %" PRIu64 "\n", position);
printf(" DEBUG: Copying %" PRIu64 " bytes from input file\n", diff_record.position - position);
}
// Since records are sequentially ordered, we now copy everything up until position
copy(file2, file1, diff_record.position - position, chunksize);
position += diff_record.position - position;
if(verbose) {
printf(" DEBUG: Appending %" PRIu64 " bytes from patch file\n", diff_record.length);
}
// And then the patched sector
copy(file2, patchfile, diff_record.length, chunksize);
position += diff_record.length;
fseeko(file1, position, SEEK_SET); // Skip this in the input file
if(verbose) {
printf(" DEBUG: File positions:\n");
printf(" FILE1 (input): %" PRIu64 "\n", ftello(file1));
printf(" FILE2 (output): %" PRIu64 "\n", ftello(file2));
printf(" PATCH FILE: %" PRIu64 "\n\n", ftello(patchfile));
}
}
// Copy the rest of the sectors
if(position != header.file2_size) {
copy(file2, file1, header.file2_size - position, chunksize);
}
// gg ez
return 0;
}
| 2.4375 | 2 |
2024-11-18T22:29:13.059445+00:00 | 2021-10-13T04:34:24 | ec34a1230af6da92edcf9e53a014590854d7420a | {
"blob_id": "ec34a1230af6da92edcf9e53a014590854d7420a",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-13T04:34:24",
"content_id": "d096798cf5d00d5c44ffde8f425ba7c36ae4a3c2",
"detected_licenses": [
"MIT"
],
"directory_id": "09cb578d09a81c03052c0abb09507d16aff0a890",
"extension": "c",
"filename": "writer.c",
"fork_events_count": 0,
"gha_created_at": "2021-10-13T04:41:14",
"gha_event_created_at": "2021-10-13T04:41:14",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 416591123,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 897,
"license": "MIT",
"license_type": "permissive",
"path": "/writer.c",
"provenance": "stackv2-0132.json.gz:106077",
"repo_name": "sidson1/Hacktoberfest-2022",
"revision_date": "2021-10-13T04:34:24",
"revision_id": "e7b798119ffc9f9bb4ffa62e680f643de1ca7cbc",
"snapshot_id": "548e8576851934f7dc5155ea25ba05714bce3c49",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sidson1/Hacktoberfest-2022/e7b798119ffc9f9bb4ffa62e680f643de1ca7cbc/writer.c",
"visit_date": "2023-08-12T21:07:18.896281"
} | stackv2 | #include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/mman.h>
#include<stdlib.h>
#include<string.h>
int main( ) {
int shmDesc;
char msg[100];
void * address;
shmDesc = shm_open("SharedMemory1", O_RDWR | O_CREAT, 0666);
if ( shmDesc == -1) {
perror("shm_open");
exit( -1 );
}
if ( ftruncate ( shmDesc , 512 ) < 0 ) {
perror("ftruncate");
exit( -1 );
}
address = mmap(NULL, 512, PROT_WRITE, MAP_SHARED, shmDesc, 0 );
if ( address == MAP_FAILED ) {
perror("mmap");
exit( -1 );
}
strcpy(msg , "Shared Memory Code");
memcpy (address, msg , strlen(msg)+1);
printf("The Writer process had written .... %s \n... to the Shared Memory\n ", msg);
return 0;
}
| 2.59375 | 3 |
2024-11-18T22:29:13.294376+00:00 | 2023-07-11T13:27:41 | 23b628c90e77a369247f274f2074ebddd6204162 | {
"blob_id": "23b628c90e77a369247f274f2074ebddd6204162",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-11T13:27:41",
"content_id": "8e8fe5d6e4ab15e7283387f31a20a369b4e91a01",
"detected_licenses": [
"BSD-3-Clause",
"PSF-2.0",
"Python-2.0",
"Zlib",
"BSD-4-Clause",
"BSD-2-Clause"
],
"directory_id": "5741e4e7e3fedc3ae03996843b2bcfec70e17049",
"extension": "c",
"filename": "bofloader.c",
"fork_events_count": 743,
"gha_created_at": "2014-04-03T21:18:24",
"gha_event_created_at": "2023-09-14T16:58:38",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 18418533,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3932,
"license": "BSD-3-Clause,PSF-2.0,Python-2.0,Zlib,BSD-4-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/c/meterpreter/source/extensions/bofloader/bofloader.c",
"provenance": "stackv2-0132.json.gz:106338",
"repo_name": "rapid7/metasploit-payloads",
"revision_date": "2023-07-11T13:27:41",
"revision_id": "dcaad10486e22885d0cbcbce508e3e763ce689e9",
"snapshot_id": "5981b44a1054d307d97b9cffcdbb559bfc690625",
"src_encoding": "UTF-8",
"star_events_count": 1674,
"url": "https://raw.githubusercontent.com/rapid7/metasploit-payloads/dcaad10486e22885d0cbcbce508e3e763ce689e9/c/meterpreter/source/extensions/bofloader/bofloader.c",
"visit_date": "2023-09-01T01:27:12.834909"
} | stackv2 | /*!
* @file bofloader.c
* @brief Entry point for the bofloader extension.
*/
#include "common.h"
#include "common_metapi.h"
#include <stdint.h>
#include "bofloader.h"
#include "beacon_compatibility.h"
#include "COFFLoader.h"
// Required so that use of the API works.
MetApi* met_api = NULL;
#define RDIDLL_NOEXPORT
#include "../../ReflectiveDLLInjection/dll/src/ReflectiveLoader.c"
/*! @brief The enabled commands for this extension. */
Command customCommands[] =
{
COMMAND_REQ(COMMAND_ID_BOFLOADER_EXECUTE, request_execute),
COMMAND_TERMINATOR
};
/*!
* @brief Handler for the generic command execution function.
* @param remote Pointer to the \c Remote instance.
* @param packet Pointer to the incoming packet.
* @returns \c ERROR_SUCCESS
*/
DWORD request_execute(Remote* remote, Packet* packet)
{
DWORD dwResult = ERROR_BAD_ARGUMENTS;
Packet* response = NULL;
PBYTE pBuffer = NULL;
DWORD dwBufferSize = 0;
LPSTR pBufferEntry = NULL;
PBYTE pArguments = NULL;
DWORD dwArgumentsSize = 0;
LPSTR pOutputData = NULL;
DWORD dwOutputDataSize = 0;
do
{
response = met_api->packet.create_response(packet);
if (!response)
BREAK_WITH_ERROR("[BOFLOADER] met_api->packet.create_response failed", ERROR_INVALID_HANDLE);
pBuffer = met_api->packet.get_tlv_value_raw(packet, TLV_TYPE_BOFLOADER_EXECUTE_BUFFER, &dwBufferSize);
if (!pBuffer)
BREAK_WITH_ERROR("[BOFLOADER] No EXECUTE_BUFFER was specified", ERROR_BAD_ARGUMENTS);
pBufferEntry = met_api->packet.get_tlv_value_string(packet, TLV_TYPE_BOFLOADER_EXECUTE_BUFFER_ENTRY);
if (!pBufferEntry)
BREAK_WITH_ERROR("[BOFLOADER] No EXECUTE_BUFFER_ENTRY was specified", ERROR_BAD_ARGUMENTS);
pArguments = met_api->packet.get_tlv_value_raw(packet, TLV_TYPE_BOFLOADER_EXECUTE_ARGUMENTS, &dwArgumentsSize);
if (!pArguments)
BREAK_WITH_ERROR("[BOFLOADER] No EXECUTE_ARGUMENTS was specified", ERROR_BAD_ARGUMENTS);
/* do our own check here to make sure the COFF data machine type matches, return ERROR_EXE_MACHINE_TYPE_MISMATCH on failure
*/
if (RunCOFF(pBufferEntry, pBuffer, dwBufferSize, pArguments, dwArgumentsSize))
BREAK_WITH_ERROR("[BOFLOADER] Buffer execution failed", ERROR_INVALID_DATA);
dprintf("[BOFLOADER] Buffer execution succeeded");
dprintf("[BOFLOADER] Getting output data");
pOutputData = BeaconGetOutputData(&dwOutputDataSize);
if (pOutputData) {
met_api->packet.add_tlv_string(response, TLV_TYPE_BOFLOADER_EXECUTE_RESULT, pOutputData);
SecureZeroMemory(pOutputData, dwOutputDataSize);
free(pOutputData);
}
dwResult = ERROR_SUCCESS;
} while (0);
if (response)
{
met_api->packet.transmit_response(dwResult, remote, response);
}
return dwResult;
}
/*!
* @brief Initialize the server extension.
* @param api Pointer to the Meterpreter API structure.
* @param remote Pointer to the remote instance.
* @return Indication of success or failure.
*/
DWORD InitServerExtension(MetApi* api, Remote* remote)
{
met_api = api;
SET_LOGGING_CONTEXT(api)
met_api->command.register_all(customCommands);
return ERROR_SUCCESS;
}
/*!
* @brief Deinitialize the server extension.
* @param remote Pointer to the remote instance.
* @return Indication of success or failure.
*/
DWORD DeinitServerExtension(Remote *remote)
{
met_api->command.deregister_all(customCommands);
return ERROR_SUCCESS;
}
/*!
* @brief Do a stageless initialisation of the extension.
* @param ID of the extension that the init was intended for.
* @param buffer Pointer to the buffer that contains the init data.
* @param bufferSize Size of the \c buffer parameter.
* @return Indication of success or failure.
*/
DWORD StagelessInit(UINT extensionId, const LPBYTE buffer, DWORD bufferSize)
{
return ERROR_SUCCESS;
}
/*!
* @brief Callback for when a command has been added to the meterpreter instance.
* @param commandId The ID of the command that has been added.
*/
VOID CommandAdded(UINT commandId)
{
}
| 2.265625 | 2 |
2024-11-18T22:29:13.395757+00:00 | 2023-05-01T11:58:27 | 8bc10341eaa7e1a226eb312e006a1aec2e171a5b | {
"blob_id": "8bc10341eaa7e1a226eb312e006a1aec2e171a5b",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-01T11:58:27",
"content_id": "851fe08d95ddaf9af7c0a9efd7d471454379fb02",
"detected_licenses": [
"MIT"
],
"directory_id": "28801f1d7a87fc01a489ef66194469b4ea5ab192",
"extension": "c",
"filename": "custloop.c",
"fork_events_count": 3,
"gha_created_at": "2012-06-29T01:10:44",
"gha_event_created_at": "2023-04-25T18:59:39",
"gha_language": "C++",
"gha_license_id": "NOASSERTION",
"github_id": 4827527,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8317,
"license": "MIT",
"license_type": "permissive",
"path": "/3rdparty/bass24-linux/custloop/custloop.c",
"provenance": "stackv2-0132.json.gz:106469",
"repo_name": "visualizersdotnl/cookiedough",
"revision_date": "2023-05-01T11:58:27",
"revision_id": "a360bef203e0ee3a5bd801f6c61b6031a595db6c",
"snapshot_id": "e41d58338fda87830f6cda24183a41a037edd8b3",
"src_encoding": "UTF-8",
"star_events_count": 14,
"url": "https://raw.githubusercontent.com/visualizersdotnl/cookiedough/a360bef203e0ee3a5bd801f6c61b6031a595db6c/3rdparty/bass24-linux/custloop/custloop.c",
"visit_date": "2023-05-14T23:04:53.459649"
} | stackv2 | /*
BASS custom looping example
Copyright (c) 2004-2021 Un4seen Developments Ltd.
*/
#include <gtk/gtk.h>
#include <glib/gthread.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#include <math.h>
#include "bass.h"
#define WIDTH 600 // display width
#define HEIGHT 201 // height (odd number for centre line)
#pragma pack(1)
typedef struct {
BYTE rgbRed, rgbGreen, rgbBlue;
} RGB;
#pragma pack()
GtkWidget *win;
DWORD chan;
DWORD bpp; // bytes per pixel
QWORD loop[2]; // loop start & end
GThread *scanthread;
BOOL killscan;
GtkWidget *waveda;
GdkPixbuf *wavepb;
RGB palette[HEIGHT / 2 + 1];
// display error messages
void Error(const char *es)
{
GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(win), GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s\n(error code: %d)", es, BASS_ErrorGetCode());
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
}
void WindowDestroy(GtkObject *obj, gpointer data)
{
gtk_main_quit();
}
void SetLoopStart(QWORD pos)
{
if (loop[1] && pos >= loop[1]) { // the loop end needs to move
loop[1] = pos + bpp;
BASS_ChannelSetPosition(chan, loop[1], BASS_POS_END);
}
BASS_ChannelSetPosition(chan, pos, BASS_POS_LOOP);
loop[0] = pos;
}
void SetLoopEnd(QWORD pos)
{
if (pos <= loop[0]) { // the loop start needs to move
loop[0] = pos - (bpp < pos ? bpp : pos);
BASS_ChannelSetPosition(chan, loop[0], BASS_POS_LOOP);
}
BASS_ChannelSetPosition(chan, pos, BASS_POS_END);
loop[1] = pos;
}
// scan the peaks
void *ScanPeaks(void *p)
{
DWORD decoder = (uintptr_t)p;
RGB *wavebuf = (RGB*)gdk_pixbuf_get_pixels(wavepb);
DWORD pos = 0;
float spp = BASS_ChannelBytes2Seconds(decoder, bpp); // seconds per pixel
while (!killscan) {
float peak[2];
int a;
BASS_ChannelGetLevelEx(decoder, peak, spp, BASS_LEVEL_STEREO); // scan peaks
for (a = 0; a < peak[0] * (HEIGHT / 2); a++)
wavebuf[(HEIGHT / 2 - 1 - a) * WIDTH + pos] = palette[1 + a]; // draw left peak
for (a = 0; a < peak[1] * (HEIGHT / 2); a++)
wavebuf[(HEIGHT / 2 + 1 + a) * WIDTH + pos] = palette[1 + a]; // draw right peak
pos++;
if (pos >= WIDTH) break; // reached end of display
if (!BASS_ChannelIsActive(decoder)) break; // reached end of channel
}
if (!killscan) {
DWORD size;
BASS_ChannelSetPosition(decoder, (QWORD)-1, BASS_POS_BYTE | BASS_POS_SCAN); // build seek table (scan to end)
size = BASS_ChannelGetAttributeEx(decoder, BASS_ATTRIB_SCANINFO, 0, 0); // get seek table size
if (size) { // got it
void *info = malloc(size); // allocate a buffer
BASS_ChannelGetAttributeEx(decoder, BASS_ATTRIB_SCANINFO, info, size); // get the seek table
BASS_ChannelSetAttributeEx(chan, BASS_ATTRIB_SCANINFO, info, size); // apply it to the playback channel
free(info);
}
}
BASS_StreamFree(decoder); // free the decoder
return NULL;
}
gboolean FileExtensionFilter(const GtkFileFilterInfo *info, gpointer data)
{
return !regexec((regex_t*)data, info->filename, 0, NULL, 0);
}
// select a file to play, and start scanning it
BOOL PlayFile()
{
BOOL ret = FALSE;
regex_t fregex;
GtkWidget *filesel; // file selector
GtkFileFilter *filter;
filesel = gtk_file_chooser_dialog_new("Open File", GTK_WINDOW(win), GTK_FILE_CHOOSER_ACTION_OPEN,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
filter = gtk_file_filter_new();
gtk_file_filter_set_name(filter, "Playable files");
regcomp(&fregex, "\\.(mo3|xm|mod|s3m|it|umx|mp[1-3]|ogg|wav|aif)$", REG_ICASE | REG_NOSUB | REG_EXTENDED);
gtk_file_filter_add_custom(filter, GTK_FILE_FILTER_FILENAME, FileExtensionFilter, &fregex, NULL);
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(filesel), filter);
filter = gtk_file_filter_new();
gtk_file_filter_set_name(filter, "All files");
gtk_file_filter_add_pattern(filter, "*");
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(filesel), filter);
if (gtk_dialog_run(GTK_DIALOG(filesel)) == GTK_RESPONSE_ACCEPT) {
char *file = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(filesel));
gtk_widget_hide(filesel);
if (!(chan = BASS_StreamCreateFile(FALSE, file, 0, 0, BASS_SAMPLE_LOOP))
&& !(chan = BASS_MusicLoad(FALSE, file, 0, 0, BASS_MUSIC_RAMP | BASS_MUSIC_POSRESET | BASS_MUSIC_PRESCAN | BASS_SAMPLE_LOOP, 1))) {
Error("Can't play file");
} else {
// create the bitmap
wavepb = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, WIDTH, HEIGHT);
{ // setup palette
RGB *pal = (RGB*)palette;
int a;
memset(palette, 0, sizeof(palette));
for (a = 1; a <= HEIGHT / 2; a++) {
pal[a].rgbRed = (255 * a) / (HEIGHT / 2);
pal[a].rgbGreen = 255 - pal[a].rgbRed;
}
}
bpp = BASS_ChannelGetLength(chan, BASS_POS_BYTE) / WIDTH; // bytes per pixel
{
DWORD bpp1 = BASS_ChannelSeconds2Bytes(chan, 0.001); // minimum 1ms per pixel
if (bpp < bpp1) bpp = bpp1;
}
BASS_ChannelPlay(chan, FALSE); // start playing
{ // create another channel to scan
DWORD chan2 = BASS_StreamCreateFile(FALSE, file, 0, 0, BASS_STREAM_DECODE);
if (!chan2) chan2 = BASS_MusicLoad(FALSE, file, 0, 0, BASS_MUSIC_DECODE, 1);
#if GLIB_CHECK_VERSION(2,32,0)
scanthread = g_thread_new(NULL, ScanPeaks, (void*)(uintptr_t)chan2); // start scanning in a new thread
#else
scanthread = g_thread_create(ScanPeaks, (void*)(uintptr_t)chan2, TRUE, NULL); // start scanning in a new thread
#endif
}
ret = TRUE;
}
g_free(file);
}
gtk_widget_destroy(filesel);
return ret;
}
void WindowButtonRelease(GtkWidget *obj, GdkEventButton *event, gpointer data)
{
if (event->type == GDK_BUTTON_RELEASE) {
if (event->button == 1) // set loop start
SetLoopStart(event->x * bpp);
else if (event->button == 3) // set loop end
SetLoopEnd(event->x * bpp);
else if (event->button == 2) // set current position
BASS_ChannelSetPosition(chan, event->x * bpp, BASS_POS_BYTE);
}
}
void DrawTimeLine(QWORD pos, DWORD col, DWORD y)
{
GdkGC *gc = waveda->style->fg_gc[GTK_WIDGET_STATE(waveda)];
DWORD wpos = pos / bpp;
GdkColor c = { 0, (col & 0xff) << 8, col & 0xff00, (col >> 8) & 0xff00 };
gdk_gc_set_rgb_fg_color(gc, &c);
gdk_draw_line(waveda->window, gc, wpos, 0, wpos, HEIGHT);
}
gboolean AreaExpose(GtkWidget *widget, GdkEventExpose *event, gpointer user)
{
GdkGC *gc = widget->style->fg_gc[GTK_WIDGET_STATE(waveda)];
GdkGCValues gcsave;
gdk_gc_get_values(gc, &gcsave);
gdk_draw_pixbuf(widget->window, gc, wavepb, 0, 0, 0, 0, -1, -1, GDK_RGB_DITHER_NONE, 0, 0);
DrawTimeLine(loop[0], 0xffff00, 12); // loop start
if (loop[1]) DrawTimeLine(loop[1], 0x00ffff, 24); // loop end
DrawTimeLine(BASS_ChannelGetPosition(chan, BASS_POS_BYTE), 0xffffff, 0); // current position
gdk_gc_set_values(gc, &gcsave, GDK_GC_FOREGROUND);
return FALSE;
}
gboolean TimerProc(gpointer data)
{
// refresh window
gtk_widget_queue_draw(waveda);
return TRUE;
}
int main(int argc, char* argv[])
{
#if !GLIB_CHECK_VERSION(2,32,0)
g_thread_init(NULL);
#endif
gtk_init(&argc, &argv);
// check the correct BASS was loaded
if (HIWORD(BASS_GetVersion()) != BASSVERSION) {
Error("An incorrect version of BASS was loaded");
return 0;
}
// initialize BASS
if (!BASS_Init(-1, 44100, 0, win, NULL)) {
Error("Can't initialize device");
return 0;
}
if (!PlayFile()) { // start a file playing
BASS_Free();
return 0;
}
// create the window
win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(win), GTK_WIN_POS_CENTER);
gtk_window_set_resizable(GTK_WINDOW(win), FALSE);
gtk_window_set_title(GTK_WINDOW(win), "BASS custom looping example (left-click to set loop start, right-click to set end)");
g_signal_connect(win, "destroy", GTK_SIGNAL_FUNC(WindowDestroy), NULL);
GtkWidget *ebox = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(win), ebox);
g_signal_connect(ebox, "button-release-event", GTK_SIGNAL_FUNC(WindowButtonRelease), NULL);
waveda = gtk_drawing_area_new();
gtk_widget_set_size_request(waveda, WIDTH, HEIGHT);
gtk_container_add(GTK_CONTAINER(ebox), waveda);
g_signal_connect(waveda, "expose-event", GTK_SIGNAL_FUNC(AreaExpose), NULL);
// setup update timer (10hz)
g_timeout_add(100, TimerProc, NULL);
gtk_widget_show_all(win);
gtk_main();
killscan = TRUE;
g_thread_join(scanthread); // wait for the scan thread
g_object_unref(wavepb);
BASS_Free();
return 0;
}
| 2.53125 | 3 |
2024-11-18T22:29:14.336553+00:00 | 2023-08-31T10:26:21 | 97fd207c44032e3bb835fff712c45166e3bfa8cc | {
"blob_id": "97fd207c44032e3bb835fff712c45166e3bfa8cc",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T10:26:21",
"content_id": "b4f2885b98df715f090233a7fdf50a775a47adeb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "abe704eb3b53944cdd6505f922f58558e334c589",
"extension": "c",
"filename": "tusb_cdc_acm.c",
"fork_events_count": 758,
"gha_created_at": "2017-08-08T12:32:16",
"gha_event_created_at": "2023-09-08T08:43:59",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 99690601,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13279,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/usb/esp_tinyuf2/cdc/tusb_cdc_acm.c",
"provenance": "stackv2-0132.json.gz:106859",
"repo_name": "espressif/esp-iot-solution",
"revision_date": "2023-08-31T10:26:21",
"revision_id": "2227f0ca21ab37df9cf9d74182fa84c52dffc76f",
"snapshot_id": "c25079eb26a8f54ddacd23689a7288533c721916",
"src_encoding": "UTF-8",
"star_events_count": 1612,
"url": "https://raw.githubusercontent.com/espressif/esp-iot-solution/2227f0ca21ab37df9cf9d74182fa84c52dffc76f/components/usb/esp_tinyuf2/cdc/tusb_cdc_acm.c",
"visit_date": "2023-09-01T15:06:17.000154"
} | stackv2 | /*
* SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include "esp_check.h"
#include "esp_err.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/ringbuf.h"
#include "tusb.h"
#include "tusb_cdc_acm.h"
#include "cdc.h"
#include "sdkconfig.h"
#define RX_UNREADBUF_SZ_DEFAULT 64 // buffer storing all unread RX data
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
typedef struct {
size_t rx_unread_buf_sz;
RingbufHandle_t rx_unread_buf;
SemaphoreHandle_t ringbuf_read_mux;
uint8_t *rx_tfbuf;
tusb_cdcacm_callback_t callback_rx;
tusb_cdcacm_callback_t callback_rx_wanted_char;
tusb_cdcacm_callback_t callback_line_state_changed;
tusb_cdcacm_callback_t callback_line_coding_changed;
} esp_tusb_cdcacm_t; /*!< CDC_ACM object */
static const char *TAG = "tusb_cdc_acm";
static inline esp_tusb_cdcacm_t *get_acm(tinyusb_cdcacm_itf_t itf)
{
esp_tusb_cdc_t *cdc_inst = tinyusb_cdc_get_intf(itf);
if (cdc_inst == NULL) {
return (esp_tusb_cdcacm_t *)NULL;
}
return (esp_tusb_cdcacm_t *)(cdc_inst->subclass_obj);
}
/* TinyUSB callbacks
********************************************************************* */
/* Invoked by cdc interface when line state changed e.g connected/disconnected */
void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
if (dtr && rts) { // connected
if (acm != NULL) {
ESP_LOGV(TAG, "Host connected to CDC no.%d.", itf);
} else {
ESP_LOGW(TAG, "Host is connected to CDC no.%d, but it is not initialized. Initialize it using `tinyusb_cdc_init`.", itf);
return;
}
} else { // disconnected
if (acm != NULL) {
ESP_LOGV(TAG, "Serial device is ready to connect to CDC no.%d", itf);
} else {
return;
}
}
if (acm) {
tusb_cdcacm_callback_t cb = acm->callback_line_state_changed;
if (cb) {
cdcacm_event_t event = {
.type = CDC_EVENT_LINE_STATE_CHANGED,
.line_state_changed_data = {
.dtr = dtr,
.rts = rts
}
};
cb(itf, &event);
}
}
}
/* Invoked when CDC interface received data from host */
void tud_cdc_rx_cb(uint8_t itf)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
if (acm) {
if (!acm->rx_unread_buf) {
ESP_LOGE(TAG, "There is no RX buffer created");
abort();
}
} else {
tud_cdc_n_read_flush(itf); // we have no place to store data, so just drop it
return;
}
while (tud_cdc_n_available(itf)) {
int read_res = tud_cdc_n_read( itf,
acm->rx_tfbuf,
CFG_TUD_CDC_RX_BUFSIZE );
int res = xRingbufferSend(acm->rx_unread_buf,
acm->rx_tfbuf,
read_res, 0);
if (res != pdTRUE) {
ESP_LOGW(TAG, "The unread buffer is too small, the data has been lost");
} else {
ESP_LOGV(TAG, "Sent %d bytes to the buffer", read_res);
}
}
if (acm) {
tusb_cdcacm_callback_t cb = acm->callback_rx;
if (cb) {
cdcacm_event_t event = {
.type = CDC_EVENT_RX
};
cb(itf, &event);
}
}
}
// Invoked when line coding is change via SET_LINE_CODING
void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const *p_line_coding)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
if (acm) {
tusb_cdcacm_callback_t cb = acm->callback_line_coding_changed;
if (cb) {
cdcacm_event_t event = {
.type = CDC_EVENT_LINE_CODING_CHANGED,
.line_coding_changed_data = {
.p_line_coding = p_line_coding,
}
};
cb(itf, &event);
}
} else {
return;
}
}
// Invoked when received `wanted_char`
void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
if (acm) {
tusb_cdcacm_callback_t cb = acm->callback_rx_wanted_char;
if (cb) {
cdcacm_event_t event = {
.type = CDC_EVENT_RX_WANTED_CHAR,
.rx_wanted_char_data = {
.wanted_char = wanted_char,
}
};
cb(itf, &event);
}
} else {
return;
}
}
esp_err_t tinyusb_cdcacm_register_callback(tinyusb_cdcacm_itf_t itf,
cdcacm_event_type_t event_type,
tusb_cdcacm_callback_t callback)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
if (acm) {
switch (event_type) {
case CDC_EVENT_RX:
acm->callback_rx = callback;
return ESP_OK;
case CDC_EVENT_RX_WANTED_CHAR:
acm->callback_rx_wanted_char = callback;
return ESP_OK;
case CDC_EVENT_LINE_STATE_CHANGED:
acm->callback_line_state_changed = callback;
return ESP_OK;
case CDC_EVENT_LINE_CODING_CHANGED:
acm->callback_line_coding_changed = callback;
return ESP_OK;
default:
ESP_LOGE(TAG, "Wrong event type");
return ESP_ERR_INVALID_ARG;
}
} else {
ESP_LOGE(TAG, "CDC-ACM is not initialized");
return ESP_ERR_INVALID_STATE;
}
}
esp_err_t tinyusb_cdcacm_unregister_callback(tinyusb_cdcacm_itf_t itf,
cdcacm_event_type_t event_type)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
if (!acm) {
ESP_LOGE(TAG, "Interface is not initialized. Use `tinyusb_cdc_init` for initialization");
return ESP_ERR_INVALID_STATE;
}
switch (event_type) {
case CDC_EVENT_RX:
acm->callback_rx = NULL;
return ESP_OK;
case CDC_EVENT_RX_WANTED_CHAR:
acm->callback_rx_wanted_char = NULL;
return ESP_OK;
case CDC_EVENT_LINE_STATE_CHANGED:
acm->callback_line_state_changed = NULL;
return ESP_OK;
case CDC_EVENT_LINE_CODING_CHANGED:
acm->callback_line_coding_changed = NULL;
return ESP_OK;
default:
ESP_LOGE(TAG, "Wrong event type");
return ESP_ERR_INVALID_ARG;
}
}
/*********************************************************************** TinyUSB callbacks*/
/* CDC-ACM
********************************************************************* */
static esp_err_t read_from_rx_unread_to_buffer(esp_tusb_cdcacm_t *acm, uint8_t *out_buf, size_t req_bytes, size_t *read_bytes)
{
uint8_t *buf = xRingbufferReceiveUpTo(acm->rx_unread_buf, read_bytes, 0, req_bytes);
if (buf) {
memcpy(out_buf, buf, *read_bytes);
vRingbufferReturnItem(acm->rx_unread_buf, (void *)(buf));
return ESP_OK;
} else {
return ESP_ERR_NO_MEM;
}
}
static esp_err_t ringbuf_mux_take(esp_tusb_cdcacm_t *acm)
{
if (xSemaphoreTake(acm->ringbuf_read_mux, 0) != pdTRUE) {
ESP_LOGW(TAG, "Read error: ACM is busy");
return ESP_ERR_INVALID_STATE;
}
return ESP_OK;
}
static esp_err_t ringbuf_mux_give(esp_tusb_cdcacm_t *acm)
{
BaseType_t ret = xSemaphoreGive(acm->ringbuf_read_mux);
assert(ret == pdTRUE);
return ESP_OK;
}
esp_err_t tinyusb_cdcacm_read(tinyusb_cdcacm_itf_t itf, uint8_t *out_buf, size_t out_buf_sz, size_t *rx_data_size)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
ESP_RETURN_ON_FALSE(acm, ESP_ERR_INVALID_STATE, TAG, "Interface is not initialized. Use `tinyusb_cdc_init` for initialization");
size_t read_sz;
/* Take a mutex to proceed two uninterrupted read operations */
ESP_RETURN_ON_ERROR(ringbuf_mux_take(acm), TAG, "ringbuf_mux_take failed");
esp_err_t res = read_from_rx_unread_to_buffer(acm, out_buf, out_buf_sz, &read_sz);
if (res != ESP_OK) {
ESP_RETURN_ON_ERROR(ringbuf_mux_give(acm), TAG, "ringbuf_mux_give failed");
return res;
}
*rx_data_size = read_sz;
/* Buffer's data can be wrapped, at that situations we should make another retrievement */
if (read_from_rx_unread_to_buffer(acm, out_buf + read_sz, out_buf_sz - read_sz, &read_sz) == ESP_OK) {
*rx_data_size += read_sz;
}
ESP_RETURN_ON_ERROR(ringbuf_mux_give(acm), TAG, "ringbuf_mux_give failed");
return ESP_OK;
}
size_t tinyusb_cdcacm_write_queue_char(tinyusb_cdcacm_itf_t itf, char ch)
{
if (!get_acm(itf)) { // non-initialized
return 0;
}
return tud_cdc_n_write_char(itf, ch);
}
size_t tinyusb_cdcacm_write_queue(tinyusb_cdcacm_itf_t itf, const uint8_t *in_buf, size_t in_size)
{
if (!get_acm(itf)) { // non-initialized
return 0;
}
const uint32_t size_available = tud_cdc_n_write_available(itf);
return tud_cdc_n_write(itf, in_buf, MIN(in_size, size_available));
}
static uint32_t tud_cdc_n_write_occupied(tinyusb_cdcacm_itf_t itf)
{
return CFG_TUD_CDC_TX_BUFSIZE - tud_cdc_n_write_available(itf);
}
esp_err_t tinyusb_cdcacm_write_flush(tinyusb_cdcacm_itf_t itf, uint32_t timeout_ticks)
{
if (!get_acm(itf)) { // non-initialized
return ESP_FAIL;
}
if (!timeout_ticks) { // if no timeout - nonblocking mode
int res = tud_cdc_n_write_flush(itf);
if (!res) {
ESP_LOGW(TAG, "flush failed (res: %d)", res);
return ESP_FAIL;
} else {
if (tud_cdc_n_write_occupied(itf)) {
ESP_LOGW(TAG, "remained data to flush!");
return ESP_FAIL;
} else {
return ESP_OK;
}
}
} else { // trying during the timeout
uint32_t ticks_start = xTaskGetTickCount();
uint32_t ticks_now = ticks_start;
while (1) { // loop until success or until the time runs out
ticks_now = xTaskGetTickCount();
if (!tud_cdc_n_write_occupied(itf)) { // if nothing to write - nothing to flush
break;
}
if (tud_cdc_n_write_flush(itf)) { // Success
break;
}
if ( (ticks_now - ticks_start) > timeout_ticks ) { // Time is up
ESP_LOGW(TAG, "Flush failed");
return ESP_ERR_TIMEOUT;
}
vTaskDelay(1);
}
return ESP_OK;
}
}
static esp_err_t alloc_obj(tinyusb_cdcacm_itf_t itf)
{
esp_tusb_cdc_t *cdc_inst = tinyusb_cdc_get_intf(itf);
cdc_inst->subclass_obj = calloc(1, sizeof(esp_tusb_cdcacm_t));
if (!cdc_inst->subclass_obj) {
return ESP_FAIL;
} else {
return ESP_OK;
}
}
static void free_obj(tinyusb_cdcacm_itf_t itf)
{
esp_tusb_cdc_t *cdc_inst = tinyusb_cdc_get_intf(itf);
free(cdc_inst->subclass_obj);
cdc_inst->subclass_obj = NULL;
}
esp_err_t tusb_cdc_acm_init(const tinyusb_config_cdcacm_t *cfg)
{
esp_err_t ret = ESP_OK;
int itf = (int)cfg->cdc_port;
/* Creating a CDC object */
const tinyusb_config_cdc_t cdc_cfg = {
.usb_dev = cfg->usb_dev,
.cdc_class = TUSB_CLASS_CDC,
.cdc_subclass.comm_subclass = CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL
};
ESP_RETURN_ON_ERROR(tinyusb_cdc_init(itf, &cdc_cfg), TAG, "tinyusb_cdc_init failed");
ESP_GOTO_ON_ERROR(alloc_obj(itf), out4, TAG, "alloc_obj failed");
/* Callbacks setting up*/
if (cfg->callback_rx) {
tinyusb_cdcacm_register_callback(itf, CDC_EVENT_RX, cfg->callback_rx);
}
if (cfg->callback_rx_wanted_char) {
tinyusb_cdcacm_register_callback(itf, CDC_EVENT_RX_WANTED_CHAR, cfg->callback_rx_wanted_char);
}
if (cfg->callback_line_state_changed) {
tinyusb_cdcacm_register_callback(itf, CDC_EVENT_LINE_STATE_CHANGED, cfg->callback_line_state_changed);
}
if (cfg->callback_line_coding_changed) {
tinyusb_cdcacm_register_callback( itf, CDC_EVENT_LINE_CODING_CHANGED, cfg->callback_line_coding_changed);
}
/* Buffers */
esp_tusb_cdcacm_t *acm = get_acm(itf);
acm->ringbuf_read_mux = xSemaphoreCreateMutex();
ESP_GOTO_ON_FALSE(acm->ringbuf_read_mux, ESP_ERR_NO_MEM, out3, TAG, "Creation of a ringbuf mutex failed");
acm->rx_tfbuf = malloc(CFG_TUD_CDC_RX_BUFSIZE);
ESP_GOTO_ON_FALSE(acm->rx_tfbuf, ESP_ERR_NO_MEM, out2, TAG, "Creation buffer error");
acm->rx_unread_buf_sz = cfg->rx_unread_buf_sz == 0 ? RX_UNREADBUF_SZ_DEFAULT : cfg->rx_unread_buf_sz;
acm->rx_unread_buf = xRingbufferCreate(acm->rx_unread_buf_sz, RINGBUF_TYPE_BYTEBUF);
ESP_GOTO_ON_FALSE(acm->rx_unread_buf, ESP_ERR_NO_MEM, out1, TAG, "Creation buffer error");
ESP_LOGD(TAG, "Comm Initialized buff:%d bytes", cfg->rx_unread_buf_sz);
return ESP_OK;
out1:
free(acm->rx_tfbuf);
out2:
vSemaphoreDelete(acm->ringbuf_read_mux);
out3:
free_obj(itf);
out4:
tinyusb_cdc_deinit(itf);
return ret;
}
bool tusb_cdc_acm_initialized(tinyusb_cdcacm_itf_t itf)
{
esp_tusb_cdcacm_t *acm = get_acm(itf);
if (acm) {
return true;
} else {
return false;
}
}
/*********************************************************************** CDC-ACM*/
| 2.234375 | 2 |
2024-11-18T22:29:14.893649+00:00 | 2018-10-13T02:01:30 | fdd3e16e72949e392090e729e3657288800e6c26 | {
"blob_id": "fdd3e16e72949e392090e729e3657288800e6c26",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-13T02:01:30",
"content_id": "25520e8f530b19a5af4d49d5ecce42b472dcf77d",
"detected_licenses": [
"MIT"
],
"directory_id": "b9b71a6303b7f1e5726f0584bbe33a25f1d87aae",
"extension": "h",
"filename": "trng.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 151630475,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2620,
"license": "MIT",
"license_type": "permissive",
"path": "/includes/application/trng.h",
"provenance": "stackv2-0132.json.gz:107119",
"repo_name": "arturnse/embedded-trng",
"revision_date": "2018-10-13T02:01:30",
"revision_id": "5c2a1d18a94ed28466d84d4d36a93e7895e1a9f8",
"snapshot_id": "bc7727c5207bdfd487a483314c2b3fa1f3b43f1d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/arturnse/embedded-trng/5c2a1d18a94ed28466d84d4d36a93e7895e1a9f8/includes/application/trng.h",
"visit_date": "2020-03-30T21:29:28.312597"
} | stackv2 |
#ifndef APPLICATION_TRNG_H_
#define APPLICATION_TRNG_H_
#include "api_config.h"
typedef enum
{
trng_simplest, ///< TRNG mais simples
trng_simple, ///< TRNG simples.
trng_allbytes, ///< TRNG processa todos os bytes dos clocks
}trng_t;
//!
//! Configura o TRNG escolhido
//!
//! \param eType Tipo do gerador que sera configurado.
//! \param ui8CfgBitQtt Configuracao de quantos bits serao gerados
//! por ciclo. Para usar o valor minimo basta informar \b 0 (zero)
//! \param ubUseSeed Antes de gerar os bytes, carrega uma seed
//! no pool.
//!
//! \return \b RES_SUCCESS caso a configuracao tenha sucesso.
//!
res_t
TRNG_Configure(trng_t eType, uint8_t ui8CfgBitQtt, bool_t ubUseSeed);
//!
//! Inicializa o modulo
//!
//! Eh necessario informar um buffer de dados.
//!
//! \param sPoolBuff e o ponteiro pro buffer de dados
//! \param ui32PoolBuffSz e o tamanho do buffer, em bytes.
//!
//! \return \b RES_SUCCESS caso a configuracao tenha sucesso
//!
res_t
TRNG_Init(void * pvPoolBuff, uint32_t ui32PoolBuffSz);
//!
//! Informa quantos bits aleatorios estao disponiveis
//!
//! \return Bits disponiveis para leitura
//!
uint32_t
TRNG_GetCountBits(void);
//!
//! Informa quanto tempo de processamento foi necessario
//! para ler os ultimos bit da entropia, em
//! microssegundos ( 1s * 10^(-6) )
//!
//! \return tempo em microssegundos necessario para capturar
//! um unico bit
//!
uint32_t
TRNG_GetBitCpuTimeUs(void);
//!
//! Informa quanto tempo de processamento foi necessario
//! para ler os ultimos bits da entropia, em
//! nanossegundos ( 1s * 10^(-9) )
//!
//! \return tempo em nanossegundos necessario para capturar
//! um unico bit
//!
uint32_t
TRNG_GetBitCpuTimeNs(void);
//!
//! Salva uma nova seed do TRNG.
//!
//! \return \b RES_SUCCESS caso a nova seed tenha sido salva
//!
res_t
TRNG_SeedSave(void);
//!
//! Informa a frequencia de chamada da funcao de captura
//! de entropia em Hz
//!
//! \param pui32freq Ponteiro para a frequencia
//! \param pui8bitQtt numero de bits capturados em cada
//! processamento
//!
//! \return \b RES_SUCCESS caso os valores retornados
//! sejam validos
//!
res_t
TRNG_GetFreqGenerationHz(uint32_t *pui32freq, uint8_t *pui8bitQtt);
//!
//! Le bytes gerados
//!
//! \param svBuff e o ponteiro que contera os dados
//! \param ui32BuffSz e o tamanho maximo do ponteiro, em bytes
//!
//! \return o numero de bytes copiados para o buffer.
//!
uint32_t
TRNG_Read(void * svBuff, uint32_t ui32BuffSz);
//!
//! Tarefa da aplicacao
//!
//! \return None.
//!
void TRNG_Task(void);
#endif /* APPLICATION_TRNG_H_ */
| 2.53125 | 3 |
2024-11-18T22:29:15.049838+00:00 | 2019-03-30T14:41:40 | fe2fe459e609737463331ca66738a0eb671debca | {
"blob_id": "fe2fe459e609737463331ca66738a0eb671debca",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-30T14:41:40",
"content_id": "a1f059ab13c70cfe2f198e7dffed0a782a7166f8",
"detected_licenses": [
"MIT"
],
"directory_id": "80c83b425f35cb531a5444ef87f124984d0b1d4f",
"extension": "c",
"filename": "abrir binario.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 177461915,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 670,
"license": "MIT",
"license_type": "permissive",
"path": "/Códigos/abrir binario.c",
"provenance": "stackv2-0132.json.gz:107247",
"repo_name": "MiguelazoDS/so2-openmp",
"revision_date": "2019-03-30T14:41:40",
"revision_id": "29598d833ab07cd4fb29a53294a2c7e887bd3ebb",
"snapshot_id": "525c9ed17b48663eb533625fe554d9b629c6005d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MiguelazoDS/so2-openmp/29598d833ab07cd4fb29a53294a2c7e887bd3ebb/Códigos/abrir binario.c",
"visit_date": "2020-05-01T12:16:02.748038"
} | stackv2 | /**@abrir binario.c
@author Cazajous Miguel A.
@date 13 May 2018.
@brief Socket TCP cliente.*/
#include <stdlib.h>
#include <stdio.h>
#define GATES 500
/**Función principal*/
int main(int argc, char const *argv[]) {
float *otro;
int i,algo;
FILE *file_in;
char *binary="binario_autoc";
file_in=fopen(binary,"rb");
while(fread(&algo,1,sizeof(int),file_in))
{
printf("cantidad %d\n", algo);
otro=malloc(2*algo*sizeof(float));
fread(otro, 2*algo, sizeof(float), file_in);
}
for (i = 0; i < GATES; i++) {
printf("cantidad %d, valores v %.10f, valores h %.10f\n", algo, *(otro+i), otro[GATES+i]);
}
fclose(file_in);
return 0;
}
| 2.765625 | 3 |
2024-11-18T22:29:15.230619+00:00 | 2020-08-08T12:17:52 | ca0af4dea7f5086dd141c9940449ca82ca7fd202 | {
"blob_id": "ca0af4dea7f5086dd141c9940449ca82ca7fd202",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-08T12:17:52",
"content_id": "17584e2b4bc284082ea4e8da16214eb46bd1bcaa",
"detected_licenses": [
"MIT"
],
"directory_id": "659d1a875afb86e38aff9992079ba0910bf9e648",
"extension": "c",
"filename": "LinkList.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": 3855,
"license": "MIT",
"license_type": "permissive",
"path": "/数据结构/C代码实现/线性表/链表/LinkList.c",
"provenance": "stackv2-0132.json.gz:107378",
"repo_name": "yanglin526000/Notes-for-myself",
"revision_date": "2020-08-08T12:17:52",
"revision_id": "52a5ec5614938f8f5ac4f30a77e18e91b4d9b5c3",
"snapshot_id": "a14be3ba8b11a752c874868ecc9d26b9140bc3ed",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yanglin526000/Notes-for-myself/52a5ec5614938f8f5ac4f30a77e18e91b4d9b5c3/数据结构/C代码实现/线性表/链表/LinkList.c",
"visit_date": "2022-12-03T00:56:29.000135"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include "LinkList.h"
// 使用头插法建立链表
LinkList List_HeadInsert(LinkList L)
{
LNode *s = NULL; ElemType x;
// 创建头结点
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;// 初始化为空链表
scanf("%d", &x);
while(x != 9999)
{
// 输入9999结束
s = (LinkList)malloc(sizeof(LNode));
// 结点数据赋值
s->data = x;
// 插入到头结点后
s->next = L->next;
L->next = s;
// 继续输入新结点data域值,输入9999即可结束新增结点
scanf("%d", &x);
}
return L;
}
// 使用尾插法建立链表
LinkList List_TailInsert(LinkList L)
{
ElemType x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
LNode *s = NULL;
// 为了记录最后一个元素的位置,引入辅助指针r,指向链表最后一个元素
LNode *r = L;
scanf("%d", &x);
while(x != 9999)
{
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
r->next = s;// 当前尾结点后新增元素
r = s;// r重新指向末尾
scanf("%d", &x);
}
// 尾结点指针域置空
r->next = NULL;
return L;
}
// 按序号查找元素,查找成功则返回指向第i个结点的指针,否则返回NULL
LNode *GetElem(LinkList L, int i)
{
int j = 1;
LNode *p = L->next;
if(i == 0)
{
return L;// 返回头指针,可用于插入1号位置时前驱0的返回值
}
if(i < 1)
{
return NULL;// 查找位置无效
}
while(p && j < i)
{
p = p->next;
j++;
}
return p;
}
// 按值查找元素,查找成功则返回该结点的指针,否则返回NULL
LNode *LocateElem(LinkList L, ElemType e)
{
LNode *p = L->next;
// 若恰好最后一个结点不是所查询的结点,以下代码失效
while(p->next && p->data != e)
{
p = p->next;// 继续往后查找
}
if(p->data != e)
{
// 处理以上代码短路情形
return NULL;
}
return p;
}
// 返回链表长度,长度为0表示链表仅含头结点
int ListLength(LinkList L)
{
int length = 0;
LNode *p = L->next;
while(p)
{
p = p->next;
length++;
}
return length;
}
// 在链表的第i个位置插入一个新的结点
LNode *ListInsert(LinkList L, int i, ElemType e)
{
// 检查插入位置的合法性
if(i < 1 || i > ListLength(L) + 1)
{
printf("插入位置有误,返回原链表\n");
return L;// 插入位置错误,原样返回
}
LNode *s = (LinkList)malloc(sizeof(LNode));
s->data = e;
LNode *p;
if((p = GetElem(L,i-1)))
{
s->next = p->next;
p->next = s;
}
return L;
}
// 删除链表中第i个位置的结点,并通过e返回该结点的信息
LNode *ListDelete(LinkList L, int i, ElemType *e)
{
// 检查删除位置的合法性
if(i < 1 || i > ListLength(L))
{
printf("删除位置有误,返回原链表\n");
return L;// 删除位置错误,原样返回
}
// 保存结点信息
*e = GetElem(L, i)->data;
LNode *p = GetElem(L, i-1);
LNode *q = NULL;
if(p)
{
q = p->next;
p->next = q->next;
free(q);
}
return L;
}
// 显示链表中各结点的逻辑关系
void ShowLinkListInfo(LinkList L)
{
int length = ListLength(L);
if(length == 0)
{
printf("L(&HeadNode)-->NULL\n");
}
if(length > 0)
{
LNode *p = L->next;
printf("L(&HeadNode)");
while(p->next)
{
printf("-->%d", p->data);
p = p->next;
}
printf("-->%d-->NULL", p->data);
printf("\nLength of LinkList : %d\n", length);
}
} | 3.71875 | 4 |
2024-11-18T22:29:15.390020+00:00 | 2023-06-05T21:51:04 | 5987938d772281985b736f964509dd087c57bed0 | {
"blob_id": "5987938d772281985b736f964509dd087c57bed0",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-05T21:51:04",
"content_id": "abcb61870db0852abe8259dff90931d858ea3ad9",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "bf1e11350796da46c9d9747d59ef0254619812c0",
"extension": "c",
"filename": "rvbap.c",
"fork_events_count": 1,
"gha_created_at": "2017-08-22T16:47:39",
"gha_event_created_at": "2022-01-21T17:06:19",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 101085755,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 31901,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/rvbap.c",
"provenance": "stackv2-0132.json.gz:107508",
"repo_name": "pd-externals/vbap",
"revision_date": "2023-06-05T21:51:04",
"revision_id": "23aab7b81b9b438b3d5d0f71d43505485cb54c58",
"snapshot_id": "601aa6b8c0ff5a81e543af17dbae7900cc49d36c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/pd-externals/vbap/23aab7b81b9b438b3d5d0f71d43505485cb54c58/rvbap.c",
"visit_date": "2023-06-12T17:03:07.393097"
} | stackv2 | /* rvbap.c vers 1.1
written by Ville Pulkki 1999-2003
Helsinki University of Technology
and
Unversity of California at Berkeley
and written by Olaf Matthes 2003, 2007
Pd port by Frank Barknecht
See copyright in file with name LICENSE.txt */
#include <math.h>
#ifdef MAXMSP
#include "ext.h" /* you must include this - it contains the external object's link to max */
#define t_float float
#endif
#ifdef PD
#include "m_pd.h" /* you must include this - it contains the external object's link to pure data */
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288
#endif
#define RVBAP_VERSION "rvbap v1.2.1 - (c) Olaf Matthes 2003-2007, based on vbap by Ville Pulkki"
#define MAX_LS_SETS 100 // maximum number of loudspeaker sets (triplets or pairs) allowed
#define MAX_LS_AMOUNT 55 // maximum amount of loudspeakers, can be increased
#ifdef _WINDOWS
#define sqrtf sqrt
#endif
#ifdef MAXMSP
typedef struct vbap /* This defines the object as an entity made up of other things */
{
t_object x_ob;
long x_azi; // panning direction azimuth
long x_ele; // panning direction elevation
t_float x_dist; // sound source distance (1.0-infinity)
void *x_outlet0;
void *x_outlet1;
void *x_outlet2;
void *x_outlet3;
void *x_outlet4;
t_float x_set_inv_matx[MAX_LS_SETS][9];// inverse matrix for each loudspeaker set
t_float x_set_matx[MAX_LS_SETS][9]; // matrix for each loudspeaker set
long x_lsset[MAX_LS_SETS][3]; // channel numbers of loudspeakers in each LS set
long x_lsset_available; // have loudspeaker sets been defined with define_loudspeakers
long x_lsset_amount; // amount of loudspeaker sets
long x_ls_amount; // amount of loudspeakers
long x_dimension; // 2 or 3
long x_spread; // spreading amount of virtual source (0-100)
t_float x_spread_base[3]; // used to create uniform spreading
t_float x_reverb_gs[MAX_LS_SETS]; // correction value for each loudspeaker set to get equal volume
} t_rvbap;
#endif
#ifdef PD
typedef struct vbap /* This defines the object as an entity made up of other things */
{
t_object x_ob;
t_float x_azi; // panning direction azimuth
t_float x_ele; // panning direction elevation
t_float x_dist; // sound source distance (1.0-infinity)
void *x_outlet0; /* outlet creation - inlets are automatic */
void *x_outlet1;
void *x_outlet2;
void *x_outlet3;
void *x_outlet4;
t_float x_set_inv_matx[MAX_LS_SETS][9];// inverse matrix for each loudspeaker set
t_float x_set_matx[MAX_LS_SETS][9]; // matrix for each loudspeaker set
long x_lsset[MAX_LS_SETS][3]; // channel numbers of loudspeakers in each LS set
long x_lsset_available; // have loudspeaker sets been defined with define_loudspeakers
long x_lsset_amount; // amount of loudspeaker sets
long x_ls_amount; // amount of loudspeakers
long x_dimension; // 2 or 3
t_float x_spread; // spreading amount of virtual source (0-100)
t_float x_spread_base[3]; // used to create uniform spreading
t_float x_reverb_gs[MAX_LS_SETS]; // correction value for each loudspeaker set to get equal volume
} t_rvbap;
#endif
// globals
static void new_spread_dir(t_rvbap *x, t_float spreaddir[3], t_float vscartdir[3], t_float spread_base[3]);
static void new_spread_base(t_rvbap *x, t_float spreaddir[3], t_float vscartdir[3]);
#ifdef MAXMSP
static void *rvbap_class;
static void rvbap_assist(t_rvbap *x, void *b, long m, long a, char *s);
static void rvbap_in1(t_rvbap *x, long n);
static void rvbap_in2(t_rvbap *x, long n);
static void rvbap_in3(t_rvbap *x, long n);
static void rvbap_in4(t_rvbap *x, long n);
static void rvbap_ft1(t_rvbap *x, double n);
static void rvbap_ft2(t_rvbap *x, double n);
static void rvbap_ft3(t_rvbap *x, double n);
static void rvbap_ft4(t_rvbap *x, double n);
#endif
#ifdef PD
static t_class *rvbap_class;
#endif
static void cross_prod(t_float v1[3], t_float v2[3], t_float v3[3]);
static void additive_vbap(t_float *final_gs, t_float cartdir[3], t_rvbap *x);
static void rvbap_bang(t_rvbap *x);
static void rvbap_matrix(t_rvbap *x, t_symbol *s, int ac, t_atom *av);
static void spread_it(t_rvbap *x, t_float *final_gs);
static void *rvbap_new(t_symbol *s, int ac, t_atom *av); // using A_GIMME - typed message list
static void vbap(t_float g[3], long ls[3], t_rvbap *x);
static void angle_to_cart(long azi, long ele, t_float res[3]);
static void cart_to_angle(t_float cvec[3], t_float avec[3]);
static void equal_reverb(t_rvbap *x, t_float *final_gs);
/* above are the prototypes for the methods/procedures/functions you will use */
#ifdef PD
void rvbap_setup(void)
{
rvbap_class = class_new(gensym("rvbap"), (t_newmethod)rvbap_new, 0, (short)sizeof(t_rvbap), 0, A_GIMME, 0);
/* rvbap_new = creation function, A_DEFLONG = its (optional) argument is a long (32-bit) int */
class_addbang(rvbap_class, rvbap_bang);
class_addmethod(rvbap_class, (t_method)rvbap_matrix, gensym("loudspeaker-matrices"), A_GIMME, 0);
}
#endif
#ifdef MAXMSP
int main(void)
{
setup((t_messlist **)&rvbap_class, (method)rvbap_new, 0L, (short)sizeof(t_rvbap), 0L, A_GIMME, 0);
/* rvbap_new = creation function, A_DEFLONG = its (optional) argument is a long (32-bit) int */
addmess((method)rvbap_assist, "assist", A_CANT, 0);
addbang((method)rvbap_bang); /* the procedure it uses when it gets a bang in the left inlet */
addinx((method)rvbap_in1, 1); /* the procedure for an int in the right inlet (inlet 1) */
addinx((method)rvbap_in2, 2); /* the procedure for an int in the right inlet (inlet 2) */
addinx((method)rvbap_in3, 3);
addinx((method)rvbap_in4, 4);
addftx((method)rvbap_ft1, 1); /* the procedure for an int in the right inlet (inlet 1) */
addftx((method)rvbap_ft2, 2); /* the procedure for an int in the right inlet (inlet 2) */
addftx((method)rvbap_ft3, 3);
addftx((method)rvbap_ft4, 4);
addmess((method)rvbap_matrix, "loudspeaker-matrices", A_GIMME, 0);
post(RVBAP_VERSION);
return 0;
}
static void rvbap_assist(t_rvbap *x, void *b, long m, long a, char *s)
{
switch(m){
case 1: // inlet
switch(a){
case 0:
sprintf(s, "define_loudspeakers / Bang to output actual values.");
break;
case 1:
sprintf(s, "(int) azimuth");
break;
case 2:
sprintf(s, "(int) elevation");
break;
case 3:
sprintf(s, "(int) spreading");
break;
case 4:
sprintf(s, "(t_float) distance");
break;
}
break;
case 2: // outlet
switch(a){
case 0:
sprintf(s, "(list) matrix~ values");
break;
case 1:
sprintf(s, "(int) actual azimuth");
break;
case 2:
sprintf(s, "(int) actual elevation");
break;
case 3:
sprintf(s, "(int) actual spreading");
break;
case 4:
sprintf(s, "(t_float) actual distance");
break;
}
break;
}
}
#endif
/* end MAXMSP */
static void angle_to_cart(long azi, long ele, t_float res[3])
/* converts angular coordinates to cartesian */
{
t_float atorad = (2.0 * M_PI / 360.0) ;
res[0] = cos((t_float) azi * atorad) * cos((t_float) ele * atorad);
res[1] = sin((t_float) azi * atorad) * cos((t_float) ele * atorad);
res[2] = sin((t_float) ele * atorad);
}
static void cart_to_angle(t_float cvec[3], t_float avec[3])
// converts cartesian coordinates to angular
{
t_float atorad = (t_float)(2.0 * M_PI / 360.0) ;
t_float pi = (t_float)M_PI;
t_float dist, atan_y_per_x, atan_x_pl_y_per_z;
t_float azi, ele;
if(cvec[0] == 0.0)
atan_y_per_x = pi / 2;
else
atan_y_per_x = atan(cvec[1] / cvec[0]);
azi = atan_y_per_x / atorad;
if(cvec[0] < 0.0)
azi += 180;
dist = sqrt(cvec[0]*cvec[0] + cvec[1]*cvec[1]);
if(cvec[2] == 0.0)
atan_x_pl_y_per_z = 0.0;
else
atan_x_pl_y_per_z = atan(cvec[2] / dist);
if(dist == 0.0){
if(cvec[2] < 0.0)
atan_x_pl_y_per_z = -pi/2.0;
else
atan_x_pl_y_per_z = pi/2.0;
}
ele = atan_x_pl_y_per_z / atorad;
dist = sqrt(cvec[0]*cvec[0] + cvec[1]*cvec[1] + cvec[2]*cvec[2]);
avec[0] = azi;
avec[1] = ele;
avec[2] = dist;
}
static void vbap(t_float g[3], long ls[3], t_rvbap *x)
{
/* calculates gain factors using loudspeaker setup and given direction */
t_float power;
int i, j, k, gains_modified;
t_float small_g;
t_float big_sm_g, gtmp[3];
long winner_set = 0;
t_float cartdir[3];
t_float new_cartdir[3];
t_float new_angle_dir[3];
long dim = x->x_dimension;
long neg_g_am, best_neg_g_am;
// transferring the azimuth angle to a decent value
while(x->x_azi > 180)
x->x_azi -= 360;
while(x->x_azi < -179)
x->x_azi += 360;
// transferring the elevation to a decent value
if(dim == 3){
while(x->x_ele > 180)
x->x_ele -= 360;
while(x->x_ele < -179)
x->x_ele += 360;
} else
x->x_ele = 0;
// go through all defined loudspeaker sets and find the set which
// has all positive values. If such is not found, set with largest
// minimum value is chosen. If at least one of gain factors of one LS set is negative
// it means that the virtual source does not lie in that LS set.
angle_to_cart(x->x_azi, x->x_ele, cartdir);
big_sm_g = -100000.0; // initial value for largest minimum gain value
best_neg_g_am = 3; // how many negative values in this set
for(i = 0; i < x->x_lsset_amount; i++){
small_g = 10000000.0;
neg_g_am = 3;
for(j = 0; j < dim; j++){
gtmp[j] = 0.0;
for(k = 0; k < dim; k++)
gtmp[j] += cartdir[k]* x->x_set_inv_matx[i][k+j*dim];
if(gtmp[j] < small_g)
small_g = gtmp[j];
if(gtmp[j] >= -0.01)
neg_g_am--;
}
if(small_g > big_sm_g && neg_g_am <= best_neg_g_am){
big_sm_g = small_g;
best_neg_g_am = neg_g_am;
winner_set = i;
g[0] = gtmp[0]; g[1] = gtmp[1];
ls[0] = x->x_lsset[i][0]; ls[1] = x->x_lsset[i][1];
if(dim == 3){
g[2] = gtmp[2];
ls[2] = x->x_lsset[i][2];
} else {
g[2] = 0.0;
ls[2] = 0;
}
}
}
// If chosen set produced a negative value, make it zero and
// calculate direction that corresponds to these new
// gain values. This happens when the virtual source is outside of
// all loudspeaker sets.
if(dim == 3){
gains_modified = 0;
for(i = 0; i < dim; i++){
if(g[i] < -0.01){
g[i] = 0.0001;
gains_modified = 1;
}
}
if(gains_modified == 1){
new_cartdir[0] = x->x_set_matx[winner_set][0] * g[0]
+ x->x_set_matx[winner_set][1] * g[1]
+ x->x_set_matx[winner_set][2] * g[2];
new_cartdir[1] = x->x_set_matx[winner_set][3] * g[0]
+ x->x_set_matx[winner_set][4] * g[1]
+ x->x_set_matx[winner_set][5] * g[2];
new_cartdir[2] = x->x_set_matx[winner_set][6] * g[0]
+ x->x_set_matx[winner_set][7] * g[1]
+ x->x_set_matx[winner_set][8] * g[2];
cart_to_angle(new_cartdir, new_angle_dir);
x->x_azi = (long) (new_angle_dir[0] + 0.5);
x->x_ele = (long) (new_angle_dir[1] + 0.5);
}
}
power = sqrt(g[0]*g[0] + g[1]*g[1] + g[2]*g[2]);
g[0] /= power;
g[1] /= power;
g[2] /= power;
}
static void cross_prod(t_float v1[3], t_float v2[3], t_float v3[3])
// vector cross product
{
t_float length;
v3[0] = (v1[1] * v2[2] ) - (v1[2] * v2[1]);
v3[1] = (v1[2] * v2[0] ) - (v1[0] * v2[2]);
v3[2] = (v1[0] * v2[1] ) - (v1[1] * v2[0]);
length = sqrt(v3[0]*v3[0] + v3[1]*v3[1] + v3[2]*v3[2]);
v3[0] /= length;
v3[1] /= length;
v3[2] /= length;
}
static void additive_vbap(t_float *final_gs, t_float cartdir[3], t_rvbap *x)
// calculates gains to be added to previous gains, used in
// multiple direction panning (source spreading)
{
t_float power;
int i, j, k, gains_modified;
t_float small_g;
t_float big_sm_g, gtmp[3];
long dim = x->x_dimension;
long neg_g_am, best_neg_g_am;
t_float g[3];
long ls[3] = {0, 0, 0};
big_sm_g = -100000.0;
best_neg_g_am = 3;
for(i = 0; i < x->x_lsset_amount; i++){
small_g = 10000000.0;
neg_g_am = 3;
for(j = 0; j < dim; j++){
gtmp[j] = 0.0;
for(k = 0; k < dim; k++)
gtmp[j] += cartdir[k]* x->x_set_inv_matx[i][k+j*dim];
if(gtmp[j] < small_g)
small_g = gtmp[j];
if(gtmp[j] >= -0.01)
neg_g_am--;
}
if(small_g > big_sm_g && neg_g_am <= best_neg_g_am){
big_sm_g = small_g;
best_neg_g_am = neg_g_am;
g[0] = gtmp[0]; g[1] = gtmp[1];
ls[0] = x->x_lsset[i][0]; ls[1] = x->x_lsset[i][1];
if(dim == 3){
g[2] = gtmp[2];
ls[2] = x->x_lsset[i][2];
} else {
g[2] = 0.0;
ls[2] = 0;
}
}
}
gains_modified = 0;
for(i = 0; i < dim; i++){
if(g[i] < -0.01){
gains_modified = 1;
}
}
if(gains_modified != 1){
if(dim == 3)
power = sqrt(g[0]*g[0] + g[1]*g[1] + g[2]*g[2]);
else
power = sqrt(g[0]*g[0] + g[1]*g[1]);
g[0] /= power;
g[1] /= power;
if(dim == 3)
g[2] /= power;
final_gs[ls[0]-1] += g[0];
final_gs[ls[1]-1] += g[1];
/* BUG FIX: this was causing negative indices with 2 dimensions so I
* made it only try when using 3 dimensions.
* 2006-08-13 <hans@at.or.at> */
if(dim == 3)
final_gs[ls[2]-1] += g[2];
}
}
static void new_spread_dir(t_rvbap *x, t_float spreaddir[3], t_float vscartdir[3], t_float spread_base[3])
// subroutine for spreading
{
t_float beta, m_gamma;
t_float a, b;
t_float pi = M_PI;
t_float power;
m_gamma = acos(vscartdir[0] * spread_base[0] +
vscartdir[1] * spread_base[1] +
vscartdir[2] * spread_base[2]) / pi * 180;
if(fabs(m_gamma) < 1){
angle_to_cart(x->x_azi + 90, 0, spread_base);
m_gamma = acos(vscartdir[0] * spread_base[0] +
vscartdir[1] * spread_base[1] +
vscartdir[2] * spread_base[2]) / pi * 180;
}
beta = 180 - m_gamma;
b = sin(x->x_spread * pi / 180) / sin(beta * pi / 180);
a = sin((180- x->x_spread - beta) * pi / 180) / sin(beta * pi / 180);
spreaddir[0] = a * vscartdir[0] + b * spread_base[0];
spreaddir[1] = a * vscartdir[1] + b * spread_base[1];
spreaddir[2] = a * vscartdir[2] + b * spread_base[2];
power=sqrt(spreaddir[0]*spreaddir[0] + spreaddir[1]*spreaddir[1]
+ spreaddir[2]*spreaddir[2]);
spreaddir[0] /= power;
spreaddir[1] /= power;
spreaddir[2] /= power;
}
static void new_spread_base(t_rvbap *x, t_float spreaddir[3], t_float vscartdir[3])
// subroutine for spreading
{
t_float d;
t_float pi = M_PI;
t_float power;
d = cos(x->x_spread / 180 * pi);
x->x_spread_base[0] = spreaddir[0] - d * vscartdir[0];
x->x_spread_base[1] = spreaddir[1] - d * vscartdir[1];
x->x_spread_base[2] = spreaddir[2] - d * vscartdir[2];
power = sqrt(x->x_spread_base[0]*x->x_spread_base[0] + x->x_spread_base[1]*x->x_spread_base[1]
+ x->x_spread_base[2]*x->x_spread_base[2]);
x->x_spread_base[0] /= power;
x->x_spread_base[1] /= power;
x->x_spread_base[2] /= power;
}
static void spread_it(t_rvbap *x, t_float *final_gs)
// apply the sound signal to multiple panning directions
// that causes some spreading.
// See theory in paper V. Pulkki "Uniform spreading of amplitude panned
// virtual sources" in WASPAA 99
{
t_float vscartdir[3];
t_float spreaddir[16][3];
t_float spreadbase[16][3];
long i, spreaddirnum;
t_float power;
if(x->x_dimension == 3){
spreaddirnum = 16;
angle_to_cart(x->x_azi, x->x_ele, vscartdir);
new_spread_dir(x, spreaddir[0], vscartdir, x->x_spread_base);
new_spread_base(x, spreaddir[0], vscartdir);
cross_prod(x->x_spread_base, vscartdir, spreadbase[1]); // four orthogonal dirs
cross_prod(spreadbase[1], vscartdir, spreadbase[2]);
cross_prod(spreadbase[2], vscartdir, spreadbase[3]);
// four between them
for(i=0;i<3;i++) spreadbase[4][i] = (x->x_spread_base[i] + spreadbase[1][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[5][i] = (spreadbase[1][i] + spreadbase[2][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[6][i] = (spreadbase[2][i] + spreadbase[3][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[7][i] = (spreadbase[3][i] + x->x_spread_base[i]) / 2.0;
// four at half spread angle
for(i=0;i<3;i++) spreadbase[8][i] = (vscartdir[i] + x->x_spread_base[i]) / 2.0;
for(i=0;i<3;i++) spreadbase[9][i] = (vscartdir[i] + spreadbase[1][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[10][i] = (vscartdir[i] + spreadbase[2][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[11][i] = (vscartdir[i] + spreadbase[3][i]) / 2.0;
// four at quarter spread angle
for(i=0;i<3;i++) spreadbase[12][i] = (vscartdir[i] + spreadbase[8][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[13][i] = (vscartdir[i] + spreadbase[9][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[14][i] = (vscartdir[i] + spreadbase[10][i]) / 2.0;
for(i=0;i<3;i++) spreadbase[15][i] = (vscartdir[i] + spreadbase[11][i]) / 2.0;
additive_vbap(final_gs, spreaddir[0], x);
for(i = 1; i < spreaddirnum; i++){
new_spread_dir(x, spreaddir[i], vscartdir, spreadbase[i]);
additive_vbap(final_gs, spreaddir[i], x);
}
} else if(x->x_dimension == 2){
spreaddirnum = 6;
angle_to_cart(x->x_azi - x->x_spread, 0, spreaddir[0]);
angle_to_cart(x->x_azi - x->x_spread / 2, 0, spreaddir[1]);
angle_to_cart(x->x_azi - x->x_spread / 4, 0, spreaddir[2]);
angle_to_cart(x->x_azi + x->x_spread / 4, 0, spreaddir[3]);
angle_to_cart(x->x_azi + x->x_spread / 2, 0, spreaddir[4]);
angle_to_cart(x->x_azi + x->x_spread, 0, spreaddir[5]);
for(i = 0; i < spreaddirnum; i++)
additive_vbap(final_gs, spreaddir[i], x);
} else
return;
if(x->x_spread > 70)
for(i = 0; i < x->x_ls_amount; i++){
final_gs[i] += (x->x_spread - 70) / 30.0 * (x->x_spread - 70) / 30.0 * 10.0;
}
for(i = 0, power = 0.0; i < x->x_ls_amount; i++){
power += final_gs[i] * final_gs[i];
}
power = sqrt(power);
for(i = 0; i < x->x_ls_amount; i++){
final_gs[i] /= power;
}
}
static void equal_reverb(t_rvbap *x, t_float *final_gs)
// calculate constant reverb gains for equally distributed
// reverb levels
// this is achieved by calculating gains for a sound source
// that is everywhere, i.e. present in all directions
{
t_float spreaddir[16][3];
long i, spreaddirnum;
t_float power;
if(x->x_dimension == 3){
spreaddirnum = 5;
// horizontal plane
angle_to_cart( 90, 0, spreaddir[0]);
angle_to_cart(180, 0, spreaddir[1]);
angle_to_cart(270, 0, spreaddir[2]);
// above, below
angle_to_cart(0, 90, spreaddir[3]);
angle_to_cart(0, -90, spreaddir[4]);
for(i = 1; i < spreaddirnum; i++){
additive_vbap(x->x_reverb_gs, spreaddir[i], x);
}
} else if(x->x_dimension == 2){
// for 2-D we calculate virtual sources
// every 45 degrees in a horizontal plane
spreaddirnum = 7;
angle_to_cart( 90, 0, spreaddir[0]);
angle_to_cart(180, 0, spreaddir[1]);
angle_to_cart(270, 0, spreaddir[2]);
angle_to_cart( 45, 0, spreaddir[3]);
angle_to_cart(135, 0, spreaddir[4]);
angle_to_cart(225, 0, spreaddir[5]);
angle_to_cart(315, 0, spreaddir[6]);
for(i = 0; i < spreaddirnum; i++)
additive_vbap(x->x_reverb_gs, spreaddir[i], x);
} else
return;
for(i = 0, power = 0.0; i < x->x_ls_amount; i++){
power += x->x_reverb_gs[i] * x->x_reverb_gs[i];
}
power = sqrt(power);
for(i = 0; i < x->x_ls_amount; i++){
final_gs[i] /= power;
}
}
static void rvbap_bang(t_rvbap *x)
// top level, vbap gains are calculated and outputted
{
t_atom at[MAX_LS_AMOUNT];
t_float g[3];
long ls[3];
long i;
t_float *final_gs, overdist, oversqrtdist;
final_gs = (t_float *) getbytes(x->x_ls_amount * sizeof(t_float));
#ifdef PD
// avoid NaN explosions, MAX does this in rvbap_in4() && rvbap_ft4()
if(x->x_dist < 1.0) {x->x_dist = 1.0;}
#endif
if(x->x_lsset_available == 1){
vbap(g, ls, x);
for(i = 0; i < x->x_ls_amount; i++)
final_gs[i] = 0.0;
for(i = 0; i < x->x_dimension; i++){
final_gs[ls[i]-1] = g[i];
}
if(x->x_spread != 0){
spread_it(x, final_gs);
}
overdist = 1 / x->x_dist;
oversqrtdist = 1 / sqrt(x->x_dist);
// build output for every loudspeaker
for(i = 0; i < x->x_ls_amount; i++){
// first, we output the gains for the direct (unreverberated) signals
// these just decrease as the distance increases
#ifdef MAXMSP
SETLONG(&at[0], i);
SETFLOAT(&at[1], (final_gs[i] / x->x_dist));
outlet_list(x->x_outlet0, NULL, 2, at);
#endif
#ifdef PD
SETFLOAT(&at[0], i);
SETFLOAT(&at[1], (final_gs[i] / x->x_dist));
outlet_list(x->x_outlet0, gensym("list"), 2, at);
#endif
// second, we output the gains for the reverberated signals
// these are made up of a global (all speakers) and a local part
#ifdef MAXMSP
SETLONG(&at[0], i+x->x_ls_amount); // direct signals come first in matrix~
SETFLOAT(&at[1], (((oversqrtdist / x->x_dist) * x->x_reverb_gs[i]) + (oversqrtdist * (1 - overdist) * final_gs[i])));
outlet_list(x->x_outlet0, NULL, 2, at);
#endif
#ifdef PD
SETFLOAT(&at[0], (i+x->x_ls_amount)); // direct signals come first in matrix~
SETFLOAT(&at[1], (((oversqrtdist / x->x_dist) * x->x_reverb_gs[i]) + (oversqrtdist * (1 - overdist) * final_gs[i])));
outlet_list(x->x_outlet0, gensym("list"), 2, at);
#endif
}
#ifdef MAXMSP
outlet_int(x->x_outlet1, x->x_azi);
outlet_int(x->x_outlet2, x->x_ele);
outlet_int(x->x_outlet3, x->x_spread);
outlet_float(x->x_outlet4, (double)x->x_dist);
#endif
#ifdef PD
outlet_float(x->x_outlet1, x->x_azi);
outlet_float(x->x_outlet2, x->x_ele);
outlet_float(x->x_outlet3, x->x_spread);
outlet_float(x->x_outlet4, x->x_dist);
#endif
}
else
post("rvbap: Configure loudspeakers first!");
freebytes(final_gs, x->x_ls_amount * sizeof(t_float)); // bug fix added 9/00
}
/*--------------------------------------------------------------------------*/
static void rvbap_matrix(t_rvbap *x, t_symbol *s, int ac, t_atom *av)
// read in loudspeaker matrices
// and calculate the gains for the equally distributed
// reverb signal part (i.e. global reverb)
{
long counter = 0;
long datapointer = 0;
long setpointer = 0;
long i;
long azi = x->x_azi, ele = x->x_ele; // store original values
t_float g[3];
long ls[3];
(void)s;
if(ac > 0)
#ifdef MAXMSP
if(av[datapointer].a_type == A_LONG){
x->x_dimension = av[datapointer++].a_w.w_long;
x->x_lsset_available = 1;
} else
#endif
{
if(av[datapointer].a_type == A_FLOAT){
x->x_dimension = (long)av[datapointer++].a_w.w_float;
x->x_lsset_available = 1;
} else {
post("Error in loudspeaker data!");
x->x_lsset_available = 0;
return;
}
//post("%d",deb++);
}
if(ac > 1)
#ifdef MAXMSP
if(av[datapointer].a_type == A_LONG)
x->x_ls_amount = av[datapointer++].a_w.w_long;
else
#endif
if(av[datapointer].a_type == A_FLOAT)
x->x_ls_amount = (long) av[datapointer++].a_w.w_float;
else {
post("rvbap: Error in loudspeaker data!");
x->x_lsset_available = 0;
return;
}
else
x->x_lsset_available = 0;
if(x->x_dimension == 3)
counter = (ac - 2) / ((x->x_dimension * x->x_dimension*2) + x->x_dimension);
if(x->x_dimension == 2)
counter = (ac - 2) / ((x->x_dimension * x->x_dimension) + x->x_dimension);
x->x_lsset_amount = counter;
if(counter <= 0){
post("rvbap: Error in loudspeaker data!");
x->x_lsset_available = 0;
return;
}
while(counter-- > 0){
for(i = 0; i < x->x_dimension; i++){
#ifdef MAXMSP
if(av[datapointer].a_type == A_LONG)
#endif
#ifdef PD
if(av[datapointer].a_type == A_FLOAT)
#endif
{
x->x_lsset[setpointer][i] = (long)av[datapointer++].a_w.w_float;
}
else {
post("rvbap: Error in loudspeaker data!");
x->x_lsset_available = 0;
return;
}
}
for(i = 0; i < x->x_dimension * x->x_dimension; i++){
if(av[datapointer].a_type == A_FLOAT){
x->x_set_inv_matx[setpointer][i] = av[datapointer++].a_w.w_float;
}
else {
post("rvbap: Error in loudspeaker data!");
x->x_lsset_available = 0;
return;
}
}
if(x->x_dimension == 3){
for(i = 0; i < x->x_dimension * x->x_dimension; i++){
if(av[datapointer].a_type == A_FLOAT){
x->x_set_matx[setpointer][i] = av[datapointer++].a_w.w_float;
}
else {
post("rvbap: Error in loudspeaker data!");
x->x_lsset_available = 0;
return;
}
}
}
setpointer++;
}
// now configure static reverb correction values...
x->x_azi = x->x_ele = 0;
vbap(g, ls, x);
for(i = 0; i < x->x_ls_amount; i++){
x->x_reverb_gs[i] = 0.0;
}
for(i = 0; i < x->x_dimension; i++){
x->x_reverb_gs[ls[i]-1] = g[i];
// post("reverb gs #%d = %f", i, x->x_reverb_gs[i]);
}
equal_reverb(x,x->x_reverb_gs);
/* for(i=0; i<x->x_ls_amount; i++){ // do this for every speaker
post("reverb gs #%d = %f", i, x->x_reverb_gs[i]);
} */
post("rvbap: Loudspeaker setup configured!");
x->x_azi = azi; // restore original panning directions
x->x_ele = ele;
}
#ifdef MAXMSP
static void rvbap_in1(t_rvbap *x, long n) /* x = the instance of the object, n = the int received in the right inlet */
// panning angle azimuth
{
x->x_azi = n; /* store n in a global variable */
}
static void rvbap_in2(t_rvbap *x, long n) /* x = the instance of the object, n = the int received in the right inlet */
// panning angle elevation
{
x->x_ele = n; /* store n in a global variable */
}
/*--------------------------------------------------------------------------*/
static void rvbap_in3(t_rvbap *x, long n) /* x = the instance of the object, n = the int received in the right inlet */
// spread amount
{
if(n < 0) n = 0;
if(n > 100) n = 100;
x->x_spread = n; /* store n in a global variable */
}
/*--------------------------------------------------------------------------*/
static void rvbap_in4(t_rvbap *x, long n) /* x = the instance of the object, n = the int received in the right inlet */
// distance
{
if(n < 1) n = 1;
x->x_dist = (t_float)n; /* store n in a global variable */
}
static void rvbap_ft1(t_rvbap *x, double n) /* x = the instance of the object, n = the int received in the right inlet */
// panning angle azimuth
{
x->x_azi = (long)n; /* store n in a global variable */
}
static void rvbap_ft2(t_rvbap *x, double n) /* x = the instance of the object, n = the int received in the right inlet */
// panning angle elevation
{
x->x_ele = (long)n; /* store n in a global variable */
}
/*--------------------------------------------------------------------------*/
static void rvbap_ft3(t_rvbap *x, double n) /* x = the instance of the object, n = the int received in the right inlet */
// spreading
{
if(n < 0.0) n = 0.0;
if(n > 100.0) n = 100.0;
x->x_spread = (long) n; /* store n in a global variable */
}
/*--------------------------------------------------------------------------*/
static void rvbap_ft4(t_rvbap *x, double n) /* x = the instance of the object, n = the int received in the right inlet */
// distance
{
if(n < 1.0) n = 1.0;
x->x_dist = (t_float)n; /* store n in a global variable */
}
#endif // MAXMSP
static void *rvbap_new(t_symbol *s, int ac, t_atom *av)
/* create new instance of object... MUST send it an int even if you do nothing with this int!! */
{
t_rvbap *x;
(void)s;
#ifdef MAXMSP
x = (t_rvbap *)newobject(rvbap_class);
t_floatin(x, 4); /* takes the distance */
intin(x, 3);
intin(x, 2); /* create a second (int) inlet... remember right-to-left ordering in Max */
intin(x, 1); /* create a second (int) inlet... remember right-to-left ordering in Max */
x->x_outlet4 = floatout(x); /* distance */
x->x_outlet3 = intout(x);
x->x_outlet2 = intout(x); /* create an (int) outlet - rightmost outlet first... */
x->x_outlet1 = intout(x); /* create an (int) outlet */
x->x_outlet0 = listout(x); /* create a (list) outlet */
#endif
#ifdef PD
x = (t_rvbap *)pd_new(rvbap_class);
floatinlet_new(&x->x_ob, &x->x_azi);
floatinlet_new(&x->x_ob, &x->x_ele);
floatinlet_new(&x->x_ob, &x->x_spread);
floatinlet_new(&x->x_ob, &x->x_dist);
x->x_outlet0 = outlet_new(&x->x_ob, gensym("list"));
x->x_outlet1 = outlet_new(&x->x_ob, gensym("float"));
x->x_outlet2 = outlet_new(&x->x_ob, gensym("float"));
x->x_outlet3 = outlet_new(&x->x_ob, gensym("float"));
x->x_outlet4 = outlet_new(&x->x_ob, gensym("float"));
#endif
x->x_azi = 0;
x->x_ele = 0;
x->x_dist = 1.0;
x->x_spread_base[0] = 0.0;
x->x_spread_base[1] = 1.0;
x->x_spread_base[2] = 0.0;
x->x_spread = 0;
x->x_lsset_available = 0;
if(ac > 0){
#ifdef MAXMSP
if(av[0].a_type == A_LONG)
x->x_azi = av[0].a_w.w_long;
else
#endif
if(av[0].a_type == A_FLOAT)
x->x_azi = av[0].a_w.w_float;
}
if(ac > 1){
#ifdef MAXMSP
if(av[1].a_type == A_LONG)
x->x_ele = av[1].a_w.w_long;
else
#endif
if(av[1].a_type == A_FLOAT)
x->x_ele = av[1].a_w.w_float;
}
if(ac > 2){
#ifdef MAXMSP
if(av[2].a_type == A_LONG)
x->x_dist = (float)av[2].a_w.w_long;
else
#endif
if(av[2].a_type == A_FLOAT)
x->x_dist = av[2].a_w.w_float;
}
return(x); /* return a reference to the object instance */
}
| 2.171875 | 2 |
2024-11-18T22:29:15.525391+00:00 | 2018-04-09T20:20:31 | 37b99082648dfba03194d337934253a496d17988 | {
"blob_id": "37b99082648dfba03194d337934253a496d17988",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-09T20:56:17",
"content_id": "1c86296c251005b1b9a4fb02a72d0c2d8e544d25",
"detected_licenses": [
"MIT"
],
"directory_id": "15fdf000f8db57e6b1212c04d6f31a16777340e3",
"extension": "c",
"filename": "led.c",
"fork_events_count": 0,
"gha_created_at": "2018-02-03T15:45:47",
"gha_event_created_at": "2018-02-03T15:45:47",
"gha_language": null,
"gha_license_id": null,
"github_id": 120104707,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1045,
"license": "MIT",
"license_type": "permissive",
"path": "/peons/src/led.c",
"provenance": "stackv2-0132.json.gz:107637",
"repo_name": "Ramlz/omfk",
"revision_date": "2018-04-09T20:20:31",
"revision_id": "f385c6523dd7bdbf09115c4328d5ee881162ed15",
"snapshot_id": "5ad875610eba3c92e97980cc3d89b6037c3ac1fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ramlz/omfk/f385c6523dd7bdbf09115c4328d5ee881162ed15/peons/src/led.c",
"visit_date": "2021-05-08T15:03:52.614648"
} | stackv2 | #include "peons/led.h"
#include "platform/gpio.h"
#include "platform/clock.h"
#include "board/cfg.h"
/**
* GPIO interface with DHT pin
*/
static gpio_iface *led_gpio_iface = NULL;
static bool led_active = true;
static uint32_t led_interval = 250;
/**
* @brief initializes GPIO pin connected to LED
*/
static void led_init(void) {
//! create GPIO port interface
led_gpio_iface = gpio_iface_get(LED_GPIO_PORT);
//! init GPIO pin connected to led
led_gpio_iface->init(led_gpio_iface, LED_GPIO_PIN, GPIO_OTYPE_PUSH_PULL,
GPIO_MODE_OUTPUT, GPIO_SPEED_FAST, GPIO_PUPD_NO, NULL);
}
void led_enable(bool enable) {
if (enable) {
led_init();
led_active = true;
} else {
led_active = false;
}
}
void led_set_interval(uint32_t interval) {
led_interval = interval;
}
void led_loop(void) {
led_init();
while (true) {
if (led_active) {
led_gpio_iface->toggle(led_gpio_iface, LED_GPIO_PIN);
clock_dly_msecs(led_interval);
}
}
}
| 2.453125 | 2 |
2024-11-18T22:29:15.696200+00:00 | 2019-04-26T01:03:30 | 9e6d832566b3c1e8fee893736e231244a1f69255 | {
"blob_id": "9e6d832566b3c1e8fee893736e231244a1f69255",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-26T01:03:30",
"content_id": "3ec3fa1b5ae7cdd815acbd82a3886d0d6b976f89",
"detected_licenses": [
"MIT"
],
"directory_id": "759421747f8b8398f91e30421d9c1d17278ce190",
"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": 183530272,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2899,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0132.json.gz:107897",
"repo_name": "maruwo/mutex",
"revision_date": "2019-04-26T01:03:30",
"revision_id": "e6258d9bddee643bafe4898314f354c17885e6d1",
"snapshot_id": "76219813fa75c61a7941fb42eea010438841cffa",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/maruwo/mutex/e6258d9bddee643bafe4898314f354c17885e6d1/main.c",
"visit_date": "2020-05-17T05:17:45.757879"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <pthread.h>
static pthread_mutex_t* mutex;
static int shmid;
static bool created = true;
void mutex_demo(void)
{
int i;
struct timeval now;
struct tm *local;
char str[32];
for (i = 0; i < 10; i++)
{
// ロック
if (pthread_mutex_lock(mutex) != 0) {
return;
}
gettimeofday(&now, NULL);
local = localtime( &now.tv_sec );
printf("%02d:%02d:%02d.%06ld : count=%d, pid=%d\n",
local->tm_hour, local->tm_min, local->tm_sec, now.tv_usec,
i+1, getpid());
sleep(1);
// アンロック
if (pthread_mutex_unlock(mutex) != 0) {
return;
}
usleep( 1 * 1000 );
}
}
bool mutex_init(void)
{
key_t key;
pthread_mutexattr_t mat;
char path[256];
// 自分のフルパスを取得
readlink( "/proc/self/exe", path, sizeof(path) );
// 自分のパスを元にkeyを作成
key = ftok(path, 1);
if( key == (key_t)-1 ) {
return false;
}
// 共有メモリ作成
shmid = shmget(key, sizeof(pthread_mutex_t), IPC_CREAT | IPC_EXCL | 0600);
if (shmid < 0) {
if (errno != EEXIST) {
// エラー
return false;
}
// すでに作成済みの場合はID取得
shmid = shmget(key, sizeof(pthread_mutex_t), 0600);
created = false;
}
// 共有メモリを取得
mutex = (pthread_mutex_t*)shmat(shmid, NULL, 0);
if (mutex == (pthread_mutex_t*)-1) {
return false;
}
// 新規作成のため初期化する
if (created) {
// mutex 属性オブジェクト attr を初期化し、すべての属性をデフォルトの値に設定
if( pthread_mutexattr_init(&mat) != 0 ) {
return false;
}
// mutex 属性オブジェクト attr の属性 pshared を 設定
if (pthread_mutexattr_setpshared(&mat, PTHREAD_PROCESS_SHARED) != 0) {
return false;
}
// mat で指定された mutex 属性オブジェクトに従って初期化する
if (pthread_mutex_init(mutex, &mat) != 0) {
return false;
}
}
return true;
}
void main(void)
{
int pid, status;
bool result = false;
// 初期化
if( !mutex_init() ) {
goto ERROR;
}
// mutex デモ
pid = fork();
mutex_demo();
if( pid == 0 ) {
exit(0);
}
waitpid(pid, &status, 0);
result = true;
ERROR:
if( !created ) {
// mutex 破棄
pthread_mutex_destroy(mutex);
// 共有メモリ破棄
shmctl(shmid, IPC_RMID, NULL);
}
if( !result ) {
exit(1);
}
}
| 2.78125 | 3 |
2024-11-18T22:29:15.769658+00:00 | 2020-03-07T02:35:22 | 47b5251282da2d9f8f91bedaa36a28bfa4a0c6ac | {
"blob_id": "47b5251282da2d9f8f91bedaa36a28bfa4a0c6ac",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-07T02:35:22",
"content_id": "4c999db3baba47f431833244c33c7f9959e4c4a7",
"detected_licenses": [
"MIT"
],
"directory_id": "9b12573486fb5beb893b96e89d3f322fbbeaf01b",
"extension": "c",
"filename": "lab.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-07T02:34:21",
"gha_event_created_at": "2020-03-07T02:34:22",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 245555067,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1196,
"license": "MIT",
"license_type": "permissive",
"path": "/gdb-py/lab.c",
"provenance": "stackv2-0132.json.gz:108025",
"repo_name": "archshift/C-Tycat",
"revision_date": "2020-03-07T02:35:22",
"revision_id": "d91471642cabee153617602e492eaf68d78c08a3",
"snapshot_id": "0aea22c3f045d27b13f1d3c717655a6f662ea6fb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/archshift/C-Tycat/d91471642cabee153617602e492eaf68d78c08a3/gdb-py/lab.c",
"visit_date": "2021-02-26T21:58:12.375621"
} | stackv2 | /*
Tycat a basic types.
Copyright (C) 2018, Guillaume Gonnet
This project is under the MIT License
*/
#include <stdio.h>
#include <stdlib.h>
#define debugger asm volatile ("int3;")
struct Container {
const char *string;
char c;
int integer;
char **array;
char fixed_str[20];
};
// A simple linked cell
struct cell {
int age;
struct cell *next;
};
// The head of the list
struct list {
struct cell *top;
};
// Append a new cell into the list
void list_append(struct list *list, int age)
{
struct cell *cell = malloc(sizeof(struct cell));
struct cell *it = list->top;
cell->age = age;
cell->next = NULL;
if (it == NULL) {
list->top = cell;
}
else {
while (it->next) it = it->next;
it->next = cell;
}
}
int main()
{
struct Container c = {
.string = "Hello, my name is Guillaume.",
.integer = 42,
.fixed_str = "A short text"
};
struct Container *ptr = &c;
int myint = 1337;
struct list list;
list_append(&list, 21);
list_append(&list, 86);
list_append(&list, 27);
list_append(&list, 1337);
// Break here
debugger;
}
| 3.21875 | 3 |
2024-11-18T22:29:16.094123+00:00 | 2018-08-07T11:54:47 | 73b76d82af49e8fba18615c61f99eaa8194643de | {
"blob_id": "73b76d82af49e8fba18615c61f99eaa8194643de",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-07T11:54:47",
"content_id": "40b980e22966ed976f0cebb48a2e541c90dc6579",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "bcc558cf76d46e8fdb28d9b9e5b777ad45cf22a7",
"extension": "c",
"filename": "locktool.c",
"fork_events_count": 0,
"gha_created_at": "2018-07-27T07:55:48",
"gha_event_created_at": "2018-07-27T07:55:48",
"gha_language": null,
"gha_license_id": "BSD-2-Clause",
"github_id": 142546619,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2568,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/locktool.c",
"provenance": "stackv2-0132.json.gz:108285",
"repo_name": "void-main/s3blkdev",
"revision_date": "2018-08-07T11:54:47",
"revision_id": "5dfeda99389657f5cbe778eee49b151e24c2cc2a",
"snapshot_id": "40a72465583ba3545f2865f8be940151f3dacf33",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/void-main/s3blkdev/5dfeda99389657f5cbe778eee49b151e24c2cc2a/locktool.c",
"visit_date": "2020-03-24T06:55:36.546038"
} | stackv2 | #define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <err.h>
#include "s3blkdev.h"
/* lock a chunk file to hinder s3blkdev and/or syncer */
static char *lock_type_to_string (int type)
{
switch (type) {
case F_RDLCK: return "F_RDLCK";
case F_WRLCK: return "F_WRLCK";
default: return "<UNKNOWN>";
}
}
static char *lock_whence_to_string (int whence)
{
switch (whence) {
case SEEK_SET: return "SEEK_SET";
case SEEK_CUR: return "SEEK_CUR";
case SEEK_END: return "SEEK_END";
default : return "<UNKNOWN>";
}
}
static int do_lock (int fd, int cmd, int type, off_t start, off_t end)
{
int result;
struct flock flk;
flk.l_type = type;
flk.l_whence = SEEK_SET;
flk.l_start = start;
flk.l_len = end - start;
flk.l_pid = 0;
if ((result = fcntl(fd, cmd, &flk)) != 0)
warn("fcntl()");
if ((cmd == F_OFD_GETLK) && (flk.l_type != F_UNLCK)) {
printf("At least one lock is being held:\n\n"
"Type: %s\n"
"Whence: %s\n"
"Start: %li\n"
"Length: %li\n"
"PID: %i\n\n",
lock_type_to_string(flk.l_type),
lock_whence_to_string(flk.l_whence),
flk.l_start, flk.l_len, flk.l_pid);
}
return result;
}
int main (int argc, char **argv)
{
int fd, i, type, cmd;
char buf[2], *chunk;
off_t start, end;
if (argc != 6)
errx(1, "locktool V" S3BLKDEV_VERSION "\n\n"
"Usage: locktool <g|l|w> <r|w> <start> <end> /path/to/chunk");
switch (argv[1][0]) {
case 'l': cmd = F_OFD_SETLK; break; /* try to lock chunk file */
case 'w': cmd = F_OFD_SETLKW; break; /* lock and possibly wait for lock */
default: cmd = F_OFD_GETLK; break; /* report lock status */
}
type = (argv[2][0] == 'w' ? F_WRLCK : F_RDLCK);
start = atol(argv[3]);
end = atol(argv[4]);
chunk = argv[5];
fd = open(chunk, O_RDWR);
if (fd < 0)
err(1, "open(): %s", chunk);
switch (cmd) {
case F_OFD_SETLKW:
do_lock(fd, F_OFD_GETLK, type, start, end);
puts("Waiting for lock...");
/* fall-thru */
case F_OFD_SETLK:
if (do_lock(fd, cmd, type, start, end) != 0)
do_lock(fd, F_OFD_GETLK, type, start, end);
else {
printf("Acquired %s lock! Press [Enter] to release...\n",
type == F_WRLCK ? "write" : "read");
i = read(0, buf, sizeof(buf));
i = i;
}
break;
default:
do_lock(fd, F_OFD_GETLK, type, start, end);
break;
}
return 0;
}
| 2.734375 | 3 |
2024-11-18T22:29:21.513281+00:00 | 2022-12-29T05:23:00 | e676f3ee878159c9eba7004819a3c36836b085e8 | {
"blob_id": "e676f3ee878159c9eba7004819a3c36836b085e8",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-29T05:23:00",
"content_id": "15e7d49e4eb35ed501a60aced9e59f7f18b9901f",
"detected_licenses": [
"MIT"
],
"directory_id": "50f63777eaef1aa4b724c360dfd6aef5356763a6",
"extension": "c",
"filename": "analyzer.c",
"fork_events_count": 0,
"gha_created_at": "2015-05-29T20:09:51",
"gha_event_created_at": "2015-06-28T23:59:56",
"gha_language": "C",
"gha_license_id": null,
"github_id": 36526602,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4161,
"license": "MIT",
"license_type": "permissive",
"path": "/src/analyzer.c",
"provenance": "stackv2-0132.json.gz:108675",
"repo_name": "Ziddykins/Dawn",
"revision_date": "2022-12-29T05:23:00",
"revision_id": "ce0bb8806e0337064bce49e06c6c3967710d09a0",
"snapshot_id": "19a0ed4575ded2c10a24ad2c7fb9ba4ad19d2b05",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/Ziddykins/Dawn/ce0bb8806e0337064bce49e06c6c3967710d09a0/src/analyzer.c",
"visit_date": "2023-01-06T04:36:20.735850"
} | stackv2 | #include "include/analyzer.h"
#include "include/tokenlist.h"
#include "include/util.h"
#include "include/colors.h"
Analyzer init_analyzer(size_t markov_tier) {
if(markov_tier == 0)
return 0;
struct analyzer * a;
CALLEXIT(!(a = malloc(sizeof *a)))
a->tlists = 0;
a->markov_tier = markov_tier;
a->tokens = 0;
a->start = 0;
return a;
}
void free_analyzer(Analyzer a) {
if(!a)
return;
struct analyzer * ca = a;
if(ca->tlists) {
for(size_t i = 0; i < CHAR_LEN; i++) {
free_token_list(ca->tlists[i]);
}
}
free(ca->tlists);
free_token_list(ca->start);
free(ca);
}
int analyze(Analyzer a, char const * fn) {
if(!a)
return 0;
struct analyzer * ca = a;
FILE * file;
CALLEXIT(!(file = fopen(fn, "r")))
char * word = 0; //malloc(MAX_WORD_LEN)
char * prediction;
CALLEXIT(!(prediction = malloc(ca->markov_tier+1))) //next n characters, \0 terminated
if(!ca->tlists) {
CALLEXIT(!(ca->tlists = malloc(CHAR_LEN * sizeof *ca->tlists)))
for(size_t i = 0; i < CHAR_LEN; i++) {
ca->tlists[i] = init_token_list();
}
}
if(!ca->start) {
ca->start = init_token_list();
}
size_t len = 0;
char * start;
CALLEXIT(!(start = calloc(1, ca->markov_tier+2)))
while(getline(&word, &len, file) != -1) { //fscanf(file, "%"MAX_WORD_LEN_LITERAL"s", word) != EOF
word[strlen(word)-1] = '\0';
char cur_char = word[0];
//initialize prediction
size_t i;
for(i = 0; i < ca->markov_tier && word[i+1] != '\0'; i++) {
prediction[i] = word[i+1];
}
prediction[ca->markov_tier] = '\0';
//word too short?
if(i < ca->markov_tier) {
continue;
}
start[0] = word[0];
strcpy(start+1, prediction);
inc_token(ca->start, start, 0);
for(i = 1; prediction[ca->markov_tier-1] != '\0' && cur_char != '\0'; i++) {
//add markov prediction
int end = 0;
if(word[i+ca->markov_tier] == '\0') {
end = 1;
}
inc_token(ca->tlists[(unsigned char)cur_char], prediction, end);
ca->tokens++;
//shift prediction
for(size_t pos = 1; pos < ca->markov_tier; pos++) {
prediction[pos-1] = prediction[pos];
}
prediction[ca->markov_tier-1] = word[i+ca->markov_tier];
//get next character
cur_char = word[i];
}
}
fclose(file);
free(word);
free(start);
free(prediction);
return 1;
}
char * gen_token(Analyzer a, char src, int end) {
if(!a) {
return 0;
}
struct analyzer * ca = a;
if(!ca->tlists || ca->tokens == 0) {
return 0;
}
if(get_len(ca->tlists[(unsigned char)src]) == 0) {
return 0;
}
double prob = randd();
TokenIterator it = get_iterator(ca->tlists[(unsigned char)src]);
while(has_elem(it) && (prob > ((double)(get_num_consumed(it)))/get_num_total(ca->tlists[(unsigned char)src]) || end ? !get_is_end(it) : 0)) {
next(it);
}
if(!has_elem(it) || (end && !get_is_end(it))) {
free_iterator(it);
return 0;
}
char * res = get_str(it);
free_iterator(it);
return res;
}
char * gen_start(Analyzer a) {
if(!a) {
return 0;
}
struct analyzer * ca = a;
if(!ca->start || ca->tokens == 0) {
return 0;
}
if(get_len(ca->start) == 0) {
return 0;
}
double prob = randd();
TokenIterator it = get_iterator(ca->start);
while(has_elem(it) && (prob > ((double)(get_num_consumed(it)))/get_num_total(ca->start))) {
next(it);
}
if(!has_elem(it)) {
free_iterator(it);
return 0;
}
char * res = get_str(it);
free_iterator(it);
return res;
}
int has_rule_for(Analyzer a, char src) {
if(!a) {
return 0;
}
struct analyzer * ca = a;
if(!ca->tlists) {
return 0;
}
return get_len(ca->tlists[(unsigned char)src]) != 0;
}
| 2.546875 | 3 |
2024-11-18T22:29:21.735887+00:00 | 2017-06-22T20:57:41 | aa2ea05d47991364197b986eea69df656acdbbd4 | {
"blob_id": "aa2ea05d47991364197b986eea69df656acdbbd4",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-22T20:57:41",
"content_id": "6ff0c5e070677da003281ee245286048e32fdfa3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "df46c80e10dfd6df27131abd2d9afd3a172cedc5",
"extension": "c",
"filename": "psde.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": 5976,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/TFSAP-7.1.1-software-package/src_TFSAP_June_2017/func_src/psde.c",
"provenance": "stackv2-0132.json.gz:108805",
"repo_name": "lysnuaa/TFSAP-7.1-software-package",
"revision_date": "2017-06-22T20:57:41",
"revision_id": "c8e30acae4aab28ab5e95a9a2c1075e891a881c0",
"snapshot_id": "cd5cb06eb7ce28f86d65432cbeec4fdf85229d8b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lysnuaa/TFSAP-7.1-software-package/c8e30acae4aab28ab5e95a9a2c1075e891a881c0/TFSAP-7.1.1-software-package/src_TFSAP_June_2017/func_src/psde.c",
"visit_date": "2020-06-17T18:55:38.636531"
} | stackv2 | /*************************************************
* Author: Boualem Boashash (boualem.boashash@gmail.com)
* Maintainer since 2015: Samir Ouelha (samir_ouelha@hotmail.fr)
*
* The following 2 references should be cited whenever this script is used:
* [1] B. Boashash, Samir Ouelha, Designing time-frequency and time-scale
* features for efficient classification of non stationary signals: a tutorial
* review with performance comparison, Digital Signal Processing, 2017.
* [2] B. Boashash, Samir Ouelha, Efficient Software Matlab Package for the calculation
* of Time-Frequency Distributions related Time-Scale methods and the extraction of
* signal characteristics, SoftwareX, 2017.
* In addition, the following 3rd reference is relevant for use of the executable
* [3] B. Boashash (ed.), Time-Frequency Signal Analysis and Processing, 2nd Edition
* (London: Elsevier / Academic Press, December 2015); ISBN 978-0-12-398499-9. Book website:
* http://booksite.elsevier.com/9780123984999/
*
* Function for computing the power spectrum density of an input signal
* using the periodogram direct method.
*
* Refs:
* ch. 5, sec. 5.7.3,
* S. Lawrence Marple Jr.,
* Digital Spectral Analysis with Applications.
* Prentice-Hall Inc., Englewood Cliffs, New Jersey.
*************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "mex.h"
#include "arithm.h" /* routines for complex data */
#include "tlocal.h" /* local function prototypes */
#include "fft.h"
#include "psde.h"
#include "tfsa_c.h"
#include "window.h"
void psde (double *result, complex *input, int signal_length,
int seg_len, int fft_len, int overlap, int window_type)
/*
* pre: fft_len must be radix 2.
*
*/
{
int i, j, k; /* Counters */
complex *Y; /* Segment minus mean and zero padded */
complex *periodogram; /* Pointer to the periodogram */
double *window; /* pointer to the window */
double mean1=0; /* Mean of the real part of input */
double mean2=0; /* Mean of the imag part of input */
int fft_order; /* order of the fft */
int seg_r2; /* same as fft length */
int signal_zeropad; /* Zero padded length of signal */
int num_segs; /* Number of segments */
int offset;
/* Calculate zero padded length of singal */
num_segs = (int) ceil((double)signal_length/(seg_len-overlap));
signal_zeropad = num_segs*(seg_len-overlap);
signal_zeropad += overlap;
/* Calculate the order of the fft for the FFT function */
fft_order = 1;
seg_r2 = 2;
while (seg_r2 < fft_len) {
fft_order++;
seg_r2 *= 2;
}
/* Allocate space for signal minus the mean */
Y = (complex *) mxCalloc (signal_zeropad, sizeof(complex));
if (Y == NULL) {
tfsaErr ("psde", "Memory allocation failed");
}
/* Copy input into zero padded array */
for (i = 0; i < signal_length; i++) {
Y[i].re = input[i].re;
Y[i].im = input[i].im;
}
/* ensure that signal is zero padded */
for (i = signal_length; i < signal_zeropad; i++) {
Y[i].re = 0;
Y[i].im = 0;
}
/* Allocate space for the window and the periodogram */
window = (double *) mxCalloc (seg_len, sizeof(double));
periodogram = (complex *) mxCalloc (fft_len, sizeof(complex));
switch( window_type) {
case RECT: for (k = 0; k < seg_len; k++)
window[k] = 0.5;
break;
case HANN: hann(window, seg_len);
break;
case HAMM: hamming(window, seg_len);
break;
case BART: bartlett(window, seg_len);
break;
default : for (k=0; k < seg_len; i++)
window[k] = 0.5;
}
periodogram[0].re = 0.3;
/*
* For each data segment: apply the data window,
* compute the periodogram,
* sum corresponding samples.
*
*/
offset = 0;
for (i = 0; i < num_segs; i++) {
/* Debug: Check array bounds */
if ((offset+seg_len) > signal_zeropad) {
return;
}
/* calculate mean of this segment */
for (j = 0; j < seg_len; j++) {
mean1 += Y[offset+j].re;
mean2 += Y[offset+j].im;
}
mean1 /= (double) seg_len;
mean2 /= (double) seg_len;
/* apply data window to each segment */
for(j = 0; j < seg_len; j++) {
periodogram[j].re = Y[offset+j].re*window[j] - mean1;
periodogram[j].im = Y[offset+j].im*window[j] - mean2;
}
/* ensure that rest of periodogram is 0 */
for(j = seg_len; j < fft_len; j++) {
periodogram[j].re = 0;
periodogram[j].im = 0;
}
offset += (seg_len - overlap);
FFT(periodogram, fft_order, 1);
for (j = 0; j < fft_len; j++) {
periodogram[j].re = periodogram[j].re * periodogram[j].re +
periodogram[j].im * periodogram[j].im;
periodogram[j].re /= (double) fft_len;
/* Add current segment periodogram to other segments */
result[j] += (double) periodogram[j].re;
}
}
/* Average periodograms */
for (j = 0; j < fft_len; j++) {
result[j] /= (double) num_segs;
}
}
| 2.0625 | 2 |
2024-11-18T23:19:57.896037+00:00 | 2021-01-10T21:34:50 | 01280b3cf225002331fa03fe79e1da08662dbcee | {
"blob_id": "01280b3cf225002331fa03fe79e1da08662dbcee",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-10T21:34:50",
"content_id": "18fb479032e02ffb61c47cc2b4e516f9bf0323c5",
"detected_licenses": [
"MIT"
],
"directory_id": "83f2362afcc7864a0ecea261f481a083ddfb6a74",
"extension": "c",
"filename": "ex22.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 328472406,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 807,
"license": "MIT",
"license_type": "permissive",
"path": "/IP/Lista 1c/ex22.c",
"provenance": "stackv2-0135.json.gz:50727",
"repo_name": "savio-matheus/exercicios",
"revision_date": "2021-01-10T21:34:50",
"revision_id": "8c91e5608be132de5ef95730292bf2c21386ff7d",
"snapshot_id": "6097da5d85e287dbce1051b14f3220b1b09cb080",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/savio-matheus/exercicios/8c91e5608be132de5ef95730292bf2c21386ff7d/IP/Lista 1c/ex22.c",
"visit_date": "2023-02-18T00:34:44.500288"
} | stackv2 | // Hipotenusas inteiras, L1c - 22
#include <stdio.h>
main(){
int n, j, i, hipotenusa;
int c1 = 1, c2 = 2;
scanf("%d", &n);
// Gera uma hipotenusa j, tal que j <= n;
for (j = 1; j <= n; j++){
// Gera um cateto c1, tal que c1 < j;
for (c1 = 1; c1 < j; c1++){
// Gera um cateto c2, tal que c2 < j,
// e testa todos os valores gerados.
for (c2 = 1; c2 < j; c2++){
// Impede repetições e garante que o primeiro cateto seja
// menor que o segundo.
if (c1 > c2){
continue;
}
hipotenusa = (c1 * c1) + (c2 * c2);
if (hipotenusa == (j * j)){
printf("hipotenusa = %d, catetos %d e %d\n", j, c1, c2);
}
}
}
}
} | 3.75 | 4 |
2024-11-18T23:19:58.054185+00:00 | 2017-04-20T10:17:49 | cbb1142400d4ab29bfc8b4e8efc110304b29e31b | {
"blob_id": "cbb1142400d4ab29bfc8b4e8efc110304b29e31b",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-20T10:17:49",
"content_id": "5daf7db28112414d447fa65f7cb510b5caf2fd56",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ebd585fdafb22d31fcd6d04b209f81e88d1a2083",
"extension": "h",
"filename": "rtxStack.h",
"fork_events_count": 10,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 88847837,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4105,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/modem_proc/modem/utils/osys/rtxsrc/rtxStack.h",
"provenance": "stackv2-0135.json.gz:50856",
"repo_name": "xusl/android-wilhelm",
"revision_date": "2017-04-20T10:17:49",
"revision_id": "13c59cb5b0913252fe0b5c672d8dc2bf938bb720",
"snapshot_id": "fd28144253cd9d7de0646f96ff27a1f4a9bec6e3",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/xusl/android-wilhelm/13c59cb5b0913252fe0b5c672d8dc2bf938bb720/modem_proc/modem/utils/osys/rtxsrc/rtxStack.h",
"visit_date": "2018-04-03T21:46:10.195170"
} | stackv2 | /*
* Copyright (c) 2003-2011 Objective Systems, Inc.
*
* This software is furnished under a license and may be used and copied
* only in accordance with the terms of such license and with the
* inclusion of the above copyright notice. This software or any other
* copies thereof may not be provided or otherwise made available to any
* other person. No title to and ownership of the software is hereby
* transferred.
*
* The information in this software is subject to change without notice
* and should not be construed as a commitment by Objective Systems, Inc.
*
* PROPRIETARY NOTICE
*
* This software is an unpublished work subject to a confidentiality agreement
* and is protected by copyright and trade secret law. Unauthorized copying,
* redistribution or other use of this work is prohibited.
*
* The above notice of copyright on this source code product does not indicate
* any actual or intended publication of such source code.
*
*****************************************************************************/
/**
* @file rtxStack.h
* Simple FIFO stack for storing void pointers to any type of data.
*/
#ifndef _RTXSTACK_H_
#define _RTXSTACK_H_
#include "rtxsrc/rtxContext.h"
/**
* @defgroup ccfStack Stack Utility Functions
*
* This is a simple stack structure with supporting push and pop functions.
* Different initialization routines are provided to permit different
* memory management schemes.
*
*@{
*/
/**
* @struct _OSRTStack
* This is the main stack structure. It uses a linked list structure.
*/
typedef struct _OSRTStack {
OSCTXT* pctxt;
OSRTDList dlist;
} OSRTStack;
#ifdef __cplusplus
extern "C" {
#endif
/**
* This function creates a new stack structure. It allocates memory for the
* structure and calls rtxStackInit to initialize the structure.
*
* @param pctxt A pointer to the context with which the stack is
* associated.
* @return A pointer to an allocated stack structure.
*/
EXTERNRT OSRTStack* rtxStackCreate (OSCTXT* pctxt);
/**
* This function initializes a stack structure. It sets the number of elements
* to zero and sets all internal pointer values to NULL.
*
* @param pctxt A pointer to the context with which the stack is
* associated.
* @param pStack A pointer to a stack structure to be initialized.
*/
EXTERNRT void rtxStackInit (OSCTXT* pctxt, OSRTStack* pStack);
/**
* This macro tests if the stack is empty.
*
* @param stack Stack structure variable to be tested.
*/
#define rtxStackIsEmpty(stack) (OSBOOL)((stack).dlist.count == 0)
/**
* This function pops an item off the stack.
*
* @param pStack The pointer to the stack structure from which the value
* is to be popped. Pointer to the updated stack
* structure.
* @return The pointer to the item popped from the stack
*/
EXTERNRT void* rtxStackPop (OSRTStack* pStack);
/**
* This function pushes an item onto the stack.
*
* @param pStack A pointer to the structure onto which the data item is
* to be pushed. The pointer updated to the stack
* structure
* @param pData A pointer to the data item to be pushed on the stack.
* @return Completion status of operation:
* - 0 (0) = success,
* - negative return value is error.
*/
EXTERNRT int rtxStackPush (OSRTStack* pStack, void* pData);
/**
* This functions returns the data item on the top of the stack.
*
* @param pStack A pointer to the structure onto which the data item is
* to be pushed. The pointer updated to the stack
* structure
* @return Pointer to data item at top of stack or NULL if
* stack empty.
* - 0 (0) = success,
* - negative return value is error.
*/
EXTERNRT void* rtxStackPeek (OSRTStack* pStack);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif
| 2.359375 | 2 |
2024-11-18T23:19:58.161308+00:00 | 2022-02-22T03:44:23 | e02cd48c8bdf60e77fb540fec01a9a6b4be1f7e6 | {
"blob_id": "e02cd48c8bdf60e77fb540fec01a9a6b4be1f7e6",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-22T03:44:23",
"content_id": "72d2d733621960ece30b24ae8863cbe80b0e1d92",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "936b73a803b7628d0d25429b9d9c12c0811914e5",
"extension": "c",
"filename": "aos_hal_spi.c",
"fork_events_count": 0,
"gha_created_at": "2017-12-18T11:01:24",
"gha_event_created_at": "2017-12-18T11:01:24",
"gha_language": null,
"gha_license_id": null,
"github_id": 114630792,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7721,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/amp_adapter/platform/esp_idf/peripheral/aos_hal_spi.c",
"provenance": "stackv2-0135.json.gz:50985",
"repo_name": "Ray148289/AliOS-Things",
"revision_date": "2022-02-22T03:44:23",
"revision_id": "47b5f7881e2d74ac92c2e6e12450b9afba9908ec",
"snapshot_id": "09eab4cc84ce19afb8bac10554ef3621d021ee1b",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Ray148289/AliOS-Things/47b5f7881e2d74ac92c2e6e12450b9afba9908ec/components/amp_adapter/platform/esp_idf/peripheral/aos_hal_spi.c",
"visit_date": "2022-03-27T13:07:33.202277"
} | stackv2 | #include <stdlib.h>
#include <errno.h>
#include <driver/spi_common.h>
#include <driver/spi_master.h>
#include <aos_hal_spi_internal.h>
#include "esp_log.h"
typedef struct {
spi_device_handle_t dev_handle;
} spi_pdata_t;
int32_t aos_hal_spi_init(aos_hal_spi_dev_t *spi)
{
spi_host_device_t host_id;
spi_bus_config_t bus_config = {
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = 1024,
.flags = SPICOMMON_BUSFLAG_MASTER,
.intr_flags = 0,
};
spi_device_interface_config_t dev_config = {
.command_bits = 0,
.address_bits = 0,
.dummy_bits = 0,
.duty_cycle_pos = 0,
.cs_ena_pretrans = 0,
.cs_ena_posttrans = 0,
.input_delay_ns = 0,
.flags = SPI_DEVICE_HALFDUPLEX,
.queue_size = 1,
.pre_cb = NULL,
.post_cb = NULL,
};
if (!spi)
return -EINVAL;
switch (spi->port) {
case 3:
host_id = SPI3_HOST;
bus_config.mosi_io_num = 23;
bus_config.sclk_io_num = 18;
#ifdef BOARD_M5STACKCORE2
bus_config.miso_io_num = 38;
dev_config.spics_io_num = 25;
#else
bus_config.miso_io_num = 19;
dev_config.spics_io_num = 5;
#endif
break;
default:
return -EINVAL;
}
switch (spi->config.role) {
case SPI_ROLE_MASTER:
break;
default:
return -EINVAL;
}
switch (spi->config.firstbit) {
case SPI_FIRSTBIT_MSB:
break;
case SPI_FIRSTBIT_LSB:
dev_config.flags |= SPI_DEVICE_BIT_LSBFIRST;
break;
default:
return -EINVAL;
}
switch (spi->config.mode) {
case SPI_WORK_MODE_0:
dev_config.mode = 0;
break;
case SPI_WORK_MODE_1:
dev_config.mode = 1;
break;
case SPI_WORK_MODE_2:
dev_config.mode = 2;
break;
case SPI_WORK_MODE_3:
dev_config.mode = 3;
break;
default:
return -EINVAL;
}
switch (spi->config.t_mode) {
case SPI_TRANSFER_DMA:
break;
case SPI_TRANSFER_NORMAL:
break;
default:
return -EINVAL;
}
dev_config.clock_speed_hz = spi->config.freq;
switch (spi->config.data_size) {
case SPI_DATA_SIZE_8BIT:
break;
default:
return -EINVAL;
}
switch (spi->config.cs) {
case SPI_CS_DIS:
break;
case SPI_CS_EN:
break;
default:
return -EINVAL;
}
spi->priv = malloc(sizeof(spi_pdata_t));
if (!spi->priv)
return -ENOMEM;
/* Change SPI_DMA_CH_AUTO to 0 as no supported by IDF-V4.2 */
if (spi_bus_initialize(host_id, &bus_config, 0) != ESP_OK) {
free(spi->priv);
spi->priv = NULL;
return -EINVAL;
}
if (spi_bus_add_device(host_id, &dev_config, &((spi_pdata_t *)spi->priv)->dev_handle) != ESP_OK) {
(void)spi_bus_free(host_id);
free(spi->priv);
spi->priv = NULL;
return -EINVAL;
}
return 0;
}
int32_t aos_hal_spi_finalize(aos_hal_spi_dev_t *spi)
{
spi_host_device_t host_id;
if (!spi || !spi->priv)
return -EINVAL;
switch (spi->port) {
case 3:
host_id = SPI3_HOST;
break;
default:
return -EINVAL;
}
(void)spi_bus_remove_device(((spi_pdata_t *)spi->priv)->dev_handle);
(void)spi_bus_free(host_id);
free(spi->priv);
spi->priv = NULL;
return 0;
}
int32_t aos_hal_spi_send(aos_hal_spi_dev_t *spi, const uint8_t *data, uint32_t size, uint32_t timeout)
{
spi_transaction_t trans_desc = {
.flags = 0,
.cmd = 0,
.addr = 0,
.rxlength = 0,
.user = NULL,
.tx_data = { 0, 0, 0, 0, },
.rx_buffer = NULL,
.rx_data = { 0, 0, 0, 0, },
};
if (!spi || !spi->priv || !data || size == 0)
return -EINVAL;
trans_desc.length = size * 8;
trans_desc.tx_buffer = data;
if (spi_device_transmit(((spi_pdata_t *)spi->priv)->dev_handle, &trans_desc) != ESP_OK)
return -EIO;
return 0;
}
int32_t aos_hal_spi_recv(aos_hal_spi_dev_t *spi, uint8_t *data, uint32_t size, uint32_t timeout)
{
spi_transaction_t trans_desc = {
.flags = 0,
.cmd = 0,
.addr = 0,
.length = 0,
.user = NULL,
.tx_buffer = NULL,
.tx_data = { 0, 0, 0, 0, },
.rx_data = { 0, 0, 0, 0, },
};
if (!spi || !spi->priv || !data || size == 0)
return -EINVAL;
trans_desc.rxlength = size * 8;
trans_desc.rx_buffer = data;
if (spi_device_transmit(((spi_pdata_t *)spi->priv)->dev_handle, &trans_desc) != ESP_OK)
return -EIO;
return 0;
}
int32_t aos_hal_spi_send_recv(aos_hal_spi_dev_t *spi, uint8_t *tx_data, uint8_t *rx_data,
uint32_t rx_size, uint32_t timeout)
{
spi_transaction_t trans_desc = {
.flags = 0,
.cmd = 0,
.addr = 0,
.user = NULL,
.tx_data = { 0, 0, 0, 0, },
.rx_data = { 0, 0, 0, 0, },
};
if (!spi || !spi->priv || !tx_data || !rx_data || rx_size == 0)
return -EINVAL;
trans_desc.length = 1 * 8;
trans_desc.tx_buffer = tx_data;
trans_desc.rxlength = rx_size * 8;
trans_desc.rx_buffer = rx_data;
if (spi_device_transmit(((spi_pdata_t *)spi->priv)->dev_handle, &trans_desc) != ESP_OK)
return -EIO;
return 0;
}
int32_t aos_hal_spi_send_and_recv(aos_hal_spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data,
uint16_t rx_size, uint32_t timeout)
{
return -ENOTSUP;
/*
if (!spi || !spi->priv || !tx_data || !rx_data || rx_size == 0)
return -EINVAL;
spi_device_handle_t dev_handle = ((spi_pdata_t *)spi->priv)->dev_handle;
int bits_to_send = tx_size * 8;
if (tx_size <= 4) {
spi_transaction_t transaction;
memset(&transaction, 0, sizeof(spi_transaction_t));
if (tx_data != NULL) {
memcpy(&transaction.tx_data, tx_data, tx_size);
}
transaction.flags = SPI_TRANS_USE_TXDATA | SPI_TRANS_USE_RXDATA;
transaction.length = bits_to_send;
spi_device_transmit(dev_handle, &transaction);
if (rx_data != NULL) {
memcpy(rx_data, transaction.rx_data, rx_size);
}
} else {
int offset = 0;
int bits_remaining = bits_to_send;
int max_transaction_bits = 1024 * 8;
spi_transaction_t *transaction, *result, transactions[2];
int i = 0;
spi_device_acquire_bus(dev_handle, portMAX_DELAY);
while (bits_remaining) {
transaction = transactions + i++ % 2;
memset(transaction, 0, sizeof(spi_transaction_t));
transaction->length =
bits_remaining > max_transaction_bits ? max_transaction_bits : bits_remaining;
if (tx_data != NULL) {
transaction->tx_buffer = tx_data + offset;
}
if (rx_data != NULL) {
transaction->rx_buffer = rx_data + offset;
}
spi_device_queue_trans(dev_handle, transaction, portMAX_DELAY);
bits_remaining -= transaction->length;
if (offset > 0) {
// wait for previously queued transaction
spi_device_get_trans_result(dev_handle, &result, portMAX_DELAY);
}
// doesn't need ceil(); loop ends when bits_remaining is 0
offset += transaction->length / 8;
}
// wait for last transaction
spi_device_get_trans_result(dev_handle, &result, portMAX_DELAY);
spi_device_release_bus(dev_handle);
}
return 0;
*/
}
| 2.234375 | 2 |
2024-11-18T23:19:59.036339+00:00 | 2015-05-13T15:51:16 | 56ad8984e3817e0053818c9477e1f190a0d20b87 | {
"blob_id": "56ad8984e3817e0053818c9477e1f190a0d20b87",
"branch_name": "refs/heads/master",
"committer_date": "2015-05-13T15:51:16",
"content_id": "1282d28de677ce2b9c37869d2cc5dc56489d5ac8",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fbf6de55f3edb841c69acee862029e8a7a227aec",
"extension": "c",
"filename": "cef_helpers.c",
"fork_events_count": 8,
"gha_created_at": "2014-04-14T15:30:41",
"gha_event_created_at": "2015-05-13T15:54:08",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 18765894,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 882,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/cef/cef_helpers.c",
"provenance": "stackv2-0135.json.gz:51763",
"repo_name": "paperlesspost/cef2go",
"revision_date": "2015-05-13T15:51:16",
"revision_id": "c39bc2648993f87423c66cabb0d8d92938b7c827",
"snapshot_id": "484788763af4991e28e92cf2f099717f580c2bc6",
"src_encoding": "UTF-8",
"star_events_count": 35,
"url": "https://raw.githubusercontent.com/paperlesspost/cef2go/c39bc2648993f87423c66cabb0d8d92938b7c827/cef/cef_helpers.c",
"visit_date": "2021-01-14T08:40:48.849881"
} | stackv2 | #include "include/internal/cef_string.h"
#include "include/capi/cef_v8_capi.h"
cef_string_utf8_t * cefSourceToString(cef_string_t * source) {
cef_string_utf8_t * output = cef_string_userfree_utf8_alloc();
if (source == 0) {
return output;
}
cef_string_to_utf8(source->str, source->length, output);
return output;
}
cef_string_userfree_t v8ValueToString(cef_v8value_t * str) {
return str->get_string_value(str);
}
int32 v8ValueToInt32(cef_v8value_t * i) {
return i->get_int_value(i);
}
int v8ValueToBool(cef_v8value_t * b) {
return b->get_bool_value(b);
}
double v8ValueToDouble(cef_v8value_t * d) {
return d->get_double_value(d);
}
void setCefRectDimensions(cef_rect_t * rect, int x, int y, int width, int height) {
rect->x = x;
rect->y = y;
rect->width = width;
rect->height = height;
}
| 2.265625 | 2 |
2024-11-18T23:19:59.125772+00:00 | 2019-06-01T19:19:41 | 042721cde7140e829926288a2e127418af41ae55 | {
"blob_id": "042721cde7140e829926288a2e127418af41ae55",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-01T19:19:41",
"content_id": "9a6dc4036b4f089b08748239fd0c12cbfc0aac28",
"detected_licenses": [
"MIT"
],
"directory_id": "70fe70db7c6a023737f1a258eba673817812c0da",
"extension": "c",
"filename": "main (3).c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 187065298,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2349,
"license": "MIT",
"license_type": "permissive",
"path": "/Algoritmos de Ordenação/Versoes anteriores/main (3).c",
"provenance": "stackv2-0135.json.gz:51894",
"repo_name": "MarianaFRocha/Estrutura-de-Dados",
"revision_date": "2019-06-01T19:19:41",
"revision_id": "0b430d711f636ae70a674fc1c7e58e243ce5c2d0",
"snapshot_id": "0ed01155c041e8ff7c0bb99c2e484779cea6f7b9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MarianaFRocha/Estrutura-de-Dados/0b430d711f636ae70a674fc1c7e58e243ce5c2d0/Algoritmos de Ordenação/Versoes anteriores/main (3).c",
"visit_date": "2020-05-24T03:03:45.932690"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "trocaPosicao.h"
#include "insertionSort.h"
#include "selectionSort.h"
#include "bubbleSort.h"
#include "heapSort.h"
//#include "quickSort.h"
#include "shellSort.h"
#include "mergeSort.h"
int main(int argc, char *argv[]){
if(argc < 2){
printf("\nErro: Digite o nome do arquivo !!!\n\n");
exit(1);
}
int tamanhoVetor;
int i = 0, aux, j;
FILE* arquivo = fopen(argv[1], "r");
if(arquivo == NULL){
printf("\nProblema ao ler o arquivo!");
return 0;
}
fscanf(arquivo, "%d", &tamanhoVetor); //a ideia é separar o primeiro valor do arquivo e só os demais entrarem no vetor
int* vetor=(int*)malloc(sizeof(int)*(tamanhoVetor));
while( !feof(arquivo) ){
fscanf(arquivo, "%d", &vetor[i]);
i++;
}
printf("\n****\tDESORDENADO\t****\n");
for(i =0 ; i<tamanhoVetor ; i++){
//printf("\nvetor[%d]: %d", i, vetor[i]);
}
printf("\n\n");
//vetor = insertionSort(vetor, tamanhoVetor);
//vetor = bubbleSort(vetor, tamanhoVetor);
//heapSort (tamanhoVetor, vetor);
//vetor = selectionSort(vetor, tamanhoVetor);
//quickSort(vetor, 0, tamanhoVetor-1);
//vetor=shellSort(vetor, tamanhoVetor);
clock_t t0,t1;
double tempoGasto;
t0 = clock();
//vetor=mergeSort(vetor, tamanhoVetor);
heapSort (tamanhoVetor, vetor);
vetor = bubbleSort(vetor, tamanhoVetor);
t1 = clock();
//Buble
//Insertion
//Heap
//Selection
//Quick
//Shell
//Counting
tempoGasto = ((t1-t0)*1000/CLOCKS_PER_SEC);
printf("TEMPO GASTO(milisegundos): %f",tempoGasto); //Divide por um milhão p segundos???
printf("\n****\tORDENADO MERGE\t****\n");
for(i =0 ; i<tamanhoVetor ; i++){
//printf("\nvetor2[%d]: %d", i, vetor[i]);
}
fclose(arquivo);
FILE *saida = fopen("Saida.txt","w+");
int ii;
for(ii=0;ii<tamanhoVetor-1;ii++){
fprintf(saida, "%d\n", vetor[ii]);
}
FILE *resultado = fopen("Resultado.txt","w+");
int jj;
fprintf(resultado, "Quantidade de chaves: %d\n", tamanhoVetor);
fprintf(resultado, "Maior chave: %d\n", 11);
fprintf(resultado, "Limite de tempo: %d segundos\n", 1200);
fprintf(resultado, "Tempo absoluto dos algoritmos:\n");
for(jj=0;jj<tamanhoVetor-1;jj++){
}
return 0;
}
| 3.015625 | 3 |
2024-11-18T23:19:59.310354+00:00 | 2019-08-31T00:39:58 | deed84f15ded9ada84ccdac22eb95e9423f88248 | {
"blob_id": "deed84f15ded9ada84ccdac22eb95e9423f88248",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-31T00:39:58",
"content_id": "b3ca6040e0c93ad28b60d608045b1ae149f280e6",
"detected_licenses": [
"MIT"
],
"directory_id": "e649358eea83e1d7d3e5cfaf88656e9b0bc7aa5f",
"extension": "c",
"filename": "IAHashMapIterator.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150095088,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1451,
"license": "MIT",
"license_type": "permissive",
"path": "/modules/common/clib/c/shared/container/IAHashMapIterator.c",
"provenance": "stackv2-0135.json.gz:52284",
"repo_name": "impsapps/impsengine",
"revision_date": "2019-08-31T00:39:58",
"revision_id": "1b796bb4bccbe27b3f084a298a22c55555429aa2",
"snapshot_id": "4c23c1bd801ebd363c96d858c4d7ebb19dc19362",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/impsapps/impsengine/1b796bb4bccbe27b3f084a298a22c55555429aa2/modules/common/clib/c/shared/container/IAHashMapIterator.c",
"visit_date": "2020-03-29T16:03:49.678574"
} | stackv2 | #include "IALibrary.h"
#include "IAHashMapIterator.h"
#define CLASSNAME "IAHashMapIterator"
void * IAHashMapIterator_returnValues(IAHashMapList * list);
void * IAHashMapIterator_returnKeys(IAHashMapList * list);
void IAHashMapIterator_makeIteratorOverValues(IAHashMapIterator * this, const IAHashMap * hashMap){
this->base = IAObject_make(this);
this->hashMap = hashMap;
this->listIndex = 0;
this->currentListElement = hashMap->list[0];
this->returnResult = IAHashMapIterator_returnValues;
}
void IAHashMapIterator_makeIteratorOverKeys(IAHashMapIterator * this, const IAHashMap * hashMap){
this->base = IAObject_make(this);
this->hashMap = hashMap;
this->listIndex = 0;
this->currentListElement = hashMap->list[0];
this->returnResult = IAHashMapIterator_returnKeys;
}
void * IAHashMapIterator_getNextObject(IAHashMapIterator * this){
while (this->currentListElement == NULL) {
if (this->listIndex == this->hashMap->size - 1) {
return NULL;
}
this->listIndex++;
this->currentListElement = this->hashMap->list[this->listIndex];
}
void * result = this->returnResult(this->currentListElement);
this->currentListElement = this->currentListElement->next;
return result;
}
void * IAHashMapIterator_returnValues(IAHashMapList * list){
return list->object;
}
void * IAHashMapIterator_returnKeys(IAHashMapList * list){
return list->key;
}
| 2.171875 | 2 |
2024-11-18T23:19:59.533875+00:00 | 2022-03-06T04:43:24 | f85c8fbb5509a1bb4e2fdaa2644f2246acb5224f | {
"blob_id": "f85c8fbb5509a1bb4e2fdaa2644f2246acb5224f",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-06T04:43:24",
"content_id": "8783bbe95d21dd6e88c3d5382e9086ad55c9d76d",
"detected_licenses": [
"MIT"
],
"directory_id": "c7468ebf6639207b6cfb70dad2b0126e0ad89140",
"extension": "h",
"filename": "Platform.h",
"fork_events_count": 0,
"gha_created_at": "2020-03-12T13:55:04",
"gha_event_created_at": "2022-03-06T04:43:25",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 246847443,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5794,
"license": "MIT",
"license_type": "permissive",
"path": "/Sources/Platform.h",
"provenance": "stackv2-0135.json.gz:52545",
"repo_name": "wisdark/MiniVisorPkg",
"revision_date": "2022-03-06T04:43:24",
"revision_id": "c714164dc0709f2124d67d6fdc9490bcdd98859f",
"snapshot_id": "951dd84df74a99bb1dea8b7ded6f4554ab6585cf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wisdark/MiniVisorPkg/c714164dc0709f2124d67d6fdc9490bcdd98859f/Sources/Platform.h",
"visit_date": "2022-03-22T06:32:05.606397"
} | stackv2 | /*!
@file Platform.h
@brief Platform specific API.
@author Satoshi Tanda
@copyright Copyright (c) 2020 - , Satoshi Tanda. All rights reserved.
*/
#pragma once
#include "Common.h"
//
// Spin lock type and state names.
//
#if defined(MV_PLATFORM_WINDOWS)
typedef volatile LONG64 SPIN_LOCK;
typedef enum _SPIN_LOCK_STATE
{
SpinLockReleased,
SpinLockAcquired,
} SPIN_LOCK_STATE;
#else
#include <Library/SynchronizationLib.h>
#endif
/*!
@brief Initializes platform specific bits.
@return MV_STATUS_SUCCESS on success; otherwise, an appropriate error code.
*/
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
MV_STATUS
InitializePlatform (
);
/*!
@brief Cleans up platform specific bits.
*/
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
CleanupPlatform (
);
/*!
@brief Stalls execution of the current processor.
@details Use of this API from the host is not allowed.
@param[in] Milliseconds - The time to stall in milliseconds.
*/
_IRQL_requires_max_(APC_LEVEL)
VOID
Sleep (
_In_ UINT64 Milliseconds
);
/*!
@brief Returns the active logical processor count.
@details Use of this API from the host is not allowed.
@return The active logical processor count.
*/
UINT32
GetActiveProcessorCount (
);
/*!
@brief Returns the current processor number. The BSP will return 0.
@details Use of this API from the host is not allowed.
@return The current processor number. 0 for BSP.
*/
UINT32
GetCurrentProcessorNumber (
);
/*!
@brief Returns the physical address of the given virtual address.
@param[in] VirualAddress - The virtual address to retrieve its physical
address for the current CR3. This must be non paged pool, otherwise the
result is undefined.
@return The physical address of the given virtual address.
*/
UINT64
GetPhysicalAddress (
_In_ VOID* VirualAddress
);
/*!
@brief Returns the virtual address of the given physical address.
@param[in] PhysicalAddress - The physical address to retrieve its virtual
address for the current CR3.
@return The virtual address of the given physical address.
*/
VOID*
GetVirtualAddress (
_In_ UINT64 PhysicalAddress
);
/*!
@brief Allocates page-aligned, zero-initialized physical memory resident pages.
@details Use of this API from the host is not allowed.
@param[in] PageCount - The page count to allocate.
@return The base of allocated pointer, or NULL on failure. The caller must
free the return value with FreeSystemMemory().
*/
__drv_allocatesMem(Mem)
_IRQL_requires_max_(DISPATCH_LEVEL)
_Post_maybenull_
_Post_writable_byte_size_(PageCount * PAGE_SIZE)
_Must_inspect_result_
VOID*
AllocateSystemMemory (
_In_ UINT64 PageCount
);
/*!
@brief Frees the memory allocated by AllocateSystemMemory().
@details Use of this API from the host is not allowed.
@param[in] Pages - The pointer to free.
@param[in] PageCount - Unused.
*/
_IRQL_requires_max_(DISPATCH_LEVEL)
VOID
FreeSystemMemory (
_Pre_notnull_ __drv_freesMem(Mem) VOID* Pages,
_In_ UINT64 PageCount
);
/*!
@brief Reserves the virtual address. The returned address is not accessible.
@details Use of this API from the host is not allowed.
@param[in] PageCount - The page count to reserve.
@return The address of reserved region on success or NULL. The caller must
free this value with FreeReservedVirtualAddress().
*/
_IRQL_requires_max_(APC_LEVEL)
_Must_inspect_result_
VOID*
ReserveVirtualAddress (
_In_ UINT64 PageCount
);
/*!
@brief Frees the address reserved with ReserveVirtualAddress().
@details Use of this API from the host is not allowed.
@param[in] Pages - The pointer returned from ReserveVirtualAddress().
@param[in] PageCount - Unused.
*/
_IRQL_requires_max_(APC_LEVEL)
VOID
FreeReservedVirtualAddress (
_In_ VOID* Pages,
_In_ UINT64 PageCount
);
typedef
VOID
USER_PASSIVE_CALLBACK (
_Inout_ VOID* Context
);
/*!
@brief Executes the callback at the PASSIVE_LEVEL on each processor one by one.
@details Use of this API from the host is not allowed.
@param[in] Callback - The pointer to the function to execute.
@param[in,out] Context - The pointer to arbitrary context data.
*/
_IRQL_requires_max_(APC_LEVEL)
VOID
RunOnAllProcessors (
_In_ USER_PASSIVE_CALLBACK* Callback,
_Inout_ VOID* Context
);
/*!
@brief Initializes the spin lock.
@param[out] SpinLock - The pointer to spin lock to initialize.
*/
VOID
InitializeSystemSpinLock (
_Out_ SPIN_LOCK* SpinLock
);
/*!
@brief Acquires the spin lock.
@details The custom spin lock is used because NT provided spin lock API is
not compatible with Driver Verifier when they are used from hypervisor.
@param[in,out] SpinLock - The pointer to the spin lock to acquire.
@return The opaque previous context.
*/
_Requires_lock_not_held_(*SpinLock)
_Acquires_lock_(*SpinLock)
_IRQL_requires_max_(HIGH_LEVEL)
_IRQL_saves_
_IRQL_raises_(DISPATCH_LEVEL)
UINT8
AcquireSystemSpinLock (
_Inout_ SPIN_LOCK* SpinLock
);
/*!
@brief Release the spin lock and lowers IRQL if necessary.
@details The custom spin lock is used because NT provided spin lock API is
not compatible with Driver Verifier when they are used from hypervisor.
@param[in,out] SpinLock - The spin lock to release.
@param[in] PreviousContext - The opaque previous context returned by the
AcquireSpinLock function.
*/
_Requires_lock_held_(*SpinLock)
_Releases_lock_(*SpinLock)
_IRQL_requires_max_(HIGH_LEVEL)
VOID
ReleaseSystemSpinLock (
_Inout_ SPIN_LOCK* SpinLock,
_In_ _IRQL_restores_ UINT8 PreviousContext
);
| 2.171875 | 2 |
2024-11-18T23:19:59.624609+00:00 | 2023-08-10T09:04:44 | a48e6f51089660a9b0d9a838fc42aafbb27ad7a5 | {
"blob_id": "a48e6f51089660a9b0d9a838fc42aafbb27ad7a5",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T09:04:44",
"content_id": "8d7d08a045ce6d8ecb62f0339a861b0cad7df60a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c6759b857e55991fea3ef0b465dbcee53fa38714",
"extension": "c",
"filename": "atomic.c",
"fork_events_count": 96,
"gha_created_at": "2018-05-14T07:50:29",
"gha_event_created_at": "2023-08-27T19:03:52",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 133324605,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1848,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/libs/openmp/tests/atomic/atomic.c",
"provenance": "stackv2-0135.json.gz:52676",
"repo_name": "GreenWaves-Technologies/gap_sdk",
"revision_date": "2023-08-10T09:04:44",
"revision_id": "3fea306d52ee33f923f2423c5a75d9eb1c07e904",
"snapshot_id": "1b343bba97b7a5ce62a24162bd72eef5cc67e269",
"src_encoding": "UTF-8",
"star_events_count": 145,
"url": "https://raw.githubusercontent.com/GreenWaves-Technologies/gap_sdk/3fea306d52ee33f923f2423c5a75d9eb1c07e904/libs/openmp/tests/atomic/atomic.c",
"visit_date": "2023-09-01T14:38:34.270427"
} | stackv2 | /* PMSIS includes */
#include "pmsis.h"
#include "omp.h"
#define ARRAY_SIZE 512
uint32_t a[ARRAY_SIZE] = {0};
uint32_t b[ARRAY_SIZE] = {0};
uint32_t c[ARRAY_SIZE] = {0};
uint32_t errors = 0;
/* Cluster main entry, executed by core 0. */
void cluster_delegate(void *arg)
{
printf("Cluster master core entry\n");
int32_t counter = 0;
#pragma omp parallel
{
printf("[%d %d] Fork entry\n", pi_cluster_id(), omp_get_thread_num() );
#pragma omp barrier
{
#pragma omp atomic
counter ++;
}
}
printf("Core counter: %d\n", counter);
if (counter != omp_get_num_threads())
{
errors = 1;
}
printf("Cluster master core exit\n");
}
void helloworld(void)
{
printf("Entering main controller\n");
uint32_t core_id = pi_core_id(), cluster_id = pi_cluster_id();
printf("[%d %d] Hello World!\n", cluster_id, core_id);
struct pi_device cluster_dev;
struct pi_cluster_conf cl_conf;
/* Init cluster configuration structure. */
pi_cluster_conf_init(&cl_conf);
cl_conf.id = 0; /* Set cluster ID. */
/* Configure & open cluster. */
pi_open_from_conf(&cluster_dev, &cl_conf);
if (pi_cluster_open(&cluster_dev))
{
printf("Cluster open failed !\n");
pmsis_exit(-1);
}
/* Prepare cluster task and send it to cluster. */
struct pi_cluster_task cl_task;
pi_cluster_send_task_to_cl(&cluster_dev, pi_cluster_task(&cl_task, cluster_delegate, NULL));
pi_cluster_close(&cluster_dev);
if (errors)
{
printf("Test failed!\n");
}
else
{
printf("Test success!\n");
}
pmsis_exit(errors);
}
/* Program Entry. */
int main(void)
{
printf("\n\n\t *** PMSIS HelloWorld ***\n\n");
return pmsis_kickoff((void *) helloworld);
}
| 2.8125 | 3 |
2024-11-18T23:19:59.777627+00:00 | 2018-02-12T16:32:43 | 09472f619f95bfb71d585d9fbd868948788df2ae | {
"blob_id": "09472f619f95bfb71d585d9fbd868948788df2ae",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-12T16:32:43",
"content_id": "8b11ae1798864d43a5f206af04702efc1d0ebcd1",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "39ab30f10a24a58d054f6a3c758e0d02fd40eae1",
"extension": "c",
"filename": "mp_dbg.c",
"fork_events_count": 0,
"gha_created_at": "2020-01-22T14:06:46",
"gha_event_created_at": "2020-01-22T14:06:47",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 235586592,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 283,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/test/tacas10-bitvectors/mp_dbg.c",
"provenance": "stackv2-0135.json.gz:52806",
"repo_name": "KaneTW/T2",
"revision_date": "2018-02-12T16:32:43",
"revision_id": "10f137385078750799e28bbb441d2cdca00cb40e",
"snapshot_id": "30918037f5ace879a09df522735cad82944c600e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/KaneTW/T2/10f137385078750799e28bbb441d2cdca00cb40e/test/tacas10-bitvectors/mp_dbg.c",
"visit_date": "2020-12-19T02:00:11.613513"
} | stackv2 |
#define DUMP_BytesPerLine 16
typedef unsigned long ULONG;
typedef int INT;
int main(void)
{
ULONG cb;
INT cbLine;
while (cb)
{
cbLine = (cb < DUMP_BytesPerLine) ? cb : DUMP_BytesPerLine;
;
cb -= cbLine;
;
}
return 0;
}
| 2.296875 | 2 |
2024-11-18T23:19:59.834891+00:00 | 2021-09-27T14:26:24 | 98b7b0f4cba38e53a34bab8ab97deb4fe2b7a79b | {
"blob_id": "98b7b0f4cba38e53a34bab8ab97deb4fe2b7a79b",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-27T14:26:24",
"content_id": "b795c2fd17ea5abd65c4e3b8630714bb79970246",
"detected_licenses": [
"MIT"
],
"directory_id": "33788e7f53f77046ee465bfe9a10ded776215b8e",
"extension": "c",
"filename": "dominoView.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": 8506,
"license": "MIT",
"license_type": "permissive",
"path": "/src/dominoView.c",
"provenance": "stackv2-0135.json.gz:52936",
"repo_name": "AlmeidaFL/domino-game",
"revision_date": "2021-09-27T14:26:24",
"revision_id": "463b49d2c7de62dbb62a5bc7b3df1474295d49ae",
"snapshot_id": "27371cb0b6dfb99aad29f75b1ca5cfe0bf10d901",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AlmeidaFL/domino-game/463b49d2c7de62dbb62a5bc7b3df1474295d49ae/src/dominoView.c",
"visit_date": "2023-08-11T07:14:57.885118"
} | stackv2 | #include "dominoView.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void mostrarMenu(){
barraN();
barraN();
printf("\t\t\t\t\t::::::::: :::::::: :::: :::: ::::::::::: :::: ::: ::::::::\n");
printf("\t\t\t\t\t:+: :+: :+: :+: +:+:+: :+:+:+ :+: :+:+: :+: :+: :+:\n");
printf("\t\t\t\t\t+:+ +:+ +:+ +:+ +:+ +:+:+ +:+ +:+ :+:+:+ +:+ +:+ +:+\n");
printf("\t\t\t\t\t+#+ +:+ +#+ +:+ +#+ +:+ +#+ +#+ +#+ +:+ +#+ +#+ +:+\n");
printf("\t\t\t\t\t+#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+\n");
printf("\t\t\t\t\t#+# #+# #+# #+# #+# #+# #+# #+# #+#+# #+# #+#\n");
printf("\t\t\t\t\t######### ######## ### ### ########### ### #### ######## \n\n\n");
printf("\t\t\t\t\t1)Iniciar novo Jogo (PESSOA X PESSOA)\n\t\t\t\t\t2)Iniciar novo Jogo (PESSOA X PC) \n\t\t\t\t\t3)Continuar a Jogar \n\t\t\t\t\t4)Carregar Jogo \n\t\t\t\t\t5)Regras do Jogo \n\t\t\t\t\t6)Sair do Jogo \n\t\t\t\t\t7)Creditos\n");
}
void mostrarRegras(){
printf("\t\t\t\t\t\n\n_____________________________ R E G R A S _____________________________ \n\n");
printf("\t\t\t\t\t--> Inicio da Partida:\n-Sao compradas 7 pedras por ");
printf("\t\t\t\t\tjogador. As 14 pedras restantes serao \nusadas para comprar ");
printf("\t\t\t\t\tno caso do jogador nao ter a pedra da vez.\n_______________________________________________________________________\n\n");
printf("\t\t\t\t\t--> Regra Numero 1:\nO jogador com a maior pedra (6-6) comeca o jogo,");
printf("\t\t\t\t\tcolocando-a na mesa.\nCaso nenhum dos jogadores tenha a pedra 6x6, inicia");
printf("\t\t\t\t\to 5x5, 4x4, 3x3,\n2x2, 1x1, 0x0 ou a pedra com maior numero de pontos, ");
printf("\t\t\t\t\tnesta ordem.\n_______________________________________________________________________\n\n");
printf("\t\t\t\t\t--> Regra Numero 2:\nCada jogador deve tentar encaixar uma de suas pedras ");
printf("\t\t\t\t\tnas extremidades\ndo jogo na mesa.\nQuando o jogador consegue encaixar uma pedra, ");
printf("\t\t\t\t\tele compra uma da pilha.\n_______________________________________________________________________\n\n");
printf("\t\t\t\t\t--> Regra Numero 3:\nO jogo acaba quando algum jogador fica sem pedras na\n");
printf("\t\t\t\t\tmao, ou o jogo fica fechado.\n_______________________________________________________________________\n\n\n\n");
}
void embaralhaOuPrinta(){
printf("\t\t\t\t\tDeseja embaralhar as pecas (1) ou printa-las? (2) resetar as pecas (3) ou nada (4)\n");
}
void qtdJogadores(){
printf("\t\t\t\t\tQuantos Jogadores?\n");
}
void printaPecas(peca pedras[]){
for(int i = 0; i < 28; i++){
printf("\t\t\t\t\t(%d). %d|%d\n", pedras[i].posicaoPeca ,pedras[i].ladoEsquerdo, pedras[i].ladoDireto);
}
}
void printaPecasJogador(peca jogador[]){
int contador = jogador[0].contador - 1; //Est� dimininuindo -1 pois o contador se basea no tamanho do array contando do 0
printf("============================================================================== MAO =====================================================================================\n");
barraN();
printf("\t\t\t\t\t");
for(int i = 0; i <= contador; i++){
if(i == 7 || i == 14)
{
printf("\n\n\t\t\t\t\t");
}
if(jogador[i].comprada == true && jogador[i].jogadaTabuleiro == false){
if(i < contador){
printf("(%d). %d|%d ", jogador[i].posicaoPeca, jogador[i].ladoEsquerdo, jogador[i].ladoDireto);
}
else if(i == contador){
printf("(%d). %d|%d\n", jogador[i].posicaoPeca, jogador[i].ladoEsquerdo, jogador[i].ladoDireto);
}
}
}
barraN();
printf("============================================================================== *** =====================================================================================\n");
}
void printaPecasTabuleiro(peca pedras[]){
int contador = pedras[0].pecasTabuleiro;
for(int i = 27; i >= contador; i--){
if(i > contador && pedras[i].comprada != true){
printf("\t\t\t\t\t(%d). %d|%d ", pedras[i].posicaoPeca ,pedras[i].ladoEsquerdo, pedras[i].ladoDireto);
}
else if(i == contador && pedras[i].comprada != true){
printf("\t\t\t\t\t(%d). %d|%d\n", pedras[i].posicaoPeca, pedras[i].ladoEsquerdo, pedras[i].ladoDireto);
}
}
}
void menuJogador(){
printf("\n\n\t\t\t\t\t1)Mesa Principal e ver pecas \n\t\t\t\t\t2)Comprar Peca \n\t\t\t\t\t3)Jogar \n\t\t\t\t\t4)Passar Vez \n\t\t\t\t\t5)Voltar ao menu principal \n\t\t\t\t\t6)Salvar Jogo\n");
}
void exibirMesa(mesa pecasMesas[]){
int i = 0;
barraN();
barraN();
printf("--------------------------------------------------------------------------------- MESA ---------------------------------------------------------------------------------\n");
barraN();
printf("\t\t\t\t\t");
if(pecasMesas[0].qtdPecas > 0){
for(i; i < 61; i++){
if(pecasMesas[i].temPeca == true){
if(i < 60){
printf("|%d|%d| ", pecasMesas[i].ladoEsquerdo, pecasMesas[i].ladoDireito);
}
else if (i == 60){
printf("|%d|%d|\n", pecasMesas[i].ladoEsquerdo, pecasMesas[i].ladoDireito);
}
}
}
}
barraN();
printf("--------------------------------------------------------------------------------- **** ---------------------------------------------------------------------------------\n");
barraN();
}
void jogarLado(){
printf("\t\t\t\t\tVoce quer jogar no lado esquerdo (1) ou direito (2)\n");
}
void pecaAjogar(){
printf("\t\t\t\t\tQual peca voce quer jogar?\n");
}
void jogadaErrada(){
printf("\t\t\t\t\t------------------------------\n\n\t\t\t\t\tNao foi possivel realizar a jogada!!\n\t\t\t\t\tVerifique os lados\n\t\t\t\t\t------------------------------\n\n");
}
void emManutencao(){
printf("\t\t\t\t\t\n--------------\nAlgumas funcionalidades do jogador 2 nao estao funcionando\nApenas printar e comprar funcionam\n--------------");
}
void printarVencedor(int jogador){
printf("\t\t\t\t\t---- PARABENS JOGADOR %d, VOCE VENCEU -----\n", jogador);
printf("\t\t\t\t\t-------------------------------------------\n");
printf("\t\t\t\t\t ___________ \n");
printf("\t\t\t\t\t '._==_==_=_.' \n");
printf("\t\t\t\t\t .-|: |-. \n");
printf("\t\t\t\t\t | (|:. |) | \n");
printf("\t\t\t\t\t '-|:. |-' \n");
printf("\t\t\t\t\t |::. | \n");
printf("\t\t\t\t\t '::. .' \n");
printf("\t\t\t\t\t ) ( \n");
printf("\t\t\t\t\t _.' '._ \n");
printf("\t\t\t\t\t ----------------- \n");
printf("\t\t\t\t\t------------------------------------------\n");
}
void flush(){
puts("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
void pressioneTecla(){
printf("\t\t\t\t\tPressione enter para continuar:");
}
void exibeJogador(int jogado){
switch(jogado){
case 1:
printf("\n\n\t\t\t\t\tJogador 1:\n\n");
break;
case 2:
printf("\n\n\t\t\t\t\tJogador 2:\n\n");
break;
}
}
void barraN(){
printf("\n\n");
}
void printaAbrirArquivo(){
printf("\t\t\t\t\t\n\n O arquivo de save não pode ser aberto: aperte enter para continuar:");
}
void printaSalvando(){
printf("\t\t\t\t\t\n\nArquivo aberto: Salvando.\n\n");
}
void printaSalvandoRodada(){
printf("\t\t\t\t\t\n\nArquivo aberto: Salvando rodada.\n\n");
}
void flush_in(){
char op;
while ((op = fgetc(stdin)) != EOF && op != '\n'){};
}
void tabulacao(){
printf("\t\t\t\t\t");
}
void naoPassa(){
printf("\n\t\t\t\t\tVoce ainda tem peca ou eh possivel comprar mais! Nao e hora de passar...\n");
}
void creditos(){
printf("\n\t\t\t\t\t\t\t\t\t PUC-SP\n");
printf("\n\t\t\t\t\t\t\t------------------------------------------------\n");
printf("\n\t\t\t\t\t\t\t|\t\tLuis Felipe\t\t\t| \n\t\t\t\t\t\t\t|\t\tGuilherme Monteiro\t\t| \n\t\t\t\t\t\t\t|\t\tGustavo Yugi\t\t\t| \n\t\t\t\t\t\t\t|\t\tEduardo Cruz\t\t\t| \n\t\t\t\t\t\t\t|\t\tLeonardo Souza\t\t\t|\n");
printf("\n\t\t\t\t\t\t\t------------------------------------------------\n");
barraN();
barraN();
}
| 2.546875 | 3 |
2024-11-18T23:20:00.097965+00:00 | 2019-12-01T06:22:25 | fd5795552e45352c841e7ec8bfde1a211c3a8d8c | {
"blob_id": "fd5795552e45352c841e7ec8bfde1a211c3a8d8c",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-01T06:22:25",
"content_id": "01b985d6f5538f03b0bdca11a214d947ddcf284f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f0ee972868e2899e42be0252fe4e8320f7237bd8",
"extension": "c",
"filename": "Touch.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": 33173,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/emulator/emul_fmsx/src/ap/fMSX/core/EMULib/Touch.c",
"provenance": "stackv2-0135.json.gz:53195",
"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_fmsx/src/ap/fMSX/core/EMULib/Touch.c",
"visit_date": "2023-03-16T02:55:41.988393"
} | stackv2 | /** EMULib Emulation Library *********************************/
/** **/
/** Touch.c **/
/** **/
/** This file contains functions that simulate joystick and **/
/** dialpad with the touch screen. It is normally used from **/
/** the platform-dependent functions that know where to get **/
/** pen coordinates from and where to draw pen cues to. **/
/** **/
/** Copyright (C) Marat Fayzullin 2008-2018 **/
/** You are not allowed to distribute this software **/
/** commercially. Please, notify me, if you make any **/
/** changes to this file. **/
/*************************************************************/
#ifndef DEFINE_ONCE
#define DEFINE_ONCE
#include "EMULib.h"
#include "Console.h"
#include "Touch.h"
#include <string.h>
#include <stdio.h>
#define XKEYS 12 /* Number of keys in a row */
#define YKEYS 6 /* Number of key rows */
#define MAX_PENJOY_WIDTH 320 /* Max pen joystick width */
#if defined(ANDROID)
static int KEYSTEP = 39; /* Key step in pixels */
static int KEYSIZE = 31; /* Key size in pixels */
static int CHRSIZE = 16; /* Key label size */
#elif defined(MEEGO)
static int KEYSTEP = 46; /* Key step in pixels */
static int KEYSIZE = 38; /* Key size in pixels */
static int CHRSIZE = 16; /* Key label size */
#elif defined(MAEMO)
static int KEYSTEP = 34; /* Key step in pixels */
static int KEYSIZE = 30; /* Key size in pixels */
static int CHRSIZE = 16; /* Key label size */
#else
static int KEYSTEP = 14; /* Key step in pixels */
static int KEYSIZE = 12; /* Key size in pixels */
static int CHRSIZE = 8; /* Key label size */
#endif
/* Currently selected virtual keyboard key */
static int KBDXPos = 0;
static int KBDYPos = 0;
/* Horizontal offsets of virtual keyboard lines */
#if defined(ANDROID) || defined(MEEGO)
static const int KBDOffsets[YKEYS] = { 0,0,0,0,32,16 };
#elif defined(MAEMO)
static const int KBDOffsets[YKEYS] = { 0,0,0,0,20,10 };
#else
static const int KBDOffsets[YKEYS] = { 0,0,0,0,8,4 };
#endif
/* Characters printed on virtual keyboard keys */
static const char *KBDLines[YKEYS+1] =
{
"\33\20\21\22\23\24\25\26\27\16\17\32",
"1234567890-=",
"\11QWERTYUIOP\10",
"^ASDFGHJKL;\15",
"ZXCVBNM,./",
"[] \\'",
0
};
static const char *PenCues[32] =
{
"LEFT","RIGHT","UP","DOWN","A","B","L","R",
"START","SELECT","EXIT","X","Y",0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
static int CueSizes[32] =
{
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
/* Characters returned from virtual keyboard */
static const unsigned char KBDKeys[YKEYS][XKEYS] =
{
{
0x1B,CON_F1,CON_F2,CON_F3,CON_F4,CON_F5,
CON_F6,CON_F7,CON_F8,CON_INSERT,CON_DELETE,CON_STOP
},
{ '1','2','3','4','5','6','7','8','9','0','-','=' },
{ CON_TAB,'Q','W','E','R','T','Y','U','I','O','P',CON_BS },
{ '^','A','S','D','F','G','H','J','K','L',';',CON_ENTER },
{ 'Z','X','C','V','B','N','M',',','.','/',0,0 },
{ '[',']',' ',' ',' ',' ',' ','\\','\'',0,0,0 }
};
static unsigned int FFWDButtons = 0;
static unsigned int MENUButtons = 0;
static int JoyCuesSetup = 0;
#if defined(ANDROID) || defined(MEEGO)
static int OldCueImgW = 0;
#endif
static const struct { int W,H,X,Y; } DefButtons[] =
{
{ 256,256, 8, -48-16-256, },
{ 128,128, -128-8,48+8, },
{ 128,128, -128-8,48+8+128+8, },
{ 128,48, 0, 0, },
{ 128,48, -128, 0, },
{ 128,48, 0, -48, },
{ 128,48, -128, -48, },
{ 128,48, -256-8,-48, },
};
static struct
{
int Bit;
Image Img;
int W,H,X,Y;
unsigned int Flags;
} Buttons[] =
{
{ 4, {0}, 0,0,0,0,0 }, // FIRE-A
{ 5, {0}, 0,0,0,0,0 }, // FIRE-B
{ 6, {0}, 0,0,0,0,0 }, // FIRE-L
{ 7, {0}, 0,0,0,0,0 }, // FIRE-R
{ 9, {0}, 0,0,0,0,0 }, // SELECT
{ 8, {0}, 0,0,0,0,0 }, // START
{ 11, {0}, 0,0,0,0,0 }, // FIRE-X
{ -1, {0}, 0,0,0,0,0 }, // Arrows (have to be last)
{ -2, {0}, 0,0,0,0,0 }
};
static int abs(int X) { return(X>=0? X:-X); }
/** GetKbdWidth()/GetKbdHeight() *****************************/
/** Return virtual keyboard dimensions. **/
/*************************************************************/
unsigned int GetKbdWidth() { return(KEYSTEP*XKEYS+8); }
unsigned int GetKbdHeight() { return(KEYSTEP*YKEYS+8+CHRSIZE); }
/** GenericFullJoystick() ************************************/
/** Treat whole screen as one big directional pad. Result **/
/** compatible with GetJoystick() (arrows only though). **/
/*************************************************************/
unsigned int GenericFullJoystick(int X,int Y,int W,int H)
{
/* Just consider the whole screen as one big directional pad */
return(
(X<(W>>1)-(W>>3)? BTN_LEFT : X>(W>>1)+(W>>3)? BTN_RIGHT : 0)
| (Y<(H>>1)-(H>>3)? BTN_UP : Y>(H>>1)+(H>>3)? BTN_DOWN : 0)
);
}
/** GenericPenJoystick() *************************************/
/** Get simulated joystick buttons from touch screen UI. **/
/** Result compatible with GetJoystick(). **/
/*************************************************************/
unsigned int GenericPenJoystick(int X,int Y,int W,int H)
{
unsigned int J;
int W3;
/* Simulate joystick when pen touches the screen at X,Y */
J = 0;
/* Don't accept touches outside of the window frame */
if((X<0)||(Y<0)||(X>=W)||(Y>=H)) return(0);
W3 = W>MAX_PENJOY_WIDTH*3? MAX_PENJOY_WIDTH:W/3;
/* Top 1/16 of the widget: FIREL and FIRER */
if(Y<(H>>3))
{ if(X<W3) J|=BTN_FIREL; else if(X>=W-W3) J|=BTN_FIRER; }
/* Bottom 1/16 of the widget: SELECT/EXIT and START */
if(!J&&(Y>=(H-(H>>3))))
{ if(X<W3) J|=BTN_SELECT|BTN_EXIT; else if(X>=W-W3) J|=BTN_START; }
/* Right upper corner of the screen is the fire buttons */
if(!J&&(X>=W-(W3>>1))&&(Y>=(H>>3))&&(Y<(H>>3)+W3+(W3>>3)))
{
/* Fire buttons overlap */
if(Y<=(H>>3)+(W3>>1)+(W3>>3)) J|=BTN_FIREA;
if(Y>=(H>>3)+(W3>>1)) J|=BTN_FIREB;
}
/* Left 1/3 of the screen is the directional pad */
if(!J&&(X<W3)&&(Y>=H-(H>>3)-W3))
{
Y-=H-W3-(H>>3);
W3/=3;
if(X<W3) J|=BTN_LEFT; else if(X>=(W3<<1)) J|=BTN_RIGHT;
if(Y<W3) J|=BTN_UP; else if(Y>=(W3<<1)) J|=BTN_DOWN;
}
/* Apply dynamically assigned FFWD and MENU buttons */
J |= J&FFWDButtons? BTN_FFWD:0;
J |= J&MENUButtons? BTN_MENU:0;
/* Done, return simulated "joystick" state */
return(J);
}
/** GenericPenDialpad() **************************************/
/** Get simulated dialpad buttons from touch screen UI. **/
/*************************************************************/
unsigned char GenericPenDialpad(int X,int Y,int W,int H)
{
int W3,H2;
/* Dialpad is the middle 1/3 of the screen */
W3 = W>MAX_PENJOY_WIDTH*3? MAX_PENJOY_WIDTH:W/3;
H2 = H>W3? ((H-W3)>>1):0;
W3 = (W-W3)>>1;
return(
(Y>=H2)&&(Y<H-H2)&&(X>=W3)&&(X<W-W3)?
3*(X-W3)/(W-(W3<<1))+3*((Y-H2)/((H-(H2<<1))>>2))+1 : 0
);
}
/** GenericPenKeyboard() *************************************/
/** Get virtual on-screen keyboard buttons. **/
/*************************************************************/
unsigned char GenericPenKeyboard(int X,int Y,int W,int H)
{
int J;
/* Pen coordinates relative to keyboard's top left corner */
X -= W-KEYSTEP*XKEYS-8;
Y -= H-KEYSTEP*YKEYS-8;
/* Pen must be inside the keyboard */
if((X<0)||(Y<0)) return(0);
/* Keyboard row index */
Y/= KEYSTEP;
if(Y>=YKEYS) return(0);
/* Adjust for row position on screen */
for(J=0;J<=Y;++J) X-=KBDOffsets[J];
if(X<0) return(0);
/* Keyboard column index */
X/= KEYSTEP;
if(X>=XKEYS) return(0);
/* Memorize last pressed key */
KBDXPos = X;
KBDYPos = Y;
/* Return key */
return(KBDKeys[Y][X]);
}
/** GenericDialKeyboard() ************************************/
/** Process dialpad input to the virtual keyboard. Returns **/
/** virtual keyboard key if selected, or 0 if not. **/
/*************************************************************/
unsigned char GenericDialKeyboard(unsigned char Key)
{
/* Interpret input key */
switch(Key)
{
case CON_LEFT:
KBDXPos = (KBDXPos>0? KBDXPos:strlen(KBDLines[KBDYPos]))-1;
break;
case CON_RIGHT:
KBDXPos = KBDXPos<strlen(KBDLines[KBDYPos])-1? KBDXPos+1:0;
break;
case CON_UP:
KBDYPos = KBDYPos>0? KBDYPos-1:YKEYS-1;
KBDXPos = KBDXPos<strlen(KBDLines[KBDYPos])? KBDXPos:strlen(KBDLines[KBDYPos])-1;
break;
case CON_DOWN:
KBDYPos = KBDYPos<YKEYS-1? KBDYPos+1:0;
KBDXPos = KBDXPos<strlen(KBDLines[KBDYPos])? KBDXPos:strlen(KBDLines[KBDYPos])-1;
break;
case CON_OK:
/* Return ASCII character */
return(KBDLines[KBDYPos][KBDXPos]);
}
/* Key has not been interpreted */
return(0);
}
/** SetPenCues() *********************************************/
/** Set pen cues for given buttons to a given string. **/
/*************************************************************/
void SetPenCues(unsigned int Buttons,const char *CueText)
{
unsigned int J;
if(!strcmp(CueText,"FFWD")||!strcmp(CueText,"SLOW")) FFWDButtons|=Buttons; else FFWDButtons&=~Buttons;
if(!strcmp(CueText,"MENU")) MENUButtons|=Buttons; else MENUButtons&=~Buttons;
for(J=0;J<sizeof(PenCues)/sizeof(PenCues[0]);++J)
if(Buttons&(1<<J))
{
PenCues[J] = CueText;
CueSizes[J] = strlen(CueText)*CHRSIZE;
}
#ifdef ANDROID
// On Android, request update to the screen overlay
UpdateOverlay();
#endif
}
/** SetPenKeyboard() *****************************************/
/** Set pen keyboard dimensions. **/
/*************************************************************/
void SetPenKeyboard(unsigned int KeyStep,unsigned int KeySize,unsigned int ChrSize)
{
int J;
/* Character size must be a multiple of 8 */
CHRSIZE = ChrSize>8? (ChrSize&~7):8;
/* Make sure keys do not overlap */
if(KeySize+4>KeyStep) KeySize=KeyStep-4;
/* Make sure key labels fit into keys */
if(CHRSIZE+2>KeySize) KeySize=CHRSIZE+2;
/* Now grow key step again, if needed */
if(KeySize+4>KeyStep) KeyStep=KeySize+4;
/* Assign new virtual key dimensions */
KEYSIZE = KeySize;
KEYSTEP = KeyStep;
/* Recompute cue lengths */
for(JoyCuesSetup=1,J=0;J<sizeof(PenCues)/sizeof(PenCues[0]);++J)
CueSizes[J] = PenCues[J]? strlen(PenCues[J])*CHRSIZE:0;
}
/** InitFinJoystick() ****************************************/
/** Initialize finger joystick images by cropping them from **/
/** the given source image. Returns number of buttons set **/
/** successfully (i.e. found inside the Src bounds). **/
/*************************************************************/
int InitFinJoystick(const Image *Src)
{
int J,X0,Y0;
/* Initialize virtual joystick images */
for(J=0;Buttons[J].Bit>-2;++J)
{
/* Free the existing image */
FreeImage(&Buttons[J].Img);
/* If source image supplied... */
if(Src)
{
/* Compute button's top-left corner position in the Src */
X0 = DefButtons[J].X + (DefButtons[J].X<0? Src->W:0);
Y0 = DefButtons[J].Y + (DefButtons[J].Y<0? Src->H:0);
/* Crop the button out of the Src image */
CropImage(&Buttons[J].Img,Src,X0,Y0,DefButtons[J].W,DefButtons[J].H);
}
/* Reset button size and position to the defaults */
Buttons[J].X = DefButtons[J].X;
Buttons[J].Y = DefButtons[J].Y;
Buttons[J].W = DefButtons[J].W;
Buttons[J].H = DefButtons[J].H;
/* Button now visible and enabled */
Buttons[J].Flags = 0;
}
/* Return number of buttons initialized */
return(J);
}
/** SetFinButton() *******************************************/
/** Set finger joystick button(s) to given location. When **/
/** Img=0, create wireframe buttons. When Mask=0, set the **/
/** directional buttons image and location. When Mask ORed **/
/** with BTN_INVISIBLE, create invisible buttons. Returns **/
/** the number of virtual buttons set or 0 for none. **/
/*************************************************************/
int SetFinButton(unsigned int Mask,const Image *Img,int X,int Y,int W,int H)
{
unsigned int Flags;
int I,J,Result;
/* Special Mask bits: make button invisible or disable it */
Flags = Mask&BTN_INVISIBLE;
Mask = Mask&~BTN_INVISIBLE;
/* No image for invisible buttons */
if(Flags&BTN_INVISIBLE) Img=0;
/* When Mask=0, we are assigning the arrow buttons */
if(!Mask) Mask=0x80000000;
for(J=Result=0;Mask;++J,Mask>>=1)
if(Mask&1)
for(I=0;Buttons[I].Bit>-2;++I)
if((Buttons[I].Bit==J) || ((Buttons[I].Bit==-1)&&(J==31)))
{
/* When Img=0, make a wireframe or invisible button */
if(Img) CropImage(&Buttons[I].Img,Img,0,0,W,H);
else FreeImage(&Buttons[I].Img);
Buttons[I].Flags = Flags;
Buttons[I].X = X;
Buttons[I].Y = Y;
Buttons[I].W = W;
Buttons[I].H = H;
++Result;
}
/* Return number of modified buttons */
return(Result);
}
/** GenericFinJoystick() *************************************/
/** Return the BTN_* bits corresponding to position X,Y of **/
/** the finger joystick shown in Dst. **/
/*************************************************************/
unsigned int GenericFinJoystick(int X,int Y,int W,int H,unsigned int CurState)
{
unsigned int Result,I,J;
int X0,Y0,AX,AY,W0,H0;
/* For every known button... */
for(J=Result=0;Buttons[J].Bit>-2;++J)
{
/* Compute finger position relative to the button */
X0 = X - Buttons[J].X - (Buttons[J].X<0? W:0);
Y0 = Y - Buttons[J].Y - (Buttons[J].Y<0? H:0);
/* If button has been pressed... */
if(
((X0>=0) && (Y0>=0) && (X0<Buttons[J].W) && (Y0<Buttons[J].H))
|| ((Buttons[J].Bit<0) && !Result && (CurState&BTN_ARROWS))
)
{
/* ...and it is a normal button... */
if(Buttons[J].Bit>=0)
{
/* Compute button mask from bit number */
I = 1<<Buttons[J].Bit;
/* Also apply dynamically assigned FFWD and MENU buttons */
Result |= I|(I&FFWDButtons? BTN_FFWD:0)|(I&MENUButtons? BTN_MENU:0);
}
else
{
/* We are dealing with the joypad arrows here */
W0 = Buttons[J].W>>1;
H0 = Buttons[J].H>>1;
X0 -= W0;
Y0 -= H0;
AX = abs(X0);
AY = abs(Y0);
/* If finger is outside the joypad, keep pressing previous arrows */
if((AX>W0) || (AY>H0))
Result |= CurState & ((X0<0? BTN_LEFT:BTN_RIGHT)|(Y0<0? BTN_UP:BTN_DOWN));
/* Joypad's center is inactive at 1/16 of the radius */
else if((AX>=(W0>>3)) || (AY>=(H0>>3)))
{
/* This is joypad's edge at 1/4 of the radius */
W0 = W0>>1;
H0 = H0>>1;
Result |=
((X0<0) && ((AX>AY) || (AX>W0))? BTN_LEFT:0)
| ((Y0<0) && ((AY>AX) || (AY>H0))? BTN_UP:0)
| ((X0>0) && ((AX>AY) || (AX>W0))? BTN_RIGHT:0)
| ((Y0>0) && ((AY>AX) || (AY>H0))? BTN_DOWN:0);
}
}
}
}
/* Done */
return(Result);
}
#endif /* DEFINE_ONCE */
#if !defined(BPP32) && !defined(BPP24) && !defined(BPP16) && !defined(BPP8)
/* When pixel size not defined, compile in the universal multiplexer */
#include "TouchMux.h"
#else
#if defined(ANDROID) || defined(MEEGO)
#define CLR_NORMALF PIXEL(64,255,64) /* Normal key foreground */
#else
#define CLR_NORMALF PIXEL(0,0,0) /* Normal key foreground */
#define CLR_NORMALB PIXEL(255,255,255) /* Normal key background */
#endif
#define CLR_ACTIVEF PIXEL(255,255,255) /* Active key foreground */
#define CLR_ACTIVEB PIXEL(255,64,64) /* Active key background */
#define CLR_FPS PIXEL(255,128,255) /* Framerate counter color */
#define CLR_CUES PIXEL(127,127,127) /* Touch joypad cues color */
/** PrintXY2() ***********************************************/
/** Print a string in given color on transparent background.**/
/*************************************************************/
static void PrintXY2(Image *Img,const char *S,int X,int Y,pixel FG)
{
const unsigned char *C;
pixel *P;
int I,J,K,N;
X = X<0? 0:X>Img->W-CHRSIZE? Img->W-CHRSIZE:X;
Y = Y<0? 0:Y>Img->H-CHRSIZE? Img->H-CHRSIZE:Y;
for(K=X;*S;S++)
switch(*S)
{
case '\n':
K=X;Y+=CHRSIZE;
if(Y>Img->H-CHRSIZE) Y=0;
break;
default:
P=(pixel *)Img->Data+Img->L*Y+K;
for(C=CONGetFont()+(*S<<3),J=8;J;P+=Img->L*(CHRSIZE/8),++C,--J)
for(I=0,N=(int)*C<<24;N&&(I<CHRSIZE);I+=CHRSIZE/8,N<<=1)
if(N&0x80000000) P[I+1]=P[I]=FG;
K+=CHRSIZE;
if(X>Img->W-CHRSIZE)
{
K=0;Y+=CHRSIZE;
if(Y>Img->H-CHRSIZE) Y=0;
}
break;
}
}
/** DrawVLine()/DrawHLine() **********************************/
/** Draw dotted lines used to show cues for PenJoystick(). **/
/*************************************************************/
static void DrawVLine(Image *Img,int X,int Y1,int Y2,pixel Color)
{
pixel *P;
int J;
if((X<0)||(X>=Img->W)) return;
Y1 = Y1<0? 0:Y1>=Img->H? Img->H-1:Y1;
Y2 = Y2<0? 0:Y2>=Img->H? Img->H-1:Y2;
if(Y1>Y2) { J=Y1;Y1=Y2;Y2=J; }
P = (pixel *)Img->Data+Img->L*Y1+X;
for(J=Y1;J<=Y2;J+=4) { *P=Color;P+=Img->L<<2; }
}
static void DrawHLine(Image *Img,int X1,int X2,int Y,pixel Color)
{
pixel *P;
int J;
if((Y<0)||(Y>=Img->H)) return;
X1 = X1<0? 0:X1>=Img->W? Img->W-1:X1;
X2 = X2<0? 0:X2>=Img->W? Img->W-1:X2;
if(X1>X2) { J=X1;X1=X2;X2=J; }
P = (pixel *)Img->Data+Img->L*Y+X1;
for(J=X1;J<=X2;J+=4) { *P=Color;P+=4; }
}
/** DrawDialpad() ********************************************/
/** Draw virtual dialpad in a given image. **/
/*************************************************************/
void DrawDialpad(Image *Img,int Color)
{
int W,H,H2,W9,W3;
/* Use default color, if requested */
if(Color<0) Color=CLR_CUES;
W = Img->W;
H = Img->H;
W3 = W>MAX_PENJOY_WIDTH*3? MAX_PENJOY_WIDTH:W/3;
H2 = H>W3? ((H-W3)>>1):0;
W9 = W3/3;
W3 = (W-W3)>>1;
DrawHLine(Img,W3,W-W3,H2,Color);
DrawHLine(Img,W3,W-W3,(H2>>1)+(H>>2),Color);
DrawHLine(Img,W3,W-W3,H>>1,Color);
DrawHLine(Img,W3,W-W3,(H>>1)-(H2>>1)+(H>>2),Color);
DrawHLine(Img,W3,W-W3,H-H2-1,Color);
DrawVLine(Img,W3,H2,H-H2-1,Color);
DrawVLine(Img,W3+W9,H2,H-H2-1,Color);
DrawVLine(Img,W-W3-W9,H2,H-H2-1,Color);
DrawVLine(Img,W-W3,H2,H-H2-1,Color);
PrintXY2(Img,"1",W3+2,H2+2,Color);
PrintXY2(Img,"2",W3+W9+2,H2+2,Color);
PrintXY2(Img,"3",W-W3-W9+2,H2+2,Color);
PrintXY2(Img,"4",W3+2,(H2>>1)+(H>>2)+2,Color);
PrintXY2(Img,"5",W3+W9+2,(H2>>1)+(H>>2)+2,Color);
PrintXY2(Img,"6",W-W3-W9+2,(H2>>1)+(H>>2)+2,Color);
PrintXY2(Img,"7",W3+2,(H>>1)+2,Color);
PrintXY2(Img,"8",W3+W9+2,(H>>1)+2,Color);
PrintXY2(Img,"9",W-W3-W9+2,(H>>1)+2,Color);
PrintXY2(Img,"*",W3+2,(H>>1)-(H2>>1)+(H>>2)+2,Color);
PrintXY2(Img,"0",W3+W9+2,(H>>1)-(H2>>1)+(H>>2)+2,Color);
PrintXY2(Img,"#",W-W3-W9+2,(H>>1)-(H2>>1)+(H>>2)+2,Color);
}
/** DrawPenCues() ********************************************/
/** Overlay dotted cue lines for using PenJoystick() onto a **/
/** given image. Show dialpad cues if requested. **/
/*************************************************************/
void DrawPenCues(Image *Img,int ShowDialpad,int Color)
{
int W,H,W9,W3;
/* Use default color, if requested */
if(Color<0) Color=CLR_CUES;
/* Set up pen keyboard for the first time */
if(!JoyCuesSetup) SetPenKeyboard(KEYSTEP,KEYSIZE,CHRSIZE);
W = Img->W;
H = Img->H;
W3 = Img->W>MAX_PENJOY_WIDTH*3? MAX_PENJOY_WIDTH:W/3;
W9 = W3/3;
/* Vertical edges */
DrawVLine(Img,W3,0,H>>3,Color);
DrawVLine(Img,W3,H-W3-(H>>3),H-1,Color);
DrawVLine(Img,W-W3,0,H>>3,Color);
DrawVLine(Img,W-W3,H-(H>>3),H,Color);
/* Corner buttons */
DrawHLine(Img,0,W3,H>>3,Color);
DrawHLine(Img,W-W3,W-1,H>>3,Color);
DrawHLine(Img,0,W3,H-(H>>3),Color);
DrawHLine(Img,W-W3,W-1,H-(H>>3),Color);
/* Fire buttons (with overlap) */
DrawHLine(Img,W-(W3>>1),W-1,(H>>3)+(W3>>1),Color);
DrawHLine(Img,W-(W3>>1),W-1,(H>>3)+(W3>>1)+(W3>>3),Color);
DrawHLine(Img,W-(W3>>1),W-1,(H>>3)+W3+(W3>>3),Color);
DrawVLine(Img,W-(W3>>1),H>>3,(H>>3)+W3+(W3>>3),Color);
/* Directional buttons */
DrawVLine(Img,W9,H-W3-(H>>3),H-(H>>3),Color);
DrawVLine(Img,W3-W9,H-W3-(H>>3),H-(H>>3),Color);
DrawHLine(Img,0,W3,H-W3-(H>>3),Color);
DrawHLine(Img,0,W3,H-(W9<<1)-(H>>3),Color);
DrawHLine(Img,0,W3,H-W9-(H>>3),Color);
/* Button labels */
if(PenCues[4]) PrintXY2(Img,PenCues[4],W-CueSizes[4]-2,(H>>3)+2,Color);
if(PenCues[5]) PrintXY2(Img,PenCues[5],W-CueSizes[5]-2,(H>>3)+(W3>>1)+(W3>>3)+2,Color);
if(PenCues[6]) PrintXY2(Img,PenCues[6],2,2,Color);
if(PenCues[7]) PrintXY2(Img,PenCues[7],W-CueSizes[7]-2,2,Color);
if(PenCues[8]) PrintXY2(Img,PenCues[8],W-CueSizes[8]-2,H-(H>>3)+2,Color);
if(PenCues[9]) PrintXY2(Img,PenCues[9],2,H-(H>>3)+2,Color);
/* Arrow labels */
if(PenCues[0]&&(CueSizes[0]<=W9)) PrintXY2(Img,PenCues[0],2,H-(W9<<1)-(H>>3)+2,Color);
if(PenCues[1]&&(CueSizes[1]<=W9)) PrintXY2(Img,PenCues[1],(W9<<1)+2,H-(W9<<1)-(H>>3)+2,Color);
if(PenCues[2]&&(CueSizes[2]<=W9)) PrintXY2(Img,PenCues[2],W9+2,H-W3-(H>>3)+2,Color);
if(PenCues[3]&&(CueSizes[3]<=W9)) PrintXY2(Img,PenCues[3],W9+2,H-W9-(H>>3)+2,Color);
/* If requested, show on-screen dialpad */
if(ShowDialpad) DrawDialpad(Img,Color);
}
/** DrawKeyboard() *******************************************/
/** Draw virtual keyboard in a given image. Key modifiers **/
/** and the key code passed in CurKey are highlighted. **/
/*************************************************************/
void DrawKeyboard(Image *Img,unsigned int CurKey)
{
int X,Y,J,I,K,L;
char S[2];
pixel *P;
/* Keyboard in the right-bottom corner by default */
X = Img->W-GetKbdWidth();
Y = Img->H-GetKbdHeight();
if((X<0)||(Y<0)) return;
/* Draw modifiers */
if(CurKey&CON_MODES)
{
J=X;
if(CurKey&CON_SHIFT) { PrintXY2(Img,"SHIFT",J,Y,CLR_ACTIVEB);J+=6*CHRSIZE; }
if(CurKey&CON_CONTROL) { PrintXY2(Img,"CTRL",J,Y,CLR_ACTIVEB);J+=5*CHRSIZE; }
if(CurKey&CON_ALT) { PrintXY2(Img,"ALT",J,Y,CLR_ACTIVEB);J+=4*CHRSIZE; }
}
/* Draw keyboard under modifiers */
Y += CHRSIZE;
/* Draw keys */
for(I=J=0,S[1]='\0';KBDLines[I];++I,Y+=KEYSTEP,X+=KBDOffsets[I]-J*KEYSTEP)
for(J=0;KBDLines[I][J];++J,X+=KEYSTEP)
{
/* Draw key frame */
P = (pixel *)Img->Data
+ Img->L*(Y+(KEYSTEP-KEYSIZE)/2)
+ X+(KEYSTEP-KEYSIZE)/2;
/* Highlight current key */
if(KBDKeys[I][J]==(CurKey&CON_KEYCODE))
{
#ifdef CLR_ACTIVEB
for(K=1;K<KEYSIZE-1;++K) P[K]=CLR_ACTIVEB;
for(K=1,P+=Img->L;K<KEYSIZE-1;++K,P+=Img->L)
for(L=0;L<KEYSIZE;++L) P[L]=CLR_ACTIVEB;
for(K=1;K<KEYSIZE-1;++K) P[K]=CLR_ACTIVEB;
#endif
K=CLR_ACTIVEF;
}
else
{
for(K=1;K<KEYSIZE-1;++K) P[K]=CLR_NORMALF;
for(K=1,P+=Img->L;K<KEYSIZE-1;++K,P+=Img->L)
{
#ifdef CLR_NORMALB
for(L=1;L<KEYSIZE-1;++L) P[L]=CLR_NORMALB;
#endif
P[0]=P[KEYSIZE-1]=CLR_NORMALF;
}
for(K=1;K<KEYSIZE-1;++K) P[K]=CLR_NORMALF;
K=CLR_NORMALF;
}
/* Draw key label */
S[0]=KBDLines[I][J];
PrintXY2(Img,S,X+(KEYSTEP-CHRSIZE)/2,Y+(KEYSTEP-CHRSIZE)/2,K);
}
}
/** DrawFinJoystick() ****************************************/
/** Draw finger joystick into given destination image. When **/
/** DW=0 or DWH=0, the whole image will be updated. When **/
/** DWxDH+DX+DY represent a dirty rectangle inside Dst, the **/
/** function will only update joystick buttons overlapping **/
/** this rectangle, representing them with dotted lines. **/
/** Returns the number of buttons overlapping the dirty **/
/** rectangle. **/
/*************************************************************/
int DrawFinJoystick(Image *Dst,int DX,int DY,int DW,int DH,int TextColor)
{
int Result,X0,Y0,X1,Y1,J,NeedFrame,NeedLabel;
Image Dirty;
/* Use default cue color, if requested */
if(TextColor<0) TextColor=CLR_CUES;
/* Compute position of the "dirty" rectangle in the middle */
if(!DW) DX=0;
if(!DH) DY=0;
/* This image corresponds to the "dirty" rectangle, if given */
CropImage(&Dirty,Dst,DX,DY,DW? DW:Dst->W,DH? DH:Dst->H);
/* Draw controls */
for(J=Result=0;Buttons[J].Bit>-2;++J)
{
X0 = Buttons[J].X + (Buttons[J].X<0? Dst->W:0) - DX;
Y0 = Buttons[J].Y + (Buttons[J].Y<0? Dst->H:0) - DY;
X1 = X0 + Buttons[J].W;
Y1 = Y0 + Buttons[J].H;
NeedLabel = Buttons[J].W && Buttons[J].H;
NeedFrame = 0;
/* If need to draw something... */
if(!(Buttons[J].Flags&BTN_INVISIBLE) && NeedLabel)
{
/* If "dirty" rectangle given... */
if(DW && DH)
{
/* Image obscures "dirty" rectangle: will draw frame and label */
if((X0<DW) && (Y0<DH) && (X1>=0) && (Y1>=0))
{ NeedFrame=NeedLabel=1;++Result; }
}
else
{
/* Draw frame if no image data */
if(!Buttons[J].Img.Data) NeedFrame=1;
else IMGCopy(Dst,X0,Y0,&Buttons[J].Img,0,0,Buttons[J].W,Buttons[J].H,PIXEL(255,0,255));
/* Draw label */
NeedLabel=1;
}
}
/* If need to draw a frame... */
if(NeedFrame)
{
/* Draw button frame */
DrawVLine(&Dirty,X0,Y0,Y1-1,TextColor);
DrawVLine(&Dirty,X1-1,Y0,Y1-1,TextColor);
DrawHLine(&Dirty,X0,X1-1,Y0,TextColor);
DrawHLine(&Dirty,X0,X1-1,Y1-1,TextColor);
/* Draw arrow pad */
if(Buttons[J].Bit<0)
{
int I;
I = (X1-X0)/3;
DrawVLine(&Dirty,X0+I,Y0,Y1-1,TextColor);
DrawVLine(&Dirty,X1-I,Y0,Y1-1,TextColor);
I = (Y1-Y0)/3;
DrawHLine(&Dirty,X0,X1-1,Y0+I,TextColor);
DrawHLine(&Dirty,X0,X1-1,Y1-I,TextColor);
}
}
/* If need to draw label and the label exists... */
if(NeedLabel && (Buttons[J].Bit>=0) && PenCues[Buttons[J].Bit])
PrintXY2(
Dst,
PenCues[Buttons[J].Bit],
((X0+X1-CueSizes[Buttons[J].Bit])>>1)+DX,
((Y0+Y1-CHRSIZE)>>1)+DY,
TextColor
);
}
/* Return number of buttons overlapping "safe" rectangle */
return(Result);
}
/** RenderVideo() ********************************************/
/** Draw video buffer to a given image. Return 0 on failure **/
/** or destination rectangle size inside OutImg on success. **/
/*************************************************************/
unsigned int RenderVideo(Image *OutImg,Image *CueImg,int Effects,int PenKey,int FrameRate)
{
unsigned int DW,DH,SW,SH,X,Y,W,H,J;
Image TmpImg;
/* Safety check */
if(!VideoImg || !VideoImg->Data) return(0);
#ifdef USE_GLES2
// When using GLES2 shaders, do not apply software effects
if(Effects&EFF_GLES) Effects&=~(EFF_RASTER_ALL|EFF_MASK_ALL);
#endif
if(Effects&EFF_DIRECT)
{
W = VideoImg->W;
H = VideoImg->H;
X = 0;
Y = 0;
}
else
{
W = VideoW;
H = VideoH;
X = VideoX;
Y = VideoY;
}
/* Determine destination image dimensions */
if(!OutImg)
{
/* If no destination image given, we assume VideoImg */
CropImage(&TmpImg,VideoImg,X,Y,W,H);
CueImg = CueImg? CueImg:&TmpImg;
OutImg = &TmpImg;
DW = W;
DH = H;
}
else if(!(Effects&EFF_SCALE)) { DW=W;DH=H; }
else if(Effects&EFF_STRETCH) { DW=OutImg->W;DH=OutImg->H; }
else
{
DW = W/H;
DH = H/W;
SW = (Effects&EFF_4X3? 4*H/3:W)*(DH>0? DH:1);
SH = H*(DW>0? DW:1);
DW = SW*OutImg->H/SH;
DH = SH*OutImg->W/SW;
if(DW>OutImg->W) DW=OutImg->W; else DH=OutImg->H;
}
/* Get current interpolation setting */
J = Effects&EFF_SOFTEN_ALL;
/* If destination image has not been given... */
if(OutImg==&TmpImg)
{
/* We do not copy or scale */
}
/* EFF_SOFTEN_ALL: Soften image using pixel interpolation */
else if(J && (J!=EFF_NEAREST))
{
CropImage(&TmpImg,OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);
switch(J)
{
case EFF_2XSAI: SoftenImage(&TmpImg,VideoImg,X,Y,W,H);break;
case EFF_EPX: SoftenEPX(&TmpImg,VideoImg,X,Y,W,H);break;
case EFF_EAGLE: SoftenEAGLE(&TmpImg,VideoImg,X,Y,W,H);break;
case EFF_SCALE2X: SoftenSCALE2X(&TmpImg,VideoImg,X,Y,W,H);break;
case EFF_NEAREST: ScaleImage(&TmpImg,VideoImg,X,Y,W,H);break;
case EFF_HQ4X:
default: SoftenImage(&TmpImg,VideoImg,X,Y,W,H);break;
}
}
/* EFF_SCALE: Scale image to the screen size */
else if(Effects&EFF_SCALE)
{
/* EFF_STRETCH: Stretch image to fill the whole screen */
if(Effects&EFF_STRETCH)
ScaleImage(OutImg,VideoImg,X,Y,W,H);
else
{
#if defined(ARM_CPU)
/* Scale image to fill the screen, using ARM assembler */
DW = ARMScaleImage(OutImg,VideoImg,X,Y,W,H,0);
/* Update destination image dimensions to optimized values */
DH = DW>>16;
DW&= 0xFFFF;
#else
/* Scale image to fill the screen, using C code */
CropImage(&TmpImg,OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);
ScaleImage(&TmpImg,VideoImg,X,Y,W,H);
#endif
}
}
/* DEFAULT: Not scaling, stretching, or softening image */
else
{
/* Center image at the screen */
IMGCopy(OutImg,(OutImg->W-W)>>1,(OutImg->H-H)>>1,VideoImg,X,Y,W,H,-1);
DW = W;
DH = H;
}
/* EFF_MASK_ALL: Apply color component masks */
switch(Effects&EFF_MASK_ALL)
{
case EFF_CMYMASK: CMYizeImage(OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);break;
case EFF_RGBMASK: RGBizeImage(OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);break;
case EFF_MONO: MonoImage(OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);break;
case EFF_GREEN: GreenImage(OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);break;
case EFF_AMBER: AmberImage(OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);break;
case EFF_SEPIA: SepiaImage(OutImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH);break;
}
/* EFF_RASTER_ALL: Apply "scanlines" effect */
if((J=Effects&EFF_RASTER_ALL))
{
/* Make sure width is a multiple of 8/16 pixels for optimization */
#if !defined(ARM_CPU)
Y = J==EFF_TVLINES? DW:(DW&~1);
#elif defined(BPP32) || defined(BPP24)
Y = DW&~7;
#else
Y = DW&~15;
#endif
switch(J)
{
case EFF_TVLINES: TelevizeImage(OutImg,(OutImg->W-Y)>>1,(OutImg->H-DH)>>1,Y,DH);break;
case EFF_LCDLINES: LcdizeImage(OutImg,(OutImg->W-Y)>>1,(OutImg->H-DH)>>1,Y,DH);break;
case EFF_RASTER: RasterizeImage(OutImg,(OutImg->W-Y)>>1,(OutImg->H-DH)>>1,Y,DH);break;
}
}
/* If drawing any touch input cues... */
if(Effects&(EFF_VKBD|EFF_PENCUES))
{
/* If no image supplied for the input cues... */
if(!CueImg)
{
/* In landscape mode, draw input cues on top of OutImg */
if(OutImg->H<=OutImg->W) CueImg=OutImg;
else
{
/* In portrait mode, draw input cues below OutImg */
CropImage(&TmpImg,OutImg,0,DH,OutImg->W,OutImg->H-DH);
CueImg = &TmpImg;
}
}
#if defined(ANDROID) || defined(MEEGO)
/* If cue image width changed... */
if(OldCueImgW!=CueImg->W)
{
/* Adjust virtual keyboard and cues size to fit screen */
if(CueImg->W>=1024) SetPenKeyboard(72,64,16);
else if(CueImg->W>=768) SetPenKeyboard(60,52,16);
else if(CueImg->W>=640) SetPenKeyboard(46,38,16);
else if(CueImg->W>=480) SetPenKeyboard(39,31,16);
else if(CueImg->W>=320) SetPenKeyboard(24,20,16);
else SetPenKeyboard(16,14,8);
/* New cue image width now in effect */
OldCueImgW = CueImg->W;
}
/* Draw virtual joystick */
if(Effects&EFF_PENCUES)
DrawFinJoystick(CueImg,(OutImg->W-DW)>>1,(OutImg->H-DH)>>1,DW,DH,CLR_CUES);
#else
/* Draw virtual joystick */
if(Effects&EFF_PENCUES) DrawPenCues(CueImg,Effects&EFF_DIALCUES,CLR_CUES);
#endif
/* Draw virtual keyboard */
if(Effects&EFF_VKBD) DrawKeyboard(CueImg,PenKey);
}
/* Show framerate if requested */
if((Effects&EFF_SHOWFPS)&&(FrameRate>0))
{
char S[8];
sprintf(S,"%dfps",FrameRate);
PrintXY2(OutImg,S,((OutImg->W-DW)>>1)+8,((OutImg->H-DH)>>1)+8,CLR_FPS);
}
/* Done with the screen */
return((DW>1)&&(DH>1)? ((DW&0xFFFF)|(DH<<16)):0);
}
#undef CLR_NORMALF
#undef CLR_NORMALB
#undef CLR_ACTIVEF
#undef CLR_ACTIVEB
#undef CLR_FPS
#undef CLR_CUES
#endif /* BPP32||BPP24||BPP16||BPP8 */
| 2.5 | 2 |
2024-11-18T23:20:01.041968+00:00 | 2021-09-10T10:57:48 | afee63ecf638231d918a108b35343ffa330e76a8 | {
"blob_id": "afee63ecf638231d918a108b35343ffa330e76a8",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-10T10:57:48",
"content_id": "73d397f8722fefedb1c11e0cd3d839352a35be9c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "62510fa67d0ca78082109a861b6948206252c885",
"extension": "h",
"filename": "audio_scene.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 406236565,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3365,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/hihope_neptune-oh_hid/00_src/v0.1/drivers/peripheral/audio/interfaces/include/audio_scene.h",
"provenance": "stackv2-0135.json.gz:53840",
"repo_name": "dawmlight/vendor_oh_fun",
"revision_date": "2021-09-10T10:57:48",
"revision_id": "bc9fb50920f06cd4c27399f60076f5793043c77d",
"snapshot_id": "a869e7efb761e54a62f509b25921e019e237219b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dawmlight/vendor_oh_fun/bc9fb50920f06cd4c27399f60076f5793043c77d/hihope_neptune-oh_hid/00_src/v0.1/drivers/peripheral/audio/interfaces/include/audio_scene.h",
"visit_date": "2023-08-05T09:25:33.485332"
} | stackv2 | /*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @addtogroup Audio
* @{
*
* @brief Defines audio-related APIs, including custom data types and functions for loading drivers,
* accessing a driver adapter, and rendering and capturing audios.
*
* @since 1.0
* @version 1.0
*/
/**
* @file audio_scene.h
*
* @brief Declares APIs for audio scenes.
*
* @since 1.0
* @version 1.0
*/
#ifndef AUDIO_SCENE_H
#define AUDIO_SCENE_H
#include "audio_types.h"
/**
* @brief Provides scene-related APIs for audio rendering or capturing, including functions to
* select an audio scene and check whether the configuration of an audio scene is supported.
*
* @since 1.0
* @version 1.0
*/
struct AudioScene {
/**
* @brief Checks whether the configuration of an audio scene is supported.
*
* @param handle Indicates the audio handle.
* @param scene Indicates the pointer to the descriptor of the audio scene.
* @param supported Indicates the pointer to the variable specifying whether the configuration is supported.
* Value <b>true</b> means that the configuration is supported, and <b>false</b> means the opposite.
* @return Returns <b>0</b> if the result is obtained; returns a negative value otherwise.
* @see SelectScene
*/
int32_t (*CheckSceneCapability)(AudioHandle handle, const struct AudioSceneDescriptor *scene, bool *supported);
/**
* @brief Selects an audio scene.
*
* <ul>
* <li>To select a specific audio scene, you need to specify both the application scenario and output device.
* For example, to select a scene using a smartphone speaker as the output device, set <b>scene</b> according
* to the scenarios where the speaker is used. For example:</li>
* <ul>
* <li>For media playback, set the value to <b>media_speaker</b>.</li>
* <li>For a voice call, set the value to <b>voice_speaker</b>.</li>
* </ul>
* <li>To select only the application scenario, such as media playback, movie, or gaming, you can set
* <b>scene</b> to <b>media</b>, <b>movie</b>, or <b>game</b>, respectively.</li>
* <li>To select only the output device, such as media receiver, speaker, or headset, you can set
* <b>scene</b> to <b>receiver</b>, <b>speaker</b>, or <b>headset</b>, respectively.</li>
* </ul>
* @param handle Indicates the audio handle.
* @param scene Indicates the pointer to the descriptor of the audio scene to select.
* @return Returns <b>0</b> if the scene is selected successfully; returns a negative value otherwise.
* @see CheckSceneCapability
*/
int32_t (*SelectScene)(AudioHandle handle, const struct AudioSceneDescriptor *scene);
};
#endif /* AUDIO_SCENE_H */
/** @} */
| 2.34375 | 2 |
2024-11-18T23:20:01.140923+00:00 | 2021-03-26T00:33:55 | 61362ca7e9ac25a5c01f2f0b0d33399d4154a33a | {
"blob_id": "61362ca7e9ac25a5c01f2f0b0d33399d4154a33a",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-26T00:33:55",
"content_id": "2ff8b8c6895c5d48eeffb4c656256ad50e452947",
"detected_licenses": [
"MIT"
],
"directory_id": "a61d4b53cbd331b4514bca7d657f93ee08205a44",
"extension": "h",
"filename": "timer.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 351615040,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 354,
"license": "MIT",
"license_type": "permissive",
"path": "/queueSimulation/timer.h",
"provenance": "stackv2-0135.json.gz:53970",
"repo_name": "Herikc2/QueueSimulation",
"revision_date": "2021-03-26T00:33:55",
"revision_id": "4a818d097b8542bbfcd020da847f50c23863e111",
"snapshot_id": "90ea5ab362d502d3af5fb8c3316d5dc04cf89a44",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Herikc2/QueueSimulation/4a818d097b8542bbfcd020da847f50c23863e111/queueSimulation/timer.h",
"visit_date": "2023-03-29T01:31:12.174674"
} | stackv2 | #pragma once
#include <time.h>
struct TIMER
{
long elapsed_time;
};
TIMER new_timer()
{
TIMER timer;
timer.elapsed_time = clock();
return timer;
}
bool to_continue(TIMER& timer, long time_condition)
{
if (clock() - timer.elapsed_time > time_condition) {
timer.elapsed_time = clock();
return true;
}
return false;
}
| 2.25 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.