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-18T19:02:34.730807+00:00
| 2021-10-10T13:42:10 |
bd955d17fd6d4c08fff5cf048eaa2ddc132ca0c5
|
{
"blob_id": "bd955d17fd6d4c08fff5cf048eaa2ddc132ca0c5",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-10T13:42:10",
"content_id": "9a9cbbd999fc2f8c3f00ad3acb72dc2e824f4ddb",
"detected_licenses": [
"MIT"
],
"directory_id": "fbb7db6fe0d3ceebc44a0684f7b829a9aba07db9",
"extension": "h",
"filename": "sig.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": 1841,
"license": "MIT",
"license_type": "permissive",
"path": "/include/ytdl/sig.h",
"provenance": "stackv2-0058.json.gz:154844",
"repo_name": "karlvoigt/libytdl",
"revision_date": "2021-10-10T13:42:10",
"revision_id": "a139623eeb97584b2f2d23b0b7023304db9173bb",
"snapshot_id": "ded7f6da2d5dfe8f932682f18cce367acc5bf99c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/karlvoigt/libytdl/a139623eeb97584b2f2d23b0b7023304db9173bb/include/ytdl/sig.h",
"visit_date": "2023-08-19T05:35:43.950236"
}
|
stackv2
|
#ifndef YTDL_SIG_H
#define YTDL_SIG_H
#include <inttypes.h>
#include <stdio.h>
#include <stddef.h>
#include <ytdl/quickjs.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum ytdl_sig_action_e {
YTDL_SIG_ACTION_SWAP = 1, // w
YTDL_SIG_ACTION_REVERSE, // r
YTDL_SIG_ACTION_SLICE, // s
YTDL_SIG_ACTION_SPLICE // p
} ytdl_sig_action_t;
#define YTDL_SIG_JS_FUNC \
"function y (z){" \
"const s=z.split('&');" \
"const i=s.findIndex(e=>e.startsWith('n='));" \
"const n=s[i].substr(2);" \
"s.splice(i,1,'n='+(%.*s)(n));" \
"return s.join('&');" \
"};y;"
#define YTDL_MAX_SIG 20
#define YTDL_SIG_ACTIONS \
ytdl_sig_action_t actions[YTDL_MAX_SIG]; \
int actions_arg[YTDL_MAX_SIG]; \
int actions_size;
typedef struct ytdl_sig_actions_head_s {
YTDL_SIG_ACTIONS
} ytdl_sig_actions_head_t;
typedef struct ytdl_sig_actions_s {
YTDL_SIG_ACTIONS
uint8_t *bytecode;
size_t bc_len;
JSRuntime *rt;
JSContext *ctx;
JSValue script;
JSValue func;
} ytdl_sig_actions_t;
int ytdl_sig_actions_init (ytdl_sig_actions_t *actions);
void ytdl_sig_actions_free (ytdl_sig_actions_t *actions);
int ytdl_sig_actions_save_file (ytdl_sig_actions_t *actions, FILE *fd);
int ytdl_sig_actions_load_file (ytdl_sig_actions_t *actions, FILE *fd);
/**
* Extracts the signature deciphering actions (steps) from the youtube player javascript.
*
* @param actions populated by the function
* @returns 0 on sucess and -1 for any error.
*/
int ytdl_sig_actions_extract (ytdl_sig_actions_t *actions,
uint8_t *buf, size_t buf_len);
#ifdef __cplusplus
}
#endif
#endif
| 2.015625 | 2 |
2024-11-18T19:02:35.150313+00:00
| 2023-08-11T20:49:35 |
f028f3f1982608bd661f957eeb73d0b318d63b3e
|
{
"blob_id": "f028f3f1982608bd661f957eeb73d0b318d63b3e",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-11T20:49:35",
"content_id": "8bceeaf7c706b356b550e14aae0981da82ef7f6f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d881849cd2df99efe9b01a1bda5cf0f2dada3835",
"extension": "h",
"filename": "statsd-client.h",
"fork_events_count": 0,
"gha_created_at": "2016-09-30T16:34:46",
"gha_event_created_at": "2023-05-09T20:12:08",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 69683549,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2241,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/binding/gridftp/src/statsd-client.h",
"provenance": "stackv2-0058.json.gz:154972",
"repo_name": "tacketar/lstore",
"revision_date": "2023-08-11T20:49:35",
"revision_id": "8ec83413ed502d862f0cdd43e345ce97593bd7f1",
"snapshot_id": "938e479a75e857b67e46aa3b562f0068f9dad0ce",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tacketar/lstore/8ec83413ed502d862f0cdd43e345ce97593bd7f1/binding/gridftp/src/statsd-client.h",
"visit_date": "2023-08-17T10:32:38.311394"
}
|
stackv2
|
#ifndef _H_STATSD_CLIENT
#define _H_STATSD_CLIENT
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
struct _statsd_link {
struct sockaddr_in server;
int sock;
char *ns;
};
typedef struct _statsd_link statsd_link;
// Global statsd socket
extern statsd_link * lfs_statsd_link;
#define STATSD_COUNT(name, count) if (lfs_statsd_link) { statsd_count(lfs_statsd_link, name, count, 1.0); globus_gfs_log_message(GLOBUS_GFS_LOG_INFO, "[lstore] statsd c:" name " %d\n", count); }
#define STATSD_TIMER_END(name, variable) time_t variable ## _end; if (lfs_statsd_link) { time(& variable ## _end); statsd_timing(lfs_statsd_link, name, (int) (difftime(variable ## _end, variable) * 1000.0)); globus_gfs_log_message(GLOBUS_GFS_LOG_INFO, "[lstore] statsd t:" name " %d\n", (int) (difftime(variable ## _end, variable) * 1000.0)); }
#define STATSD_TIMER_RESET(variable) variable = apr_time_now()
#define STATSD_TIMER_POST(name, variable) if (lfs_statsd_link) { statsd_timing(lfs_statsd_link, name, (int) apr_time_msec(apr_time_now()-variable)); globus_gfs_log_message(GLOBUS_GFS_LOG_INFO, "[lstore] statsd t:" name " %d\n",(int) apr_time_msec(apr_time_now()-variable) ); }
statsd_link *statsd_init(const char *host, int port);
statsd_link *statsd_init_with_namespace(const char *host, int port,
const char *ns);
void statsd_finalize(statsd_link *link);
/*
write the stat line to the provided buffer,
type can be "c", "g" or "ms"
lf - whether line feed needs to be added
*/
void statsd_prepare(statsd_link *link, char *stat, size_t value,
const char *type, float sample_rate, char *buf,
size_t buflen, int lf);
/* manually send a message, which might be composed of several lines. Must be
* null-terminated */
int statsd_send(statsd_link *link, const char *message);
int statsd_inc(statsd_link *link, char *stat, float sample_rate);
int statsd_dec(statsd_link *link, char *stat, float sample_rate);
int statsd_count(statsd_link *link, char *stat, size_t count,
float sample_rate);
int statsd_gauge(statsd_link *link, char *stat, size_t value);
int statsd_timing(statsd_link *link, char *stat, size_t ms);
#endif
| 2.140625 | 2 |
2024-11-18T19:02:36.317290+00:00
| 2019-11-26T01:57:16 |
1b64e186854498587c6a256459635899a64aa0a1
|
{
"blob_id": "1b64e186854498587c6a256459635899a64aa0a1",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-26T01:57:16",
"content_id": "9f6bd20967f676365652fcf30c4b9ddee43b79e5",
"detected_licenses": [
"MIT"
],
"directory_id": "98fb7e9a5f62e2a4621f3e30e474e4c6cd75ebe6",
"extension": "c",
"filename": "shm_writer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 202035515,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 411,
"license": "MIT",
"license_type": "permissive",
"path": "/xv6-public/ipc/shm_writer.c",
"provenance": "stackv2-0058.json.gz:155357",
"repo_name": "hecH98/OperativeSystems2019",
"revision_date": "2019-11-26T01:57:16",
"revision_id": "58013063505db025a980f279c4238240b0208bf3",
"snapshot_id": "d8a730122fbd62b6861d098833c5a9f336718344",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hecH98/OperativeSystems2019/58013063505db025a980f279c4238240b0208bf3/xv6-public/ipc/shm_writer.c",
"visit_date": "2020-07-03T20:08:56.555984"
}
|
stackv2
|
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <unistd.h>
int main(){
int key = 27; // numero usado para generar el id del bloque de memoria
int shmid = shmget(key, 11, IPC_CREAT);
char* word;
word = (char*)shmat(shmid, NULL, 0);
sprintf(word,"Hello world\n");
while(word[0] == 'H'){
sleep(1);
}
printf("Sali del ciclo: %s",word);
return 0;
}
| 2.609375 | 3 |
2024-11-18T19:02:36.461963+00:00
| 2021-10-19T23:31:30 |
f50777c72d870088355e1136dab465dd3409bb88
|
{
"blob_id": "f50777c72d870088355e1136dab465dd3409bb88",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-19T23:31:30",
"content_id": "40de9a69ba5b258c2bf85e1b3341aaa9d1b31d81",
"detected_licenses": [
"Unlicense"
],
"directory_id": "33c4279bb89776f4bd0836c0b40586c11f6ddf8c",
"extension": "c",
"filename": "functions.c",
"fork_events_count": 0,
"gha_created_at": "2019-06-11T21:47:25",
"gha_event_created_at": "2023-04-18T14:33:30",
"gha_language": "C",
"gha_license_id": "Unlicense",
"github_id": 191454942,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 272,
"license": "Unlicense",
"license_type": "permissive",
"path": "/code/c/secure_intro/functions.c",
"provenance": "stackv2-0058.json.gz:155485",
"repo_name": "AlexMapley/workstation",
"revision_date": "2021-10-19T23:31:30",
"revision_id": "d286fc969d540d9599dad487e6e6d9b3734ade0c",
"snapshot_id": "6f5c52a0dda3286770eb2c87dff784baa4b7ab44",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/AlexMapley/workstation/d286fc969d540d9599dad487e6e6d9b3734ade0c/code/c/secure_intro/functions.c",
"visit_date": "2021-10-29T04:02:09.261533"
}
|
stackv2
|
#include <stdio.h>
int add (int num1, int num2);
int main (void) {
int sum;
int num1 = 12;
int num2 = 30;
sum = add (num1,num2);
printf ("The foobar sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
int add (int num1, int num2) {
return num1 * num2;
}
| 3.234375 | 3 |
2024-11-18T19:02:36.888099+00:00
| 2013-04-17T18:42:40 |
dc070edbfb0f154a65fd6853631908c8d154e31c
|
{
"blob_id": "dc070edbfb0f154a65fd6853631908c8d154e31c",
"branch_name": "refs/heads/master",
"committer_date": "2013-04-17T18:42:40",
"content_id": "69286f3fe4035e089bc03d0c050043d1f895390f",
"detected_licenses": [
"MIT"
],
"directory_id": "bb108c3ea7d235e6fee0575181b5988e6b6a64ef",
"extension": "c",
"filename": "strnskil.c",
"fork_events_count": 8,
"gha_created_at": "2012-03-23T04:23:01",
"gha_event_created_at": "2013-04-17T18:42:41",
"gha_language": "C",
"gha_license_id": null,
"github_id": 3805274,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3772,
"license": "MIT",
"license_type": "permissive",
"path": "/mame/src/mame/video/strnskil.c",
"provenance": "stackv2-0058.json.gz:156001",
"repo_name": "clobber/MAME-OS-X",
"revision_date": "2013-04-17T18:42:40",
"revision_id": "ca11d0e946636bda042b6db55c82113e5722fc08",
"snapshot_id": "3c5e6058b2814754176f3c6dcf1b2963ca804fc3",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/clobber/MAME-OS-X/ca11d0e946636bda042b6db55c82113e5722fc08/mame/src/mame/video/strnskil.c",
"visit_date": "2021-01-20T05:31:15.086981"
}
|
stackv2
|
/******************************************************************************
Strength & Skill (c) 1984 Sun Electronics
Video hardware driver by Uki
19/Jun/2001 -
******************************************************************************/
#include "emu.h"
#include "includes/strnskil.h"
PALETTE_INIT( strnskil )
{
int i;
/* allocate the colortable */
machine.colortable = colortable_alloc(machine, 0x100);
/* create a lookup table for the palette */
for (i = 0; i < 0x100; i++)
{
int r = pal4bit(color_prom[i + 0x000]);
int g = pal4bit(color_prom[i + 0x100]);
int b = pal4bit(color_prom[i + 0x200]);
colortable_palette_set_color(machine.colortable, i, MAKE_RGB(r, g, b));
}
/* color_prom now points to the beginning of the lookup table */
color_prom += 0x300;
/* sprites lookup table */
for (i = 0; i < 0x400; i++)
{
UINT8 ctabentry = color_prom[i];
colortable_entry_set_value(machine.colortable, i, ctabentry);
}
}
WRITE8_HANDLER( strnskil_videoram_w )
{
strnskil_state *state = space->machine().driver_data<strnskil_state>();
UINT8 *videoram = state->m_videoram;
videoram[offset] = data;
tilemap_mark_tile_dirty(state->m_bg_tilemap, offset / 2);
}
WRITE8_HANDLER( strnskil_scrl_ctrl_w )
{
strnskil_state *state = space->machine().driver_data<strnskil_state>();
state->m_scrl_ctrl = data >> 5;
if (flip_screen_get(space->machine()) != (data & 0x08))
{
flip_screen_set(space->machine(), data & 0x08);
tilemap_mark_all_tiles_dirty_all(space->machine());
}
}
static TILE_GET_INFO( get_bg_tile_info )
{
strnskil_state *state = machine.driver_data<strnskil_state>();
UINT8 *videoram = state->m_videoram;
int attr = videoram[tile_index * 2];
int code = videoram[(tile_index * 2) + 1] + ((attr & 0x60) << 3);
int color = (attr & 0x1f) | ((attr & 0x80) >> 2);
SET_TILE_INFO(0, code, color, 0);
}
VIDEO_START( strnskil )
{
strnskil_state *state = machine.driver_data<strnskil_state>();
state->m_bg_tilemap = tilemap_create(machine, get_bg_tile_info, tilemap_scan_cols,
8, 8, 32, 32);
tilemap_set_scroll_rows(state->m_bg_tilemap, 32);
}
static void draw_sprites(running_machine &machine, bitmap_t *bitmap, const rectangle *cliprect)
{
strnskil_state *state = machine.driver_data<strnskil_state>();
UINT8 *spriteram = state->m_spriteram;
int offs;
for (offs = 0x60; offs < 0x100; offs += 4)
{
int code = spriteram[offs + 1];
int color = spriteram[offs + 2] & 0x3f;
int flipx = flip_screen_x_get(machine);
int flipy = flip_screen_y_get(machine);
int sx = spriteram[offs + 3];
int sy = spriteram[offs];
int px, py;
if (flip_screen_get(machine))
{
px = 240 - sx + 0; /* +2 or +0 ? */
py = sy;
}
else
{
px = sx - 2;
py = 240 - sy;
}
sx = sx & 0xff;
if (sx > 248)
sx = sx - 256;
drawgfx_transmask(bitmap, cliprect,
machine.gfx[1],
code, color,
flipx, flipy,
px, py,
colortable_get_transpen_mask(machine.colortable, machine.gfx[1], color, 0));
}
}
SCREEN_UPDATE( strnskil )
{
strnskil_state *state = screen->machine().driver_data<strnskil_state>();
int row;
const UINT8 *usr1 = screen->machine().region("user1")->base();
for (row = 0; row < 32; row++)
{
if (state->m_scrl_ctrl != 0x07)
{
switch (usr1[state->m_scrl_ctrl * 32 + row])
{
case 2:
tilemap_set_scrollx(state->m_bg_tilemap, row, -~state->m_xscroll[1]);
break;
case 4:
tilemap_set_scrollx(state->m_bg_tilemap, row, -~state->m_xscroll[0]);
break;
}
}
}
tilemap_draw(bitmap, cliprect, state->m_bg_tilemap, 0, 0);
draw_sprites(screen->machine(), bitmap, cliprect);
return 0;
}
| 2.25 | 2 |
2024-11-18T19:02:37.050931+00:00
| 2023-03-13T19:34:34 |
8943eee87efb27a09c49bd7289bf8f3487e73cdc
|
{
"blob_id": "8943eee87efb27a09c49bd7289bf8f3487e73cdc",
"branch_name": "refs/heads/v1.0.x",
"committer_date": "2023-03-13T19:34:34",
"content_id": "9e2b1fedf9d50a72f252f4b2366c360b05d2d53e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "1a5ee9578a794aea1ff6e731a9b25ca8cb92af09",
"extension": "h",
"filename": "led.h",
"fork_events_count": 6,
"gha_created_at": "2019-02-27T19:22:21",
"gha_event_created_at": "2023-08-25T21:39:54",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 172975569,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1051,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/sdk/app_cpu1/common/drv/led.h",
"provenance": "stackv2-0058.json.gz:156258",
"repo_name": "Severson-Group/AMDC-Firmware",
"revision_date": "2023-03-13T19:34:34",
"revision_id": "4dcb288f51b6879c003468ef5844b102ed3c6372",
"snapshot_id": "ae897a643d5a3d691a12f6cda71671fde254afa4",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/Severson-Group/AMDC-Firmware/4dcb288f51b6879c003468ef5844b102ed3c6372/sdk/app_cpu1/common/drv/led.h",
"visit_date": "2023-08-17T01:57:55.677000"
}
|
stackv2
|
#ifndef LED_H
#define LED_H
#include <stdint.h>
typedef struct led_color_t {
uint8_t r;
uint8_t g;
uint8_t b;
} led_color_t;
// clang-format off
static const led_color_t LED_COLOR_RED = { 020, 000, 000 };
static const led_color_t LED_COLOR_GREEN = { 000, 020, 000 };
static const led_color_t LED_COLOR_BLUE = { 000, 000, 020 };
static const led_color_t LED_COLOR_YELLOW = { 020, 020, 000 };
static const led_color_t LED_COLOR_CYAN = { 000, 020, 020 };
static const led_color_t LED_COLOR_MAGENTA = { 020, 000, 020 };
static const led_color_t LED_COLOR_WHITE = { 020, 020, 020 };
static const led_color_t LED_COLOR_BLACK = { 000, 000, 000 };
// clang-format on
typedef enum {
LED0 = 0,
LED1,
LED2,
LED3,
NUM_LEDS,
} led_t;
void led_init(void);
void led_set_color(led_t idx, led_color_t color);
void led_set_color_bytes(led_t idx, uint8_t r, uint8_t g, uint8_t b);
void led_set_raw(led_t idx, uint32_t color);
led_color_t led_get_color(led_t idx);
uint32_t led_get_raw(led_t idx);
#endif // LED_H
| 2.546875 | 3 |
2024-11-18T19:02:37.195942+00:00
| 2021-09-17T03:00:25 |
7228c2d65a10921e8d3e888f151efc855e4eec08
|
{
"blob_id": "7228c2d65a10921e8d3e888f151efc855e4eec08",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-17T03:00:25",
"content_id": "9745a9cda375657d95e6b7d4f2e45803c5bc1719",
"detected_licenses": [
"MIT"
],
"directory_id": "bcaf3ff659329d03f2298e01ad7f2656a6e3781e",
"extension": "c",
"filename": "06 - gaulesSM1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 407376248,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2289,
"license": "MIT",
"license_type": "permissive",
"path": "/APS06 - Gaules Dinner w Shared Memory/06 - gaulesSM1.c",
"provenance": "stackv2-0058.json.gz:156514",
"repo_name": "whoiswelliton/Operational_Systems",
"revision_date": "2021-09-17T03:00:25",
"revision_id": "8c37a173eb6cb265ffee7bed2ce82b497d62666e",
"snapshot_id": "0d1c240932ab52aef4880baad61f9ca8ffe407f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/whoiswelliton/Operational_Systems/8c37a173eb6cb265ffee7bed2ce82b497d62666e/APS06 - Gaules Dinner w Shared Memory/06 - gaulesSM1.c",
"visit_date": "2023-08-18T10:09:05.863089"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <time.h>
#include <math.h>
#define SIZE_GAU 8
#define SIZE_JVL 15
#define KEY 1234
typedef struct DINNER
{
int JAVA_COUNT;
sem_t table;
sem_t hungry;
}dinner;
dinner *ptr;
sem_t mutex;
void eatJAVALI(void *g)
{
printf(" - G[%c] is eating the lucky javali %d n very happy.\n",g,ptr->JAVA_COUNT+1);
}
void takeJavali(void *g)
{
sem_wait(&mutex);
if(ptr->JAVA_COUNT == 0)
{
printf(" - Gaules G[%c] get hungry first n wake up the cooker\n",g);
sem_post(&ptr->table);
sem_wait(&ptr->hungry);
}
ptr->JAVA_COUNT = ptr->JAVA_COUNT-1;
eatJAVALI(g);
sem_post(&mutex);
}
void *gaules(void *g)
{
while(1)
{
takeJavali(g);
sleep(1);
}
}
int main()
{
key_t key;
int i = 0;
int shmid;
char Name[8];
strcpy(Name, "Wel1iton");
pthread_t GAULES[SIZE_GAU];
//printf("1\n");
//generating a public key
key = ftok("/home/ecomp/a1543857/SO/Shared Memory/shrd.txt", KEY);
//printf("2\n");
//creating n saving shared memory
shmid = shmget(key, sizeof(struct dinner*), IPC_CREAT|0666);
if(shmid == -1)
{
perror("shmget");
exit(1);
}
//printf("3\n");
//attaching-connecting process with memory space
ptr = (struct dinner*) shmat(shmid, 0, 0);
if((int) ptr == -1)
{
perror("shmat");
exit(1);
}
ptr->JAVA_COUNT = SIZE_JVL;
sem_init(&mutex,0,1);
sem_init(&ptr->table,1,0);
sem_init(&ptr->hungry,1,1);
//printf("4\n");
pid_t pid;
if(pid = fork() < 0)
{
printf("Erro\n");
}
if(pid == 0)
{
execl("./c2",NULL);
}
printf("-----------------[Dinner is Served]--------------\n");
for(i = 0; i < SIZE_GAU; i++)
{
pthread_create(&GAULES[i], NULL, gaules, (void*) Name[i]);
printf(" + Gaules G[%c] is on the table.\n",Name[i]);
}
//printf("5\n");
sleep(6);
printf("-----------------[Dinner is Over]----------------\n");
sem_destroy(&mutex);
sem_destroy(&ptr->table);
sem_destroy(&ptr->hungry);
return 1;
}
| 2.953125 | 3 |
2024-11-18T19:02:37.480736+00:00
| 2016-08-28T00:11:45 |
322a9b42847d2ee9428c50e0b4084f15b7aa1e87
|
{
"blob_id": "322a9b42847d2ee9428c50e0b4084f15b7aa1e87",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-28T00:11:45",
"content_id": "e83a556355982e7f6f9414b428298cce11ea2503",
"detected_licenses": [
"MIT"
],
"directory_id": "ea71f6289415dfeb4b158a68a763515d0fb8f325",
"extension": "h",
"filename": "lineSeg.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 61383694,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4936,
"license": "MIT",
"license_type": "permissive",
"path": "/funkyForms/src/common/rayTrace/lineSeg.h",
"provenance": "stackv2-0058.json.gz:156770",
"repo_name": "ofZach/funkyForms",
"revision_date": "2016-08-28T00:11:45",
"revision_id": "3a5b231be5382c1376bffb6890951aada24aded4",
"snapshot_id": "dc043b9ad7a7cd46bb89887852f6ef192f9635a5",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/ofZach/funkyForms/3a5b231be5382c1376bffb6890951aada24aded4/funkyForms/src/common/rayTrace/lineSeg.h",
"visit_date": "2020-04-06T07:07:21.303408"
}
|
stackv2
|
#ifndef LINESEG
#define LINESEG
#include <cmath>
#include "Object.h"
#include "ofMain.h"
int get_line_intersection (float p0_x, float p0_y, float p1_x, float p1_y,
float p2_x, float p2_y, float p3_x, float p3_y, float * i_x, float * i_y)
{
float s1_x, s1_y, s2_x, s2_y;
s1_x = p1_x - p0_x; s1_y = p1_y - p0_y;
s2_x = p3_x - p2_x; s2_y = p3_y - p2_y;
float s, t;
s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
{
// Collision detected
//if (i_x != NULL)
*i_x = p0_x + (t * s1_x);
//if (i_y != NULL)
*i_y = p0_y + (t * s1_y);
return 1;
}
return 0; // No collision
}
inline ofPoint getNormalFacing ( ofPoint const incident, ofPoint const norma, ofPoint const normb){ // assume normalized....
float a = norma.dot(incident);
float b = normb.dot(incident);
if (a < b) return norma;
else return normb;
}
ofPoint getReflect( ofPoint const incident, ofPoint const norma, ofPoint const normb){ // assume normalized....
ofPoint normal = getNormalFacing(incident, norma, normb);
return incident - normal * 2.f * normal.dot(incident);
}
ofPoint getRefract( ofPoint const incident, ofPoint const norma, ofPoint const normb, float eta ){
ofPoint normal = getNormalFacing(incident, norma, normb);
ofPoint negInc = -incident;
float cosi = negInc.dot(normal);
float cost2 = 1.0f - eta * eta * (1.0f - cosi*cosi);
ofPoint t = eta*incident + ((eta*cosi - sqrt(fabs(cost2))) * normal);
t *= cost2 > 0 ? 1 : 0;
return t;
//
// ofPoint out;
// float N_dot_I = normal.dot(incident);
// float k = 1.f - eta * eta * (1.f - N_dot_I * N_dot_I);
// if (k < 0.f)
// out = ofPoint(0.f, 0.f, 0.f);
// else
// out = eta * incident - (eta * N_dot_I + sqrtf(k)) * normal;
//
// return out;
}
//! For the purposes of demonstrating the BVH, a simple sphere
struct lineSeg : public Object {
Vector3 center; // Center of the sphere
float r, r2; // Radius, Radius^2
ofPoint a, b;
ofPoint normA, normB;
ofPoint dirRay;
lineSeg(ofPoint _a, ofPoint _b){
//const Vector3& center, float radius)
// : center(a + b), r(radius), r2(radius*radius) {
a = _a;
b = _b;
ofPoint mid = (a + b)/2.0;
center = Vector3(mid.x, mid.y, mid.z);
r2 = (mid - a).length();
r2 = (mid - a).lengthSquared();
normA = (b-a).getNormalized().rotate(90, ofPoint(0,0,1));
normB = (b-a).getNormalized().rotate(-90, ofPoint(0,0,1));
}
bool getIntersection(const Ray& ray, IntersectionInfo* I) const {
ofPoint rayOrigin(ray.o.x, ray.o.y, ray.o.z);
ofPoint rayDir(ray.d.x, ray.d.y, ray.d.z);
ofPoint rayB = rayOrigin + rayDir * 2000;
ofPoint intersection;
// if (ofLineSegmentIntersection(rayOrigin, rayB, a, b, intersection)){
if (get_line_intersection(rayOrigin.x, rayOrigin.y,
rayB.x, rayB.y,
a.x, a.y,
b.x, b.y,
&intersection.x, &intersection.y)){
I->object = this;
I->t = (rayOrigin - intersection).length();
I->hit = Vector3(intersection.x, intersection.y, 0);
I->dir = rayDir;
//cout << "HIT !! "<< endl;
return true;
} else{
return false;
}
//Vector3 s = center - ray.o;
//float sd = s * ray.d;
//float ss = s * s;
// Compute discriminant
//float disc = sd*sd - ss + r2;
// Complex values: No intersection
//if( disc < 0.f ) return false;
// Assume we are not in a sphere... The first hit is the lesser valued
//I->object = this;
//I->t = sd - sqrt(disc);
return true;
}
Vector3 getNormal(const IntersectionInfo& I) const {
ofPoint pt = getReflect( I.dir, normA, normB);
return Vector3(pt.x, pt.y, 0);//normalize(I.hit - center);
}
Vector3 getNormal(const IntersectionInfo& I, float index) const {
ofPoint pt = getRefract( I.dir, normA, normB, index);
return Vector3(pt.x, pt.y, 0);//normalize(I.hit - center);
}
BBox getBBox() const {
float minX = min(a.x, b.x);
float minY = min(a.y, b.y);
float maxX = max(a.x, b.x);
float maxY = max(a.y, b.y);
return BBox(Vector3(minX, minY, -1), Vector3(maxX, maxY, 1));
}
Vector3 getCentroid() const {
return center;
}
};
#endif
| 2.46875 | 2 |
2024-11-18T19:02:37.590619+00:00
| 2019-03-04T11:51:52 |
cc3f1c73b95191773d4f949863283a67ad8c0587
|
{
"blob_id": "cc3f1c73b95191773d4f949863283a67ad8c0587",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-04T11:51:52",
"content_id": "568a22d924ed55b8ee23409e821ce5fac8a920a9",
"detected_licenses": [
"MIT"
],
"directory_id": "67d5c5b5a27fb4d75d12133f6773acb95781e1a2",
"extension": "c",
"filename": "client.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 130221122,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 372,
"license": "MIT",
"license_type": "permissive",
"path": "/snode/fnet/test/client.c",
"provenance": "stackv2-0058.json.gz:156898",
"repo_name": "tridcatov/shelled",
"revision_date": "2019-03-04T11:51:52",
"revision_id": "df0a5f06585c8752ba4ad41546478f4dd1e2f8eb",
"snapshot_id": "287936c0af19127dadb96e17543b607a1b58c56c",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/tridcatov/shelled/df0a5f06585c8752ba4ad41546478f4dd1e2f8eb/snode/fnet/test/client.c",
"visit_date": "2020-03-11T19:54:23.990599"
}
|
stackv2
|
#include <fnet/socket.h>
#include <stdio.h>
int main()
{
fnet_socket_init();
fnet_address_t addr;
fnet_str2addr("127.0.0.1:10500", &addr);
fnet_socket_t cli = fnet_socket_create(FNET_SOCK_DGRAM);
char buf[] = "ololo 12345";
fnet_socket_sendto(cli, buf, sizeof buf, &addr);
fnet_socket_close(cli);
fnet_socket_uninit();
return 0;
}
| 2.515625 | 3 |
2024-11-18T19:02:37.919932+00:00
| 2018-08-10T16:25:32 |
21915174384131b6d230528afe99a24a01f749df
|
{
"blob_id": "21915174384131b6d230528afe99a24a01f749df",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-10T16:25:32",
"content_id": "44410f5d5b32172d810da3618393ab74b2e4d556",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e4d950344c52d72a7cf9b9f200d174706cf2ed2b",
"extension": "c",
"filename": "button.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 144297551,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 960,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/02_Button/src/hw/core/button.c",
"provenance": "stackv2-0058.json.gz:157155",
"repo_name": "chcbaram/stm32f4_discovery",
"revision_date": "2018-08-10T16:25:32",
"revision_id": "ef9c103772f0a5410d454f15b91d50c4cddfa67e",
"snapshot_id": "f0feb96e9a930af1a1cc089a2eff13a2cd470a1a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/chcbaram/stm32f4_discovery/ef9c103772f0a5410d454f15b91d50c4cddfa67e/02_Button/src/hw/core/button.c",
"visit_date": "2020-03-25T23:53:22.304603"
}
|
stackv2
|
/*
* button.c
*
* Created on: 2018. 8. 9.
* Author: Baram
*/
#include "button.h"
#ifdef _USE_HW_BUTTON
typedef struct
{
GPIO_TypeDef *port;
uint32_t pin;
GPIO_PinState on_state;
GPIO_PinState off_state;
} button_tbl_t;
button_tbl_t button_tbl[BUTTON_MAX_CH] =
{
{GPIOA, GPIO_PIN_0, GPIO_PIN_SET, GPIO_PIN_RESET},
};
void buttonInit(void)
{
uint32_t i;
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
for (i=0; i<BUTTON_MAX_CH; i++)
{
GPIO_InitStruct.Pin = button_tbl[i].pin;
HAL_GPIO_Init(button_tbl[i].port, &GPIO_InitStruct);
}
}
bool buttonGetPressed(uint8_t ch)
{
if (ch >= BUTTON_MAX_CH)
{
return false;
}
if (HAL_GPIO_ReadPin(button_tbl[ch].port, button_tbl[ch].pin) == button_tbl[ch].on_state)
{
return true;
}
else
{
return false;
}
}
#endif
| 2.59375 | 3 |
2024-11-18T19:02:40.826804+00:00
| 2020-06-06T14:50:21 |
666e1d10e40cbb219ac39606cc78c04b63f41d45
|
{
"blob_id": "666e1d10e40cbb219ac39606cc78c04b63f41d45",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-06T14:50:21",
"content_id": "15d3f839f750b6216bea60d30f61e32cf609af2b",
"detected_licenses": [
"MIT"
],
"directory_id": "9e03db614541fc0cb7034002ab68d4d887be4618",
"extension": "h",
"filename": "Trie.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 174433522,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 249,
"license": "MIT",
"license_type": "permissive",
"path": "/Spelling Checker/Trie.h",
"provenance": "stackv2-0058.json.gz:158053",
"repo_name": "AbdallahHemdan/DidUMean",
"revision_date": "2020-06-06T14:50:21",
"revision_id": "39d1b835e6b95de73bdccf0a25295c0c382aa3da",
"snapshot_id": "d0caf64bca5dbca73ba92496ddfab521defba9e7",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/AbdallahHemdan/DidUMean/39d1b835e6b95de73bdccf0a25295c0c382aa3da/Spelling Checker/Trie.h",
"visit_date": "2021-07-16T14:56:05.332107"
}
|
stackv2
|
#pragma once
#define ll long long int
#define NoOfEdges 26
struct Trie
{
ll Words;
Trie* Edges[NoOfEdges];
Trie()
{
Words = 0;
for (int index = 0; index < NoOfEdges; index++)
{
Edges[index] = nullptr;
}
}
};
| 2 | 2 |
2024-11-18T19:02:40.910019+00:00
| 2022-03-31T16:27:18 |
ceae7d597c64992c2b0abd1540732ec7fb7bee80
|
{
"blob_id": "ceae7d597c64992c2b0abd1540732ec7fb7bee80",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-31T16:27:18",
"content_id": "028743fca5d479567ce2e0ef54d34cdfe3a893c9",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "61aae9d3dff63a1804b5960c1885054018d7e76c",
"extension": "c",
"filename": "ofmo-input.c",
"fork_events_count": 0,
"gha_created_at": "2022-03-28T15:17:59",
"gha_event_created_at": "2022-03-28T15:18:00",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 475059502,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 32844,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/common/ofmo-input.c",
"provenance": "stackv2-0058.json.gz:158181",
"repo_name": "JorgeG94/OpenFMO",
"revision_date": "2022-03-31T16:27:18",
"revision_id": "00b60867671978401958cfdd60168640af50f9f7",
"snapshot_id": "dd22f4ec41738fd0f40a36ff22ace99e031e70cf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JorgeG94/OpenFMO/00b60867671978401958cfdd60168640af50f9f7/common/ofmo-input.c",
"visit_date": "2022-05-20T01:04:05.737990"
}
|
stackv2
|
/**
* @file ofmo-input.c
* 入力データを読み込むための関数群を定義したファイル。
*
* OpenFMOでは、GAMESSの入力形式に近い入力データを読み込む。
* このファイルに記述された関数群は、各セクションの入力を担当する
* 関数である。
*
* */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <math.h>
#include "ofmo-def.h"
#include "ofmo-string.h"
#include "ofmo-data.h"
static char **local;
static char **elems;
static char line[MAXSTRLEN];
static int NATOM = 0;
static int NFRAG = 1;
/* ------------------------------------------------------
* $CONTRL部分の読み込み
* 以下の変数を読み込む
*
* maxit = SCFの最大繰り返し回数
* nprint = 出力レベル
* itol = primitiveのカットオフファクタ
* icut = 2電子積分のカットオフファクタ
* ------------------------------------------------------- */
static int input_contrl( FILE *fp, char **token, const int ntok ) {
//int maxit=30, nprint=0, itol=20, icut=15;
int maxit=30, nprint=0, itol=20, icut=12;
// local variables
int i, nline = 0, n, ne, errpos = -1, flag_end = false;
if ( fp == NULL ) {
ofmo_data_put_vals("maxscf nprint itol icut",
maxit, nprint, itol, icut );
return 0;
}
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$contrl" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
ne = ofmo_split( local[i], "=", elems, MAXTOKEN, MAXSTRLEN );
if ( ne<2 ) {
errpos = i;
break;
}
if ( strcmp( elems[0], "maxit" ) == 0 )
maxit = atoi( elems[1] );
else if ( strcmp( elems[0], "nprint" ) == 0 )
nprint = atoi( elems[1] );
else if ( strcmp( elems[0], "itol" ) == 0 )
itol = atoi( elems[1] );
else if ( strcmp( elems[0], "icut" ) == 0 )
icut = atoi( elems[1] );
}
if ( errpos >= 0 ) {
dbg("line=%d, elem=%d : ERROR\n", nline, ++i );
break;
}
if ( flag_end ) break;
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("maxscf nprint itol icut",
maxit, nprint, itol, icut );
return 0;
}
/* ------------------------------------------------------
* $SYSTEM部分の読み込み
* 2011/03/02時点では、何もしない($endまで流して読み込むだけ)
* ------------------------------------------------------- */
static int input_system( FILE *fp, char **token, const int ntok ) {
int i, nline = 0, n, errpos = -1, flag_end = false;
if ( fp == NULL ) return 0;
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$system" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
}
if ( flag_end ) break;
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
// 次の行を読み込む
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
return 0;
}
/* --------------------------------------------------------
* $BASIS部分の読み込み
* 以下の変数の値を読み込む
* ngauss = (int)
* diffsp = 重原子に対してSP型のdiffuse関数を加える(1)か否(0)か
* diffs = 水素原子に対してS型のdiffuse関数を加える(1)か否(0)か
* gbasis = 関数のタイプ(STO, N21, N31, N311など)
* ndfunc = 重原子に対するd型分極関数の個数
* nffunc = 重原子に対するf型分極関数の個数
* npfunc = 水素原子に対するp型分極関数の個数
* -------------------------------------------------------- */
static int input_basis( FILE *fp, char **token, const int ntok ) {
int ngauss=3, diffsp=false, diffs=false, npfunc=0, ndfunc=0, nffunc=0;
char *gbasis;
// local variables
int i, nline = 0, n, ne, errpos = -1, flag_end = false;
gbasis = (char*)malloc( sizeof(char) * MAXSTRLEN );
gbasis[0] = '\0';
if ( fp == NULL ) {
ofmo_data_put_vals(
"ngauss diffsp diffs ndfunc nffunc npfunc gbasis",
ngauss, diffsp, diffs, ndfunc, nffunc, npfunc, gbasis );
return 0;
}
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$basis" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
ne = ofmo_split( local[i], "=", elems, MAXTOKEN, MAXSTRLEN );
if ( ne<2 ) {
errpos = i;
break;
}
if ( strcmp( elems[0], "ngauss" ) == 0 )
ngauss = atoi( elems[1] );
else if ( strcmp( elems[0], "diffsp" ) == 0 )
diffsp = (strcmp(elems[1], ".f.") == 0 ? false : true );
else if ( strcmp( elems[0], "diffs" ) == 0 )
diffs = (strcmp(elems[1], ".f.") == 0 ? false : true );
else if ( strcmp( elems[0], "gbasis" ) == 0 )
strcpy( gbasis, elems[1] );
else if ( strcmp( elems[0], "ndfunc" ) == 0 )
ndfunc = atoi( elems[1] );
else if ( strcmp( elems[0], "nffunc" ) == 0 )
nffunc = atoi( elems[1] );
else if ( strcmp( elems[0], "npfunc" ) == 0 )
npfunc = atoi( elems[1] );
}
if ( errpos >= 0 ) {
dbg("line=%d, elem=%d : ERROR\n", nline, ++i );
break;
}
if ( flag_end ) break;
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("ngauss diffsp diffs ndfunc nffunc npfunc gbasis",
ngauss, diffsp, diffs, ndfunc, nffunc, npfunc, gbasis );
return 0;
}
static int input_intgrl( FILE *fp, char **token, const int ntok ) {
//long nintmx=15000, nintic=512*1024*1024;
long nintmx=15000, nintic=512;
// local variables
int i, nline = 0, n, ne, errpos = -1, flag_end = false;
if ( fp == NULL ) {
ofmo_data_put_vals("nintmx nintic", nintmx, nintic );
return 0;
}
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$intgrl" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
ne = ofmo_split( local[i], "=", elems, MAXTOKEN, MAXSTRLEN );
if ( ne<2 ) {
errpos = i;
break;
}
if ( strcmp( elems[0], "nintmx" ) == 0 )
nintmx = atol( elems[1] );
else if ( strcmp( elems[0], "nintic" ) == 0 )
nintic = atol( elems[1] );
}
if ( errpos >= 0 ) {
dbg("line=%d, elem=%d : ERROR\n", nline, ++i );
break;
}
if ( flag_end ) break;
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("nintmx nintic", nintmx, nintic );
return 0;
}
static int input_gddi( FILE *fp, char **token, const int ntok ) {
#ifdef USE_FALANX
int ngroup=1, niogroup=2, nioprocs=1, master=0, iopos=-1;
#else
int ngroup=1, niogroup=1, nioprocs=1, master=0, iopos=-1;
#endif
// local variables
int i, nline = 0, n, ne, errpos = -1, flag_end = false;
if ( fp == NULL ) {
ofmo_data_put_vals("ngroup niogroup nioprocs master iopos",
ngroup, niogroup, nioprocs, master, iopos );
return 0;
}
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$gddi" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
if ( strncmp( local[i], "ngroup", 6) == 0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne<2 ) {
errpos = i;
break;
}
ngroup = atoi( elems[1] );
if ( ngroup < 1 ) ngroup = 1;
} else if ( strncmp( local[i], "niogroup", 8) == 0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne<2 ) {
errpos = i;
break;
}
niogroup = atoi( elems[1] );
if ( niogroup < 1 ) niogroup = 1;
} else if ( strncmp( local[i], "nioprocs", 8) == 0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne<2 ) {
errpos = i;
break;
}
nioprocs = atoi( elems[1] );
if ( nioprocs < 1 ) nioprocs = 1;
} else if ( strncmp( local[i], "master", 6) == 0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne<2 ) {
errpos = i;
break;
}
master = atoi( elems[1] );
if ( master < 0 ) master = 0;
} else if ( strncmp( local[i], "iopos", 5) == 0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne<2 ) {
errpos = i;
break;
}
iopos = atoi( elems[1] );
}
}
if ( errpos >= 0 ) {
dbg("line=%d, elem=%d : ERROR\n", nline, ++i );
break;
}
if ( flag_end ) break;
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("ngroup niogroup nioprocs master iopos",
ngroup, niogroup, nioprocs, master, iopos );
return 0;
}
static int input_scf( FILE *fp, char **token, const int ntok ) {
int diis=true, npunch=0, conv=7;
// local variables
int i, nline = 0, n, ne, errpos = -1, flag_end = false;
if ( fp == NULL ) {
ofmo_data_put_vals("diis npunch scfconv", diis, npunch, conv );
return 0;
}
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$scf" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
ne = ofmo_split( local[i], "=", elems, MAXTOKEN, MAXSTRLEN );
if ( ne<2 ) {
errpos = i;
break;
}
if ( strcmp( elems[0], "diis" ) == 0 )
diis = ( strcmp(elems[1], ".f.")==0 ? false : true );
else if ( strcmp( elems[0], "npunch" ) == 0 )
npunch = atoi( elems[1] );
else if ( strcmp( elems[0], "conv") == 0 ) {
//conv = atoi( elems[1] );
//if ( conv < 1 ) conv = 5;
char *endptr=NULL;
double convd;
convd = strtod( elems[1], &endptr );
if (convd <=0 ) {
dbg("CONV in $SCF must be a positive value.\n");
break;
} else if ( convd < 1 ) conv = -log10(convd);
else conv = convd;
}
}
if ( errpos >= 0 ) {
dbg("line=%d, elem=%d : ERROR\n", nline, ++i );
break;
}
if ( flag_end ) break;
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("diis npunch scfconv", diis, npunch, conv );
return 0;
}
/* ------------------------------------------------------
* $FMOPRP部分の読み込み
* 2012/01/04時点では、SCCCONVとMAXSCCを読み込む
* ------------------------------------------------------- */
static int input_fmoprp( FILE *fp, char **token, const int ntok ) {
int i, nline = 0, n, ne, errpos = -1, flag_end = false;
int maxscc=30, sccconv=7;
if ( fp == NULL ) {
ofmo_data_put_vals("sccconv maxscc", sccconv, maxscc );
return 0;
}
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$fmoprp" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
ne = ofmo_split( local[i], "=", elems, MAXTOKEN, MAXSTRLEN );
#if 0
if ( ne<2 ) {
errpos = i;
break;
}
#endif
if ( strcmp( elems[0], "maxit" ) == 0 ) {
maxscc = atoi( elems[1] );
if ( maxscc < 1 ) maxscc = 30;
} else if ( strcmp( elems[0], "conv" ) == 0 ) {
//sccconv = atoi( elems[1] );
//if ( sccconv < 1 ) sccconv = 5;
char *endptr=NULL;
double sccconvd;
sccconvd = strtod( elems[1], &endptr );
if (sccconvd <=0 ) {
dbg("CONV in $FMOPROP must be a positive value.\n");
break;
} else if ( sccconvd < 1 ) sccconv = -log10(sccconvd);
else sccconv = sccconvd;
}
}
if ( errpos >= 0 ) {
dbg("line=%d, elem=%d : ERROR\n", nline, ++i );
break;
}
if ( flag_end ) break;
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
ofmo_data_put_vals("sccconv maxscc", sccconv, maxscc );
if ( !flag_end ) exit(1);
if ( !flag_end ) return -1;
return 0;
}
/*
原子座標の入力
(絶対に呼ばれる必要がある)
*/
static int input_fmoxyz( FILE *fp, char **token, const int ntok ) {
double *atom_x, *atom_y, *atom_z;
int *atomic_number;
// local variables
int nline = 0, n, flag_end = false;
int nat = 0, pos=-1;
// memory allocation
if ( NATOM < 1 ) {
dbg("# of atom hasn\'t be read, yet\n");
return -1;
}
atom_x = (double*)malloc( sizeof(double) * NATOM );
atom_y = (double*)malloc( sizeof(double) * NATOM );
atom_z = (double*)malloc( sizeof(double) * NATOM );
atomic_number = (int*)malloc( sizeof(int) * NATOM );
/*if ( atom_x == NULL || atom_y == NULL ||
atom_z == NULL || atomic_number == NULL ) {
//errpos = 101;
}*/
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while (1) {
nline++;
if ( strcmp( local[0], "$fmoxyz" ) == 0 ) {
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN,
line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
continue;
}
if ( strcmp( local[0], "$end" ) == 0 ) {
flag_end = true;
break;
}
if ( n < 5 ) { // 要素が足りないとき
dbg("Illegal number of elements (line=%d)\n", nline );
break;
}
if ( nat == 0 ) {
if ( isalpha(local[0][0]) ) pos = 0;
else if ( isalpha(local[1][0]) ) pos = 1;
}
// 読み込み
//atomic_number[nat] = atoi( local[1] );
atomic_number[nat] = AtomicNumber( local[pos] );
atom_x[nat] = atof( local[2] );
atom_y[nat] = atof( local[3] );
atom_z[nat] = atof( local[4] );
nat++;
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
if ( nat != NATOM ) {
dbg("Inconsisten between nat(%d) vs NATOM(%d)\n", nat, NATOM );
return -1;
}
/* change unit of length */
double rb;
rb = 1.e0 / BOHR_RADIUS;
for ( int iat=0; iat<nat; iat++ ) {
atom_x[iat] *= rb;
atom_y[iat] *= rb;
atom_z[iat] *= rb;
}
ofmo_data_put_vals("natom atn atx aty atz",
nat, atomic_number, atom_x, atom_y, atom_z );
return 0;
}
/* 各モノマーの電荷を入力する
(必ず呼ばれる必要がある)
*/
static int input_fmo_icharg( FILE *fp, char **token, const int ntok ) {
int *icharg;
int flag = false; // icharg=true 読み込み中, =false 読み込んでない
int valid = false; // ichargの行に、要素があるか?
// local variables
int i, nline = 0, n, nr, ne, errpos = -1, flag_end = false;
if ( NFRAG < 1 ) {
dbg("# of fragment hasn\'t be read, yet\n");
return -1;
}
icharg = (int*)malloc( sizeof(int) * NFRAG );
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
if ( flag == false ) {
for ( i=0; i<n; i++ ) {
if (strncmp( local[i], "icharg", 6) == 0 ) {// 発見!
strcpy( line, local[i] );// この行の残りをコピー
for ( int j=i+1; j<n; j++ ) strcat( line, local[j] );
ofmo_delete_all_space( line );
ne=ofmo_split(line, "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne > 1 ) { // '='以降をコピー
strcpy( line, elems[1] );
valid = true;
}
nr = 0;
flag = true;
break;
}
}
} else {
//ne = ofmo_split( line, ",", elems, MAXTOKEN, MAXSTRLEN );
ofmo_replace_char( line, ',', ' ' );
ofmo_delete_prepost_space( line );
ne = ofmo_split( line, " ", elems, MAXTOKEN, MAXSTRLEN );
for ( i=0; i<ne; i++ ) icharg[nr++] = atoi( elems[i] );
if ( nr == NFRAG ) flag_end = true;
}
if ( flag_end ) break;
// (最初の行以外で)次の行を読み込む
if ( valid == false ) {
if ( fgets( line, MAXSTRLEN, fp ) == NULL ) {
dbg("Unexpected EOF\n");
break;
}
ofmo_tolower( line );
ofmo_delete_all_space( line );
}
valid = false;
}
if ( !flag_end ) {
dbg(" %d elements has been read, but not reach nfrag(%d)\n",
nr, NFRAG );
return -1;
}
ofmo_data_put_vals("icharg", icharg );
return 0;
}
/* 各原子がどのモノマーに含まれているか?のデータを入力する
(必ず呼ばれる必要がある)
*/
static int input_fmo_indat( FILE *fp, char **token, const int ntok ) {
int *atom2frg;
int flag = false; // indat=true 読み込み中, =false 読み込んでない
int valid = false; // indatの行に、要素があるか?
// local variables
int i, nline = 0, n, nr, ne, errpos = -1, flag_end = false;
int mode = -1; /* 0 = 通常、1 = 短縮形 */
int nf, is, prev;
if ( NATOM < 1 ) {
dbg("# of atom hasn\'t be read, yet\n");
return -1;
}
atom2frg = (int*)malloc( sizeof(int) * NATOM );
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
if ( flag == false ) {
for ( i=0; i<n; i++ ) {
if (strncmp( local[i], "indat", 5) == 0 ) {// 発見!
strcpy( line, local[i] );// この行の残りをコピー
for ( int j=i+1; j<n; j++ ) strcat( line, local[j] );
//ofmo_delete_all_space( line );
ne=ofmo_split( line, "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne > 1 ) { // '='以降をコピー
strcpy( line, elems[1] );
valid = true;
}
nr = 0;
flag = true;
break;
}
}
} else {
int k, tmp;
//ne = ofmo_split( line, ",", elems, MAXTOKEN, MAXSTRLEN );
ofmo_replace_char( line, ',', ' ' );
ofmo_delete_multiple_space( line );
ofmo_delete_prepost_space( line );
ne = ofmo_split( line, " ", elems, MAXTOKEN, MAXSTRLEN );
is = 0;
if ( mode == -1 ) {
mode = ( line[0] == '0' ? 1 : 0 );
if ( mode == 1 ) {
nf = 0;
prev = 0;
is = 1;
} else is = 0;
}
if ( mode == 0 ) {
for ( i=is; i<ne; i++ ) atom2frg[nr++] = atoi(elems[i])-1;
} else if ( mode == 1 ) {
for ( i=is; i<ne; i++ ) {
tmp = atoi( elems[i] );
//printf("elems[%d]=%s\n", i, elems[i] );
//fflush(stdout);
if ( tmp > 0 ) {
if ( prev > 0 ) { // ++ = 前の要素を追加
// debug
/*printf("prev=%d, tmp=%d\n", prev, tmp );
fflush(stdout);*/
atom2frg[prev-1] = nf;
nr++;
}
} else if ( tmp < 0 ) {
if ( prev > 0 ) { // -+ = まとめて追加
for ( k=prev; k<=(-tmp); k++ ) {
atom2frg[k-1] = nf;
nr++;
}
} else { // 0-, -- = エラー
errpos = i;
break;
}
} else { // 今回が0
if ( prev == 0 ) { // 00 = エラー
errpos = i;
break;
}
if ( prev > 0 ) { // +0
atom2frg[prev-1] = nf;
nr++;
}
nf++;
}
prev = tmp;
} // for ( i=is )
} // if ( mode == )
if ( nr == NATOM ) flag_end = true;
}
if ( flag_end ) break;
// (最初の行以外で)次の行を読み込む
if ( valid == false ) {
if ( fgets( line, MAXSTRLEN, fp ) == NULL ) {
dbg("Unexpected EOF\n");
break;
}
ofmo_tolower( line );
//ofmo_delete_all_space( line );
}
valid = false;
}
if ( !flag_end ) {
dbg(" %d elements has been read, but not reach nfrag(%d)\n",
nr, NATOM );
return -1;
}
ofmo_data_put_vals("at2frg", atom2frg );
return 0;
}
/* ----------------------------------------------------
* FMO関連の入力(必ず呼ばれる必要がある)
* 以下の変数を読む
* nfrag = フラグメント数
* nbody = N-body (2011/0721現在は、呼んでいない)
* icharg[] = 各フラグメントの電荷
* indat[] = 各原子が属するフラグメントの番号
* ---------------------------------------------------- */
static int input_fmo( FILE *fp, char **token, const int ntok ) {
int nfrag=1, nbody=2;
double lptc=2.e0, laop=1.e0, ldim=2.e0;
int flag = false; /* nfragを呼んだ=true, 読んでいない =false */
// local variables
long pos;
int i, nline = 0, n, ne, errpos = -1, flag_end = false;
int flag_ichrg = false, flag_indat = false;
pos = ftell( fp );
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while ( errpos < 0 && !flag_end ) {
nline++;
errpos = -1;
for ( i=0; i<n; i++ ) {
if ( strcmp( local[i], "$fmo" ) == 0 ) continue;
if ( strcmp( local[i], "$end" ) == 0 ) { // 終了
flag_end = true;
break;
}
if ( strncmp( local[i], "nfrag", 5)==0 && flag == false ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne < 2 ) {
errpos = i;
break;
}
NFRAG = nfrag = atoi( elems[1] );
flag = true;
fseek( fp, pos, SEEK_SET );
} else if ( strncmp( local[i], "respap", 6)==0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne < 2 ) {
errpos = i;
break;
}
laop = atof( elems[1] );
if ( laop < 0.e0 ) laop = 1.e0;
} else if ( strncmp( local[i], "resppc", 6)==0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne < 2 ) {
errpos = i;
break;
}
lptc = atof( elems[1] );
if ( lptc < 0.e0 ) lptc = 2.e0;
} else if ( strncmp( local[i], "resdim", 6)==0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne < 2 ) {
errpos = i;
break;
}
ldim = atof( elems[1] );
if ( ldim < 0.e0 ) ldim = 2.e0;
} else if ( strncmp( local[i], "nbody", 5)==0 ) {
ne=ofmo_split(local[i], "=", elems, MAXTOKEN, MAXSTRLEN);
if ( ne < 2 ) {
errpos = i;
break;
}
nbody = atoi( elems[1] );
if ( nbody < 0 ) nbody = 2;
} else if ( strncmp( local[i], "icharg", 6)==0 ) {
if ( flag == true && flag_ichrg == false ) {
input_fmo_icharg( fp, local, n );
flag_ichrg = true;
}
} else if ( strncmp( local[i], "indat", 5)==0 ) {
if ( flag == true && flag_indat == false ) {
input_fmo_indat( fp, local, n );
flag_indat = true;
}
}
}
if ( flag_end == true ) break;
if ( errpos >= 0 ) dbg("line=%d, elem=%d : ERROR\n", nline, ++i );
// 次の行を読み込む
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("nfrag nbody lptc laop ldim",
nfrag, nbody, lptc, laop, ldim );
return 0;
}
/*
* LMO関連のパラメタを読み取る(必ず呼ばれる必要がある)
* 以下の制限がある
* 1. 1種類のLMOパラメタしか読まない
* 2. 各行の2番目のパラメタは無視する
* */
static int input_fmolmo( FILE *fp, char **token, const int ntok ) {
int nlmo=0, nfunc=0, *lea = NULL;
double *clmo = NULL;
// local variables
int i, n, flag_end = false, reading, iao=-1;
int lmo = -1;
char *bs_name;
int nbs=0;
bs_name = (char*)malloc( sizeof(char) * MAXSTRLEN );
bs_name[0] = '\0';
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while (1) {
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
if ( strcmp( local[0], "$end" ) == 0 ) {
if ( iao != nfunc ) {
dbg("error: Illegal number of AO(%d)\n", iao );
}
flag_end = true;
break;
}
if (nbs>0) continue;
/*
if ( strcmp( local[0], "$fmolmo") == 0 ||
strcmp( local[0], "$fmohyb" ) == 0 ) {
} else if ( strcmp( local[0], "$end" ) == 0 ) {
if ( iao != nfunc ) {
dbg("error: Illegal number of AO(%d)\n", iao );
}
flag_end = true;
break;
} else if ( n == 3 ) {
*/
if ( n == 3 ) {
strcpy( bs_name, local[0] );
ofmo_toupper( bs_name );
nfunc = atoi( local[1] );
nlmo = atoi( local[2] );
clmo = (double*)malloc( sizeof(double)*nfunc*nlmo );
lea = (int*)malloc( sizeof(int)*nlmo );
lmo = -1;
reading=false;
} else {
if ( reading == false ) {
if ( n > 5 ) {// first line of each LMO
iao=0;
lmo++;
reading = true;
lea[lmo] = atoi( local[0] );
for ( i=2; i<n; i++, iao++ )
clmo[lmo*nfunc+iao] = atof( local[i] );
if ( iao == nfunc ) reading = false;
}
} else {
for ( i=0; i<n; i++, iao++ )
clmo[lmo*nfunc+iao] = atof( local[i] );
if ( iao == nfunc ) reading = false;
}
if ( lmo == nlmo-1 && reading == false ) nbs++;
}
/*
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
*/
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("nlmo nfunc clmo ban lmobs",
nlmo, nfunc, clmo, lea, bs_name );
return 0;
}
/* 結合原子の情報を入力する(必ず呼ばれる必要がある)
*/
static int input_fmobnd( FILE *fp, char **token, const int ntok ) {
int nbond=0, *welec=NULL, *woelec=NULL;
// local variables
int n, flag_end = false, ibond=-1;
int counted_nbond = false;
long pos=0;
ofmo_strcpy_2d( token, local, ntok, MAXSTRLEN );
n = ntok;
while (1) {
if ( strcmp(local[0], "$fmobnd") == 0 ) {
ibond = 0;
pos = ftell( fp );
} else if ( strcmp( local[0], "$end" ) == 0 ) {
if ( counted_nbond == false ) {
counted_nbond = true;
nbond = ibond;
welec = (int*)malloc( sizeof(int) * nbond );
woelec = (int*)malloc( sizeof(int) * nbond );
ibond = 0;
fseek( fp, pos, SEEK_SET );
} else {
flag_end = true;
break;
}
} else if ( counted_nbond ) {
woelec[ibond] = (-atoi( local[0])) - 1 ;/* 0-offset */
welec[ibond] = atoi( local[1] ) - 1 ;/* 0-offset */
ibond++;
} else ibond++;
n=ofmo_read_line(fp, MAXSTRLEN, MAXTOKEN, MAXSTRLEN, line, local);
if ( n < 0 ) {
dbg("Unexpected EOF\n");
break;
}
}
if ( !flag_end ) return -1;
ofmo_data_put_vals("nbond welec woelec", nbond, welec, woelec );
return 0;
}
/* ------------------------------------------------------
* $DATA部分の読み込み
* 2011/03/02時点では、何もしない($endまで流して読み込むだけ)
* ------------------------------------------------------- */
static int input_data( FILE *fp, char **token, const int ntok ) {
int i, nline = 0, n, flag_end = false;
char **now;
if ( fp == NULL ) return 0;
while (1) {
if ( nline == 0 ) {
now = token;
n = ntok;
nline++;
} else {
if ( fgets( line, MAXSTRLEN, fp ) == NULL ) {
dbg("Unexpected EOF\n");
return -1;
}
nline++;
ofmo_delete_prepost_space( line );
n = ofmo_split( line, " \t\n\r", local, MAXTOKEN, MAXSTRLEN );
if ( n<1 ) continue;
now = local;
}
for ( i=0; i<n; i++ ) {
if ( strcasecmp( now[i], "$data" ) == 0 ) continue;
if ( strcasecmp( now[i], "$end" ) == 0 ) {
flag_end = true;
break;
}
}
if ( flag_end ) break;
}
if ( !flag_end ) return -1;
return 0;
}
static int input_nat( FILE* fp ) {
int is_reading_nat = false, nat = 0;
// $fmoxyzのサーチ
while ( fgets( line, MAXSTRLEN, fp ) != NULL ) {
ofmo_delete_prepost_space( line );
if ( strncasecmp( line, "$fmoxyz", 7 ) == 0 ) {
is_reading_nat = true;
} else if ( is_reading_nat == true ) {
if ( strncasecmp( line, "$end", 4 ) == 0 ) {
return nat;
} else nat++;
}
}
return nat;
}
/** GAMESS形式の入力データを読み込む関数
*
* 各セクションのデータを読み込む関数を駆動している
*
* @param[in] fp 入力ファイルのファイル記述子
*
* @note この関数が呼ばれた時点で、入力ファイルが開かれている
* 必要がある
*
* @ingroup ofmo-input
* */
int ofmo_read_gamess_input( const char *filename ) {
int ntok, i, ierr=0, nat;
char **token;
int ctrl, sys, basis, intgrl, gddi, scf, fmo, fmoprp, fmoxyz;
int fmolmo, fmobnd, data;
FILE *fp;
if ( (fp=fopen( filename, "r")) == NULL ) {
dbg("Failure in opening file (%s)\n", filename );
return -1;
}
token = ofmo_alloc_char_2d( MAXTOKEN, MAXSTRLEN );
local = ofmo_alloc_char_2d( MAXTOKEN, MAXSTRLEN );
elems = ofmo_alloc_char_2d( MAXTOKEN, MAXSTRLEN );
if ( token == NULL || local == NULL || elems == NULL ) {
dbg("Failure in allocation temporary space\n");
return -1;
}
if ( (nat=input_nat( fp )) < 1 ) {
dbg("Illegal number of atom (%d)\n", nat );
return -1;
}
NATOM = nat;
rewind( fp );
ctrl = sys = basis = intgrl = gddi = scf = fmo = fmoprp
= fmoxyz = fmolmo = fmobnd = data = false;
while ( fgets( line, MAXSTRLEN, fp ) != NULL ) {
ofmo_delete_prepost_space( line );
if ( line[0] == '!' ) continue;
ntok = ofmo_split( line, " \t\n\r", token, MAXTOKEN, MAXSTRLEN );
if ( ntok < 1 ) continue;
for ( i=0; i<ntok; i++ ) ofmo_tolower( token[i] );
if ( token[0][0] == '$' ) {
if ( strcmp( &token[0][1], "contrl" ) == 0 ) {
ierr=input_contrl( fp, token, ntok );
//printf("== 1 ==\n");
ctrl = true;
} else if ( strcmp( &token[0][1], "system" ) == 0 ) {
ierr=input_system( fp, token, ntok );
//printf("== 2 ==\n");
sys = true;
} else if ( strcmp( &token[0][1], "basis" ) == 0 ) {
ierr=input_basis( fp, token, ntok );
//printf("== 3 ==\n");
basis = true;
} else if ( strcmp( &token[0][1], "intgrl" ) == 0 ) {
ierr=input_intgrl( fp, token, ntok );
//printf("== 4 ==\n");
intgrl = true;
} else if ( strcmp( &token[0][1], "gddi" ) == 0 ) {
ierr=input_gddi( fp, token, ntok );
//printf("== 5 ==\n");
gddi = true;
} else if ( strcmp( &token[0][1], "scf" ) == 0 ) {
ierr=input_scf( fp, token, ntok );
//printf("== 6 ==\n");
scf = true;
} else if ( strcmp( &token[0][1], "fmo" ) == 0 ) {
ierr=input_fmo( fp, token, ntok );
//printf("== 7 ==\n");
fmo = true;
} else if ( strcmp( &token[0][1], "fmoprp" ) == 0 ) {
ierr=input_fmoprp( fp, token, ntok );
//printf("== 8 ==\n");
fmoprp = true;
} else if ( strcmp( &token[0][1], "fmoxyz" ) == 0 ) {
ierr=input_fmoxyz( fp, token, ntok );
//printf("== 9 ==\n");
fmoxyz = true;
} else if ( strcmp( &token[0][1], "fmolmo" ) == 0 ||
strcmp( &token[0][1], "fmohyb" ) == 0 ) {
ierr=input_fmolmo( fp, token, ntok );
//printf("== 10 ==\n");
fmolmo = true;
} else if ( strcmp( &token[0][1], "fmobnd" ) == 0 ) {
ierr=input_fmobnd( fp, token, ntok );
//printf("== 11 ==\n");
fmobnd = true;
} else if ( strcmp( &token[0][1], "data" ) == 0 ) {
ierr=input_data( fp, token, ntok );
//printf("== 12 ==\n");
data = true;
} else {
printf("Illegal section name (%s)\n", &token[0][1] );
ierr = -2;
}
}
}
int ierr0 = 0;
if ( !ctrl ) input_contrl( NULL, token, ntok );
if ( !sys ) input_system( NULL, token, ntok );
if ( !basis ) input_basis( NULL, token, ntok );
if ( !intgrl ) input_intgrl( NULL, token, ntok );
if ( !gddi ) input_gddi( NULL, token, ntok );
if ( !scf ) input_scf( NULL, token, ntok );
if ( !fmoprp ) input_fmoprp( NULL, token, ntok );
if ( !data ) input_data( NULL, token, ntok );
if ( !fmo ) { ierr0++; dbg("error: no $fmo section\n"); }
if ( !fmoxyz ) { ierr0++; dbg("error: no $fmoxyz section\n"); }
if ( !fmolmo ) { ierr0++; dbg("error: no $fmolmo section\n"); }
if ( !fmobnd ) { ierr0++; dbg("error: no $fmobnd section\n"); }
ofmo_free_char_2d( token );
ofmo_free_char_2d( local );
ofmo_free_char_2d( elems );
if ( ierr0 > 0 ) ierr = -1;
return ierr;
}
| 2.40625 | 2 |
2024-11-18T19:02:41.019498+00:00
| 2020-05-23T18:27:27 |
054972c2b287e7795998c428b2cc6efc21f675d9
|
{
"blob_id": "054972c2b287e7795998c428b2cc6efc21f675d9",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-23T18:27:27",
"content_id": "cf507b7bfca7e6d0a863dcfdcb510740ce47f600",
"detected_licenses": [
"Artistic-2.0"
],
"directory_id": "c70c52d7c2c1ed0865a6b804f7ae751e7a90832c",
"extension": "h",
"filename": "effect.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 266347263,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1293,
"license": "Artistic-2.0",
"license_type": "permissive",
"path": "/base/include/effect.h",
"provenance": "stackv2-0058.json.gz:158309",
"repo_name": "cahirwpz/ghostown-sushiboyz",
"revision_date": "2020-05-23T18:27:27",
"revision_id": "aabbbeded37ad49e5055190009e6a4f79637d32c",
"snapshot_id": "f8b7a18815b909d52cd4889cd6adf34e69fd6ae8",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/cahirwpz/ghostown-sushiboyz/aabbbeded37ad49e5055190009e6a4f79637d32c/base/include/effect.h",
"visit_date": "2022-08-22T16:58:39.152889"
}
|
stackv2
|
#ifndef __EFFECT_H__
#define __EFFECT_H__
#include "common.h"
#define EFFECT_LOADED 1
#define EFFECT_READY 2
#define EFFECT_RUNNING 4
typedef struct Effect {
const char *name;
/* AmigaOS is active during this step. Loads resources from disk. */
void (*Load)();
/* Frees all resources allocated by "Load" step. */
void (*UnLoad)();
/*
* Does all initialization steps required to launch the effect.
* 1) Allocate required memory.
* 2) Run all precalc routines.
* 2) Generate copper lists.
* 3) Set up interrupts and DMA channels.
*/
void (*Init)();
/* Frees all resources allocated by "Init" step. */
void (*Kill)();
/* Renders single frame of an effect. */
void (*Render)();
/* Called to prepare the data for the effect - e.g. decompress, generate,
* move to chip memory. */
void (*Prepare)();
/* Keeps information about state of resources related to this effect. */
UWORD state;
} EffectT;
__regargs void EffectLoad(EffectT *effect);
__regargs void EffectPrepare(EffectT *effect);
__regargs void EffectInit(EffectT *effect);
__regargs void EffectKill(EffectT *effect);
__regargs void EffectUnLoad(EffectT *effect);
#define EFFECT(NAME, A1, A2, A3, A4, A5, A6) \
EffectT NAME = { #NAME, (A1), (A2), (A3), (A4), (A5), (A6) };
#endif
| 2.171875 | 2 |
2024-11-18T19:02:41.110642+00:00
| 2021-02-27T10:57:31 |
3cac14d1c45fddafb9dd36e94681794137958093
|
{
"blob_id": "3cac14d1c45fddafb9dd36e94681794137958093",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-27T10:57:31",
"content_id": "ce44235a4e7911ac82dc1158673beec05079a396",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1905deabba3ab1b65530f725c5a99454ebaa0db6",
"extension": "c",
"filename": "expression.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 340868829,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 17103,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/expression.c",
"provenance": "stackv2-0058.json.gz:158438",
"repo_name": "fox136/compiler",
"revision_date": "2021-02-27T10:57:31",
"revision_id": "77330a62e7e5aa0801274a9a85ec2bb8291a7057",
"snapshot_id": "38c9e731188701aa7bafab98e6810ff989e54761",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/fox136/compiler/77330a62e7e5aa0801274a9a85ec2bb8291a7057/expression.c",
"visit_date": "2023-03-20T11:52:24.810057"
}
|
stackv2
|
#include "bianyi.h"
void expression(int level) {
// expressions have various format.
// but majorly can be divided into two parts: unit and operator
// for example `(char) *a[10] = (int *) func(b > 0 ? 10 : 20);
// `a[10]` is an unit while `*` is an operator.
// `func(...)` in total is an unit.
// so we should first parse those unit and unary operators
// and then the binary ones
//
// also the expression can be in the following types:
//
// 1. unit_unary ::= unit | unit unary_op | unary_op unit
// 2. expr ::= unit_unary (bin_op unit_unary ...)
// unit_unary()
int *id;
int tmp;
int *addr;
{
if (!token) {
printf("%d: unexpected token EOF of expression\n", line);
exit(-1);
}
if (token == Num) {
match(Num);
// emit code
*++text = IMM;
*++text = token_val;
expr_type = INT;
}
else if (token == Sin){
match(Sin);
match('(');
expression(Assign);
match(')');
*++text = SIN; //单目运算符
}
else if (token == Cos){
match(Cos);
match('(');
expression(Assign);
match(')');
*++text = COS; //单目运算符
}
else if (token == Tan){
match(Tan);
match('(');
expression(Assign);
match(')');
*++text = Tan; //单目运算符
}
else if (token == '"') {
// continous string "abc" "abc"
// emit code
*++text = IMM;
*++text = token_val;
match('"');
// store the rest strings
while (token == '"') {
match('"');
}
// append the end of string character '\0', all the data are default
// to 0, so just move data one position forward.
data = (char *)(((int)data + sizeof(int)) & (-sizeof(int)));
expr_type = PTR;
}
else if (token == Sizeof) {
// sizeof is actually an unary operator
// now only `sizeof(int)`, `sizeof(char)` and `sizeof(*...)` are
// supported.
match(Sizeof);
match('(');
expr_type = INT;
if (token == Int) {
match(Int);
} else if (token == Char) {
match(Char);
expr_type = CHAR;
}
while (token == Mul) {
match(Mul);
expr_type = expr_type + PTR;
}
match(')');
// emit code
*++text = IMM;
*++text = (expr_type == CHAR) ? sizeof(char) : sizeof(int);
expr_type = INT;
}
else if (token == Id) {
// there are several type when occurs to Id
// but this is unit, so it can only be
// 1. function call
// 2. Enum variable
// 3. global/local variable
match(Id);
id = current_id;
if (token == '(') {
// function call
match('(');
// pass in arguments
tmp = 0; // number of arguments
while (token != ')') {
expression(Assign);
*++text = PUSH;
tmp ++;
if (token == ',') {
match(',');
}
}
match(')');
// emit code
if (id[Class] == Sys) {
// system functions
*++text = id[Value];
}
else if (id[Class] == Fun) {
// function call
*++text = CALL;
*++text = id[Value];
}
else {
printf("%d: bad function call\n", line);
exit(-1);
}
// clean the stack for arguments
if (tmp > 0) {
*++text = ADJ;
*++text = tmp;
}
expr_type = id[Type];
}
else if (id[Class] == Num) {
// enum variable
*++text = IMM;
*++text = id[Value];
expr_type = INT;
}
else {
// variable
if (id[Class] == Loc) {
*++text = LEA;
*++text = index_of_bp - id[Value];
}
else if (id[Class] == Glo) {
*++text = IMM;
*++text = id[Value];
}
else {
printf("%d: undefined variable\n", line);
exit(-1);
}
// emit code, default behaviour is to load the value of the
// address which is stored in `ax`
expr_type = id[Type];
*++text = (expr_type == Char) ? LC : LI;
}
}
else if (token == '(') {
// cast or parenthesis
match('(');
if (token == Int || token == Char) {
tmp = (token == Char) ? CHAR : INT; // cast type
match(token);
while (token == Mul) {
match(Mul);
tmp = tmp + PTR;
}
match(')');
expression(Inc); // cast has precedence as Inc(++)
expr_type = tmp;
} else {
// normal parenthesis
expression(Assign);
match(')');
}
}
else if (token == Mul) {
// dereference *<addr>
match(Mul);
expression(Inc); // dereference has the same precedence as Inc(++)
if (expr_type >= PTR) {
expr_type = expr_type - PTR;
} else {
printf("%d: bad dereference\n", line);
exit(-1);
}
*++text = (expr_type == CHAR) ? LC : LI;
}
else if (token == And) {
// get the address of
match(And);
expression(Inc); // get the address of
if (*text == LC || *text == LI) {
text --;
} else {
printf("%d: bad address of\n", line);
exit(-1);
}
expr_type = expr_type + PTR;
}
else if (token == '!') {
// not
match('!');
expression(Inc);
// emit code, use <expr> == 0
*++text = PUSH;
*++text = IMM;
*++text = 0;
*++text = EQ;
expr_type = INT;
}
else if (token == '~') {
// bitwise not
match('~');
expression(Inc);
// emit code, use <expr> XOR -1
*++text = PUSH;
*++text = IMM;
*++text = -1;
*++text = XOR;
expr_type = INT;
}
else if (token == Add) {
// +var, do nothing
match(Add);
expression(Inc);
expr_type = INT;
}
else if (token == Sub) {
// -var
match(Sub);
if (token == Num) {
*++text = IMM;
*++text = -token_val;
match(Num);
} else {
*++text = IMM;
*++text = -1;
*++text = PUSH;
expression(Inc);
*++text = MUL;
}
expr_type = INT;
}
else if (token == Inc || token == Dec) {
tmp = token;
match(token);
expression(Inc);
if (*text == LC) {
*text = PUSH; // to duplicate the address
*++text = LC;
} else if (*text == LI) {
*text = PUSH;
*++text = LI;
} else {
printf("%d: bad lvalue of pre-increment\n", line);
exit(-1);
}
*++text = PUSH;
*++text = IMM;
*++text = (expr_type > PTR) ? sizeof(int) : sizeof(char);
*++text = (tmp == Inc) ? ADD : SUB;
*++text = (expr_type == CHAR) ? SC : SI;
}
else {
printf("%d: bad expression\n", line);
exit(-1);
}
}
// binary operator and postfix operators.
{
while (token >= level) {
// handle according to current operator's precedence
tmp = expr_type;
if (token == Assign) {
// var = expr;
match(Assign);
if (*text == LC || *text == LI) {
*text = PUSH; // save the lvalue's pointer
} else {
printf("%d: bad lvalue in assignment\n", line);
exit(-1);
}
expression(Assign);
expr_type = tmp;
*++text = (expr_type == CHAR) ? SC : SI;
}
else if (token == Cond) {
// expr ? a : b;
match(Cond);
*++text = JZ;
addr = ++text;
expression(Assign);
if (token == ':') {
match(':');
} else {
printf("%d: missing colon in conditional\n", line);
exit(-1);
}
*addr = (int)(text + 3);
*++text = JMP;
addr = ++text;
expression(Cond);
*addr = (int)(text + 1);
}
else if (token == Lor) {
// logic or
match(Lor);
*++text = JNZ;
addr = ++text;
expression(Lan);
*addr = (int)(text + 1);
expr_type = INT;
}
else if (token == Lan) {
// logic and
match(Lan);
*++text = JZ;
addr = ++text;
expression(Or);
*addr = (int)(text + 1);
expr_type = INT;
}
else if (token == Or) {
// bitwise or
match(Or);
*++text = PUSH;
expression(Xor);
*++text = OR;
expr_type = INT;
}
else if (token == Xor) {
// bitwise xor
match(Xor);
*++text = PUSH;
expression(And);
*++text = XOR;
expr_type = INT;
}
else if (token == And) {
// bitwise and
match(And);
*++text = PUSH;
expression(Eq);
*++text = AND;
expr_type = INT;
}
else if (token == Eq) {
// equal ==
match(Eq);
*++text = PUSH;
expression(Ne);
*++text = EQ;
expr_type = INT;
}
else if (token == Ne) {
// not equal !=
match(Ne);
*++text = PUSH;
expression(Lt);
*++text = NE;
expr_type = INT;
}
else if (token == Lt) {
// less than
match(Lt);
*++text = PUSH;
expression(Shl);
*++text = LT;
expr_type = INT;
}
else if (token == Gt) {
// greater than
match(Gt);
*++text = PUSH;
expression(Shl);
*++text = GT;
expr_type = INT;
}
else if (token == Le) {
// less than or equal to
match(Le);
*++text = PUSH;
expression(Shl);
*++text = LE;
expr_type = INT;
}
else if (token == Ge) {
// greater than or equal to
match(Ge);
*++text = PUSH;
expression(Shl);
*++text = GE;
expr_type = INT;
}
else if (token == Shl) {
// shift left
match(Shl);
*++text = PUSH;
expression(Add);
*++text = SHL;
expr_type = INT;
}
else if (token == Shr) {
// shift right
match(Shr);
*++text = PUSH;
expression(Add);
*++text = SHR;
expr_type = INT;
}
else if (token == Add) {
// add
match(Add);
*++text = PUSH;
expression(Mul);
expr_type = tmp;
if (expr_type > PTR) {
// pointer type, and not `char *`
*++text = PUSH;
*++text = IMM;
*++text = sizeof(int);
*++text = MUL;
}
*++text = ADD;
}
else if (token == Sub) {
// sub
match(Sub);
*++text = PUSH;
expression(Mul);
if (tmp > PTR && tmp == expr_type) {
// pointer subtraction
*++text = SUB;
*++text = PUSH;
*++text = IMM;
*++text = sizeof(int);
*++text = DIV;
expr_type = INT;
} else if (tmp > PTR) {
// pointer movement
*++text = PUSH;
*++text = IMM;
*++text = sizeof(int);
*++text = MUL;
*++text = SUB;
expr_type = tmp;
} else {
// numeral subtraction
*++text = SUB;
expr_type = tmp;
}
}
else if (token == Mul) {
// multiply
match(Mul);
*++text = PUSH;
expression(Inc);
*++text = MUL;
expr_type = tmp;
}
else if (token == Div) {
// divide
match(Div);
*++text = PUSH;
expression(Inc);
*++text = DIV;
expr_type = tmp;
}
else if (token == Mod) {
// Modulo
match(Mod);
*++text = PUSH;
expression(Inc);
*++text = MOD;
expr_type = tmp;
}
else if (token == Inc || token == Dec) {
// postfix inc(++) and dec(--)
// we will increase the value to the variable and decrease it
// on `ax` to get its original value.
if (*text == LI) {
*text = PUSH;
*++text = LI;
}
else if (*text == LC) {
*text = PUSH;
*++text = LC;
}
else {
printf("%d: bad value in increment\n", line);
exit(-1);
}
*++text = PUSH;
*++text = IMM;
*++text = (expr_type > PTR) ? sizeof(int) : sizeof(char);
*++text = (token == Inc) ? ADD : SUB;
*++text = (expr_type == CHAR) ? SC : SI;
*++text = PUSH;
*++text = IMM;
*++text = (expr_type > PTR) ? sizeof(int) : sizeof(char);
*++text = (token == Inc) ? SUB : ADD;
match(token);
}
else if (token == Brak) {
// array access var[xx]
match(Brak);
*++text = PUSH;
expression(Assign);
match(']');
if (tmp > PTR) {
// pointer, `not char *`
*++text = PUSH;
*++text = IMM;
*++text = sizeof(int);
*++text = MUL;
}
else if (tmp < PTR) {
printf("%d: pointer type expected\n", line);
exit(-1);
}
expr_type = tmp - PTR;
*++text = ADD;
*++text = (expr_type == CHAR) ? LC : LI;
}
else {
printf("%d: compiler error, token = %d\n", line, token);
exit(-1);
}
}
}
}
| 2.796875 | 3 |
2024-11-18T19:02:41.270016+00:00
| 2018-05-12T04:26:26 |
86e6017c5ea8638277140cab43e8a774596e60e5
|
{
"blob_id": "86e6017c5ea8638277140cab43e8a774596e60e5",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-12T04:26:26",
"content_id": "7a46a0d5dfeb39ec0272c7794808485441f162f1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "1eb76fcbe062a57f1cf6256c830aafb66e6166ee",
"extension": "c",
"filename": "debug_write.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 130634919,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2313,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/libplatform/source/debug/debug_write.c",
"provenance": "stackv2-0058.json.gz:158697",
"repo_name": "duaneellissd/ejtag",
"revision_date": "2018-05-12T04:26:26",
"revision_id": "bd6ebd1d2ec826667f44d48836ce90368b8d4b6f",
"snapshot_id": "91337127b4203056e240cbf4106e11a55404dbe5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/duaneellissd/ejtag/bd6ebd1d2ec826667f44d48836ce90368b8d4b6f/libplatform/source/debug/debug_write.c",
"visit_date": "2020-03-12T13:08:55.700523"
}
|
stackv2
|
#include "ejtag/platform/platform.h"
#include "ejtag/platform/debug.h"
#include "ejtag/platform/time.h"
#include "ejtag/platform/string.h"
static int dbg_column;
void DEBUG_newline(void)
{
DEBUG_writeRaw( "\r\n", 2);
dbg_column = 0;
}
static void now_check(void)
{
#define NOWBUF_SIZE 32
char buf[NOWBUF_SIZE];
int x;
uint32_t now;
/* print now if at column 0 */
if (dbg_column != 0) {
return;
}
buf[NOWBUF_SIZE - 1] = 0;
buf[NOWBUF_SIZE - 2] = ' ';
buf[NOWBUF_SIZE - 3] = '|';
buf[NOWBUF_SIZE - 4] = ' ';
now = TIME_mSecsNow();
buf[NOWBUF_SIZE - 5] = '0' + (now % 10);
now = now / 10;
buf[NOWBUF_SIZE - 6] = '0' + (now % 10);
now = now / 10;
buf[NOWBUF_SIZE - 7] = '0' + (now % 10);
now = now / 10;
buf[NOWBUF_SIZE - 8] = '.';
x = NOWBUF_SIZE - 9;
do {
buf[x] = '0' + (now % 10);
now /= 10;
x--;
} while (now)
;
switch (x) {
case (NOWBUF_SIZE - 10):
buf[x] = ' ';
x--;
/* fallthru; */
case (NOWBUF_SIZE - 11):
buf[x] = ' ';
x--;
/* fallthru; */
case (NOWBUF_SIZE - 12):
buf[x] = ' ';
x--;
/* fallthru; */
case (NOWBUF_SIZE - 13):
buf[x] = ' ';
x--;
/* fallthru; */
default:
/* do not space pad any more */
break;
}
/* backup to the last byte written to the buffer */
x++;
dbg_column = NOWBUF_SIZE - x - 1;
DEBUG_writeRaw( &buf[x], dbg_column );
}
void DEBUG_printNow(void)
{
dbg_column = 0;
now_check();
}
void DEBUG_putc(int c)
{
now_check();
if (c == '\n') {
DEBUG_newline();
}
else {
char buf[2];
buf[0] = (char)(c);
buf[1] = 0;
DEBUG_writeRaw(buf, 1);
dbg_column += 1;
}
}
int DEBUG_write( const char *s, size_t n )
{
int r;
size_t n2;
const char *cp;
/* we return what we write, which is everything */
/* the count does *NOT* include the cr/lf conversion */
r = (int)(n);
while(n > 0){
/* look forward for a newline */
cp = memchr(s, '\n', n);
if (cp == NULL) {
/* none, then we are done */
break;
}
/* how many bytes until we find the newline? */
n2 = (cp - s);
if (n2) {
/* write bytes prior to the newline */
now_check();
DEBUG_writeRaw(s, n2);
}
/* output the newline */
DEBUG_newline();
/* adjust pointer & count, and accounting for the newline */
n2++;
n = n - n2;
s += n2;
}
if (n) {
now_check();
DEBUG_writeRaw(s, n);
}
return r;
}
| 2.984375 | 3 |
2024-11-18T19:02:42.107483+00:00
| 2016-08-03T11:48:36 |
b8b57674033a735c94fd67a13bbf0498816b8750
|
{
"blob_id": "b8b57674033a735c94fd67a13bbf0498816b8750",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-03T11:48:36",
"content_id": "aea8509d1cc529ce3b272bab4b61071000b35a2d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ae3fd2bc5e0a5de2606eaf1709b135e0ff720103",
"extension": "c",
"filename": "dat_copy.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": 5349,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ADAS_core/alTILib/src/dat_copy.c",
"provenance": "stackv2-0058.json.gz:159338",
"repo_name": "kailushan/Car_System_suv",
"revision_date": "2016-08-03T11:48:36",
"revision_id": "92ad76b36e3850a7c68e5d361041d04745bbefee",
"snapshot_id": "58ff5eab9129429708d5b66eba7de4cd2d657658",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kailushan/Car_System_suv/92ad76b36e3850a7c68e5d361041d04745bbefee/ADAS_core/alTILib/src/dat_copy.c",
"visit_date": "2022-04-26T08:27:07.023109"
}
|
stackv2
|
#ifdef WIN32
#include <string.h>
#include "dat_copy.h"
//////////////////////////////////////////////////////////////////////////
Uint32 DAT_copy(void *a_pSrc , void *a_pDst , Uint16 a_uwByteCnt)
{
memcpy((Uint8 *)a_pDst, (Uint8 *)a_pSrc, a_uwByteCnt);
return 0;
}
Uint32 DAT_copy2d(Uint32 ulType, void *a_pSrc, void *a_pDst, Uint16 uwLineLen, Uint16 uwLineCnt, Uint16 uwLinePitch)
{
int i;
switch (ulType)
{
case DAT_1D2D:
for (i=0; i<uwLineCnt; i++)
memcpy((Uint8 *)a_pDst + i*uwLinePitch, (Uint8 *)a_pSrc + i*uwLineLen, uwLineLen);
break;
case DAT_2D1D:
for (i=0; i<uwLineCnt; i++)
memcpy((Uint8 *)a_pDst + i*uwLineLen, (Uint8 *)a_pSrc + i*uwLinePitch, uwLineLen);
break;
case DAT_2D2D:
for (i=0; i<uwLineCnt; i++)
memcpy((Uint8 *)a_pDst + i*uwLinePitch, (Uint8 *)a_pSrc + i*uwLinePitch, uwLineLen);
break;
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
Uint32 DAT_copy2d2d(void *src, void *dst, Uint16 lineLen,
Uint16 lineCnt, Uint16 linePitch_src, Uint16 linePitch_dst)
{
int i;
for (i=0; i<lineCnt; i++)
memcpy((Uint8 *)dst + i*linePitch_dst, (Uint8 *)src + i*linePitch_src, lineLen);
return 0;
}
//////////////////////////////////////////////////////////////////////////
Uint32 DAT_copy2d_lut(Uint32 type, void const * src, void * dst, Uint16 lineLen, Uint16 lineCnt, Uint16 linePitch, Uint16 PixelDepth)
{
#ifdef WIN32
int i;
#endif
switch (type)
{
case DAT_1D2D:
#ifndef WIN32
//source
stSrcInfo.pBuf = (uint8_t*) src;
stSrcInfo.ucPixelDepth = PixelDepth;
stSrcInfo.uwBufWidth = lineLen;
stSrcInfo.uwBufHeight = lineCnt;
stSrcInfo.uwStartX = 0;
stSrcInfo.uwStartY = 0;
stSrcInfo.uwSelWidth = lineLen;
stSrcInfo.uwSelHeight = lineCnt;
//destination
stDstInfo.pBuf = dst;
stDstInfo.ucPixelDepth = PixelDepth;
stDstInfo.uwBufWidth = linePitch;
stDstInfo.uwBufHeight = lineCnt;
stDstInfo.uwStartX = 0;
stDstInfo.uwStartY = 0;
stDstInfo.uwSelWidth = linePitch;
stDstInfo.uwSelHeight = lineCnt;
DMADRV_Copy2D(&stDstInfo, &stSrcInfo);
#else
for (i=0; i<lineCnt; i++)
memcpy((Uint8 *)dst + i*linePitch*PixelDepth, (Uint8 *)src + i*lineLen*PixelDepth, lineLen*PixelDepth);
#endif
break;
case DAT_2D1D:
#ifndef WIN32
//source
stSrcInfo.pBuf = (uint8_t*) src;
stSrcInfo.uwBufWidth = linePitch;
stSrcInfo.uwBufHeight = 0;
stSrcInfo.uwStartX = 0;
stSrcInfo.uwStartY = 0;
stSrcInfo.ucPixelDepth = PixelDepth;
stSrcInfo.uwSelWidth = linePitch;
stSrcInfo.uwSelHeight = lineCnt; //BCnt
//destination
stDstInfo.pBuf = dst;
stDstInfo.uwBufWidth = lineLen;
stDstInfo.uwBufHeight = lineCnt;
stDstInfo.uwStartX = 0;
stDstInfo.uwStartY = 0;
stDstInfo.ucPixelDepth = PixelDepth;
stDstInfo.uwSelWidth = lineLen;
stDstInfo.uwSelHeight = lineCnt;
DMADRV_Copy2D(&stDstInfo, &stSrcInfo);
#else
for (i=0; i<lineCnt; i++)
memcpy((Uint8 *)dst + i*lineLen*PixelDepth, (Uint8 *)src + i*linePitch*PixelDepth, lineLen*PixelDepth);
#endif
break;
case DAT_2D2D:
#ifndef WIN32
//source
stSrcInfo.pBuf = (uint8_t*) src;
stSrcInfo.uwBufWidth = linePitch;
stSrcInfo.uwBufHeight = 0;
stSrcInfo.uwStartX = 0;
stSrcInfo.uwStartY = 0;
stSrcInfo.ucPixelDepth = PixelDepth;
stSrcInfo.uwSelWidth = lineLen;
stSrcInfo.uwSelHeight = lineCnt;
//destination
stDstInfo.pBuf = dst;
stDstInfo.uwBufWidth = linePitch;
stDstInfo.uwBufHeight = 0;
stDstInfo.uwStartX = 0;
stDstInfo.uwStartY = 0;
stDstInfo.ucPixelDepth = PixelDepth;
stDstInfo.uwSelWidth = lineLen;
stDstInfo.uwSelHeight = lineCnt;
DMADRV_Copy2D(&stDstInfo, &stSrcInfo);
#else
for (i=0; i<lineCnt; i++)
memcpy((Uint8 *)dst + i*linePitch*PixelDepth, (Uint8 *)src + i*linePitch*PixelDepth, lineLen*PixelDepth);
#endif
break;
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
Uint32 DAT_fill(void *a_pDst , Uint16 a_uwByteCnt, Uint32 *ulValue)
{
memset(a_pDst, *ulValue, a_uwByteCnt);
return 0;
}
//////////////////////////////////////////////////////////////////////////
void DAT_wait(Uint32 id)
{
}
#endif
| 2.46875 | 2 |
2024-11-18T19:02:42.875024+00:00
| 2021-03-21T23:48:53 |
db34d879737cf359433e63031435612dfb0ae9f3
|
{
"blob_id": "db34d879737cf359433e63031435612dfb0ae9f3",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-24T21:33:15",
"content_id": "cc6c3a5e0331e57f0627ec962204c19ecf938fee",
"detected_licenses": [
"MIT"
],
"directory_id": "1248a15f947ea37492b573d98d24c7240c133c75",
"extension": "c",
"filename": "file.c",
"fork_events_count": 0,
"gha_created_at": "2021-03-25T20:48:53",
"gha_event_created_at": "2021-03-25T20:48:54",
"gha_language": null,
"gha_license_id": null,
"github_id": 351571884,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1104,
"license": "MIT",
"license_type": "permissive",
"path": "/host/file.c",
"provenance": "stackv2-0058.json.gz:159724",
"repo_name": "seh-msft/mystikos",
"revision_date": "2021-03-21T23:48:53",
"revision_id": "fffb88be2e98de80b975dfa5986aeea441db70d8",
"snapshot_id": "dae07dc3348db30bf09bf8626f0931d5ed4a2beb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/seh-msft/mystikos/fffb88be2e98de80b975dfa5986aeea441db70d8/host/file.c",
"visit_date": "2023-04-06T08:34:09.100425"
}
|
stackv2
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <myst/eraise.h>
#include <myst/file.h>
int myst_write_file(const char* path, const void* data, size_t size)
{
int ret = 0;
int fd;
const uint8_t* p = (const uint8_t*)data;
size_t r = size;
ssize_t n;
if ((fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0666)) < 0)
ERAISE(-errno);
while ((n = write(fd, p, r)) > 0)
{
p += n;
r -= n;
}
if (r != 0)
ERAISE(-EIO);
close(fd);
done:
return ret;
}
int myst_write_file_fd(int fd, const void* data, size_t size)
{
int ret = 0;
const uint8_t* p = (const uint8_t*)data;
size_t r = size;
ssize_t n;
if (fd < 0 || !data)
ERAISE(-EINVAL);
while (r > 0)
{
if ((n = write(fd, p, r)) == 0)
break;
if (n < 0)
ERAISE((int)-n);
p += n;
r -= (size_t)n;
}
if (r != 0)
ERAISE(-EIO);
done:
return ret;
}
| 2.75 | 3 |
2024-11-18T19:02:44.057257+00:00
| 2020-07-04T20:54:10 |
4342051042a4f2869273c4fee04ea790f3ae4fe9
|
{
"blob_id": "4342051042a4f2869273c4fee04ea790f3ae4fe9",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-04T20:54:10",
"content_id": "20db64f951275a0af58dd4ee7c80a307e9087059",
"detected_licenses": [
"MIT"
],
"directory_id": "fbd75a3173ef6b40a86ddf2cf2d8e0f079010315",
"extension": "c",
"filename": "cmd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 109163247,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6980,
"license": "MIT",
"license_type": "permissive",
"path": "/cmd.c",
"provenance": "stackv2-0058.json.gz:160237",
"repo_name": "andreluis034/compiladores",
"revision_date": "2020-07-04T20:54:10",
"revision_id": "9d9eb9017b8d917e147094518f07ce28701e5090",
"snapshot_id": "324dff3389fa540811dcaafa183e96f4f7685bd1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andreluis034/compiladores/9d9eb9017b8d917e147094518f07ce28701e5090/cmd.c",
"visit_date": "2021-03-16T11:02:08.066714"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cmd.h"
#include "ast.h"
#include "utility.h"
#define sCase(caso, func) case caso: \
func(cmd, level, lastChild);\
break
makeTypeList(CmdList*, makeCmdList, Cmd*)
appendType(CmdList*, appendCmd, Cmd*)
prependType(CmdList*, prependCmd, Cmd*)
getType(Cmd*, getCmd, CmdList*)
/*
Cmd* getCmd(CmdList* list)
{
return (Cmd*)getPointer(list);
}
*/
Cmd* makeDeclarationCmd(Expr* variable, char* operator, Expr* expr)
{
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_DECLARATION;
node->attr.declaration.variable = variable;// makeVariable(varName, expr);
node->attr.declaration.operator = operator;
node->attr.declaration.expr = expr;
return node;
}
Cmd* makeIncrementCmd(Expr* variable, char* operator, Expr* expr)
{
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_INCREMENT;
node->attr.increment.variable = variable;// makeVariable(varName, expr);
node->attr.increment.operator = operator;
node->attr.increment.expr = expr;
return node;
}
Cmd* makeIfElseCmd(Expr* expr, CmdList* iftrue, CmdList* iffalse )
{
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_IF_ELSE;
node->attr.ifelse.condition = expr;
node->attr.ifelse.iftrue = iftrue;
node->attr.ifelse.iffalse = iffalse;
return node;
}
Cmd* makeFor(Cmd* initial, Expr* condition, Cmd* afterIteration, CmdList* body )
{
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_FOR;
node->attr.forCmd.initial = initial;
node->attr.forCmd.condition = condition;
node->attr.forCmd.afterIteration = afterIteration;
node->attr.forCmd.body = body;
return node;
}
Cmd* makeFuncCall(char* funcName, ExprList* variables)
{
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_FUNC_CALL;
node->attr.funcCall.funcName = funcName;
node->attr.funcCall.variables = variables;
return node;
}
Cmd* makeFunctionReturn(Expr* variable, char* operator, Cmd* funcCall)
{
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_FUNC_RETURN;
node->attr.funcReturn.variable = variable;
node->attr.funcReturn.operator = operator;
node->attr.funcReturn.funcCall = funcCall;
return node;
}
Cmd* makeReturn(Expr* expr)
{
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_RETURN;
node->attr._return.value = expr;
return node;
}
Cmd* makeFunc(char* funcName, ExprList* arglist, CmdList* cmdlist)
{
int regNumber = 0;
int stackCount = 0;
Cmd* node = (Cmd*) malloc(sizeof(Cmd));
node->kind = C_FUNC;
node->attr.func.funcName = funcName;
node->attr.func.argList = arglist;
node->attr.func.commandList = cmdlist;
node->attr.func.scope = createScope();
while(arglist != NULL)
{
Expr* expr = getExpr(arglist);
if (regNumber < ARG_REGISTER_COUNT)
{
addArgument(node->attr.func.scope, expr->attr.variable, registerr, regNumber);
regNumber++;
}
else
{
addArgument(node->attr.func.scope, expr->attr.variable, stack, 4*stackCount);
stackCount++;
}
arglist = arglist->Next;
}
VariableList* varlist = checkCmdList(prependCmd(EMPTY_LIST, node));
stackCount = 1;
while(varlist != NULL)
{
addLocalVariable(node->attr.func.scope, getVariable(varlist));
varlist = varlist->Next;
stackCount++;
}
//printVariableList(cmdlist);
return node;
}
void printDeclaration(Cmd* cmd, int level, int lastChild)
{
printPadding(level, lastChild);
printf("C_DECLARATION\n");
printExpr(cmd->attr.declaration.variable, level+1, 0);
printKeyValue("OPERATOR", cmd->attr.declaration.operator, level + 1, 0);
printExpr(cmd->attr.declaration.expr, level+1, 1);
}
void printIncrement(Cmd* cmd, int level, int lastChild)
{
printPadding(level, lastChild);
printf("C_INCREMENT\n");
printKeyValue("OPERATOR", cmd->attr.increment.operator,
level + 1, 0);
printExpr(cmd->attr.increment.variable, level +1, cmd->attr.increment.expr == NULL);
if(cmd->attr.increment.expr != NULL)
{
printExpr(cmd->attr.increment.expr, level +1, 1);
}
}
void printIfElse(Cmd* cmd, int level, int lastChild)
{
printPadding(level, lastChild);
printf("C_IF_ELSE\n");
lastChild = IS_EMPTY_LIST( cmd->attr.ifelse.iffalse );
printExpr(cmd->attr.ifelse.condition, level + 1, 0);
printCmdList(cmd->attr.ifelse.iftrue, level + 1, lastChild);
if(!lastChild)
{
printCmdList(cmd->attr.ifelse.iffalse, level + 1, 1);
}
}
void printFor(Cmd* cmd, int level, int lastChild)
{
printPadding(level, lastChild);
printf("C_FOR\n");
if(cmd->attr.forCmd.initial != NULL)
{
printCmd(cmd->attr.forCmd.initial, level + 1, 0);
}
printExpr(cmd->attr.forCmd.condition, level + 1, 0);
if(cmd->attr.forCmd.afterIteration != NULL)
{
printCmd(cmd->attr.forCmd.afterIteration, level + 1, 0);
}
printCmdList(cmd->attr.forCmd.body, level + 1, 1);
}
void printFuncCall(Cmd* cmd, int level, int lastChild)
{
printPadding(level, lastChild);
printf("C_FUNC_CALL\n");
printKeyValue("NAME", cmd->attr.funcCall.funcName, level + 1, IS_EMPTY_LIST(cmd->attr.funcCall.variables));
if(!IS_EMPTY_LIST(cmd->attr.funcCall.variables))
{
printExprList(cmd->attr.funcCall.variables, level + 1, 1);
}
}
void printFunc(Cmd* cmd, int level, int lastChild)
{
printPadding(level, lastChild);
printf("C_FUNC\n");
printKeyValue("NAME", cmd->attr.func.funcName, level + 1, 0);
printExprList(cmd->attr.func.argList, level + 1, 0);
printCmdList(cmd->attr.func.commandList, level + 1, 1);
}
void printFuncReturn(Cmd* cmd, int level, int lastChild)
{
printPadding(level, lastChild);
printf("C_FUNC_RETURN\n");
printExpr(cmd->attr.funcReturn.variable, level+1, 0);
printKeyValue("OPERATOR", cmd->attr.funcReturn.operator, level + 1, 0);
printFuncCall(cmd->attr.funcReturn.funcCall,level + 1,1);
}
void printReturn(Cmd* cmd, int level, int lastChild){
printPadding(level, lastChild);
printf("C_RETURN\n");
printExpr(cmd->attr._return.value, level+1, 1);
}
void printCmd(Cmd* cmd, int level, int lastChild)
{
switch(cmd->kind)
{
sCase(C_DECLARATION, printDeclaration);
sCase(C_INCREMENT, printIncrement);
sCase(C_IF_ELSE, printIfElse);
sCase(C_FOR, printFor);
sCase(C_FUNC_CALL, printFuncCall);
sCase(C_FUNC_RETURN, printFuncReturn);
sCase(C_FUNC, printFunc);
sCase(C_RETURN, printReturn);
}
}
void printCmdList(CmdList* cmdlist, int level, int lastChild)
{
printPadding(level, lastChild);
printf("CmdList\n");
while(cmdlist != NULL)
{
printCmd(getCmd(cmdlist), level + 1, IS_EMPTY_LIST(cmdlist->Next));
cmdlist = cmdlist->Next;
}
}
| 2.328125 | 2 |
2024-11-18T19:02:44.254288+00:00
| 2013-08-02T03:59:20 |
f7b2c0cacc5f854d57c2effee386e056f3ef7a5e
|
{
"blob_id": "f7b2c0cacc5f854d57c2effee386e056f3ef7a5e",
"branch_name": "refs/heads/master",
"committer_date": "2013-08-02T03:59:20",
"content_id": "b858567316d5ac8e6ca27af0838db7bc00449a56",
"detected_licenses": [
"Zlib"
],
"directory_id": "a2ca795d725f6bf234e5fabba58f17de18027063",
"extension": "c",
"filename": "helpers-binary.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": 3994,
"license": "Zlib",
"license_type": "permissive",
"path": "/libembroidery/helpers-binary.c",
"provenance": "stackv2-0058.json.gz:160495",
"repo_name": "claudeocquidant/Embroidermodder",
"revision_date": "2013-08-02T03:59:20",
"revision_id": "dbce0041a9bbd061b4423a3cb11cb75d20d31132",
"snapshot_id": "7f8ddcee446fa561e885aea8d3a45da3e863624a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/claudeocquidant/Embroidermodder/dbce0041a9bbd061b4423a3cb11cb75d20d31132/libembroidery/helpers-binary.c",
"visit_date": "2021-01-18T10:30:39.167437"
}
|
stackv2
|
#include "helpers-binary.h"
char binaryReadByte(FILE* file)
{
return fgetc(file);
}
int binaryReadBytes(FILE* file, unsigned char* destination, int count)
{
return (int) fread((char*) destination, 1, count, file);
}
int binaryReadInt16(FILE* file)
{
short x = fgetc(file);
x = x | fgetc(file) << 8;
return x;
}
int binaryReadInt32(FILE* file)
{
int x = fgetc(file);
x = x | fgetc(file) << 8;
x = x | fgetc(file) << 16;
x = x | fgetc(file) << 24;
return x;
}
unsigned char binaryReadUInt8(FILE* file)
{
return (unsigned char)fgetc(file);
}
unsigned short binaryReadUInt16(FILE* file)
{
return (unsigned short)(fgetc(file) | fgetc(file) << 8);
}
unsigned int binaryReadUInt32(FILE* file)
{
unsigned int x = fgetc(file);
x = x | fgetc(file) << 8;
x = x | fgetc(file) << 16;
x = x | fgetc(file) << 24;
return x;
}
/* Big endian version */
short binaryReadInt16BE(FILE* file)
{
short returnValue = (short)(fgetc(file) << 8);
returnValue |= fgetc(file);
return returnValue;
}
/* Big endian version */
unsigned short binaryReadUInt16BE(FILE* file)
{
unsigned short returnValue = (unsigned short)(fgetc(file) << 8);
returnValue |= fgetc(file);
return returnValue;
}
/* Big endian version */
int binaryReadInt32BE(FILE* file)
{
int returnValue = fgetc(file) << 24;
returnValue |= fgetc(file) << 16;
returnValue |= fgetc(file) << 8;
returnValue |= fgetc(file);
return (returnValue);
}
/* Big endian version */
unsigned int binaryReadUInt32BE(FILE* file)
{
unsigned int returnValue = fgetc(file) << 24;
returnValue |= fgetc(file) << 16;
returnValue |= fgetc(file) << 8;
returnValue |= fgetc(file);
return returnValue;
}
void binaryReadString(FILE* file, char *buffer, int maxLength)
{
int i = 0;
while(i < maxLength)
{
buffer[i] = fgetc(file);
if(buffer[i] == '\0') break;
i++;
}
}
float binaryReadFloat(FILE* file)
{
union
{
float f32;
unsigned int u32;
} float_int_u;
float_int_u.u32 = fgetc(file);
float_int_u.u32 |= fgetc(file) << 8;
float_int_u.u32 |= fgetc(file) << 16;
float_int_u.u32 |= fgetc(file) << 24;
return float_int_u.f32;
}
void binaryWriteByte(FILE* file, unsigned char data)
{
fputc(data, file);
}
void binaryWriteBytes(FILE* file, const char* data, int size)
{
fwrite((char*)data, 1, size, file);
}
void binaryWriteShort(FILE* file, short data)
{
fputc(data & 0xFF, file);
fputc((data >> 8) & 0xFF, file);
}
void binaryWriteUShort(FILE* file, unsigned short data)
{
fputc(data & 0xFF, file);
fputc((data >> 8) & 0xFF, file);
}
void binaryWriteUShortBE(FILE* file, unsigned short data)
{
fputc((data >> 8) & 0xFF, file);
fputc(data & 0xFF, file);
}
void binaryWriteInt(FILE* file, int data)
{
fputc(data & 0xFF, file);
fputc((data >> 8) & 0xFF, file);
fputc((data >> 16) & 0xFF, file);
fputc((data >> 24) & 0xFF, file);
}
void binaryWriteUInt(FILE* file, unsigned int data)
{
fputc(data & 0xFF, file);
fputc((data >> 8) & 0xFF, file);
fputc((data >> 16) & 0xFF, file);
fputc((data >> 24) & 0xFF, file);
}
void binaryWriteUIntBE(FILE* file, unsigned int data)
{
fputc((data >> 24) & 0xFF, file);
fputc((data >> 16) & 0xFF, file);
fputc((data >> 8) & 0xFF, file);
fputc(data & 0xFF, file);
}
void binaryWriteFloat(FILE* file, float data)
{
union
{
float f32;
unsigned int u32;
} float_int_u;
float_int_u.f32 = data;
fputc(float_int_u.u32 & 0xFF, file);
fputc((float_int_u.u32 >> 8) & 0xFF, file);
fputc((float_int_u.u32 >> 16) & 0xFF, file);
fputc((float_int_u.u32 >> 24) & 0xFF, file);
}
/* kate: bom off; indent-mode cstyle; indent-width 4; replace-trailing-space-save on; */
| 2.703125 | 3 |
2024-11-18T19:02:44.364370+00:00
| 2019-06-01T16:19:20 |
1d13b49e4c2dbb8dbb8a603c7538b12097fa62c0
|
{
"blob_id": "1d13b49e4c2dbb8dbb8a603c7538b12097fa62c0",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-01T16:19:20",
"content_id": "82cb262f6221c53ffec4109e194bbd12079df9a5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0a058865c6e6a79ba80576f97d560f5108ef9688",
"extension": "c",
"filename": "Util.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 189062061,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 18717,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/Util.c",
"provenance": "stackv2-0058.json.gz:160624",
"repo_name": "yhyeh/DBMSFinalProject",
"revision_date": "2019-06-01T16:19:20",
"revision_id": "7ab9803d57fd694c70be3a51846962b2230753ee",
"snapshot_id": "6db35b480a3c1b7c19f386c38e03a42f8b2438fd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yhyeh/DBMSFinalProject/7ab9803d57fd694c70be3a51846962b2230753ee/src/Util.c",
"visit_date": "2020-05-29T09:25:37.963508"
}
|
stackv2
|
#include <stdio.h>
#include <stdio_ext.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include "Util.h"
#include "Command.h"
#include "Table.h"
#include "SelectState.h"
#include "User.h"
///
/// Allocate State_t and initialize some attributes
/// Return: ptr of new State_t
///
State_t* new_State() {
State_t *state = (State_t*)malloc(sizeof(State_t));
state->saved_stdout = -1;
return state;
}
///
/// Print shell prompt
///
void print_prompt(State_t *state) {
if (state->saved_stdout == -1) {
printf("db > ");
}
}
///
/// Print the user in the specific format
///
void print_user(User_t *user, SelectArgs_t *sel_args) {
size_t idx;
printf("(");
for (idx = 0; idx < sel_args->fields_len; idx++) {
if (!strncmp(sel_args->fields[idx], "*", 1)) {
printf("%d, %s, %s, %d", user->id, user->name, user->email, user->age);
} else {
if (idx > 0) printf(", ");
if (!strncmp(sel_args->fields[idx], "id", 2)) {
printf("%d", user->id);
} else if (!strncmp(sel_args->fields[idx], "name", 4)) {
printf("%s", user->name);
} else if (!strncmp(sel_args->fields[idx], "email", 5)) {
printf("%s", user->email);
} else if (!strncmp(sel_args->fields[idx], "age", 3)) {
printf("%d", user->age);
}
}
}
printf(")\n");
}
///
/// Print the users for given offset and limit restriction
///
void print_users(Table_t *table, int *idxList, size_t idxListLen, Command_t *cmd) {
size_t idx;
int limit = cmd->cmd_args.sel_args.limit;
int offset = cmd->cmd_args.sel_args.offset;
if (offset == -1) {
offset = 0;
}
int flag = 0;
for (int i = 0; i < cmd->cmd_args.sel_args.fields_len; i++){
if (!strncmp(cmd->cmd_args.sel_args.fields[i], "avg(id)", 7)) {
if (offset !=0 || limit == 0)
return;
flag = 1;
if (i==0)
printf("(");
else
printf(", ");
if (idxList){
double sum = 0 ;
for (idx = 0 ; idx < idxListLen; idx++)
{
User_t* user = get_User(table, idxList[idx]);
sum += user->id;
}
printf("%.3f",sum/idxListLen);
}
else{
double sum = 0 ;
for (idx = 0 ; idx < table->len; idx++)
{
User_t* user = get_User(table, idx);
sum += user->id;
}
printf("%.3f",sum/table->len);
}
}
else if (!strncmp(cmd->cmd_args.sel_args.fields[i], "avg(age)", 8)){
if (offset !=0 || limit == 0)
return;
flag = 1;
if (i==0)
printf("(");
else
printf(", ");
if (idxList){
double sum = 0 ;
for (idx = 0 ; idx < idxListLen; idx++)
{
User_t* user = get_User(table, idxList[idx]);
sum += user->age;
}
printf("%.3f",sum/idxListLen);
}
else{
double sum = 0 ;
for (idx = 0 ; idx < table->len; idx++)
{
User_t* user = get_User(table, idx);
sum += user->age;
}
printf("%.3f",sum/table->len);
}
}
else if (!strncmp(cmd->cmd_args.sel_args.fields[i], "sum(id)", 7)){
if (offset !=0 || limit == 0)
return;
flag = 1;
if (i==0)
printf("(");
else
printf(", ");
if (idxList){
int sum = 0 ;
for (idx = 0 ; idx < idxListLen; idx++)
{
User_t* user = get_User(table, idxList[idx]);
sum += user->id;
}
printf("%d",sum);
}
else{
int sum = 0 ;
for (idx = 0 ; idx < table->len; idx++)
{
User_t* user = get_User(table, idx);
sum += user->id;
}
printf("%d",sum);
}
}
else if (!strncmp(cmd->cmd_args.sel_args.fields[i], "sum(age)", 8)){
if (offset !=0 || limit == 0)
return;
flag = 1;
if (i==0)
printf("(");
else
printf(", ");
if (idxList){
int sum = 0 ;
for (idx = 0 ; idx < idxListLen; idx++)
{
User_t* user = get_User(table, idxList[idx]);
sum += user->age;
}
printf("%d",sum);
}
else{
int sum = 0 ;
for (idx = 0 ; idx < table->len; idx++)
{
User_t* user = get_User(table, idx);
sum += user->age;
}
printf("%d",sum);
}
}
else if (!strncmp(cmd->cmd_args.sel_args.fields[i], "count(", 6)){
if (offset !=0 || limit == 0)
return;
flag = 1;
if (i==0)
printf("(");
else
printf(", ");
if (idxList){
printf("%ld",idxListLen);
}
else{
printf("%ld",table->len);
}
}
}
if(flag){
printf(")\n");
}
else{
if (idxList) {
for (idx = offset; idx < idxListLen; idx++) {
if (limit != -1 && (idx - offset) >= limit) {
break;
}
print_user(get_User(table, idxList[idx]), &(cmd->cmd_args.sel_args));
}
} else {
for (idx = offset; idx < table->len; idx++) {
if (limit != -1 && (idx - offset) >= limit) {
break;
}
print_user(get_User(table, idx), &(cmd->cmd_args.sel_args));
}
}
}
}
///
/// This function received an output argument
/// Return: category of the command
///
int parse_input(char *input, Command_t *cmd) {
char *token;
int idx;
token = strtok(input, " ,\n");
cmd->type_table = UNRECOG_TB;
if(token == NULL){
cmd->type = UNRECOG_CMD;
return cmd->type;
}
for (idx = 0; strlen(cmd_list[idx].name) != 0; idx++) {
if (!strncmp(token, cmd_list[idx].name, cmd_list[idx].len)) {
cmd->type = cmd_list[idx].type;
}
}
while (token != NULL) {
if (!strncmp(token,"join",4))
cmd->type_table = JOIN_TB;
if (cmd->type_table == UNRECOG_TB){
if (!strncmp(token,"user",4)){
cmd->type_table = USER_TB;
}
else if (!strncmp(token,"like",4)){
cmd->type_table = LIKE_TB;
}
}
add_Arg(cmd, token);
token = strtok(NULL, " ,\n");
}
return cmd->type;
}
///
/// Handle built-in commands
/// Return: command type
///
void handle_builtin_cmd(Table_t *table, Command_t *cmd, State_t *state) {
if (!strncmp(cmd->args[0], ".exit", 5)) {
archive_table(table);
exit(0);
} else if (!strncmp(cmd->args[0], ".output", 7)) {
if (cmd->args_len == 2) {
if (!strncmp(cmd->args[1], "stdout", 6)) {
close(1);
dup2(state->saved_stdout, 1);
state->saved_stdout = -1;
} else if (state->saved_stdout == -1) {
int fd = creat(cmd->args[1], 0644);
state->saved_stdout = dup(1);
if (dup2(fd, 1) == -1) {
state->saved_stdout = -1;
}
__fpurge(stdout); //This is used to clear the stdout buffer
}
}
} else if (!strncmp(cmd->args[0], ".load", 5)) {
if (cmd->args_len == 2) {
load_table(table, cmd->args[1]);
}
} else if (!strncmp(cmd->args[0], ".help", 5)) {
print_help_msg();
}
}
///
/// Handle query type commands
/// Return: command type
///
int handle_query_cmd(Table_t *table, Command_t *cmd) {
if (!strncmp(cmd->args[0], "insert", 6)) {
handle_insert_cmd(table, cmd);
return INSERT_CMD;
} else if (!strncmp(cmd->args[0], "select", 6)) {
handle_select_cmd(table, cmd);
return SELECT_CMD;
}
else if (!strncmp(cmd->args[0], "update", 6)) {
handle_update_cmd(table,cmd);
return UPDATE_CMD;
}
else if (!strncmp(cmd->args[0], "delete", 6)) {
handle_delete_cmd(table,cmd);
return DELETE_CMD;
}
else {
return UNRECOG_CMD;
}
}
///
/// The return value is the number of rows insert into table
/// If the delete operation success, then change the input arg
/// `cmd->type` to DELETE_CMD
///
int handle_delete_cmd(Table_t *table, Command_t *cmd) {
int ret = 0;
cmd->cmd_args.sel_args.where_begin = -1;
cmd->cmd_args.sel_args.where_end = -1;
if(strncmp(cmd->args[1], "from", 4) || strncmp(cmd->args[2], "user", 4)){
cmd->type = UNRECOG_CMD;
return ret;
}
size_t arg_idx = 3;
if (arg_idx == cmd->args_len){
table->len = 0;
}
else if(!strncmp(cmd->args[arg_idx], "where", 5)){
cmd->cmd_args.sel_args.where_begin = arg_idx+1;
cmd->cmd_args.sel_args.where_end = cmd->args_len - 1 ;
int *idxList = malloc(sizeof(int)* table->len);
size_t idxListLen = where_check(table,cmd,idxList);
for (int idx = idxListLen -1 ; idx >=0 ; idx--)
{
for(int i = idxList[idx] ; i < table->len -1 ; i++)
{
User_t* temp_u1 = get_User(table,i);
User_t* temp_u2 = get_User(table,i+1);
memcpy((table->users)+i, temp_u2, sizeof(User_t));
memcpy((table->users)+i+1, temp_u1, sizeof(User_t));
}
table->len--;
}
}
else {
cmd->type = UNRECOG_CMD;
return ret;
}
cmd->type = DELETE_CMD;
ret = 1;
return ret;
}
///
/// The return value is the number of rows insert into table
/// If the update operation success, then change the input arg
/// `cmd->type` to UPDATE_CMD
///
int handle_update_cmd(Table_t *table, Command_t *cmd) {
int ret = 0;
cmd->cmd_args.sel_args.where_begin = -1;
cmd->cmd_args.sel_args.where_end = -1;
if(strncmp(cmd->args[1], "user", 4) || strncmp(cmd->args[2], "set", 3)){
cmd->type = UNRECOG_CMD;
return ret;
}
size_t arg_idx = 3;
size_t char_idx = 0;
int flag_col = -1;
int num = 0;
char *str = NULL;
char temp[200];
for(size_t i = arg_idx; i < cmd->args_len; i++){
if (!strncmp(cmd->args[i], "where", 5)){
arg_idx = i;
cmd->cmd_args.sel_args.where_begin = i+1;
break;
}
if(i == arg_idx)
strcpy(temp,cmd->args[i]);
else
strcat(temp,cmd->args[i]);
}
if(!strncmp(temp, "id", 2)){
char_idx = 2;
if (temp[char_idx] != '='){
cmd->type = UNRECOG_CMD;
return ret;
}
char_idx++;
char *ptr = temp + char_idx;
flag_col = 1;
num = atoi(ptr);
}
else if(!strncmp(temp, "name", 4)){
char_idx = 4;
if (temp[char_idx] != '='){
cmd->type = UNRECOG_CMD;
return ret;
}
char_idx++;
char *ptr = temp + char_idx;
flag_col = 2;
str = strdup(ptr);
}
else if(!strncmp(temp, "email", 5)){
char_idx = 5;
if (temp[char_idx] != '='){
cmd->type = UNRECOG_CMD;
return ret;
}
char_idx++;
char *ptr = temp + char_idx;
flag_col = 3;
str = strdup(ptr);
}
else if(!strncmp(temp, "age", 3)){
char_idx = 3;
if (temp[char_idx] != '='){
cmd->type = UNRECOG_CMD;
return ret;
}
char_idx++;
char *ptr = temp + char_idx;
flag_col = 4;
num = atoi(ptr);
}
else {
cmd->type = UNRECOG_CMD;
return ret;
}
if (cmd->cmd_args.sel_args.where_begin != -1){
cmd->cmd_args.sel_args.where_end = cmd->args_len - 1;
int *idxList = malloc(sizeof(int)* table->len);
size_t idxListLen = where_check(table,cmd,idxList);
for (size_t idx =0 ; idx<idxListLen; idx++){
User_t* user = get_User(table, idxList[idx]);
if(flag_col ==1){
if(idxListLen==1)
{
int flag_t = 0;
for(size_t i = 0 ; i < table->len; i++)
{
User_t* user_temp = get_User(table, i);
if(user_temp->id == num)
{
flag_t = 1;
break;
}
}
if(!flag_t)
user->id = num;
}
}
else if(flag_col ==2){
strncpy(user->name,str,strlen(str)+1);
}
else if(flag_col ==3){
strncpy(user->email,str,strlen(str)+1);
}
else if(flag_col ==4){
user->age = num;
}
}
}
else{
for(size_t idx = 0 ; idx < table->len; idx++)
{
User_t* user = get_User(table, idx);
if(flag_col ==1){
if (table->len == 1)
user->id = num;
}
else if(flag_col ==2){
strncpy(user->name,str,strlen(str)+1);
}
else if(flag_col ==3){
strncpy(user->email,str,strlen(str)+1);
}
else if(flag_col ==4){
user->age = num;
}
}
}
if(str != NULL)
free(str);
cmd->type = UPDATE_CMD;
ret = 1;
return ret;
}
///
/// The return value is the number of rows insert into table
/// If the insert operation success, then change the input arg
/// `cmd->type` to INSERT_CMD
///
int handle_insert_cmd(Table_t *table, Command_t *cmd) {
int ret = 0;
User_t *user = command_to_User(cmd);
if (user) {
ret = add_User(table, user);
if (ret > 0) {
cmd->type = INSERT_CMD;
}
}
return ret;
}
size_t where_check(Table_t *table, Command_t *cmd, int* idxList)
{
if (idxList == NULL)
idxList = malloc(sizeof(int) * table->len);
int operator_mat[10]; // relational_ops
int op_i = 0;
int cond_mat[10]; // user_fields
int cond_i = 0;
double number_mat[10];
char char_mat[10][100];
int num_i = 0;
int logic_mat[10]; // logical_ops
int logic_i = 0;
size_t idxListLen = 0;
int cond_begin = cmd->cmd_args.sel_args.where_begin;
int cond_end = cmd->cmd_args.sel_args.where_end;
int cond_len = cond_end - cond_begin + 1;
char cur_str[256];
for(int index_cmd = 0; index_cmd < cond_len; index_cmd++){
strcpy(cur_str, cmd->args[cond_begin + index_cmd]);
switch(index_cmd % 4){
case COND:
if (!strncmp(cur_str, "id", 2))
cond_mat[cond_i++] = ID;
else if (!strncmp(cur_str, "name", 4))
cond_mat[cond_i++] = NAME;
else if (!strncmp(cur_str, "email", 5))
cond_mat[cond_i++] = EMAIL;
else if (!strncmp(cur_str, "age", 3))
cond_mat[cond_i++] = AGE;
else
printf("where-condition field err: %s\n", cur_str);
break;
case OP:
if (!strncmp(cur_str, "=", 1))
operator_mat[op_i++] = EQ;
else if (!strncmp(cur_str, "!=", 2))
operator_mat[op_i++] = NEQ;
else if (!strncmp(cur_str, ">=", 2))
operator_mat[op_i++] = GTE;
else if (!strncmp(cur_str, "<=", 2))
operator_mat[op_i++] = LTE;
else if (!strncmp(cur_str, ">", 1))
operator_mat[op_i++] = GT;
else if (!strncmp(cur_str, "<", 1))
operator_mat[op_i++] = LT;
else
printf("where-condition op err: %s\n", cur_str);
break;
case VALUE:
if (cur_str[0] == '"')
strcpy(char_mat[num_i++], cur_str);
else
number_mat[num_i++] = atof(cur_str);
break;
case LOGIC:
if (!strncmp(cur_str, "or", 2))
logic_mat[logic_i++] = OR;
else if (!strncmp(cur_str, "and", 3))
logic_mat[logic_i++] = AND;
else
printf("where-condition logic op err: %s\n", cur_str);
}
}
//////////////////////end translation /////////////////////////////
if(op_i != cond_i || op_i != num_i || op_i != logic_i + 1)
{
printf("error op cond num error!\n");
cmd->type = UNRECOG_CMD;
return table->len;
}
for (int idx = 0 ; idx < table->len; idx++)
{
User_t* User = get_User(table, idx);
int flag1 = 0 ;
int flag2 = 0 ;
for(int i = 0 ; i < op_i;i++){
double number = number_mat[i];
if (cond_mat[i] == ID){
if(operator_mat[i]==EQ){
if(User->id == number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==NEQ){
if(User->id != number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==GT){
if(User->id > number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==LT){
if(User->id < number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==GTE){
if(User->id >= number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==LTE){
if(User->id <= number)
flag2 = 1;
else
flag2 = 0;
}
}
else if (cond_mat[i] == NAME){
if(operator_mat[i]==EQ){
if(!strcmp(User->name,char_mat[i]))
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==NEQ){
if(strcmp(User->name,char_mat[i]))
flag2 = 1;
else
flag2 = 0;
}
}
else if (cond_mat[i] == EMAIL){
if(operator_mat[i]==EQ){
if(!strcmp(User->email,char_mat[i]))
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==NEQ){
if(strcmp(User->email,char_mat[i]))
flag2 = 1;
else
flag2 = 0;
}
}
else if (cond_mat[i] == AGE){
if(operator_mat[i]==EQ){
if(User->age == number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==NEQ){
if(User->age != number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==GT){
if(User->age > number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==LT){
if(User->age < number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==GTE){
if(User->age >= number)
flag2 = 1;
else
flag2 = 0;
}
if(operator_mat[i]==LTE){
if(User->age <= number)
flag2 = 1;
else
flag2 = 0;
}
}
if(i == 0)
flag1 = flag2;
else
{
if(logic_mat[i-1]==OR) // or
flag1 |= flag2;
else if (logic_mat[i-1]==AND)
flag1 &= flag2;
}
}
if (flag1)
idxList[idxListLen++] = idx;
}
return idxListLen;
}
///
/// The return value is the number of rows select from table
/// If the select operation success, then change the input arg
/// `cmd->type` to SELECT_CMD
///
int handle_select_cmd(Table_t *table, Command_t *cmd) {
cmd->type = SELECT_CMD;
field_state_handler(cmd, 1);
if (cmd->cmd_args.sel_args.where_begin == -1){
print_users(table, NULL, 0, cmd);
}
else {
int *idxList ;
idxList = malloc(sizeof(int) * table->len);
size_t idxListLen;
idxListLen = where_check(table,cmd,idxList);
print_users(table, idxList, idxListLen, cmd);
free(idxList);
}
return table->len;
}
///
/// Show the help messages
///
void print_help_msg() {
const char msg[] = "# Supported Commands\n"
"\n"
"## Built-in Commands\n"
"\n"
" * .exit\n"
"\tThis cmd archives the table, if the db file is specified, then exit.\n"
"\n"
" * .output\n"
"\tThis cmd change the output strategy, default is stdout.\n"
"\n"
"\tUsage:\n"
"\t .output (<file>|stdout)\n\n"
"\tThe results will be redirected to <file> if specified, otherwise they will display to stdout.\n"
"\n"
" * .load\n"
"\tThis command loads records stored in <DB file>.\n"
"\n"
"\t*** Warning: This command will overwrite the records already stored in current table. ***\n"
"\n"
"\tUsage:\n"
"\t .load <DB file>\n\n"
"\n"
" * .help\n"
"\tThis cmd displays the help messages.\n"
"\n"
"## Query Commands\n"
"\n"
" * insert\n"
"\tThis cmd inserts one user record into table.\n"
"\n"
"\tUsage:\n"
"\t insert <id> <name> <email> <age>\n"
"\n"
"\t** Notice: The <name> & <email> are string without any whitespace character, and maximum length of them is 255. **\n"
"\n"
" * select\n"
"\tThis cmd will display all user records in the table.\n"
"\n";
printf("%s", msg);
}
| 2.84375 | 3 |
2024-11-18T19:02:44.902340+00:00
| 2019-07-26T10:40:27 |
028e8485e1ccc65b3b5d2bde271e963094e69729
|
{
"blob_id": "028e8485e1ccc65b3b5d2bde271e963094e69729",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-26T10:40:27",
"content_id": "23b42221230022f6fc37549c6c6323354d52be99",
"detected_licenses": [
"MIT"
],
"directory_id": "2725bed874de7d01173ecd2e2fd1f54d702c07dd",
"extension": "c",
"filename": "set.c",
"fork_events_count": 2,
"gha_created_at": "2017-11-25T04:06:08",
"gha_event_created_at": "2019-07-26T10:40:28",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 111975279,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4045,
"license": "MIT",
"license_type": "permissive",
"path": "/source/set.c",
"provenance": "stackv2-0058.json.gz:161009",
"repo_name": "duxingzhe/LearningMasteringAlgorithms-C",
"revision_date": "2019-07-26T10:40:27",
"revision_id": "1d3d800e0561a97a0676aec6c483eb9e9e5a5333",
"snapshot_id": "6ea977f0afaa06236ae3410c45d79a2defc4f66b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/duxingzhe/LearningMasteringAlgorithms-C/1d3d800e0561a97a0676aec6c483eb9e9e5a5333/source/set.c",
"visit_date": "2021-05-06T18:15:47.051064"
}
|
stackv2
|
//
// set.c
// Algorithms - set
//
// Created by YourtionGuo on 26/04/2017.
// Copyright © 2017 Yourtion. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
#include "set.h"
#pragma mark - Public
void set_init(Set *set, int (*match)(const void *key1, const void *key2), void (*destroy)(void *data))
{
/// 初始化集合
list_init(set, destroy);
set->match = match;
return;
}
int set_insert(Set *set, const void *data)
{
/// 不允许插入已存在元素
if (set_is_member(set, data)) return 1;
/// 插入数据
return list_ins_next(set, list_tail(set), data);
}
int set_remove(Set *set, void **data)
{
ListElmt *member, *prev;
/// 查找待移除的元素
prev = NULL;
for (member = list_head(set); member != NULL; member = list_next(member)) {
if (set->match(*data, list_data(member))) break;
prev = member;
}
/// 找不到则返回 -1
if (member == NULL) return -1;
/// 移除成员
return list_rem_next(set, prev, data);
}
int set_union(Set *setu, const Set *set1, const Set *set2)
{
ListElmt *member;
void *data;
/// 初始化新集合
set_init(setu, set1->match, NULL);
/// 插入第一个集合的数据
for (member = list_head(set1); member != NULL; member = list_next(member)) {
data = list_data(member);
if (list_ins_next(setu, list_tail(setu), data) != 0) {
set_destroy(setu);
return -1;
}
}
/// 插入第二个集合的数据
for (member = list_head(set2); member != NULL; member = list_next(member)) {
if (set_is_member(set1, list_data(member))) {
/// 不插入 set1 存在的元素
continue;
} else {
data = list_data(member);
if (list_ins_next(setu, list_tail(setu), data) != 0) {
set_destroy(setu);
return -1;
}
}
}
return 0;
}
int set_intersection(Set *seti, const Set *set1, const Set *set2)
{
ListElmt *member;
void *data;
/// 初始化新集合
set_init(seti, set1->match, NULL);
/// 将两个集合都插入到集合中
for (member = list_head(set1); member != NULL; member = list_next(member)) {
if (set_is_member(set2, list_data(member))) {
data = list_data(member);
if (list_ins_next(seti, list_tail(seti), data) != 0) {
set_destroy(seti);
return -1;
}
}
}
return 0;
}
int set_difference(Set *setd, const Set *set1, const Set *set2)
{
ListElmt *member;
void *data;
/// 初始化新集合
set_init(setd, set1->match, NULL);
/// 将在 set1 但是不在 set2 中的元素插入集合
for (member = list_head(set1); member != NULL; member = list_next(member)) {
if (!set_is_member(set2, list_data(member))) {
data = list_data(member);
if (list_ins_next(setd, list_tail(setd), data) != 0) {
set_destroy(setd);
return -1;
}
}
}
return 0;
}
int set_is_member(const Set *set, const void *data)
{
ListElmt *member;
/// 判断元素是否在集合内
for (member = list_head(set); member != NULL; member = list_next(member)) {
if (set->match(data, list_data(member))) return 1;
}
return 0;
}
int set_is_subset(const Set *set1, const Set *set2)
{
ListElmt *member;
/// 快速判断,先判断集合大小
if (set_size(set1) > set_size(set2)) return 0;
/// 判断 set1 元素是否在 set2 中
for (member = list_head(set1); member != NULL; member = list_next(member)) {
if (!set_is_member(set2, list_data(member))) return 0;
}
return 1;
}
int set_is_equal(const Set *set1, const Set *set2)
{
/// 快速判断,先判断集合大小
if (set_size(set1) != set_size(set2)) return 0;
/// 如果集合大小相等,那么子集就是本身
return set_is_subset(set1, set2);
}
| 3 | 3 |
2024-11-18T19:02:45.577060+00:00
| 2017-01-12T15:24:56 |
916c909a57faf93017589fc72095f2e1f06a7e67
|
{
"blob_id": "916c909a57faf93017589fc72095f2e1f06a7e67",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-12T15:24:56",
"content_id": "a3d45f44fd317d8941b335d58753aa0465653121",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "78067abbd5f6bdc862a186379d9aae30bca83704",
"extension": "c",
"filename": "utils.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 157692820,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3003,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/prog/zpp/utils.c",
"provenance": "stackv2-0058.json.gz:161265",
"repo_name": "cocoppang/SecureKeeper",
"revision_date": "2017-01-12T15:24:56",
"revision_id": "845e811bab0782494d8d70f21056b311c3451064",
"snapshot_id": "6e74494a530719560caaa12c6511b4319fc76d93",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/cocoppang/SecureKeeper/845e811bab0782494d8d70f21056b311c3451064/prog/zpp/utils.c",
"visit_date": "2020-04-06T18:17:34.699966"
}
|
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.
*
* Authors: Stefan Brenner, Colin Wulf
*/
#include <stdint.h>
#include <stddef.h>
#include "utils.h"
#include "Enclave.h"
/**
* This functions prints a given char array of a certain length as bytes
* */
void hexdump_p(package_t * p_package) {
hexdump("hexdump_p", p_package->buffer, p_package->size);
}
void hexdump(const char *desc, void *addr, int len) {
int i;
unsigned char buff[17];
unsigned char *pc = (unsigned char*) addr;
// Output description if given.
if (desc != NULL)
printf("%s:\n", desc);
// Process every byte in the data.
for (i = 0; i < len; i++) {
// Multiple of 16 means new line (with line offset).
if ((i % 16) == 0) {
// Just don't print ASCII for the zeroth line.
if (i != 0)
printf(" %s\n", buff);
// Output the offset.
printf(" %04x ", i);
}
// Now the hex code for the specific character.
printf(" %02x", pc[i]);
// And store a printable ASCII character for later.
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
buff[i % 16] = '.';
else
buff[i % 16] = pc[i];
buff[(i % 16) + 1] = '\0';
}
// Pad out last line if not exactly 16 characters.
while ((i % 16) != 0) {
printf(" ");
i++;
}
// And print the final ASCII bit.
printf(" %s\n", buff);
}
void hexdump_clean(const char *desc, void *addr, int len) {
int i;
unsigned char buff[17];
unsigned char *pc = (unsigned char*) addr;
// Output description if given.
if (desc != NULL)
printf("%s:\n", desc);
// Process every byte in the data.
for (i = 0; i < len; i++) {
// Multiple of 16 means new line (with line offset).
if ((i % 16) == 0) {
// Just don't print ASCII for the zeroth line.
// if (i != 0)
// printf(" %s\n", buff);
// Output the offset.
// printf(" %04x ", i);
}
// Now the hex code for the specific character.
printf("%02x", pc[i]);
// And store a printable ASCII character for later.
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
buff[i % 16] = '.';
else
buff[i % 16] = pc[i];
buff[(i % 16) + 1] = '\0';
}
// Pad out last line if not exactly 16 characters.
while ((i % 16) != 0) {
printf(" ");
i++;
}
// And print the final ASCII bit.
// printf(" %s\n", buff);
printf("\n");
}
| 2.796875 | 3 |
2024-11-18T19:02:47.480932+00:00
| 2021-06-11T15:43:08 |
19507e50f4872b151c6cd5206500709d950f9358
|
{
"blob_id": "19507e50f4872b151c6cd5206500709d950f9358",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-11T15:43:08",
"content_id": "106b960d592323780c0d597992313d17ee2adc31",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "14fd126ff68624b66daf64fc251a633244593ab1",
"extension": "c",
"filename": "planck_interface.c",
"fork_events_count": 1,
"gha_created_at": "2020-07-09T11:38:12",
"gha_event_created_at": "2021-06-11T15:43:09",
"gha_language": "Fortran",
"gha_license_id": "BSD-2-Clause",
"github_id": 278347824,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10359,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/cosmosis-standard-library/likelihood/planck2015/planck_interface.c",
"provenance": "stackv2-0058.json.gz:162036",
"repo_name": "ktanidis/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"revision_date": "2021-06-11T15:43:08",
"revision_id": "ce195564631b148bef0214a27a57470640c69a08",
"snapshot_id": "6749d1dec87b3f070f9d255b602d32260341f478",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ktanidis/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra/ce195564631b148bef0214a27a57470640c69a08/cosmosis-standard-library/likelihood/planck2015/planck_interface.c",
"visit_date": "2023-05-15T09:11:32.086202"
}
|
stackv2
|
#include "clik.h"
#include "cosmosis/datablock/c_datablock.h"
#include <math.h>
// Hard-coded maximum number of likelihoods.
// This is far more than have been released.
// I'm just doing this to avoid some mallocs and stuff.
#define MAX_NUMBER_LIKES 128
typedef struct configuration_data{
int ndata, nlensing;
clik_object * clik_data[MAX_NUMBER_LIKES];
clik_lensing_object * clik_lensing_data[MAX_NUMBER_LIKES];
} configuration_data;
typedef enum {clik_type_standard, clik_type_lensing} clik_type;
static
int read_requested_files(configuration_data * config, c_datablock * options, clik_type mode){
int status = 0;
char param[512];
error * err = initError();
char * prefix;
switch (mode) {
case clik_type_standard:
prefix = "data";
break;
case clik_type_lensing:
prefix = "lensing";
break;
default:
fprintf(stderr, "Unknown type of clik file - this is a coding error, please report it.\n");
exit(1);
break;
}
int n=0;
while (1){
if (n==127){
fprintf(stderr, "Somehow you have reached the hard-coded maximum number of clik files supported by cosmosis: %d.", MAX_NUMBER_LIKES);
fprintf(stderr, "Probably you are just messing about trying to break things. Well done, then.\n");
fprintf(stderr, "If not (somehow) you will need to modify MAX_NUMBER_LIKES in cosmosis-stadard-library/likelihood/planck2014/planck_interface.c\n");
exit(1);
}
snprintf(param, 128, "%s_%d", prefix, n+1);
char * value;
status |= c_datablock_get_string_default(options, OPTION_SECTION,
param, "", &value);
if (strlen(value)==0) break;
printf("Looking for clik Planck likelihood file %d: %s\n",
n+1, value);
switch (mode) {
case clik_type_standard:
config->clik_data[n] = clik_init(value, &err);
break;
case clik_type_lensing:
config->clik_lensing_data[n] = clik_lensing_init(value, &err);
break;
default:
fprintf(stderr, "Unknown type of clik file - this is a coding error, please report it.\n");
exit(1);
break;
}
n++;
if (isError(err)){
fprintf(stderr,"There was an error initializating one of the Planck likelihoods.\n");
fprintf(stderr,"Here is the error message:\n");
printError(stderr,err);
fprintf(stderr,"\nIf it mentions \"stat\" then this probably means that a likelihood file was not found.\n\n");
fprintf(stderr,"If you are running demo two or demo four then it just means that you\n");
fprintf(stderr,"did not download the Planck likelihood when installing.\n");
fprintf(stderr,"You can either get it manually from:\n");
fprintf(stderr," http://pla.esac.esa.int/pla/aio/planckProducts.html\n");
fprintf(stderr,"and edit demos/demo2.ini, or just skip demos two and four for now.\n\n");
exit(1);
}
}
endError(&err);
return n;
}
configuration_data * setup(c_datablock * options){
configuration_data * config = malloc(sizeof(configuration_data));
int status = 0;
config->ndata=read_requested_files(config, options, clik_type_standard);
config->nlensing=read_requested_files(config, options, clik_type_lensing);
if (config->ndata==0 + config->nlensing){
fprintf(stderr, "No data files were specified for Planck at all!\n");
fprintf(stderr, "In the options file (not the values.ini file) you need to set in the section for Planck at least the first of:\n");
fprintf(stderr, " data_1 = ...\n");
fprintf(stderr, " data_2 = ...\n");
fprintf(stderr, " data_3 = ...\n");
fprintf(stderr, " data_4 = ...\n");
fprintf(stderr, " etc. and/or\n");
fprintf(stderr, " lensing_1 = ...\n");
fprintf(stderr, " lensing_2 = ...\n");
fprintf(stderr, " etc.\n");
fprintf(stderr, "The Planck data files can be downloaded from:\n");
fprintf(stderr, "http://pla.esac.esa.int/pla/aio/planckProducts.html\n");
fprintf(stderr, "or some are packaged with the planck2015 cosmosis module.\n");
exit(1);
}
return config;
}
static
int extract_c_ell(c_datablock * block, int n_cl,
char * package_names[n_cl], int lmax_by_type[n_cl], int n_nuisance,
parname nuisance_names[n_nuisance], double *p, double *cl)
{
int i;
int status=0;
for (i=0;i<n_cl;i++) {
// Check lmax for this spectrum. If not needed, continue
int lmax = lmax_by_type[i];
if (lmax<=0) continue;
// Otherwise fill in first the trivial cl and then the rest, loaded fromt the package
cl[0]=0.0;
cl[1]=0.0;
int nread=0;
double * ell_squared_cl = NULL;
status |= c_datablock_get_double_array_1d(block, CMB_CL_SECTION, package_names[i],
&ell_squared_cl, &nread);
if (status){
fprintf(stderr, "Could not get C_ell values for %s (status=%d)\n",
package_names[i],status);
status = 1;
return status;
}
if (nread<lmax-1){
fprintf(stderr, "Could not get enough C_ell values for %s (read lmax=%d but needed lmax=%d). May need to adjust lmax.\n",
package_names[i], nread+1, lmax_by_type[i]);
status = 1;
return status;
}
// Transform to raw cl from l**2 cl
int ell;
for (ell=2; ell<=lmax; ell++) {
cl[ell] = ell_squared_cl[ell-2] / (ell*(ell+1.0)/2.0/M_PI);
}
free(ell_squared_cl);
// Move the spectrum pointer forward ready for the next spectrum (e.g. TT->EE)
cl+=lmax+1;
}
// ... and now get the nuisance parameters
for (i=0; i<n_nuisance; i++){
int this_status=c_datablock_get_double(block, PLANCK_SECTION, nuisance_names[i], cl+i ); //ok
// Report any missing parameters
if (this_status) fprintf(stderr, "Could not get required Planck parameter %s in section %s\n",nuisance_names[i], PLANCK_SECTION);
status |= this_status;
}
return status;
}
static
int run_clik_cosmosis(c_datablock * block, clik_object * like_obj, double * output_like)
{
int i;
const int N_CL = 6;
int param_count=0;
int status = 0;
char * package_names[] = {"TT","EE","BB","TE","TB","EB"};
int lmax_by_type[N_CL];
// Planck internal error system
error * err = initError();
// Get the lmax values for the different spectra and sum them
clik_get_lmax(like_obj, lmax_by_type,&err);
for (i=0;i<N_CL;i++) if (lmax_by_type[i]>0) param_count += lmax_by_type[i]+1;
// Check for any errors from the Planck library
if (isError(err)){
fprintf(stderr,"There was an error getting lmax from a Planck likelihood.\n");
endError(&err);
return 1;
}
// Get the number and names of extra parameters and add to total
int n_nuisance;
parname * nuisance_names;
n_nuisance = clik_get_extra_parameter_names(like_obj, &nuisance_names, &err);
param_count += n_nuisance;
// Check for any errors from the Planck library
if (isError(err)){
fprintf(stderr,"There was an error getting nuisance params from a Planck likelihood.\n");
endError(&err);
return 2;
}
// p is the overall space and cl is the space within it for each spectra.
double * p = malloc(sizeof(double)*param_count);
double * cl = p;
// Get the c_ell we need, and the nuisance parameters (if any)
status |= extract_c_ell(block, N_CL, package_names, lmax_by_type, n_nuisance,
nuisance_names, p,cl);
free(nuisance_names);
// Check for any errors reading things in
if (status){
free(p);
return status;
}
// Compute the actual likelihood
double like = clik_compute(like_obj, p, &err);
free(p);
// ... and check for errors
if (isError(err)){
status = 1;
fprintf(stderr,"Planck likelihood error\n");
}
// Clean up Planck error system and
// return required outputs
endError(&err);
*output_like = like;
return 0;
}
static
int run_clik_cosmosis_lensing(c_datablock * block, clik_object * like_obj, double * output_like)
{
int i;
const int N_CL=7;
int param_count=0;
int status = 0;
char * package_names[] = {"PP","TT","EE","BB","TE", "TB", "EB"};
error * err = initError();
int lmax_by_type[N_CL];
// Get the lmax values for the different spectra and sum them
clik_lensing_get_lmaxs(like_obj, lmax_by_type,&err);
for (i=0;i<N_CL;i++) if (lmax_by_type[i]>0) param_count += lmax_by_type[i]+1;
// Check for any errors from the Planck library
if (isError(err)){
fprintf(stderr,"There was an error getting lmax from a Planck lensing likelihood:\n");
printError(stderr,err);
return 1;
}
// Get the number and names of extra parameters and add to total
int n_nuisance;
parname * nuisance_names;
n_nuisance = clik_lensing_get_extra_parameter_names(like_obj, &nuisance_names, &err);
param_count += n_nuisance;
// Check for any errors from the Planck library
if (isError(err)){
fprintf(stderr,"There was an error getting nuisance params from a Planck lensing likelihood.\n");
printError(stderr,err);
return 2;
}
// p is the overall space and cl is the space within it for each spectra.
double * p = malloc(sizeof(double)*param_count);
double * cl = p;
// Get the c_ell we need, and the nuisance parameters (if any)
status |= extract_c_ell(block, N_CL, package_names, lmax_by_type, n_nuisance,
nuisance_names, p,cl);
free(nuisance_names);
// Check for any errors reading things in and quit early if problem
if (status){
free(p);
return status;
}
// Compute the actual likelihood and check for errors
double like = clik_lensing_compute(like_obj, p, &err);
free(p);
//Clean up
if (isError(err)){
status = 1;
fprintf(stderr, "Error running Planck lensing\n");
}
// Clean up Planck error system and
// return required outputs
endError(&err);
*output_like = like;
return 0;
return 0;
}
int execute(c_datablock * block, configuration_data * config){
double like = 0.0;
int status = 0;
for (int i=0; i<config->ndata; i++){
// Compute the likelihood for this file.
double like_i = 0.0;
status |= run_clik_cosmosis(block, config->clik_data[i], &like_i);
//
char name[64];
snprintf(name, 64, "PLANCK_LIKE_%d", i+1);
status |= c_datablock_put_double(block, LIKELIHOODS_SECTION, name, like_i);
like += like_i;
}
for (int i=0; i<config->nlensing; i++){
// Compute the likelihood for this file.
double like_i = 0.0;
status = run_clik_cosmosis_lensing(block, config->clik_lensing_data[i], &like_i);
//
char name[64];
snprintf(name, 64, "PLANCK_LENSING_LIKE_%d", i+1);
status |= c_datablock_put_double(block, LIKELIHOODS_SECTION, name, like_i);
like += like_i;
}
if (status) return status;
// Save the total likelihood
status |= c_datablock_put_double(block, LIKELIHOODS_SECTION, "PLANCK2015_LIKE", like);
return 0;
}
| 2.4375 | 2 |
2024-11-18T19:02:47.655699+00:00
| 2020-05-03T20:14:05 |
71891ba62caa190cf9429e21c0cbe4559efd51be
|
{
"blob_id": "71891ba62caa190cf9429e21c0cbe4559efd51be",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-03T20:14:05",
"content_id": "51aa71b110d3c24469d0728b7c49b534a00b6b2a",
"detected_licenses": [
"MIT"
],
"directory_id": "02f67bb03c7f52d495eb16b8ae4e224b032c76f8",
"extension": "h",
"filename": "Array.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 253516625,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1513,
"license": "MIT",
"license_type": "permissive",
"path": "/include/Array.h",
"provenance": "stackv2-0058.json.gz:162165",
"repo_name": "qawse3dr/cstringlib",
"revision_date": "2020-05-03T20:14:05",
"revision_id": "61ff53dc890918d54e973b8e991d0a05f8bf425b",
"snapshot_id": "3c79b7b816dde572020ead812f03569cc7787f46",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qawse3dr/cstringlib/61ff53dc890918d54e973b8e991d0a05f8bf425b/include/Array.h",
"visit_date": "2021-05-24T10:22:33.766352"
}
|
stackv2
|
/*
*Lawrence Milne
*1049930
*March 26th 2020
*Assignment 4
*/
/**dynamic Array api used to hold void*
*/
#ifndef ARRAY_H
#define ARRAY_H
typedef struct Array_Struct{
void** data;
int length;
void (*delete)(void*);
}Array;
/**mallocs an array structure
*@return a pointer to an array structure*/
Array* createArray(void (*delete)(void*));
/**frees the array structure
*@param Array the array to be freed
*/
void freeArray(Array* array);
/**pushes values on the the array stack
*@param array the array the the value is being appened too
*@param data the data being pushed on*/
void arrayPush(Array* array, void* data);
/**gets a value from index i
*@param Array the array the index is being accessed from
*@param i the index the element is in
*@return the value at the index NULL if it is out of bounds
*/
void* arrayGet(Array* array,int i);
/**finds if a value is inside of an array
*@param array the array being checked
*@param key the key being searched for
*@param compar a function that compars 2 functions
*@return returns 1 if contains 0 if it doesnt
*/
int arrayContains(Array* array,void* key, int(*compar)(void*,void*));
/**generic free function that just deletes the pointer itself*/
void genericFree(void*);
/**a function that doesnt do anything for freeing data*/
void emptyFree(void*);
/**uses qsort to sort the array
*@param array to be sorted
*@param compar used to compar values in the array*/
void arrayQsort(Array* array,int(*compar)(void*,void*));
#endif
| 2.796875 | 3 |
2024-11-18T19:02:49.751449+00:00
| 2020-07-04T09:36:15 |
2f2e6cc3d0319b8d87773bbd0063a67bfc9824c0
|
{
"blob_id": "2f2e6cc3d0319b8d87773bbd0063a67bfc9824c0",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-04T09:36:15",
"content_id": "d73b34911087997f664f91c8ea42d8b4cf9e332d",
"detected_licenses": [
"MIT"
],
"directory_id": "64cc66dd91635f18296b762c95806230fc0ef204",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-20T04:51:05",
"gha_event_created_at": "2020-06-28T17:20:02",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 273640430,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10316,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0058.json.gz:163064",
"repo_name": "erikoui/Genetic_Architect",
"revision_date": "2020-07-04T09:36:15",
"revision_id": "f03fcc089c5c397b0c95bbcc9fc632eb6a602591",
"snapshot_id": "4e917b3e156e1193b473dc1045797d64ee81e18d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/erikoui/Genetic_Architect/f03fcc089c5c397b0c95bbcc9fc632eb6a602591/main.c",
"visit_date": "2022-11-13T01:24:53.137875"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
//TODO: fix segfault lmao good luck with all those pointers
#define MUTATIONS_PER_10K 500
#define MAX_MUTATIONS 1
#define POPULATION_SIZE 1000
#define GENOME_SIZE 10
#define MAX_GENERATIONS 1000
#define NUM_PARENTS 10
#define ZERO_CHANCE 0.0001
#define ROOM_TYPE_CHANGES 0
const char USE_OPTS[]={'B','M','K','S','L','C','U','O','W','T'};
#define USE_OPTS_SIZE 10
const char B_DIR_OPTS[]={'N','W','S','E'};
#define B_DIR_OPTS_SIZE 4
const char R_DIR_OPTS[]={'R','L'};
#define R_DIR_OPTS_SIZE 2
const int ENSUITE_OPTS_MAX=3;
//This array sets the types of rooms you want to have (e.g 2 bdr with kitchen and 2 wc)
const char CFG_TYPES[]={'B','B','K','W','T','T','M','L','C','C'};
//This one sets if you want ensuite (0) or not (1)
const char CFG_ENSUITE[]={1,1,1,1,0,3,1,3,3};
struct gene{
/****************************************
Variable [use] contains the type of room.
[use] can be:
B: Bedroom
M: Master Bedroom
K: Kitchen
S: Store
L: Living Room
C: Covered Veranda
U: Uncovered Veranda
O: Other or Extra room
W: Walkway
T: Bathroom
Remember to change USE_OPTS if you add another room type
*****************************************/
char use;
/****************************************
Variables [b_dir,r_dir] contains the Bearing and Rotational direction of
the room relative to room [rel]. Rotational direction means left or right
side of [rel], seen as if standing in the center of that room.
[b_dir] can be:
N: north (up)
W: west (left)
S: south (down)
E: east (right)
[r_dir] can be:
L: left
R: right
Remember to change R_DIR_OPTS and B_DIR_OPTS if you add another direction (???)
*****************************************/
char b_dir,r_dir;
/****************************************
Variable [rel] contains the room index that the current room postion is
based on.
*****************************************/
int rel;
double width,height;
/****************************************
Variable [ensuite] defines a bathroom or store if it needs to be connected
to a bedroom or kitchen.
[ensuite] can be:
0: MUST connect
1: MUST NOT connect
2: PREFER connect
3: dont care if connected or not
*****************************************/
//TODO: Verandas must be hardcoded to connect to anything except walkways
int ensuite;
};
/*Converts a genome to a int array for easier working.
This imposes a significant overhead in exchange for codeability.
I might rewrite the whole thing in c++ in the future where i can use a
vector of objects je kani.
*/
void genome_to_int_arr(gene* g, unsigned long long* s){
int i;
for(i=0;i<GENOME_SIZE;i++){
s[i]= 10000000000000*g[i]->use;//2 digits
s[i]+= 10000000000*g[i]->b_dir;//2
s[i]+= 100000000*g[i]->r_dir;//2
s[i]+= 1000000*g[i]->rel;//2
s[i]+= 10000*floor(g[i]->width*100);//3
s[i]+= 1000*floor(g[i]->height*100)//3
s[i]+= g[i]->ensuite;//1
printf("gene %d: %llu",i,s[i]);
}
}
void random_shuffle(int* l,int size){
int i,r1,r2,t;
for(i=0;i<GENOME_SIZE*2;i++){
r1=rand()%size;
r2=rand()%size;
t=l[r1];
l[r1]=l[r2];
l[r2]=t;
}
}
void random_shuffle_gene(struct gene* l,int size){
int i,r1,r2;
struct gene t;
for(i=0;i<GENOME_SIZE*2;i++){
r1=rand()%size;
r2=rand()%size;
t=l[r1];
l[r1]=l[r2];
l[r2]=t;
}
}
double normdist(double m,double s){
double r=(double)(rand()%10000)/10000;
return 1/(s*sqrt(3.283))*exp(-0.5*((r-m)/s)*((r-m)/s));
}
//This is the score function
double score(const struct gene* s){
//Bedroom area increases score up to a point
//Room aspect ratio increases score as it reaches a constant (propose 1.1)
//Walkway area decreases score
//more MORE MOOOOOOOOOOARRRRRRRRRRRR
return 1;
}
double random_dim(char use){
double w;
const double BEDROOM_MEAN=3.0;
const double BEDROOM_STD=0.5;
const double MASTER_BEDROOM_MEAN=3.7;//ooh racist word
const double MASTER_BEDROOM_STD=0.5;
const double KITCHEN_MEAN=3.0;
const double KITCHEN_STD=0.8;
const double STORE_MEAN=2.0;
const double STORE_STD=0.5;
const double LIVING_ROOM_MEAN=4.5;
const double LIVING_ROOM_STD=1;
const double VERANDA_MEAN=5.0;
const double VERANDA_STD=3;
const double BATHROOM_MEAN=1.8;
const double BATHROOM_STD=0.2;
const double WALKWAY_MEAN=3.0;
const double WALKWAY_STD=1;
switch(use){
case 'B':
return normdist(BEDROOM_MEAN,BEDROOM_STD);
break;
case 'M':
return normdist(MASTER_BEDROOM_MEAN,MASTER_BEDROOM_STD);
break;
case 'K':
return normdist(KITCHEN_MEAN,KITCHEN_STD);
break;
case 'S':
return normdist(STORE_MEAN,STORE_STD);
break;
case 'L':
return normdist(LIVING_ROOM_MEAN,LIVING_ROOM_STD);
break;
case 'C':
case 'U':
return normdist(VERANDA_MEAN,VERANDA_STD);
break;
case 'O':
return normdist(STORE_MEAN,STORE_STD);
break;
case 'T':
return normdist(BATHROOM_MEAN,BATHROOM_STD);
break;
case 'W':
return normdist(WALKWAY_MEAN,WALKWAY_STD);
break;
default:
printf("BAD ROOM USE PLS FIX AAAAAA\n");
exit(0);
break;
}
return 100;
}
void randomize_gene(struct gene* g){
//genes are essentially room definitions.
if(ROOM_TYPE_CHANGES){
g->use=USE_OPTS[rand()%(USE_OPTS_SIZE)];
}
g->b_dir=B_DIR_OPTS[rand()%(B_DIR_OPTS_SIZE)];
g->r_dir=R_DIR_OPTS[rand()%(R_DIR_OPTS_SIZE)];
g->rel=rand()%GENOME_SIZE;
g->width=random_dim(g->use);
g->height=random_dim(g->use);
}
//mutates a random gene to another (' '-'z')
void mutate(struct gene** p){
int n,m,j,i;
n=rand()%POPULATION_SIZE*MUTATIONS_PER_10K/10000;//how many genomes to mutate
for(i=0;i<n;i++){
m=rand()%MAX_MUTATIONS+1;//how many genes to mutate
for(j=0;j<m;j++){
randomize_gene(&p[i][rand()%GENOME_SIZE]);
}
}
}
//generates a population
void init(struct gene*** p){
int i,j;
for(i=0;i<POPULATION_SIZE;i++){
for(j=0;j<GENOME_SIZE;j++){//this loop is the generator function
p[i][j]->use=CFG_TYPES[j];
p[i][j]->ensuite=CFG_ENSUITE[j];
randomize_gene(*p[i]);
}
random_shuffle_gene(*p[i],GENOME_SIZE);
}
}
void print_genome(struct gene** g){
int i;
for(i=0;i<GENOME_SIZE;i++){
printf("%c%c%c %2d %.2f %.2f %d",g[i]->use,
g[i]->b_dir,
g[i]->r_dir,
g[i]->rel,
g[i]->width,
g[i]->height,
g[i]->ensuite);
}
}
//prints n genomes randomly sampled from p
void print_sample(struct gene*** p,int n){
int index;
printf("Sample Genes:\n");
for(;n>=0;n--){
index=rand()%POPULATION_SIZE;
printf("%6d: ",index);
print_genome(p[index]);
printf(" (%.3f)\n",score(*p[index]));
}
}
// Fills s with the score of each genome and returns the sum of all scores.
int generate_score_array(struct gene*** p,double* s){
int i;
double sum=0;//total score
double max=0;//best genome score
int maxi;//index of max
for(i=0;i<POPULATION_SIZE;i++){
s[i]=score(*p[i]);
sum+=s[i];
if(s[i]>max){
max=s[i];
maxi=i;
}
}
printf("Best Genome\n%6d: ",maxi);
print_genome(p[maxi]);
printf(" (%.3f)\n",max);
return sum;
}
// Chooses an index of population randomly with more chance the higher its score
int choose_parent(double* s,double tot){
int i,k;
double r,p;
do{
k=rand()%POPULATION_SIZE;
r=(double)(rand()%100000)/100000;
p=s[k]/tot+ZERO_CHANCE;
}
while(r>p);
//printf("Chose parent %d with score %.5f (r=%.5f,p=%.5f)\n",k,s[k],r,p);
return k;
}
void crossover(struct gene*** p,struct gene*** new_population,int* unique_randoms,double* s,double tot){
int i,j,parent_index,c;
int start=0;
int end;
//printf("Started Crossover.\n");
for(i=0;i<POPULATION_SIZE;i++){//for each genome
random_shuffle(unique_randoms,GENOME_SIZE);//make a list of unique randoms from 0 to GENOME_SIZE-1
for(j=1;j<=NUM_PARENTS;j++){//for each parent
parent_index=choose_parent(s,tot);
end=start+GENOME_SIZE/NUM_PARENTS-1;
for(c=start;c<end;c++){
new_population[i][unique_randoms[c]]=p[parent_index][unique_randoms[c]];
}
start=end;
}
//keep going on the last parent until you make a full genome
for(c=start;c<GENOME_SIZE;c++){
new_population[i][unique_randoms[c]]=p[parent_index][unique_randoms[c]];
}
start=0;
p[i][GENOME_SIZE]='\0';
}
//move new population to the old one
for(i=0;i<POPULATION_SIZE;i++){
p[i]=new_population[i];
}
}
int main(){
time_t t;
srand((unsigned) time(NULL));
double total_score;
int i;
printf("Allocating memory...");
fflush(stdout);
struct gene** population;
population=( struct gene**)malloc(POPULATION_SIZE*sizeof( struct gene*));
for(i=0;i<POPULATION_SIZE;i++){
population[i]=( struct gene*)malloc(GENOME_SIZE*sizeof( struct gene));
}
struct gene** new_population;
new_population=( struct gene**)malloc(POPULATION_SIZE*sizeof( struct gene*));
for(i=0;i<POPULATION_SIZE;i++){
new_population[i]=( struct gene*)malloc(GENOME_SIZE*sizeof( struct gene));
}
int* unique_randoms;
unique_randoms=(int*)malloc(GENOME_SIZE*sizeof(int));
for(i=0;i<GENOME_SIZE;i++){
unique_randoms[i]=i;
}
double* scores;
scores=(double*)malloc(POPULATION_SIZE*sizeof(double));
printf("Allocated.\n");
print_sample(&population,9);
//initialization
init(&population);
//print_sample(population,10);
printf("intialized %d genomes. Genome size: %d\n",(int)POPULATION_SIZE,(int)GENOME_SIZE);
printf("Generation 0 preview:\n");
print_sample(&population,9);
//loop over generations
for(i=0;i<MAX_GENERATIONS;i++){
total_score=generate_score_array(&population,scores);
crossover(&population,&new_population,unique_randoms,scores,total_score);
if(i%1==0){
printf("Gen %d: %.3f average\n",i,total_score/POPULATION_SIZE);
//printf("Generation %5d preview:\n",i);
//print_sample(population,9);
}
mutate(population);
}
return 0;
}
| 2.28125 | 2 |
2024-11-18T19:02:49.881685+00:00
| 2020-12-11T03:29:02 |
42839553d9b534bb91d21ec5bdba2830b8a37d24
|
{
"blob_id": "42839553d9b534bb91d21ec5bdba2830b8a37d24",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-11T03:29:02",
"content_id": "6adcb6b9975099f2e2df4c87cb1d4220ff07a88c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "32c1a7c2cbed043362dea6268a44cd7474274a6e",
"extension": "c",
"filename": "span_CRCW_cas.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": 2383,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/span_CRCW_cas.c",
"provenance": "stackv2-0058.json.gz:163195",
"repo_name": "Bader-Research/biconnected-components",
"revision_date": "2020-12-11T03:29:02",
"revision_id": "37e1f95497b083a5dc05dd6b3423b9048b520133",
"snapshot_id": "d1c3a00a8439506fcaaa38e061a7b66d8b9153f5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Bader-Research/biconnected-components/37e1f95497b083a5dc05dd6b3423b9048b520133/span_CRCW_cas.c",
"visit_date": "2023-01-29T21:49:25.624180"
}
|
stackv2
|
#include "simple.h"
#include "graph.h"
#define DEBUG_CORRECTNESS 1
extern inline int CASW(int * a, int e, int n);
int spanning_tree_CRCW_cas(V* graph,E* El, int nVertices,int n_edges,THREADED)
{
int *p_changed,*buffer,*D,*assign,*done,changed,i,j,n,iter_count=0;
V * tree;
E *El_tmp;
#if DEBUG_TIMING
hrtime_t start,end;
double interval1=0,interval2=0,interval3=0;
#endif
#if DEBUG_CORRECTNESS
int edge_count=0;
#endif
p_changed=node_malloc(sizeof(int),TH);
on_one_thread (*p_changed)=1;
buffer=node_malloc(sizeof(int)*nVertices,TH);
D=node_malloc(sizeof(int)*nVertices,TH); /*used for Di*/
assign=node_malloc(sizeof(int)*nVertices,TH); /*used to check which processor should do this*/
done=node_malloc(sizeof(int)*nVertices,TH);
pardo(i,0,nVertices,1) /*initialize the D values, Jaja p217*/
{
done[i]=0;
graph[i].v_attribute=i;
D[i]=i;
}
node_Barrier();
while((*p_changed)==1)
{
iter_count++;
node_Barrier();
/*1. phase one*/
on_one_thread (*p_changed)=0;
changed=0;
node_Barrier();
pardo(n,0,n_edges,1)
{
if(El[n].workspace==1) continue;
i=El[n].v1;
j=El[n].v2;
if(D[j]<D[i] && D[i]==D[D[i]] && CASW(&done[D[i]],0,MYTHREAD+1)==0)
{
changed=1;
El[n].workspace=1;
D[D[i]]=D[j];
#if DEBUG_CORRECTNESS
edge_count++;
#endif
}
}
if(changed) (*p_changed)=1;
node_Barrier();
/*3.phase 3*/
pardo(i,0,nVertices,1)
{
while(D[i]!=D[D[i]]) D[i]=D[D[i]];
}
node_Barrier();
/*phase 4: shrink the edge list to reduce the size*/
#if 0
if(iter_count%2==0){
El_tmp=shrink_edgeL(El, &n_edges,D,TH);
node_free(El,TH);
El=El_tmp;
}
#endif
} /*while*/
#if DEBUG_CORRECTNESS
node_Barrier();
pardo(i,0,nVertices,1)
{
#if 0
if(graph[i].v_attribute!=graph[0].v_attribute) {
printf("ERROR in SPANNING TREE\n");
break;
}
#endif
if(D[i]!=D[0] ){
printf("ERROR in SPANNING TREE\n");
break;
}
}
#endif
printf("number of iterations:%d\n",iter_count);
#if DEBUG_CORRECTNESS
edge_count = node_Reduce_i(edge_count,SUM,TH);
on_one printf("Total edges got is %d\n",edge_count);
#endif
node_free(p_changed,TH);
node_free(buffer, TH);
node_free(D, TH);
node_free(assign, TH);
node_free(done, TH);
}
| 2.359375 | 2 |
2024-11-18T19:02:50.067495+00:00
| 2016-02-01T00:49:52 |
825b8c0d8582bf13abd3a60b1a98fee4af69e922
|
{
"blob_id": "825b8c0d8582bf13abd3a60b1a98fee4af69e922",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-01T00:49:52",
"content_id": "22a5181c316f6b6a5d831fe97aabac7987b8a55f",
"detected_licenses": [
"MIT"
],
"directory_id": "039f07655ac9b8385f4431d6eb701bce5f0c4d60",
"extension": "c",
"filename": "servidor.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44362834,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5358,
"license": "MIT",
"license_type": "permissive",
"path": "/request-procedure-call/servidor.c",
"provenance": "stackv2-0058.json.gz:163323",
"repo_name": "cassiopagnoncelli/networks-utils",
"revision_date": "2016-02-01T00:49:52",
"revision_id": "f5d0a0dec0b4747e75e0805a0b612e55fbade1c3",
"snapshot_id": "75f5f0cf7a952618c15a3de892d0b28af248165f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cassiopagnoncelli/networks-utils/f5d0a0dec0b4747e75e0805a0b612e55fbade1c3/request-procedure-call/servidor.c",
"visit_date": "2021-01-10T13:29:15.981493"
}
|
stackv2
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h> /* bind() */
#include <sys/types.h> /* bind() */
#include <netinet/in.h>
#include <netdb.h>
#include "calc.h"
#include "msg.h"
#include <time.h>
#define TAM_FILA_CONEXOES 5
#define PORTA_TCP_PADRAO 63000
int meu_id;
/* abre uma conexão TCP na `porta' e devolve o socket. */
int sock_cliente(char *nome_servidor, int porta)
{
struct hostent *dns = gethostbyname(nome_servidor);
if (!dns)
return erro("servidor DNS inalcançável.");
struct sockaddr_in endereco_servidor;
bcopy(dns->h_addr, &(endereco_servidor.sin_addr), dns->h_length);
endereco_servidor.sin_family = AF_INET;
endereco_servidor.sin_port = htons(porta);
/* abre o socket. */
int cliente_servidor = socket(AF_INET, SOCK_STREAM, 0);
if (cliente_servidor < 0)
return erro("socket().");
timestamp();
printf("[%d] Tentando conectar com %s em %d\n", meu_id, nome_servidor, porta);
if (connect(cliente_servidor, (struct sockaddr *) &endereco_servidor, sizeof(endereco_servidor)) < 0)
return erro("connect().");
return cliente_servidor;
}
int timestamp()
{
time_t ltime;
struct tm *Tm;
ltime=time(NULL);
Tm=localtime(<ime);
printf("[%d-%d-%d %d:%d:%d] ",
Tm->tm_year+1900,
Tm->tm_mon,
Tm->tm_mday,
Tm->tm_hour,
Tm->tm_min,
Tm->tm_sec);
}
/* imprime na saída padrão a mensagem de erro e devolve falha. */
int erro(const char *str)
{
fprintf(stderr, "** erro: %s\n", str);
return -1;
}
/* encerra `sock'. */
int fecha_socket(int sock)
{
return close(sock);
}
/* abre uma conexão TCP na `porta' e devolve o socket. */
int sock_serv(uint16_t porta)
{
/* tradução DNS para IP */
char host[100];
gethostname(host, 100);
struct hostent *IP;
if ((IP=gethostbyname(host)) == NULL)
return erro("DNS inalcançável.");
/* abre socket */
struct sockaddr_in endereco_local;
endereco_local.sin_port = htons(porta);
endereco_local.sin_family = AF_INET;
memcpy(IP->h_addr, &(endereco_local.sin_addr), IP->h_length);
int socket_conexao = socket(AF_INET, SOCK_STREAM, 0);
if (socket_conexao < 0)
return erro("socket().");
if (bind(socket_conexao, (struct sockaddr *) &endereco_local, sizeof(endereco_local)) < 0)
return erro("bind().");
/* modo passivo; i.e., esse processo é um servidor. */
if (listen(socket_conexao, TAM_FILA_CONEXOES) != 0)
return erro("listen().");
return socket_conexao;
}
int tcp_serv(int num_serv, char *prox_serv)
{
/* abre conexão. */
int fila_sock = sock_serv(PORTA_TCP_PADRAO + meu_id);
if (fila_sock < 0)
return erro("abrir_conexao()");
timestamp();
printf("[%d] Sou o servidor %d e estou ouvindo na porta %d\n", meu_id, meu_id, PORTA_TCP_PADRAO + meu_id);
/* atende os pedidos de conexão na fila. */
int cliente_sock;
socklen_t tam_endereco = (socklen_t) sizeof(struct sockaddr_in);
struct sockaddr_in endereco_cliente;
unsigned char buffer[BUFSIZ];
char *res;
msg *mensagem;
while (1) {
timestamp();
printf("[%d] Estou esperando alguem falar comigo... (Modo de escuta)\n", meu_id);
cliente_sock = accept(fila_sock, (struct sockaddr *) &endereco_cliente, &tam_endereco);
/* cliente atendido. */
if (cliente_sock > 0) {
bzero(buffer, BUFSIZ);
read(cliente_sock, buffer, BUFSIZ);
mensagem = buffer_para_msg(buffer);
if (meu_id == num_serv) {
timestamp();
printf("[%d] Recebi a seguinte expressão: ( %s )\n", meu_id, mensagem->expressao);
res = calc_expr(mensagem->expressao);
timestamp();
printf("[%d] O valor dessa expressão é: ( %s )\n", meu_id, res);
timestamp();
printf("[%d] Resta repassar esse valor até o cliente.\n", meu_id);
write (cliente_sock, msg_para_buffer(nova_expressao(res)), sizeof(msg));
} else {
timestamp();
printf("[%d] Nao sou o ultimo servidor, entao estou repassando a expressão: ( %s )\n", meu_id, mensagem->expressao);
int con_serv = sock_cliente(prox_serv, PORTA_TCP_PADRAO + meu_id + 1);
if (con_serv <= 0)
return erro("abrir_conexao()");
write (con_serv, buffer, sizeof(msg));
bzero(buffer, BUFSIZ);
read(con_serv, buffer, BUFSIZ);
msg *m = buffer_para_msg(buffer);
timestamp();
printf("[%d] Recebi o retorno: ( %s )\n", meu_id, m->expressao);
write (cliente_sock, buffer, sizeof(msg));
fecha_socket (con_serv);
}
fecha_socket (cliente_sock);
} else
erro("accept(), erro possível com &tam_endereco.");
}
/* quem sai por último, apaga a luz. */
return fecha_socket(fila_sock);
}
/* principal. */
int main(int argc, char **argv) {
int num_serv;
char *prox_serv = "localhost";
if (argc != 3 && argc !=4)
return erro(" ./servidor <identificador> <num_servidores> [<host>] # onde <num_servidores> [<host>] é opcional.");
meu_id = atoi(argv[1]);
num_serv = atoi(argv[2]);
if (argc == 4) {
prox_serv = argv[3];
}
timestamp();
printf("[%d] Num. servidores = [%d] - Proximo servidor = '%s'\n", meu_id, num_serv, prox_serv);
return tcp_serv(num_serv, prox_serv);
}
| 2.796875 | 3 |
2024-11-18T19:02:50.178102+00:00
| 2021-01-02T15:15:37 |
def3d25c695c0f50ec4f31cca7d5a124d9f367c0
|
{
"blob_id": "def3d25c695c0f50ec4f31cca7d5a124d9f367c0",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-02T15:15:37",
"content_id": "4567e7c28309701dd5d960b369bf868559f31968",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "bc92c058b0c2dd2877648e30156245e36ee571a4",
"extension": "c",
"filename": "example.c",
"fork_events_count": 0,
"gha_created_at": "2020-11-03T06:11:06",
"gha_event_created_at": "2020-12-08T07:48:54",
"gha_language": null,
"gha_license_id": "BSD-2-Clause",
"github_id": 309591131,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6198,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/source/common/xstream/imagetools/example/src/example.c",
"provenance": "stackv2-0058.json.gz:163453",
"repo_name": "robort-yuan/AI-EXPRESS",
"revision_date": "2021-01-02T15:15:37",
"revision_id": "56f86d03afbb09f42c21958c8cd9f2f1c6437f48",
"snapshot_id": "c1783f5f155b918dcc6da11956c842ae5467de8e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/robort-yuan/AI-EXPRESS/56f86d03afbb09f42c21958c8cd9f2f1c6437f48/source/common/xstream/imagetools/example/src/example.c",
"visit_date": "2023-02-09T03:51:44.775020"
}
|
stackv2
|
/**
* Copyright (c) 2018 Horizon Robotics. All rights reserved.
* @brief 图像处理接口的example程序
* @author hangjun.yang
* @email hangjun.yang@horizon.ai
* @version 0.0.0.1
* @date 2018.12.15
*/
#include <stdio.h>
#include <stdlib.h>
#include "hobotxstream/image_tools.h"
int main() {
FILE *fp = fopen("test.jpg", "rb");
if (fp == NULL) {
return -1;
}
fseek(fp, 0, SEEK_END);
int jpg_size = ftell(fp);
unsigned char *jpg_data = (unsigned char *)malloc(jpg_size);
rewind(fp);
fread(jpg_data, 1, jpg_size, fp);
fclose(fp);
int width = 0;
int height = 0;
int first_stride = 0;
int second_stride = 0;
uint8_t *output_data = NULL;
int output_size = 0;
// 解码值BGR格式
int ret = HobotXStreamDecodeImage(jpg_data,
jpg_size,
IMAGE_TOOLS_RAW_BGR,
&output_data,
&output_size,
&width,
&height,
&first_stride,
&second_stride);
if (ret == 0) {
fprintf(stdout, "decode to bgr format, result is :\n"
"width = %d\n"
"height = %d\n"
"first_stride = %d\n"
"second_stride = %d\n"
"output_data_size = %d\n\n",
width, height,
first_stride, second_stride, output_size);
free(jpg_data);
} else {
free(jpg_data);
fprintf(stderr, "decode error\n");
return -1;
}
// 抠图
uint8_t *crop_data = NULL;
int crop_data_size = 0;
ret = HobotXStreamCropImage(output_data, output_size,
width, height,
first_stride, second_stride,
IMAGE_TOOLS_RAW_BGR,
10, 560, 601, 931,
&crop_data, &crop_data_size,
&width, &height,
&first_stride, &second_stride);
if (ret == 0) {
fprintf(stdout, "cropr image, result is :\n"
"width = %d\n"
"height = %d\n"
"first_stride = %d\n"
"second_stride = %d\n"
"output_data_size = %d\n\n",
width, height,
first_stride, second_stride, crop_data_size);
// 释放解码得到的内存
HobotXStreamFreeImage(output_data);
} else {
fprintf(stderr, "resize format error\n");
HobotXStreamFreeImage(output_data);
return -1;
}
// 缩放至400 x 300, 保持宽高比
uint8_t *scale_data = NULL;
int scale_data_size = 0;
struct HobotXStreamImageToolsResizeInfo resize_info;
ret = HobotXStreamResizeImage(crop_data, crop_data_size,
width, height,
first_stride, second_stride,
IMAGE_TOOLS_RAW_BGR,
1,
400, 300,
&scale_data, &scale_data_size,
&first_stride, &second_stride,
&resize_info);
if (ret == 0) {
fprintf(stdout, "resize, result is :\n"
"width = 400\n"
"height = 300\n"
"first_stride = %d\n"
"second_stride = %d\n"
"output_data_size = %d\n"
"padding_right = %d\n"
"padding_bottom = %d\n"
"width_ratio = %f\n"
"height_ratio = %f\n\n",
first_stride, second_stride, scale_data_size,
resize_info.padding_right_,
resize_info.padding_bottom_,
resize_info.width_ratio_,
resize_info.height_ratio_);
// 释放抠图得到的内存
HobotXStreamFreeImage(crop_data);
} else {
fprintf(stderr, "resize format error\n");
HobotXStreamFreeImage(crop_data);
return -1;
}
// padding
uint8_t *padding_data = NULL;
int padding_data_size = 0;
uint8_t padding_rgb[3] = {255, 0, 0};
ret = HobotXStreamPadImage(scale_data, scale_data_size,
400, 300,
first_stride, second_stride,
IMAGE_TOOLS_RAW_BGR,
100, 300, 200, 400,
padding_rgb,
&padding_data, &padding_data_size,
&width, &height,
&first_stride, &second_stride);
if (ret == 0) {
fprintf(stdout, "pedding, result is :\n"
"width = %d\n"
"height = %d\n"
"first_stride = %d\n"
"second_stride = %d\n"
"output_data_size = %d\n\n",
width, height,
first_stride, second_stride, padding_data_size);
// 释放 缩放得到的内存
HobotXStreamFreeImage(scale_data);
} else {
fprintf(stderr, "resize format error\n");
HobotXStreamFreeImage(scale_data);
return -1;
}
// 格式转换
uint8_t *i420_data = NULL;
int i420_data_size = 0;
ret = HobotXStreamConvertImage(padding_data, padding_data_size,
width, height,
first_stride, second_stride,
IMAGE_TOOLS_RAW_BGR,
IMAGE_TOOLS_RAW_YUV_I420,
&i420_data, &i420_data_size,
&first_stride, &second_stride);
if (ret == 0) {
fprintf(stdout, "convert, result is :\n"
"width = %d\n"
"height = %d\n"
"first_stride = %d\n"
"second_stride = %d\n"
"output_data_size = %d\n\n",
width, height,
first_stride, second_stride, i420_data_size);
// 释放 pedding得到的内存
HobotXStreamFreeImage(padding_data);
} else {
fprintf(stderr, "resize format error\n");
HobotXStreamFreeImage(padding_data);
return -1;
}
FILE *result = fopen("example.i420", "wb+");
fwrite(i420_data, 1, i420_data_size, result);
fclose(result);
// 释放格式转换得到的内存
HobotXStreamFreeImage(i420_data);
return 0;
}
| 2.703125 | 3 |
2024-11-18T19:02:50.527265+00:00
| 2016-05-12T05:32:53 |
edd94af0f5e32b03e46f13dbbff3e6d72b77e0a7
|
{
"blob_id": "edd94af0f5e32b03e46f13dbbff3e6d72b77e0a7",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-12T05:32:53",
"content_id": "6a9ea6f0bab645da738a07d24d6928c69f90645f",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "976203016c462ec1d6fa7c7df03685d65be612f2",
"extension": "c",
"filename": "protocol_result_analizer.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 74460,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1656,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/protocol_result_analizer.c",
"provenance": "stackv2-0058.json.gz:163581",
"repo_name": "tractis/mod_tractis_auth",
"revision_date": "2016-05-12T05:32:53",
"revision_id": "1088dd98a6cdb1ceb9d05874575c5d0c0fb00355",
"snapshot_id": "0ef44c548a93074a11dcb509258097f96048ac65",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tractis/mod_tractis_auth/1088dd98a6cdb1ceb9d05874575c5d0c0fb00355/protocol_result_analizer.c",
"visit_date": "2021-01-21T13:48:51.090810"
}
|
stackv2
|
const char* TRACTIS_URL = "https://www.tractis.com/certificate_verification";
const char* resultStartTag = "<validationStatus>";
const char* resultEndTag = "</validationStatus>";
char* get_tag_text(char* result, char* tag_open, char *tag_close);
int check_validation_result(char* result){
if (is_debug_enabled()){
log_debug("Received result");
log_debug(result);
}
char* res = get_tag_text(result,(char*) resultStartTag,(char*) resultEndTag);
if (res == NULL) {
log_error(-1, "Server reported invalid response \n");
log_debug(result);
return SERVER_ERROR;
}
if (is_debug_enabled()){
log_debug("Validation result is");
log_debug(res);
log_debug("\n");
}
int result_code;
if (res == NULL){
log_error(-1, "Invalid message format");
result_code = SERVER_ERROR;
}else{
//Result analisys
if (strcmp(res,"VALID")==0){
result_code = VALID;
}else if (strcmp(res,"INVALID")==0){
result_code = INVALID;
}else if (strcmp(res,"UNKNOWN")==0){
result_code = UNKNOWN;
}else{
result_code = SERVER_ERROR;
}
}
free(res);
return result_code;
}
//Returns the text value of xml tag
char* get_tag_text(char* result, char* tag_open, char *tag_close){
int startToken = find_token_at_string(result, tag_open) + strlen(tag_open);
int endToken;
if (startToken >= 0) endToken = find_token_at_string_from(result, tag_close, startToken);
else return NULL;
if (startToken < 0 || endToken < 0){
log_error(-1,"Cannot find requested tokens on string");
return NULL;
}
size_t size = endToken - startToken;
char *res = malloc(size);
substring(result, res, startToken, size);
return res;
}
| 2.1875 | 2 |
2024-11-18T19:02:51.276534+00:00
| 2014-09-09T05:21:25 |
dbb3dc09270ae73885e1b6807a5bfb766c1d41cd
|
{
"blob_id": "dbb3dc09270ae73885e1b6807a5bfb766c1d41cd",
"branch_name": "refs/heads/master",
"committer_date": "2014-09-09T05:21:25",
"content_id": "a3a66da7d5afc64ef3270b6a32febb725a863f05",
"detected_licenses": [
"Unlicense"
],
"directory_id": "a2a69f6cc901f6fc4b4e578e3fddecb3107eed08",
"extension": "h",
"filename": "window.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": 2698,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/window.h",
"provenance": "stackv2-0058.json.gz:164484",
"repo_name": "archo5/nailer",
"revision_date": "2014-09-09T05:21:25",
"revision_id": "c0c4e1a22f77b788202a2cd9d0ac1aed4a171d1e",
"snapshot_id": "bde3069df7112c0711605c7287420aa4947b023e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/archo5/nailer/c0c4e1a22f77b788202a2cd9d0ac1aed4a171d1e/src/window.h",
"visit_date": "2021-08-27T15:19:14.338100"
}
|
stackv2
|
#pragma once
#include "config.h"
/* MAX_* - config.h */
/* --- control types --- */
#define WCTL_NONE 0
#define WCTL_TEXT 1
#define WCTL_BUTTON 2
/* --- control states --- */
#define WST_NORMAL 0
#define WST_HOVER 1
#define WST_CLICKED 2
/* --- actions --- */
#define WA_MOUSE_CLICK 1
#define WA_MOUSE_ENTER 2
#define WA_MOUSE_LEAVE 3
#define WA_MOUSE_BTNDN 4
#define WA_MOUSE_BTNUP 5
#define WA_CTRL_CREATED 100 /* custom */
#define WA_PROC_LAUNCH 200
#define WA_PROC_EXIT 201
/* --- image modes --- */
#define WIM_STRETCH 0
#define WIM_TOPLEFT 1
#define WIM_TOPRIGHT 2
#define WIM_BOTTOMLEFT 3
#define WIM_BOTTOMRIGHT 4
#define WIM_IS_BUTTON_MODE(x) ((x)<0)
#define WIM_GET_BUTTON_OFF(x) (-(x))
/* --- update categories --- */
#define WCU_RECT 0x0001
#define WCU_FG_COLOR 0x0002
#define WCU_BG_COLOR 0x0004
#define WCU_BG_IMAGE 0x0008
#define WCU_BG_IMGMODE 0x0010
#define WCU_FONT 0x0020
#define WCU_TEXT 0x0040
#define WCU_TYPE 0x0080
#define WCU_EVERYTHING 0xffff
typedef struct _wcontrol wcontrol;
typedef void (*wctl_action_callback) ( wcontrol*, int /* action */, int* /* data */ );
struct _wcontrol
{
/* control basic description */
int type;
int x1, y1, x2, y2;
/* state */
int state : 3;
int mouse_on : 1;
int clickedL : 1;
int clickedR : 1;
int clickedM : 1;
/* visual overrides */
byte fgColor[4];
byte bgColor[4];
int bgImage;
int bgImageMode;
char text[ MAX_CAPTION_SIZE_UTF8 ];
char fontName[ MAX_FONT_NAME_SIZE ];
};
extern wcontrol g_controls[ MAX_CONTROLS ];
extern int g_numControls;
extern wctl_action_callback g_winActCb;
void win_initialize( int argc, char* argv[] );
void win_destroy();
int win_process( int peek );
void win_quit();
void win_set_title( const char* title );
void win_set_size( int w, int h );
void win_set_background_image( int which );
void win_set_background_color( int r, int g, int b );
void win_ctl_resize( int count );
void win_ctl_updated( int i, int what );
/* platform file system */
FILE* platfs_exereadfile();
int platfs_curdir( const char* path_utf8 ); // sets current directory to the specified (absolute) directory
int platfs_tmpdir(); // sets current directory to a temporary directory
int platfs_nukedir(); // changes current directory back to executable, removes contents of previous temporary directory and the directory itself
int platfs_createdir_utf16( const unsigned short* path_utf16 );
int platfs_openwritefile_utf16( const unsigned short* path_utf16 ); // opens internal file slot for writing
int platfs_writefile( byte* buf, size_t num ); // writes to opened file
int platfs_closewritefile(); // closes opened file
int platfs_run( const char* cmd );
| 2.03125 | 2 |
2024-11-18T19:02:51.740516+00:00
| 2018-04-24T10:10:49 |
485a8736281bb9e4d8a915fb75fb5351b98fe80c
|
{
"blob_id": "485a8736281bb9e4d8a915fb75fb5351b98fe80c",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-24T10:10:49",
"content_id": "b888479f76956e10350966d38ed92bf1c248c013",
"detected_licenses": [
"MIT"
],
"directory_id": "c48cdc031866bfed8841229562ab8bb87804ade2",
"extension": "c",
"filename": "reg.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 123541574,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2123,
"license": "MIT",
"license_type": "permissive",
"path": "/Source/STM8S_Slave/User/Middle/reg.c",
"provenance": "stackv2-0058.json.gz:165002",
"repo_name": "HgN37/EmbbededPlatform",
"revision_date": "2018-04-24T10:10:49",
"revision_id": "1ccdca5bb41665cbd70b360f8cac82037b4a8518",
"snapshot_id": "a57a07b1ae26ba05b4016fe86d90f9baf76298b7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HgN37/EmbbededPlatform/1ccdca5bb41665cbd70b360f8cac82037b4a8518/Source/STM8S_Slave/User/Middle/reg.c",
"visit_date": "2021-01-25T13:11:57.009883"
}
|
stackv2
|
#include "reg.h"
struct {
uint8_t id;
uint8_t hardware;
uint8_t version;
uint8_t status;
} REG_RO;
struct {
uint8_t output[16];
uint8_t input[16];
} REG_RW;
struct {
uint8_t address;
} REG_CONFIG;
void regInit(void) {
eepromInit();
eepromRead(REG_ID_EEPROM, ®_RO.id, 1);
eepromRead(REG_HARDWARE_EEPROM, ®_RO.hardware, 1);
eepromRead(REG_VERSION_EEPROM, ®_RO.version, 1);
eepromRead(REG_STATUS_EEPROM, ®_RO.status, 1);
int count;
for(count = 0; count < 16; count++) {
REG_RW.output[count] = 0xFF;
REG_RW.input[count] = 0xFF;
}
eepromRead(REG_ADDR_EEPROM, ®_CONFIG.address, 1);
}
void regWrite(uint8_t pAddr, uint8_t pData) {
if((pAddr & 0xF0) == 0x10) {
REG_RW.output[pAddr & 0x0F] = pData;
}
else if((pAddr & 0xF0) == 0x20) {
REG_RW.input[pAddr & 0x0F] = pData;
}
else if(pAddr == 0x30) {
REG_CONFIG.address = pData;
eepromWrite(REG_ADDR_EEPROM, ®_CONFIG.address, 1);
}
else if(pAddr == REG_ID) {
REG_RO.id = pData;
eepromWrite(REG_ID_EEPROM, ®_RO.id, 1);
}
else if(pAddr == REG_HARDWARE) {
REG_RO.hardware = pData;
eepromWrite(REG_HARDWARE_EEPROM, ®_RO.hardware, 1);
}
else if(pAddr == REG_VERSION) {
REG_RO.version = pData;
eepromWrite(REG_VERSION_EEPROM, ®_RO.version, 1);
}
else if(pAddr == REG_STATUS) {
REG_RO.status = pData;
eepromWrite(REG_STATUS_EEPROM, ®_RO.status, 1);
}
}
uint8_t regRead(uint8_t pAddr) {
if((pAddr & 0xF0) == 0x10) {
return REG_RW.output[pAddr & 0x0F];
}
else if((pAddr & 0xF0) == 0x20) {
return REG_RW.input[pAddr & 0x0F];
}
else if(pAddr == 0xF0) {
return REG_RO.id;
}
else if(pAddr == 0xF1) {
return REG_RO.hardware;
}
else if(pAddr == 0xF2) {
return REG_RO.version;
}
else if(pAddr == 0xF3) {
return REG_RO.status;
}
else if(pAddr == 0x30) {
return REG_CONFIG.address;
}
else {
return 0xFF;
}
}
| 2.75 | 3 |
2024-11-18T19:02:51.876868+00:00
| 2020-03-10T02:07:53 |
8422ff2ed0564c906540b43ca6f03da43fbe8a07
|
{
"blob_id": "8422ff2ed0564c906540b43ca6f03da43fbe8a07",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-10T02:07:53",
"content_id": "e00d0c47e275f0d01adaf6d89f6a151fc4454fca",
"detected_licenses": [
"MIT"
],
"directory_id": "fde930e237313b8616475affbe82de77266d5de4",
"extension": "c",
"filename": "date.c",
"fork_events_count": 2,
"gha_created_at": "2020-02-25T02:06:12",
"gha_event_created_at": "2020-03-10T02:07:54",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 242887518,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 420,
"license": "MIT",
"license_type": "permissive",
"path": "/date.c",
"provenance": "stackv2-0058.json.gz:165258",
"repo_name": "CorreianAngel/homework_2",
"revision_date": "2020-03-10T02:07:53",
"revision_id": "e411dc99807136845650db77cbecdfade76b8d65",
"snapshot_id": "e38ea89d225ba7001d72c19df0898a46c584a6b9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CorreianAngel/homework_2/e411dc99807136845650db77cbecdfade76b8d65/date.c",
"visit_date": "2021-01-15T05:12:30.703579"
}
|
stackv2
|
/* date.c
*Author: Alex Correia
*File: date.c
*Description: This is the date command that is exectuted in the xv6 shell prompt.
*/
# include "types.h"
# include "user.h"
# include "date.h"
int
main (int argc, char *argv[])
{
struct rtcdate r;
if (!date(&r))
{
printf(2, "date failed\n");
exit();
}
// printf(1, "%d/%d/%d %d:%d:%d\n", r.day, r.month, r.year, r.hour,
// r.minute, r.second);
exit();
}
| 2.421875 | 2 |
2024-11-18T19:02:52.389927+00:00
| 2016-10-09T15:37:46 |
028165dd91c822a0d65e726adf9d9d4aedbad825
|
{
"blob_id": "028165dd91c822a0d65e726adf9d9d4aedbad825",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-09T15:37:46",
"content_id": "ed0850b120d136099eb11ef0e0604f883f2aea41",
"detected_licenses": [
"MIT"
],
"directory_id": "db487fccb3deff564d4612e25395998a421bdcee",
"extension": "c",
"filename": "convert.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": 4079,
"license": "MIT",
"license_type": "permissive",
"path": "/src/convert.c",
"provenance": "stackv2-0058.json.gz:165387",
"repo_name": "accenture-schuylervo/RomanNumeralCalcInC",
"revision_date": "2016-10-09T15:37:46",
"revision_id": "2a54f598dccd72fb3d9fd34d6e43d0321cfdcd90",
"snapshot_id": "0d4e215c2e42a990fe377fc5fbcbb45de575361f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/accenture-schuylervo/RomanNumeralCalcInC/2a54f598dccd72fb3d9fd34d6e43d0321cfdcd90/src/convert.c",
"visit_date": "2020-07-21T08:38:07.370395"
}
|
stackv2
|
#include "convert.h"
arabicRomanPair roman_arabic_lookup[] = {
{ 3, ROMAN_III, sizeof(ROMAN_III) - 1},
{ 2, ROMAN_II , sizeof(ROMAN_II) - 1 },
{ 4, ROMAN_IV , sizeof(ROMAN_IV) - 1 },
{ 9, ROMAN_IX , sizeof(ROMAN_IX) - 1 },
{ 40, ROMAN_XL , sizeof(ROMAN_XL) - 1 },
{ 90, ROMAN_XC , sizeof(ROMAN_XC) - 1 },
{ 400, ROMAN_CD , sizeof(ROMAN_CD) - 1 },
{ 900, ROMAN_CM , sizeof(ROMAN_CM) - 1 },
{ 1, ROMAN_I , sizeof(ROMAN_I) - 1 },
{ 5, ROMAN_V , sizeof(ROMAN_V) - 1 },
{ 10, ROMAN_X , sizeof(ROMAN_X) - 1 },
{ 50, ROMAN_L , sizeof(ROMAN_L) - 1 },
{ 100, ROMAN_C , sizeof(ROMAN_C) - 1 },
{ 500, ROMAN_D , sizeof(ROMAN_D) - 1 },
{1000, ROMAN_M , sizeof(ROMAN_M) - 1 }
};
arabicRomanPair* lastRomanArabicLookupEntry = &roman_arabic_lookup[sizeof(roman_arabic_lookup) /
sizeof(arabicRomanPair) - 1];
arabicRomanPair arabic_roman_lookup[] = {
{ 1, ROMAN_I , sizeof(ROMAN_I) - 1 },
{ 2, ROMAN_II , sizeof(ROMAN_II) - 1 },
{ 3, ROMAN_III, sizeof(ROMAN_III) - 1},
{ 4, ROMAN_IV , sizeof(ROMAN_IV) - 1 },
{ 5, ROMAN_V , sizeof(ROMAN_V) - 1 },
{ 9, ROMAN_IX , sizeof(ROMAN_IX) - 1 },
{ 10, ROMAN_X , sizeof(ROMAN_X) - 1 },
{ 40, ROMAN_XL , sizeof(ROMAN_XL) - 1 },
{ 50, ROMAN_L , sizeof(ROMAN_L) - 1 },
{ 90, ROMAN_XC , sizeof(ROMAN_XC) - 1 },
{ 100, ROMAN_C , sizeof(ROMAN_C) - 1 },
{ 400, ROMAN_CD , sizeof(ROMAN_CD) - 1 },
{ 500, ROMAN_D , sizeof(ROMAN_D) - 1 },
{ 900, ROMAN_CM , sizeof(ROMAN_CM) - 1 },
{1000, ROMAN_M , sizeof(ROMAN_M) - 1 }
};
arabicRomanPair* lastArabicRomanLookupEntry = &arabic_roman_lookup[sizeof(roman_arabic_lookup) /
sizeof(arabicRomanPair) - 1];
#define romanNumeralComponentIsFound() strncmp(position_in_roman_numeral, pair->roman, pair->romanLength) == 0
#define charactersRemainInRomanNumeral() strlen(position_in_roman_numeral) != 0
#define notPastEndOfLookupTable() pair <= lastRomanArabicLookupEntry
#define advanceToNextPositionInRomanNumeral() position_in_roman_numeral += pair->romanLength
int convertRomanToArabic(char* romanNumeral) {
char* position_in_roman_numeral = romanNumeral;
int accumulator = 0;
while( charactersRemainInRomanNumeral() ) {
arabicRomanPair* pair = roman_arabic_lookup;
while( notPastEndOfLookupTable() ) {
if(romanNumeralComponentIsFound()) {
accumulator += pair->arabic;
break;
}
pair++;
}
advanceToNextPositionInRomanNumeral();
}
return accumulator;
}
#define arabicValueNotDepleted() arabic_value > 0
#define exactMatchToArabicValue() pair->arabic == arabic_value
#define tableEntryExceedsArabicValue() pair->arabic > arabic_value
#define lastTableEntryIsLessOrEqualToArabicValue() pair == lastArabicRomanLookupEntry && pair->arabic <= arabic_value
#define arabicValueAndTableEntriesRemain() pair <= lastArabicRomanLookupEntry && arabic_value > 0
char* convertArabicToRoman(int arabic_number, char *romanNumeral){
int arabic_value = arabic_number;
while(arabicValueNotDepleted()) {
arabicRomanPair* pair = arabic_roman_lookup;
do {
if(lastTableEntryIsLessOrEqualToArabicValue()) {
strcat(romanNumeral, pair->roman);
arabic_value -= pair->arabic;
break;
}
if(tableEntryExceedsArabicValue()) {
strcat(romanNumeral, (pair - 1)->roman);
arabic_value -= (pair - 1)->arabic;
break;
}
else if (exactMatchToArabicValue()) {
strcat(romanNumeral, pair->roman);
arabic_value -= pair->arabic;
break;
}
pair++;
} while(arabicValueAndTableEntriesRemain());
}
return romanNumeral;
}
| 2.09375 | 2 |
2024-11-18T19:02:56.283100+00:00
| 2022-06-10T14:28:33 |
eada97da38324a9084a2eeb5b846e5327ee45004
|
{
"blob_id": "eada97da38324a9084a2eeb5b846e5327ee45004",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-10T14:28:33",
"content_id": "7bbf95f5fa186aa52dcecc79c80e68122d41c655",
"detected_licenses": [
"MIT"
],
"directory_id": "c42a251cfe4873d350e2836a51d625ec1d17826e",
"extension": "h",
"filename": "buzzheap.h",
"fork_events_count": 3,
"gha_created_at": "2017-06-23T17:49:17",
"gha_event_created_at": "2022-02-28T21:23:41",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 95243176,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1860,
"license": "MIT",
"license_type": "permissive",
"path": "/src/buzz/buzzheap.h",
"provenance": "stackv2-0058.json.gz:170838",
"repo_name": "NESTLab/Buzz",
"revision_date": "2022-06-10T14:28:33",
"revision_id": "6a9a51f9b658b76fc995152546d4b625e74abb6d",
"snapshot_id": "ec0e6d4daaa7e87b408985c595d4f799696086b1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/NESTLab/Buzz/6a9a51f9b658b76fc995152546d4b625e74abb6d/src/buzz/buzzheap.h",
"visit_date": "2022-07-09T07:47:56.423512"
}
|
stackv2
|
#ifndef BUZZHEAP_H
#define BUZZHEAP_H
#include <buzz/buzztype.h>
#include <buzz/buzzdarray.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Forward declaration of the VM state.
*/
struct buzzvm_s;
/**
* The state of the object heap
*/
struct buzzheap_s {
/* The list of all objects */
buzzdarray_t objs;
/* The maximum number of vars after which GC is triggered */
uint32_t max_objs;
/* Current marker for garbage collection */
uint16_t marker;
};
typedef struct buzzheap_s* buzzheap_t;
/**
* Creates a new heap.
* @return The state of a new heap.
*/
buzzheap_t buzzheap_new();
/**
* Destroys a heap.
* @param A pointer to the heap.
*/
void buzzheap_destroy(buzzheap_t* h);
/**
* Creates a new Buzz object.
* @param vm The Buzz VM.
* @param The object type.
* @param The new object.
*/
buzzobj_t buzzheap_newobj(struct buzzvm_s* vm,
uint16_t type);
/*
* Internally used to clones a Buzz object.
* @param vm The Buzz VM.
* @param o The Buzz object to clone.
* @return The cloned object.
*/
extern buzzobj_t buzzheap_clone(struct buzzvm_s* vm,
const buzzobj_t o);
/**
* Performs garbage collection, if necessary.
* Internally uses a simple mark-and-sweep algorithm.
* @param vm The Buzz VM.
*/
void buzzheap_gc(struct buzzvm_s* vm);
extern void buzzheap_obj_mark(buzzobj_t o, struct buzzvm_s* vm);
extern void buzzheap_darrayobj_mark(uint32_t pos, void* data, void* params);
extern void buzzheap_dictobj_mark(const void* key, void* data, void* params);
extern void buzzheap_vstigobj_mark(const void* key, void* data, void* params);
#ifdef __cplusplus
}
#endif
#define buzzheap_addvar();
#endif
| 2.21875 | 2 |
2024-11-18T19:02:56.470383+00:00
| 2017-06-12T05:35:07 |
19be38aab745e46f35f9542fe2812387fdb130fe
|
{
"blob_id": "19be38aab745e46f35f9542fe2812387fdb130fe",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-12T05:35:07",
"content_id": "312a1f7f58ace4e8f4795d46b31a3156f04c8185",
"detected_licenses": [
"MIT"
],
"directory_id": "06a364b84b20a5b7f524831d00921668ac1a5b23",
"extension": "c",
"filename": "produce_csv_value_dta.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60890144,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3814,
"license": "MIT",
"license_type": "permissive",
"path": "/src/bin/modules/produce_csv_value_dta.c",
"provenance": "stackv2-0058.json.gz:171095",
"repo_name": "ngr-t/smuggler",
"revision_date": "2017-06-12T05:35:07",
"revision_id": "b49a4b77c453f5c42272d70b4201036f628cd79d",
"snapshot_id": "8da7dc46efbbe4e30021543a9c11c99450eff27b",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/ngr-t/smuggler/b49a4b77c453f5c42272d70b4201036f628cd79d/src/bin/modules/produce_csv_value_dta.c",
"visit_date": "2020-04-06T07:06:23.092810"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include "../util/readstat_dta_days.h"
#include "produce_csv_value.h"
#include "produce_csv_value_dta.h"
#include "produce_csv_column_header.h"
readstat_value_t value_int32_date_dta(const char *s, size_t len, struct csv_metadata *c) {
readstat_variable_t *var = &c->variables[c->columns];
char* dest;
int val = readstat_dta_num_days(s, &dest);
if (dest == s) {
fprintf(stderr, "%s:%d not a date: %s\n", __FILE__, __LINE__, (char*)s);
exit(EXIT_FAILURE);
}
int missing_ranges_count = readstat_variable_get_missing_ranges_count(var);
for (int i=0; i<missing_ranges_count; i++) {
readstat_value_t lo_val = readstat_variable_get_missing_range_lo(var, i);
readstat_value_t hi_val = readstat_variable_get_missing_range_hi(var, i);
if (readstat_value_type(lo_val) != READSTAT_TYPE_INT32) {
fprintf(stderr, "%s:%d expected type of lo_val to be of type int32. Should not happen\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
int lo = readstat_int32_value(lo_val);
int hi = readstat_int32_value(hi_val);
if (val >= lo && val <= hi) {
readstat_value_t value = {
.type = READSTAT_TYPE_INT32,
.is_tagged_missing = 1,
.tag = 'a' + i,
.v = { .i32_value = val }
};
return value;
}
}
readstat_value_t value = {
.type = READSTAT_TYPE_INT32,
.is_tagged_missing = 0,
.v = { .i32_value = val }
};
return value;
}
readstat_value_t value_double_dta(const char *s, size_t len, struct csv_metadata *c) {
char *dest;
readstat_variable_t *var = &c->variables[c->columns];
double val = strtod(s, &dest);
if (dest == s) {
fprintf(stderr, "not a number: %s\n", (char*)s);
exit(EXIT_FAILURE);
}
int missing_ranges_count = readstat_variable_get_missing_ranges_count(var);
for (int i=0; i<missing_ranges_count; i++) {
readstat_value_t lo_val = readstat_variable_get_missing_range_lo(var, i);
readstat_value_t hi_val = readstat_variable_get_missing_range_hi(var, i);
if (readstat_value_type(lo_val) != READSTAT_TYPE_DOUBLE) {
fprintf(stderr, "%s:%d expected type of lo_val to be of type double. Should not happen\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
double lo = readstat_double_value(lo_val);
double hi = readstat_double_value(hi_val);
if (val >= lo && val <= hi) {
readstat_value_t value = {
.type = READSTAT_TYPE_DOUBLE,
.is_tagged_missing = 1,
.tag = 'a' + i,
.v = { .double_value = val }
};
return value;
}
}
readstat_value_t value = {
.type = READSTAT_TYPE_DOUBLE,
.is_tagged_missing = 0,
.v = { .double_value = val }
};
return value;
}
void produce_csv_value_dta(const char *s, size_t len, struct csv_metadata *c) {
readstat_variable_t *var = &c->variables[c->columns];
int is_date = c->is_date[c->columns];
int obs_index = c->rows - 1; // TODO: ???
readstat_value_t value;
if (len == 0) {
value = value_sysmiss(s, len, c);
} else if (is_date) {
value = value_int32_date_dta(s, len, c);
} else if (var->type == READSTAT_TYPE_DOUBLE) {
value = value_double_dta(s, len, c);
} else if (var->type == READSTAT_TYPE_STRING) {
value = value_string(s, len, c);
} else {
fprintf(stderr, "%s:%d unsupported variable type %d\n", __FILE__, __LINE__, var->type);
exit(EXIT_FAILURE);
}
c->parser->value_handler(obs_index, var, value, c->user_ctx);
}
| 2.28125 | 2 |
2024-11-18T19:02:56.535951+00:00
| 2020-06-23T14:47:53 |
246dfe592c3676b43808ca41ea21ac4b503fb312
|
{
"blob_id": "246dfe592c3676b43808ca41ea21ac4b503fb312",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-23T14:47:53",
"content_id": "d959a76c993af0911536c574bd33471d4e7a736d",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fe70c380a5b05e5d2a1788ba5d95b75706cd8856",
"extension": "c",
"filename": "common.c",
"fork_events_count": 0,
"gha_created_at": "2020-07-13T17:58:58",
"gha_event_created_at": "2020-07-13T17:58:59",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 279375323,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 952,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/tests/common.c",
"provenance": "stackv2-0058.json.gz:171225",
"repo_name": "marla396/punchboot",
"revision_date": "2020-06-23T14:47:53",
"revision_id": "3d53bac818e430f5f015e43b607944a882a08e4f",
"snapshot_id": "abd77d8a4a478308270c108ad8818bde1128bf16",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/marla396/punchboot/3d53bac818e430f5f015e43b607944a882a08e4f/tests/common.c",
"visit_date": "2022-11-12T03:31:22.207724"
}
|
stackv2
|
/**
* Punch BOOT
*
* Copyright (C) 2018 Jonas Blixt <jonpe960@gmail.com>
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include <stdio.h>
#include <pb/board.h>
#include <pb/plat.h>
#include <plat/qemu/pl061.h>
#include <plat/qemu/gcov.h>
#include <plat/qemu/uart.h>
#include <plat/qemu/semihosting.h>
#include <pb/assert.h>
#include "test.h"
static struct qemu_uart_device console_uart =
{
.base = 0x09000000,
};
int plat_console_putchar(char c)
{
qemu_uart_write(&console_uart, (char *) &c, 1);
return PB_OK;
}
void __assert(const char *file, unsigned int line,
const char *assertion)
{
printf("Assert failed %s:%i (%s)\n\r", file, line, assertion);
gcov_final();
semihosting_sys_exit(1);
while (1) {}
}
int plat_get_uuid(char *out)
{
return PB_OK;
}
void pb_main(void)
{
qemu_uart_init(&console_uart);
gcov_init();
test_main();
gcov_final();
semihosting_sys_exit(0);
}
| 2.234375 | 2 |
2024-11-18T19:02:56.659773+00:00
| 2021-02-16T04:43:08 |
b7704fb74a6bc615374748a755358c677fbb839d
|
{
"blob_id": "b7704fb74a6bc615374748a755358c677fbb839d",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-16T04:43:08",
"content_id": "85efbfac5a5c5e2a20412b43423375aa7605ad34",
"detected_licenses": [
"MIT"
],
"directory_id": "4ad404f367e45e36305675af89febbbea9d36a54",
"extension": "c",
"filename": "rbc.c",
"fork_events_count": 2,
"gha_created_at": "2018-06-25T04:44:50",
"gha_event_created_at": "2018-06-25T04:44:50",
"gha_language": null,
"gha_license_id": null,
"github_id": 138544498,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 27075,
"license": "MIT",
"license_type": "permissive",
"path": "/source/ev3/rbc.c",
"provenance": "stackv2-0058.json.gz:171354",
"repo_name": "Evolitist/ev3dev-c",
"revision_date": "2021-02-16T04:43:08",
"revision_id": "a91fea930c9b61be1b0552cfc7ff260dbfd97081",
"snapshot_id": "662af8f62b5d6005e91d45bb1aa03d0820a53650",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Evolitist/ev3dev-c/a91fea930c9b61be1b0552cfc7ff260dbfd97081/source/ev3/rbc.c",
"visit_date": "2021-06-15T17:54:58.003728"
}
|
stackv2
|
#include "rbc.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
bool checkBack = true;
task exitWatcher()
{
uint8_t keys = 0;
while(1)
{
if(checkBack)
{
ev3_read_keys(&keys);
if(keys & 32)
{
exit(130);
}
}
}
}
void init()
{
ev3_sensor_init();
ev3_tacho_init();
uint8_t sn = 0;
while(sn < TACHO_DESC__LIMIT_)
{
if(ev3_tacho[sn].port != 0)
{
set_tacho_stop_action_inx(sn, TACHO_BRAKE);
}
++sn;
}
ev3_tasks_init();
ev3_display_init();
startTask(exitWatcher);
}
void uninit()
{
uint8_t sn = 0;
while(sn < TACHO_DESC__LIMIT_)
{
if(ev3_tacho[sn].port != 0)
{
set_tacho_stop_action_inx(sn, TACHO_BRAKE);
set_tacho_command_inx(sn, TACHO_STOP);
}
++sn;
}
ev3_display_uninit();
}
uint8_t multiOutToOutPtr(tMotor mOut, uint8_t *sn)
{
uint8_t _sn, res = 0;
memset(sn, DESC_LIMIT, DESC_VEC_LEN);
for (_sn = 0; _sn < DESC_LIMIT; _sn++)
{
if (ev3_tacho[_sn].type_inx != TACHO_TYPE__NONE_)
{
uint8_t sock = 0UL;
switch(ev3_tacho[_sn].port)
{
case OUTPUT_A:
sock = motorA;
break;
case OUTPUT_B:
sock = motorB;
break;
case OUTPUT_C:
sock = motorC;
break;
case OUTPUT_D:
sock = motorD;
break;
}
if (sock & mOut)
{
++res;
*sn = _sn;
++sn;
mOut &= ~sock;
if (mOut == 0) {
return res;
}
}
}
}
return res;
}
/* **** BUTTON **** */
int getButtonPress(tButton button)
{
uint8_t keys = 0;
ev3_read_keys(&keys);
return ((keys & button) == button);
}
void waitForButtonPress()
{
uint8_t keys = 0;
while(!keys) ev3_read_keys(&keys);
}
void setBlockBackButton(bool block)
{
checkBack = !block;
}
/* **** SCREEN **** */
void clearDisplay()
{
display_clear();
}
void displayClearTextLine(uint8_t line)
{
display_clear_text_line(line);
}
void setPixel(int x, int y)
{
display_draw_pixel(x, y, true);
}
void clearPixel(int x, int y)
{
display_draw_pixel(x, y, false);
}
void displayTextLine(uint8_t line, const char *format, ...)
{
display_draw_text_line(line, format);
}
void displayCenteredTextLine(uint8_t line, const char *format, ...)
{
display_draw_centered_text_line(line, format);
}
void displayString(uint8_t line, const char *format, ...)
{
display_draw_string(line, format);
}
/* **** MATH **** */
double degreesToRadians(int d)
{
return PI * (d) / 180.0;
}
int radiansToDegrees(double r)
{
return (int)round(180.0 * (r) / PI);
}
/*double abs(double d)
{
return fabs(d);
}*/
int8_t sgn(double d)
{
return d < 0 ? -1 : 1;
}
double sinDegrees(int d)
{
return sin(degreesToRadians(d));
}
double cosDegrees(int d)
{
return cos(degreesToRadians(d));
}
/*double random(int a, int b)
{
return a + (rand() % b);
}*/
/* **** MOTORS **** */
TBrakeModes getMotorBrakeMode(tMotor motor)
{
uint8_t sn;
if(ev3_search_tacho_plugged_in(motor, EXT_PORT__NONE_, &sn, 0))
{
switch(get_tacho_stop_action_inx(sn))
{
case TACHO_COAST:
return motorCoast;
case TACHO_BRAKE:
return motorBrake;
case TACHO_HOLD:
return motorHold;
}
}
return 0;
}
int getMotorEncoder(tMotor motor)
{
int val = 0;
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motor, sn) == 1)
{
get_tacho_position(*sn, &val);
}
return val;
}
float getMotorEncoderAverage(tMotor motors)
{
uint8_t sn[DESC_VEC_LEN];
float val = 0.0F;
uint8_t cnt = multiOutToOutPtr(motors, sn);
if (cnt == 1)
{
int intval = 0;
get_tacho_position(*sn, &intval);
val = (float)intval;
}
else if (cnt > 1)
{
uint8_t i = 0;
while (sn[i] != DESC_LIMIT && i < DESC_VEC_LEN)
{
int intval = 0;
get_tacho_position(sn[i], &intval);
val += (float)intval;
++i;
}
val = val / (float)cnt;
}
return val;
}
float getMotorRPM(tMotor motor)
{
int val = 0;
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motor, sn) == 1)
{
get_tacho_speed(*sn, &val);
}
return (float)val / (float)360;
}
bool getMotorRunning(tMotor motors)
{
uint8_t sn[DESC_VEC_LEN];
FLAGS_T flags = TACHO_STATE__NONE_;
uint8_t cnt = multiOutToOutPtr(motors, sn);
if (cnt == 1)
{
get_tacho_state_flags(*sn, &flags);
}
else if (cnt > 1)
{
uint8_t i = 0;
while (sn[i] != DESC_LIMIT && i < DESC_VEC_LEN)
{
FLAGS_T nf = TACHO_STATE__NONE_;
get_tacho_state_flags(sn[i], &nf);
flags |= nf;
++i;
}
}
return flags != TACHO_STATE__NONE_;
}
int getMotorTarget(tMotor motor)
{
int val = 0;
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motor, sn) == 1)
{
get_tacho_position_sp(*sn, &val);
}
return val;
}
void moveMotorTarget(tMotor motors, int position, int8_t speed)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn))
{
multi_set_tacho_position_sp(sn, sgn(speed) * position);
multi_set_tacho_speed_sp(sn, speed * 10);
multi_set_tacho_command_inx(sn, TACHO_RUN_TO_REL_POS);
}
}
void resetMotorEncoder(tMotor motors)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn))
{
multi_set_tacho_position(sn, 0);
}
}
void setMotorBrakeMode(tMotor motors, TBrakeModes brakeMode)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn))
{
multi_set_tacho_stop_action_inx(sn, brakeMode);
}
}
void setMotorReversed(tMotor motors, bool rev)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn))
{
multi_set_tacho_polarity_inx(sn, rev ? TACHO_INVERSED : TACHO_NORMAL);
}
}
void setMotorSpeed(tMotor motors, int8_t speed)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn))
{
multi_set_tacho_speed_sp(sn, speed * 10);
multi_set_tacho_command_inx(sn, TACHO_RUN_FOREVER);
}
}
void setMotorSync(tMotor motors, int8_t turnRatio, int8_t speed)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn) == 2)
{
int speed1 = speed * 10, speed2 = speed * 10;
if(turnRatio < 0) speed1 -= speed1 * abs(turnRatio) / 50;
if(turnRatio > 0) speed2 -= speed2 * abs(turnRatio) / 50;
set_tacho_speed_sp(sn[0], speed1);
set_tacho_speed_sp(sn[1], speed2);
multi_set_tacho_command_inx(sn, TACHO_RUN_FOREVER);
}
}
void setMotorSyncEncoder(tMotor motors, int8_t turnRatio, int enc, int8_t speed)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn) == 2)
{
int speed1 = speed * 10, speed2 = speed * 10;
if(turnRatio < 0) speed1 -= speed1 * abs(turnRatio) / 50;
if(turnRatio > 0) speed2 -= speed2 * abs(turnRatio) / 50;
set_tacho_speed_sp(sn[0], speed1);
set_tacho_speed_sp(sn[1], speed2);
set_tacho_position_sp(sn[0], enc);
set_tacho_position_sp(sn[1], enc * speed2 / speed1);
multi_set_tacho_command_inx(sn, TACHO_RUN_TO_REL_POS);
}
}
void setMotorSyncTime(tMotor motors, int8_t turnRatio, int time_ms, int8_t speed)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motors, sn) == 2)
{
int speed1 = speed * 10, speed2 = speed * 10;
if(turnRatio < 0) speed1 -= speed1 * abs(turnRatio) / 50;
if(turnRatio > 0) speed2 -= speed2 * abs(turnRatio) / 50;
set_tacho_speed_sp(sn[0], speed1);
set_tacho_speed_sp(sn[1], speed2);
multi_set_tacho_time_sp(sn, time_ms);
multi_set_tacho_command_inx(sn, TACHO_RUN_TIMED);
}
}
void setMotorTarget(tMotor motor, int position, int8_t speed)
{
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motor, sn))
{
multi_set_tacho_position_sp(sn, position);
multi_set_tacho_speed_sp(sn, speed * 10);
multi_set_tacho_command_inx(sn, TACHO_RUN_TO_ABS_POS);
}
}
int getMotorPreciseEncoder(tMotor motor)
{
int val = 0;
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motor, sn) == 1)
{
get_tacho_position_precise(*sn, &val);
}
return val;
}
int getMotorPreciseSpeed(tMotor motor)
{
int val = 0;
uint8_t sn[DESC_VEC_LEN];
if (multiOutToOutPtr(motor, sn) == 1)
{
get_tacho_speed_precise(*sn, &val);
}
return val;
}
/* **** SENSOR **** */
/* ---- SYSTEM ---- */
/* ---- USER ---- */
tSensor findSensor(INX_T type)
{
uint8_t sn = 0;
ev3_search_sensor(type, &sn, sn);
switch(ev3_sensor[sn].port)
{
case INPUT_1: return S1;
case INPUT_2: return S2;
case INPUT_3: return S3;
case INPUT_4: return S4;
}
return 0;
}
int getSensorValue(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0))
{
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getColorAmbient(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_COLOR) != LEGO_EV3_COLOR_COL_AMBIENT)
{
set_sensor_mode_inx(sn, LEGO_EV3_COLOR_COL_AMBIENT);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getColorName(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_COLOR) != LEGO_EV3_COLOR_COL_COLOR)
{
set_sensor_mode_inx(sn, LEGO_EV3_COLOR_COL_COLOR);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getColorReflected(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_COLOR) != LEGO_EV3_COLOR_COL_REFLECT)
{
set_sensor_mode_inx(sn, LEGO_EV3_COLOR_COL_REFLECT);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getColorRed(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_COLOR) != LEGO_EV3_COLOR_RGB_RAW)
{
set_sensor_mode_inx(sn, LEGO_EV3_COLOR_RGB_RAW);
}
get_sensor_value0(sn, &val);
val = val * 255 / 1023;
}
return (int)round(val);
}
int getColorGreen(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_COLOR) != LEGO_EV3_COLOR_RGB_RAW)
{
set_sensor_mode_inx(sn, LEGO_EV3_COLOR_RGB_RAW);
}
get_sensor_value1(sn, &val);
val = val * 255 / 1023;
}
return (int)round(val);
}
int getColorBlue(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_COLOR) != LEGO_EV3_COLOR_RGB_RAW)
{
set_sensor_mode_inx(sn, LEGO_EV3_COLOR_RGB_RAW);
}
get_sensor_value2(sn, &val);
val = val * 255 / 1023;
}
return (int)round(val);
}
void getColorRGB(tSensor sensor, int *red, int *green, int *blue)
{
uint8_t sn;
float r = 0, g = 0, b = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_COLOR) != LEGO_EV3_COLOR_RGB_RAW)
{
set_sensor_mode_inx(sn, LEGO_EV3_COLOR_RGB_RAW);
}
get_sensor_value0(sn, &r);
get_sensor_value1(sn, &g);
get_sensor_value2(sn, &b);
*red = (int)round(r * 255 / 1023);
*green = (int)round(g * 255 / 1023);
*blue = (int)round(b * 255 / 1023);
}
}
float getUSDistance(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_US)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_US) != LEGO_EV3_US_US_DIST_CM)
{
set_sensor_mode_inx(sn, LEGO_EV3_US_US_DIST_CM);
}
get_sensor_value0(sn, &val);
val /= 10;
}
return val;
}
int getGyroHeading(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_GYRO)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_GYRO) != LEGO_EV3_GYRO_GYRO_ANG && get_sensor_mode_inx_of_type(sn, LEGO_EV3_GYRO) != LEGO_EV3_GYRO_GYRO_G_AND_A)
{
set_sensor_mode_inx(sn, LEGO_EV3_GYRO_GYRO_G_AND_A);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getGyroRate(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_GYRO)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_GYRO) != LEGO_EV3_GYRO_GYRO_RATE && get_sensor_mode_inx_of_type(sn, LEGO_EV3_GYRO) != LEGO_EV3_GYRO_GYRO_G_AND_A)
{
set_sensor_mode_inx(sn, LEGO_EV3_GYRO_GYRO_G_AND_A);
}
get_sensor_value1(sn, &val);
}
return (int)round(val);
}
void resetGyro(tSensor sensor)
{
uint8_t sn;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_GYRO)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_GYRO) == LEGO_EV3_GYRO_GYRO_ANG && get_sensor_mode_inx_of_type(sn, LEGO_EV3_GYRO) == LEGO_EV3_GYRO_GYRO_G_AND_A)
{
set_sensor_mode_inx(sn, LEGO_EV3_GYRO_GYRO_RATE);
set_sensor_mode_inx(sn, LEGO_EV3_GYRO_GYRO_G_AND_A);
}
}
}
int getIRDistance(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_IR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_IR) != LEGO_EV3_IR_IR_PROX)
{
set_sensor_mode_inx(sn, LEGO_EV3_IR_IR_PROX);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getIRBeaconDirection(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_IR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_IR) != LEGO_EV3_IR_IR_SEEK)
{
set_sensor_mode_inx(sn, LEGO_EV3_IR_IR_SEEK);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getIRBeaconChannelDirection(tSensor sensor, uint8_t channel)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_IR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_IR) != LEGO_EV3_IR_IR_SEEK)
{
set_sensor_mode_inx(sn, LEGO_EV3_IR_IR_SEEK);
}
switch(channel)
{
case 1: get_sensor_value0(sn, &val); break;
case 2: get_sensor_value2(sn, &val); break;
case 3: get_sensor_value4(sn, &val); break;
case 4: get_sensor_value6(sn, &val); break;
}
}
return (int)round(val);
}
int getIRBeaconStrength(tSensor sensor)
{
uint8_t sn;
float val = -128;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_IR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_IR) != LEGO_EV3_IR_IR_SEEK)
{
set_sensor_mode_inx(sn, LEGO_EV3_IR_IR_SEEK);
}
get_sensor_value1(sn, &val);
}
return (int)round(val);
}
int getIRBeaconChannelStrength(tSensor sensor, uint8_t channel)
{
uint8_t sn;
float val = -128;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_IR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_IR) != LEGO_EV3_IR_IR_SEEK)
{
set_sensor_mode_inx(sn, LEGO_EV3_IR_IR_SEEK);
}
switch(channel)
{
case 1: get_sensor_value1(sn, &val); break;
case 2: get_sensor_value3(sn, &val); break;
case 3: get_sensor_value5(sn, &val); break;
case 4: get_sensor_value7(sn, &val); break;
}
}
return (int)round(val);
}
int getIRRemoteButtons(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_IR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_IR) != LEGO_EV3_IR_IR_REMOTE)
{
set_sensor_mode_inx(sn, LEGO_EV3_IR_IR_REMOTE);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getIRRemoteChannelButtons(tSensor sensor, uint8_t channel)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_IR)
{
if(get_sensor_mode_inx_of_type(sn, LEGO_EV3_IR) != LEGO_EV3_IR_IR_REMOTE)
{
set_sensor_mode_inx(sn, LEGO_EV3_IR_IR_REMOTE);
}
switch(channel)
{
case 1: get_sensor_value0(sn, &val); break;
case 2: get_sensor_value1(sn, &val); break;
case 3: get_sensor_value2(sn, &val); break;
case 4: get_sensor_value3(sn, &val); break;
}
}
return (int)round(val);
}
int getTouchValue(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == LEGO_EV3_TOUCH)
{
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getIRSACDirection(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_IR_SEEK_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_IR_SEEK_V2) != HT_NXT_IR_SEEK_V2_AC && get_sensor_mode_inx_of_type(sn, HT_NXT_IR_SEEK_V2) != HT_NXT_IR_SEEK_V2_AC_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_IR_SEEK_V2_AC_ALL);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
void getIRSACStrength(tSensor sensor, int *d1, int *d2, int *d3, int *d4, int *d5)
{
uint8_t sn;
float s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_IR_SEEK_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_IR_SEEK_V2) != HT_NXT_IR_SEEK_V2_AC_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_IR_SEEK_V2_AC_ALL);
}
get_sensor_value1(sn, &s1);
get_sensor_value2(sn, &s2);
get_sensor_value3(sn, &s3);
get_sensor_value4(sn, &s4);
get_sensor_value5(sn, &s5);
*d1 = (int)round(s1);
*d2 = (int)round(s2);
*d3 = (int)round(s3);
*d4 = (int)round(s4);
*d5 = (int)round(s5);
}
}
int getIRSDCDirection(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_IR_SEEK_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_IR_SEEK_V2) != HT_NXT_IR_SEEK_V2_DC && get_sensor_mode_inx_of_type(sn, HT_NXT_IR_SEEK_V2) != HT_NXT_IR_SEEK_V2_DC_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_IR_SEEK_V2_DC_ALL);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
void getIRSDCStrength(tSensor sensor, int *d1, int *d2, int *d3, int *d4, int *d5)
{
uint8_t sn;
float s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_IR_SEEK_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_IR_SEEK_V2) != HT_NXT_IR_SEEK_V2_DC_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_IR_SEEK_V2_DC_ALL);
}
get_sensor_value1(sn, &s1);
get_sensor_value2(sn, &s2);
get_sensor_value3(sn, &s3);
get_sensor_value4(sn, &s4);
get_sensor_value5(sn, &s5);
*d1 = (int)round(s1);
*d2 = (int)round(s2);
*d3 = (int)round(s3);
*d4 = (int)round(s4);
*d5 = (int)round(s5);
}
}
int getHTColorName(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR) != HT_NXT_COLOR_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_ALL);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getHTColorRed(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR) != HT_NXT_COLOR_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_ALL);
}
get_sensor_value1(sn, &val);
}
return (int)round(val);
}
int getHTColorGreen(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR) != HT_NXT_COLOR_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_ALL);
}
get_sensor_value2(sn, &val);
}
return (int)round(val);
}
int getHTColorBlue(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR) != HT_NXT_COLOR_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_ALL);
}
get_sensor_value3(sn, &val);
}
return (int)round(val);
}
void getHTColorRGB(tSensor sensor, int *red, int *green, int *blue)
{
uint8_t sn;
float r = 0, g = 0, b = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR) != HT_NXT_COLOR_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_ALL);
}
get_sensor_value1(sn, &r);
get_sensor_value2(sn, &g);
get_sensor_value3(sn, &b);
*red = (int)round(r);
*green = (int)round(g);
*blue = (int)round(b);
}
}
int getHTColor2Name(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR_V2) != HT_NXT_COLOR_V2_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_V2_ALL);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getHTColor2Red(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR_V2) != HT_NXT_COLOR_V2_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_V2_ALL);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getHTColor2Green(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR_V2) != HT_NXT_COLOR_V2_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_V2_ALL);
}
get_sensor_value1(sn, &val);
}
return (int)round(val);
}
int getHTColor2Blue(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR_V2) != HT_NXT_COLOR_V2_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_V2_ALL);
}
get_sensor_value2(sn, &val);
}
return (int)round(val);
}
void getHTColor2RGB(tSensor sensor, int *red, int *green, int *blue)
{
uint8_t sn;
float r = 0, g = 0, b = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COLOR_V2)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_COLOR_V2) != HT_NXT_COLOR_V2_ALL)
{
set_sensor_mode_inx(sn, HT_NXT_COLOR_V2_ALL);
}
get_sensor_value0(sn, &r);
get_sensor_value1(sn, &g);
get_sensor_value2(sn, &b);
*red = (int)round(r);
*green = (int)round(g);
*blue = (int)round(b);
}
}
int getHTAngle(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_ANGLE)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_ANGLE) != HT_NXT_ANGLE_ANGLE)
{
set_sensor_mode_inx(sn, HT_NXT_ANGLE_ANGLE);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getHTAngleAccumulated(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_ANGLE)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_ANGLE) != HT_NXT_ANGLE_ANGLE_ACC)
{
set_sensor_mode_inx(sn, HT_NXT_ANGLE_ANGLE_ACC);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
int getHTAngleSpeed(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_ANGLE)
{
if(get_sensor_mode_inx_of_type(sn, HT_NXT_ANGLE) != HT_NXT_ANGLE_SPEED)
{
set_sensor_mode_inx(sn, HT_NXT_ANGLE_SPEED);
}
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
void resetHTAngle(tSensor sensor)
{
uint8_t sn;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_ANGLE)
{
set_sensor_command_inx(sn, HT_NXT_ANGLE_RESET);
}
}
int getHTCompassHeading(tSensor sensor)
{
uint8_t sn;
float val = 0;
if (ev3_search_sensor_plugged_in(sensor, EXT_PORT__NONE_, &sn, 0) && ev3_sensor[sn].type_inx == HT_NXT_COMPASS)
{
get_sensor_value0(sn, &val);
}
return (int)round(val);
}
/* **** SOUND **** */
void playTone(int freq, int timeMs)
{
speaker_play_tone(freq, timeMs);
}
void playImmediateTone(int freq, int timeMs)
{
speaker_play_tone(freq, timeMs);
}
void setSoundVolume(int vol)
{
speaker_set_volume(vol);
}
int getSoundVolume()
{
return speaker_get_volume();
}
/* **** TASKS **** */
void abortTimeslice()
{
task_yield();
}
void stopAllTasks()
{
task_stop_all();
}
void startTask(task (*task_func)(void*))
{
task_start(task_func);
}
void stopTask(task (*task_func)(void*))
{
task_stop(task_func);
}
/* **** TIMING **** */
void delay(unsigned long int ms)
{
if(ms == 0) return;
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000;
nanosleep(&ts, NULL);
}
void delay_us(unsigned long int us)
{
if(us == 0) return;
struct timespec ts;
ts.tv_sec = us / 1000000;
ts.tv_nsec = (us % 1000000) * 1000;
nanosleep(&ts, NULL);
}
void delay_ns(unsigned long int ns)
{
if(ns == 0) return;
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = ns;
nanosleep(&ts, NULL);
}
double sysTime()
{
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) return 0;
return (double)ts.tv_sec + ((double)ts.tv_nsec / 1000000000.0);
}
/* *** LOGGING *** */
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
void print(tLogType type, const char *_str, ...)
{
char str[512];
va_list vl;
va_start(vl, _str);
vsnprintf(str, 511, _str, vl);
va_end(vl);
char *tag;
switch(type) {
case DEBUG:
tag = "[DEBUG] ";
break;
case INFO:
tag = "[INFO] ";
break;
case WARN:
tag = ANSI_COLOR_YELLOW "[WARN] ";
break;
case ERROR:
tag = ANSI_COLOR_RED "[ERROR] " ;
break;
}
fprintf(type == ERROR ? stderr : stdout, "%s", tag);
vfprintf(type == ERROR ? stderr : stdout, str, vl);
fprintf(type == ERROR ? stderr : stdout, ANSI_COLOR_RESET);
}
void println(tLogType type, const char *_str, ...)
{
char str[512];
va_list vl;
va_start(vl, _str);
vsnprintf(str, 511, _str, vl);
va_end(vl);
char *tag;
switch(type) {
case DEBUG:
tag = "[DEBUG] ";
break;
case INFO:
tag = "[INFO] ";
break;
case WARN:
tag = ANSI_COLOR_YELLOW "[WARN] ";
break;
case ERROR:
tag = ANSI_COLOR_RED "[ERROR] " ;
break;
}
fprintf(type == ERROR ? stderr : stdout, "%s", tag);
vfprintf(type == ERROR ? stderr : stdout, str, vl);
fprintf(type == ERROR ? stderr : stdout, ANSI_COLOR_RESET "\n");
}
| 2.390625 | 2 |
2024-11-18T19:02:56.764851+00:00
| 2020-10-04T07:10:45 |
ade4c6c9b2d91d0614affd93de93b797266fbaa5
|
{
"blob_id": "ade4c6c9b2d91d0614affd93de93b797266fbaa5",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-21T05:58:05",
"content_id": "95aa6476e89dc0383baf5db889217d1b40147ec9",
"detected_licenses": [
"MIT"
],
"directory_id": "b1e1e680ba49c74be432ca314e1992ef982c68fc",
"extension": "c",
"filename": "madt.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": 1724,
"license": "MIT",
"license_type": "permissive",
"path": "/acpi/madt.c",
"provenance": "stackv2-0058.json.gz:171482",
"repo_name": "shreyaslad/slate",
"revision_date": "2020-10-04T07:10:45",
"revision_id": "3c237a449209d0520b677766ee3eea93803fedb1",
"snapshot_id": "ceef0ad45804e4596da92c0b111e3f7a1cd76cc5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shreyaslad/slate/3c237a449209d0520b677766ee3eea93803fedb1/acpi/madt.c",
"visit_date": "2023-03-17T16:14:11.594124"
}
|
stackv2
|
#include <acpi/madt.h>
#undef __MODULE__
#define __MODULE__ "madt"
struct madt_t* madt;
struct madt_lapic_t** lapics;
int lapic_cnt;
struct madt_ioapic_t** ioapics;
int ioapic_cnt;
struct madt_iso_t** isos;
int iso_cnt;
struct madt_nmi_t** nmis;
int nmi_cnt;
void init_madt() {
if ((madt = find_sdt("APIC", 0))) {
TRACE("APIC Configuration:\n");
lapics = kmalloc(ACPI_MAX_TBL_CNT) + HIGH_VMA;
ioapics = kmalloc(ACPI_MAX_TBL_CNT) + HIGH_VMA;
isos = kmalloc(ACPI_MAX_TBL_CNT) + HIGH_VMA;
nmis = kmalloc(ACPI_MAX_TBL_CNT) + HIGH_VMA;
for (uint8_t* madt_ptr = (uint8_t *)(&madt->madt_entries_begin);
(size_t)madt_ptr < (size_t)madt + madt->sdt.len;
madt_ptr += *(madt_ptr + 1)) {
switch (*(madt_ptr)) {
case 0:
TRACE("\tLAPIC #%u\n", lapic_cnt);
lapics[lapic_cnt++] = (struct madt_lapic_t *)madt_ptr;
break;
case 1:
TRACE("\tIOAPIC #%u\n", ioapic_cnt);
ioapics[ioapic_cnt++] = (struct madt_ioapic_t *)madt_ptr;
break;
case 2:
TRACE("\tISO #%u\n", iso_cnt);
isos[iso_cnt++] = (struct madt_iso_t *)madt_ptr;
break;
case 4:
TRACE("\tNMI #%u\n", nmi_cnt);
nmis[nmi_cnt++] = (struct madt_nmi_t *)madt_ptr;
break;
default:
WARN("\tNothing found\n");
break;
}
}
}
}
| 2.0625 | 2 |
2024-11-18T19:02:57.181771+00:00
| 2022-01-07T19:27:27 |
fd05065225d54fa22c38795290a8a747ea35d3d4
|
{
"blob_id": "fd05065225d54fa22c38795290a8a747ea35d3d4",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-07T19:27:27",
"content_id": "15e34d54bd66d3284094b493b07941087f03d0b5",
"detected_licenses": [
"MIT"
],
"directory_id": "80c7cd0763a2e49cf716b5e1d190492289595614",
"extension": "c",
"filename": "checked_array_types.c",
"fork_events_count": 0,
"gha_created_at": "2020-03-04T20:05:37",
"gha_event_created_at": "2021-06-25T20:14:25",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 244993072,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8149,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/parsing/checked_array_types.c",
"provenance": "stackv2-0058.json.gz:171610",
"repo_name": "correctcomputation/checkedc",
"revision_date": "2022-01-07T19:27:27",
"revision_id": "36a89b3722caa381405d939c70708e610cabf0de",
"snapshot_id": "11402f92ad5cd0504af4e025b6ccbfa343c0c58d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/correctcomputation/checkedc/36a89b3722caa381405d939c70708e610cabf0de/tests/parsing/checked_array_types.c",
"visit_date": "2023-09-03T23:43:01.217120"
}
|
stackv2
|
// Feature tests of parsing new Checked C checked array type
//
// * Test that checked array types can be used as parameter types, local
// variable types, structure member types, in typedefs, and as arguments
// to operators that take types. In C, return types for functions
// cannot be array types.
// * Test parsing of array types and function types combined with checked
// array types.
//
// The following lines are for the LLVM test harness:
//
// RUN: %clang_cc1 -verify -Wno-unused-value %s
// expected-no-diagnostics
//
// parameter have new checked array types
//
#include <stdchecked.h>
extern void f1(int a checked[], int y) {
}
extern void f2(int a checked[5], int y) {
}
extern void f3(const int a checked[5], int y) {
}
extern void f4(int a checked[][5], int y) {
}
extern void f5(int a checked[5][5], int y) {
}
// not necessary, but syntactically legal
extern void f6(int a checked[]checked[5], int y) {
}
// not necessary, but syntactically legal
extern void f7(int a checked[5]checked[5], int y) {
}
//
// Null-terminated array versions
//
extern void f10(int a nt_checked[], int y) {
}
extern void f11(int a nt_checked[5], int y) {
}
extern void f12(const int a nt_checked[5], int y) {
}
// Arrays of null-terminated checked arrays are allowed.
extern void f13(int a checked[]nt_checked[5], int y) {
}
extern void f14(int a checked[5]nt_checked[5], int y) {
}
//
// Second parameter is a new pointer type
//
extern void g1(int y, int a checked[]) {
}
extern void g2(int y, int a checked[5]) {
}
extern void g3(int y, const int a checked[5]) {
}
extern void g4(int y, int a checked[][5]) {
}
extern void g5(int y, int a checked[5][5]) {
}
// not necessary, but syntactically legal
extern void g6(int y, int a checked[]checked[5]) {
}
// not necessary, but syntactically legal
extern void g7(int y, int a checked[5]checked[5]) {
}
//
// Null-terminated checked array versions.
//
extern void g10(int y, int a nt_checked[]) {
}
extern void g11(int y, int a nt_checked[5]) {
}
extern void g12(int y, const int a nt_checked[5]) {
}
// Arrays of null-terminated checked arrays are allowed.
extern void g13(int y, int a checked[]nt_checked[5]) {
}
extern void g14(int y, int a checked[5]nt_checked[5]) {
}
//
// Local variables with pointer types
//
extern void k1(int y)
{
int arr1 checked[] = { 0, 1 , 2 };
int arr2 checked[5];
int arr3 checked[][5] = { { 1 }, {2 } };
int arr4 checked[5][5];
int arr5 nt_checked[] = { 0, 1, 2, 0 };
int arr6 nt_checked[5];
}
//
// Struct member with fixed-sized array types
//
struct Vector {
int data checked[5];
int len;
};
extern int Multiply(struct Vector vec1, struct Vector vec2) {
if (vec1.len != vec2.len) {
return 1;
}
for (int i = 0; i < vec1.len; i++) {
vec1.data[i] *= vec2.data[i];
}
return 0;
}
extern int Multiply2(ptr<struct Vector> vec1p, ptr<struct Vector> vec2p) {
if (vec1p->len != vec2p->len) {
return 1;
}
for (int i = 0; i < vec1p->len; i++) {
vec1p->data[i] *= vec2p->data[i];
}
return 0;
}
//
// Declaring checked arrays of function pointers
//
struct FixedLengthString {
char str nt_checked[5];
};
int (*array_of_unchecked_ptr_to_func checked[10])(int x, int y);
int (*nullterm_array_of_unchecked_ptr_to_func nt_checked[10])(int x, int y);
extern int (*incomplete_array_of_unchecked_ptr_to_func checked[])(int x, int y);
extern int (*nullterm_incomplete_array_of_unchecked_ptr_to_func nt_checked[])(int x, int y);
ptr<int(int x, int y)> array_of_ptr_to_func checked[10];
extern ptr<int(int x, int y)> array_of_ptr_to_func checked[];
ptr<int(int x checked[10], int y)> aptr2 checked[10];
ptr<int(int x nt_checked[10], int y)> aptr3 nt_checked[10];
//
// Declaring pointers to arrays and arrays of pointers
//
int (*unchecked_ptr_to_array)checked[5];
ptr<int checked[5]> ptr_to_array;
ptr<int nt_checked[5]> ptr_to_nullterm_array;
array_ptr<int checked[5]> array_ptr_to_array;
array_ptr<int nt_checked[5]> array_ptr_to_nullterm_array;
int(*unchecked_ptr_to_incomplete_array)checked[];
ptr<int checked[]> ptr_to_incomplete_array;
ptr<int nt_checked[]> ptr_to_nullterm_incomplete_array;
array_ptr<int checked[]> array_ptr_to_incomplete_array;
array_ptr<int nt_checked[]> array_ptr_to_nullterm_incomplete_array;
// Declaring checked arrays of pointers
int *array_of_unchecked_ptrs checked[5];
int *nullterm_array_of_unchecked_ptrs nt_checked[5];
ptr<int> array_of_ptrs checked[5];
ptr<int> nullterm_array_of_ptrs nt_checked[5];
array_ptr<int> array_of_array_ptrs checked[5];
array_ptr<int> nullterm_array_of_array_ptrs nt_checked[5];
nt_array_ptr<int> array_of_nullterm_array_ptrs checked[5];
nt_array_ptr<int> nullterm_array_of_nullterm_array_ptrs nt_checked[5];
// Declare an unchecked pointer to checked arrays of pointers
int *(*uncheckedptr_to_array_of_unchecked_ptrs) checked[5];
ptr<int>(*unchecked_ptr_to_array_of_ptrs) checked[5];
array_ptr<int>(*unchecked_ptr_to_array_of_array_ptrs) checked[5];
array_ptr<int>(*unchecked_ptr_to_null_term_array_of_array_ptrs) nt_checked[5];
// Declare ptr to checked arrays of pointers
ptr<int *checked[5]> ptr_to_array_of_unchecked_ptrs;
ptr<ptr<int> checked[5]> ptr_to_array_of_ptrs;
ptr<array_ptr<int> checked[5]> ptr_to_array_of_array_ptrs;
ptr<array_ptr<int> nt_checked[5]> ptr_to_nullterm_array_of_array_ptrs;
ptr<nt_array_ptr<int> nt_checked[5]> ptr_to_nullterm_array_of_nullterm_array_ptrs;
// Declare ptr to a checked array of function pointers
ptr<int (*checked[5])(int x, int y)> ptr_to_array_of_unchecked_func_ptrs;
ptr<ptr<int (int x, int y)>checked [5]> ptr_to_array_of_checked_func_ptrs;
ptr<ptr<int (int x, int y)>nt_checked [5]> ptr_to_nullterm_array_of_checked_func_ptrs;
// Make parameter and return types be ptrs too.
ptr<ptr<ptr<int>(ptr<int> x, ptr<int> y)>checked[5]>
ptr_to_array_of_checked_func_ptrs_with_ptr_parameters;
ptr<ptr<ptr<int> (ptr<int> x, ptr<int> y)>nt_checked[5]>
ptr_to_nullterm_array_of_checked_func_ptrs_with_ptr_parameters;
//
// Typedefs using checked pointer types
//
typedef int arr_ty[5];
typedef int incomplete_arr_ty[];
typedef int checked_arr_ty checked[5];
typedef int incomplete_checked_array_ty checked[];
typedef int nullterm_checked_arr_ty nt_checked[5];
typedef int nullterm_incomplete_checked_array_ty nt_checked[];
//
// Operators that take types
//
void parse_operators_with_types(void) {
int s1 = sizeof(int checked[10]);
int s2 = sizeof(ptr<int checked[5]>);
int s3 = sizeof(array_ptr<int checked[5]>);
int s4 = sizeof(ptr<int>checked[5]);
int s5 = sizeof(array_ptr<int> checked[5]);
// null-terminated versions.
int s6 = sizeof(int nt_checked[10]);
int s7 = sizeof(ptr<int nt_checked[5]>);
int s8 = sizeof(array_ptr<int nt_checked[5]>);
int s9 = sizeof(ptr<int> nt_checked[5]);
int s10 = sizeof(array_ptr<int> nt_checked[5]);
int s20 = _Alignof(int checked[10]);
int s21 = _Alignof(ptr<int checked[5]>);
int s22 = _Alignof(array_ptr<int checked[5]>);
int s23 = _Alignof(ptr<int> checked[5]);
int s24 = _Alignof(array_ptr<int>checked[5]);
int s25 = _Alignof(nt_array_ptr<int>checked[5]);
// null-terminated versions.
int s26 = _Alignof(int nt_checked[10]);
int s27 = _Alignof(ptr<int nt_checked[5]>);
int s28 = _Alignof(array_ptr<int nt_checked[5]>);
int s29 = _Alignof(ptr<int> nt_checked[5]);
int s30 = _Alignof(array_ptr<int> nt_checked[5]);
int s31 = _Alignof(nt_array_ptr<int> nt_checked[5]);
// Test parsing of some cast operations that should pass checking
// of bounds declarations
int x = 0;
int arr checked[5];
ptr<int> px = (ptr<int>) &x;
array_ptr<int> pax = (array_ptr<int>) &x;
pax = arr;
// ptr to array type
ptr<int checked[5]> parr = 0;
parr = &arr;
parr = (int (*)checked[5]) &arr;
parr = (int (*)checked[5]) ((int (*)checked[]) &arr);
// ptr to function type
ptr<int (int x, int y)> pfunc = (ptr<int (int x, int y)>) 0;
ptr<ptr<int (int x, int y)>checked [5]> ptr_to_pfunc_arr = (ptr<ptr<int (int x, int y)>checked[5]>) 0;
}
| 2.78125 | 3 |
2024-11-18T19:02:57.417986+00:00
| 2019-06-25T08:31:01 |
4ab1ed92d567a4ebd40c2eb8be21bf9b7e5a8f77
|
{
"blob_id": "4ab1ed92d567a4ebd40c2eb8be21bf9b7e5a8f77",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-25T08:31:01",
"content_id": "0ca73f62069a41557b3e7a11e8e4051670b4c171",
"detected_licenses": [
"MIT"
],
"directory_id": "335931617ff83c8019eca5ab4ff7bb4cb09933f1",
"extension": "h",
"filename": "bstree.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 178547197,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1056,
"license": "MIT",
"license_type": "permissive",
"path": "/binary_search_tree/bstree.h",
"provenance": "stackv2-0058.json.gz:171998",
"repo_name": "weezybusy/Data-Structures-in-C",
"revision_date": "2019-06-25T08:31:01",
"revision_id": "a8e9719d4211fd5e8b1dd5b07442dd5b3ae4aea4",
"snapshot_id": "c739c1ec638d09f70f89a8fc35a5a8b0619ef9a9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/weezybusy/Data-Structures-in-C/a8e9719d4211fd5e8b1dd5b07442dd5b3ae4aea4/binary_search_tree/bstree.h",
"visit_date": "2020-05-03T09:14:21.672522"
}
|
stackv2
|
#ifndef BSTREE_H
#define BSTREE_H
#include "btree.h"
/* Define balance factors for AVL trees. ---------------------------------- */
#define AVL_LEFT_HEAVY 1
#define AVL_BALANCED 0
#define AVL_RIGHT_HEAVY -1
/* Define a structure for nodes in AVL trees. ----------------------------- */
typedef struct _avlnode {
void *data;
int hidden;
int factor;
} avlnode_t;
/* Implement binary search trees as binary trees. ------------------------- */
typedef btree_t bstree_t;
/* Public Interface. ------------------------------------------------------ */
void bstree_init(bstree_t *tree,
int (*compare)(const void *key1, const void *key2),
void (*destroy)(void *data));
void bstree_destroy(bstree_t *tree);
int bstree_insert(bstree_t *tree, const void *data);
int bstree_remove(bstree_t *tree, const void *data);
int bstree_lookup(bstree_t *tree, void **data);
/* Macros. ---------------------------------------------------------------- */
#define bstree_size(tree) ((tree)->size)
#endif
| 2.0625 | 2 |
2024-11-18T19:02:57.609444+00:00
| 2020-10-10T14:46:24 |
995b6ebb6215bfa882db35a6b447fb8f34adff72
|
{
"blob_id": "995b6ebb6215bfa882db35a6b447fb8f34adff72",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-10T14:46:24",
"content_id": "bde9972dace3b6bd921200b9105a55aeaf8a910e",
"detected_licenses": [
"MIT"
],
"directory_id": "3672a4ea09de21a893bad25646de8b59e2c88370",
"extension": "h",
"filename": "tvm_memory.h",
"fork_events_count": 0,
"gha_created_at": "2020-08-17T23:11:07",
"gha_event_created_at": "2020-08-17T23:11:07",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 288305346,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1560,
"license": "MIT",
"license_type": "permissive",
"path": "/include/tvm/tvm_memory.h",
"provenance": "stackv2-0058.json.gz:172257",
"repo_name": "miwest929/tinyvm",
"revision_date": "2020-10-10T14:46:24",
"revision_id": "fc636033df1defdfab562631828dec60e9f3d197",
"snapshot_id": "eb54a43014ceea46d3e2083a59bba50a43cc1778",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/miwest929/tinyvm/fc636033df1defdfab562631828dec60e9f3d197/include/tvm/tvm_memory.h",
"visit_date": "2023-02-19T22:32:12.290833"
}
|
stackv2
|
#ifndef TVM_MEMORY_H_
#define TVM_MEMORY_H_
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#define MIN_MEMORY_SIZE (64 * 1024 * 1024) /* 64 MB */
#define EBP 0x7
#define ESP 0x6
#define GET_VALUE(v) (v.value)
#define GET_PTR_REF(v) (v.refValue)
typedef unsigned int uint;
union tvm_reg_u {
int32_t i32;
int32_t *i32_ptr;
union {
int16_t h;
int16_t l;
} i16;
};
union tvm_local_var_value_type {
int value;
int* refValue;
};
struct tvm_single_local_var {
union tvm_local_var_value_type variable;
bool isInUse;
};
struct tvm_objs {
int* ref;
uint count;
bool reachable;
struct tvm_objs* next;
};
// a indexed map into the local variables
// NOTE: The local var references get destroyed along with the stack frame
struct tvm_local_vars {
struct tvm_single_local_var values[256];
int count;
};
struct tvm_mem {
/*
* Similar to x86 FLAGS register
*
* 0x1 EQUAL
* 0x2 GREATER
*
*/
int FLAGS;
int remainder;
void *mem_space;
int mem_space_size;
union tvm_reg_u *registers;
struct tvm_local_vars local_vars;
struct tvm_objs *objs; // linked list of allocated objects
};
struct tvm_mem *tvm_mem_create(size_t size);
void tvm_mem_destroy(struct tvm_mem *mem);
union tvm_local_var_value_type tvm_mem_get_local_var_value(struct tvm_mem *m, uint localIndex);
void tvm_mem_set_local_var_value(struct tvm_mem *m, uint localIndex, union tvm_local_var_value_type value);
int* tvm_mem_allocate(struct tvm_mem *m, size_t size);
void tvm_register_obj(struct tvm_mem *m, int* ref, size_t size);
#endif
| 2.515625 | 3 |
2024-11-18T19:02:57.705837+00:00
| 2018-09-22T02:49:45 |
a9e36ec8bffacb9698824a43419603ee6a55daaa
|
{
"blob_id": "a9e36ec8bffacb9698824a43419603ee6a55daaa",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-22T02:49:45",
"content_id": "302e26bef44647a135505b164b390eb2b9f83061",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "381d5fa396f8bd378bb834c08816e6d6923d03b7",
"extension": "c",
"filename": "filter.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 75907036,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7059,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/filter.c",
"provenance": "stackv2-0058.json.gz:172385",
"repo_name": "kalamay/crux",
"revision_date": "2018-09-22T02:49:45",
"revision_id": "9a7c5f2ff337a6af005cd3979a254b6606bb9637",
"snapshot_id": "08290aad4f37fc1f677e84b461b5b4693cf40452",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kalamay/crux/9a7c5f2ff337a6af005cd3979a254b6606bb9637/src/filter.c",
"visit_date": "2021-03-19T14:29:10.798242"
}
|
stackv2
|
#include "../include/crux/filter.h"
#include "../include/crux/err.h"
#include <stdlib.h>
#include <string.h>
#include <stdatomic.h>
#include <hs/hs.h>
#define MAX 256
struct xmatch
{
const struct xfilter *filter;
const char *value;
size_t valuelen;
int id;
};
struct xfilter
{
enum xfilter_mode mode;
int count;
atomic_int ref;
struct xfilter *clone;
hs_scratch_t *key_scratch;
hs_scratch_t *value_scratch;
hs_database_t *key;
union {
hs_database_t *values[0];
struct xfilter *chain[0];
};
};
static inline struct xfilter *
ref(struct xfilter *f)
{
atomic_fetch_add(&f->ref, 1);
return f;
}
static inline bool
unref(struct xfilter *f)
{
return atomic_fetch_sub(&f->ref, 1) == 1;
}
#define ALLOC(_mode, _count) __extension__ ({ \
struct xfilter *f = calloc(1, sizeof(*f) + sizeof(f->values[0])*_count); \
if (f == NULL) { return xerrno; } \
f->mode = _mode; \
f->count = _count; \
f->ref = 1; \
f; \
})
#define ISBASE(_mode) \
(_mode == XFILTER_ACCEPT || _mode == XFILTER_REJECT)
#define ISCHAIN(_mode) \
(_mode == XFILTER_CHAIN_AND || _mode == XFILTER_CHAIN_OR)
int
xfilter_new(struct xfilter **fp,
const struct xfilter_expr *exp, size_t count,
enum xfilter_mode mode,
struct xfilter_err *err)
{
if (count == 0 || count > MAX || !ISBASE(mode)) {
return xerr_sys(EINVAL);
}
struct xfilter *f = ALLOC(mode, count);
const char *expr[MAX];
unsigned flags[MAX];
unsigned ids[MAX];
hs_compile_error_t *e = NULL;
hs_error_t ec;
for (size_t i = 0; i < count; i++) {
expr[i] = exp[i].key;
flags[i] = exp[i].flags | HS_FLAG_SINGLEMATCH;
ids[i] = (unsigned)i + 1;
}
ec = hs_compile_multi(expr, flags, ids, count, HS_MODE_BLOCK, NULL, &f->key, &e);
if (ec != HS_SUCCESS) { goto error; }
ec = hs_alloc_scratch(f->key, &f->key_scratch);
if (ec != HS_SUCCESS) { goto error; }
for (size_t i = 0; i < count; i++) {
if (exp[i].value == NULL) { continue; }
ec = hs_compile(exp[i].value, exp[i].flags, HS_MODE_BLOCK, NULL, &f->values[i], &e);
if (ec != HS_SUCCESS) { goto error; }
ec = hs_alloc_scratch(f->values[i], &f->value_scratch);
if (ec != HS_SUCCESS) { goto error; }
}
*fp = f;
return 0;
error:
err->message = strdup(e->message);
err->index = e->expression;
hs_free_compile_error(e);
xfilter_free(&f);
return xerr_sys(EINVAL);
}
int
xfilter_clone(struct xfilter **fp, struct xfilter *src)
{
int count = src->count;
enum xfilter_mode mode = src->mode;
struct xfilter *f = ALLOC(mode, count);
int rc = xerr_sys(EINVAL);
if (ISCHAIN(mode)) {
for (int i = 0; i < count; i++) {
rc = xfilter_clone(&f->chain[i], src->chain[i]);
if (rc < 0) { goto error; }
}
}
else {
f->clone = ref(src);
hs_error_t ec;
ec = hs_clone_scratch(src->key_scratch, &f->key_scratch);
if (ec != HS_SUCCESS) { goto error; }
if (src->value_scratch) {
ec = hs_clone_scratch(src->value_scratch, &f->value_scratch);
if (ec != HS_SUCCESS) { goto error; }
}
f->key = src->key;
for (int i = 0; i < count; i++) {
f->values[i] = src->values[i];
}
}
*fp = f;
return 0;
error:
xfilter_free(&f);
return rc;
}
struct xfilter *
xfilter_ref(struct xfilter *f)
{
return f ? ref(f) : NULL;
}
int
xfilter_chain(struct xfilter **fp,
struct xfilter **src, size_t srclen,
enum xfilter_mode mode)
{
if (srclen == 0 || srclen > MAX || !ISCHAIN(mode)) {
return xerr_sys(EINVAL);
}
struct xfilter *f = ALLOC(mode, srclen);
for (size_t i = 0; i < srclen; i++) {
f->chain[i] = ref(src[i]);
}
*fp = f;
return 0;
}
void
xfilter_free(struct xfilter **fp)
{
struct xfilter *f = *fp;
if (f == NULL) { return; }
*fp = NULL;
if (unref(f)) {
if (f->key_scratch) { hs_free_scratch(f->key_scratch); }
if (f->value_scratch) { hs_free_scratch(f->value_scratch); }
if (ISCHAIN(f->mode)) {
for (int i = 0; i < f->count; i++) {
xfilter_free(&f->chain[i]);
}
}
else if (f->clone) {
xfilter_free(&f->clone);
}
else {
if (f->key) { hs_free_database(f->key); }
for (int i = 0; i < f->count; i++) {
if (f->values[i]) { hs_free_database(f->values[i]); }
}
}
free(f);
}
}
static int
match(unsigned int id,
unsigned long long from,
unsigned long long to,
unsigned int flags,
void *context)
{
(void)from;
(void)to;
(void)flags;
*(int *)context = (int)id;
return 0;
}
static int
match_full(unsigned int id,
unsigned long long from,
unsigned long long to,
unsigned int flags,
void *context)
{
(void)from;
(void)to;
(void)flags;
struct xmatch *m = context;
const struct xfilter *f = m->filter;
hs_database_t *db = f->values[id-1];
if (db) {
int sub = -1;
hs_scan(db, m->value, m->valuelen, 0, f->value_scratch, match, &sub);
m->id = sub == 0 ? (int)id : -1;
}
else {
m->id = (int)id;
}
return 0;
}
int
xfilter_key(const struct xfilter *f, const char *key, size_t keylen)
{
enum xfilter_mode mode = f->mode;
if (xunlikely(ISCHAIN(mode))) {
bool or = mode == XFILTER_CHAIN_OR;
int count = f->count;
for (int i = 0; i < count; i++) {
int rc = xfilter_key(f->chain[i], key, keylen);
if (or == (rc >= 0)) { return or - 1; }
}
return !or - 1;
}
int id = -1;
hs_scan(f->key, key, keylen, 0, f->key_scratch, match, &id);
if (id == -1) {
return mode == XFILTER_ACCEPT ? -1 : 0;
}
return mode == XFILTER_ACCEPT ? id : -1;
}
int
xfilter(const struct xfilter *f,
const char *key, size_t keylen,
const char *value, size_t valuelen)
{
enum xfilter_mode mode = f->mode;
if (xunlikely(ISCHAIN(mode))) {
bool or = mode == XFILTER_CHAIN_OR;
int count = f->count;
for (int i = 0; i < count; i++) {
int rc = xfilter(f->chain[i], key, keylen, value, valuelen);
if (or == (rc >= 0)) { return or - 1; }
}
return !or - 1;
}
struct xmatch m = { f, value, valuelen, -1 };
hs_scan(f->key, key, keylen, 0, f->key_scratch, match_full, &m);
if (m.id == -1) {
return mode == XFILTER_ACCEPT ? -1 : 0;
}
return mode == XFILTER_ACCEPT ? m.id : -1;
}
static void
print(const struct xfilter *f, FILE *out, int depth)
{
for (int i = 0; i < depth; i++) {
fwrite(" ", 1, 2, out);
}
if (f == NULL) {
fprintf(out, "<crux:filter:(null)>\n");
return;
}
const char *end = "INVALID>\n";
switch (f->mode) {
case XFILTER_ACCEPT: end = "ACCEPT"; break;
case XFILTER_REJECT: end = "REJECT"; break;
case XFILTER_CHAIN_AND: end = "CHAIN AND"; break;
case XFILTER_CHAIN_OR: end = "CHAIN OR"; break;
}
fprintf(out, "<crux:filter:%p count=%d ref=%d %s%s>",
(void *)f, f->count, f->ref, f->clone ? "CLONE " : "", end);
struct xfilter *const *chld;
int nchld = 0;
if (ISCHAIN(f->mode)) {
chld = f->chain;
nchld = f->count;
}
else if (f->clone) {
chld = &f->clone;
nchld = 1;
}
if (nchld > 0) {
fprintf(out, " {\n");
for (int i = 0; i < nchld; i++) {
print(chld[i], out, depth+1);
}
for (int i = 0; i < depth; i++) {
fwrite(" ", 1, 2, out);
}
fprintf(out, "}\n");
}
else {
fprintf(out, "\n");
}
}
void
xfilter_print(const struct xfilter *f, FILE *out)
{
if (out == NULL) { out = stdout; }
print(f, out, 0);
}
| 2.421875 | 2 |
2024-11-18T19:02:57.930464+00:00
| 2011-02-07T04:06:16 |
9949436a0c91c0b99d2b552548cc6d273e0c760b
|
{
"blob_id": "9949436a0c91c0b99d2b552548cc6d273e0c760b",
"branch_name": "refs/heads/master",
"committer_date": "2011-02-07T04:35:00",
"content_id": "6418d833bfcd6126c786f37c4e5b28fbac5a70c3",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "4a153fcbe64201ec3b8c6637181cfb5132e62f20",
"extension": "c",
"filename": "examples_run.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1352988,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6460,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/tools/ccanlint/tests/examples_run.c",
"provenance": "stackv2-0058.json.gz:172643",
"repo_name": "stewartsmith/ccan",
"revision_date": "2011-02-07T04:06:16",
"revision_id": "59d2b90f59df57007c97cd8f8dc3db9e24781e06",
"snapshot_id": "fbdbfa0844c7a669cda8c810c5d292c94b0b8e30",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/stewartsmith/ccan/59d2b90f59df57007c97cd8f8dc3db9e24781e06/tools/ccanlint/tests/examples_run.c",
"visit_date": "2016-09-05T18:13:48.259668"
}
|
stackv2
|
#include <tools/ccanlint/ccanlint.h>
#include <tools/tools.h>
#include <ccan/talloc/talloc.h>
#include <ccan/foreach/foreach.h>
#include <ccan/str/str.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <assert.h>
static const char *can_run(struct manifest *m)
{
struct list_head *list;
if (safe_mode)
return "Safe mode enabled";
foreach_ptr(list, &m->examples, &m->mangled_examples)
if (!list_empty(list))
return NULL;
return "No examples";
}
/* Very dumb scanner, allocates %s-strings. */
static bool scan_forv(const void *ctx,
const char *input, const char *fmt, va_list *args)
{
va_list ap;
bool ret;
if (input[0] == '\0' || fmt[0] == '\0')
return input[0] == fmt[0];
va_copy(ap, *args);
if (isspace(fmt[0])) {
/* One format space can swallow many input spaces */
ret = false;
while (isspace(input[0])) {
if (scan_forv(ctx, ++input, fmt+1, &ap)) {
ret = true;
break;
}
}
} else if (fmt[0] != '%') {
if (toupper(input[0]) != toupper(fmt[0]))
ret = false;
else
ret = scan_forv(ctx, input+1, fmt+1, &ap);
} else {
char **p = va_arg(ap, char **);
unsigned int len;
ret = false;
assert(fmt[1] == 's');
for (len = 1; input[len-1]; len++) {
ret = scan_forv(ctx, input + len, fmt+2, &ap);
if (ret) {
*p = talloc_strndup(ctx, input, len);
ret = true;
break;
}
}
}
va_end(ap);
return ret;
}
static bool scan_for(const void *ctx, const char *input, const char *fmt, ...)
{
bool ret;
va_list ap;
va_start(ap, fmt);
ret = scan_forv(ctx, input, fmt, &ap);
va_end(ap);
return ret;
}
static char *find_expect(struct ccan_file *file,
char **lines, char **input, bool *exact,
unsigned *line)
{
char *expect;
const char *fmt;
for (; lines[*line]; (*line)++) {
char *p = lines[*line] + strspn(lines[*line], " \t");
if (!strstarts(p, "//"))
continue;
p += strspn(p, "/ ");
foreach_ptr(fmt,
"given '%s', outputs '%s'",
"given '%s' outputs '%s'",
"given \"%s\", outputs \"%s\"",
"given \"%s\" outputs \"%s\"") {
if (scan_for(file, p, fmt, input, &expect)) {
*exact = true;
return expect;
}
}
foreach_ptr(fmt,
"given '%s', output contains '%s'",
"given '%s' output contains '%s'",
"given \"%s\", output contains \"%s\"",
"given \"%s\" output contains \"%s\"") {
if (scan_for(file, p, fmt, input, &expect)) {
*exact = false;
return expect;
}
}
foreach_ptr(fmt, "outputs '%s'", "outputs \"%s\"") {
if (scan_for(file, p, fmt, &expect)) {
*input = "";
*exact = true;
return expect;
}
}
foreach_ptr(fmt,
"given '%s', output contains '%s'",
"given '%s' output contains '%s'",
"given \"%s\", output contains \"%s\"",
"given \"%s\" output contains \"%s\"") {
if (scan_for(file, p, fmt, input, &expect)) {
*exact = false;
return expect;
}
}
/* Unquoted versions... we can get this wrong! */
foreach_ptr(fmt,
"given %s, outputs '%s'",
"given '%s', outputs %s",
"given %s, outputs \"%s\"",
"given \"%s\", outputs %s",
"given %s, outputs %s",
"given %s outputs '%s'",
"given '%s' outputs %s",
"given %s outputs \"%s\"",
"given \"%s\" outputs %s",
"given %s outputs %s") {
if (scan_for(file, p, fmt, input, &expect)) {
*exact = true;
return expect;
}
}
foreach_ptr(fmt,
"given %s, output contains '%s'",
"given '%s', output contains %s",
"given %s, output contains \"%s\"",
"given \"%s\", output contains %s",
"given %s, output contains %s",
"given %s output contains '%s'",
"given '%s' output contains %s",
"given %s output contains \"%s\"",
"given \"%s\" output contains %s",
"given %s output contains %s") {
if (scan_for(file, p, fmt, input, &expect)) {
*exact = false;
return expect;
}
}
foreach_ptr(fmt,
"outputs '%s'",
"outputs \"%s\"",
"outputs %s") {
if (scan_for(file, p, fmt, &expect)) {
*input = "";
*exact = true;
return expect;
}
}
foreach_ptr(fmt,
"output contains '%s'",
"output contains \"%s\"",
"output contains %s") {
if (scan_for(file, p, fmt, &expect)) {
*input = "";
*exact = false;
return expect;
}
}
}
return NULL;
}
static char *trim(char *string)
{
while (strends(string, "\n"))
string[strlen(string)-1] = '\0';
return string;
}
static char *unexpected(struct ccan_file *i, const char *input,
const char *expect, bool exact)
{
char *output, *cmd;
bool ok;
unsigned int default_time = default_timeout_ms;
cmd = talloc_asprintf(i, "echo '%s' | %s %s",
input, i->compiled, input);
output = run_with_timeout(i, cmd, &ok, &default_time);
if (!ok)
return talloc_asprintf(i, "Exited with non-zero status\n");
if (exact) {
if (streq(output, expect) || streq(trim(output), expect))
return NULL;
} else {
if (strstr(output, expect))
return NULL;
}
return output;
}
static void run_examples(struct manifest *m, bool keep,
unsigned int *timeleft, struct score *score)
{
struct ccan_file *i;
struct list_head *list;
score->total = 0;
score->pass = true;
foreach_ptr(list, &m->examples, &m->mangled_examples) {
list_for_each(list, i, list) {
char **lines, *expect, *input, *output;
unsigned int linenum = 0;
bool exact;
lines = get_ccan_file_lines(i);
for (expect = find_expect(i, lines, &input, &exact,
&linenum);
expect;
linenum++,
expect = find_expect(i, lines, &input,
&exact, &linenum)) {
char *err;
if (i->compiled == NULL)
continue;
score->total++;
output = unexpected(i, input, expect, exact);
if (!output) {
score->score++;
continue;
}
err = talloc_asprintf(score,
"output '%s' didn't"
" %s '%s'\n",
output,
exact
? "match" : "contain",
expect);
score_file_error(score, i, linenum+1, err);
score->pass = false;
}
}
}
}
struct ccanlint examples_run = {
.key = "examples_run",
.name = "Module examples with expected output give that output",
.check = run_examples,
.can_run = can_run,
.needs = "examples_compile"
};
REGISTER_TEST(examples_run);
| 2.28125 | 2 |
2024-11-18T19:02:57.981023+00:00
| 2015-09-07T13:13:08 |
390b54de7638a20ff95b4eb4040639d91c70e1d0
|
{
"blob_id": "390b54de7638a20ff95b4eb4040639d91c70e1d0",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-07T13:13:08",
"content_id": "d29ea46da33bb50a56dfcd94f4d0b3c7a9d0f9ed",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7c6fa1516443fcef24d64747f92c8832531aaf69",
"extension": "c",
"filename": "list.c",
"fork_events_count": 0,
"gha_created_at": "2015-09-08T04:14:17",
"gha_event_created_at": "2015-09-08T04:14:17",
"gha_language": null,
"gha_license_id": null,
"github_id": 42089614,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 463,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/ds/list.c",
"provenance": "stackv2-0058.json.gz:172773",
"repo_name": "gitter-badger/c",
"revision_date": "2015-09-07T13:13:08",
"revision_id": "fa6ff906617d93c3240906dbc2664666818c536f",
"snapshot_id": "f10dae5aa1210fe6fa15361b847b33ee403bee2e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gitter-badger/c/fa6ff906617d93c3240906dbc2664666818c536f/src/ds/list.c",
"visit_date": "2021-01-15T17:07:42.173475"
}
|
stackv2
|
#include <u.h>
#include <gc/gc.h>
#include "ds.h"
List *
list()
{
List *l;
l = gcmalloc(sizeof(List));
return l;
}
void
listappend(List *l, void *v)
{
ListEnt *e, *ne;
ne = gcmalloc(sizeof(ListEnt));
ne->v = v;
if(l->head == 0) {
l->head = ne;
return;
}
e = l->head;
while(e->next)
e = e->next;
e->next = ne;
}
void
listprepend(List *l, void *v)
{
ListEnt *e;
e = gcmalloc(sizeof(ListEnt));
e->v = v;
e->next = l->head;
l->head = e;
}
| 2.515625 | 3 |
2024-11-18T19:02:58.125986+00:00
| 2021-06-14T16:36:11 |
afe34bdecb8c7fbbe37cf3453fcc4c795f2b7641
|
{
"blob_id": "afe34bdecb8c7fbbe37cf3453fcc4c795f2b7641",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-14T16:36:11",
"content_id": "d41e5dc1f449383403ad0f8522fdeae3dddff860",
"detected_licenses": [
"MIT"
],
"directory_id": "88a0fadf7676f00fd5de8b23ec66a9d5f8971d17",
"extension": "c",
"filename": "jaao.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 348853212,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1548,
"license": "MIT",
"license_type": "permissive",
"path": "/jaao.c",
"provenance": "stackv2-0058.json.gz:172901",
"repo_name": "DinossauroBebado/Fund-Prog",
"revision_date": "2021-06-14T16:36:11",
"revision_id": "2cdb1750910d6409c04f429555005270a12766e1",
"snapshot_id": "df356abf30a9796bbc203cfce91d7f8f1c7c3039",
"src_encoding": "WINDOWS-1252",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/DinossauroBebado/Fund-Prog/2cdb1750910d6409c04f429555005270a12766e1/jaao.c",
"visit_date": "2023-05-27T17:43:42.068817"
}
|
stackv2
|
//Declarar uma estrutura denominada “rgAluno”, para controlar as notas obtidas pelos acadêmicos(as)
//na primeira prova da disciplina de “Fundamentos de Programação”, com os seguintes campos:
//- nome do aluno (como uma cadeia com 35 caracteres)
//- nota (como um valor numérico real)
//Solicite do professor a quantidade de acadêmicos(as), variável “n”, realizaram a avaliação e declarar
//um vetor para armazenar todas os nomes e as notas informadas, por exemplo:
//struct rgAluno turma[n];
//O programa ainda deverá ler todas as notas e os respectivos nomes dos alunos da turma e ao final
//informar: a) a média geral da turma; b) a quantidades de alunos possuem notas acima e abaixo da
//média geral da turma.
#include <stdio.h>
#include <stdlib.h>
int n, i, count=0;
float media=0;
struct rgAluno
{
char nome[35];
float nota;
};
int main()
{
printf("Digite o numero de alunos: ");
scanf(" %d", &n);
struct rgAluno aluno;
char turma[n];
int notas[n];
for (i=0; i<n; i++)
{
printf("Nome do aluno: ");
scanf(" %s", &aluno.nome);
printf("Nota obtida: ");
scanf(" %f", &aluno.nota);
media = media + aluno.nota;
turma[i] = ("%c - %f",aluno.nome, aluno.nota);
notas[i] = aluno.nota;
}
printf("A media geral da turma foi: %f.", media);
for (i=0; i<n; i++)
{
if (notas[i]>=media)
{
count = count + 1;
}
}
printf("%d alunos ficaram acima da media geral!", count);
}
| 3.84375 | 4 |
2024-11-18T19:02:58.255020+00:00
| 2021-08-05T13:15:49 |
cfe48aba55575e1143d1b2677b6576401dc73177
|
{
"blob_id": "cfe48aba55575e1143d1b2677b6576401dc73177",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-07T07:04:12",
"content_id": "c9ec30ae8ce1542d2b6a68c9ca22dc9395c40f85",
"detected_licenses": [
"MIT"
],
"directory_id": "7736f410333e94b393806b617a2a379a9f36f985",
"extension": "c",
"filename": "tablet_pad.c",
"fork_events_count": 1,
"gha_created_at": "2017-09-01T13:00:31",
"gha_event_created_at": "2021-11-22T13:30:45",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 102113165,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6387,
"license": "MIT",
"license_type": "permissive",
"path": "/backend/libinput/tablet_pad.c",
"provenance": "stackv2-0058.json.gz:173029",
"repo_name": "emersion/wlroots",
"revision_date": "2021-08-05T13:15:49",
"revision_id": "033c9cab74801db9ad1165cbdfc4c4c63cb40dda",
"snapshot_id": "cfc893e2c27685a03911f072525043beccc270e4",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/emersion/wlroots/033c9cab74801db9ad1165cbdfc4c4c63cb40dda/backend/libinput/tablet_pad.c",
"visit_date": "2021-12-06T09:56:49.924593"
}
|
stackv2
|
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif
#include <assert.h>
#include <string.h>
#include <libinput.h>
#include <stdlib.h>
#include <wlr/backend/session.h>
#include <wlr/interfaces/wlr_tablet_pad.h>
#include <wlr/types/wlr_input_device.h>
#include <wlr/util/log.h>
#include "backend/libinput.h"
#include "util/signal.h"
// FIXME: Decide on how to alloc/count here
static void add_pad_group_from_libinput(struct wlr_tablet_pad *pad,
struct libinput_device *device, unsigned int index) {
struct libinput_tablet_pad_mode_group *li_group =
libinput_device_tablet_pad_get_mode_group(device, index);
struct wlr_tablet_pad_group *group =
calloc(1, sizeof(struct wlr_tablet_pad_group));
if (!group) {
return;
}
for (size_t i = 0; i < pad->ring_count; ++i) {
if (libinput_tablet_pad_mode_group_has_ring(li_group, i)) {
++group->ring_count;
}
}
group->rings = calloc(sizeof(unsigned int), group->ring_count);
size_t ring = 0;
for (size_t i = 0; i < pad->ring_count; ++i) {
if (libinput_tablet_pad_mode_group_has_ring(li_group, i)) {
group->rings[ring++] = i;
}
}
for (size_t i = 0; i < pad->strip_count; ++i) {
if (libinput_tablet_pad_mode_group_has_strip(li_group, i)) {
++group->strip_count;
}
}
group->strips = calloc(sizeof(unsigned int), group->strip_count);
size_t strip = 0;
for (size_t i = 0; i < pad->strip_count; ++i) {
if (libinput_tablet_pad_mode_group_has_strip(li_group, i)) {
group->strips[strip++] = i;
}
}
for (size_t i = 0; i < pad->button_count; ++i) {
if (libinput_tablet_pad_mode_group_has_button(li_group, i)) {
++group->button_count;
}
}
group->buttons = calloc(sizeof(unsigned int), group->button_count);
size_t button = 0;
for (size_t i = 0; i < pad->button_count; ++i) {
if (libinput_tablet_pad_mode_group_has_button(li_group, i)) {
group->buttons[button++] = i;
}
}
group->mode_count = libinput_tablet_pad_mode_group_get_num_modes(li_group);
wl_list_insert(&pad->groups, &group->link);
}
struct wlr_tablet_pad *create_libinput_tablet_pad(
struct libinput_device *libinput_dev) {
assert(libinput_dev);
struct wlr_tablet_pad *wlr_tablet_pad =
calloc(1, sizeof(struct wlr_tablet_pad));
if (!wlr_tablet_pad) {
wlr_log(WLR_ERROR, "Unable to allocate wlr_tablet_pad");
return NULL;
}
wlr_tablet_pad_init(wlr_tablet_pad, NULL);
wlr_tablet_pad->button_count =
libinput_device_tablet_pad_get_num_buttons(libinput_dev);
wlr_tablet_pad->ring_count =
libinput_device_tablet_pad_get_num_rings(libinput_dev);
wlr_tablet_pad->strip_count =
libinput_device_tablet_pad_get_num_strips(libinput_dev);
struct udev_device *udev = libinput_device_get_udev_device(libinput_dev);
char **dst = wl_array_add(&wlr_tablet_pad->paths, sizeof(char *));
*dst = strdup(udev_device_get_syspath(udev));
int groups = libinput_device_tablet_pad_get_num_mode_groups(libinput_dev);
for (int i = 0; i < groups; ++i) {
add_pad_group_from_libinput(wlr_tablet_pad, libinput_dev, i);
}
return wlr_tablet_pad;
}
void handle_tablet_pad_button(struct libinput_event *event,
struct libinput_device *libinput_dev) {
struct wlr_input_device *wlr_dev =
get_appropriate_device(WLR_INPUT_DEVICE_TABLET_PAD, libinput_dev);
if (!wlr_dev) {
wlr_log(WLR_DEBUG,
"Got a tablet pad event for a device with no tablet pad?");
return;
}
struct libinput_event_tablet_pad *pevent =
libinput_event_get_tablet_pad_event(event);
struct wlr_event_tablet_pad_button wlr_event = { 0 };
wlr_event.time_msec =
usec_to_msec(libinput_event_tablet_pad_get_time_usec(pevent));
wlr_event.button = libinput_event_tablet_pad_get_button_number(pevent);
wlr_event.mode = libinput_event_tablet_pad_get_mode(pevent);
wlr_event.group = libinput_tablet_pad_mode_group_get_index(
libinput_event_tablet_pad_get_mode_group(pevent));
switch (libinput_event_tablet_pad_get_button_state(pevent)) {
case LIBINPUT_BUTTON_STATE_PRESSED:
wlr_event.state = WLR_BUTTON_PRESSED;
break;
case LIBINPUT_BUTTON_STATE_RELEASED:
wlr_event.state = WLR_BUTTON_RELEASED;
break;
}
wlr_signal_emit_safe(&wlr_dev->tablet_pad->events.button, &wlr_event);
}
void handle_tablet_pad_ring(struct libinput_event *event,
struct libinput_device *libinput_dev) {
struct wlr_input_device *wlr_dev =
get_appropriate_device(WLR_INPUT_DEVICE_TABLET_PAD, libinput_dev);
if (!wlr_dev) {
wlr_log(WLR_DEBUG,
"Got a tablet pad event for a device with no tablet pad?");
return;
}
struct libinput_event_tablet_pad *pevent =
libinput_event_get_tablet_pad_event(event);
struct wlr_event_tablet_pad_ring wlr_event = { 0 };
wlr_event.time_msec =
usec_to_msec(libinput_event_tablet_pad_get_time_usec(pevent));
wlr_event.ring = libinput_event_tablet_pad_get_ring_number(pevent);
wlr_event.position = libinput_event_tablet_pad_get_ring_position(pevent);
wlr_event.mode = libinput_event_tablet_pad_get_mode(pevent);
switch (libinput_event_tablet_pad_get_ring_source(pevent)) {
case LIBINPUT_TABLET_PAD_RING_SOURCE_UNKNOWN:
wlr_event.source = WLR_TABLET_PAD_RING_SOURCE_UNKNOWN;
break;
case LIBINPUT_TABLET_PAD_RING_SOURCE_FINGER:
wlr_event.source = WLR_TABLET_PAD_RING_SOURCE_FINGER;
break;
}
wlr_signal_emit_safe(&wlr_dev->tablet_pad->events.ring, &wlr_event);
}
void handle_tablet_pad_strip(struct libinput_event *event,
struct libinput_device *libinput_dev) {
struct wlr_input_device *wlr_dev =
get_appropriate_device(WLR_INPUT_DEVICE_TABLET_PAD, libinput_dev);
if (!wlr_dev) {
wlr_log(WLR_DEBUG,
"Got a tablet pad event for a device with no tablet pad?");
return;
}
struct libinput_event_tablet_pad *pevent =
libinput_event_get_tablet_pad_event(event);
struct wlr_event_tablet_pad_strip wlr_event = { 0 };
wlr_event.time_msec =
usec_to_msec(libinput_event_tablet_pad_get_time_usec(pevent));
wlr_event.strip = libinput_event_tablet_pad_get_strip_number(pevent);
wlr_event.position = libinput_event_tablet_pad_get_strip_position(pevent);
wlr_event.mode = libinput_event_tablet_pad_get_mode(pevent);
switch (libinput_event_tablet_pad_get_strip_source(pevent)) {
case LIBINPUT_TABLET_PAD_STRIP_SOURCE_UNKNOWN:
wlr_event.source = WLR_TABLET_PAD_STRIP_SOURCE_UNKNOWN;
break;
case LIBINPUT_TABLET_PAD_STRIP_SOURCE_FINGER:
wlr_event.source = WLR_TABLET_PAD_STRIP_SOURCE_FINGER;
break;
}
wlr_signal_emit_safe(&wlr_dev->tablet_pad->events.strip, &wlr_event);
}
| 2.21875 | 2 |
2024-11-18T19:02:58.428305+00:00
| 2021-06-09T02:15:49 |
88192ef56285efc2fe9ced94614687e4ee8fa575
|
{
"blob_id": "88192ef56285efc2fe9ced94614687e4ee8fa575",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-09T02:15:49",
"content_id": "2642b8126768592bea418872a4cefca4ac47072c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ecbdee92072bf7b377a099ec19d35bbe0f0b4946",
"extension": "c",
"filename": "config_par.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 294375810,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7532,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/STM32F103xx/OneCM_App/src/config_device/config_par.c",
"provenance": "stackv2-0058.json.gz:173157",
"repo_name": "chuxuanqk/STM32CubeIDE_Project",
"revision_date": "2021-06-09T02:15:49",
"revision_id": "17f3646c47f4e87b96ce65f9d282b861a49727b3",
"snapshot_id": "263b1d34440d155b931e07ff15ff3ea4e68a6056",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/chuxuanqk/STM32CubeIDE_Project/17f3646c47f4e87b96ce65f9d282b861a49727b3/STM32F103xx/OneCM_App/src/config_device/config_par.c",
"visit_date": "2023-05-31T06:43:03.031626"
}
|
stackv2
|
/*
* config_par.c
*
* Created on: 2020年1月3日
* Author: Fox
*/
#include "config_device/config_par.h"
#include "stm32f10x_flash.h"
Config_Data_Str Config_Data; // 配置信息
union STM32_ID_12Byte STM32_ID; // STM32芯片物理地址12*8字节共同体
/**
* @description: 擦除页
* @param {pageaddr} 起始地址
* @param {num} 擦除的页数
* @return {1}
*/
uint32_t Erase_page(uint32_t pageaddr, uint32_t num)
{
FLASH_Unlock();
/* 擦除FLASH */
FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); /* 清空所有标志位 */
/* 按页擦除 */
for (uint32_t EraseCounter = 0; EraseCounter < num; EraseCounter++)
{
while (FLASH_COMPLETE != FLASH_ErasePage(pageaddr + (PageSize * EraseCounter)))
;
}
FLASH_Lock();
return 1;
}
/**
* @description: 读数据
* @param {addr} 读取的flash地址
* @param {*buff} 读出数据的数组指针
* @param {word_size} 字长长度
* @return {*}
*/
void ReadFlash(uint32_t addr, uint32_t *buff, uint16_t word_size)
{
for (uint32_t i = 0; i < word_size; i++)
buff[i] = *(__IO uint32_t *)(addr + 4 * i);
return;
}
/**
* @description: 写数据
* @param {addr} 写入的flash地址
* @param {*buff} 写入数据的数组指针
* @param {word_size} 长度
* @return {*}
*/
void WriteFlash(uint32_t addr, uint32_t *buff, int word_size)
{
FLASH_Unlock();
for (uint32_t i = 0; i < word_size; i++)
{
while (FLASH_COMPLETE != FLASH_ProgramWord(addr + 4 * i, buff[i]))
;
}
FLASH_Lock();
}
/**
* @description: 写数据,半字
* @param {uint32_t} addr
* @param {uint16_t} *buff
* @param {int} halfword_size
* @return {*}
*/
void Write_HalfWord_Flash(uint32_t addr, uint16_t *buff, int halfword_size)
{
FLASH_Unlock();
for (uint32_t i = 0; i < halfword_size; i++)
{
while (FLASH_COMPLETE != FLASH_ProgramHalfWord(addr + 2 * i, buff[i]))
;
}
FLASH_Lock();
}
/**
* @description: 写设备数据到flash
* @param {Config_Data_Str} *config
* @return {*}
*/
void Write_Config_To_Flash(Config_Data_Str *config)
{
uint32_t flash_addr = CONFIG_DATA_FLASH_ADDR;
uint32_t *pdata = (uint32_t *)config;
uint8_t word_size = (sizeof(Config_Data_Str) / 4);
Erase_page(flash_addr, 1);
WriteFlash(flash_addr, pdata, word_size);
}
void Dev_Config_Reinit(device_config *dev_con)
{
uint8_t i = 0; //设置默认值
for (i = 0; i < Net_IDs_All; i++)
{
// dev_con->baud_rate = 9600;
dev_con->baud_rate_HH = 0x00;
dev_con->baud_rate_HL = 0x00;
dev_con->baud_rate_LH = 0x25;
dev_con->baud_rate_LL = 0x80;
dev_con->data_bit = 8;
dev_con->stop_bit = 1;
dev_con->parity_bit = 0;
dev_con->response_Signal = 0;
dev_con->delay_time_H = 0;
dev_con->delay_time_L = 0x64;
}
return;
}
void Config_Data_ReInit(Config_Data_Str *config)
{
uint16_t i;
uint8_t *temp_ptr = (uint8_t *)config;
//清零所有参数
for (i = 0; i < sizeof(Config_Data_Str); i++)
{
temp_ptr[i] = 0;
}
Dev_Config_Reinit(&config->dev_con);
config->save_data_flag = 1;
};
/**
* @description: 读取Flash中的设备数据
* @param {*}
* @return {*}
*/
void Read_Config_Form_Flash(Config_Data_Str *config)
{
uint32_t flash_addr = CONFIG_DATA_FLASH_ADDR;
uint32_t *pdata = (uint32_t *)config;
uint8_t word_size = (sizeof(Config_Data_Str) / 4);
ReadFlash(flash_addr, pdata, word_size);
printf("data: %d, stop: %d, flag: %d\r\n",
Config_Data.dev_con.data_bit, Config_Data.dev_con.stop_bit,
Config_Data.save_data_flag);
if (Config_Data.save_data_flag != 1)
{
Config_Data_ReInit(config);
Write_Config_To_Flash(config);
}
}
/**
* @description: 清除配置数据
* @param {*}
* @return {*}
*/
void Config_Data_Clear_Even(void)
{
uint8_t i = 0;
Config_Data_ReInit(&Config_Data); //清除配置信息
Write_Config_To_Flash(&Config_Data);
}
#ifdef OLD_CFG_CODE
//配置信息初始化
void Dev_Config_Reinit(device_config *dev_con)
{
//设置默认值
uint8_t i = 0;
for (i = 0; i < Net_IDs_All; i++)
{
// dev_con->baud_rate = 9600;
dev_con->baud_rate_HH = 0x00;
dev_con->baud_rate_HL = 0x00;
dev_con->baud_rate_LH = 0x25;
dev_con->baud_rate_LL = 0x80;
dev_con->data_bit = 8;
dev_con->stop_bit = 1;
dev_con->parity_bit = 0;
dev_con->response_Signal = 0;
dev_con->delay_time_H = 0;
dev_con->delay_time_L = 0x64;
}
return;
}
void Write_Config_To_Flash(Config_Data_Str *config)
{
uint16_t i;
uint8_t *data_ptr = (uint8_t *)config;
u32 flash_addr = CONFIG_DATA_FLASH_ADDR;
FLASH_Unlock(); /* 每次擦除Flash中数据时得先解锁 */
FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); //清除标记
for (i = 0; i < (sizeof(Config_Data_Str) / FLASH_Page_SIZE + 1); i++)
while (FLASH_COMPLETE != FLASH_ErasePage(CONFIG_DATA_FLASH_ADDR + i * FLASH_Page_SIZE))
;
for (i = 0; i < sizeof(Config_Data_Str); i++)
{
while (FLASH_COMPLETE != FLASH_ProgramHalfWord(flash_addr, (data_ptr[i] + data_ptr[i + 1] * 256)))
;
i++;
flash_addr += 2;
}
}
void Read_Config_Form_Flash(Config_Data_Str *config)
{
uint16_t i;
uint8_t *data_ptr = (uint8_t *)config;
uint16_t tmp_read;
u32 flash_addr = CONFIG_DATA_FLASH_ADDR;
for (i = 0; i < sizeof(Config_Data_Str); i++)
{
tmp_read = *(uint16_t *)(flash_addr);
data_ptr[i] = tmp_read % 256;
i++;
if (i < sizeof(Config_Data_Str))
data_ptr[i] = tmp_read / 256;
flash_addr += 2;
}
//判断是否为第一次启动
if (config->save_data_flag != 1)
{
Config_Data_ReInit(config); //重置所有参数
Write_Config_To_Flash(config); //回写参数到flash
}
}
void Config_Data_ReInit(Config_Data_Str *config)
{
uint16_t i;
uint8_t *temp_ptr = (uint8_t *)config;
//清零所有参数
for (i = 0; i < sizeof(Config_Data_Str); i++)
{
temp_ptr[i] = 0;
}
Dev_Config_Reinit(&config->dev_con);
config->save_data_flag = 1;
};
/**
* @description: 清除配置数据
* @param {*}
* @return {*}
*/
void Config_Data_Clear_Even(void)
{
uint8_t i = 0;
//清除配置信息
Config_Data_ReInit(&Config_Data);
Write_Config_To_Flash(&Config_Data);
}
#endif
/**
* @description: 判断是否配置了通道,未完成
* @param {*}
* @return {*}
*/
bool Is_Config_portid(uint8_t temp_port)
{
bool rflag = false;
if (temp_port == 0) // 广播,默认开启
rflag = true;
// 已配置进config
// if()
// rflag = true;
return rflag;
}
//读取ChipID
void Cpu_GetId(void)
{
STM32_ID.id_u32[0] = *(__IO u32 *)(0x1FFFF7E8); //产品唯一身份标识寄存器(96位)
STM32_ID.id_u32[1] = *(__IO u32 *)(0x1FFFF7EC);
STM32_ID.id_u32[2] = *(__IO u32 *)(0x1FFFF7F0);
}
/**
* @description: 提供外部模块访问Config_Data
* @param {*}
* @return {*}
*/
Config_Data_Str *Get_Config_data(void)
{
return &Config_Data;
}
union STM32_ID_12Byte *Get_CpuId(void)
{
return &STM32_ID;
}
| 2.578125 | 3 |
2024-11-18T19:02:59.609774+00:00
| 2021-04-06T02:14:39 |
763e4c48501abf7a82521ebf8e24025fc9a1bd8d
|
{
"blob_id": "763e4c48501abf7a82521ebf8e24025fc9a1bd8d",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-06T02:14:39",
"content_id": "9432a5060b12ef241a56e00454adef212710022c",
"detected_licenses": [
"MIT"
],
"directory_id": "ddd0dc27b07df085efe9239f3347747dba0706c5",
"extension": "c",
"filename": "bsp_ili9341_lcd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 343998046,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 50440,
"license": "MIT",
"license_type": "permissive",
"path": "/tuya_iot/User/lcd/bsp_ili9341_lcd.c",
"provenance": "stackv2-0058.json.gz:173670",
"repo_name": "Mimi233/mico-pat-iot-sdk-v1",
"revision_date": "2021-04-06T02:14:39",
"revision_id": "1a07074d8af960ceb06d99c6cf855a3811f40235",
"snapshot_id": "1e8f35c68bb6cca962047a0a85faaddd6af7dd3c",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mimi233/mico-pat-iot-sdk-v1/1a07074d8af960ceb06d99c6cf855a3811f40235/tuya_iot/User/lcd/bsp_ili9341_lcd.c",
"visit_date": "2023-03-29T15:24:05.800867"
}
|
stackv2
|
/**
******************************************************************************
* @file bsp_ili9341_lcd.c
* @version V1.0
* @date 2013-xx-xx
* @brief ili9341液晶屏驱动
******************************************************************************
* @attention
*
* 实验平台:野火 F103-指南者 STM32 开发板
* 论坛 :http://www.firebbs.cn
* 淘宝 :https://fire-stm32.taobao.com
*
******************************************************************************
*/
#include "./lcd/bsp_ili9341_lcd.h"
#include "./font/fonts.h"
//根据液晶扫描方向而变化的XY像素宽度
//调用ILI9341_GramScan函数设置方向时会自动更改
uint16_t LCD_X_LENGTH = ILI9341_LESS_PIXEL;
uint16_t LCD_Y_LENGTH = ILI9341_MORE_PIXEL;
//液晶屏扫描模式,本变量主要用于方便选择触摸屏的计算参数
//参数可选值为0-7
//调用ILI9341_GramScan函数设置方向时会自动更改
//LCD刚初始化完成时会使用本默认值
uint8_t LCD_SCAN_MODE = 6;
static sFONT *LCD_Currentfonts = &Font8x16; //英文字体
static uint16_t CurrentTextColor = BLACK;//前景色
static uint16_t CurrentBackColor = WHITE;//背景色
__inline void ILI9341_Write_Cmd ( uint16_t usCmd );
__inline void ILI9341_Write_Data ( uint16_t usData );
__inline uint16_t ILI9341_Read_Data ( void );
static void ILI9341_Delay ( __IO uint32_t nCount );
static void ILI9341_GPIO_Config ( void );
static void ILI9341_FSMC_Config ( void );
static void ILI9341_REG_Config ( void );
static void ILI9341_SetCursor ( uint16_t usX, uint16_t usY );
static __inline void ILI9341_FillColor ( uint32_t ulAmout_Point, uint16_t usColor );
static uint16_t ILI9341_Read_PixelData ( void );
/**
* @brief 向ILI9341写入命令
* @param usCmd :要写入的命令(表寄存器地址)
* @retval 无
*/
__inline void ILI9341_Write_Cmd ( uint16_t usCmd )
{
* ( __IO uint16_t * ) ( FSMC_Addr_ILI9341_CMD ) = usCmd;
}
/**
* @brief 向ILI9341写入数据
* @param usData :要写入的数据
* @retval 无
*/
__inline void ILI9341_Write_Data ( uint16_t usData )
{
* ( __IO uint16_t * ) ( FSMC_Addr_ILI9341_DATA ) = usData;
}
/**
* @brief 从ILI9341读取数据
* @param 无
* @retval 读取到的数据
*/
__inline uint16_t ILI9341_Read_Data ( void )
{
return ( * ( __IO uint16_t * ) ( FSMC_Addr_ILI9341_DATA ) );
}
/**
* @brief 用于 ILI9341 简单延时函数
* @param nCount :延时计数值
* @retval 无
*/
static void ILI9341_Delay ( __IO uint32_t nCount )
{
for ( ; nCount != 0; nCount -- );
}
/**
* @brief 初始化ILI9341的IO引脚
* @param 无
* @retval 无
*/
static void ILI9341_GPIO_Config ( void )
{
GPIO_InitTypeDef GPIO_InitStructure;
/* 使能FSMC对应相应管脚时钟*/
RCC_APB2PeriphClockCmd (
/*控制信号*/
ILI9341_CS_CLK|ILI9341_DC_CLK|ILI9341_WR_CLK|
ILI9341_RD_CLK |ILI9341_BK_CLK|ILI9341_RST_CLK|
/*数据信号*/
ILI9341_D0_CLK|ILI9341_D1_CLK| ILI9341_D2_CLK |
ILI9341_D3_CLK | ILI9341_D4_CLK|ILI9341_D5_CLK|
ILI9341_D6_CLK | ILI9341_D7_CLK|ILI9341_D8_CLK|
ILI9341_D9_CLK | ILI9341_D10_CLK|ILI9341_D11_CLK|
ILI9341_D12_CLK | ILI9341_D13_CLK|ILI9341_D14_CLK|
ILI9341_D15_CLK , ENABLE );
/* 配置FSMC相对应的数据线,FSMC-D0~D15 */
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = ILI9341_D0_PIN;
GPIO_Init ( ILI9341_D0_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D1_PIN;
GPIO_Init ( ILI9341_D1_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D2_PIN;
GPIO_Init ( ILI9341_D2_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D3_PIN;
GPIO_Init ( ILI9341_D3_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D4_PIN;
GPIO_Init ( ILI9341_D4_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D5_PIN;
GPIO_Init ( ILI9341_D5_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D6_PIN;
GPIO_Init ( ILI9341_D6_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D7_PIN;
GPIO_Init ( ILI9341_D7_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D8_PIN;
GPIO_Init ( ILI9341_D8_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D9_PIN;
GPIO_Init ( ILI9341_D9_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D10_PIN;
GPIO_Init ( ILI9341_D10_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D11_PIN;
GPIO_Init ( ILI9341_D11_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D12_PIN;
GPIO_Init ( ILI9341_D12_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D13_PIN;
GPIO_Init ( ILI9341_D13_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D14_PIN;
GPIO_Init ( ILI9341_D14_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_D15_PIN;
GPIO_Init ( ILI9341_D15_PORT, & GPIO_InitStructure );
/* 配置FSMC相对应的控制线
* FSMC_NOE :LCD-RD
* FSMC_NWE :LCD-WR
* FSMC_NE1 :LCD-CS
* FSMC_A16 :LCD-DC
*/
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = ILI9341_RD_PIN;
GPIO_Init (ILI9341_RD_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_WR_PIN;
GPIO_Init (ILI9341_WR_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_CS_PIN;
GPIO_Init ( ILI9341_CS_PORT, & GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = ILI9341_DC_PIN;
GPIO_Init ( ILI9341_DC_PORT, & GPIO_InitStructure );
/* 配置LCD复位RST控制管脚*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = ILI9341_RST_PIN;
GPIO_Init ( ILI9341_RST_PORT, & GPIO_InitStructure );
/* 配置LCD背光控制管脚BK*/
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = ILI9341_BK_PIN;
GPIO_Init ( ILI9341_BK_PORT, & GPIO_InitStructure );
}
/**
* @brief LCD FSMC 模式配置
* @param 无
* @retval 无
*/
static void ILI9341_FSMC_Config ( void )
{
FSMC_NORSRAMInitTypeDef FSMC_NORSRAMInitStructure;
FSMC_NORSRAMTimingInitTypeDef readWriteTiming;
/* 使能FSMC时钟*/
RCC_AHBPeriphClockCmd ( RCC_AHBPeriph_FSMC, ENABLE );
//地址建立时间(ADDSET)为1个HCLK 2/72M=28ns
readWriteTiming.FSMC_AddressSetupTime = 0x01; //地址建立时间
//数据保持时间(DATAST)+ 1个HCLK = 5/72M=70ns
readWriteTiming.FSMC_DataSetupTime = 0x04; //数据建立时间
//选择控制的模式
//模式B,异步NOR FLASH模式,与ILI9341的8080时序匹配
readWriteTiming.FSMC_AccessMode = FSMC_AccessMode_B;
/*以下配置与模式B无关*/
//地址保持时间(ADDHLD)模式A未用到
readWriteTiming.FSMC_AddressHoldTime = 0x00; //地址保持时间
//设置总线转换周期,仅用于复用模式的NOR操作
readWriteTiming.FSMC_BusTurnAroundDuration = 0x00;
//设置时钟分频,仅用于同步类型的存储器
readWriteTiming.FSMC_CLKDivision = 0x00;
//数据保持时间,仅用于同步型的NOR
readWriteTiming.FSMC_DataLatency = 0x00;
FSMC_NORSRAMInitStructure.FSMC_Bank = FSMC_Bank1_NORSRAMx;
FSMC_NORSRAMInitStructure.FSMC_DataAddressMux = FSMC_DataAddressMux_Disable;
FSMC_NORSRAMInitStructure.FSMC_MemoryType = FSMC_MemoryType_NOR;
FSMC_NORSRAMInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_16b;
FSMC_NORSRAMInitStructure.FSMC_BurstAccessMode = FSMC_BurstAccessMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalPolarity = FSMC_WaitSignalPolarity_Low;
FSMC_NORSRAMInitStructure.FSMC_WrapMode = FSMC_WrapMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalActive = FSMC_WaitSignalActive_BeforeWaitState;
FSMC_NORSRAMInitStructure.FSMC_WriteOperation = FSMC_WriteOperation_Enable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignal = FSMC_WaitSignal_Disable;
FSMC_NORSRAMInitStructure.FSMC_ExtendedMode = FSMC_ExtendedMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WriteBurst = FSMC_WriteBurst_Disable;
FSMC_NORSRAMInitStructure.FSMC_ReadWriteTimingStruct = &readWriteTiming;
FSMC_NORSRAMInitStructure.FSMC_WriteTimingStruct = &readWriteTiming;
FSMC_NORSRAMInit ( & FSMC_NORSRAMInitStructure );
/* 使能 FSMC_Bank1_NORSRAM4 */
FSMC_NORSRAMCmd ( FSMC_Bank1_NORSRAMx, ENABLE );
}
/**
* @brief 初始化ILI9341寄存器
* @param 无
* @retval 无
*/
static void ILI9341_REG_Config ( void )
{
/* Power control B (CFh) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xCF );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x81 );
ILI9341_Write_Data ( 0x30 );
/* Power on sequence control (EDh) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xED );
ILI9341_Write_Data ( 0x64 );
ILI9341_Write_Data ( 0x03 );
ILI9341_Write_Data ( 0x12 );
ILI9341_Write_Data ( 0x81 );
/* Driver timing control A (E8h) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xE8 );
ILI9341_Write_Data ( 0x85 );
ILI9341_Write_Data ( 0x10 );
ILI9341_Write_Data ( 0x78 );
/* Power control A (CBh) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xCB );
ILI9341_Write_Data ( 0x39 );
ILI9341_Write_Data ( 0x2C );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x34 );
ILI9341_Write_Data ( 0x02 );
/* Pump ratio control (F7h) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xF7 );
ILI9341_Write_Data ( 0x20 );
/* Driver timing control B */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xEA );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x00 );
/* Frame Rate Control (In Normal Mode/Full Colors) (B1h) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xB1 );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x1B );
/* Display Function Control (B6h) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xB6 );
ILI9341_Write_Data ( 0x0A );
ILI9341_Write_Data ( 0xA2 );
/* Power Control 1 (C0h) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xC0 );
ILI9341_Write_Data ( 0x35 );
/* Power Control 2 (C1h) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0xC1 );
ILI9341_Write_Data ( 0x11 );
/* VCOM Control 1 (C5h) */
ILI9341_Write_Cmd ( 0xC5 );
ILI9341_Write_Data ( 0x45 );
ILI9341_Write_Data ( 0x45 );
/* VCOM Control 2 (C7h) */
ILI9341_Write_Cmd ( 0xC7 );
ILI9341_Write_Data ( 0xA2 );
/* Enable 3G (F2h) */
ILI9341_Write_Cmd ( 0xF2 );
ILI9341_Write_Data ( 0x00 );
/* Gamma Set (26h) */
ILI9341_Write_Cmd ( 0x26 );
ILI9341_Write_Data ( 0x01 );
DEBUG_DELAY ();
/* Positive Gamma Correction */
ILI9341_Write_Cmd ( 0xE0 ); //Set Gamma
ILI9341_Write_Data ( 0x0F );
ILI9341_Write_Data ( 0x26 );
ILI9341_Write_Data ( 0x24 );
ILI9341_Write_Data ( 0x0B );
ILI9341_Write_Data ( 0x0E );
ILI9341_Write_Data ( 0x09 );
ILI9341_Write_Data ( 0x54 );
ILI9341_Write_Data ( 0xA8 );
ILI9341_Write_Data ( 0x46 );
ILI9341_Write_Data ( 0x0C );
ILI9341_Write_Data ( 0x17 );
ILI9341_Write_Data ( 0x09 );
ILI9341_Write_Data ( 0x0F );
ILI9341_Write_Data ( 0x07 );
ILI9341_Write_Data ( 0x00 );
/* Negative Gamma Correction (E1h) */
ILI9341_Write_Cmd ( 0XE1 ); //Set Gamma
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x19 );
ILI9341_Write_Data ( 0x1B );
ILI9341_Write_Data ( 0x04 );
ILI9341_Write_Data ( 0x10 );
ILI9341_Write_Data ( 0x07 );
ILI9341_Write_Data ( 0x2A );
ILI9341_Write_Data ( 0x47 );
ILI9341_Write_Data ( 0x39 );
ILI9341_Write_Data ( 0x03 );
ILI9341_Write_Data ( 0x06 );
ILI9341_Write_Data ( 0x06 );
ILI9341_Write_Data ( 0x30 );
ILI9341_Write_Data ( 0x38 );
ILI9341_Write_Data ( 0x0F );
/* memory access control set */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0x36 );
ILI9341_Write_Data ( 0xC8 ); /*竖屏 左上角到 (起点)到右下角 (终点)扫描方式*/
DEBUG_DELAY ();
/* column address control set */
ILI9341_Write_Cmd ( CMD_SetCoordinateX );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0xEF );
/* page address control set */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( CMD_SetCoordinateY );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x00 );
ILI9341_Write_Data ( 0x01 );
ILI9341_Write_Data ( 0x3F );
/* Pixel Format Set (3Ah) */
DEBUG_DELAY ();
ILI9341_Write_Cmd ( 0x3a );
ILI9341_Write_Data ( 0x55 );
/* Sleep Out (11h) */
ILI9341_Write_Cmd ( 0x11 );
ILI9341_Delay ( 0xAFFf<<2 );
DEBUG_DELAY ();
/* Display ON (29h) */
ILI9341_Write_Cmd ( 0x29 );
}
/**
* @brief ILI9341初始化函数,如果要用到lcd,一定要调用这个函数
* @param 无
* @retval 无
*/
void ILI9341_Init ( void )
{
ILI9341_GPIO_Config ();
ILI9341_FSMC_Config ();
ILI9341_BackLed_Control ( ENABLE ); //点亮LCD背光灯
ILI9341_Rst ();
ILI9341_REG_Config ();
//设置默认扫描方向,其中 6 模式为大部分液晶例程的默认显示方向
ILI9341_GramScan(LCD_SCAN_MODE);
}
/**
* @brief ILI9341背光LED控制
* @param enumState :决定是否使能背光LED
* 该参数为以下值之一:
* @arg ENABLE :使能背光LED
* @arg DISABLE :禁用背光LED
* @retval 无
*/
void ILI9341_BackLed_Control ( FunctionalState enumState )
{
if ( enumState )
GPIO_ResetBits ( ILI9341_BK_PORT, ILI9341_BK_PIN );
else
GPIO_SetBits ( ILI9341_BK_PORT, ILI9341_BK_PIN );
}
/**
* @brief ILI9341 软件复位
* @param 无
* @retval 无
*/
void ILI9341_Rst ( void )
{
GPIO_ResetBits ( ILI9341_RST_PORT, ILI9341_RST_PIN ); //低电平复位
ILI9341_Delay ( 0xAFF );
GPIO_SetBits ( ILI9341_RST_PORT, ILI9341_RST_PIN );
ILI9341_Delay ( 0xAFF );
}
/**
* @brief 设置ILI9341的GRAM的扫描方向
* @param ucOption :选择GRAM的扫描方向
* @arg 0-7 :参数可选值为0-7这八个方向
*
* !!!其中0、3、5、6 模式适合从左至右显示文字,
* 不推荐使用其它模式显示文字 其它模式显示文字会有镜像效果
*
* 其中0、2、4、6 模式的X方向像素为240,Y方向像素为320
* 其中1、3、5、7 模式下X方向像素为320,Y方向像素为240
*
* 其中 6 模式为大部分液晶例程的默认显示方向
* 其中 3 模式为摄像头例程使用的方向
* 其中 0 模式为BMP图片显示例程使用的方向
*
* @retval 无
* @note 坐标图例:A表示向上,V表示向下,<表示向左,>表示向右
X表示X轴,Y表示Y轴
------------------------------------------------------------
模式0: . 模式1: . 模式2: . 模式3:
A . A . A . A
| . | . | . |
Y . X . Y . X
0 . 1 . 2 . 3
<--- X0 o . <----Y1 o . o 2X---> . o 3Y--->
------------------------------------------------------------
模式4: . 模式5: . 模式6: . 模式7:
<--- X4 o . <--- Y5 o . o 6X---> . o 7Y--->
4 . 5 . 6 . 7
Y . X . Y . X
| . | . | . |
V . V . V . V
---------------------------------------------------------
LCD屏示例
|-----------------|
| 野火Logo |
| |
| |
| |
| |
| |
| |
| |
| |
|-----------------|
屏幕正面(宽240,高320)
*******************************************************/
void ILI9341_GramScan ( uint8_t ucOption )
{
//参数检查,只可输入0-7
if(ucOption >7 )
return;
//根据模式更新LCD_SCAN_MODE的值,主要用于触摸屏选择计算参数
LCD_SCAN_MODE = ucOption;
//根据模式更新XY方向的像素宽度
if(ucOption%2 == 0)
{
//0 2 4 6模式下X方向像素宽度为240,Y方向为320
LCD_X_LENGTH = ILI9341_LESS_PIXEL;
LCD_Y_LENGTH = ILI9341_MORE_PIXEL;
}
else
{
//1 3 5 7模式下X方向像素宽度为320,Y方向为240
LCD_X_LENGTH = ILI9341_MORE_PIXEL;
LCD_Y_LENGTH = ILI9341_LESS_PIXEL;
}
//0x36命令参数的高3位可用于设置GRAM扫描方向
ILI9341_Write_Cmd ( 0x36 );
ILI9341_Write_Data ( 0x08 |(ucOption<<5));//根据ucOption的值设置LCD参数,共0-7种模式
ILI9341_Write_Cmd ( CMD_SetCoordinateX );
ILI9341_Write_Data ( 0x00 ); /* x 起始坐标高8位 */
ILI9341_Write_Data ( 0x00 ); /* x 起始坐标低8位 */
ILI9341_Write_Data ( ((LCD_X_LENGTH-1)>>8)&0xFF ); /* x 结束坐标高8位 */
ILI9341_Write_Data ( (LCD_X_LENGTH-1)&0xFF ); /* x 结束坐标低8位 */
ILI9341_Write_Cmd ( CMD_SetCoordinateY );
ILI9341_Write_Data ( 0x00 ); /* y 起始坐标高8位 */
ILI9341_Write_Data ( 0x00 ); /* y 起始坐标低8位 */
ILI9341_Write_Data ( ((LCD_Y_LENGTH-1)>>8)&0xFF ); /* y 结束坐标高8位 */
ILI9341_Write_Data ( (LCD_Y_LENGTH-1)&0xFF ); /* y 结束坐标低8位 */
/* write gram start */
ILI9341_Write_Cmd ( CMD_SetPixel );
}
/**
* @brief 在ILI9341显示器上开辟一个窗口
* @param usX :在特定扫描方向下窗口的起点X坐标
* @param usY :在特定扫描方向下窗口的起点Y坐标
* @param usWidth :窗口的宽度
* @param usHeight :窗口的高度
* @retval 无
*/
void ILI9341_OpenWindow ( uint16_t usX, uint16_t usY, uint16_t usWidth, uint16_t usHeight )
{
ILI9341_Write_Cmd ( CMD_SetCoordinateX ); /* 设置X坐标 */
ILI9341_Write_Data ( usX >> 8 ); /* 先高8位,然后低8位 */
ILI9341_Write_Data ( usX & 0xff ); /* 设置起始点和结束点*/
ILI9341_Write_Data ( ( usX + usWidth - 1 ) >> 8 );
ILI9341_Write_Data ( ( usX + usWidth - 1 ) & 0xff );
ILI9341_Write_Cmd ( CMD_SetCoordinateY ); /* 设置Y坐标*/
ILI9341_Write_Data ( usY >> 8 );
ILI9341_Write_Data ( usY & 0xff );
ILI9341_Write_Data ( ( usY + usHeight - 1 ) >> 8 );
ILI9341_Write_Data ( ( usY + usHeight - 1) & 0xff );
}
/**
* @brief 设定ILI9341的光标坐标
* @param usX :在特定扫描方向下光标的X坐标
* @param usY :在特定扫描方向下光标的Y坐标
* @retval 无
*/
static void ILI9341_SetCursor ( uint16_t usX, uint16_t usY )
{
ILI9341_OpenWindow ( usX, usY, 1, 1 );
}
/**
* @brief 在ILI9341显示器上以某一颜色填充像素点
* @param ulAmout_Point :要填充颜色的像素点的总数目
* @param usColor :颜色
* @retval 无
*/
static __inline void ILI9341_FillColor ( uint32_t ulAmout_Point, uint16_t usColor )
{
uint32_t i = 0;
/* memory write */
ILI9341_Write_Cmd ( CMD_SetPixel );
for ( i = 0; i < ulAmout_Point; i ++ )
ILI9341_Write_Data ( usColor );
}
/**
* @brief 对ILI9341显示器的某一窗口以某种颜色进行清屏
* @param usX :在特定扫描方向下窗口的起点X坐标
* @param usY :在特定扫描方向下窗口的起点Y坐标
* @param usWidth :窗口的宽度
* @param usHeight :窗口的高度
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_Clear ( uint16_t usX, uint16_t usY, uint16_t usWidth, uint16_t usHeight )
{
ILI9341_OpenWindow ( usX, usY, usWidth, usHeight );
ILI9341_FillColor ( usWidth * usHeight, CurrentBackColor );
}
/**
* @brief 对ILI9341显示器的某一点以某种颜色进行填充
* @param usX :在特定扫描方向下该点的X坐标
* @param usY :在特定扫描方向下该点的Y坐标
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_SetPointPixel ( uint16_t usX, uint16_t usY )
{
if ( ( usX < LCD_X_LENGTH ) && ( usY < LCD_Y_LENGTH ) )
{
ILI9341_SetCursor ( usX, usY );
ILI9341_FillColor ( 1, CurrentTextColor );
}
}
/**
* @brief 读取ILI9341 GRAN 的一个像素数据
* @param 无
* @retval 像素数据
*/
static uint16_t ILI9341_Read_PixelData ( void )
{
uint16_t usR=0, usG=0, usB=0 ;
ILI9341_Write_Cmd ( 0x2E ); /* 读数据 */
usR = ILI9341_Read_Data (); /*FIRST READ OUT DUMMY DATA*/
usR = ILI9341_Read_Data (); /*READ OUT RED DATA */
usB = ILI9341_Read_Data (); /*READ OUT BLUE DATA*/
usG = ILI9341_Read_Data (); /*READ OUT GREEN DATA*/
return ( ( ( usR >> 11 ) << 11 ) | ( ( usG >> 10 ) << 5 ) | ( usB >> 11 ) );
}
/**
* @brief 获取 ILI9341 显示器上某一个坐标点的像素数据
* @param usX :在特定扫描方向下该点的X坐标
* @param usY :在特定扫描方向下该点的Y坐标
* @retval 像素数据
*/
uint16_t ILI9341_GetPointPixel ( uint16_t usX, uint16_t usY )
{
uint16_t usPixelData;
ILI9341_SetCursor ( usX, usY );
usPixelData = ILI9341_Read_PixelData ();
return usPixelData;
}
/**
* @brief 在 ILI9341 显示器上使用 Bresenham 算法画线段
* @param usX1 :在特定扫描方向下线段的一个端点X坐标
* @param usY1 :在特定扫描方向下线段的一个端点Y坐标
* @param usX2 :在特定扫描方向下线段的另一个端点X坐标
* @param usY2 :在特定扫描方向下线段的另一个端点Y坐标
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DrawLine ( uint16_t usX1, uint16_t usY1, uint16_t usX2, uint16_t usY2 )
{
uint16_t us;
uint16_t usX_Current, usY_Current;
int32_t lError_X = 0, lError_Y = 0, lDelta_X, lDelta_Y, lDistance;
int32_t lIncrease_X, lIncrease_Y;
lDelta_X = usX2 - usX1; //计算坐标增量
lDelta_Y = usY2 - usY1;
usX_Current = usX1;
usY_Current = usY1;
if ( lDelta_X > 0 )
lIncrease_X = 1; //设置单步方向
else if ( lDelta_X == 0 )
lIncrease_X = 0;//垂直线
else
{
lIncrease_X = -1;
lDelta_X = - lDelta_X;
}
if ( lDelta_Y > 0 )
lIncrease_Y = 1;
else if ( lDelta_Y == 0 )
lIncrease_Y = 0;//水平线
else
{
lIncrease_Y = -1;
lDelta_Y = - lDelta_Y;
}
if ( lDelta_X > lDelta_Y )
lDistance = lDelta_X; //选取基本增量坐标轴
else
lDistance = lDelta_Y;
for ( us = 0; us <= lDistance + 1; us ++ )//画线输出
{
ILI9341_SetPointPixel ( usX_Current, usY_Current );//画点
lError_X += lDelta_X ;
lError_Y += lDelta_Y ;
if ( lError_X > lDistance )
{
lError_X -= lDistance;
usX_Current += lIncrease_X;
}
if ( lError_Y > lDistance )
{
lError_Y -= lDistance;
usY_Current += lIncrease_Y;
}
}
}
/**
* @brief 在 ILI9341 显示器上画一个矩形
* @param usX_Start :在特定扫描方向下矩形的起始点X坐标
* @param usY_Start :在特定扫描方向下矩形的起始点Y坐标
* @param usWidth:矩形的宽度(单位:像素)
* @param usHeight:矩形的高度(单位:像素)
* @param ucFilled :选择是否填充该矩形
* 该参数为以下值之一:
* @arg 0 :空心矩形
* @arg 1 :实心矩形
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DrawRectangle ( uint16_t usX_Start, uint16_t usY_Start, uint16_t usWidth, uint16_t usHeight, uint8_t ucFilled )
{
if ( ucFilled )
{
ILI9341_OpenWindow ( usX_Start, usY_Start, usWidth, usHeight );
ILI9341_FillColor ( usWidth * usHeight ,CurrentTextColor);
}
else
{
ILI9341_DrawLine ( usX_Start, usY_Start, usX_Start + usWidth - 1, usY_Start );
ILI9341_DrawLine ( usX_Start, usY_Start + usHeight - 1, usX_Start + usWidth - 1, usY_Start + usHeight - 1 );
ILI9341_DrawLine ( usX_Start, usY_Start, usX_Start, usY_Start + usHeight - 1 );
ILI9341_DrawLine ( usX_Start + usWidth - 1, usY_Start, usX_Start + usWidth - 1, usY_Start + usHeight - 1 );
}
}
/**
* @brief 在 ILI9341 显示器上使用 Bresenham 算法画圆
* @param usX_Center :在特定扫描方向下圆心的X坐标
* @param usY_Center :在特定扫描方向下圆心的Y坐标
* @param usRadius:圆的半径(单位:像素)
* @param ucFilled :选择是否填充该圆
* 该参数为以下值之一:
* @arg 0 :空心圆
* @arg 1 :实心圆
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DrawCircle ( uint16_t usX_Center, uint16_t usY_Center, uint16_t usRadius, uint8_t ucFilled )
{
int16_t sCurrentX, sCurrentY;
int16_t sError;
sCurrentX = 0; sCurrentY = usRadius;
sError = 3 - ( usRadius << 1 ); //判断下个点位置的标志
while ( sCurrentX <= sCurrentY )
{
int16_t sCountY;
if ( ucFilled )
for ( sCountY = sCurrentX; sCountY <= sCurrentY; sCountY ++ )
{
ILI9341_SetPointPixel ( usX_Center + sCurrentX, usY_Center + sCountY ); //1,研究对象
ILI9341_SetPointPixel ( usX_Center - sCurrentX, usY_Center + sCountY ); //2
ILI9341_SetPointPixel ( usX_Center - sCountY, usY_Center + sCurrentX ); //3
ILI9341_SetPointPixel ( usX_Center - sCountY, usY_Center - sCurrentX ); //4
ILI9341_SetPointPixel ( usX_Center - sCurrentX, usY_Center - sCountY ); //5
ILI9341_SetPointPixel ( usX_Center + sCurrentX, usY_Center - sCountY ); //6
ILI9341_SetPointPixel ( usX_Center + sCountY, usY_Center - sCurrentX ); //7
ILI9341_SetPointPixel ( usX_Center + sCountY, usY_Center + sCurrentX ); //0
}
else
{
ILI9341_SetPointPixel ( usX_Center + sCurrentX, usY_Center + sCurrentY ); //1,研究对象
ILI9341_SetPointPixel ( usX_Center - sCurrentX, usY_Center + sCurrentY ); //2
ILI9341_SetPointPixel ( usX_Center - sCurrentY, usY_Center + sCurrentX ); //3
ILI9341_SetPointPixel ( usX_Center - sCurrentY, usY_Center - sCurrentX ); //4
ILI9341_SetPointPixel ( usX_Center - sCurrentX, usY_Center - sCurrentY ); //5
ILI9341_SetPointPixel ( usX_Center + sCurrentX, usY_Center - sCurrentY ); //6
ILI9341_SetPointPixel ( usX_Center + sCurrentY, usY_Center - sCurrentX ); //7
ILI9341_SetPointPixel ( usX_Center + sCurrentY, usY_Center + sCurrentX ); //0
}
sCurrentX ++;
if ( sError < 0 )
sError += 4 * sCurrentX + 6;
else
{
sError += 10 + 4 * ( sCurrentX - sCurrentY );
sCurrentY --;
}
}
}
/**
* @brief 在 ILI9341 显示器上显示一个英文字符
* @param usX :在特定扫描方向下字符的起始X坐标
* @param usY :在特定扫描方向下该点的起始Y坐标
* @param cChar :要显示的英文字符
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispChar_EN ( uint16_t usX, uint16_t usY, const char cChar )
{
uint8_t byteCount, bitCount,fontLength;
uint16_t ucRelativePositon;
uint8_t *Pfont;
//对ascii码表偏移(字模表不包含ASCII表的前32个非图形符号)
ucRelativePositon = cChar - ' ';
//每个字模的字节数
fontLength = (LCD_Currentfonts->Width*LCD_Currentfonts->Height)/8;
//字模首地址
/*ascii码表偏移值乘以每个字模的字节数,求出字模的偏移位置*/
Pfont = (uint8_t *)&LCD_Currentfonts->table[ucRelativePositon * fontLength];
//设置显示窗口
ILI9341_OpenWindow ( usX, usY, LCD_Currentfonts->Width, LCD_Currentfonts->Height);
ILI9341_Write_Cmd ( CMD_SetPixel );
//按字节读取字模数据
//由于前面直接设置了显示窗口,显示数据会自动换行
for ( byteCount = 0; byteCount < fontLength; byteCount++ )
{
//一位一位处理要显示的颜色
for ( bitCount = 0; bitCount < 8; bitCount++ )
{
if ( Pfont[byteCount] & (0x80>>bitCount) )
ILI9341_Write_Data ( CurrentTextColor );
else
ILI9341_Write_Data ( CurrentBackColor );
}
}
}
/**
* @brief 在 ILI9341 显示器上显示英文字符串
* @param line :在特定扫描方向下字符串的起始Y坐标
* 本参数可使用宏LINE(0)、LINE(1)等方式指定文字坐标,
* 宏LINE(x)会根据当前选择的字体来计算Y坐标值。
* 显示中文且使用LINE宏时,需要把英文字体设置成Font8x16
* @param pStr :要显示的英文字符串的首地址
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispStringLine_EN ( uint16_t line, char * pStr )
{
uint16_t usX = 0;
while ( * pStr != '\0' )
{
if ( ( usX - ILI9341_DispWindow_X_Star + LCD_Currentfonts->Width ) > LCD_X_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
line += LCD_Currentfonts->Height;
}
if ( ( line - ILI9341_DispWindow_Y_Star + LCD_Currentfonts->Height ) > LCD_Y_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
line = ILI9341_DispWindow_Y_Star;
}
ILI9341_DispChar_EN ( usX, line, * pStr);
pStr ++;
usX += LCD_Currentfonts->Width;
}
}
/**
* @brief 在 ILI9341 显示器上显示英文字符串
* @param usX :在特定扫描方向下字符的起始X坐标
* @param usY :在特定扫描方向下字符的起始Y坐标
* @param pStr :要显示的英文字符串的首地址
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispString_EN ( uint16_t usX ,uint16_t usY, char * pStr )
{
while ( * pStr != '\0' )
{
if ( ( usX - ILI9341_DispWindow_X_Star + LCD_Currentfonts->Width ) > LCD_X_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY += LCD_Currentfonts->Height;
}
if ( ( usY - ILI9341_DispWindow_Y_Star + LCD_Currentfonts->Height ) > LCD_Y_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY = ILI9341_DispWindow_Y_Star;
}
ILI9341_DispChar_EN ( usX, usY, * pStr);
pStr ++;
usX += LCD_Currentfonts->Width;
}
}
/**
* @brief 在 ILI9341 显示器上显示英文字符串(沿Y轴方向)
* @param usX :在特定扫描方向下字符的起始X坐标
* @param usY :在特定扫描方向下字符的起始Y坐标
* @param pStr :要显示的英文字符串的首地址
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispString_EN_YDir ( uint16_t usX,uint16_t usY , char * pStr )
{
while ( * pStr != '\0' )
{
if ( ( usY - ILI9341_DispWindow_Y_Star + LCD_Currentfonts->Height ) >LCD_Y_LENGTH )
{
usY = ILI9341_DispWindow_Y_Star;
usX += LCD_Currentfonts->Width;
}
if ( ( usX - ILI9341_DispWindow_X_Star + LCD_Currentfonts->Width ) > LCD_X_LENGTH)
{
usX = ILI9341_DispWindow_X_Star;
usY = ILI9341_DispWindow_Y_Star;
}
ILI9341_DispChar_EN ( usX, usY, * pStr);
pStr ++;
usY += LCD_Currentfonts->Height;
}
}
/**
* @brief 在 ILI9341 显示器上显示一个中文字符
* @param usX :在特定扫描方向下字符的起始X坐标
* @param usY :在特定扫描方向下字符的起始Y坐标
* @param usChar :要显示的中文字符(国标码)
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispChar_CH ( uint16_t usX, uint16_t usY, uint16_t usChar )
{
uint8_t rowCount, bitCount;
uint8_t ucBuffer [ WIDTH_CH_CHAR*HEIGHT_CH_CHAR/8 ];
uint16_t usTemp;
// LCD_SetBackColor(BLACK);
//设置显示窗口
ILI9341_OpenWindow ( usX, usY, WIDTH_CH_CHAR, HEIGHT_CH_CHAR );
ILI9341_Write_Cmd ( CMD_SetPixel );
//取字模数据
GetGBKCode ( ucBuffer, usChar );
for ( rowCount = 0; rowCount < HEIGHT_CH_CHAR; rowCount++ )
{
/* 取出两个字节的数据,在lcd上即是一个汉字的一行 */
usTemp = ucBuffer [ rowCount * 2 ];
usTemp = ( usTemp << 8 );
usTemp |= ucBuffer [ rowCount * 2 + 1 ];
for ( bitCount = 0; bitCount < WIDTH_CH_CHAR; bitCount ++ )
{
if ( usTemp & ( 0x8000 >> bitCount ) ) //高位在前
ILI9341_Write_Data ( CurrentTextColor );
else
ILI9341_Write_Data ( CurrentBackColor );
}
}
}
/**
* @brief 在 ILI9341 显示器上显示中文字符串
* @param line :在特定扫描方向下字符串的起始Y坐标
* 本参数可使用宏LINE(0)、LINE(1)等方式指定文字坐标,
* 宏LINE(x)会根据当前选择的字体来计算Y坐标值。
* 显示中文且使用LINE宏时,需要把英文字体设置成Font8x16
* @param pStr :要显示的英文字符串的首地址
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispString_CH ( uint16_t usX , uint16_t usY, char * pStr )
{
uint16_t usCh;
while( * pStr != '\0' )
{
if ( ( usX - ILI9341_DispWindow_X_Star + WIDTH_CH_CHAR ) > LCD_X_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY += HEIGHT_CH_CHAR;
}
if ( ( usY - ILI9341_DispWindow_Y_Star + HEIGHT_CH_CHAR ) > LCD_Y_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY = ILI9341_DispWindow_Y_Star;
}
usCh = * ( uint16_t * ) pStr;
usCh = ( usCh << 8 ) + ( usCh >> 8 );
ILI9341_DispChar_CH ( usX, usY, usCh );
usX += WIDTH_CH_CHAR;
pStr += 2; //一个汉字两个字节
}
}
/**
* @brief 在 ILI9341 显示器上显示中英文字符串
* @param line :在特定扫描方向下字符串的起始Y坐标
* 本参数可使用宏LINE(0)、LINE(1)等方式指定文字坐标,
* 宏LINE(x)会根据当前选择的字体来计算Y坐标值。
* 显示中文且使用LINE宏时,需要把英文字体设置成Font8x16
* @param pStr :要显示的字符串的首地址
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispStringLine_EN_CH ( uint16_t line, char * pStr )
{
uint16_t usCh;
uint16_t usX = 0;
while( * pStr != '\0' )
{
if ( * pStr <= 126 ) //英文字符
{
if ( ( usX - ILI9341_DispWindow_X_Star + LCD_Currentfonts->Width ) > LCD_X_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
line += LCD_Currentfonts->Height;
}
if ( ( line - ILI9341_DispWindow_Y_Star + LCD_Currentfonts->Height ) > LCD_Y_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
line = ILI9341_DispWindow_Y_Star;
}
ILI9341_DispChar_EN ( usX, line, * pStr );
usX += LCD_Currentfonts->Width;
pStr ++;
}
else //汉字字符
{
if ( ( usX - ILI9341_DispWindow_X_Star + WIDTH_CH_CHAR ) > LCD_X_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
line += HEIGHT_CH_CHAR;
}
if ( ( line - ILI9341_DispWindow_Y_Star + HEIGHT_CH_CHAR ) > LCD_Y_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
line = ILI9341_DispWindow_Y_Star;
}
usCh = * ( uint16_t * ) pStr;
usCh = ( usCh << 8 ) + ( usCh >> 8 );
ILI9341_DispChar_CH ( usX, line, usCh );
usX += WIDTH_CH_CHAR;
pStr += 2; //一个汉字两个字节
}
}
}
/**
* @brief 在 ILI9341 显示器上显示中英文字符串
* @param usX :在特定扫描方向下字符的起始X坐标
* @param usY :在特定扫描方向下字符的起始Y坐标
* @param pStr :要显示的字符串的首地址
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispString_EN_CH ( uint16_t usX , uint16_t usY, char * pStr )
{
uint16_t usCh;
// LCD_SetBackColor(BLACK);
while( * pStr != '\0' )
{
if ( * pStr <= 126 ) //英文字符
{
if ( ( usX - ILI9341_DispWindow_X_Star + LCD_Currentfonts->Width ) > LCD_X_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY += LCD_Currentfonts->Height;
}
if ( ( usY - ILI9341_DispWindow_Y_Star + LCD_Currentfonts->Height ) > LCD_Y_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY = ILI9341_DispWindow_Y_Star;
}
ILI9341_DispChar_EN ( usX, usY, * pStr );
usX += LCD_Currentfonts->Width;
pStr ++;
}
else //汉字字符
{
if ( ( usX - ILI9341_DispWindow_X_Star + WIDTH_CH_CHAR ) > LCD_X_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY += HEIGHT_CH_CHAR;
}
if ( ( usY - ILI9341_DispWindow_Y_Star + HEIGHT_CH_CHAR ) > LCD_Y_LENGTH )
{
usX = ILI9341_DispWindow_X_Star;
usY = ILI9341_DispWindow_Y_Star;
}
usCh = * ( uint16_t * ) pStr;
usCh = ( usCh << 8 ) + ( usCh >> 8 );
ILI9341_DispChar_CH ( usX, usY, usCh );
usX += WIDTH_CH_CHAR;
pStr += 2; //一个汉字两个字节
}
}
}
/**
* @brief 在 ILI9341 显示器上显示中英文字符串(沿Y轴方向)
* @param usX :在特定扫描方向下字符的起始X坐标
* @param usY :在特定扫描方向下字符的起始Y坐标
* @param pStr :要显示的中英文字符串的首地址
* @note 可使用LCD_SetBackColor、LCD_SetTextColor、LCD_SetColors函数设置颜色
* @retval 无
*/
void ILI9341_DispString_EN_CH_YDir ( uint16_t usX,uint16_t usY , char * pStr )
{
uint16_t usCh;
while( * pStr != '\0' )
{
//统一使用汉字的宽高来计算换行
if ( ( usY - ILI9341_DispWindow_Y_Star + HEIGHT_CH_CHAR ) >LCD_Y_LENGTH )
{
usY = ILI9341_DispWindow_Y_Star;
usX += WIDTH_CH_CHAR;
}
if ( ( usX - ILI9341_DispWindow_X_Star + WIDTH_CH_CHAR ) > LCD_X_LENGTH)
{
usX = ILI9341_DispWindow_X_Star;
usY = ILI9341_DispWindow_Y_Star;
}
//显示
if ( * pStr <= 126 ) //英文字符
{
ILI9341_DispChar_EN ( usX, usY, * pStr);
pStr ++;
usY += HEIGHT_CH_CHAR;
}
else //汉字字符
{
usCh = * ( uint16_t * ) pStr;
usCh = ( usCh << 8 ) + ( usCh >> 8 );
ILI9341_DispChar_CH ( usX,usY , usCh );
usY += HEIGHT_CH_CHAR;
pStr += 2; //一个汉字两个字节
}
}
}
/***********************缩放字体****************************/
#define ZOOMMAXBUFF 16384
uint8_t zoomBuff[ZOOMMAXBUFF] = {0}; //用于缩放的缓存,最大支持到128*128
uint8_t zoomTempBuff[1024] = {0};
/**
* @brief 缩放字模,缩放后的字模由1个像素点由8个数据位来表示
0x01表示笔迹,0x00表示空白区
* @param in_width :原始字符宽度
* @param in_heig :原始字符高度
* @param out_width :缩放后的字符宽度
* @param out_heig:缩放后的字符高度
* @param in_ptr :字库输入指针 注意:1pixel 1bit
* @param out_ptr :缩放后的字符输出指针 注意: 1pixel 8bit
* out_ptr实际上没有正常输出,改成了直接输出到全局指针zoomBuff中
* @param en_cn :0为英文,1为中文
* @retval 无
*/
void ILI9341_zoomChar(uint16_t in_width, //原始字符宽度
uint16_t in_heig, //原始字符高度
uint16_t out_width, //缩放后的字符宽度
uint16_t out_heig, //缩放后的字符高度
uint8_t *in_ptr, //字库输入指针 注意:1pixel 1bit
uint8_t *out_ptr, //缩放后的字符输出指针 注意: 1pixel 8bit
uint8_t en_cn) //0为英文,1为中文
{
uint8_t *pts,*ots;
//根据源字模及目标字模大小,设定运算比例因子,左移16是为了把浮点运算转成定点运算
unsigned int xrIntFloat_16=(in_width<<16)/out_width+1;
unsigned int yrIntFloat_16=(in_heig<<16)/out_heig+1;
unsigned int srcy_16=0;
unsigned int y,x;
uint8_t *pSrcLine;
uint16_t byteCount,bitCount;
//检查参数是否合法
if(in_width >= 32) return; //字库不允许超过32像素
if(in_width * in_heig == 0) return;
if(in_width * in_heig >= 1024 ) return; //限制输入最大 32*32
if(out_width * out_heig == 0) return;
if(out_width * out_heig >= ZOOMMAXBUFF ) return; //限制最大缩放 128*128
pts = (uint8_t*)&zoomTempBuff;
//为方便运算,字库的数据由1 pixel/1bit 映射到1pixel/8bit
//0x01表示笔迹,0x00表示空白区
if(en_cn == 0x00)//英文
{
//英文和中文字库上下边界不对,可在此处调整。需要注意tempBuff防止溢出
for(byteCount=0;byteCount<in_heig*in_width/8;byteCount++)
{
for(bitCount=0;bitCount<8;bitCount++)
{
//把源字模数据由位映射到字节
//in_ptr里bitX为1,则pts里整个字节值为1
//in_ptr里bitX为0,则pts里整个字节值为0
*pts++ = (in_ptr[byteCount] & (0x80>>bitCount))?1:0;
}
}
}
else //中文
{
for(byteCount=0;byteCount<in_heig*in_width/8;byteCount++)
{
for(bitCount=0;bitCount<8;bitCount++)
{
//把源字模数据由位映射到字节
//in_ptr里bitX为1,则pts里整个字节值为1
//in_ptr里bitX为0,则pts里整个字节值为0
*pts++ = (in_ptr[byteCount] & (0x80>>bitCount))?1:0;
}
}
}
//zoom过程
pts = (uint8_t*)&zoomTempBuff; //映射后的源数据指针
ots = (uint8_t*)&zoomBuff; //输出数据的指针
for (y=0;y<out_heig;y++) /*行遍历*/
{
unsigned int srcx_16=0;
pSrcLine=pts+in_width*(srcy_16>>16);
for (x=0;x<out_width;x++) /*行内像素遍历*/
{
ots[x]=pSrcLine[srcx_16>>16]; //把源字模数据复制到目标指针中
srcx_16+=xrIntFloat_16; //按比例偏移源像素点
}
srcy_16+=yrIntFloat_16; //按比例偏移源像素点
ots+=out_width;
}
/*!!!缩放后的字模数据直接存储到全局指针zoomBuff里了*/
out_ptr = (uint8_t*)&zoomBuff; //out_ptr没有正确传出,后面调用直接改成了全局变量指针!
/*实际中如果使用out_ptr不需要下面这一句!!!
只是因为out_ptr没有使用,会导致warning。强迫症*/
out_ptr++;
}
/**
* @brief 利用缩放后的字模显示字符
* @param Xpos :字符显示位置x
* @param Ypos :字符显示位置y
* @param Font_width :字符宽度
* @param Font_Heig:字符高度
* @param c :要显示的字模数据
* @param DrawModel :是否反色显示
* @retval 无
*/
void ILI9341_DrawChar_Ex(uint16_t usX, //字符显示位置x
uint16_t usY, //字符显示位置y
uint16_t Font_width, //字符宽度
uint16_t Font_Height, //字符高度
uint8_t *c, //字模数据
uint16_t DrawModel) //是否反色显示
{
uint32_t index = 0, counter = 0;
//设置显示窗口
ILI9341_OpenWindow ( usX, usY, Font_width, Font_Height);
ILI9341_Write_Cmd ( CMD_SetPixel );
//按字节读取字模数据
//由于前面直接设置了显示窗口,显示数据会自动换行
for ( index = 0; index < Font_Height; index++ )
{
//一位一位处理要显示的颜色
for ( counter = 0; counter < Font_width; counter++ )
{
//缩放后的字模数据,以一个字节表示一个像素位
//整个字节值为1表示该像素为笔迹
//整个字节值为0表示该像素为背景
if ( *c++ == DrawModel )
ILI9341_Write_Data ( CurrentBackColor );
else
ILI9341_Write_Data ( CurrentTextColor );
}
}
}
/**
* @brief 利用缩放后的字模显示字符串
* @param Xpos :字符显示位置x
* @param Ypos :字符显示位置y
* @param Font_width :字符宽度,英文字符在此基础上/2。注意为偶数
* @param Font_Heig:字符高度,注意为偶数
* @param c :要显示的字符串
* @param DrawModel :是否反色显示
* @retval 无
*/
void ILI9341_DisplayStringEx(uint16_t x, //字符显示位置x
uint16_t y, //字符显示位置y
uint16_t Font_width, //要显示的字体宽度,英文字符在此基础上/2。注意为偶数
uint16_t Font_Height, //要显示的字体高度,注意为偶数
uint8_t *ptr, //显示的字符内容
uint16_t DrawModel) //是否反色显示
{
uint16_t Charwidth = Font_width; //默认为Font_width,英文宽度为中文宽度的一半
uint8_t *psr;
uint8_t Ascii; //英文
uint16_t usCh; //中文
uint8_t ucBuffer [ WIDTH_CH_CHAR*HEIGHT_CH_CHAR/8 ];
while ( *ptr != '\0')
{
/****处理换行*****/
if ( ( x - ILI9341_DispWindow_X_Star + Charwidth ) > LCD_X_LENGTH )
{
x = ILI9341_DispWindow_X_Star;
y += Font_Height;
}
if ( ( y - ILI9341_DispWindow_Y_Star + Font_Height ) > LCD_Y_LENGTH )
{
x = ILI9341_DispWindow_X_Star;
y = ILI9341_DispWindow_Y_Star;
}
if(*ptr > 0x80) //如果是中文
{
Charwidth = Font_width;
usCh = * ( uint16_t * ) ptr;
usCh = ( usCh << 8 ) + ( usCh >> 8 );
GetGBKCode ( ucBuffer, usCh ); //取字模数据
//缩放字模数据,源字模为16*16
ILI9341_zoomChar(WIDTH_CH_CHAR,HEIGHT_CH_CHAR,Charwidth,Font_Height,(uint8_t *)&ucBuffer,psr,1);
//显示单个字符
ILI9341_DrawChar_Ex(x,y,Charwidth,Font_Height,(uint8_t*)&zoomBuff,DrawModel);
x+=Charwidth;
ptr+=2;
}
else
{
Charwidth = Font_width / 2;
Ascii = *ptr - 32;
//使用16*24字体缩放字模数据
ILI9341_zoomChar(16,24,Charwidth,Font_Height,(uint8_t *)&Font16x24.table[Ascii * Font16x24.Height*Font16x24.Width/8],psr,0);
//显示单个字符
ILI9341_DrawChar_Ex(x,y,Charwidth,Font_Height,(uint8_t*)&zoomBuff,DrawModel);
x+=Charwidth;
ptr++;
}
}
}
/**
* @brief 利用缩放后的字模显示字符串(沿Y轴方向)
* @param Xpos :字符显示位置x
* @param Ypos :字符显示位置y
* @param Font_width :字符宽度,英文字符在此基础上/2。注意为偶数
* @param Font_Heig:字符高度,注意为偶数
* @param c :要显示的字符串
* @param DrawModel :是否反色显示
* @retval 无
*/
void ILI9341_DisplayStringEx_YDir(uint16_t x, //字符显示位置x
uint16_t y, //字符显示位置y
uint16_t Font_width, //要显示的字体宽度,英文字符在此基础上/2。注意为偶数
uint16_t Font_Height, //要显示的字体高度,注意为偶数
uint8_t *ptr, //显示的字符内容
uint16_t DrawModel) //是否反色显示
{
uint16_t Charwidth = Font_width; //默认为Font_width,英文宽度为中文宽度的一半
uint8_t *psr;
uint8_t Ascii; //英文
uint16_t usCh; //中文
uint8_t ucBuffer [ WIDTH_CH_CHAR*HEIGHT_CH_CHAR/8 ];
while ( *ptr != '\0')
{
//统一使用汉字的宽高来计算换行
if ( ( y - ILI9341_DispWindow_X_Star + Font_width ) > LCD_X_LENGTH )
{
y = ILI9341_DispWindow_X_Star;
x += Font_width;
}
if ( ( x - ILI9341_DispWindow_Y_Star + Font_Height ) > LCD_Y_LENGTH )
{
y = ILI9341_DispWindow_X_Star;
x = ILI9341_DispWindow_Y_Star;
}
if(*ptr > 0x80) //如果是中文
{
Charwidth = Font_width;
usCh = * ( uint16_t * ) ptr;
usCh = ( usCh << 8 ) + ( usCh >> 8 );
GetGBKCode ( ucBuffer, usCh ); //取字模数据
//缩放字模数据,源字模为16*16
ILI9341_zoomChar(WIDTH_CH_CHAR,HEIGHT_CH_CHAR,Charwidth,Font_Height,(uint8_t *)&ucBuffer,psr,1);
//显示单个字符
ILI9341_DrawChar_Ex(x,y,Charwidth,Font_Height,(uint8_t*)&zoomBuff,DrawModel);
y+=Font_Height;
ptr+=2;
}
else
{
Charwidth = Font_width / 2;
Ascii = *ptr - 32;
//使用16*24字体缩放字模数据
ILI9341_zoomChar(16,24,Charwidth,Font_Height,(uint8_t *)&Font16x24.table[Ascii * Font16x24.Height*Font16x24.Width/8],psr,0);
//显示单个字符
ILI9341_DrawChar_Ex(x,y,Charwidth,Font_Height,(uint8_t*)&zoomBuff,DrawModel);
y+=Font_Height;
ptr++;
}
}
}
/**
* @brief 设置英文字体类型
* @param fonts: 指定要选择的字体
* 参数为以下值之一
* @arg:Font24x32;
* @arg:Font16x24;
* @arg:Font8x16;
* @retval None
*/
void LCD_SetFont(sFONT *fonts)
{
LCD_Currentfonts = fonts;
}
/**
* @brief 获取当前字体类型
* @param None.
* @retval 返回当前字体类型
*/
sFONT *LCD_GetFont(void)
{
return LCD_Currentfonts;
}
/**
* @brief 设置LCD的前景(字体)及背景颜色,RGB565
* @param TextColor: 指定前景(字体)颜色
* @param BackColor: 指定背景颜色
* @retval None
*/
void LCD_SetColors(uint16_t TextColor, uint16_t BackColor)
{
CurrentTextColor = TextColor;
CurrentBackColor = BackColor;
}
/**
* @brief 获取LCD的前景(字体)及背景颜色,RGB565
* @param TextColor: 用来存储前景(字体)颜色的指针变量
* @param BackColor: 用来存储背景颜色的指针变量
* @retval None
*/
void LCD_GetColors(uint16_t *TextColor, uint16_t *BackColor)
{
*TextColor = CurrentTextColor;
*BackColor = CurrentBackColor;
}
/**
* @brief 设置LCD的前景(字体)颜色,RGB565
* @param Color: 指定前景(字体)颜色
* @retval None
*/
void LCD_SetTextColor(uint16_t Color)
{
CurrentTextColor = Color;
}
/**
* @brief 设置LCD的背景颜色,RGB565
* @param Color: 指定背景颜色
* @retval None
*/
void LCD_SetBackColor(uint16_t Color)
{
CurrentBackColor = Color;
}
/**
* @brief 清除某行文字
* @param Line: 指定要删除的行
* 本参数可使用宏LINE(0)、LINE(1)等方式指定要删除的行,
* 宏LINE(x)会根据当前选择的字体来计算Y坐标值,并删除当前字体高度的第x行。
* @retval None
*/
void LCD_ClearLine(uint16_t Line)
{
ILI9341_Clear(0,Line,LCD_X_LENGTH,((sFONT *)LCD_GetFont())->Height); /* 清屏,显示全黑 */
}
/*********************end of file*************************/
| 2.1875 | 2 |
2024-11-18T19:03:01.763190+00:00
| 2016-09-30T09:22:41 |
d790e8057117d460d2ecbe32550ba53acdeafb70
|
{
"blob_id": "d790e8057117d460d2ecbe32550ba53acdeafb70",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-30T09:22:41",
"content_id": "c99ac55fc16e3ffa27e7edbcafb8ffed9d49575e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "dbd8d6be7b3f99972b6eaf4d23338413247e8738",
"extension": "c",
"filename": "mqdraw.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": 4536,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/Reference/radiance/src/meta/mqdraw.c",
"provenance": "stackv2-0058.json.gz:174055",
"repo_name": "CamelCarmack/SHTest",
"revision_date": "2016-09-30T09:22:41",
"revision_id": "4ef130bcb38beab3bf8882d448d0ed22535e8543",
"snapshot_id": "5fc6e99d4057d6534c82d9c11275b82bfc0f20e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CamelCarmack/SHTest/4ef130bcb38beab3bf8882d448d0ed22535e8543/Reference/radiance/src/meta/mqdraw.c",
"visit_date": "2023-06-14T10:23:52.667022"
}
|
stackv2
|
#ifndef lint
static const char RCSid[] = "$Id: mqdraw.c,v 1.1 2003/02/22 02:07:26 greg Exp $";
#endif
/*
* Interface to MacIntosh QuickDraw routines
*
* 6/5/85
*/
#include "meta.h"
#include "macplot.h"
static short curpat = -1; /* current line drawing pattern */
static short curpsiz = -1; /* current pen size */
static short curpmod = -1; /* current pen mode */
static int xpos = -1, /* current position */
ypos = -1;
printstr(p) /* output a string */
register PRIMITIVE *p;
{
char *ctop(), *ptoc();
MoveTo(mapx(p->xy[XMN]), mapy(p->xy[YMN]));
DrawString(ctop(p->args));
ptoc(p->args);
xpos = -1;
ypos = -1;
}
plotlseg(p) /* plot a line segment */
register PRIMITIVE *p;
{
static short right = FALSE;
int x1, x2, y1, y2;
short pp, ps;
pp = (p->arg0 >> 4) & 03;
if (p->arg0 & 0100 && pp != 0)
pp += 03;
if (pp != curpat) {
PenPat(macpat[pp]);
curpat = pp;
}
ps = WIDTH((p->arg0 >> 2) & 03);
if (ps != curpsiz) {
PenSize(CONV(ps, dxsize) + 1, CONV(ps, dysize) + 1);
curpsiz = ps;
}
if (curpmod != patOr) {
PenMode(patOr);
curpmod = patOr;
}
x1 = mapx(p->xy[XMN]);
x2 = mapx(p->xy[XMX]);
if (p->arg0 & 0100) {
y1 = mapy(p->xy[YMX]);
y2 = mapy(p->xy[YMN]);
} else {
y1 = mapy(p->xy[YMN]);
y2 = mapy(p->xy[YMX]);
}
if (x1 == xpos && y1 == ypos) {
LineTo(x2, y2);
xpos = x2;
ypos = y2;
} else if (x2 == xpos && y2 == ypos) {
LineTo(x1, y1);
xpos = x1;
ypos = y1;
} else if (right = !right) {
MoveTo(x1, y1);
LineTo(x2, y2);
xpos = x2;
ypos = y2;
} else {
MoveTo(x2, y2);
LineTo(x1, y1);
xpos = x1;
ypos = y1;
}
}
setfill(a0) /* set filling mode */
register int a0;
{
short pp, pm;
pp = pati[(a0 >> 2) & 03];
if (pp != curpat) {
PenPat(macpat[pp]);
curpat = pp;
}
if (a0 & 0100)
pm = patXor;
else
pm = patOr;
if (pm != curpmod) {
PenMode(pm);
curpmod = pm;
}
}
fillrect(p) /* fill a rectangle */
register PRIMITIVE *p;
{
static Rect r;
r.left = mapx(p->xy[XMN]);
r.right = mapx(p->xy[XMX]);
r.top = mapy(p->xy[YMX]);
r.bottom = mapy(p->xy[YMN]);
setfill(p->arg0);
PaintRect(&r);
}
filltri(p) /* fill a triangle */
register PRIMITIVE *p;
{
PolyHandle polyh;
int x[4], y[4];
int skipv;
register int i;
polyh = OpenPoly();
x[0] = x[1] = mapx(p->xy[XMN]);
x[2] = x[3] = mapx(p->xy[XMX]);
y[1] = y[2] = mapy(p->xy[YMN]);
y[0] = y[3] = mapy(p->xy[YMX]);
skipv = (p->arg0 >> 4) & 03;
if (skipv == 3)
MoveTo(x[2], y[2]);
else
MoveTo(x[3], y[3]);
for (i = 0; i < 4; i++)
if (i != skipv)
LineTo(x[i], y[i]);
ClosePoly();
setfill(p->arg0);
PaintPoly(polyh);
KillPoly(polyh);
xpos = -1;
ypos = -1;
}
xform(xp, yp, p) /* transform a point according to p */
register int *xp, *yp;
register PRIMITIVE *p;
{
int x, y;
switch (p->arg0 & 060) {
case 0: /* right */
x = *xp;
y = *yp;
break;
case 020: /* up */
x = (XYSIZE-1) - *yp;
y = *xp;
break;
case 040: /* left */
x = (XYSIZE-1) - *xp;
y = (XYSIZE-1) - *yp;
break;
case 060: /* down */
x = *yp;
y = (XYSIZE-1) - *xp;
break;
}
*xp = CONV(x, p->xy[XMX] - p->xy[XMN]) + p->xy[XMN];
*yp = CONV(y, p->xy[YMX] - p->xy[YMN]) + p->xy[YMN];
}
fillpoly(p) /* fill a polygon */
register PRIMITIVE *p;
{
int x0, y0, curx, cury;
PolyHandle polyh;
char *nextscan();
register char *s;
polyh = OpenPoly();
if ((s = nextscan(nextscan(p->args, "%d", &x0), "%d", &y0)) == NULL)
error(USER, "illegal polygon spec in fillpoly");
xform(&x0, &y0, p);
x0 = mapx(x0); y0 = mapy(y0);
MoveTo(x0, y0);
while ((s = nextscan(nextscan(s, "%d", &curx), "%d", &cury)) != NULL) {
xform(&curx, &cury, p);
curx = mapx(curx); cury = mapy(cury);
LineTo(curx, cury);
}
LineTo(x0, y0);
ClosePoly();
if (p->arg0 & 0100) { /* draw border */
if (curpat != 0) {
PenPat(macpat[0]);
curpat = 0;
}
if (curpsiz != 1) {
PenSize(1, 1);
curpsiz = 1;
}
if (curpmod != patOr) {
PenMode(patOr);
curpmod = patOr;
}
FramePoly(polyh);
}
setfill(p->arg0 & 077);
PaintPoly(polyh);
KillPoly(polyh);
xpos = -1;
ypos = -1;
}
| 2.265625 | 2 |
2024-11-18T19:03:01.808280+00:00
| 2017-05-06T16:56:48 |
bcdb1fb80baa6cf468fa3e27b8567f3514d4267c
|
{
"blob_id": "bcdb1fb80baa6cf468fa3e27b8567f3514d4267c",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-06T16:56:48",
"content_id": "45351ebded3133147959be4eff9bb32b92d5ee91",
"detected_licenses": [
"MIT"
],
"directory_id": "f9b9634e0b7d55ccd844a1416fbbcab3b3c395c0",
"extension": "h",
"filename": "paramlist.h",
"fork_events_count": 0,
"gha_created_at": "2017-03-20T20:59:47",
"gha_event_created_at": "2017-05-04T17:53:47",
"gha_language": "C",
"gha_license_id": null,
"github_id": 85626641,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1214,
"license": "MIT",
"license_type": "permissive",
"path": "/lexyacc/paramlist.h",
"provenance": "stackv2-0058.json.gz:174183",
"repo_name": "kuannie1/SoftSysEccentricEucalyptus",
"revision_date": "2017-05-06T16:56:48",
"revision_id": "7d86dd706de14cc700b4b5767271fe467deffaf5",
"snapshot_id": "51133a1af0b653993ea22cf0a765030933bc048d",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/kuannie1/SoftSysEccentricEucalyptus/7d86dd706de14cc700b4b5767271fe467deffaf5/lexyacc/paramlist.h",
"visit_date": "2021-01-22T23:21:00.945651"
}
|
stackv2
|
/* Paramlist.h
*
* Paramlist.h is a header file that declares and defines the
* the ParamNode structure, to store lists of variables and
* their values.
*
* Software Systems Spring 2017 - Olin College
* Eccentric Eucalyptus
*
*/
#ifndef paramlist_h
#define paramlist_h
#include "parser.h"
/* param_node struct stores a single variable name and value
* pair, and a reference to the next ParamNode
*
* Members:
* param_name: name of the variable
* anonymous union:
* val_flt: value of variable. Stored in a union for future
* scalability
* type: enum Type, type of variable. Currently can only be a
* float; however this field exists for scalability,
* along with the union above.
* next: reference to the next ParamNode
*/
typedef struct param_node {
char* param_name;
union {
float val_flt;
};
Type type;
struct param_node *next;
} ParamNode;
ParamNode *make_param_node_float(char* name, float val, ParamNode *next);
void print_param_list(ParamNode **list);
char* pop_param(ParamNode **list);
void push_param_float(ParamNode **list, char* name, float val);
float get_value(ParamNode** varlist, char* varname);
#endif
| 2.71875 | 3 |
2024-11-18T19:53:03.172782+00:00
| 2017-11-25T06:10:22 |
4bcc4ae0e15b0dc86efe5f4f863617bedf9fdf8e
|
{
"blob_id": "4bcc4ae0e15b0dc86efe5f4f863617bedf9fdf8e",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-25T06:10:22",
"content_id": "6af61a6888fb7cea310f37c0318ea2fe19132a01",
"detected_licenses": [
"MIT"
],
"directory_id": "722438fd5179a6a9b0e6764ffb90786e75c82b4e",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5864,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0061.json.gz:386",
"repo_name": "sudoconf/Arashi",
"revision_date": "2017-11-25T06:10:22",
"revision_id": "12135c429005685e5d901d5f4f866360601ae7c6",
"snapshot_id": "127bd0f366bb4a86e24aaf6696f4f0c92598afe4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sudoconf/Arashi/12135c429005685e5d901d5f4f866360601ae7c6/main.c",
"visit_date": "2020-03-28T17:01:58.367338"
}
|
stackv2
|
#include <stdio.h>
#include <uev/uev.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>
#include "channels/tun_interface.h"
#include "channels/simple_tcp.h"
#include "channels/socks5_client.h"
#include "external/log.h"
#include "signal.h"
#include "router.h"
static uev_ctx_t ctx;
static channel_tun_t tun;
static channel_simple_tcp_t tcp;
static socks5_client_t socks5_client;
void cleanup_exit(uev_t *w, void *arg, int events)
{
if (w != NULL) uev_exit(w->ctx);
simple_tcp_clean(&tcp);
channel_tun_close(&tun);
log_info("Server closed");
}
typedef struct {
char *tun_dev_name;
bool tcp_listen; // true=listen, false=connect
char *tcp_host;
char *tcp_port;
bool use_socks;
char *socks_host;
char *socks_port;
bool verbose;
} arg_t;
void print_help(void);
#define CHECK_NEXT_PARAMETER(x) if (++i >= argc) {log_fatal("Missing parameter for \"%s\"", x);return false;}
// return true if parsing success
bool parse_arg(int argc, char *argv[], arg_t *arg) {
if (argc <= 1) {
print_help();
return false;
}
arg->tun_dev_name = NULL;
arg->verbose = false;
arg->tcp_listen = true;
arg->tcp_host = NULL;
arg->tcp_port = NULL;
arg->use_socks = false;
arg->socks_host = NULL;
arg->socks_port = NULL;
for (ssize_t i = 1; i < argc; i++) {
if (0 == strncmp("--tun", argv[i], 6)) {
CHECK_NEXT_PARAMETER("--tun");
arg->tun_dev_name = argv[i];
} else if (0 == strncmp("--tcp-connect", argv[i], 14)) {
CHECK_NEXT_PARAMETER("--tcp-connect")
CHECK_NEXT_PARAMETER("--tcp-connect")
arg->tcp_listen = false;
arg->tcp_host = argv[i-1];
arg->tcp_port = argv[i];
} else if (0 == strncmp("--tcp-listen", argv[i], 13)) {
CHECK_NEXT_PARAMETER("--tcp-listen")
arg->tcp_listen = true;
arg->tcp_port = argv[i];
} else if (0 == strncmp("--via-socks5", argv[i], 13)) {
CHECK_NEXT_PARAMETER("--via-socks5")
CHECK_NEXT_PARAMETER("--tcp-connect")
arg->use_socks = true;
arg->socks_host = argv[i-1];
arg->socks_port = argv[i];
} else if (0 == strncmp("--verbose", argv[i], 10)) {
arg->verbose = true;
} else if (0 == strncmp("--help", argv[i], 7)) {
print_help();
return false;
} else {
log_fatal("Unknown argument \"%s\"", argv[i]);
return false;
}
}
if (arg->tun_dev_name == NULL) {
log_fatal("No TUN device specified");
return false;
} else if (arg->tcp_port == NULL) {
log_fatal("No TCP connection specified");
return false;
} else if (arg->use_socks && arg->tcp_listen) {
log_fatal("Socks5 client bind not implemented");
}
return true;
}
/* ./arashi
* --tun [TUN device name]
* --tcp-connect [peer_ip] [peer_port]
* --tcp-listen [listen_port]
* --via-socks5 [socks_ip] [socks_ip]
* --verbose
*/
void print_help(void) {
printf( "./arashi\n"
" --tun [TUN device name]\n"
" --tcp-connect [peer_ip] [peer_port]\n"
" --tcp-listen [listen_port]\n"
" --via-socks5 [socks_ip] [socks_ip]\n"
" --verbose\n");
}
int main(int argc, char *argv[]) {
arg_t arg;
if (!parse_arg(argc, argv, &arg)) {
exit(-1);
}
if (arg.verbose) {
log_set_level(LOG_DEBUG);
} else {
log_set_level(LOG_INFO);
}
uev_init(&ctx);
uev_t sigterm_watcher, sigint_watcher;
uev_signal_init(&ctx, &sigterm_watcher, cleanup_exit, NULL, SIGTERM);
uev_signal_init(&ctx, &sigint_watcher, cleanup_exit, NULL, SIGINT);
log_info("Event context created");
const char* tun_name = arg.tun_dev_name;
int tun_fd = channel_tun_init(&tun, tun_name, &ctx);
if (tun_fd < 0) {
log_fatal("failed to open tun device: %s", strerror(errno));
exit(-1);
}
log_info("TUN device allocated: fd = %d", tun_fd);
simple_tcp_init(&tcp);
if (arg.tcp_listen) {
int err = simple_tcp_listen(&tcp, "0.0.0.0", arg.tcp_port, &ctx);
if (err < 0) {
log_fatal("failed to open listen socket: %s", strerror(errno));
exit(-1);
}
log_info("Listening socket created");
} else {
if (arg.use_socks) {
socks5_init(&socks5_client);
log_info("connecting to socks5 server");
if (0 > socks5_auth(&socks5_client, arg.socks_host, arg.socks_port)) {
log_fatal("cannot authenticate with socks5 server", strerror(errno));
exit(-1);
}
log_info("connecting to tun server");
if (0 > socks5_connect(&socks5_client, arg.tcp_host, arg.tcp_port)) {
log_fatal("cannot connect to remote TUN server", strerror(errno));
exit(-1);
}
if (0 > simple_tcp_via_socks5(&tcp, &socks5_client, &ctx)) {
log_fatal("cannot connect to remote TUN server", strerror(errno));
exit(-1);
}
} else { // do not use socks5
if (0 > simple_tcp_connect(&tcp, arg.tcp_host, arg.tcp_port, &ctx)) {
log_fatal("failed to connect: %s", strerror(errno));
exit(-1);
}
}
log_info("Connected to peer");
}
router_init();
default_router.ctx = &ctx;
router_add_forward_channel(&tun);
router_add_forward_channel(&tcp);
router_add_backward_channel(&tcp);
router_add_backward_channel(&tun);
log_info("Server started");
uev_run(&ctx, 0);
cleanup_exit(NULL, NULL, 0);
}
| 2.390625 | 2 |
2024-11-18T19:53:03.520648+00:00
| 2018-11-06T15:31:53 |
d13716ee1bf963eb8471c5e88a93967ed4aa9b32
|
{
"blob_id": "d13716ee1bf963eb8471c5e88a93967ed4aa9b32",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-06T15:31:53",
"content_id": "349dabed6ac284fbd0300bf37fdf3e3e2176573a",
"detected_licenses": [
"MIT"
],
"directory_id": "259179e2c05011ff42df8d96a1974e997f2e6ada",
"extension": "c",
"filename": "fcfs.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-19T10:15:32",
"gha_event_created_at": "2018-10-19T10:15:35",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 153764740,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 805,
"license": "MIT",
"license_type": "permissive",
"path": "/fcfs.c",
"provenance": "stackv2-0061.json.gz:642",
"repo_name": "SumitSh7/disk-scheduling-mem-mgmt",
"revision_date": "2018-11-06T15:31:53",
"revision_id": "165961f8ca8855926a81988da4fdc44ede9fb436",
"snapshot_id": "b9a117c27505f2204a19a1f6260a2a49d6d48ed1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SumitSh7/disk-scheduling-mem-mgmt/165961f8ca8855926a81988da4fdc44ede9fb436/fcfs.c",
"visit_date": "2020-04-01T23:35:06.034856"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int queue[100], q_size, head, seek =0, diff;
float avg;
printf("%s\n", "***FCFS Disk Scheduling Algorithm***");
printf("%s\n", "Enter the size of the queue");
scanf("%d", &q_size);
printf("%s\n", "Enter queue elements");
for(int i=1; i<=q_size; i++)
{
scanf("%d",&queue[i]);
}
printf("%s\n","Enter initial head position");
scanf("%d", &head);
queue[0]=head;
for(int j=0; j<=q_size-1; j++)
{
diff = abs(queue[j]-queue[j+1]);
seek += diff;
printf("Move from %d to %d with Seek %d\n",queue[j],queue[j+1],diff);
}
printf("\nTotal seek time is %d\t",seek);
avg = seek/(float)q_size;
printf("\nAverage seek time is %f\t", avg);
return 0;
}
| 3.296875 | 3 |
2024-11-18T19:53:03.905653+00:00
| 2015-03-02T07:39:23 |
70867b14f771450aa6987d17a0a8825a2045ca66
|
{
"blob_id": "70867b14f771450aa6987d17a0a8825a2045ca66",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-02T07:39:23",
"content_id": "1a4d2b694bfd6e8915ae907dc842ddbc8e354628",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f37c3546f39d7ebc4236c043e740d68bf826e8c1",
"extension": "c",
"filename": "rc.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": 1305,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/extensions/crypt/sources/rc.c",
"provenance": "stackv2-0061.json.gz:770",
"repo_name": "sandy-slin/kinomajs",
"revision_date": "2015-03-02T07:39:23",
"revision_id": "567b52be74ec1482e0bab2d370781a7188aeb0ab",
"snapshot_id": "f08f60352b63f1d3fad3f6b0e9a5e4bc8025f082",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sandy-slin/kinomajs/567b52be74ec1482e0bab2d370781a7188aeb0ab/extensions/crypt/sources/rc.c",
"visit_date": "2020-12-24T22:21:05.506599"
}
|
stackv2
|
/*
Copyright (C) 2010-2015 Marvell International Ltd.
Copyright (C) 2002-2010 Kinoma, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "cryptTypes.h"
#include "rc.h"
#if !FSK_NO_RC4
void
rc4_init(rc4_state *rc4, const UInt8 *key, int keySize)
{
int i;
UInt8 j, t;
UInt8 *s;
for (i = 0, s = rc4->state; i < 256; i++)
*s++ = i;
for (i = j = 0, s = rc4->state; i < 256; i++) {
j += s[i] + key[i % keySize];
t = s[i];
s[i] = s[j];
s[j] = t;
}
rc4->i = rc4->j = 0;
}
void
rc4_process(UInt8 *bp, int bufsiz, rc4_state *rc4)
{
UInt8 *bufend = bp + bufsiz;
UInt8 i, j, t;
UInt8 *s = rc4->state;
while (bp < bufend) {
i = ++rc4->i;
j = rc4->j += s[i];
t = s[i];
s[i] = s[j];
s[j] = t;
t = s[i] + s[j];
*bp++ ^= s[t];
}
}
#endif
| 2.140625 | 2 |
2024-11-18T19:53:04.039717+00:00
| 2018-02-21T20:58:17 |
076248726034bd3df79af5e92869ae99a494b559
|
{
"blob_id": "076248726034bd3df79af5e92869ae99a494b559",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-23T18:20:55",
"content_id": "74585d2c9528de5df08177ee072677dbf484874e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "61cffd4bb110c0215eb8e8bb5fb10b1130a1d5b0",
"extension": "c",
"filename": "odp_ipsec_offload_cache.c",
"fork_events_count": 1,
"gha_created_at": "2017-12-20T21:03:37",
"gha_event_created_at": "2018-01-03T12:05:07",
"gha_language": "C",
"gha_license_id": null,
"github_id": 114930968,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3520,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/example/ipsec_offload/odp_ipsec_offload_cache.c",
"provenance": "stackv2-0061.json.gz:1026",
"repo_name": "semihalf-mazur-michal/odp-dpdk",
"revision_date": "2018-02-21T20:58:17",
"revision_id": "5f931a30fc8bfe74f3a17c776ef7c69e1d4db528",
"snapshot_id": "6b01ef4077dbe6a4fede2b9b57f7dc9b63a2dcf2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/semihalf-mazur-michal/odp-dpdk/5f931a30fc8bfe74f3a17c776ef7c69e1d4db528/example/ipsec_offload/odp_ipsec_offload_cache.c",
"visit_date": "2021-05-06T03:54:57.167521"
}
|
stackv2
|
/*
* Copyright (c) 2017 NXP. All rights reserved.
*/
/* Copyright (c) 2017, Linaro Limited
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdlib.h>
#include <string.h>
#include <example_debug.h>
#include <odp.h>
#include <odp/helper/ipsec.h>
#include <odp/helper/ip.h>
#include <odp_ipsec_offload_cache.h>
/** Global pointer to ipsec_cache db */
ipsec_cache_t *ipsec_cache;
#define IPDEFTTL 64
void init_ipsec_cache(void)
{
odp_shm_t shm;
shm = odp_shm_reserve("shm_ipsec_cache",
sizeof(ipsec_cache_t),
ODP_CACHE_LINE_SIZE,
0);
ipsec_cache = odp_shm_addr(shm);
if (ipsec_cache == NULL)
EXAMPLE_ABORT("Error: shared mem alloc failed.\n");
memset(ipsec_cache, 0, sizeof(*ipsec_cache));
}
int create_ipsec_cache_entry(sa_db_entry_t *cipher_sa,
sa_db_entry_t *auth_sa,
tun_db_entry_t *tun,
odp_bool_t in,
odp_queue_t completionq)
{
odp_ipsec_sa_param_t sa_params;
ipsec_cache_entry_t *entry;
odp_ipsec_sa_t sa;
uint32_t src_ip, dst_ip;
odp_ipsec_sa_param_init(&sa_params);
/* Verify we have a good entry */
entry = &ipsec_cache->array[ipsec_cache->index];
if (MAX_DB <= ipsec_cache->index)
return -1;
/* Verify SA mode match in case of cipher&auth */
if (!tun) {
printf("\n TRANSPORT MODE not supported");
return -1;
}
/* Setup parameters and call ipsec library to create sa */
if (in) {
sa_params.dir = ODP_IPSEC_DIR_INBOUND;
sa_params.inbound.lookup_mode = ODP_IPSEC_LOOKUP_SPI;
} else {
sa_params.dir = ODP_IPSEC_DIR_OUTBOUND;
src_ip = odp_cpu_to_be_32(tun->tun_src_ip);
dst_ip = odp_cpu_to_be_32(tun->tun_dst_ip);
sa_params.outbound.tunnel.type = ODP_IPSEC_TUNNEL_IPV4;
sa_params.outbound.tunnel.ipv4.src_addr = &src_ip;
sa_params.outbound.tunnel.ipv4.dst_addr = &dst_ip;
sa_params.outbound.tunnel.ipv4.ttl = IPDEFTTL;
sa_params.outbound.tunnel.ipv4.dscp = 0;
sa_params.outbound.tunnel.ipv4.df = 1;
}
sa_params.dest_queue = completionq;
sa_params.mode = ODP_IPSEC_MODE_TUNNEL;
/* Cipher */
if (cipher_sa) {
sa_params.crypto.cipher_alg = cipher_sa->alg.u.cipher;
sa_params.crypto.cipher_key.data = cipher_sa->key.data;
sa_params.crypto.cipher_key.length = cipher_sa->key.length;
sa_params.spi = cipher_sa->spi;
} else {
sa_params.crypto.cipher_alg = ODP_CIPHER_ALG_NULL;
}
/* Auth */
if (auth_sa) {
sa_params.crypto.auth_alg = auth_sa->alg.u.auth;
sa_params.crypto.auth_key.data = auth_sa->key.data;
sa_params.crypto.auth_key.length = auth_sa->key.length;
} else {
sa_params.crypto.auth_alg = ODP_AUTH_ALG_NULL;
}
sa = odp_ipsec_sa_create(&sa_params);
if (sa == ODP_IPSEC_SA_INVALID)
return -1;
/* Copy selector IPs in cache entry*/
if (cipher_sa) {
entry->src_ip = cipher_sa->src_ip;
entry->dst_ip = cipher_sa->dst_ip;
} else if (auth_sa) {
entry->src_ip = auth_sa->src_ip;
entry->dst_ip = auth_sa->dst_ip;
}
/* Initialize state */
entry->sa = sa;
/* Add entry to the appropriate list */
ipsec_cache->index++;
if (in) {
entry->next = ipsec_cache->in_list;
ipsec_cache->in_list = entry;
} else {
entry->next = ipsec_cache->out_list;
ipsec_cache->out_list = entry;
}
return 0;
}
ipsec_cache_entry_t *find_ipsec_cache_entry_out(uint32_t src_ip,
uint32_t dst_ip)
{
ipsec_cache_entry_t *entry = ipsec_cache->out_list;
/* Look for a hit */
for (; NULL != entry; entry = entry->next) {
if ((entry->src_ip == src_ip) && (entry->dst_ip == dst_ip))
break;
}
return entry;
}
| 2.125 | 2 |
2024-11-18T19:53:04.136844+00:00
| 2018-09-16T17:27:56 |
43c2c4f32257d3a190aaba3b27dbe79f323d3028
|
{
"blob_id": "43c2c4f32257d3a190aaba3b27dbe79f323d3028",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-16T17:27:56",
"content_id": "85b3abe3f18ce52754815c765d2b0a9f6eabdf2a",
"detected_licenses": [
"MIT"
],
"directory_id": "e55c37d27779c89e63f123c7e39792aab078da32",
"extension": "c",
"filename": "Borders_drawing.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 149011345,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 913,
"license": "MIT",
"license_type": "permissive",
"path": "/ILS/Borders_drawing.c",
"provenance": "stackv2-0061.json.gz:1154",
"repo_name": "fernandeslouro/ILS-signals",
"revision_date": "2018-09-16T17:27:56",
"revision_id": "91853d36092c00a09bc976cbb99c859103f1fa29",
"snapshot_id": "81d9f59a53af433392f3ecbcbf8d234f4a89cf5d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fernandeslouro/ILS-signals/91853d36092c00a09bc976cbb99c859103f1fa29/ILS/Borders_drawing.c",
"visit_date": "2020-03-28T19:48:22.594738"
}
|
stackv2
|
#include "ILS.h"
//*********** Borders Drawing *****************
// Desenha bordas entre os indicadores
void Borders_drawing(cairo_t *cr, cairo_operator_t op)
{
cairo_save(cr);
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_set_line_width(cr, 3);
// Border #1
cairo_move_to(cr, 0, 400);
cairo_line_to(cr, 1200, 400);
cairo_line_to(cr, 1200, 900);
cairo_stroke(cr);
// Border #2
cairo_move_to(cr, 0, 0);
cairo_line_to(cr, 1200, 0);
cairo_line_to(cr, 1200, 900);
cairo_line_to(cr, 0, 900);
cairo_line_to(cr, 0, 0);
cairo_stroke(cr);
// Border #3 separating runways when visible
if (!flag_control)
{
cairo_move_to(cr, 0, 648);
cairo_line_to(cr, 1200, 648);
cairo_stroke(cr);
}
// Border #4
cairo_move_to(cr, 950, 0);
cairo_line_to(cr, 950, 400);
cairo_stroke(cr);
// Border #5
cairo_move_to(cr, 1200, 400);
cairo_line_to(cr, 1600, 400);
cairo_stroke(cr);
cairo_restore(cr);
}
| 2.4375 | 2 |
2024-11-18T19:53:04.238025+00:00
| 2017-08-07T17:01:49 |
be62da38a051f89bcd137f399d6dccdb64ffc312
|
{
"blob_id": "be62da38a051f89bcd137f399d6dccdb64ffc312",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-07T17:01:49",
"content_id": "e8bf30598aa163c5ff22c0928e449528f615cc28",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "84147460b46f4d3aa676afbff0a2f3db6af4c40b",
"extension": "h",
"filename": "segment.h",
"fork_events_count": 0,
"gha_created_at": "2017-08-07T16:58:58",
"gha_event_created_at": "2017-08-07T16:58:58",
"gha_language": null,
"gha_license_id": null,
"github_id": 99600385,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4292,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/include/mvas/segment.h",
"provenance": "stackv2-0061.json.gz:1283",
"repo_name": "LSS-USP/libmvas",
"revision_date": "2017-08-07T17:01:49",
"revision_id": "2a31cf7fcb89fcc79e6245f75f0585e307001d8a",
"snapshot_id": "9d42236d76f1a5dc977c60e51cdaf33dd3cfedc7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LSS-USP/libmvas/2a31cf7fcb89fcc79e6245f75f0585e307001d8a/include/mvas/segment.h",
"visit_date": "2021-01-15T10:54:14.988858"
}
|
stackv2
|
#ifndef __SEGMENT_H__
#define __SEGMENT_H__
#include <mvas/vas.h>
#include <linux/types.h>
#include <linux/vas.h>
#include <fcntl.h>
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
#define SYS_vas_seg_create __NR_vas_seg_create
#define SYS_vas_seg_delete __NR_vas_seg_delete
#define SYS_vas_seg_find __NR_vas_seg_find
#define SYS_vas_seg_attach __NR_vas_seg_attach
#define SYS_vas_seg_detach __NR_vas_seg_detach
#define SYS_vas_seg_getattr __NR_vas_seg_getattr
#define SYS_vas_seg_setattr __NR_vas_seg_setattr
typedef int segid_t;
/**
* Create a new segment.
*
* @param[in] name: The name which the segment should have.
* @param[in] start: The virtual address where the segment should start.
* @param[in] end: The virtual address where the segment should end.
* @param[in] mode: The access control list for the segment defining
* which users are allowed to use the segment in which
* way. See creat(3) for more information about how to
* specify the mode.
*
* @returns: The ID of the segment on succes, -1 on failure
* (setting errno).
**/
extern segid_t segment_create(const char * const name, unsigned long start,
unsigned long end, mode_t mode);
/**
* Create a new segment - specifying its size.
*
* @see segment_create
*
* @param[in] size: The size of the resulting segment in bytes.
**/
extern segid_t segment_create_sz(const char * const name, unsigned long start,
unsigned long size, mode_t mode);
/**
* Delete an existing segment again.
*
* @param[in] sid: The ID of the segment that should be deleted.
*
* @returns: 0 on success, -1 on failure (setting errno).
**/
extern int segment_delete(segid_t sid);
/**
* Find the ID of the segment with the given name.
*
* @param[in] name: The name of the segment for which the ID should be
* found.
*
* @returns: The ID of the segment on success, -1 on failure
* (setting errno).
**/
extern segid_t segment_find(const char * const name);
/**
* Attach a segment to a VAS.
*
* @param[in] vid: The ID of the VAS to which the segment should be
* attached.
* @param[in] sid: The ID of the segment that should be attached.
* @param[in] type: The way in which the segment should be attached.
* This must be either O_RDONLY, O_RDWR or O_WRONLY.
* See open(3) for more information about the different
* types available.
*
* @returns: 0 on success, -1 on failure (setting errno).
**/
extern int segment_attach(vasid_t vid, segid_t sid, int type);
/**
* Detach a segment from a VAS again.
*
* @param[in] vid: The ID of the VAS from which the segment should be
* detached.
* @param[in] sid: The ID of the segment that should be detached.
*
* @returns: 0 on success, -1 on failure (setting errno).
**/
extern int segment_detach(vasid_t vid, segid_t sid);
/**
* Get the attributes of a segment.
*
* @param[in] sid: The ID of the segment of which the attributes
* should be retrieved.
* @param[out] attr: The pointer to the data structure where the
* attributes should be saved in.
*
* @returns: 0 on success, -1 on failure (setting errno).
**/
extern int segment_getattr(segid_t sid, struct vas_seg_attr * const attr);
/**
* Change the attributes of a segment.
*
* @param[in] sid: The ID of the segment of which the attributes
* should be changed.
* @param[in] attr: The pointer to the data structure containing the
* new attributes that should be set.
*
* @returns: 0 on success, -1 on failure (setting errno).
**/
extern int segment_setattr(segid_t sid,
const struct vas_seg_attr * const attr);
#ifdef __cplusplus
}
#endif
#endif /* __SEGMENT_H__ */
| 2.515625 | 3 |
2024-11-18T19:53:04.317111+00:00
| 2016-09-30T07:50:10 |
0a1cf4392bf9ff2f92f4d7526bbafa81af16c5ed
|
{
"blob_id": "0a1cf4392bf9ff2f92f4d7526bbafa81af16c5ed",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-30T07:50:10",
"content_id": "afcd0188c21de17a4afd3a4ee43adf6571b79e55",
"detected_licenses": [
"MIT"
],
"directory_id": "ace01ab7cb929964f80ea7737fe2edccd8f8b8f6",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2016-09-24T10:07:53",
"gha_event_created_at": "2016-09-30T07:50:10",
"gha_language": "Lua",
"gha_license_id": null,
"github_id": 69094746,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 185,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/helloworld/src/main.c",
"provenance": "stackv2-0061.json.gz:1413",
"repo_name": "EemeliSyynimaa/enkone",
"revision_date": "2016-09-30T07:50:10",
"revision_id": "80e89ff3e229c8044c31cc7c42af416efd2392a1",
"snapshot_id": "49376f6c00c9aad77ed1cc3f603706b001cf26c1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/EemeliSyynimaa/enkone/80e89ff3e229c8044c31cc7c42af416efd2392a1/examples/helloworld/src/main.c",
"visit_date": "2021-05-03T17:46:47.536894"
}
|
stackv2
|
#include <stdio.h>
#include "test.h"
int main(int argc, char** argv)
{
// Not used.
(void)argc;
(void)argv;
//printf("Hello world: %d!\n", getNumber());
return 0;
}
| 2 | 2 |
2024-11-18T19:53:05.069545+00:00
| 2017-01-14T11:19:03 |
a2656d76b921058acc369b69d00d2c18706f6b86
|
{
"blob_id": "a2656d76b921058acc369b69d00d2c18706f6b86",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-14T11:19:03",
"content_id": "517c7e72154b6d8899b0e120afd349e365131546",
"detected_licenses": [
"MIT"
],
"directory_id": "015ded1a91bfd3204983b3333a3627a77383b074",
"extension": "c",
"filename": "event.c",
"fork_events_count": 0,
"gha_created_at": "2017-02-15T14:38:38",
"gha_event_created_at": "2017-02-15T14:38:38",
"gha_language": null,
"gha_license_id": null,
"github_id": 82070232,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12228,
"license": "MIT",
"license_type": "permissive",
"path": "/user/main/event.c",
"provenance": "stackv2-0061.json.gz:1541",
"repo_name": "dmsherazi/Electrombile_Firmware",
"revision_date": "2017-01-14T11:19:03",
"revision_id": "7c3b686d12b82030eb521845fd9dba2c233cdfd3",
"snapshot_id": "cbafc7a7bcc8e6de6cb4b54456b3a0fead6793d2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/dmsherazi/Electrombile_Firmware/7c3b686d12b82030eb521845fd9dba2c233cdfd3/user/main/event.c",
"visit_date": "2021-01-19T08:07:54.545926"
}
|
stackv2
|
/*
* event.c
*
* Created on: 2015/6/25
* Author: jk
*/
#include <string.h>
#include <eat_interface.h>
#include <eat_uart.h>
#include "timer.h"
#include "thread_msg.h"
#include "log.h"
#include "uart.h"
#include "socket.h"
#include "setting.h"
#include "diagnosis.h"
#include "msg.h"
#include "client.h"
#include "modem.h"
#include "fsm.h"
#include "request.h"
#include "data.h"
#include "adc.h"
#include "modem.h"
#include "response.h"
#include "msg_queue.h"
#include "mem.h"
typedef int (*EVENT_FUNC)(const EatEvent_st* event);
typedef struct
{
EatEvent_enum event;
EVENT_FUNC pfn;
}EVENT_PROC;
typedef int (*THREAD_MSG_FUNC)(const MSG_THREAD* msg);
typedef struct
{
char cmd;
THREAD_MSG_FUNC pfn;
}THREAD_MSG_PROC;
#define DESC_DEF(x) case x:\
return #x
static char* getEventDescription(EatEvent_enum event)
{
switch (event)
{
#ifdef APP_DEBUG
DESC_DEF(EAT_EVENT_TIMER);
DESC_DEF(EAT_EVENT_KEY);
DESC_DEF(EAT_EVENT_INT);
DESC_DEF(EAT_EVENT_MDM_READY_RD);
DESC_DEF(EAT_EVENT_MDM_READY_WR);
DESC_DEF(EAT_EVENT_MDM_RI);
DESC_DEF(EAT_EVENT_UART_READY_RD);
DESC_DEF(EAT_EVENT_UART_READY_WR);
DESC_DEF(EAT_EVENT_ADC);
DESC_DEF(EAT_EVENT_UART_SEND_COMPLETE);
DESC_DEF(EAT_EVENT_USER_MSG);
DESC_DEF(EAT_EVENT_IME_KEY);
#endif
default:
{
static char soc_event[10] = {0};
snprintf(soc_event, 10, "%d", event);
return soc_event;
}
}
}
static int event_timer(const EatEvent_st* event)
{
switch (event->data.timer.timer_id)
{
case TIMER_LOOP:
LOG_DEBUG("TIMER_LOOP expire.");
fsm_run(EVT_LOOP);
eat_timer_start(event->data.timer.timer_id, setting.main_loop_timer_period);
break;
case TIMER_GPS_SEND:
cmd_GPSPack();
eat_timer_start(event->data.timer.timer_id, setting.gps_send_period);
break;
case TIMER_MSG_RESEND:
msg_resend();
eat_timer_start(event->data.timer.timer_id, 60*1000);
break;
default:
LOG_ERROR ("timer(%d) not processed!", event->data.timer.timer_id);
break;
}
return 0;
}
static int event_adc(const EatEvent_st* event)
{
unsigned int value = event->data.adc.v;
LOG_DEBUG("ad value=%d", value);
if (event->data.adc.pin == ADC_433)
{
seek_proc(value);
}
else
{
LOG_INFO("not processed adc pin:%d", event->data.adc.pin);
}
return 0;
}
static void sendGPS2Server(LOCAL_GPS* gps)
{
if (gps->isGps)
{
cmd_GPS(&gps->gps);
}
#if 0
else
{
size_t msgLen = sizeof(MSG_HEADER) + sizeof(CGI) + sizeof(CELL) * gps->cellInfo.cellNo;
MSG_HEADER* msg = alloc_msg(CMD_CELL, msgLen);
CGI* cgi = (CGI*)(msg + 1);
CELL* cell = (CELL*)(cgi + 1);
int i = 0;
if (!msg)
{
LOG_ERROR("alloc CELL message failed!");
return;
}
cgi->mcc = htons(gps->cellInfo.mcc);
cgi->mnc = htons(gps->cellInfo.mnc);
cgi->cellNo = gps->cellInfo.cellNo;
for (i = 0; i < gps->cellInfo.cellNo; i++)
{
cell[i].lac = htons(gps->cellInfo.cell[i].lac);
cell[i].cellid = htons(gps->cellInfo.cell[i].cellid);
cell[i].rxl= htons(gps->cellInfo.cell[i].rxl);
}
LOG_DEBUG("send CELL message.");
socket_sendDataDirectly(msg, msgLen);
data.isCellGet = EAT_FALSE;
}
#endif
}
static int threadCmd_GPS(const MSG_THREAD* msg)
{
LOCAL_GPS* gps = (LOCAL_GPS*) msg->data;
if (msg->length < sizeof(LOCAL_GPS) || !gps)
{
LOG_ERROR("msg from THREAD_GPS error!");
return -1;
}
if (gps->isGps)
{
gps_enqueue(&gps->gps);
}
if (gps_isQueueFull())
{
cmd_GPSPack();
}
return 0;
}
static int threadCmd_AutolockState(const MSG_THREAD* msg)
{
AUTOLOCK_INFO* msg_state = (AUTOLOCK_INFO*) msg->data;
MSG_AUTODEFEND_STATE_REQ* autolock_msg;
if (msg->length < sizeof(AUTOLOCK_INFO) || !msg_state)
{
LOG_ERROR("msg from THREAD_VIBRATION error!");
return -1;
}
autolock_msg = alloc_msg(CMD_DEFEND_NOTIFY, sizeof(MSG_AUTODEFEND_STATE_REQ));
autolock_msg->state = msg_state->state;
LOG_DEBUG("send auto lock state change message: %d", msg_state->state);
socket_sendDataDirectly(autolock_msg, sizeof(MSG_AUTODEFEND_STATE_REQ));
return 0;
}
/*
*fun: receive msg from GPS_Thread and send GPSSignal msg to server
*/
static int threadCmd_GPSHdop(const MSG_THREAD* msg)
{
GPS_HDOP_INFO* msg_data = (GPS_HDOP_INFO*) msg->data;
MSG_GET_GPS_RSP* hdop_msg;
u8 msgLen = 0;
char buf[MAX_DEBUG_BUF_LEN] = {0};
if (msg->length < sizeof(GPS_HDOP_INFO) || !msg_data)
{
LOG_ERROR("msg from THREAD_GPS error!");
return -1;
}
if(!msg_data->satellites)
{
snprintf(buf,MAX_DEBUG_BUF_LEN,"GPS not fixed,hdop:%f;satellites:%d",msg_data->hdop,msg_data->satellites);
}
else
{
snprintf(buf,MAX_DEBUG_BUF_LEN,"GPS fixed,hdop:%f;satellites:%d",msg_data->hdop,msg_data->satellites);
}
msgLen = sizeof(MSG_GET_HEADER) + strlen(buf) + 1;
hdop_msg = alloc_msg(CMD_GET_GPS,msgLen);
if (!hdop_msg)
{
LOG_ERROR("alloc LogInfo rsp message failed!");
return -1;
}
hdop_msg->managerSeq = msg_data->managerSeq;
strncpy(hdop_msg->data,buf,strlen(buf)+1);
socket_sendDataDirectly(hdop_msg, msgLen);
return 0;
}
static int threadCmd_SMS(const MSG_THREAD* msg)
{
SMS_SEND_INFO *data = (SMS_SEND_INFO *)msg->data;
if (msg->length != sizeof(SMS_SEND_INFO) + data->smsLen)
{
LOG_ERROR("msg length error: msgLen(%d)!", msg->length);
return -1;
}
return cmd_SMS(data->number, data->type, data->smsLen, data->content);
}
static int threadCmd_Alarm(const MSG_THREAD* msg)
{
ALARM_INFO *msg_data = (ALARM_INFO*)msg->data;
if (msg->length != sizeof(ALARM_INFO))
{
LOG_ERROR("msg length error: msgLen(%d)!", msg->length);
return -1;
}
LOG_DEBUG("receive thread command CMD_VIBRATE: alarmType(%d).", msg_data->alarm_type);
return cmd_alarm(msg_data->alarm_type);
}
static int threadCmd_Location(const MSG_THREAD* msg)
{
LOCAL_GPS* gps = (LOCAL_GPS*) msg->data;
if (msg->length < sizeof(LOCAL_GPS) || !gps)
{
LOG_ERROR("msg from THREAD_GPS error!");
return -1;
}
if (gps->isGps) //update the local GPS data
{
MSG_GPSLOCATION_RSP* msg = alloc_msg(CMD_LOCATE, sizeof(MSG_GPSLOCATION_RSP));
if (!msg)
{
LOG_ERROR("alloc message failed!");
return -1;
}
msg->isGps= gps->isGps;
memcpy(&msg->gps, &gps->gps, sizeof(GPS));
msg->gps.timestamp = htonl(gps->gps.timestamp);
msg->gps.course = htons(gps->gps.course);
LOG_DEBUG("send GPS_LOCATION message.");
socket_sendDataDirectly(msg, sizeof(MSG_GPSLOCATION_RSP));
}
else //update local cell info
{
size_t msgLen = sizeof(MSG_CELLLOCATION_HEADER) + sizeof(CGI) + sizeof(CELL) * gps->cellInfo.cellNo;
MSG_CELLLOCATION_HEADER* msg = alloc_msg(CMD_LOCATE, msgLen);
CGI* cgi = (CGI*)(msg + 1);
CELL* cell = (CELL*)(cgi + 1);
int i = 0;
if (!msg)
{
LOG_ERROR("alloc message failed!");
return -1;
}
msg->isGps = gps->isGps;
cgi->mcc = htons(gps->cellInfo.mcc);
cgi->mnc = htons(gps->cellInfo.mnc);
cgi->cellNo = gps->cellInfo.cellNo;
for (i = 0; i < gps->cellInfo.cellNo; i++)
{
cell[i].lac = htons(gps->cellInfo.cell[i].lac);
cell[i].cellid = htons(gps->cellInfo.cell[i].cellid);
cell[i].rxl= htons(gps->cellInfo.cell[i].rxl);
}
LOG_DEBUG("send CELL_LOCATION message.");
socket_sendDataDirectly(msg, msgLen);
}
return 0;
}
static int cmd_get_AT(char *data)
{
MSG_GET_AT_RSP* msg;
u8 msgLen = 0;
char buf[MAX_DEBUG_BUF_LEN] = {0};
snprintf(buf,MAX_DEBUG_BUF_LEN,"%s",data);
msgLen = sizeof(MSG_GET_HEADER) + strlen(buf) + 1;
msg = alloc_msg(CMD_GET_AT,msgLen);
if (!msg)
{
LOG_ERROR("alloc LogInfo rsp message failed!");
return -1;
}
msg->managerSeq = get_manager_seq();
strncpy(msg->data,buf,strlen(buf)+1);
socket_sendDataDirectly(msg, msgLen);
return 0;
}
static int event_mod_ready_rd(const EatEvent_st* event)
{
u8 buf[256] = {0};
u16 len = 0;
len = eat_modem_read(buf, 256);
if (!len)
{
LOG_ERROR("modem received nothing.");
return -1;
}
LOG_DEBUG("modem recv: %s", buf);
if(get_manager_ATcmd_state())
{
set_manager_ATcmd_state(EAT_FALSE);
cmd_get_AT(buf);
}
if (modem_IsCallReady(buf))
{
//diag_check(); // because diagnosis is not accurate, remove it
fsm_run(EVT_CALL_READY);
}
if(modem_IsCCIDOK(buf))
{
cmd_SimInfo(buf + 9);//str(AT+CCID\r\n) = 9
}
return 0;
}
static THREAD_MSG_PROC msgProcs[] =
{
{CMD_THREAD_GPS, threadCmd_GPS},
{CMD_THREAD_SMS, threadCmd_SMS},
{CMD_THREAD_ALARM, threadCmd_Alarm},
{CMD_THREAD_LOCATION, threadCmd_Location},
{CMD_THREAD_AUTOLOCK, threadCmd_AutolockState},
{CMD_THREAD_GPSHDOP, threadCmd_GPSHdop},
};
static int event_threadMsg(const EatEvent_st* event)
{
MSG_THREAD* msg = (MSG_THREAD*) event->data.user_msg.data_p;
u8 msgLen = event->data.user_msg.len;
size_t i = 0;
int rc = 0;
if (msg->length + sizeof(MSG_THREAD) != msgLen)
{
LOG_ERROR("Message length error");
freeMsg(msg);
return -1;
}
for (i = 0; i < sizeof(msgProcs) / sizeof(msgProcs[0]); i++)
{
if (msgProcs[i].cmd == msg->cmd)
{
THREAD_MSG_FUNC pfn = msgProcs[i].pfn;
if (pfn)
{
rc = pfn(msg);
break;
}
else
{
LOG_ERROR("thread message %d not processed!", msg->cmd);
rc = -1;
break;
}
}
}
freeMsg(msg);
return rc;
}
static EVENT_PROC eventProcs[] =
{
{EAT_EVENT_TIMER, event_timer},
{EAT_EVENT_MDM_READY_RD, event_mod_ready_rd},
{EAT_EVENT_MDM_READY_WR, EAT_NULL},
{EAT_EVENT_UART_READY_RD, event_uart_ready_rd},
{EAT_EVENT_UART_READY_WR, event_uart_ready_wr},
{EAT_EVENT_UART_SEND_COMPLETE, EAT_NULL},
{EAT_EVENT_USER_MSG, event_threadMsg},
{EAT_EVENT_ADC, event_adc},
};
int event_proc(EatEvent_st* event)
{
int i = 0;
LOG_DEBUG("event: %s happened", getEventDescription(event->event));
for (i = 0; i < sizeof(eventProcs) / sizeof(eventProcs[0]); i++)
{
if (eventProcs[i].event == event->event)
{
EVENT_FUNC pfn = eventProcs[i].pfn;
if (pfn)
{
return pfn(event);
}
else
{
LOG_ERROR("event(%s) not processed!", getEventDescription(event->event));
return -1;
}
}
}
LOG_ERROR("event(%s) has no handler!", getEventDescription(event->event));
return -1;
}
| 2.03125 | 2 |
2024-11-18T19:53:06.209246+00:00
| 2020-03-01T22:00:43 |
475d214992ab28be6a6e361785817bcd95eb5628
|
{
"blob_id": "475d214992ab28be6a6e361785817bcd95eb5628",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-01T22:00:43",
"content_id": "14355a5531d1269ea94c9be6c51e56b1bb4deeb8",
"detected_licenses": [
"MIT"
],
"directory_id": "4d7cefa9badfeb954138637ba364c59eff567483",
"extension": "c",
"filename": "test_Kalman.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 244230159,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4252,
"license": "MIT",
"license_type": "permissive",
"path": "/Examples/test_Kalman.c",
"provenance": "stackv2-0061.json.gz:2571",
"repo_name": "maj0e/kalman-filter",
"revision_date": "2020-03-01T22:00:43",
"revision_id": "3376ab6083d2eaa7cad7703a79f2265398e5ec9e",
"snapshot_id": "cf21a2384718ef5fc22e05582393c365e0bec396",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/maj0e/kalman-filter/3376ab6083d2eaa7cad7703a79f2265398e5ec9e/Examples/test_Kalman.c",
"visit_date": "2021-02-09T02:48:57.106744"
}
|
stackv2
|
/*******************************************************************/
/** Example to test the Kalman-Filter functions **/
/*******************************************************************/
#include "kalman.h"
#include "lah.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*the state prediction function: linear case for simplicity */
const lah_value accel = 0.4;
const lah_value deltaT = 0.1;
const lah_value sigma_x = 1.5;
const lah_value sigma_z = 10;
struct optData
{
lah_index inits;
lah_index initm;
lah_mat* B; /* Control matrix*/
};
lah_Return timeEvolve(lah_mat* xp, const lah_mat *x,
const lah_mat *u, lah_mat *A,
struct optData *Data)
{
/* Set the state transition Matrix A
* if not done yet*/
lah_mat *B = Data->B;
lah_Return result;
if (Data->inits == 0 )
{
A->data[0] = 1;
A->data[A->incRow] = 0;
A->data[A->incCol] = deltaT;
A->data[A->incCol + A->incRow] = 1;
B->data[0] = deltaT * deltaT /2;
B->data[1] = deltaT;
Data->inits = 1;
}
/* compute predicted state */
result = lah_matMul(lahNorm, lahNorm, 0.0, 1.0 , xp, A, x);
result += lah_matMul(lahNorm, lahNorm, 1.0, 1.0, xp, B, u);
if (result != 0)
return lahReturnMathError;
else
return lahReturnOk;
}
/* measurement prediction function */
lah_Return measure(lah_mat *zp, const lah_mat *x,
lah_mat *H, struct optData *Data)
{
/* Set the state transition Matrix A
* if not done yet*/
if (Data->initm == 0 )
{
H->data[0] = 1;
H->data[H->incCol] = 0 ;
Data->initm = 1;
}
/* compute the measurement from state x */
zp->data[0] = x->data[0];
return lahReturnOk;
}
int main ()
{
lah_index i;
lah_value vel = 0, pos = 0;
lah_value noise;
lah_mat *u = lah_matAlloc(1, 1, 1);
lah_mat *z = lah_matAlloc(1, 1, 1);
kal_Filter* kal;
const lah_index nState = 2;
const lah_index nMeas = 1;
/*Initialize the struct for prediction */
struct optData Data;
Data.initm = 0;
Data.inits = 0;
Data.B = lah_matAlloc(1, 2, 1);
kal = kal_create(nState, nMeas,
(kal_StateFun) timeEvolve,
(kal_MeasFun) measure, (void*) &Data);
/* Initialization */
kal->P->data[0] = pow(sigma_x, 2) * pow(deltaT, 4) / 4;
kal->P->data[kal->P->incCol] = pow(sigma_x, 2) * pow(deltaT, 3) / 2;
kal->P->data[kal->P->incRow] = pow(sigma_x, 2) * pow(deltaT, 3) / 2;
kal->P->data[kal->P->incRow + kal->P->incCol]
= pow(sigma_x, 2) * pow(deltaT, 2);
/* input and process noise variables */
u->data[0] = accel;
kal->R->data[0] = sigma_z * sigma_z;
LAH_ENTRY(kal->Q, 0, 0) = pow(sigma_x, 2) * pow(deltaT, 4) / 4;
LAH_ENTRY(kal->Q, 0, 1) = pow(sigma_x, 2) * pow(deltaT, 3) / 2;
LAH_ENTRY(kal->Q, 1, 0) = pow(sigma_x, 2) * pow(deltaT, 3) / 2;
LAH_ENTRY(kal->Q, 1, 1) = pow(sigma_x, 2) * pow(deltaT, 2);
/* initialize random number generator */
srand(0);
/* print header */
printf("i pos vel realpos realvel P11 P12 P21 P22 z zp\n");
/* loop over time and demonstrate Kalman filter */
for (i = 0; i < 5000; i++)
{
/* virtual measurement */
noise = lah_gaussNoise();
pos = u->data[0] / 2.0 * pow(i * deltaT, 2.0);
vel = u->data[0] * i * deltaT;
z->data[0] = pos + noise * sigma_z;
/* correct filter state */
if (lahReturnOk != kal_correct(kal, z))
printf("Error in kal_correct !!!\n");
/* print out */
printf("%d %g %g %g %g %g %g %g %g %g %g\n", i,
kal->x->data[0], kal->x->data[1], pos, vel,
kal->P->data[0], kal->P->data[1],
kal->P->data[2], kal->P->data[3],
z->data[0] , kal->zp->data[0]);
u->data[0] = accel;
/* predict the next filter state */
if (lahReturnOk != kal_predict(kal, u))
printf("Error in kal_predict !!!\n");
}
lah_matFree(u);
lah_matFree(z);
lah_matFree(Data.B);
kal_free(kal);
return 0;
}
| 2.625 | 3 |
2024-11-18T19:53:06.514437+00:00
| 2023-05-12T19:55:18 |
aed6cc984d65dd98e963b64d5216c68df17c30bc
|
{
"blob_id": "aed6cc984d65dd98e963b64d5216c68df17c30bc",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-12T19:55:18",
"content_id": "a46f1b8c6bff31c71b83db991a8f3d5dadd423e5",
"detected_licenses": [
"MIT"
],
"directory_id": "599c482c754564f53a6c5f517a95d9be101ad091",
"extension": "c",
"filename": "gamemodesBase.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 133724623,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2498,
"license": "MIT",
"license_type": "permissive",
"path": "/RoboSAX/modules/modulesInterface/gamemodesBase.c",
"provenance": "stackv2-0061.json.gz:2827",
"repo_name": "RoboSAX/avr_spielfeld",
"revision_date": "2023-05-12T19:55:18",
"revision_id": "723c15c2ad391780655b808436a95a06c0d8fc5b",
"snapshot_id": "7a3dbfde1ec70bf99ae039cf8d026fe783edbf74",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RoboSAX/avr_spielfeld/723c15c2ad391780655b808436a95a06c0d8fc5b/RoboSAX/modules/modulesInterface/gamemodesBase.c",
"visit_date": "2023-05-29T00:32:47.711722"
}
|
stackv2
|
/******************************************************************************
* gamemodes.h *
* ======== *
* *
* Version: 1.0.0 *
* Date : 01.06.18 *
* Author : Peter Weissig, Leander Herr *
* *
******************************************************************************/
//**************************<Included files>***********************************
#include "gamemodes.h"
#include "menueHelper.h"
#include "currentYear.h"
//**************************<Types and Variables>******************************
gamemode_init_pointer gamemode_init;
gamemode_start_pointer gamemode_start;
gamemode_update_pointer gamemode_update;
gamemode_points_pointer gamemode_points;
gamemode_to_display_pointer gamemode_to_display;
uint8_t maxGameModes;
uint8_t currGameNr;
#define YEAR_ACTION(YEAR) YEAR,
const uint16_t availibleYears[]={ProcessYears};
#undef YEAR_ACTION
//**************************<Methods>******************************************
void game_to_display(uint8_t gameNr,
uint8_t const** displayOut1, uint8_t const** displayOut2,
uint8_t const** displayOut3, uint8_t const** displayOut4){
if (gameNr==0) gameNr=CURRENT_YEAR;
uint16_t year=availibleYears[gameNr-1];
*displayOut1=numbers[year/1000];
year%=1000;
*displayOut2=numbers[year/100];
year%=100;
*displayOut3=numbers[year/10];
*displayOut4=numbers[year%10];
}
void curr_game_to_display(
uint8_t const** displayOut1, uint8_t const** displayOut2,
uint8_t const** displayOut3, uint8_t const** displayOut4){
game_to_display(currGameNr,displayOut1,displayOut2,displayOut3,displayOut4);
}
void change_gameNr(uint8_t gameNr){
currGameNr=gameNr;
if (gameNr==0) gameNr=CURRENT_YEAR;
switch(gameNr){
#define YEAR_ACTION(YEAR) \
case GameOfYear##YEAR:\
gamemode_init=gamemode_init_##YEAR;\
gamemode_start=gamemode_start_##YEAR;\
gamemode_update=gamemode_update_##YEAR;\
gamemode_points=gamemode_points_##YEAR;\
gamemode_to_display=gamemode_to_display_##YEAR;\
break;
ProcessYears
#undef YEAR_ACTION
}
gamemode_init();
}
| 2.265625 | 2 |
2024-11-18T19:53:06.649496+00:00
| 2020-04-11T01:31:26 |
bd1fb0474677a380fe85748931b1ebfda3cb327b
|
{
"blob_id": "bd1fb0474677a380fe85748931b1ebfda3cb327b",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-11T01:31:26",
"content_id": "d5923ff51583c70f747bd1949ac4c3c7e28cae7f",
"detected_licenses": [
"MIT"
],
"directory_id": "a957c4cdc11f6decc2432db16c96026bf13a274e",
"extension": "c",
"filename": "test_urldecode.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 54804261,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5605,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/test_urldecode.c",
"provenance": "stackv2-0061.json.gz:2956",
"repo_name": "jeffpc/libjeffpc",
"revision_date": "2020-04-11T01:31:26",
"revision_id": "559b48a81cd6300529f4ac54b2d471247323577b",
"snapshot_id": "980e2bd5142fc046f6d251223f682736f2d62a23",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jeffpc/libjeffpc/559b48a81cd6300529f4ac54b2d471247323577b/tests/test_urldecode.c",
"visit_date": "2021-01-10T09:05:06.618918"
}
|
stackv2
|
/*
* Copyright (c) 2017 Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
*
* 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 <jeffpc/types.h>
#include <jeffpc/error.h>
#include <jeffpc/urldecode.h>
#include "test.c"
struct test {
const char *in;
const char *out;
ssize_t inlen;
ssize_t outlen;
};
static const struct test input_tests[] = {
{
.in = NULL,
.inlen = 1,
.outlen = -EINVAL,
},
{
.in = "",
.out = "",
.inlen = 0,
.outlen = 0,
},
{
.in = "a",
.out = "a",
.inlen = 1,
.outlen = 1,
},
{
.in = "ab",
.out = "a",
.inlen = 1,
.outlen = 1,
},
{
.in = "+",
.out = " ",
.inlen = 1,
.outlen = 1,
},
{
.in = "%20",
.out = " ",
.inlen = 3,
.outlen = 1,
},
{
.in = "%",
.inlen = 1,
.outlen = -EILSEQ,
},
{
.in = "%0",
.inlen = 1,
.outlen = -EILSEQ,
},
{
.in = "%0",
.inlen = 2,
.outlen = -EILSEQ,
},
{
.in = "%00",
.out = "\0",
.inlen = 3,
.outlen = 1,
},
{
.in = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789",
.out = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789",
.inlen = 26 + 26 + 10,
.outlen = 26 + 26 + 10,
},
{
.in = "abc+def",
.out = "abc def",
.inlen = 7,
.outlen = 7,
},
{
.in = "abc=def",
.out = "abc=def",
.inlen = 7,
.outlen = 7,
},
{
.in = "abc&def",
.out = "abc&def",
.inlen = 7,
.outlen = 7,
},
{
.in = "abc%def",
.out = "abc\xde""f",
.inlen = 7,
.outlen = 5,
},
{
.in = "abc%DEf",
.out = "abc\xde""f",
.inlen = 7,
.outlen = 5,
},
{
.in = "abc%a0f",
.out = "abc\xa0""f",
.inlen = 7,
.outlen = 5,
},
{
.in = "abc%A0f",
.out = "abc\xa0""f",
.inlen = 7,
.outlen = 5,
},
{
.in = "abc%88f",
.out = "abc\x88""f",
.inlen = 7,
.outlen = 5,
},
};
static const struct test arg_tests[] = {
{
.in = NULL,
.out = "",
.inlen = 0,
.outlen = -EINVAL,
},
{
.in = "",
.out = NULL,
.inlen = 0,
.outlen = -EINVAL,
},
{
.in = NULL,
.out = NULL,
.inlen = 0,
.outlen = -EINVAL,
},
{
.in = NULL,
.out = "",
.inlen = 1,
.outlen = -EINVAL,
},
{
.in = "",
.out = NULL,
.inlen = 1,
.outlen = -EINVAL,
},
{
.in = NULL,
.out = NULL,
.inlen = 1,
.outlen = -EINVAL,
},
{
.in = "",
.out = "",
.inlen = 0,
.outlen = 0,
},
};
static char out[1024 * 1024];
static void test_args(void)
{
int i;
for (i = 0; i < ARRAY_LEN(arg_tests); i++) {
const struct test *test = &arg_tests[i];
ssize_t ret;
fprintf(stderr, "%s: iter = %2d...", __func__, i);
if (test->outlen > 0)
fail("expected outlen %zd > 0", test->outlen);
ret = urldecode(test->in, test->inlen, (char *) test->out);
if ((ret > 0) && !test->outlen)
fail("succeeded with %zd, should have succeeded with 0",
ret);
if ((ret < 0) && !test->outlen)
fail("failed with '%s', should have succeded with 0",
xstrerror(ret));
if ((ret >= 0) && (test->outlen < 0))
fail("succeeded with %zd, should have failed with %s",
ret, xstrerror(test->outlen));
if (ret != test->outlen)
fail("failed with '%s', should have failed with '%s'",
xstrerror(ret), xstrerror(test->outlen));
fprintf(stderr, "ok.\n");
}
}
static void test_inputs(void)
{
int i;
for (i = 0; i < ARRAY_LEN(input_tests); i++) {
const struct test *test = &input_tests[i];
ssize_t outlen;
fprintf(stderr, "%s: iter = %2d...", __func__, i);
if ((test->outlen >= 0) && (sizeof(out) < test->outlen))
fail("output buffer is too small; "
"need %zd bytes, got %zu", test->outlen,
sizeof(out));
outlen = urldecode(test->in, test->inlen, out);
if ((outlen < 0) && (test->outlen >= 0))
fail("urldecode failed with error: %s",
xstrerror(outlen));
if ((outlen >= 0) && (test->outlen < 0))
fail("urldecode returned %zd, should have failed: %s",
outlen, xstrerror(test->outlen));
if ((outlen >= 0) && (outlen != test->outlen))
fail("urldecode returned wrong number of bytes; "
"expected %zd, got %zd", test->outlen, outlen);
if ((outlen < 0) && (outlen != test->outlen))
fail("urldecode failed with wrong error; "
"expected '%s', got '%s'", xstrerror(test->outlen),
xstrerror(outlen));
if ((outlen >= 0) && memcmp(out, test->out, outlen))
fail("output doesn't match expected string; "
"expected '%*.*s', got '%*.*s'",
outlen, outlen, test->out,
outlen, outlen, out);
fprintf(stderr, "ok.\n");
}
}
void test(void)
{
test_args();
test_inputs();
}
| 2.03125 | 2 |
2024-11-18T19:53:06.865093+00:00
| 2021-09-23T19:49:34 |
930f8e07ab9a28dfb0916aa7a960bc5c42533101
|
{
"blob_id": "930f8e07ab9a28dfb0916aa7a960bc5c42533101",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-23T19:49:34",
"content_id": "6b3139a5d1e18ed391144192ff7ddeaf46ba222d",
"detected_licenses": [
"MIT"
],
"directory_id": "6ba7b246e42246865721152f6ff57330005b04dd",
"extension": "c",
"filename": "lat_flow.c",
"fork_events_count": 8,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 175664674,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10981,
"license": "MIT",
"license_type": "permissive",
"path": "/src/lat_flow.c",
"provenance": "stackv2-0061.json.gz:3084",
"repo_name": "PSUmodeling/BioRT-Flux-PIHM",
"revision_date": "2021-09-23T19:49:34",
"revision_id": "7a32acfa467e3211ab52322d88fb7919242b37c2",
"snapshot_id": "54c750e85ddd2b8e5c22fa76bf04cf017176a150",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/PSUmodeling/BioRT-Flux-PIHM/7a32acfa467e3211ab52322d88fb7919242b37c2/src/lat_flow.c",
"visit_date": "2021-09-25T22:01:12.458605"
}
|
stackv2
|
#include "pihm.h"
void LateralFlow(elem_struct *elem, const river_struct *river, int surf_mode)
{
int i;
double *dhbydx;
double *dhbydy;
dhbydx = (double *)malloc(nelem * sizeof(double));
dhbydy = (double *)malloc(nelem * sizeof(double));
FrictSlope(elem, river, surf_mode, dhbydx, dhbydy);
#if defined(_OPENMP)
# pragma omp parallel for
#endif
for (i = 0; i < nelem; i++)
{
int j;
double avg_sf;
elem_struct *nabr;
for (j = 0; j < NUM_EDGE; j++)
{
if (elem[i].nabr[j] == 0) /* Boundary condition flux */
{
BoundFluxElem(elem[i].attrib.bc_type[j], j, &elem[i].bc,
&elem[i].ws, &elem[i].topo, &elem[i].soil, &elem[i].wf);
}
else if (elem[i].nabr_river[j] == 0)
{
nabr = &elem[elem[i].nabr[j] - 1];
/* Subsurface flow between triangular elements */
elem[i].wf.subsurf[j] = SubFlowElemToElem(&elem[i], nabr, j);
/* Surface flux between triangular elements */
avg_sf = 0.5 *
(sqrt(dhbydx[i] * dhbydx[i] + dhbydy[i] * dhbydy[i]) +
sqrt(dhbydx[nabr->ind - 1] * dhbydx[nabr->ind - 1] +
dhbydy[nabr->ind - 1] * dhbydy[nabr->ind - 1]));
elem[i].wf.ovlflow[j] =
OvlFlowElemToElem(&elem[i], nabr, j, avg_sf, surf_mode);
}
else
{
/* Do nothing. River-element interactions are calculated
* in river_flow.c */
}
} /* End of neighbor loop */
} /* End of element loop */
free(dhbydx);
free(dhbydy);
#if defined(_FBR_)
/*
* Lateral fractured bedrock flow
*/
#if defined(_OPENMP)
# pragma omp parallel for
#endif
for (i = 0; i < nelem; i++)
{
int j;
elem_struct *nabr;
for (j = 0; j < NUM_EDGE; j++)
{
if (elem[i].nabr[j] == 0)
{
elem[i].wf.fbrflow[j] =
FbrBoundFluxElem(elem[i].attrib.fbrbc_type[j], j,
&elem[i].fbr_bc, &elem[i].ws, &elem[i].topo, &elem[i].geol);
}
else
{
nabr = &elem[elem[i].nabr[j] - 1];
/* Groundwater flow modeled by Darcy's Law */
elem[i].wf.fbrflow[j] = FbrFlowElemToElem(&elem[i], nabr,
elem[i].topo.nabrdist[j], elem[i].topo.edge[j]);
}
}
}
#endif
}
void FrictSlope(const elem_struct *elem, const river_struct *river,
int surf_mode, double *dhbydx, double *dhbydy)
{
int i;
#if defined(_OPENMP)
# pragma omp parallel for
#endif
for (i = 0; i < nelem; i++)
{
int j;
double surfh[NUM_EDGE];
double x[NUM_EDGE];
double y[NUM_EDGE];
const elem_struct *nabr;
const river_struct *rivnabr;
if (surf_mode == DIFF_WAVE)
{
for (j = 0; j < NUM_EDGE; j++)
{
if (elem[i].nabr[j] == 0)
{
surfh[j] = elem[i].topo.zmax + elem[i].ws.surfh;
x[j] = elem[i].topo.nabr_x[j];
y[j] = elem[i].topo.nabr_y[j];
}
else if (elem[i].nabr_river[j] == 0)
{
nabr = &elem[elem[i].nabr[j] - 1];
surfh[j] = nabr->topo.zmax + nabr->ws.surfh;
x[j] = elem[i].topo.nabr_x[j];
y[j] = elem[i].topo.nabr_y[j];
}
else
{
rivnabr = &river[elem[i].nabr_river[j] - 1];
surfh[j] = (rivnabr->ws.stage > rivnabr->shp.depth) ?
rivnabr->topo.zbed + rivnabr->ws.stage :
rivnabr->topo.zmax;
x[j] = river[elem[i].nabr_river[j] - 1].topo.x;
y[j] = river[elem[i].nabr_river[j] - 1].topo.y;
}
}
dhbydx[i] = DhByDl(y, x, surfh);
dhbydy[i] = DhByDl(x, y, surfh);
}
}
}
double AvgHsurf(double diff, double hsurf, double hnabr)
{
double avg_h;
if (diff > 0.0)
{
if (hsurf > DEPRSTG)
{
avg_h = 1.0 * (hsurf - DEPRSTG);
}
else
{
avg_h = 0.0;
}
}
else
{
if (hnabr > DEPRSTG)
{
avg_h = 1.0 * (hnabr - DEPRSTG);
}
else
{
avg_h = 0.0;
}
}
return avg_h;
}
double AvgH(double diff, double hsub, double hnabr)
{
double avg_h = 0.0;
if (diff > 0.0)
{
if (hsub > 0.0)
{
avg_h = hsub;
}
}
else
{
if (hnabr > 0.0)
{
avg_h = hnabr;
}
}
return avg_h;
}
double DhByDl(const double *l1, const double *l2, const double *surfh)
{
return -1.0 *
(l1[2] * (surfh[1] - surfh[0]) + l1[1] * (surfh[0] - surfh[2]) +
l1[0] * (surfh[2] - surfh[1])) /
(l2[2] * (l1[1] - l1[0]) + l2[1] * (l1[0] - l1[2]) +
l2[0] * (l1[2] - l1[1]));
}
double EffKh(const soil_struct *soil, double gw)
{
double k1, k2;
double d1, d2;
gw = (gw > 0.0) ? gw : 0.0;
if (gw > soil->depth - soil->dmac)
{
k1 = soil->kmach * soil->areafv + soil->ksath * (1.0 - soil->areafv);
k2 = soil->ksath;
if (gw > soil->depth)
{
d1 = soil->dmac;
d2 = soil->depth - soil->dmac;
}
else
{
d1 = gw - (soil->depth - soil->dmac);
d2 = soil->depth - soil->dmac;
}
return (k1 * d1 + k2 * d2) / (d1 + d2);
}
else
{
return soil->ksath;
}
}
double OverLandFlow(double avg_h, double grad_h, double avg_sf, double crossa,
double avg_rough)
{
return crossa * pow(avg_h, 0.6666667) * grad_h / (sqrt(avg_sf) * avg_rough);
}
double SubFlowElemToElem(const elem_struct *elem, const elem_struct *nabr,
int j)
{
double diff_h;
double avg_h;
double grad_h;
double effk, effk_nabr;
double avg_ksat;
/*
* Subsurface lateral flux calculation between triangular
* elements
*/
diff_h = (elem->ws.gw + elem->topo.zmin) - (nabr->ws.gw + nabr->topo.zmin);
avg_h = AvgH(diff_h, elem->ws.gw, nabr->ws.gw);
grad_h = diff_h / elem->topo.nabrdist[j];
/* Take into account macropore effect */
effk = EffKh(&elem->soil, elem->ws.gw);
effk_nabr = EffKh(&nabr->soil, nabr->ws.gw);
avg_ksat = 0.5 * (effk + effk_nabr);
/* Groundwater flow modeled by Darcy's Law */
return avg_ksat * grad_h * avg_h * elem->topo.edge[j];
}
double OvlFlowElemToElem(const elem_struct *elem, const elem_struct *nabr,
int j, double avg_sf, int surf_mode)
{
double diff_h;
double avg_h;
double grad_h;
double avg_rough;
double crossa;
diff_h = (surf_mode == KINEMATIC) ?
elem->topo.zmax - nabr->topo.zmax :
(elem->ws.surfh + elem->topo.zmax) - (nabr->ws.surfh + nabr->topo.zmax);
avg_h = AvgHsurf(diff_h, elem->ws.surfh, nabr->ws.surfh);
grad_h = diff_h / elem->topo.nabrdist[j];
if (surf_mode == KINEMATIC)
{
avg_sf = (grad_h > 0.0) ? grad_h : GRADMIN;
}
else
{
avg_sf = (avg_sf > GRADMIN) ? avg_sf : GRADMIN;
}
/* Weighting needed */
avg_rough = 0.5 * (elem->lc.rough + nabr->lc.rough);
crossa = avg_h * elem->topo.edge[j];
return OverLandFlow(avg_h, grad_h, avg_sf, crossa, avg_rough);
}
void BoundFluxElem(int bc_type, int j, const bc_struct *bc,
const wstate_struct *ws, const topo_struct *topo, const soil_struct *soil,
wflux_struct *wf)
{
double diff_h;
double avg_h;
double effk;
double avg_ksat;
double grad_h;
/* No flow (natural) boundary condition is default */
if (bc_type == NO_FLOW)
{
wf->ovlflow[j] = 0.0;
wf->subsurf[j] = 0.0;
}
/* Note: ideally different boundary conditions need to be
* incorporated for surf and subsurf respectively */
else if (bc_type > 0)
{
/* Note: the formulation assumes only Dirichlet TS right now */
/* note the assumption here is no flow for surface */
wf->ovlflow[j] = 0.0;
diff_h = ws->gw + topo->zmin - bc->head[j];
avg_h = AvgH(diff_h, ws->gw, bc->head[j] - topo->zmin);
/* Minimum distance from circumcenter to the edge of the triangle
* on which boundary condition is defined */
effk = EffKh(soil, ws->gw);
avg_ksat = effk;
grad_h = diff_h / topo->nabrdist[j];
wf->subsurf[j] = avg_ksat * grad_h * avg_h * topo->edge[j];
}
else
{
/* Neumann bc (note: md->ele[i].bc[j] value has to be
* = 2+(index of Neumann boundary ts) */
wf->ovlflow[j] = 0.0;
/* Negative sign is added so the positive numbers in forcing time series
* represents source */
wf->subsurf[j] = -bc->flux[j];
}
}
#if defined(_FBR_)
double FbrFlowElemToElem(const elem_struct *elem, const elem_struct *nabr,
double dist, double edge)
{
double diff_h;
double avg_h;
double grad_h;
double avg_ksat;
diff_h = (elem->ws.fbr_gw + elem->topo.zbed) -
(nabr->ws.fbr_gw + nabr->topo.zbed);
avg_h = AvgH(diff_h, elem->ws.fbr_gw, nabr->ws.fbr_gw);
grad_h = diff_h / dist;
avg_ksat = 0.5 * (elem->geol.ksath + nabr->geol.ksath);
return avg_ksat * grad_h * avg_h * edge;
}
double FbrBoundFluxElem(int bc_type, int j, const bc_struct *bc,
const wstate_struct *ws, const topo_struct *topo, const geol_struct *geol)
{
double diff_h;
double avg_h;
double effk;
double grad_h;
double flux;
/* No flow (natural) boundary condition is default */
if (bc_type == NO_FLOW)
{
flux = 0.0;
}
else if (bc_type > 0)
{
/* Dirichlet boundary conditions */
diff_h = ws->fbr_gw + topo->zbed - bc->head[j];
avg_h = AvgH(diff_h, ws->fbr_gw, bc->head[j] - topo->zbed);
/* Minimum distance from circumcenter to the edge of the triangle
* on which boundary condition is defined */
effk = geol->ksath;
grad_h = diff_h / topo->nabrdist[j];
flux = effk * grad_h * avg_h * topo->edge[j];
}
else
{
/* Neumann boundary conditions */
flux = -bc->flux[j];
}
return flux;
}
#endif
| 2.171875 | 2 |
2024-11-18T19:53:07.075440+00:00
| 2022-03-14T09:49:15 |
80877d0cb343733d31922e2a9aa5df8a47740db0
|
{
"blob_id": "80877d0cb343733d31922e2a9aa5df8a47740db0",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T09:50:00",
"content_id": "e3cbbbd1a7b1ed4affa8e0f07ba1efd5dec13b8d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e1cddfd754d952134e72dfd03522c5ea4fb6008e",
"extension": "c",
"filename": "npt66.c",
"fork_events_count": 630,
"gha_created_at": "2017-07-07T16:29:40",
"gha_event_created_at": "2023-06-21T05:39:17",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 96556718,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3223,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/plugins/npt66/npt66.c",
"provenance": "stackv2-0061.json.gz:3341",
"repo_name": "FDio/vpp",
"revision_date": "2022-03-14T09:49:15",
"revision_id": "f234b0d4626d7e686422cc9dfd25958584f4931e",
"snapshot_id": "0ad30fa1bec2975ffa6b66b45c9f4f32163123b6",
"src_encoding": "UTF-8",
"star_events_count": 1048,
"url": "https://raw.githubusercontent.com/FDio/vpp/f234b0d4626d7e686422cc9dfd25958584f4931e/src/plugins/npt66/npt66.c",
"visit_date": "2023-08-31T16:09:04.068646"
}
|
stackv2
|
// SPDX-License-Identifier: Apache-2.0
// Copyright(c) 2023 Cisco Systems, Inc.
/*
* npt66.c: NPT66 plugin
* An implementation of Network Prefix Translation for IPv6-to-IPv6 (NPTv6) as
* specified in RFC6296.
*/
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <vlib/vlib.h>
#include <vnet/feature/feature.h>
#include <vppinfra/pool.h>
#include "npt66.h"
static int
npt66_feature_enable_disable (u32 sw_if_index, bool is_add)
{
if (vnet_feature_enable_disable ("ip6-unicast", "npt66-input", sw_if_index,
is_add, 0, 0) != 0)
return -1;
if (vnet_feature_enable_disable ("ip6-output", "npt66-output", sw_if_index,
is_add, 0, 0) != 0)
return -1;
return 0;
}
static void
ipv6_prefix_zero (ip6_address_t *address, int prefix_len)
{
int byte_index = prefix_len / 8;
int bit_offset = prefix_len % 8;
uint8_t mask = (1 << (8 - bit_offset)) - 1;
if (byte_index < 16)
{
address->as_u8[byte_index] &= mask;
for (int i = byte_index + 1; i < 16; i++)
{
address->as_u8[i] = 0;
}
}
}
int
npt66_binding_add_del (u32 sw_if_index, ip6_address_t *internal,
int internal_plen, ip6_address_t *external,
int external_plen, bool is_add)
{
npt66_main_t *nm = &npt66_main;
if (is_add)
{
/* Ensure prefix lengths are less than or equal to a /64 */
if (internal_plen > 64 || external_plen > 64)
return VNET_API_ERROR_INVALID_VALUE;
/* Create a binding entry */
npt66_binding_t *b;
pool_get_zero (nm->bindings, b);
b->internal = *internal;
b->internal_plen = internal_plen;
b->external = *external;
b->external_plen = external_plen;
b->sw_if_index = sw_if_index;
ipv6_prefix_zero (&b->internal, internal_plen);
ipv6_prefix_zero (&b->external, external_plen);
vec_validate_init_empty (nm->interface_by_sw_if_index, sw_if_index, ~0);
nm->interface_by_sw_if_index[sw_if_index] = b - nm->bindings;
uword delta = 0;
delta = ip_csum_add_even (delta, b->external.as_u64[0]);
delta = ip_csum_add_even (delta, b->external.as_u64[1]);
delta = ip_csum_sub_even (delta, b->internal.as_u64[0]);
delta = ip_csum_sub_even (delta, b->internal.as_u64[1]);
delta = ip_csum_fold (delta);
b->delta = delta;
}
else
{
/* Delete a binding entry */
npt66_binding_t *b = npt66_interface_by_sw_if_index (sw_if_index);
if (!b)
return VNET_API_ERROR_NO_SUCH_ENTRY;
nm->interface_by_sw_if_index[sw_if_index] = ~0;
pool_put (nm->bindings, b);
}
/* Enable feature on interface */
int rv = npt66_feature_enable_disable (sw_if_index, is_add);
return rv;
}
/*
* Do a lookup in the interface vector (interface_by_sw_if_index)
* and return pool entry.
*/
npt66_binding_t *
npt66_interface_by_sw_if_index (u32 sw_if_index)
{
npt66_main_t *nm = &npt66_main;
if (!nm->interface_by_sw_if_index ||
sw_if_index > (vec_len (nm->interface_by_sw_if_index) - 1))
return 0;
u32 index = nm->interface_by_sw_if_index[sw_if_index];
if (index == ~0)
return 0;
if (pool_is_free_index (nm->bindings, index))
return 0;
return pool_elt_at_index (nm->bindings, index);
}
| 2.265625 | 2 |
2024-11-18T19:53:07.762864+00:00
| 2021-02-22T16:58:24 |
ed07e4f7fc7ac29c4b836fdc976151d17b4021b0
|
{
"blob_id": "ed07e4f7fc7ac29c4b836fdc976151d17b4021b0",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-22T16:58:24",
"content_id": "065deb17bd042a39f3a023cf5300dcb88705b74a",
"detected_licenses": [
"MIT"
],
"directory_id": "dfd8091e79dfa6f8727e132c0ac79840453b3629",
"extension": "c",
"filename": "cmp.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 341261543,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3515,
"license": "MIT",
"license_type": "permissive",
"path": "/test/cmp.c",
"provenance": "stackv2-0061.json.gz:4114",
"repo_name": "kurtsansom/ftnchek",
"revision_date": "2021-02-22T16:58:24",
"revision_id": "cb5b24689fec20e0dac4d158ae57a5b7387e9723",
"snapshot_id": "663704aded132262e40e8ccc4748cecd48647975",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kurtsansom/ftnchek/cb5b24689fec20e0dac4d158ae57a5b7387e9723/test/cmp.c",
"visit_date": "2023-03-05T22:24:14.024550"
}
|
stackv2
|
/* cmp.c:
Simple replacement for Unix cmp, for use with the check.bat script.
This program lacks options such as -l and -s.
*/
/*
Copyright (c) 2000 by Robert K. Moniot.
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
ROBERT K. MONIOT OR FORDHAM UNIVERSITY 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.
Except as contained in this notice, the name of ftnchek shall not be used
in advertising or otherwise to promote the sale, use or other dealings in
this Software without prior written authorization from the author.
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 1024 /* Big enough for present purposes */
long char_count, line_count; /* Total byte and line counts */
char *myname; /* For error messages */
/* Prototypes */
FILE *fopen_or_fail( char *path, char *mode );
int cmp_lines( char *line1, char *line2);
/* Open file or fail with error message.
*/
FILE *fopen_or_fail( char *path, char *mode )
{
FILE *fd;
fd = fopen(path,mode);
if( fd == NULL ) {
fprintf(stderr,"%s: ",myname);
perror(path);
exit(2);
}
return fd;
}
/* Compare two lines, return 0 if equal and 1 if
different. Also keep track of line & char count.
*/
int cmp_lines( char *line1, char *line2)
{
int i;
for(i=0; line1[i] != '\0' && line2[i] != '\0'; i++) {
if(line1[i] != line2[i])
return 1;
char_count++;
if(line1[i] == '\n')
line_count++;
}
return 0;
}
int main( int argc, char *argv[] )
{
FILE *fd1, *fd2; /* input file descriptors */
char line1[MAXLINE], line2[MAXLINE]; /* buffers for input */
char *read1, *read2; /* return status from fgets */
int status = 0; /* exit status */
myname = argv[0];
/* Make sure exactly 2 args are present */
if( argc != 3 ) {
fprintf(stderr,"Usage: %s file1 file2\n", myname);
exit(2);
}
/* Open files, die if cannot */
fd1 = fopen_or_fail( argv[1], "r" );
fd2 = fopen_or_fail( argv[2], "r" );
/* Read files and compare line by line */
line_count = char_count = 1;
for(;;) {
read1 = fgets(line1, sizeof(line1), fd1);
read2 = fgets(line2, sizeof(line2), fd2);
if( read1 == NULL || read2 == NULL ) {
if(read1 != NULL || read2 != NULL) {
printf("%s: EOF on %s\n", myname,
read1 == NULL? argv[1]: argv[2]);
status = 1;
}
break;
}
/* Compare the two lines */
if( (status = cmp_lines(line1, line2)) != 0 ) {
printf("%s %s differ: char %ld, line %ld\n",argv[1],argv[2],
char_count,line_count);
break;
}
}
fclose(fd1);
fclose(fd2);
exit(status);
}
| 2.640625 | 3 |
2024-11-18T19:53:08.295127+00:00
| 2019-05-30T03:19:42 |
e11064ce95c1fcc30972d5f8045a2054bfd47b5b
|
{
"blob_id": "e11064ce95c1fcc30972d5f8045a2054bfd47b5b",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-30T03:19:42",
"content_id": "f179a507342ab930900291d9c984ded8fd94f1f7",
"detected_licenses": [
"Unlicense"
],
"directory_id": "b058c201472df07839de7ea90cf52ed18d938f44",
"extension": "c",
"filename": "Tetris.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": 5792,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Source/Tetris.c",
"provenance": "stackv2-0061.json.gz:4371",
"repo_name": "zer0warm/Hetris",
"revision_date": "2019-05-30T03:19:42",
"revision_id": "9d90c07d780dccf811f22457a4a929599264d53d",
"snapshot_id": "377c115410dbd3d646287d4b0f0edd894aaa1d01",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zer0warm/Hetris/9d90c07d780dccf811f22457a4a929599264d53d/Source/Tetris.c",
"visit_date": "2022-01-07T20:48:28.455887"
}
|
stackv2
|
/*
* File: Tetris.c
* Author: Hieu Do
* Description: Define functions control the logic of the game.
*/
#include "Tetris.h"
/* Loop through all possible units that the tetromino, if performing the
* action, will take places. If one of those places had already been occupied
* (by comparing with 'landed'), the tetromino won't perform those actions.
*
* Return COLLIDE if the tetromino can't perform the action, CLEAR otherwise.
*/
int checkCollision (gridType *landed, tetroType *tetromino, int action)
{
int stylenum = tetromino->stylenum;
if (stylenum == MAX_SHAPES) {
stylenum = 0;
}
int tempRow = tetromino->topLeft->row;
int tempCol = tetromino->topLeft->col;
switch (action) {
case DOWN:
tempRow = tetromino->topLeft->row + 1;
break;
case LEFT:
tempCol = tetromino->topLeft->col - 1;
break;
case RIGHT:
tempCol = tetromino->topLeft->col + 1;
break;
case ROTATE:
break;
default:
break;
}
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
if (tetromino->shapes[stylenum][row][col] != 0) {
if (landed->grid[row + tempRow][col + tempCol] != 0) {
return COLLIDE;
}
}
}
}
tetromino->stylenum = stylenum;
return CLEAR;
}
/* Move the tetromino down by one unit. Check for possible collision
* beforehand. If checkCollision() returns COLLIDE, the tetromino has landed,
* therefore landTetro() is called.
*/
void moveTetroDown (gridType *landed, tetroType *tetromino)
{
if (checkCollision (landed, tetromino, DOWN) == CLEAR) {
tetromino->topLeft->row++;
}
else {
landTetro (landed, tetromino);
}
}
/* Hard drop (move the tetro to the landing area) the tetromino
* Use moveTetroDown() to move it to the landing area.
*/
void hardDropTetro (gridType *landed, tetroType *tetromino)
{
while (landed->justUpdated == FALSE) {
moveTetroDown (landed, tetromino);
}
}
/* Move the tetromino to the left by one unit.
* Check for possible collision beforehand.
*/
void moveTetroLeft (gridType *landed, tetroType *tetromino)
{
if (checkCollision (landed, tetromino, LEFT) == CLEAR) {
tetromino->topLeft->col--;
}
}
/* Move the tetromino to the right by one unit.
* Check for possible collision beforehand.
*/
void moveTetroRight (gridType *landed, tetroType *tetromino)
{
if (checkCollision (landed, tetromino, RIGHT) == CLEAR) {
tetromino->topLeft->col++;
}
}
/* Rotate the tetromino. The style are determined by 'stylenum'
* Check for possible collision beforehand.
*/
void rotateTetro (gridType *landed, tetroType *tetromino)
{
tetromino->stylenum++;
if (checkCollision (landed, tetromino, ROTATE) == COLLIDE) {
tetromino->stylenum--;
}
}
/* Updating the values to 'landed' grid by copying values at the right
* position.
* After doing this, set 'landed->justUpdated' to TRUE to signal the generation
* of new tetrominoes.
*/
void landTetro (gridType *landed, tetroType *tetromino)
{
int style = tetromino->stylenum;
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
int tRow = tetromino->topLeft->row;
int tCol = tetromino->topLeft->col;
int tVal = tetromino->shapes[style][row][col];
if (tVal != 0) {
landed->grid[row + tRow][col + tCol] = tVal;
}
}
}
landed->justUpdated = TRUE;
}
/* Clear the 'lineno' line by copying values of the previous line to it.
* Same thing happens to the previous lines.
* Used by updateGridState().
*/
void clearLine (gridType *landed, int lineno)
{
for (int row = lineno; row > 0; row--) {
for (int col = 1; col <= MAX_GAME_WIDTH; col++) {
landed->grid[row][col] = landed->grid[row - 1][col];
}
}
}
/* Check the whole grid and see whether there are lines to clear, game is over
* (the launching area is crowded).
* Update score when lines are cleared, using this rule:
* 1 line (at the same time) = 100 points
* 2 lines (at the same time) = 200 points
* 3 lines (at the same time) = 600 points
* 4 lines (at the same time) = 2400 points
* (This rule is based on factorial)
*/
void updateGridState (gridType *landed, int *score)
{
int lineStates[MAX_GAME_HEIGHT] = { 0 };
int isFull = TRUE;
int clearCounter = 0;
/* The game can't be continued once the launching area is crowded,
* therefore 'landed->isFull' is set to TRUE to signal the end of the
* current game.
*/
//if (landed->grid[0][5] == 1
// || landed->grid[0][6] == 1
// || landed->grid[0][7] == 1
// || landed->grid[0][8] == 1) {
// landed->isFull = TRUE;
// return;
//}
for (int row = 0; row < MAX_GAME_HEIGHT; row++) {
isFull = TRUE;
for (int col = 1; col <= MAX_GAME_WIDTH; col++) {
if (landed->grid[row][col] == 0) {
isFull = FALSE;
break;
}
}
if (isFull) {
lineStates[row] = TRUE;
}
}
for (int line = 0; line < MAX_GAME_HEIGHT; line++) {
if (lineStates[line] != 0) {
clearLine (landed, line);
++clearCounter;
}
}
switch (clearCounter) {
case 1:
*score += 100;
break;
case 2:
*score += 200;
break;
case 3:
*score += 600;
break;
case 4:
*score += 2400;
default:
break;
}
}
| 3.15625 | 3 |
2024-11-18T19:53:08.392706+00:00
| 2013-12-05T18:46:08 |
079e4c3255bc5de46a3acbf378ecdb0af3ac4777
|
{
"blob_id": "079e4c3255bc5de46a3acbf378ecdb0af3ac4777",
"branch_name": "refs/heads/master",
"committer_date": "2013-12-05T18:46:08",
"content_id": "a8d8a585ac65a52ee3a303c0f3cd657aef3e05a6",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "96f84c16a7efe61126880b3006dd3523fd46d2a5",
"extension": "c",
"filename": "test-file.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 121671003,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 478,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/bin/test-file/test-file.c",
"provenance": "stackv2-0061.json.gz:4499",
"repo_name": "tpalit/SBUnix",
"revision_date": "2013-12-05T18:46:08",
"revision_id": "d519c06aa2c93c9ba1a798baff819752500a2fff",
"snapshot_id": "5e3e86e037f76268490e6cc1c88d974482b3c188",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tpalit/SBUnix/d519c06aa2c93c9ba1a798baff819752500a2fff/bin/test-file/test-file.c",
"visit_date": "2021-04-29T17:31:34.936492"
}
|
stackv2
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<file.h>
#include<string.h>
#define BUFFSIZE 50
int main(int argc, char* argv[], char* envp[])
{
char buff[BUFFSIZE];
int fd = open("filesystem/test2.txt");
printf("\n file descriptor:%d",fd);
if (fd != 0){
if(read(buff,fd,10)!=-1)
{
printf("\n%s",buff);
}
close(fd);
} else {
printf("Could not find directory!\n");
}
return 0;
}
| 2.484375 | 2 |
2024-11-18T19:53:08.462627+00:00
| 2020-06-05T20:01:37 |
30cdb9343bc4c4467ac229cfca55834b0fa3570a
|
{
"blob_id": "30cdb9343bc4c4467ac229cfca55834b0fa3570a",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-05T20:01:37",
"content_id": "2e6afbb8a66dc9685086418a55974d6abee2e40c",
"detected_licenses": [
"MIT"
],
"directory_id": "cfec46e63d2fe742ca879b4b06b6b9d71456b556",
"extension": "c",
"filename": "02_StaticnGlobalVariables.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 266923107,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 596,
"license": "MIT",
"license_type": "permissive",
"path": "/02_Recursion/02_StaticnGlobalVariables.c",
"provenance": "stackv2-0061.json.gz:4627",
"repo_name": "maxponmar/DataStructures_C-Cpp",
"revision_date": "2020-06-05T20:01:37",
"revision_id": "025d8aa4347a080016cf37caea8f6ea433e6baff",
"snapshot_id": "17f6f4c4bf7cf538c193851b21f2cf92228e20bf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/maxponmar/DataStructures_C-Cpp/025d8aa4347a080016cf37caea8f6ea433e6baff/02_Recursion/02_StaticnGlobalVariables.c",
"visit_date": "2022-09-24T10:30:09.734681"
}
|
stackv2
|
#include <stdio.h>
// Original function
int fun(int n)
{
if (n>0)
{
return fun(n-1)+n;
}
return 0;
}
// Static variable function
int fun_static(int n)
{
static int x=0;
if (n>0)
{
x++;
return fun_static(n-1)+x;
}
return 0;
}
// Global variable function
int x=0;
int fun_global(int n)
{
if (n>0)
{
x++;
return fun_global(n-1)+x;
}
return 0;
}
int main()
{
int a=5;
printf("=== Original Function ===\n%d\n", fun(a));
printf("=== Static Variable Function ===\n%d\n", fun_static(a));
printf("=== Global Variable Function ===\n%d\n", fun_global(a));
return 0;
}
| 3.5 | 4 |
2024-11-18T19:53:08.517161+00:00
| 2023-07-29T00:38:27 |
e5236aa5e26fcd596a3bff8d42d415018ad58a92
|
{
"blob_id": "e5236aa5e26fcd596a3bff8d42d415018ad58a92",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-29T00:38:27",
"content_id": "1fd5d9a7b4a53dac8852924e7a3df722d0684f98",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "d5add0361e35f2d86a23a40338fb96e5c8676e53",
"extension": "c",
"filename": "inet.c",
"fork_events_count": 8,
"gha_created_at": "2012-10-29T20:58:42",
"gha_event_created_at": "2016-10-24T22:02:32",
"gha_language": "C",
"gha_license_id": null,
"github_id": 6447532,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4490,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/socket/arpa/inet.c",
"provenance": "stackv2-0061.json.gz:4755",
"repo_name": "DeforaOS/libc",
"revision_date": "2023-07-29T00:38:27",
"revision_id": "b458772e85e69b4f750c0111f18ac3b9bbdc704e",
"snapshot_id": "813b7ba17a607c70cd52ea18b5d3be29b1a07654",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/DeforaOS/libc/b458772e85e69b4f750c0111f18ac3b9bbdc704e/src/socket/arpa/inet.c",
"visit_date": "2023-08-08T11:54:17.059951"
}
|
stackv2
|
/* $Id$ */
/* Copyright (c) 2008-2016 Pierre Pronchery <khorben@defora.org> */
/* This file is part of DeforaOS System libc */
/* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* FIXME check if correct then optimize with macros or whatever */
#include "sys/types.h"
#include "stdlib.h"
#include "stdio.h"
#include "errno.h"
#include "arpa/inet.h"
/* variables */
static const int _test = 0x1234;
static const char * _ptest = (char *)&_test;
/* functions */
/* htonl */
uint32_t htonl(uint32_t host32)
{
if(*_ptest == 0x12)
return host32;
return ((host32 & 0xff) << 24) | ((host32 & 0xff00) << 8)
| ((host32 & 0xff0000) >> 8) | ((host32 & 0xff000000) >> 24);
}
/* htons */
uint16_t htons(uint16_t host16)
{
if(*_ptest == 0x12)
return host16;
return ((host16 & 0xff) << 8) | ((host16 & 0xff00) >> 8);
}
/* inet_addr */
in_addr_t inet_addr(const char *cp)
{
struct in_addr ia;
if(inet_aton(cp, &ia) != 1)
return INADDR_NONE;
return ia.s_addr;
}
/* inet_aton */
int inet_aton(const char *cp, struct in_addr *addr)
{
unsigned long byte;
char * p;
int i;
if(cp == NULL || cp[0] == '\0')
return 0;
addr->s_addr = 0;
for(i = 0; i < 4; i++)
{
byte = strtoul(cp, &p, 0);
if(*p != '.' && *p != '\0')
return 0;
if(byte > 0xff)
return 0;
addr->s_addr = (addr->s_addr << 8) | byte;
if(*p == '\0')
{
addr->s_addr = htonl(addr->s_addr);
return 1;
}
cp = ++p;
}
return 0;
}
/* inet_ntoa */
char * inet_ntoa(struct in_addr in)
{
static char ret[16];
if(inet_ntop(AF_INET, &in, ret, sizeof(ret)) == NULL)
return NULL;
return ret;
}
/* inet_ntop */
static char const * _ntop_inet(const struct in_addr * in, char * dst,
socklen_t size);
static char const * _ntop_inet6(const struct in6_addr * in6, char * dst,
socklen_t size);
char const * inet_ntop(int family, const void * src, char * dst, socklen_t size)
{
const struct in_addr * in = src;
const struct in6_addr * in6 = src;
switch(family)
{
case AF_INET:
return _ntop_inet(in, dst, size);
case AF_INET6:
return _ntop_inet6(in6, dst, size);
default:
#ifdef EAFNOSUPPORT
errno = EAFNOSUPPORT;
#else
errno = EINVAL;
#endif
return NULL;
}
}
static char const * _ntop_inet(const struct in_addr * in, char * dst,
socklen_t size)
{
unsigned char const * b = (unsigned char const *)&in->s_addr;
unsigned int i;
unsigned int pos;
unsigned int p;
for(i = 0, pos = 0;; i++)
if(i == sizeof(in->s_addr))
break;
else if((p = snprintf(&dst[pos], size - pos, "%s%u",
(i > 0) ? "." : "", b[i]))
>= size - pos)
{
errno = ENOSPC;
return NULL;
}
else
pos += p;
return dst;
}
static char const * _ntop_inet6(const struct in6_addr * in6, char * dst,
socklen_t size)
{
uint16_t * b = (uint16_t *)&in6->s6_addr;
unsigned int i;
unsigned int pos;
unsigned int p;
for(i = 0, pos = 0;; i++)
if(i == sizeof(in6->s6_addr))
break;
else if((p = snprintf(&dst[pos], size - pos, "%s%x",
(i > 0) ? ":" : "", b[i]))
>= size - pos)
return NULL;
else
pos += p;
return dst;
}
/* ntohl */
uint32_t ntohl(uint32_t net32)
{
return htonl(net32);
}
/* ntohs */
uint16_t ntohs(uint16_t net16)
{
return htons(net16);
}
| 2.078125 | 2 |
2024-11-18T19:53:08.671265+00:00
| 2022-04-04T13:51:18 |
de6b9c0aa5b98a590c39c36303e4f2b0007fd53d
|
{
"blob_id": "de6b9c0aa5b98a590c39c36303e4f2b0007fd53d",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-04T13:51:18",
"content_id": "af4cf362656941802ccf52c0521d873340cec900",
"detected_licenses": [
"Unlicense"
],
"directory_id": "ab3eefa8fef2c85154399e3100775212c4efe1fc",
"extension": "c",
"filename": "loraWANHandler.c",
"fork_events_count": 8,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 212585005,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4596,
"license": "Unlicense",
"license_type": "permissive",
"path": "/docs/example/loraWANHandler.c",
"provenance": "stackv2-0061.json.gz:5011",
"repo_name": "ihavn/IoT_Semester_project",
"revision_date": "2022-04-04T13:51:18",
"revision_id": "b4d082f58bf6ec7edca1c6618e1d9f300d6da03e",
"snapshot_id": "81800b340e974ea3b14200e3823cd31ea1b8355d",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/ihavn/IoT_Semester_project/b4d082f58bf6ec7edca1c6618e1d9f300d6da03e/docs/example/loraWANHandler.c",
"visit_date": "2022-05-03T11:52:39.366106"
}
|
stackv2
|
/*
* loraWANHandler.c
*
* Created: 12/04/2019 10:09:05
* Author: IHA
*/
#include <stddef.h>
#include <stdio.h>
#include <ATMEGA_FreeRTOS.h>
#include <lora_driver.h>
#include <status_leds.h>
// Parameters for OTAA join - You have got these in a mail from IHA
#define LORA_appEUI "XXXXXXXXXXXXXXX"
#define LORA_appKEY "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
static char _out_buf[100];
void lora_handler_task( void *pvParameters );
static lora_driver_payload_t _uplink_payload;
void lora_handler_create(UBaseType_t lora_handler_task_priority)
{
xTaskCreate(
lora_handler_task
, (const portCHAR *)"LRHand" // A name just for humans
, configMINIMAL_STACK_SIZE+200 // This stack size can be checked & adjusted by reading the Stack Highwater
, NULL
, lora_handler_task_priority // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
, NULL );
}
static void _lora_setup(void)
{
lora_driver_returnCode_t rc;
status_leds_slowBlink(led_ST2); // OPTIONAL: Led the green led blink slowly while we are setting up LoRa
// Factory reset the transceiver
printf("FactoryReset >%s<\n", lora_driver_mapReturnCodeToText(lora_driver_rn2483FactoryReset()));
// Configure to EU868 LoRaWAN standards
printf("Configure to EU868 >%s<\n", lora_driver_mapReturnCodeToText(lora_driver_configureToEu868()));
// Get the transceivers HW EUI
rc = lora_driver_getRn2483Hweui(_out_buf);
printf("Get HWEUI >%s<: %s\n",lora_driver_mapReturnCodeToText(rc), _out_buf);
// Set the HWEUI as DevEUI in the LoRaWAN software stack in the transceiver
printf("Set DevEUI: %s >%s<\n", _out_buf, lora_driver_mapReturnCodeToText(lora_driver_setDeviceIdentifier(_out_buf)));
// Set Over The Air Activation parameters to be ready to join the LoRaWAN
printf("Set OTAA Identity appEUI:%s appKEY:%s devEUI:%s >%s<\n", LORA_appEUI, LORA_appKEY, _out_buf, lora_driver_mapReturnCodeToText(lora_driver_setOtaaIdentity(LORA_appEUI,LORA_appKEY,_out_buf)));
// Save all the MAC settings in the transceiver
printf("Save mac >%s<\n",lora_driver_mapReturnCodeToText(lora_driver_saveMac()));
// Enable Adaptive Data Rate
printf("Set Adaptive Data Rate: ON >%s<\n", lora_driver_mapReturnCodeToText(lora_driver_setAdaptiveDataRate(LORA_ON)));
// Set receiver window1 delay to 500 ms - this is needed if down-link messages will be used
printf("Set Receiver Delay: %d ms >%s<\n", 500, lora_driver_mapReturnCodeToText(lora_driver_setReceiveDelay(500)));
// Join the LoRaWAN
uint8_t maxJoinTriesLeft = 10;
do {
rc = lora_driver_join(LORA_OTAA);
printf("Join Network TriesLeft:%d >%s<\n", maxJoinTriesLeft, lora_driver_mapReturnCodeToText(rc));
if ( rc != LORA_ACCEPTED)
{
// Make the red led pulse to tell something went wrong
status_leds_longPuls(led_ST1); // OPTIONAL
// Wait 5 sec and lets try again
vTaskDelay(pdMS_TO_TICKS(5000UL));
}
else
{
break;
}
} while (--maxJoinTriesLeft);
if (rc == LORA_ACCEPTED)
{
// Connected to LoRaWAN :-)
// Make the green led steady
status_leds_ledOn(led_ST2); // OPTIONAL
}
else
{
// Something went wrong
// Turn off the green led
status_leds_ledOff(led_ST2); // OPTIONAL
// Make the red led blink fast to tell something went wrong
status_leds_fastBlink(led_ST1); // OPTIONAL
// Lets stay here
while (1)
{
taskYIELD();
}
}
}
/*-----------------------------------------------------------*/
void lora_handler_task( void *pvParameters )
{
// Hardware reset of LoRaWAN transceiver
lora_driver_resetRn2483(1);
vTaskDelay(2);
lora_driver_resetRn2483(0);
// Give it a chance to wakeup
vTaskDelay(150);
lora_driver_flushBuffers(); // get rid of first version string from module after reset!
_lora_setup();
_uplink_payload.len = 6;
_uplink_payload.port_no = 2;
TickType_t xLastWakeTime;
const TickType_t xFrequency = pdMS_TO_TICKS(300000UL); // Upload message every 5 minutes (300000 ms)
xLastWakeTime = xTaskGetTickCount();
for(;;)
{
vTaskDelayUntil( &xLastWakeTime, xFrequency );
// Some dummy payload
uint16_t hum = 12345; // Dummy humidity
int16_t temp = 675; // Dummy temp
uint16_t co2_ppm = 1050; // Dummy CO2
_uplink_payload.bytes[0] = hum >> 8;
_uplink_payload.bytes[1] = hum & 0xFF;
_uplink_payload.bytes[2] = temp >> 8;
_uplink_payload.bytes[3] = temp & 0xFF;
_uplink_payload.bytes[4] = co2_ppm >> 8;
_uplink_payload.bytes[5] = co2_ppm & 0xFF;
status_leds_shortPuls(led_ST4); // OPTIONAL
printf("Upload Message >%s<\n", lora_driver_mapReturnCodeToText(lora_driver_sendUploadMessage(false, &_uplink_payload)));
}
}
| 2.359375 | 2 |
2024-11-18T19:53:08.783324+00:00
| 2021-09-14T01:06:12 |
a60bfd2f74114704163357d96041ba2099e703b9
|
{
"blob_id": "a60bfd2f74114704163357d96041ba2099e703b9",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-14T01:06:12",
"content_id": "8c472e37955e7e924658cb64a2706ac08ffdb486",
"detected_licenses": [
"MIT"
],
"directory_id": "a68ba3fc0eb86b0ea1fa21152ba253eeee06b63e",
"extension": "c",
"filename": "Exer7 List1 ER.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 406155520,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1136,
"license": "MIT",
"license_type": "permissive",
"path": "/Repetition Structures/Lista 1/Exer7 List1 ER.c",
"provenance": "stackv2-0061.json.gz:5140",
"repo_name": "whoiswelliton/Programming_Fundamentals",
"revision_date": "2021-09-14T01:06:12",
"revision_id": "63d41e0d14b67cc64d38b0188b583dd8f8ac2905",
"snapshot_id": "68e458ce5b1c36f24e82a09085445763be8aa322",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/whoiswelliton/Programming_Fundamentals/63d41e0d14b67cc64d38b0188b583dd8f8ac2905/Repetition Structures/Lista 1/Exer7 List1 ER.c",
"visit_date": "2023-09-05T00:55:52.418712"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
/*
Ler dois números que representam os limites de um intervalo. Mostrar os ímpares desse intervalo,
em ordem decrescente. O usuário pode informar os valores que representam os limites do intervalo
em ordem crescente ou decrescente.
*/
int main (void)
{
int LimSup,LimIf,Aux,Cont,SomaPares=0,Qdepares=0;
float Media;
printf("Informe o limite inferior do intervalo: ");
scanf("%d",&LimIf);
printf("Informe o limite superior do intervalo: ");
scanf("%d",&LimSup);
// trocar os valores das variaveis lida, se nescessario
if (LimSup < LimIf)
{
Aux = LimSup;
LimSup = LimIf;
LimIf = Aux;
}
printf("Valores impares entre %d e %d: \n",LimSup,LimIf);
for(Cont=LimSup;Cont>=LimIf;Cont--)
{
if(Cont%2!=0)
{
printf("%d\t",Cont);
}
else
{
SomaPares=SomaPares+Cont;
Qdepares++;
}
}
if(Qdepares !=0)
{
Media = (float)SomaPares/Qdepares;
printf("A media e %.2f",Media);
}
printf("\n");
system("pause");
}
| 3.53125 | 4 |
2024-11-18T19:53:08.870821+00:00
| 2022-05-11T16:01:03 |
b0ce3becff20571e29547ee2a24f850e5c03cbb2
|
{
"blob_id": "b0ce3becff20571e29547ee2a24f850e5c03cbb2",
"branch_name": "refs/heads/develop",
"committer_date": "2022-05-11T16:01:03",
"content_id": "32c03bc5787760aea375fcad2d29296a3f617884",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "19a9f2c19bcb81c4a14ba17831d3098de7731fb5",
"extension": "c",
"filename": "dsgridW.c",
"fork_events_count": 68,
"gha_created_at": "2016-09-01T01:34:28",
"gha_event_created_at": "2022-10-08T07:20:06",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 67087395,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 93060,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ni/src/lib/nfp/dsgridW.c",
"provenance": "stackv2-0061.json.gz:5269",
"repo_name": "NCAR/ncl",
"revision_date": "2022-05-11T16:01:03",
"revision_id": "8a96101fe14d0cf0f5ed66a5e6b1733084bc69df",
"snapshot_id": "243c30eaefce642d53373aa583b73df72eb59f22",
"src_encoding": "UTF-8",
"star_events_count": 254,
"url": "https://raw.githubusercontent.com/NCAR/ncl/8a96101fe14d0cf0f5ed66a5e6b1733084bc69df/ni/src/lib/nfp/dsgridW.c",
"visit_date": "2023-03-17T07:53:18.883458"
}
|
stackv2
|
#include <string.h>
#include <stdio.h>
#include "wrapper.h"
NhlErrorTypes dsgrid2s_W( void )
{
int ier = 0;
float *x;
ng_size_t dsizes_x[1];
int has_missing_x;
float *y;
ng_size_t dsizes_y[1];
int has_missing_y;
float *z;
int ndims_z;
ng_size_t dsizes_z[NCL_MAX_DIMENSIONS];
int has_missing_z;
float *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
float *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
NclScalar missing_x, missing_y, missing_z, missing_xo, missing_yo;
float *zo, *tmp_zo;
int ndims_zo;
ng_size_t *dsizes_zo;
ng_size_t i, nzo, size_leftmost, size_z, size_zo;
ng_size_t npts, nxo, nyo;
int type_size_zo, inpts, inxo, inyo;
ng_size_t index_z = 0, index_zo = 0;
int ret;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (float*)NclGetArgValue(
0,
5,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (float*)NclGetArgValue(
1,
5,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if(dsizes_x[0] > INT_MAX) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2s: the length of x is > INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
inpts = (int) npts;
/*
* Check dimension sizes for x and y.
*/
if(dsizes_y[0] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2s: x and y must be the same length");
return(NhlFATAL);
}
/*
* Get z.
*/
z = (float*)NclGetArgValue(
2,
5,
&ndims_z,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
/*
* Check rightmost dimension size for z.
*/
if(dsizes_z[ndims_z-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2s: the last (rightmost) dimension of z must be the same length as x and y");
return(NhlFATAL);
}
/*
* Get rest of parameters.
*/
xo = (float*)NclGetArgValue(
3,
5,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (float*)NclGetArgValue(
4,
5,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_xo[0] > INT_MAX) || (dsizes_yo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2s: the length of xo and/or yo is greater than INT_MAX");
return(NhlFATAL);
}
nxo = dsizes_xo[0];
nyo = dsizes_yo[0];
inxo = (int) nxo;
inyo = (int) nyo;
nzo = nxo * nyo;
/*
* Compute the total size of the input and the leftmost dimensions.
*/
size_leftmost = 1;
for( i = 0; i < ndims_z-1; i++ ) size_leftmost *= dsizes_z[i];
size_z = size_leftmost * npts;
/*
* Check for missing values.
*/
if(contains_missing_float(x,npts,has_missing_x,missing_x.floatval) ||
contains_missing_float(y,npts,has_missing_y,missing_y.floatval) ||
contains_missing_float(z,size_z,has_missing_z,missing_z.floatval) ||
contains_missing_float(xo,nxo,has_missing_xo,missing_xo.floatval) ||
contains_missing_float(yo,nyo,has_missing_yo,missing_yo.floatval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2s: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Calculate space for output array and its dimension sizes.
*/
ndims_zo = ndims_z + 1;
size_zo = size_leftmost * nzo;
zo = (float *) calloc(size_zo, sizeof(float));
dsizes_zo = (ng_size_t *) calloc(ndims_zo, sizeof(ng_size_t));
type_size_zo = nzo * sizeof(float);
if(zo == NULL || dsizes_zo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,
"dsgrid2s: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
for( i = 0; i < ndims_zo-2; i++ ) dsizes_zo[i] = dsizes_z[i];
dsizes_zo[ndims_zo-2] = nxo;
dsizes_zo[ndims_zo-1] = nyo;
/*
* The following section loops through the leftmost dimensions and calls
* the c_dsgrid2s function.
*/
for( i = 0; i < size_leftmost; i++ ) {
tmp_zo = c_dsgrid2s (inpts,x,y,&z[index_z],inxo,inyo,xo,yo,&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2s: ier = %d", ier);
NclFree(tmp_zo);
return(NhlFATAL);
}
memcpy((void*)((char*)zo+i*type_size_zo),
(void*)((char*)tmp_zo),type_size_zo);
index_z += npts;
index_zo += nzo;
NclFree(tmp_zo);
}
ret = NclReturnValue((void*)zo,ndims_zo,dsizes_zo,NULL,NCL_float,0);
NclFree(dsizes_zo);
return(ret);
}
NhlErrorTypes dsgrid2_W( void )
{
/*
* Input values
*/
void *x, *y, *z;
double *tmp_x, *tmp_y;
double *tmp_z = NULL;
ng_size_t dsizes_x[1];
int has_missing_x;
ng_size_t dsizes_y[1];
int has_missing_y;
int ndims_z;
ng_size_t dsizes_z[NCL_MAX_DIMENSIONS];
int has_missing_z;
NclBasicDataTypes type_x, type_y, type_z;
NclScalar missing_x, missing_y, missing_z;
NclScalar missing_dx, missing_dy, missing_dz, missing_rz;
/*
* Output grid to interpolate on.
*/
void *xo, *yo;
double *tmp_xo, *tmp_yo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
NclBasicDataTypes type_xo, type_yo;
NclScalar missing_xo, missing_yo, missing_dxo, missing_dyo;
/*
* Output variables.
*/
void *zo;
double *tmp_zo;
int ndims_zo;
ng_size_t *dsizes_zo;
NclBasicDataTypes type_zo;
NclScalar missing_zo, missing_dzo;
/*
* Various
*/
ng_size_t i, nzo, size_leftmost, size_z, size_zo;
ng_size_t npts, nxo, nyo;
int inpts, inxo, inyo, ier = 0, nmiss = 0, ret;
ng_size_t index_z = 0, index_zo = 0;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept numerics.
*/
x = (void*)NclGetArgValue(
0,
5,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
5,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if(dsizes_x[0] > INT_MAX) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2: the length of x is > INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
inpts = (int) npts;
/*
* Check dimension sizes for x and y.
*/
if(dsizes_y[0] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2: x and y must be the same length");
return(NhlFATAL);
}
/*
* Get z.
*/
z = (void*)NclGetArgValue(
2,
5,
&ndims_z,
dsizes_z,
&missing_z,
&has_missing_z,
&type_z,
DONT_CARE);
/*
* Check rightmost dimension size for z.
*/
if(dsizes_z[ndims_z-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2: the last (rightmost) dimension of z must be the same length as x and y");
return(NhlFATAL);
}
/*
* Get rest of parameters.
*/
xo = (void*)NclGetArgValue(
3,
5,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
&type_xo,
DONT_CARE);
yo = (void*)NclGetArgValue(
4,
5,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
&type_yo,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_xo[0] > INT_MAX) || (dsizes_yo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2: the length of xo and/or yo is greater than INT_MAX");
return(NhlFATAL);
}
nxo = dsizes_xo[0];
nyo = dsizes_yo[0];
inxo = (int) nxo;
inyo = (int) nyo;
nzo = nxo * nyo;
/*
* Compute the total size of the input and the leftmost dimensions.
*/
size_leftmost = 1;
for( i = 0; i < ndims_z-1; i++ ) size_leftmost *= dsizes_z[i];
size_z = size_leftmost * npts;
/*
* Coerce missing values.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
coerce_missing(type_z,has_missing_z,&missing_z,&missing_dz,&missing_rz);
coerce_missing(type_xo,has_missing_xo,&missing_xo,&missing_dxo,NULL);
coerce_missing(type_yo,has_missing_yo,&missing_yo,&missing_dyo,NULL);
/*
* Coerce input arrays to double, if necessary.
*/
tmp_x = coerce_input_double(x,type_x,npts,has_missing_x,&missing_x,
&missing_dx);
tmp_y = coerce_input_double(y,type_y,npts,has_missing_y,&missing_y,
&missing_dy);
tmp_xo = coerce_input_double(xo,type_xo,nxo,has_missing_xo,&missing_xo,
&missing_dxo);
tmp_yo = coerce_input_double(yo,type_yo,nyo,has_missing_yo,&missing_yo,
&missing_dyo);
/*
* Allocate space for temporary input array. The temporary array
* tmp_z is just big enough to hold a one-dimensional subsection of the
* z array. We only need to allocate space for it if the
* input is not already double. Otherwise, we just have it point
* to the appropriate locations in z.
*/
if(type_z != NCL_double) {
tmp_z = (double*)calloc(npts,sizeof(double));
if(tmp_z == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2: Unable to allocate memory for coercing z array to double precision");
return(NhlFATAL);
}
}
/*
* Check for missing values.
*/
if(contains_missing(tmp_x,npts,has_missing_x,missing_dx.doubleval) ||
contains_missing(tmp_y,npts,has_missing_y,missing_dy.doubleval) ||
contains_missing(tmp_xo,nxo,has_missing_xo,missing_dxo.doubleval) ||
contains_missing(tmp_yo,nyo,has_missing_yo,missing_dyo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Calculate space for output array and its dimension sizes.
*/
ndims_zo = ndims_z + 1;
size_zo = size_leftmost * nzo;
dsizes_zo = (ng_size_t *) calloc(ndims_zo, sizeof(ng_size_t));
if(type_z != NCL_double) {
type_zo = NCL_float;
zo = (void*)calloc(size_zo,sizeof(float));
}
else {
type_zo = NCL_double;
zo = (void*)calloc(size_zo,sizeof(double));
}
if(zo == NULL || dsizes_zo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,
"dsgrid2: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
if(has_missing_z) {
if(type_zo == NCL_double) missing_zo = missing_dz;
else missing_zo = missing_rz;
missing_dzo = missing_dz;
}
for( i = 0; i < ndims_zo-2; i++ ) dsizes_zo[i] = dsizes_z[i];
dsizes_zo[ndims_zo-2] = nxo;
dsizes_zo[ndims_zo-1] = nyo;
/*
* The following section loops through the leftmost dimensions and calls
* the c_dsgrid2d function.
*/
for( i = 0; i < size_leftmost; i++ ) {
if(type_z != NCL_double) {
/*
* Coerce npts subsection of z (tmp_z) to double.
*/
coerce_subset_input_double(z,tmp_z,index_z,type_z,npts,has_missing_z,
&missing_z,&missing_dz);
}
else {
/*
* Point tmp_z to appropriate location in z.
*/
tmp_z = &((double*)z)[index_z];
}
/*
* Check for missing values in z.
*/
if(contains_missing(tmp_z,npts,has_missing_z,missing_dz.doubleval)) {
nmiss++;
/*
* Set all elements of this 2D grid to a missing value, if a missing
* value exists.
*/
set_subset_output_missing(zo,index_zo,type_zo,nzo,missing_dzo.doubleval);
}
else {
/*
* Call c_dsgrid2d.
*/
tmp_zo = c_dsgrid2d (inpts,tmp_x,tmp_y,tmp_z,inxo,inyo,tmp_xo,tmp_yo,&ier);
/*
* Check for errors.
*/
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2: ier = %d", ier);
/*
* Free arrays
*/
if(type_x != NCL_double) NclFree(tmp_x);
if(type_y != NCL_double) NclFree(tmp_y);
if(type_z != NCL_double) NclFree(tmp_z);
if(type_xo != NCL_double) NclFree(tmp_xo);
if(type_yo != NCL_double) NclFree(tmp_yo);
NclFree(tmp_zo);
return(NhlFATAL);
}
coerce_output_float_or_double(zo,tmp_zo,type_zo,nzo,index_zo);
index_z += npts;
index_zo += nzo;
NclFree(tmp_zo);
}
}
/*
* Check if z array had missing values. If so, print a warning message.
*/
if(nmiss) {
NhlPError(NhlWARNING,NhlEUNKNOWN,"dsgrid2: %d one-dimensional input arrays contained missing values. No interpolation performed on these arrays",nmiss);
}
/*
* Free arrays
*/
if(type_x != NCL_double) NclFree(tmp_x);
if(type_y != NCL_double) NclFree(tmp_y);
if(type_z != NCL_double) NclFree(tmp_z);
if(type_xo != NCL_double) NclFree(tmp_xo);
if(type_yo != NCL_double) NclFree(tmp_yo);
if(has_missing_z) {
ret = NclReturnValue(zo,ndims_zo,dsizes_zo,&missing_zo,type_zo,0);
}
else {
ret = NclReturnValue(zo,ndims_zo,dsizes_zo,NULL,type_zo,0);
}
NclFree(dsizes_zo);
return(ret);
}
NhlErrorTypes dsgrid2d_W( void )
{
int ier = 0;
double *x;
ng_size_t dsizes_x[1];
int has_missing_x;
double *y;
ng_size_t dsizes_y[1];
int has_missing_y;
double *z;
int ndims_z;
ng_size_t dsizes_z[NCL_MAX_DIMENSIONS];
int has_missing_z;
double *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
double *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
NclScalar missing_x, missing_y, missing_z, missing_xo, missing_yo;
double *zo, *tmp_zo;
int ndims_zo;
ng_size_t *dsizes_zo;
ng_size_t i, nzo, size_leftmost, size_z, size_zo;
ng_size_t npts, nxo, nyo;
int inpts, inxo, inyo, type_size_zo;
ng_size_t index_z = 0, index_zo = 0;
int ret;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (double*)NclGetArgValue(
0,
5,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (double*)NclGetArgValue(
1,
5,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if(dsizes_x[0] > INT_MAX) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2d: the length of x is > INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
inpts = (int) npts;
/*
* Check dimension sizes for x and y.
*/
if(dsizes_y[0] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2d: x and y must be the same length");
return(NhlFATAL);
}
/*
* Get z.
*/
z = (double*)NclGetArgValue(
2,
5,
&ndims_z,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
/*
* Check rightmost dimension size for z.
*/
if(dsizes_z[ndims_z-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2d: the last (rightmost) dimension of z must be the same length as x and y");
return(NhlFATAL);
}
/*
* Get rest of parameters.
*/
xo = (double*)NclGetArgValue(
3,
5,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (double*)NclGetArgValue(
4,
5,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_xo[0] > INT_MAX) || (dsizes_yo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2d: the length of xo and/or yo is greater than INT_MAX");
return(NhlFATAL);
}
nxo = dsizes_xo[0];
nyo = dsizes_yo[0];
inxo = (int) nxo;
inyo = (int) nyo;
nzo = nxo * nyo;
/*
* Compute the total size of the input and the leftmost dimensions.
*/
size_leftmost = 1;
for( i = 0; i < ndims_z-1; i++ ) size_leftmost *= dsizes_z[i];
size_z = size_leftmost * npts;
/*
* Check for missing values.
*/
if(contains_missing(x,npts,has_missing_x,missing_x.doubleval) ||
contains_missing(y,npts,has_missing_y,missing_y.doubleval) ||
contains_missing(z,size_z,has_missing_z,missing_z.doubleval) ||
contains_missing(xo,nxo,has_missing_xo,missing_xo.doubleval) ||
contains_missing(yo,nyo,has_missing_yo,missing_yo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2d: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Calculate space for output array and its dimension sizes.
*/
ndims_zo = ndims_z + 1;
size_zo = size_leftmost * nzo;
zo = (double *) calloc(size_zo, sizeof(double));
dsizes_zo = (ng_size_t *) calloc(ndims_zo, sizeof(ng_size_t));
type_size_zo = nzo * sizeof(double);
if(zo == NULL || dsizes_zo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,
"dsgrid2d: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
for( i = 0; i < ndims_zo-2; i++ ) dsizes_zo[i] = dsizes_z[i];
dsizes_zo[ndims_zo-2] = nxo;
dsizes_zo[ndims_zo-1] = nyo;
/*
* The following section loops through the leftmost dimensions and calls
* the c_dsgrid2d function.
*/
for( i = 0; i < size_leftmost; i++ ) {
tmp_zo = c_dsgrid2d (inpts,x,y,&z[index_z],inxo,inyo,xo,yo,&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid2d: ier = %d", ier);
NclFree(tmp_zo);
return(NhlFATAL);
}
memcpy((void*)((char*)zo+i*type_size_zo),
(void*)((char*)tmp_zo),type_size_zo);
index_z += npts;
index_zo += nzo;
NclFree(tmp_zo);
}
ret = NclReturnValue((void*)zo,ndims_zo,dsizes_zo,NULL,NCL_double,0);
NclFree(dsizes_zo);
return(ret);
}
NhlErrorTypes dsgrid3s_W( void )
{
int ier = 0;
float *x;
ng_size_t dsizes_x[1];
int has_missing_x;
float *y;
ng_size_t dsizes_y[1];
int has_missing_y;
float *z;
ng_size_t dsizes_z[1];
int has_missing_z;
float *u;
int ndims_u;
ng_size_t dsizes_u[NCL_MAX_DIMENSIONS];
int has_missing_u;
float *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
float *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
float *zo;
ng_size_t dsizes_zo[1];
int has_missing_zo;
NclScalar missing_x, missing_y, missing_z, missing_u;
NclScalar missing_xo, missing_yo, missing_zo;
float *uo, *tmp_uo;
int ndims_uo;
ng_size_t *dsizes_uo;
ng_size_t i, npts, nxo, nyo, nzo, nuo;
int inpts, inxo, inyo, inzo, ret;
ng_size_t size_leftmost, size_u, size_uo;
int type_size_uo;
ng_size_t index_u = 0, index_uo = 0;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (float*)NclGetArgValue(
0,
7,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (float*)NclGetArgValue(
1,
7,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
z = (float*)NclGetArgValue(
2,
7,
NULL,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if(dsizes_x[0] > INT_MAX) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3s: the length of x is > INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
inpts = (int) npts;
/*
* Check dimension sizes for x, y, and z.
*/
if(dsizes_y[0] != npts || dsizes_z[0] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3s: x, y, and z must be the same length");
return(NhlFATAL);
}
/*
* Get u.
*/
u = (float*)NclGetArgValue(
3,
7,
&ndims_u,
dsizes_u,
&missing_u,
&has_missing_u,
NULL,
DONT_CARE);
/*
* Check rightmost dimension size for u.
*/
if(dsizes_u[ndims_u-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3s: the last (rightmost) dimension of u must be the same length as x, y, and z");
return(NhlFATAL);
}
/*
* Compute the total size of the input and the leftmost dimensions.
*/
size_leftmost = 1;
for( i = 0; i < ndims_u-1; i++ ) size_leftmost *= dsizes_u[i];
size_u = size_leftmost * npts;
/*
* Get rest of parameters.
*/
xo = (float*)NclGetArgValue(
4,
7,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (float*)NclGetArgValue(
5,
7,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
zo = (float*)NclGetArgValue(
6,
7,
NULL,
dsizes_zo,
&missing_zo,
&has_missing_zo,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_xo[0] > INT_MAX) || (dsizes_yo[0] > INT_MAX) ||
(dsizes_zo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3s: the length of xo, yo, and/or zo is greater than INT_MAX");
return(NhlFATAL);
}
nxo = dsizes_xo[0];
nyo = dsizes_yo[0];
nzo = dsizes_zo[0];
inxo = (int) nxo;
inyo = (int) nyo;
inzo = (int) nzo;
nuo = nxo * nyo * nzo;
/*
* Check for missing values.
*/
if(contains_missing_float(x,npts,has_missing_x,missing_x.floatval) ||
contains_missing_float(y,npts,has_missing_y,missing_y.floatval) ||
contains_missing_float(z,npts,has_missing_z,missing_z.floatval) ||
contains_missing_float(u,size_u,has_missing_u,missing_u.floatval) ||
contains_missing_float(xo,nxo,has_missing_xo,missing_xo.floatval) ||
contains_missing_float(yo,nyo,has_missing_yo,missing_yo.floatval) ||
contains_missing_float(zo,nzo,has_missing_zo,missing_zo.floatval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3s: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Calculate space for output array and its dimension sizes.
*/
ndims_uo = ndims_u + 2;
size_uo = size_leftmost * nuo;
uo = (float *) calloc(size_uo, sizeof(float));
dsizes_uo = (ng_size_t *) calloc(ndims_uo, sizeof(ng_size_t));
type_size_uo = nuo * sizeof(float);
if(uo == NULL || dsizes_uo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,
"dsgrid3s: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
for( i = 0; i < ndims_uo-3; i++ ) dsizes_uo[i] = dsizes_u[i];
dsizes_uo[ndims_uo-3] = nxo;
dsizes_uo[ndims_uo-2] = nyo;
dsizes_uo[ndims_uo-1] = nzo;
/*
* The following section loops through the leftmost dimensions and calls
* the c_dsgrid3s function.
*/
for( i = 0; i < size_leftmost; i++ ) {
tmp_uo = c_dsgrid3s(inpts,x,y,z,&u[index_u],inxo,inyo,inzo,xo,yo,zo,&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3s: ier = %d", ier);
NclFree(tmp_uo);
return(NhlFATAL);
}
memcpy((void*)((char*)uo+i*type_size_uo),
(void*)((char*)tmp_uo),type_size_uo);
index_u += npts;
index_uo += nuo;
NclFree(tmp_uo);
}
ret = NclReturnValue((void*)uo,ndims_uo,dsizes_uo,NULL,NCL_float,0);
NclFree(dsizes_uo);
return(ret);
}
NhlErrorTypes dsgrid3_W( void )
{
/*
* Input values
*/
void *x, *y, *z, *u;
double *tmp_x, *tmp_y, *tmp_z;
double *tmp_u = NULL;
ng_size_t dsizes_x[1];
int has_missing_x;
ng_size_t dsizes_y[1];
int has_missing_y;
ng_size_t dsizes_z[1];
int has_missing_z;
int ndims_u;
ng_size_t dsizes_u[NCL_MAX_DIMENSIONS];
int has_missing_u;
NclBasicDataTypes type_x, type_y, type_z, type_u;
NclScalar missing_x, missing_y, missing_z, missing_u;
NclScalar missing_dx, missing_dy, missing_dz, missing_du, missing_ru;
/*
* Output grid to interpolate on.
*/
void *xo, *yo, *zo;
double *tmp_xo, *tmp_yo, *tmp_zo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
ng_size_t dsizes_zo[1];
int has_missing_zo;
NclBasicDataTypes type_xo, type_yo, type_zo;
NclScalar missing_xo, missing_yo, missing_zo;
NclScalar missing_dxo, missing_dyo, missing_dzo;
/*
* Output variables.
*/
void *uo;
double *tmp_uo;
int ndims_uo;
ng_size_t *dsizes_uo;
NclBasicDataTypes type_uo;
NclScalar missing_uo, missing_duo;
/*
* Various
*/
ng_size_t i, nuo, size_leftmost, size_u, size_uo;
ng_size_t index_u = 0, index_uo = 0;
ng_size_t npts, nxo, nyo, nzo;
int inpts, inxo, inyo, inzo, ier = 0, nmiss = 0, ret;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept numerics.
*/
x = (void*)NclGetArgValue(
0,
7,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
7,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
z = (void*)NclGetArgValue(
2,
7,
NULL,
dsizes_z,
&missing_z,
&has_missing_z,
&type_z,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if(dsizes_x[0] > INT_MAX) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: the length of x is > INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
inpts = (int) npts;
/*
* Check dimension sizes for x, y, and z.
*/
if(dsizes_y[0] != npts || dsizes_z[0] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: x, y, and z must be the same length");
return(NhlFATAL);
}
/*
* Get u.
*/
u = (void*)NclGetArgValue(
3,
7,
&ndims_u,
dsizes_u,
&missing_u,
&has_missing_u,
&type_u,
DONT_CARE);
/*
* Check rightmost dimension size for u.
*/
if(dsizes_u[ndims_u-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: the last (rightmost) dimension of u must be the same length as x, y, and z");
return(NhlFATAL);
}
/*
* Get rest of parameters.
*/
xo = (void*)NclGetArgValue(
4,
7,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
&type_xo,
DONT_CARE);
yo = (void*)NclGetArgValue(
5,
7,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
&type_yo,
DONT_CARE);
zo = (void*)NclGetArgValue(
6,
7,
NULL,
dsizes_zo,
&missing_zo,
&has_missing_zo,
&type_zo,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_xo[0] > INT_MAX) || (dsizes_yo[0] > INT_MAX) ||
(dsizes_zo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: the length of xo, yo, and/or zo is greater than INT_MAX");
return(NhlFATAL);
}
nxo = dsizes_xo[0];
nyo = dsizes_yo[0];
nzo = dsizes_zo[0];
inxo = (int) nxo;
inyo = (int) nyo;
inzo = (int) nzo;
nuo = nxo * nyo * nzo;
/*
* Compute the total size of the input and the leftmost dimensions.
*/
size_leftmost = 1;
for( i = 0; i < ndims_u-1; i++ ) size_leftmost *= dsizes_u[i];
size_u = size_leftmost * npts;
/*
* Coerce missing values.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
coerce_missing(type_z,has_missing_z,&missing_z,&missing_dz,NULL);
coerce_missing(type_u,has_missing_u,&missing_u,&missing_du,&missing_ru);
coerce_missing(type_xo,has_missing_xo,&missing_xo,&missing_dxo,NULL);
coerce_missing(type_yo,has_missing_yo,&missing_yo,&missing_dyo,NULL);
coerce_missing(type_zo,has_missing_zo,&missing_zo,&missing_dzo,NULL);
/*
* Coerce input arrays to double, if necessary.
*/
tmp_x = coerce_input_double(x,type_x,npts,has_missing_x,&missing_x,
&missing_dx);
tmp_y = coerce_input_double(y,type_y,npts,has_missing_y,&missing_y,
&missing_dy);
tmp_z = coerce_input_double(z,type_z,npts,has_missing_z,&missing_z,
&missing_dz);
tmp_xo = coerce_input_double(xo,type_xo,nxo,has_missing_xo,&missing_xo,
&missing_dxo);
tmp_yo = coerce_input_double(yo,type_yo,nyo,has_missing_yo,&missing_yo,
&missing_dyo);
tmp_zo = coerce_input_double(zo,type_zo,nzo,has_missing_zo,&missing_zo,
&missing_dzo);
/*
* Allocate space for temporary input array. The temporary array
* tmp_u is just big enough to hold a one-dimensional subsection of the
* u array. We only need to allocate space for it if the
* input is not already double. Otherwise, we just have it point
* to the appropriate locations in u.
*/
if(type_u != NCL_double) {
tmp_u = (double*)calloc(npts,sizeof(double));
if(tmp_u == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: Unable to allocate memory for coercing u array to double precision");
return(NhlFATAL);
}
}
/*
* Check for missing values.
*/
if(contains_missing(tmp_x,npts,has_missing_x,missing_dx.doubleval) ||
contains_missing(tmp_y,npts,has_missing_y,missing_dy.doubleval) ||
contains_missing(tmp_z,npts,has_missing_z,missing_dz.doubleval) ||
contains_missing(tmp_xo,nxo,has_missing_xo,missing_dxo.doubleval) ||
contains_missing(tmp_yo,nyo,has_missing_yo,missing_dyo.doubleval) ||
contains_missing(tmp_zo,nzo,has_missing_zo,missing_dzo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Calculate space for output array and its dimension sizes.
*/
ndims_uo = ndims_u + 2;
size_uo = size_leftmost * nuo;
dsizes_uo = (ng_size_t *) calloc(ndims_uo, sizeof(ng_size_t));
if(type_u != NCL_double) {
type_uo = NCL_float;
uo = (void*)calloc(size_uo,sizeof(float));
}
else {
type_uo = NCL_double;
uo = (void*)calloc(size_uo,sizeof(double));
}
if(uo == NULL || dsizes_uo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,
"dsgrid3: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
if(has_missing_u) {
if(type_uo == NCL_double) missing_uo = missing_du;
else missing_uo = missing_ru;
missing_duo = missing_du;
}
for( i = 0; i < ndims_uo-3; i++ ) dsizes_uo[i] = dsizes_u[i];
dsizes_uo[ndims_uo-3] = nxo;
dsizes_uo[ndims_uo-2] = nyo;
dsizes_uo[ndims_uo-1] = nzo;
/*
* The following section loops through the leftmost dimensions and calls
* the c_dsgrid3d function.
*/
for( i = 0; i < size_leftmost; i++ ) {
if(type_u != NCL_double) {
/*
* Coerce npts subsection of u (tmp_u) to double.
*/
coerce_subset_input_double(u,tmp_u,index_u,type_u,npts,has_missing_u,
&missing_u,&missing_du);
}
else {
/*
* Point tmp_u to appropriate location in u.
*/
tmp_u = &((double*)u)[index_u];
}
/*
* Check for missing values in u.
*/
if(contains_missing(tmp_u,npts,has_missing_u,missing_du.doubleval)) {
nmiss++;
/*
* Set all elements of this 2D grid to a missing value, if a missing
* value exists.
*/
set_subset_output_missing(uo,index_uo,type_uo,nuo,missing_duo.doubleval);
}
else {
/*
* Call c_dsgrid3d.
*/
tmp_uo = c_dsgrid3d(inpts,tmp_x,tmp_y,tmp_z,tmp_u,inxo,inyo,inzo,
tmp_xo,tmp_yo,tmp_zo,&ier);
/*
* Check for errors.
*/
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: ier = %d", ier);
/*
* Free arrays
*/
if(type_x != NCL_double) NclFree(tmp_x);
if(type_y != NCL_double) NclFree(tmp_y);
if(type_z != NCL_double) NclFree(tmp_z);
if(type_u != NCL_double) NclFree(tmp_u);
if(type_xo != NCL_double) NclFree(tmp_xo);
if(type_yo != NCL_double) NclFree(tmp_yo);
if(type_zo != NCL_double) NclFree(tmp_zo);
NclFree(tmp_uo);
return(NhlFATAL);
}
coerce_output_float_or_double(uo,tmp_uo,type_uo,nuo,index_uo);
index_u += npts;
index_uo += nuo;
NclFree(tmp_uo);
}
}
/*
* Check if u array had missing values. If so, print a warning message.
*/
if(nmiss) {
NhlPError(NhlWARNING,NhlEUNKNOWN,"dsgrid2: %d one-dimensional input arrays contained missing values. No interpolation performed on these arrays",nmiss);
}
/*
* Free arrays
*/
if(type_x != NCL_double) NclFree(tmp_x);
if(type_y != NCL_double) NclFree(tmp_y);
if(type_z != NCL_double) NclFree(tmp_z);
if(type_u != NCL_double) NclFree(tmp_u);
if(type_xo != NCL_double) NclFree(tmp_xo);
if(type_yo != NCL_double) NclFree(tmp_yo);
if(type_zo != NCL_double) NclFree(tmp_zo);
if(has_missing_u) {
ret = NclReturnValue(uo,ndims_uo,dsizes_uo,&missing_uo,type_uo,0);
}
else {
ret = NclReturnValue(uo,ndims_uo,dsizes_uo,NULL,type_uo,0);
}
NclFree(dsizes_uo);
return(ret);
}
NhlErrorTypes dsgrid3d_W( void )
{
int ier = 0;
double *x;
ng_size_t dsizes_x[1];
int has_missing_x;
double *y;
ng_size_t dsizes_y[1];
int has_missing_y;
double *z;
ng_size_t dsizes_z[1];
int has_missing_z;
double *u;
int ndims_u;
ng_size_t dsizes_u[NCL_MAX_DIMENSIONS];
int has_missing_u;
double *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
double *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
double *zo;
ng_size_t dsizes_zo[1];
int has_missing_zo;
NclScalar missing_x, missing_y, missing_z, missing_u;
NclScalar missing_xo, missing_yo, missing_zo;
double *uo, *tmp_uo;
int ndims_uo;
ng_size_t *dsizes_uo;
ng_size_t i, nuo;
ng_size_t npts, nxo, nyo, nzo;
int inpts, inxo, inyo, inzo, type_size_uo;
ng_size_t size_leftmost, size_u, size_uo;
int ret;
ng_size_t index_u = 0, index_uo = 0;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (double*)NclGetArgValue(
0,
7,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (double*)NclGetArgValue(
1,
7,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
z = (double*)NclGetArgValue(
2,
7,
NULL,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if(dsizes_x[0] > INT_MAX) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3d: the length of x is > INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
inpts = (int) npts;
/*
* Check dimension sizes for x, y, and z.
*/
if(dsizes_y[0] != npts || dsizes_z[0] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3d: x, y, and z must be the same length");
return(NhlFATAL);
}
/*
* Get u.
*/
u = (double*)NclGetArgValue(
3,
7,
&ndims_u,
dsizes_u,
&missing_u,
&has_missing_u,
NULL,
DONT_CARE);
/*
* Check rightmost dimension size for u.
*/
if(dsizes_u[ndims_u-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3: the last (rightmost) dimension of u must be the same length as x, y, and z");
return(NhlFATAL);
}
/*
* Compute the total size of the input and the leftmost dimensions.
*/
size_leftmost = 1;
for( i = 0; i < ndims_u-1; i++ ) size_leftmost *= dsizes_u[i];
size_u = size_leftmost * npts;
/*
* Get rest of parameters.
*/
xo = (double*)NclGetArgValue(
4,
7,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (double*)NclGetArgValue(
5,
7,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
zo = (double*)NclGetArgValue(
6,
7,
NULL,
dsizes_zo,
&missing_zo,
&has_missing_zo,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_xo[0] > INT_MAX) || (dsizes_yo[0] > INT_MAX) ||
(dsizes_zo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3d: the length of xo, yo, and/or zo is greater than INT_MAX");
return(NhlFATAL);
}
nxo = dsizes_xo[0];
nyo = dsizes_yo[0];
nzo = dsizes_zo[0];
inxo = (int) nxo;
inyo = (int) nyo;
inzo = (int) nzo;
nuo = nxo * nyo * nzo;
/*
* Check for missing values.
*/
if(contains_missing(x,npts,has_missing_x,missing_x.doubleval) ||
contains_missing(y,npts,has_missing_y,missing_y.doubleval) ||
contains_missing(z,npts,has_missing_z,missing_z.doubleval) ||
contains_missing(u,size_u,has_missing_u,missing_u.doubleval) ||
contains_missing(xo,nxo,has_missing_xo,missing_xo.doubleval) ||
contains_missing(yo,nyo,has_missing_yo,missing_yo.doubleval) ||
contains_missing(zo,nzo,has_missing_zo,missing_zo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3d: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Calculate space for output array and its dimension sizes.
*/
ndims_uo = ndims_u + 2;
size_uo = size_leftmost * nuo;
uo = (double *) calloc(size_uo, sizeof(double));
dsizes_uo = (ng_size_t *) calloc(ndims_uo, sizeof(ng_size_t));
type_size_uo = nuo * sizeof(double);
if(uo == NULL || dsizes_uo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,
"dsgrid3d: Unable to allocate memory for output arrays");
return(NhlFATAL);
}
for( i = 0; i < ndims_uo-3; i++ ) dsizes_uo[i] = dsizes_u[i];
dsizes_uo[ndims_uo-3] = nxo;
dsizes_uo[ndims_uo-2] = nyo;
dsizes_uo[ndims_uo-1] = nzo;
/*
* The following section loops through the leftmost dimensions and calls
* the c_dsgrid3d function.
*/
for( i = 0; i < size_leftmost; i++ ) {
tmp_uo = c_dsgrid3d(inpts,x,y,z,&u[index_u],inxo,inyo,inzo,xo,yo,zo,&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dsgrid3d: ier = %d", ier);
NclFree(tmp_uo);
return(NhlFATAL);
}
memcpy((void*)((char*)uo+i*type_size_uo),
(void*)((char*)tmp_uo),type_size_uo);
index_u += npts;
index_uo += nuo;
NclFree(tmp_uo);
}
ret = NclReturnValue((void*)uo,ndims_uo,dsizes_uo,NULL,NCL_double,0);
NclFree(dsizes_uo);
return(ret);
}
NhlErrorTypes dssetp_W(void)
{
char *arg1, *cval;
int numpi, numpf, numpc, i;
/*
* List the integer and float parameter names. To add new ones,
* all that needs to be done is add the names to this list.
*/
char *params_i[] = {"shd", "SHD"};
char *params_f[] = {"dmv", "dmx", "exp", "DMV", "DMX", "EXP"};
char *params_c[] = {"erf", "ERF"};
/*
* Input array variables
*/
NrmQuark *pname;
int ndims_pname;
ng_size_t dsizes_pname[NCL_MAX_DIMENSIONS];
void *pvalue;
int ndims_pvalue;
ng_size_t dsizes_pvalue[NCL_MAX_DIMENSIONS];
NclBasicDataTypes type_pname, type_pvalue;
/*
* Retrieve argument #1
*/
pname = (NrmQuark *) NclGetArgValue(
0,
2,
&ndims_pname,
dsizes_pname,
NULL,
NULL,
&type_pname,
DONT_CARE);
/*
* Check number of dimensions for argument #1.
*/
if(ndims_pname != 1) {
NhlPError(NhlFATAL, NhlEUNKNOWN,
"dssetp: Argument #1 has the wrong number of dimensions.");
return(NhlFATAL);
}
arg1 = NrmQuarkToString(*pname);
/*
* Check to see if the parameter name is valid.
*/
numpi = sizeof(params_i)/sizeof(void *);
numpf = sizeof(params_f)/sizeof(void *);
numpc = sizeof(params_c)/sizeof(void *);
for (i = 0; i < numpi; i++) {
if (!strncmp(arg1, params_i[i], strlen(params_i[i]))) {
goto OK_NAME;
}
}
for (i = 0; i < numpf; i++) {
if (!strncmp(arg1, params_f[i], strlen(params_f[i]))) {
goto OK_NAME;
}
}
for (i = 0; i < numpc; i++) {
if (!strncmp(arg1, params_c[i], strlen(params_c[i]))) {
goto OK_NAME;
}
}
NhlPError(NhlFATAL, NhlEUNKNOWN, "dssetp: unrecognized parameter name");
return(NhlFATAL);
/*
* Retrieve argument #2
*/
OK_NAME: pvalue = (void *) NclGetArgValue(
1,
2,
&ndims_pvalue,
dsizes_pvalue,
NULL,
NULL,
&type_pvalue,
DONT_CARE);
/*
* Process the parameter if it has an integer value.
*/
if (type_pvalue == NCL_int) {
for (i = 0; i < numpi; i++) {
if (!strncmp(arg1, params_i[i], strlen(params_i[i]))) {
c_dsseti(arg1, *((int *) pvalue));
return(NhlNOERROR);
}
}
NhlPError(NhlFATAL, NhlEUNKNOWN, "The specified value for the parameter "
"has an invalid type");
return(NhlFATAL);
}
else if (type_pvalue == NCL_float || type_pvalue == NCL_double) {
/*
* Process the parameter if it has a float value or double value.
*/
for (i = 0; i < numpf; i++) {
if (!strncmp(arg1, params_f[i], strlen(params_f[i]))) {
if (type_pvalue == NCL_float) {
c_dssetr(arg1, *((float *) pvalue));
return(NhlNOERROR);
}
else if (type_pvalue == NCL_double) {
c_dssetrd(arg1, *((double *) pvalue));
return(NhlNOERROR);
}
}
}
NhlPError(NhlFATAL, NhlEUNKNOWN, "The specified value for the parameter "
"has an invalid type");
return(NhlFATAL);
}
else if (type_pvalue == NCL_string) {
/*
* Process the parameter if it has a string value.
*/
for (i = 0; i < numpc; i++) {
if (!strncmp(arg1, params_c[i], strlen(params_c[i]))) {
cval = NrmQuarkToString( *((NrmQuark *) pvalue));
c_dssetc(arg1, cval);
return(NhlNOERROR);
}
}
NhlPError(NhlFATAL, NhlEUNKNOWN, "The specified value for the parameter "
"has an invalid type");
return(NhlFATAL);
}
return(NhlNOERROR);
}
NhlErrorTypes dsgetp_W(void)
{
/*
* Get values for dsgrid parameters.
*/
char *arg1, *cval;
int numpi, numpf, numpc, i;
NrmQuark *qvalue;
/*
* List the integer and float parameter names. To add new ones,
* all that needs to be done is add the names to this list.
*/
char *params_i[] = {"shd", "SHD"};
char *params_f[] = {"dmv", "dmx", "exp", "DMV", "DMX", "EXP"};
char *params_c[] = {"erf", "ERF"};
/*
* Input array variable
*/
NrmQuark *pname;
int ndims_pname;
ng_size_t dsizes_pname[NCL_MAX_DIMENSIONS];
NclBasicDataTypes type_pname;
float *fval;
int *ival;
ng_size_t ret_size = 1;
/*
* Retrieve argument #1
*/
pname = (NrmQuark *) NclGetArgValue(
0,
1,
&ndims_pname,
dsizes_pname,
NULL,
NULL,
&type_pname,
DONT_CARE);
/*
* Check number of dimensions for argument #1.
*/
if(ndims_pname != 1) {
NhlPError(NhlFATAL, NhlEUNKNOWN,
"dsgetp: Argument #1 has the wrong number of dimensions.");
return(NhlFATAL);
}
arg1 = NrmQuarkToString(*pname);
/*
* Check to see if the parameter name is valid.
*/
numpi = sizeof(params_i)/sizeof(void *);
numpf = sizeof(params_f)/sizeof(void *);
numpc = sizeof(params_c)/sizeof(void *);
for (i = 0; i < numpi; i++) {
if (!strncmp(arg1, params_i[i], strlen(params_i[i]))) {
goto OK_NAME;
}
}
for (i = 0; i < numpf; i++) {
if (!strncmp(arg1, params_f[i], strlen(params_f[i]))) {
goto OK_NAME;
}
}
for (i = 0; i < numpc; i++) {
if (!strncmp(arg1, params_c[i], strlen(params_c[i]))) {
goto OK_NAME;
}
}
NhlPError(NhlFATAL, NhlEUNKNOWN, "dssetp: unrecognized parameter name");
return(NhlFATAL);
/*
* Process the parameter if it has an integer value.
*/
OK_NAME: for (i = 0; i < numpi; i++) {
if (!strncmp(arg1, params_i[i], strlen(params_i[i]))) {
ival = (int *) calloc(1,sizeof(int));
c_dsgeti(arg1, ival);
return(NclReturnValue( (void *) ival, 1, &ret_size, NULL, NCL_int, 0));
}
}
/*
* Process the parameter if it has a float value.
*/
for (i = 0; i < numpf; i++) {
if (!strncmp(arg1, params_f[i], strlen(params_f[i]))) {
fval = (float *) calloc(1,sizeof(float));
c_dsgetr(arg1, fval);
return(NclReturnValue((void *) fval, 1, &ret_size, NULL, NCL_float, 0));
}
}
/*
* Process the parameter if it has a string value.
*/
for (i = 0; i < numpc; i++) {
if (!strncmp(arg1, params_c[i], strlen(params_c[i]))) {
cval = (char *) calloc(100,sizeof(char));
if (cval == NULL) {
NhlPError(NhlFATAL, NhlEUNKNOWN,
"dsgetp: unable to allocate memory for return string");
return(NhlFATAL);
}
c_dsgetc(arg1, cval);
qvalue = (NrmQuark *) calloc(1,sizeof(NrmQuark));
*qvalue = NrmStringToQuark(cval);
return(NclReturnValue((void *) qvalue, 1, &ret_size, NULL,NCL_string, 1));
}
}
return(NhlNOERROR);
}
NhlErrorTypes dspnt2s_W( void )
{
float *x;
ng_size_t dsizes_x[1];
int has_missing_x;
float *y;
ng_size_t dsizes_y[1];
int has_missing_y;
float *z;
int ndims_z;
ng_size_t dsizes_z[NCL_MAX_DIMENSIONS];
int has_missing_z;
float *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
float *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
float *zo;
int ndims_zo;
ng_size_t dsizes_zo[NCL_MAX_DIMENSIONS];
NclScalar missing_x, missing_y, missing_z, missing_xo, missing_yo;
ng_size_t i, size_leftmost, size_z, index_z, index_zo;
ng_size_t npts, nptso;
int inpts, inptso, ier;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (float*)NclGetArgValue(
0,
6,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (float*)NclGetArgValue(
1,
6,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
z = (float*)NclGetArgValue(
2,
6,
&ndims_z,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
xo = (float*)NclGetArgValue(
3,
6,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (float*)NclGetArgValue(
4,
6,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
zo = (float*)NclGetArgValue(
5,
6,
&ndims_zo,
dsizes_zo,
NULL,
NULL,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_x[0] > INT_MAX) || (dsizes_xo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2s: the length of x and/or xo is greater than INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
nptso = dsizes_xo[0];
inpts = (int) npts;
inptso = (int) nptso;
/*
* Make sure z and zo have the same number of dimensions.
*/
if(ndims_z != ndims_zo) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2s: z and zo must have the same number of dimensions");
return(NhlFATAL);
}
/*
* Calculate leftmost dimensions of z/zo, and make sure they are
* the same.
*/
size_leftmost = 1;
for( i = 0; i < ndims_z-1; i++ ) {
if(dsizes_z[i] != dsizes_zo[i]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2s: z and zo must have the same leftmost dimension sizes");
return(NhlFATAL);
}
size_leftmost *= dsizes_z[i];
}
size_z = size_leftmost * npts;
/*
* Check dimension sizes.
*/
if(dsizes_y[0] == npts && dsizes_z[ndims_z-1] == npts &&
dsizes_yo[0] == nptso && dsizes_zo[ndims_zo-1] == nptso) {
/*
* Check for missing values.
*/
if(contains_missing_float(x,npts,has_missing_x,missing_x.floatval) ||
contains_missing_float(y,npts,has_missing_y,missing_y.floatval) ||
contains_missing_float(z,size_z,has_missing_z,missing_z.floatval) ||
contains_missing_float(xo,nptso,has_missing_xo,missing_xo.floatval) ||
contains_missing_float(yo,nptso,has_missing_yo,missing_yo.floatval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2s: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* The following section loops through the leftmost dimensions and calls
* the c_dspnt2s function.
*/
index_z = index_zo = 0;
for( i = 0; i < size_leftmost; i++ ) {
c_dspnt2s(inpts,x,y,&z[index_z],inptso,xo,yo,&zo[index_zo],&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2s: ier = %d", ier);
return(NhlFATAL);
}
index_z += npts;
index_zo += nptso;
}
}
else {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2s: the dimension sizes of parameters x and y, and xo and yo must be identical");
return(NhlFATAL);
}
return(NhlNOERROR);
}
NhlErrorTypes dspnt2d_W( void )
{
double *x;
ng_size_t dsizes_x[1];
int has_missing_x;
double *y;
ng_size_t dsizes_y[1];
int has_missing_y;
double *z;
int ndims_z;
ng_size_t dsizes_z[NCL_MAX_DIMENSIONS];
int has_missing_z;
double *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
double *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
double *zo;
int ndims_zo;
ng_size_t dsizes_zo[NCL_MAX_DIMENSIONS];
NclScalar missing_x, missing_y, missing_z, missing_xo, missing_yo;
int ier = 0;
ng_size_t index_z, index_zo;
ng_size_t i, size_leftmost, size_z;
ng_size_t npts, nptso;
int inpts, inptso;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (double*)NclGetArgValue(
0,
6,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (double*)NclGetArgValue(
1,
6,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
z = (double*)NclGetArgValue(
2,
6,
&ndims_z,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
xo = (double*)NclGetArgValue(
3,
6,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (double*)NclGetArgValue(
4,
6,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
zo = (double*)NclGetArgValue(
5,
6,
&ndims_zo,
dsizes_zo,
NULL,
NULL,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_x[0] > INT_MAX) || (dsizes_xo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2d: the length of x and/or xo is greater than INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
nptso = dsizes_xo[0];
inpts = (int) npts;
inptso = (int) nptso;
/*
* Make sure z and zo have the same number of dimensions.
*/
if(ndims_z != ndims_zo) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2d: z and zo must have the same number of dimensions");
return(NhlFATAL);
}
/*
* Calculate leftmost dimensions of z/zo, and make sure they are
* the same.
*/
size_leftmost = 1;
for( i = 0; i < ndims_z-1; i++ ) {
if(dsizes_z[i] != dsizes_zo[i]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2s: z and zo must have the same leftmost dimension sizes");
return(NhlFATAL);
}
size_leftmost *= dsizes_z[i];
}
size_z = size_leftmost * npts;
/*
* Check dimension sizes.
*/
if(dsizes_y[0] == npts && dsizes_z[ndims_z-1] == npts &&
dsizes_yo[0] == nptso && dsizes_zo[ndims_zo-1] == nptso) {
/*
* Check for missing values.
*/
if(contains_missing(x,npts,has_missing_x,missing_x.doubleval) ||
contains_missing(y,npts,has_missing_y,missing_y.doubleval) ||
contains_missing(z,size_z,has_missing_z,missing_z.doubleval) ||
contains_missing(xo,nptso,has_missing_xo,missing_xo.doubleval) ||
contains_missing(yo,nptso,has_missing_yo,missing_yo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2d: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* The following section loops through the leftmost dimensions and calls
* the c_dspnt2d function.
*/
index_z = index_zo = 0;
for( i = 0; i < size_leftmost; i++ ) {
c_dspnt2d(inpts,x,y,&z[index_z],inptso,xo,yo,&zo[index_zo],&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2d: ier = %d", ier);
return(NhlFATAL);
}
index_z += npts;
index_zo += nptso;
}
}
else {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2d: the dimension sizes of parameters x, y, and z, and xo and yo must be identical");
return(NhlFATAL);
}
return(NhlNOERROR);
}
NhlErrorTypes dspnt2_W( void )
{
void *x, *y, *z;
ng_size_t dsizes_x[1];
int has_missing_x;
ng_size_t dsizes_y[1];
int has_missing_y;
int ndims_z;
ng_size_t dsizes_z[NCL_MAX_DIMENSIONS];
int has_missing_z;
void *xo, *yo, *zo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
ng_size_t *dsizes_zo;
NclScalar missing_x, missing_y, missing_z, missing_xo, missing_yo;
NclScalar missing_dx, missing_dy, missing_dz, missing_dxo, missing_dyo;
NclBasicDataTypes type_x, type_y, type_z, type_xo, type_yo, type_zo;
/*
* Temporary arrays.
*/
double *tmp_x, *tmp_y, *tmp_xo, *tmp_yo;
double *tmp_z = NULL;
double *tmp_zo = NULL;
ng_size_t i, npts, nptso, size_z, size_zo, size_leftmost;
int inpts, inptso, ier = 0, ret;
ng_size_t index_z, index_zo;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value.
*/
x = (void*)NclGetArgValue(
0,
5,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
5,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
z = (void*)NclGetArgValue(
2,
5,
&ndims_z,
dsizes_z,
&missing_z,
&has_missing_z,
&type_z,
DONT_CARE);
xo = (void*)NclGetArgValue(
3,
5,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
&type_xo,
DONT_CARE);
yo = (void*)NclGetArgValue(
4,
5,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
&type_yo,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_x[0] > INT_MAX) || (dsizes_xo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: the length of x and/or xo is greater than INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
nptso = dsizes_xo[0];
inpts = (int) npts;
inptso = (int) nptso;
/*
* Check dimensions.
*/
if(dsizes_y[0] != npts || dsizes_z[ndims_z-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: the rightmost dimension of z must be the same as the dimension of x and y");
return(NhlFATAL);
}
if(dsizes_yo[0] != nptso) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: xo and yo must be the same length");
return(NhlFATAL);
}
/*
* Calculate size of z and zo.
*/
size_leftmost = 1;
for( i = 0; i < ndims_z-1; i++ ) size_leftmost *= dsizes_z[i];
size_z = size_leftmost * npts;
size_zo = size_leftmost * nptso;
/*
* Coerce missing values.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
coerce_missing(type_z,has_missing_z,&missing_z,&missing_dz,NULL);
coerce_missing(type_xo,has_missing_xo,&missing_xo,&missing_dxo,NULL);
coerce_missing(type_yo,has_missing_yo,&missing_yo,&missing_dyo,NULL);
/*
* Allocate space for temporary z array. The temporary array
* tmp_z is just big enough to hold a one-dimensional subsection of the
* z array. We only need to allocate space for it if the
* input is not already double. Otherwise, we just have it point
* to the appropriate locations in z later.
*/
if(type_z != NCL_double) {
tmp_z = (double*)calloc(npts,sizeof(double));
if(tmp_z == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: Unable to allocate memory for coercing z array to double precision");
return(NhlFATAL);
}
}
/*
* Coerce other arrays to double, if necessary.
*/
tmp_x = coerce_input_double(x,type_x,npts,has_missing_x,&missing_x,
&missing_dx);
tmp_y = coerce_input_double(y,type_y,npts,has_missing_y,&missing_y,
&missing_dy);
tmp_xo = coerce_input_double(xo,type_xo,nptso,has_missing_xo,&missing_xo,
&missing_dxo);
tmp_yo = coerce_input_double(yo,type_yo,nptso,has_missing_yo,&missing_yo,
&missing_dyo);
if(tmp_x == NULL || tmp_y == NULL || tmp_xo == NULL || tmp_yo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: Unable to allocate memory for coercing input arrays to double precision");
return(NhlFATAL);
}
/*
* Check for missing values.
*/
if(contains_missing(tmp_x,npts,has_missing_x,missing_dx.doubleval) ||
contains_missing(tmp_y,npts,has_missing_y,missing_dy.doubleval) ||
contains_missing(tmp_xo,nptso,has_missing_xo,missing_dxo.doubleval) ||
contains_missing(tmp_yo,nptso,has_missing_yo,missing_dyo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Allocate space for temporary output array. We only need to allocate
* space for it if the input is not already double. Otherwise, we just
* have it point to the appropriate location in zo.
*/
if( type_x != NCL_double && type_y != NCL_double && type_z != NCL_double &&
type_xo != NCL_double && type_yo != NCL_double) {
type_zo = NCL_float;
zo = (void*)calloc(size_zo,sizeof(float));
tmp_zo = (double*)calloc(nptso,sizeof(double));
if(tmp_zo == NULL || zo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: Unable to allocate memory for coercing zo array to double precision");
return(NhlFATAL);
}
}
else {
type_zo = NCL_double;
zo = (void*)calloc(size_zo,sizeof(double));
if(zo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: Unable to allocate memory for coercing zo array to double precision");
return(NhlFATAL);
}
}
/*
* Allocate array to hold dimension sizes for zo, and fill it up.
*/
dsizes_zo = (ng_size_t *)calloc(ndims_z, sizeof(ng_size_t));
if(dsizes_zo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: Unable to allocate memory dimension size array");
return(NhlFATAL);
}
for( i = 0; i <= ndims_z-2; i++ ) dsizes_zo[i] = dsizes_z[i];
dsizes_zo[ndims_z-1] = nptso;
/*
* The following section calls the c_dspnt2d function.
* Loop through the left most dimensions and call c_dspnt2d for
* each one.
*/
index_z = index_zo = 0;
for(i = 0; i < size_leftmost; i++) {
if(type_z != NCL_double) {
/*
* Coerce npts subsection of z (tmp_z) to double.
*/
coerce_subset_input_double(z,tmp_z,index_z,type_z,npts,has_missing_z,
&missing_z,&missing_dz);
}
else {
/*
* Point tmp_z to appropriate location in z.
*/
tmp_z = &((double*)z)[index_z];
}
if(type_zo == NCL_double) {
/*
* Point tmp_zo to appropriate location in zo.
*/
tmp_zo = &((double*)zo)[index_zo];
}
/*
* Check for missing values.
*/
if(contains_missing(tmp_z,npts,has_missing_z,missing_dz.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Call c_dspnt2d.
*/
c_dspnt2d(inpts,tmp_x,tmp_y,tmp_z,inptso,tmp_xo,tmp_yo,tmp_zo,&ier);
/*
* Check for errors.
*/
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt2: ier = %d", ier);
return(NhlFATAL);
}
/*
* Coerce output back to float if necessary.
*/
if(type_zo != NCL_double) {
coerce_output_float_only(zo,tmp_zo,inptso,index_zo);
}
index_z += npts;
index_zo += nptso;
}
/*
* Free arrays
*/
if(type_x != NCL_double) NclFree(tmp_x);
if(type_y != NCL_double) NclFree(tmp_y);
if(type_z != NCL_double) NclFree(tmp_z);
if(type_xo != NCL_double) NclFree(tmp_xo);
if(type_yo != NCL_double) NclFree(tmp_yo);
if(type_zo != NCL_double) NclFree(tmp_zo);
ret = NclReturnValue(zo,ndims_z,dsizes_zo,NULL,type_zo,0);
NclFree(dsizes_zo);
return(ret);
}
NhlErrorTypes dspnt3s_W( void )
{
float *x;
ng_size_t dsizes_x[1];
int has_missing_x;
float *y;
ng_size_t dsizes_y[1];
int has_missing_y;
float *z;
ng_size_t dsizes_z[1];
int has_missing_z;
float *u;
int ndims_u;
ng_size_t dsizes_u[NCL_MAX_DIMENSIONS];
int has_missing_u;
float *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
float *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
float *zo;
ng_size_t dsizes_zo[1];
int has_missing_zo;
float *uo;
int ndims_uo;
ng_size_t dsizes_uo[NCL_MAX_DIMENSIONS];
NclScalar missing_x, missing_y, missing_z, missing_u;
NclScalar missing_xo, missing_yo, missing_zo;
ng_size_t i, size_leftmost, size_u;
ng_size_t npts, nptso, index_u, index_uo;
int inpts, inptso, ier = 0;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (float*)NclGetArgValue(
0,
8,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (float*)NclGetArgValue(
1,
8,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
z = (float*)NclGetArgValue(
2,
8,
NULL,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
u = (float*)NclGetArgValue(
3,
8,
&ndims_u,
dsizes_u,
&missing_u,
&has_missing_u,
NULL,
DONT_CARE);
xo = (float*)NclGetArgValue(
4,
8,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (float*)NclGetArgValue(
5,
8,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
zo = (float*)NclGetArgValue(
6,
8,
NULL,
dsizes_zo,
&missing_zo,
&has_missing_zo,
NULL,
DONT_CARE);
uo = (float*)NclGetArgValue(
7,
8,
&ndims_uo,
dsizes_uo,
NULL,
NULL,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_x[0] > INT_MAX) || (dsizes_xo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3s: the length of x and/or xo is greater than INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
nptso = dsizes_xo[0];
inpts = (int) npts;
inptso = (int) nptso;
/*
* Make sure u and uo have the same number of dimensions.
*/
if(ndims_u != ndims_uo) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3s: u and uo must have the same number of dimensions");
return(NhlFATAL);
}
/*
* Calculate leftmost dimensions of u/uo, and make sure they are
* the same.
*/
size_leftmost = 1;
for( i = 0; i < ndims_u-1; i++ ) {
if(dsizes_u[i] != dsizes_uo[i]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3s: u and uo must have the same leftmost dimension sizes");
return(NhlFATAL);
}
size_leftmost *= dsizes_u[i];
}
size_u = size_leftmost * npts;
/*
* Check dimension sizes.
*/
if(dsizes_y[0] == npts && dsizes_z[0] == npts &&
dsizes_yo[0] == nptso && dsizes_zo[0] == nptso &&
dsizes_u[ndims_u-1] == npts && dsizes_uo[ndims_uo-1] == nptso) {
/*
* Check for missing values.
*/
if(contains_missing_float(x,npts,has_missing_x,missing_x.floatval) ||
contains_missing_float(y,npts,has_missing_y,missing_y.floatval) ||
contains_missing_float(z,npts,has_missing_z,missing_z.floatval) ||
contains_missing_float(u,size_u,has_missing_u,missing_u.floatval) ||
contains_missing_float(xo,nptso,has_missing_xo,missing_xo.floatval) ||
contains_missing_float(yo,nptso,has_missing_yo,missing_yo.floatval) ||
contains_missing_float(zo,nptso,has_missing_zo,missing_zo.floatval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3s: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* The following section calls the c_dspnt3s function.
*/
index_u = index_uo = 0;
for( i = 0; i < size_leftmost; i++ ) {
c_dspnt3s(inpts,x,y,z,&u[index_u],inptso,xo,yo,zo,&uo[index_uo],&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3s: ier = %d", ier);
return(NhlFATAL);
}
index_u += npts;
index_uo += nptso;
}
}
else {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3s: the dimension sizes of parameters x, y, and z, and xo and yo must be identical");
return(NhlFATAL);
}
return(NhlNOERROR);
}
NhlErrorTypes dspnt3d_W( void )
{
double *x;
ng_size_t dsizes_x[1];
int has_missing_x;
double *y;
ng_size_t dsizes_y[1];
int has_missing_y;
double *z;
ng_size_t dsizes_z[1];
int has_missing_z;
double *u;
int ndims_u;
ng_size_t dsizes_u[NCL_MAX_DIMENSIONS];
int has_missing_u;
double *xo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
double *yo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
double *zo;
ng_size_t dsizes_zo[1];
int has_missing_zo;
double *uo;
int ndims_uo;
ng_size_t dsizes_uo[NCL_MAX_DIMENSIONS];
NclScalar missing_x, missing_y, missing_z, missing_u;
NclScalar missing_xo, missing_yo, missing_zo;
int ier = 0;
ng_size_t index_u, index_uo;
ng_size_t i, npts, nptso, size_leftmost, size_u;
int inpts, inptso;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value. In this example
* the type parameter is set to NULL because the function
* is later registered to only accept floating point numbers.
*/
x = (double*)NclGetArgValue(
0,
8,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
NULL,
DONT_CARE);
y = (double*)NclGetArgValue(
1,
8,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
NULL,
DONT_CARE);
z = (double*)NclGetArgValue(
2,
8,
NULL,
dsizes_z,
&missing_z,
&has_missing_z,
NULL,
DONT_CARE);
u = (double*)NclGetArgValue(
3,
8,
&ndims_u,
dsizes_u,
&missing_u,
&has_missing_u,
NULL,
DONT_CARE);
xo = (double*)NclGetArgValue(
4,
8,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
NULL,
DONT_CARE);
yo = (double*)NclGetArgValue(
5,
8,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
NULL,
DONT_CARE);
zo = (double*)NclGetArgValue(
6,
8,
NULL,
dsizes_zo,
&missing_zo,
&has_missing_zo,
NULL,
DONT_CARE);
uo = (double*)NclGetArgValue(
7,
8,
&ndims_uo,
dsizes_uo,
NULL,
NULL,
NULL,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_x[0] > INT_MAX) || (dsizes_xo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3d: the length of x and/or xo is greater than INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
nptso = dsizes_xo[0];
inpts = (int) npts;
inptso = (int) nptso;
/*
* Make sure u and uo have the same number of dimensions.
*/
if(ndims_u != ndims_uo) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3d: u and uo must have the same number of dimensions");
return(NhlFATAL);
}
/*
* Calculate leftmost dimensions of u/uo, and make sure they are
* the same.
*/
size_leftmost = 1;
for( i = 0; i < ndims_u-1; i++ ) {
if(dsizes_u[i] != dsizes_uo[i]) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3d: u and uo must have the same leftmost dimension sizes");
return(NhlFATAL);
}
size_leftmost *= dsizes_u[i];
}
size_u = size_leftmost * npts;
/*
* Check dimension sizes.
*/
if(dsizes_y[0] == npts && dsizes_z[0] == npts &&
dsizes_yo[0] == nptso && dsizes_zo[0] == nptso &&
dsizes_u[ndims_u-1] == npts && dsizes_uo[ndims_uo-1] == nptso) {
/*
* Check for missing values.
*/
if(contains_missing(x,npts,has_missing_x,missing_x.doubleval) ||
contains_missing(y,npts,has_missing_y,missing_y.doubleval) ||
contains_missing(z,npts,has_missing_z,missing_z.doubleval) ||
contains_missing(u,size_u,has_missing_u,missing_u.doubleval) ||
contains_missing(xo,nptso,has_missing_xo,missing_xo.doubleval) ||
contains_missing(yo,nptso,has_missing_yo,missing_yo.doubleval) ||
contains_missing(zo,nptso,has_missing_zo,missing_zo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3d: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* The following section calls the c_dspnt3d function.
*/
index_u = index_uo = 0;
for( i = 0; i < size_leftmost; i++ ) {
c_dspnt3d(inpts,x,y,z,&u[index_u],inptso,xo,yo,zo,&uo[index_uo],&ier);
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3d: ier = %d", ier);
return(NhlFATAL);
}
index_u += npts;
index_uo += nptso;
}
}
else {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3d: the dimension sizes of parameters x, y, and z, and xo and yo must be identical");
return(NhlFATAL);
}
return(NhlNOERROR);
}
NhlErrorTypes dspnt3_W( void )
{
void *x, *y, *z, *u;
ng_size_t dsizes_x[1];
int has_missing_x;
ng_size_t dsizes_y[1];
int has_missing_y;
ng_size_t dsizes_z[1];
int has_missing_z;
int ndims_u;
ng_size_t dsizes_u[NCL_MAX_DIMENSIONS];
int has_missing_u;
void *xo, *yo, *zo, *uo;
ng_size_t dsizes_xo[1];
int has_missing_xo;
ng_size_t dsizes_yo[1];
int has_missing_yo;
ng_size_t dsizes_zo[1];
int has_missing_zo;
ng_size_t *dsizes_uo;
NclScalar missing_x, missing_y, missing_z, missing_u;
NclScalar missing_xo, missing_yo, missing_zo;
NclScalar missing_dx, missing_dy, missing_dz, missing_du;
NclScalar missing_dxo, missing_dyo, missing_dzo;
NclBasicDataTypes type_x, type_y, type_z, type_u;
NclBasicDataTypes type_xo, type_yo, type_zo, type_uo;
/*
* Temporary arrays.
*/
double *tmp_x, *tmp_y, *tmp_z, *tmp_xo, *tmp_yo, *tmp_zo;
double *tmp_u = NULL;
double *tmp_uo = NULL;
ng_size_t i, npts, nptso, size_u, size_uo, size_leftmost;
int inpts, inptso;
int ier = 0, ret;
ng_size_t index_u, index_uo;
/*
* Retrieve parameters
*
* Note any of the pointer parameters can be set to NULL, which
* implies you don't care about its value.
*/
x = (void*)NclGetArgValue(
0,
7,
NULL,
dsizes_x,
&missing_x,
&has_missing_x,
&type_x,
DONT_CARE);
y = (void*)NclGetArgValue(
1,
7,
NULL,
dsizes_y,
&missing_y,
&has_missing_y,
&type_y,
DONT_CARE);
z = (void*)NclGetArgValue(
2,
7,
NULL,
dsizes_z,
&missing_z,
&has_missing_z,
&type_z,
DONT_CARE);
u = (void*)NclGetArgValue(
3,
7,
&ndims_u,
dsizes_u,
&missing_u,
&has_missing_u,
&type_u,
DONT_CARE);
xo = (void*)NclGetArgValue(
4,
7,
NULL,
dsizes_xo,
&missing_xo,
&has_missing_xo,
&type_xo,
DONT_CARE);
yo = (void*)NclGetArgValue(
5,
7,
NULL,
dsizes_yo,
&missing_yo,
&has_missing_yo,
&type_yo,
DONT_CARE);
zo = (void*)NclGetArgValue(
6,
7,
NULL,
dsizes_zo,
&missing_zo,
&has_missing_zo,
&type_zo,
DONT_CARE);
/*
* Test the dimension sizes.
*/
if( (dsizes_x[0] > INT_MAX) || (dsizes_xo[0] > INT_MAX)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: the length of x and/or xo is greater than INT_MAX");
return(NhlFATAL);
}
npts = dsizes_x[0];
nptso = dsizes_xo[0];
inpts = (int) npts;
inptso = (int) nptso;
/*
* Check dimensions.
*/
if(dsizes_y[0] != npts || dsizes_z[0] != npts || dsizes_u[ndims_u-1] != npts) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: the rightmost dimension of u must be the same as the dimension of x, y, and z");
return(NhlFATAL);
}
if(dsizes_yo[0] != nptso || dsizes_zo[0] != nptso) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: xo, yo, and zo must be the same length");
return(NhlFATAL);
}
/*
* Calculate size of u and uo.
*/
size_leftmost = 1;
for( i = 0; i < ndims_u-1; i++ ) size_leftmost *= dsizes_u[i];
size_u = size_leftmost * npts;
size_uo = size_leftmost * nptso;
/*
* Coerce missing values.
*/
coerce_missing(type_x,has_missing_x,&missing_x,&missing_dx,NULL);
coerce_missing(type_y,has_missing_y,&missing_y,&missing_dy,NULL);
coerce_missing(type_z,has_missing_z,&missing_z,&missing_dz,NULL);
coerce_missing(type_u,has_missing_u,&missing_u,&missing_du,NULL);
coerce_missing(type_xo,has_missing_xo,&missing_xo,&missing_dxo,NULL);
coerce_missing(type_yo,has_missing_yo,&missing_yo,&missing_dyo,NULL);
coerce_missing(type_zo,has_missing_zo,&missing_zo,&missing_dzo,NULL);
/*
* Allocate space for temporary u array. The temporary array
* tmp_u is just big enough to hold a one-dimensional subsection of the
* u array. We only need to allocate space for it if the
* input is not already double. Otherwise, we just have it point
* to the appropriate locations in u later.
*/
if(type_u != NCL_double) {
tmp_u = (double*)calloc(npts,sizeof(double));
if(tmp_u == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: Unable to allocate memory for coercing u array to double precision");
return(NhlFATAL);
}
}
/*
* Coerce other arrays to double, if necessary.
*/
tmp_x = coerce_input_double(x,type_x,npts,has_missing_x,&missing_x,
&missing_dx);
tmp_y = coerce_input_double(y,type_y,npts,has_missing_y,&missing_y,
&missing_dy);
tmp_z = coerce_input_double(z,type_z,npts,has_missing_z,&missing_z,
&missing_dz);
tmp_xo = coerce_input_double(xo,type_xo,nptso,has_missing_xo,&missing_xo,
&missing_dxo);
tmp_yo = coerce_input_double(yo,type_yo,nptso,has_missing_yo,&missing_yo,
&missing_dyo);
tmp_zo = coerce_input_double(zo,type_zo,nptso,has_missing_zo,&missing_zo,
&missing_dzo);
if(tmp_x == NULL || tmp_y == NULL || tmp_z == NULL ||
tmp_xo == NULL || tmp_yo == NULL || tmp_zo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: Unable to allocate memory for coercing input arrays to double precision");
return(NhlFATAL);
}
/*
* Check for missing values.
*/
if(contains_missing(tmp_x,npts,has_missing_x,missing_dx.doubleval) ||
contains_missing(tmp_y,npts,has_missing_y,missing_dy.doubleval) ||
contains_missing(tmp_z,npts,has_missing_z,missing_dz.doubleval) ||
contains_missing(tmp_xo,nptso,has_missing_xo,missing_dxo.doubleval) ||
contains_missing(tmp_yo,nptso,has_missing_yo,missing_dyo.doubleval) ||
contains_missing(tmp_zo,nptso,has_missing_zo,missing_dzo.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Allocate space for temporary output array. We only need to allocate
* space for it if the input is not already double. Otherwise, we just
* have it point to the appropriate location in zo.
*/
if(type_x != NCL_double && type_y != NCL_double &&
type_z != NCL_double && type_u != NCL_double &&
type_xo != NCL_double && type_yo != NCL_double && type_zo !=NCL_double) {
type_uo = NCL_float;
uo = (void*)calloc(size_uo,sizeof(float));
tmp_uo = (double*)calloc(nptso,sizeof(double));
if(tmp_uo == NULL || uo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: Unable to allocate memory for coercing uo array to double precision");
return(NhlFATAL);
}
}
else {
type_uo = NCL_double;
uo = (void*)calloc(size_uo,sizeof(double));
if(uo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: Unable to allocate memory for coercing uo array to double precision");
return(NhlFATAL);
}
}
/*
* Allocate array to hold dimension sizes for uo, and fill it up.
*/
dsizes_uo = (ng_size_t *)calloc(ndims_u, sizeof(ng_size_t));
if(dsizes_uo == NULL) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: Unable to allocate memory dimension size array");
return(NhlFATAL);
}
for( i = 0; i <= ndims_u-2; i++ ) dsizes_uo[i] = dsizes_u[i];
dsizes_uo[ndims_u-1] = nptso;
/*
* The following section calls the c_dspnt3d function.
* Loop through the left most dimensions and call c_dspnt3d for
* each one.
*/
index_u = index_uo = 0;
for(i = 0; i < size_leftmost; i++) {
if(type_u != NCL_double) {
/*
* Coerce npts subsection of u (tmp_u) to double.
*/
coerce_subset_input_double(u,tmp_u,index_u,type_u,npts,has_missing_u,
&missing_u,&missing_du);
}
else {
/*
* Point tmp_u to appropriate location in u.
*/
tmp_u = &((double*)u)[index_u];
}
if(type_uo == NCL_double) {
/*
* Point tmp_uo to appropriate location in uo.
*/
tmp_uo = &((double*)uo)[index_uo];
}
/*
* Check for missing values.
*/
if(contains_missing(tmp_u,npts,has_missing_u,missing_du.doubleval)) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: the input arrays cannot contain any missing values" );
return(NhlFATAL);
}
/*
* Call c_dspnt3d.
*/
c_dspnt3d(inpts,tmp_x,tmp_y,tmp_z,tmp_u,inptso,tmp_xo,tmp_yo,tmp_zo,
tmp_uo,&ier);
/*
* Check for errors.
*/
if(ier) {
NhlPError(NhlFATAL,NhlEUNKNOWN,"dspnt3: ier = %d", ier);
return(NhlFATAL);
}
/*
* Coerce output back to float if necessary.
*/
if(type_uo != NCL_double) {
coerce_output_float_only(uo,tmp_uo,nptso,index_uo);
}
index_u += npts;
index_uo += nptso;
}
/*
* Free arrays
*/
if(type_x != NCL_double) NclFree(tmp_x);
if(type_y != NCL_double) NclFree(tmp_y);
if(type_z != NCL_double) NclFree(tmp_z);
if(type_u != NCL_double) NclFree(tmp_u);
if(type_xo != NCL_double) NclFree(tmp_xo);
if(type_yo != NCL_double) NclFree(tmp_yo);
if(type_zo != NCL_double) NclFree(tmp_zo);
if(type_uo != NCL_double) NclFree(tmp_uo);
ret = NclReturnValue(uo,ndims_u,dsizes_uo,NULL,type_uo,0);
NclFree(dsizes_uo);
return(ret);
}
| 2.28125 | 2 |
2024-11-18T19:53:09.024953+00:00
| 2023-08-31T14:32:05 |
4bb06a1c3c4b09c6423daf9cf6998f232a9b6c15
|
{
"blob_id": "4bb06a1c3c4b09c6423daf9cf6998f232a9b6c15",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T14:32:05",
"content_id": "4bc7ef1acfbaa0df0ca227d5f3f45aff864d0094",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "75d7f619e3caf4e22790e24f66691de542a925b6",
"extension": "c",
"filename": "example3.c",
"fork_events_count": 30,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 169997882,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 369,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/C/c-take-user-inputs-with-spaces/example3.c",
"provenance": "stackv2-0061.json.gz:5527",
"repo_name": "codevscolor/codevscolor",
"revision_date": "2023-08-31T14:32:05",
"revision_id": "c061d289faefb20618a9b3d339de3aecec64a253",
"snapshot_id": "c2e0c8a30acd439ec30ad1d2e8a5a1f13ba92ac0",
"src_encoding": "UTF-8",
"star_events_count": 12,
"url": "https://raw.githubusercontent.com/codevscolor/codevscolor/c061d289faefb20618a9b3d339de3aecec64a253/C/c-take-user-inputs-with-spaces/example3.c",
"visit_date": "2023-09-01T00:00:47.412477"
}
|
stackv2
|
// https://codevscolor.com/c-take-user-inputs-with-spaces
#include<stdio.h>
int main()
{
char input[30], secondInput[30];
printf("Enter a string: ");
fgets(input, 30, stdin);
printf("Enter another string: ");
fgets(secondInput, 30, stdin);
printf("First string: %s", input);
printf("Second string: %s", secondInput);
return 0;
}
| 3.40625 | 3 |
2024-11-18T19:53:10.659252+00:00
| 2017-08-24T12:55:32 |
55e5d6246741c3f9f12f8871fbe28c9cdee6956d
|
{
"blob_id": "55e5d6246741c3f9f12f8871fbe28c9cdee6956d",
"branch_name": "refs/heads/master_rhino_20170613",
"committer_date": "2017-08-24T12:55:32",
"content_id": "4cafa1a46502b4a4edebe41c30c86bb010eebb90",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3ee83e5b767c0bc4fdf7c215e37673c56bc6b6ef",
"extension": "h",
"filename": "svm_image.h",
"fork_events_count": 14,
"gha_created_at": "2016-05-04T11:20:24",
"gha_event_created_at": "2017-08-24T13:12:34",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 58046507,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14720,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/kernel/svm/svm_image.h",
"provenance": "stackv2-0061.json.gz:5784",
"repo_name": "mcneel/cycles",
"revision_date": "2017-08-24T12:55:32",
"revision_id": "0a3866af513acb771f2e30d51bf05dec69394074",
"snapshot_id": "1873e931563f763f49e26506f15e2643f8b25f1e",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/mcneel/cycles/0a3866af513acb771f2e30d51bf05dec69394074/src/kernel/svm/svm_image.h",
"visit_date": "2023-09-01T20:00:58.001153"
}
|
stackv2
|
/*
* Copyright 2011-2013 Blender Foundation
*
* 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.
*/
CCL_NAMESPACE_BEGIN
/* Float4 textures on various devices. */
#if defined(__KERNEL_CPU__)
# define TEX_NUM_FLOAT4_IMAGES TEX_NUM_FLOAT4_CPU
#elif defined(__KERNEL_CUDA__)
# if __CUDA_ARCH__ < 300
# define TEX_NUM_FLOAT4_IMAGES TEX_NUM_FLOAT4_CUDA
# else
# define TEX_NUM_FLOAT4_IMAGES TEX_NUM_FLOAT4_CUDA_KEPLER
# endif
#else
# define TEX_NUM_FLOAT4_IMAGES TEX_NUM_FLOAT4_OPENCL
#endif
ccl_device float4 svm_image_texture(KernelGlobals *kg, int id, float x, float y, uint srgb, uint use_alpha)
{
#ifdef __KERNEL_CPU__
float4 r = kernel_tex_image_interp(id, x, y);
#elif defined(__KERNEL_OPENCL__)
float4 r = kernel_tex_image_interp(kg, id, x, y);
#else
float4 r;
# if __CUDA_ARCH__ < 300
/* not particularly proud of this massive switch, what are the
* alternatives?
* - use a single big 1D texture, and do our own lookup/filtering
* - group by size and use a 3d texture, performance impact
* - group into larger texture with some padding for correct lerp
*
* also note that cuda has a textures limit (128 for Fermi, 256 for Kepler),
* and we cannot use all since we still need some for other storage */
switch(id) {
case 0: r = kernel_tex_image_interp(__tex_image_float4_000, x, y); break;
case 1: r = kernel_tex_image_interp(__tex_image_float4_001, x, y); break;
case 2: r = kernel_tex_image_interp(__tex_image_float4_002, x, y); break;
case 3: r = kernel_tex_image_interp(__tex_image_float4_003, x, y); break;
case 4: r = kernel_tex_image_interp(__tex_image_float4_004, x, y); break;
case 5: r = kernel_tex_image_interp(__tex_image_byte4_005, x, y); break;
case 6: r = kernel_tex_image_interp(__tex_image_byte4_006, x, y); break;
case 7: r = kernel_tex_image_interp(__tex_image_byte4_007, x, y); break;
case 8: r = kernel_tex_image_interp(__tex_image_byte4_008, x, y); break;
case 9: r = kernel_tex_image_interp(__tex_image_byte4_009, x, y); break;
case 10: r = kernel_tex_image_interp(__tex_image_byte4_010, x, y); break;
case 11: r = kernel_tex_image_interp(__tex_image_byte4_011, x, y); break;
case 12: r = kernel_tex_image_interp(__tex_image_byte4_012, x, y); break;
case 13: r = kernel_tex_image_interp(__tex_image_byte4_013, x, y); break;
case 14: r = kernel_tex_image_interp(__tex_image_byte4_014, x, y); break;
case 15: r = kernel_tex_image_interp(__tex_image_byte4_015, x, y); break;
case 16: r = kernel_tex_image_interp(__tex_image_byte4_016, x, y); break;
case 17: r = kernel_tex_image_interp(__tex_image_byte4_017, x, y); break;
case 18: r = kernel_tex_image_interp(__tex_image_byte4_018, x, y); break;
case 19: r = kernel_tex_image_interp(__tex_image_byte4_019, x, y); break;
case 20: r = kernel_tex_image_interp(__tex_image_byte4_020, x, y); break;
case 21: r = kernel_tex_image_interp(__tex_image_byte4_021, x, y); break;
case 22: r = kernel_tex_image_interp(__tex_image_byte4_022, x, y); break;
case 23: r = kernel_tex_image_interp(__tex_image_byte4_023, x, y); break;
case 24: r = kernel_tex_image_interp(__tex_image_byte4_024, x, y); break;
case 25: r = kernel_tex_image_interp(__tex_image_byte4_025, x, y); break;
case 26: r = kernel_tex_image_interp(__tex_image_byte4_026, x, y); break;
case 27: r = kernel_tex_image_interp(__tex_image_byte4_027, x, y); break;
case 28: r = kernel_tex_image_interp(__tex_image_byte4_028, x, y); break;
case 29: r = kernel_tex_image_interp(__tex_image_byte4_029, x, y); break;
case 30: r = kernel_tex_image_interp(__tex_image_byte4_030, x, y); break;
case 31: r = kernel_tex_image_interp(__tex_image_byte4_031, x, y); break;
case 32: r = kernel_tex_image_interp(__tex_image_byte4_032, x, y); break;
case 33: r = kernel_tex_image_interp(__tex_image_byte4_033, x, y); break;
case 34: r = kernel_tex_image_interp(__tex_image_byte4_034, x, y); break;
case 35: r = kernel_tex_image_interp(__tex_image_byte4_035, x, y); break;
case 36: r = kernel_tex_image_interp(__tex_image_byte4_036, x, y); break;
case 37: r = kernel_tex_image_interp(__tex_image_byte4_037, x, y); break;
case 38: r = kernel_tex_image_interp(__tex_image_byte4_038, x, y); break;
case 39: r = kernel_tex_image_interp(__tex_image_byte4_039, x, y); break;
case 40: r = kernel_tex_image_interp(__tex_image_byte4_040, x, y); break;
case 41: r = kernel_tex_image_interp(__tex_image_byte4_041, x, y); break;
case 42: r = kernel_tex_image_interp(__tex_image_byte4_042, x, y); break;
case 43: r = kernel_tex_image_interp(__tex_image_byte4_043, x, y); break;
case 44: r = kernel_tex_image_interp(__tex_image_byte4_044, x, y); break;
case 45: r = kernel_tex_image_interp(__tex_image_byte4_045, x, y); break;
case 46: r = kernel_tex_image_interp(__tex_image_byte4_046, x, y); break;
case 47: r = kernel_tex_image_interp(__tex_image_byte4_047, x, y); break;
case 48: r = kernel_tex_image_interp(__tex_image_byte4_048, x, y); break;
case 49: r = kernel_tex_image_interp(__tex_image_byte4_049, x, y); break;
case 50: r = kernel_tex_image_interp(__tex_image_byte4_050, x, y); break;
case 51: r = kernel_tex_image_interp(__tex_image_byte4_051, x, y); break;
case 52: r = kernel_tex_image_interp(__tex_image_byte4_052, x, y); break;
case 53: r = kernel_tex_image_interp(__tex_image_byte4_053, x, y); break;
case 54: r = kernel_tex_image_interp(__tex_image_byte4_054, x, y); break;
case 55: r = kernel_tex_image_interp(__tex_image_byte4_055, x, y); break;
case 56: r = kernel_tex_image_interp(__tex_image_byte4_056, x, y); break;
case 57: r = kernel_tex_image_interp(__tex_image_byte4_057, x, y); break;
case 58: r = kernel_tex_image_interp(__tex_image_byte4_058, x, y); break;
case 59: r = kernel_tex_image_interp(__tex_image_byte4_059, x, y); break;
case 60: r = kernel_tex_image_interp(__tex_image_byte4_060, x, y); break;
case 61: r = kernel_tex_image_interp(__tex_image_byte4_061, x, y); break;
case 62: r = kernel_tex_image_interp(__tex_image_byte4_062, x, y); break;
case 63: r = kernel_tex_image_interp(__tex_image_byte4_063, x, y); break;
case 64: r = kernel_tex_image_interp(__tex_image_byte4_064, x, y); break;
case 65: r = kernel_tex_image_interp(__tex_image_byte4_065, x, y); break;
case 66: r = kernel_tex_image_interp(__tex_image_byte4_066, x, y); break;
case 67: r = kernel_tex_image_interp(__tex_image_byte4_067, x, y); break;
case 68: r = kernel_tex_image_interp(__tex_image_byte4_068, x, y); break;
case 69: r = kernel_tex_image_interp(__tex_image_byte4_069, x, y); break;
case 70: r = kernel_tex_image_interp(__tex_image_byte4_070, x, y); break;
case 71: r = kernel_tex_image_interp(__tex_image_byte4_071, x, y); break;
case 72: r = kernel_tex_image_interp(__tex_image_byte4_072, x, y); break;
case 73: r = kernel_tex_image_interp(__tex_image_byte4_073, x, y); break;
case 74: r = kernel_tex_image_interp(__tex_image_byte4_074, x, y); break;
case 75: r = kernel_tex_image_interp(__tex_image_byte4_075, x, y); break;
case 76: r = kernel_tex_image_interp(__tex_image_byte4_076, x, y); break;
case 77: r = kernel_tex_image_interp(__tex_image_byte4_077, x, y); break;
case 78: r = kernel_tex_image_interp(__tex_image_byte4_078, x, y); break;
case 79: r = kernel_tex_image_interp(__tex_image_byte4_079, x, y); break;
case 80: r = kernel_tex_image_interp(__tex_image_byte4_080, x, y); break;
case 81: r = kernel_tex_image_interp(__tex_image_byte4_081, x, y); break;
case 82: r = kernel_tex_image_interp(__tex_image_byte4_082, x, y); break;
case 83: r = kernel_tex_image_interp(__tex_image_byte4_083, x, y); break;
case 84: r = kernel_tex_image_interp(__tex_image_byte4_084, x, y); break;
case 85: r = kernel_tex_image_interp(__tex_image_byte4_085, x, y); break;
case 86: r = kernel_tex_image_interp(__tex_image_byte4_086, x, y); break;
case 87: r = kernel_tex_image_interp(__tex_image_byte4_087, x, y); break;
case 88: r = kernel_tex_image_interp(__tex_image_byte4_088, x, y); break;
default:
kernel_assert(0);
return make_float4(0.0f, 0.0f, 0.0f, 0.0f);
}
# else
CUtexObject tex = kernel_tex_fetch(__bindless_mapping, id);
/* float4, byte4 and half4 */
const int texture_type = kernel_tex_type(id);
if(texture_type == IMAGE_DATA_TYPE_FLOAT4 ||
texture_type == IMAGE_DATA_TYPE_BYTE4 ||
texture_type == IMAGE_DATA_TYPE_HALF4)
{
r = kernel_tex_image_interp_float4(tex, x, y);
}
/* float, byte and half */
else {
float f = kernel_tex_image_interp_float(tex, x, y);
r = make_float4(f, f, f, 1.0f);
}
# endif
#endif
const float alpha = r.w;
if(use_alpha && alpha != 1.0f && alpha != 0.0f) {
r /= alpha;
const int texture_type = kernel_tex_type(id);
if(texture_type == IMAGE_DATA_TYPE_BYTE4 ||
texture_type == IMAGE_DATA_TYPE_BYTE)
{
r = min(r, make_float4(1.0f, 1.0f, 1.0f, 1.0f));
}
r.w = alpha;
}
if(srgb) {
r = color_srgb_to_scene_linear_v4(r);
}
return r;
}
/* Remap coordnate from 0..1 box to -1..-1 */
ccl_device_inline float3 texco_remap_square(float3 co)
{
return (co - make_float3(0.5f, 0.5f, 0.5f)) * 2.0f;
}
ccl_device void svm_node_tex_image(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node)
{
uint id = node.y;
uint co_offset, out_offset, alpha_offset, srgb;
decode_node_uchar4(node.z, &co_offset, &out_offset, &alpha_offset, &srgb);
float3 co = stack_load_float3(stack, co_offset);
float2 tex_co;
uint use_alpha = stack_valid(alpha_offset);
if(node.w == NODE_IMAGE_PROJ_SPHERE) {
co = texco_remap_square(co);
tex_co = map_to_sphere(co);
}
else if(node.w == NODE_IMAGE_PROJ_TUBE) {
co = texco_remap_square(co);
tex_co = map_to_tube(co);
}
else {
tex_co = make_float2(co.x, co.y);
}
float4 f = svm_image_texture(kg, id, tex_co.x, tex_co.y, srgb, use_alpha);
if(stack_valid(out_offset))
stack_store_float3(stack, out_offset, make_float3(f.x, f.y, f.z));
if(stack_valid(alpha_offset))
stack_store_float(stack, alpha_offset, f.w);
}
ccl_device void svm_node_tex_image_box(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node)
{
/* get object space normal */
float3 N = sd->N;
N = sd->N;
object_inverse_normal_transform(kg, sd, &N);
/* project from direction vector to barycentric coordinates in triangles */
N.x = fabsf(N.x);
N.y = fabsf(N.y);
N.z = fabsf(N.z);
N /= (N.x + N.y + N.z);
/* basic idea is to think of this as a triangle, each corner representing
* one of the 3 faces of the cube. in the corners we have single textures,
* in between we blend between two textures, and in the middle we a blend
* between three textures.
*
* the Nxyz values are the barycentric coordinates in an equilateral
* triangle, which in case of blending, in the middle has a smaller
* equilateral triangle where 3 textures blend. this divides things into
* 7 zones, with an if() test for each zone */
float3 weight = make_float3(0.0f, 0.0f, 0.0f);
float blend = __int_as_float(node.w);
float limit = 0.5f*(1.0f + blend);
/* first test for corners with single texture */
if(N.x > limit*(N.x + N.y) && N.x > limit*(N.x + N.z)) {
weight.x = 1.0f;
}
else if(N.y > limit*(N.x + N.y) && N.y > limit*(N.y + N.z)) {
weight.y = 1.0f;
}
else if(N.z > limit*(N.x + N.z) && N.z > limit*(N.y + N.z)) {
weight.z = 1.0f;
}
else if(blend > 0.0f) {
/* in case of blending, test for mixes between two textures */
if(N.z < (1.0f - limit)*(N.y + N.x)) {
weight.x = N.x/(N.x + N.y);
weight.x = saturate((weight.x - 0.5f*(1.0f - blend))/blend);
weight.y = 1.0f - weight.x;
}
else if(N.x < (1.0f - limit)*(N.y + N.z)) {
weight.y = N.y/(N.y + N.z);
weight.y = saturate((weight.y - 0.5f*(1.0f - blend))/blend);
weight.z = 1.0f - weight.y;
}
else if(N.y < (1.0f - limit)*(N.x + N.z)) {
weight.x = N.x/(N.x + N.z);
weight.x = saturate((weight.x - 0.5f*(1.0f - blend))/blend);
weight.z = 1.0f - weight.x;
}
else {
/* last case, we have a mix between three */
weight.x = ((2.0f - limit)*N.x + (limit - 1.0f))/(2.0f*limit - 1.0f);
weight.y = ((2.0f - limit)*N.y + (limit - 1.0f))/(2.0f*limit - 1.0f);
weight.z = ((2.0f - limit)*N.z + (limit - 1.0f))/(2.0f*limit - 1.0f);
}
}
else {
/* Desperate mode, no valid choice anyway, fallback to one side.*/
weight.x = 1.0f;
}
/* now fetch textures */
uint co_offset, out_offset, alpha_offset, srgb;
decode_node_uchar4(node.z, &co_offset, &out_offset, &alpha_offset, &srgb);
float3 co = stack_load_float3(stack, co_offset);
uint id = node.y;
float4 f = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
uint use_alpha = stack_valid(alpha_offset);
if(weight.x > 0.0f)
f += weight.x*svm_image_texture(kg, id, co.y, co.z, srgb, use_alpha);
if(weight.y > 0.0f)
f += weight.y*svm_image_texture(kg, id, co.x, co.z, srgb, use_alpha);
if(weight.z > 0.0f)
f += weight.z*svm_image_texture(kg, id, co.y, co.x, srgb, use_alpha);
if(stack_valid(out_offset))
stack_store_float3(stack, out_offset, make_float3(f.x, f.y, f.z));
if(stack_valid(alpha_offset))
stack_store_float(stack, alpha_offset, f.w);
}
ccl_device void svm_node_tex_environment(KernelGlobals *kg, ShaderData *sd, float *stack, uint4 node)
{
uint id = node.y;
uint co_offset, out_offset, alpha_offset, srgb;
uint projection = node.w;
decode_node_uchar4(node.z, &co_offset, &out_offset, &alpha_offset, &srgb);
float3 co = stack_load_float3(stack, co_offset);
float2 uv;
co = safe_normalize(co);
if(projection == 0)
uv = direction_to_equirectangular(co);
else if (projection == 1)
uv = direction_to_mirrorball(co);
else {
float3 P = sd->P; //ccl_fetch(sd, P);
Transform worldtocamera = kernel_data.cam.worldtocamera;
Transform cameratondc = kernel_data.cam.cameratondc;
P = normalize(P);
P = transform_direction(&worldtocamera, P);
P = P / dot(P, make_float3(0, 0, 1));
P = transform_point(&cameratondc, P);
uv.x = P.x;
uv.y = 1 - P.y;
}
uint use_alpha = stack_valid(alpha_offset);
float4 f = svm_image_texture(kg, id, uv.x, uv.y, srgb, use_alpha);
if(stack_valid(out_offset))
stack_store_float3(stack, out_offset, make_float3(f.x, f.y, f.z));
if(stack_valid(alpha_offset))
stack_store_float(stack, alpha_offset, f.w);
}
CCL_NAMESPACE_END
| 2 | 2 |
2024-11-18T19:53:10.717918+00:00
| 2018-01-23T04:40:22 |
e718861b9d37aea96d035cdebe2e751078be9f7d
|
{
"blob_id": "e718861b9d37aea96d035cdebe2e751078be9f7d",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-23T04:40:22",
"content_id": "4fe8255bfe6927bed7cec2b7f7e1c3fd355440fa",
"detected_licenses": [
"MIT"
],
"directory_id": "103f2bea6b8dcb1764868c959bd047c7798ad367",
"extension": "c",
"filename": "stu_endian.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": 496,
"license": "MIT",
"license_type": "permissive",
"path": "/src/studease.cn/utils/stu_endian.c",
"provenance": "stackv2-0061.json.gz:5912",
"repo_name": "skyformat99/kiwistrmd",
"revision_date": "2018-01-23T04:40:22",
"revision_id": "238eb8284875b93bad756165cc2b36f845cfe2bd",
"snapshot_id": "d9a1e1e7d3d2cb1ce71ddf414e6a3bced67eded3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skyformat99/kiwistrmd/238eb8284875b93bad756165cc2b36f845cfe2bd/src/studease.cn/utils/stu_endian.c",
"visit_date": "2021-05-05T04:42:31.933182"
}
|
stackv2
|
/*
* stu_endian.c
*
* Created on: 2018年1月17日
* Author: Tony Lau
*/
#include "stu_utils.h"
stu_inline stu_uint16_t
stu_endian_16(stu_uint16_t n) {
return (n << 8) | (n >> 8);
}
stu_inline stu_uint32_t
stu_endian_32(stu_uint32_t n) {
return (n << 24) | ((n << 8) & 0xFF0000) | ((n >> 8) & 0xFF00) | (n >> 24);
}
stu_inline stu_uint64_t
stu_endian_64(stu_uint64_t n) {
return (stu_uint64_t) stu_endian_32((stu_uint32_t) n) << 32 | stu_endian_32((stu_uint32_t) (n >> 32));
}
| 2.40625 | 2 |
2024-11-18T19:53:10.882616+00:00
| 2021-02-03T06:06:39 |
d0bf84ab2fa46335ac7cb7f42f9f4d14289bf42e
|
{
"blob_id": "d0bf84ab2fa46335ac7cb7f42f9f4d14289bf42e",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-03T06:06:39",
"content_id": "2a5b5c91dcb3acfc99d2f9ce73cd9f8dde4f1b03",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5b599754b0721dc1abaee62ae5b09b33bb4d10e5",
"extension": "c",
"filename": "josephus_circle.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 62367837,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1337,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/DS/DS/linked-list/josephus_circle.c",
"provenance": "stackv2-0061.json.gz:6169",
"repo_name": "puneet222/Wiki-Analyser",
"revision_date": "2021-02-03T06:06:39",
"revision_id": "00def04c82fda74a9497e3869424f03f360c58e5",
"snapshot_id": "fa7b6fea4dd3795b4fff486a5763d81570d558e1",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/puneet222/Wiki-Analyser/00def04c82fda74a9497e3869424f03f360c58e5/DS/DS/linked-list/josephus_circle.c",
"visit_date": "2021-06-16T00:06:51.910813"
}
|
stackv2
|
#include<stdio.h>
#include<malloc.h>
struct list
{
int data ;
struct list * next ;
};
void display(struct list *head)
{
while(head != NULL)
{
printf(" %d ", head -> data);
head = head -> next ;
}
}
void cdisplay(struct list *head)
{
struct list *ptr ;
ptr = head ;
if(head == NULL)
return ;
do{
printf(" %d ", ptr -> data);
ptr = ptr -> next ;
}
while(ptr != head) ;
}
int josephusCircle(struct list *head , int k , int m)
{
int i , j;
struct list *ptr;
ptr = head ;
for(i = 1 ; i < k ; i++)
{
for(j = 0 ; j < m-1 ; j++)
{
head = ptr ;
ptr = ptr -> next ;
}
head -> next = ptr -> next ;
free(ptr) ;
ptr = head -> next ;
}
return head -> data ;
}
int main()
{
int k , i , m;
printf("Enter number of persons : ") ;
scanf("%d" , &k) ;
printf("\nEnter value of m in josephus circle : ");
scanf("%d" , &m);
struct list *head = NULL , *ptr ;
ptr = head ;
for(i = 1 ; i <= k ; i++)
{
struct list *newNode = malloc(sizeof(struct list)) ;
newNode -> data = i ;
newNode -> next = NULL ;
if(ptr == NULL)
{
ptr = newNode ;
head = ptr ;
}
else
{
ptr -> next = newNode ;
ptr = ptr -> next ;
}
}
ptr -> next = head ;
// cdisplay(head) ;
int res = josephusCircle(head , k , m) ;
printf("Result after eliminating in josephus circle is : %d\n", res );
}
| 3.75 | 4 |
2024-11-18T19:53:10.984703+00:00
| 2017-08-13T14:08:07 |
5206c6167c49c7d36842b77a889bcbeeecea36dc
|
{
"blob_id": "5206c6167c49c7d36842b77a889bcbeeecea36dc",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-13T14:08:07",
"content_id": "11db914f3eda5d901ab80d6d7bc4970a1b4f2c83",
"detected_licenses": [
"MIT"
],
"directory_id": "1583be85274dee6f59039c5d0b06911cd1674187",
"extension": "h",
"filename": "traffic.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98232691,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1681,
"license": "MIT",
"license_type": "permissive",
"path": "/traffic.h",
"provenance": "stackv2-0061.json.gz:6299",
"repo_name": "MalcolmLorber/ross_traffic",
"revision_date": "2017-08-13T14:08:07",
"revision_id": "70a9b35d935ec90c1ff4cb76607cd2c8c3265aec",
"snapshot_id": "9bab5a7f147ca9b84740dbfe42a66b3e578c428c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MalcolmLorber/ross_traffic/70a9b35d935ec90c1ff4cb76607cd2c8c3265aec/traffic.h",
"visit_date": "2021-01-01T18:04:00.281381"
}
|
stackv2
|
#ifndef INC_traffic_h
#define INC_traffic_h
#include <ross.h>
#define MEAN_DEPARTURE 10
#define MEAN_UTURN 1
typedef enum traffic_event_t traffic_event_t;
typedef enum traffic_direction_t traffic_direction_t;
typedef struct traffic_state traffic_state;
typedef struct traffic_message traffic_message;
enum traffic_event_t {
ARRIVAL,
DEPARTURE
};
enum traffic_direction_t {
NORTH = 0,
SOUTH,
EAST,
WEST
};
struct traffic_state {
int num_cars_finished_here;
int num_cars_arrived_here;
int waiting_time;
tw_stime cur_ns_cycle_start;
tw_stime last_ns_time;
tw_stime cur_we_cycle_start;
tw_stime last_we_time;
int num_cars_in_north;
int num_cars_in_south;
int num_cars_in_east;
int num_cars_in_west;
int num_u_turns;
int cars_started;
};
typedef struct {
int x_to_go;
int y_to_go;
traffic_direction_t direction;
} car;
typedef struct {
car saved_car;
struct traffic_state saved_ts;
} saved_data;
struct traffic_message {
tw_stime time_arrived;
traffic_event_t type;
car car;
saved_data saved;
long rng_count;
};
static int grid_size = 256;
static int opt_mem = 16000;
static int initial_cars_per_intersection = 1;
static int lane_capacity = 4;
static int lane_unit_traversal_time = 1;
static long int total_cars_finished = 0;
static long int total_cars_started = 0;
static double num_u_turns_avg = 0;
static double average_cars_per_intersection = 0.0;
static tw_lpid nlp_per_pe = 1024;
static tw_stime lookahead = 0.00000001;
static tw_stime traffic_light_duration = 10.0;
static tw_stime time_car_takes = 1.0;
static tw_stime wait_time_avg = 0.0;
#endif
| 2.03125 | 2 |
2024-11-18T19:53:11.062540+00:00
| 2020-01-30T15:52:16 |
f144141a5fa2eb3d7573386ec265f391b8d4924c
|
{
"blob_id": "f144141a5fa2eb3d7573386ec265f391b8d4924c",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-30T15:52:16",
"content_id": "7e218229269134958bfa710b8ed4d3392a52b673",
"detected_licenses": [
"MIT"
],
"directory_id": "40de3da30239862f11a946166b50438174c2fd4e",
"extension": "c",
"filename": "hills07.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 237240459,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1113,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/wizards/torspo/areat/gnomes/hills07.c",
"provenance": "stackv2-0061.json.gz:6427",
"repo_name": "vlehtola/questmud",
"revision_date": "2020-01-30T15:52:16",
"revision_id": "8bc3099b5ad00a9e0261faeb6637c76b521b6dbe",
"snapshot_id": "f53b7205351f30e846110300d60b639d52d113f8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vlehtola/questmud/8bc3099b5ad00a9e0261faeb6637c76b521b6dbe/lib/wizards/torspo/areat/gnomes/hills07.c",
"visit_date": "2020-12-23T19:59:44.886028"
}
|
stackv2
|
inherit "room/room";
reset(arg) {
if(!present("farmer")) {
move_object(clone_object("/wizards/torspo/areat/gnomes/monsters/farmer1"), this_object());
move_object(clone_object("/wizards/torspo/areat/gnomes/monsters/farmer1"), this_object());
}
if(!present("pony")) {
move_object(clone_object("/wizards/torspo/areat/gnomes/monsters/pony1"), this_object());
}
if(arg) { return; }
add_exit("south", "/wizards/torspo/areat/gnomes/hills03.c");
add_exit("west", "/wizards/torspo/areat/gnomes/hills06.c");
add_exit("north", "/wizards/torspo/areat/gnomes/hills13.c");
short_desc = "Grassy hills";
long_desc = "The path turns to west here. The ground is full of small footprints\n"+
"and there's a broken plow lying in the bottom of the ditch. Far to the\n"+
"west you see some stunted grain fields.\n";
items = allocate(4);
items[0] = "plow";
items[1] = "The iron plow has broken in hard work. The ground is too rocky and icy\n"+
"for raising";
items[2] = "footprints";
items[3] = "The ground is covered with small, gnomish made footprints";
}
| 2 | 2 |
2024-11-18T19:53:11.299892+00:00
| 2017-11-17T17:18:30 |
0855cf711d75b565432d91aea5f304d2f4e244fb
|
{
"blob_id": "0855cf711d75b565432d91aea5f304d2f4e244fb",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-17T17:18:30",
"content_id": "252363bd29341a8dcf499bd793423095f8bdc242",
"detected_licenses": [
"MIT"
],
"directory_id": "0b404b6dcd6f2facabc184563a4957fb32ffd044",
"extension": "c",
"filename": "hvs_multi_moments.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 111130025,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12896,
"license": "MIT",
"license_type": "permissive",
"path": "/src/libhvs/hvs_multi_moments.c",
"provenance": "stackv2-0061.json.gz:6811",
"repo_name": "vitos555/hevosol",
"revision_date": "2017-11-17T17:18:30",
"revision_id": "13e99066228cd3d23db891c754b4525aa55746d3",
"snapshot_id": "bc0d1857595981ba17f4b9c39687ed918e317ef9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vitos555/hevosol/13e99066228cd3d23db891c754b4525aa55746d3/src/libhvs/hvs_multi_moments.c",
"visit_date": "2021-08-15T09:00:22.695166"
}
|
stackv2
|
//
// Copyright (C) 2010-2011, Vitalii Ostrovskyi <vitalii@ostrovskyi.org.ua>
// Author: Vitalii Ostrovskyi <vitalii@ostrovskyi.org.ua>
//
#include <omp.h>
#if HVS_DEBUG>2
#include <stdio.h>
#endif
#ifdef HVS_PROFILE
#include <time.h>
#endif
int init_ode_data(hvs_ode_data *data, hvs_state *input) {
data->ncenters = input->ncenters;
data->lambdasq = input->lambdasq;
data->moments = (hvs_moment *) malloc(input->ncenters*sizeof(hvs_moment));
if (data->moments != NULL) {
memset(data->moments, 0, input->ncenters*sizeof(hvs_moment));
} else {
return HVS_ERR;
}
data->centers = (hvs_center *) malloc(input->ncenters*sizeof(hvs_center));
if (data->centers != NULL) {
memset(data->centers, 0, input->ncenters*sizeof(hvs_center));
} else {
free(data->moments);
return HVS_ERR;
}
return HVS_OK;
}
int free_ode_data(hvs_ode_data *data) {
if (data->moments != NULL)
free(data->moments);
data->moments = NULL;
if (data->centers != NULL)
free(data->centers);
data->centers = NULL;
return HVS_OK;
}
int update_vorticity_field(hvs_state *state) {
int i,j,k,k1,k2;
FLOAT_TYPE sum;
#ifdef HVS_PROFILE
time_t starttime, endtime;
starttime = time(NULL);
#endif
#if HVS_DEBUG
printf("update_vorticity_field\n");
#endif
for (i=0; i<state->size; i++) {
sum = 0.0;
#pragma omp parallel for reduction(+:sum) private(j) shared(state)
for (j=0; j<state->ncenters; j++) {
for(k=0; j<NCOMBS;j++) {
k1 = COMBS_IND1(k);
k2 = COMBS_IND2(k);
sum += state->moments[j][k]*he(state->grid[i].x-state->centers[j].x,state->grid[i].y-state->centers[j].y,state->lambdasq,k1,k2);
}
}
state->vorticity_field[i] = sum;
}
#ifdef HVS_PROFILE
endtime = time(NULL);
timings.vorticity_update += (int)(endtime-starttime);
timings.vorticity_update = (int)(timings.vorticity_update/2);
#endif
return HVS_OK;
}
int init_moments(hvs_state *state) {
FLOAT_TYPE *A,*x;
UINT i,j,k;
int status;
#ifdef HVS_PROFILE
time_t starttime, endtime;
starttime = time(NULL);
#endif
#if HVS_DEBUG
printf("init_moments\n");
#endif
if (state->size!=state->ncenters) {
return HVS_ERR;
}
if ((A=malloc(sizeof(FLOAT_TYPE)*state->size*state->size))==NULL) {
return HVS_ERR;
}
if ((x=malloc(sizeof(FLOAT_TYPE)*state->size))==NULL) {
free(A);
return HVS_ERR;
}
memset(x,0,sizeof(FLOAT_TYPE)*state->size);
#pragma omp parallel for collapse(2) private(i,j) shared(A,state)
for(i=0;i<state->size;i++)
for(j=0;j<state->size;j++)
A[state->size*i+j] =
he(state->grid[i].x-state->centers[j].x,
state->grid[i].y-state->centers[j].y,
state->lambdasq,
0,0);
if ((status=gmres(A,x,state->vorticity_field,state->size,HVS_GMRES_PRECISION,HVS_GMRES_MAX_INNER_MATRIX,x))!=HVS_OK) {
free(A);
free(x);
return status;
}
// Get moments
for(i=0;i<state->ncenters;i++) {
state->moments[i][0]=x[i];
}
free(A);
free(x);
#ifdef HVS_PROFILE
endtime = time(NULL);
timings.init_moments = (int)(endtime-starttime);
#endif
return HVS_OK;
}
int eval_eq(hvs_ode_data *input, hvs_ode_data *output, hvs_coefs *coefs, FLOAT_TYPE time_val) {
FLOAT_TYPE lambdasq = input->lambdasq;
FLOAT_TYPE gamma1,gamma2;
int i0,j0,k,k1,k2,l,l1,l2,m,m1,m2,i,j;
#ifdef HVS_PROFILE
time_t starttime, endtime;
starttime = time(NULL);
#endif
output->lambdasq = input->lambdasq;
#if HVS_DEBUG
printf("eval_eq\n");
#endif
// Parallelize execution
#pragma omp parallel default(none) shared(input,output,coefs,time_val,lambdasq)
{
// First evaluate centers equation
#pragma omp for private(i0,j0,l,m,l1,l2,m1,m2)
for (i0=0; i0<input->ncenters; i0++) {
output->centers[i0].x=(FLOAT_TYPE)0.0;
output->centers[i0].y=(FLOAT_TYPE)0.0;
for(j0=0; j0<input->ncenters; j0++) {
if (i0==j0) continue;
for(l=0;l<NCOMBS;l++) {
l1=COMBS_IND1(l);
l2=COMBS_IND2(l);
for(m=0;m<NCOMBS;m++) {
m1=COMBS_IND1(m);
m2=COMBS_IND2(m);
output->centers[i0].x +=
input->moments[j0][MOM_INDEX(l1,l2)]*
input->moments[i0][MOM_INDEX(m1,m2)]*
POWN1(m1+m2)*
hb1(
input->centers[i0].x-input->centers[j0].x,
input->centers[i0].y-input->centers[j0].y,
input->lambdasq,
m1+l1,m2+l2);
output->centers[i0].y +=
input->moments[j0][MOM_INDEX(l1,l2)]*
input->moments[i0][MOM_INDEX(m1,m2)]*
POWN1(m1+m2)*
hb2(
input->centers[i0].x-input->centers[j0].x,
input->centers[i0].y-input->centers[j0].y,
input->lambdasq,
m1+l1,m2+l2);
}
}
}
output->centers[i0].x/=input->moments[i0][MOM_INDEX(0,0)];
output->centers[i0].y/=input->moments[i0][MOM_INDEX(0,0)];
}
// Now get the moments equations
#pragma omp for collapse(2) private(i0,j0,l,m,k,k1,k2,l1,l2,m1,m2,gamma1,gamma2,i,j)
for (i0=0; i0<input->ncenters; i0++) {
for(j0=0; j0<input->ncenters; j0++)
for(k=0;k<NCOMBS;k++) {
k1=COMBS_IND1(k);
k2=COMBS_IND2(k);
for(l=0;l<NCOMBS;l++) {
l1=COMBS_IND1(l);
l2=COMBS_IND2(l);
for(m=0;m<NCOMBS;m++) {
m1=COMBS_IND1(m);
m2=COMBS_IND2(m);
gamma1=0.0;
gamma2=0.0;
for (i=0;i<=NMOMENTS;i++)
for (j=0;j<=NMOMENTS;j++) {
if (j0==i0) {
// If j'==j gammas will come from A
if ( (i<=MIN(l1,k1-1)) && (j<=MIN(l2,k2)) )
gamma1+=coefs->gamma1[COEF_INDEX(k1,k2,l1,l2,m1,m2,i,j)]/
POW(lambdasq,i+j+1)*h1(m1+k1-i-1+l1-i,m2+k2-j+l2-j,lambdasq);
if ( (i<=MIN(l1,k1)) && (j<=MIN(l2,k2-1)) )
gamma2+=coefs->gamma2[COEF_INDEX(k1,k2,l1,l2,m1,m2,i,j)]/
POW(lambdasq,i+j+1)*h2(m1+k1-i+l1-i,m2+k2-j-1+l2-j,lambdasq);
} else {
// If j'<>j gammas will come from B
if ((i<=MIN(l1,k1-1)) && (j<=MIN(l2,k2)))
gamma1+=coefs->gamma1[COEF_INDEX(k1,k2,l1,l2,m1,m2,i,j)]/
POW(lambdasq,i+j+1)*hb1(input->centers[i0].x-input->centers[j0].x,
input->centers[i0].y-input->centers[j0].y,
lambdasq,m1+k1-i-1+l1-i,m2+k2-j+l2-j);
if ((i<=MIN(l1,k1)) && (j<=MIN(l2,k2-1)))
gamma2+=coefs->gamma2[COEF_INDEX(k1,k2,l1,l2,m1,m2,i,j)]/
POW(lambdasq,i+j+1)*hb2(input->centers[i0].x-input->centers[j0].x,
input->centers[i0].y-input->centers[j0].y,
lambdasq,m1+k1-i+l1-i,m2+k2-j-1+l2-j);
}
}
// Add A+B
output->moments[i0][MOM_INDEX(k1,k2)] += (gamma1+gamma2)*
input->moments[i0][MOM_INDEX(l1,l2)]*
input->moments[j0][MOM_INDEX(m1,m2)]*
POWN1(k1+k2)*POW(input->lambdasq,k1+k2)/
(POW2(k1+k2)*factorial(k1)*factorial(k2));
}
}
// Add C once
if (j0==0) {
if (k1>0)
output->moments[i0][MOM_INDEX(k1,k2)]+=
output->centers[i0].x*
input->moments[i0][MOM_INDEX(k1-1,k2)];
if (k2>0)
output->moments[i0][MOM_INDEX(k1,k2)]+=
output->centers[i0].y*
input->moments[i0][MOM_INDEX(k1,k2-1)];
}
}
} // end for
} // end pragma omp parallel
#ifdef HVS_PROFILE
endtime = time(NULL);
timings.eval_equation += (int)(endtime-starttime);
timings.eval_equation = (int)(timings.eval_equation/2);
#endif
return HVS_OK;
}
int rk4_hvs_solve(hvs_state *curdata, FLOAT_TYPE tn, FLOAT_TYPE timestep, FLOAT_TYPE nu) {
hvs_ode_data k1, k2, k3, k4, kt;
int status = HVS_OK;
int i0,i,i1,i2;
#ifdef HVS_PROFILE
time_t starttime, endtime;
starttime = time(NULL);
#endif
#if HVS_DEBUG
printf("rk4_hvs_solve\n");
#endif
// Initialize temporary variable for moments and centers
if ((status=init_ode_data(&kt,curdata))!=HVS_OK) {
return status;
}
memcpy(kt.moments,curdata->moments,sizeof(hvs_moment)*curdata->ncenters);
memcpy(kt.centers,curdata->centers,sizeof(hvs_center)*curdata->ncenters);
// Initialize k1,k2,k3,k4 - rk4 function evaluations
if ((status=init_ode_data(&k1,curdata))!=HVS_OK) {
return status;
}
if ((status=init_ode_data(&k2,curdata))!=HVS_OK) {
return status;
}
if ((status=init_ode_data(&k3,curdata))!=HVS_OK) {
return status;
}
if ((status=init_ode_data(&k4,curdata))!=HVS_OK) {
return status;
}
// Get k1
if ((status=eval_eq(&kt, &k1, curdata->coefs, tn))!=HVS_OK) {
return status;
}
#if HVS_DEBUG>2
printf("m00=%f,m20=%f,m11=%f,m02=%f\n",k1.moments[0][0],k1.moments[0][3],k1.moments[0][4],k1.moments[0][5]);
printf("m00=%f,m20=%f,m11=%f,m02=%f\n",k1.moments[1][0],k1.moments[1][3],k1.moments[1][4],k1.moments[1][5]);
printf("y1=%.12f,y2=%.1f\n", k1.centers[0].y, k1.centers[1].y);
#endif
// Update kt
for (i0=0; i0<curdata->ncenters; i0++) {
for (i=0; i<NCOMBS; i++) {
i1=COMBS_IND1(i);
i2=COMBS_IND2(i);
kt.moments[i0][MOM_INDEX(i1,i2)] = curdata->moments[i0][MOM_INDEX(i1,i2)]+k1.moments[i0][MOM_INDEX(i1,i2)]*0.5*timestep;
}
kt.centers[i0].x = curdata->centers[i0].x+k1.centers[i0].x*0.5*timestep;
kt.centers[i0].y = curdata->centers[i0].y+k1.centers[i0].y*0.5*timestep;
}
kt.lambdasq += 4*0.5*timestep*nu;
// Get k2
if ((status=eval_eq(&kt, &k2, curdata->coefs, tn+0.5*timestep))!=HVS_OK) {
return status;
}
// Update kt
for (i0=0; i0<curdata->ncenters; i0++) {
for (i=0; i<NCOMBS; i++) {
i1=COMBS_IND1(i);
i2=COMBS_IND2(i);
kt.moments[i0][MOM_INDEX(i1,i2)] = curdata->moments[i0][MOM_INDEX(i1,i2)]+k2.moments[i0][MOM_INDEX(i1,i2)]*0.5*timestep;
}
kt.centers[i0].x = curdata->centers[i0].x+k2.centers[i0].x*0.5*timestep;
kt.centers[i0].y = curdata->centers[i0].y+k2.centers[i0].y*0.5*timestep;
}
// Get k3
if ((status=eval_eq(&kt, &k3, curdata->coefs, tn+0.5*timestep))!=HVS_OK) {
return status;
}
// Update kt
for (i0=0; i0<curdata->ncenters; i0++) {
for (i=0; i<NCOMBS; i++) {
i1=COMBS_IND1(i);
i2=COMBS_IND2(i);
kt.moments[i0][MOM_INDEX(i1,i2)] = curdata->moments[i0][MOM_INDEX(i1,i2)]+k3.moments[i0][MOM_INDEX(i1,i2)]*timestep;
}
kt.centers[i0].x = curdata->centers[i0].x+k3.centers[i0].x*timestep;
kt.centers[i0].y = curdata->centers[i0].y+k3.centers[i0].y*timestep;
}
kt.lambdasq += 4*0.5*timestep*nu;
// Get k4
if ((status=eval_eq(&kt, &k4, curdata->coefs, tn+timestep))!=HVS_OK) {
return status;
}
// Use k1,k2,k3,k4 to find rk4 value
for (i0=0; i0<curdata->ncenters; i0++) {
for (i=0; i<NCOMBS; i++) {
i1=COMBS_IND1(i);
i2=COMBS_IND2(i);
curdata->moments[i0][MOM_INDEX(i1,i2)] = curdata->moments[i0][MOM_INDEX(i1,i2)]+1.0/6*timestep*
(k1.moments[i0][MOM_INDEX(i1,i2)]+2*k2.moments[i0][MOM_INDEX(i1,i2)]+2*k3.moments[i0][MOM_INDEX(i1,i2)]+k4.moments[i0][MOM_INDEX(i1,i2)]);
}
curdata->centers[i0].x = curdata->centers[i0].x+1.0/6*timestep*(k1.centers[i0].x+2*k2.centers[i0].x+2*k3.centers[i0].x+k4.centers[i0].x);
curdata->centers[i0].y = curdata->centers[i0].y+1.0/6*timestep*(k1.centers[i0].y+2*k2.centers[i0].y+2*k3.centers[i0].y+k4.centers[i0].y);
}
curdata->lambdasq += 4.0*timestep*nu;
// Free all the Intermediate values
free_ode_data(&kt);
free_ode_data(&k1);
free_ode_data(&k2);
free_ode_data(&k3);
free_ode_data(&k4);
#if HVS_DEBUG>2
printf("m00=%f,m20=%f,m11=%f,m02=%f\n",curdata->moments[0][0],curdata->moments[0][3],curdata->moments[0][4],curdata->moments[0][5]);
printf("m00=%f,m20=%f,m11=%f,m02=%f\n",curdata->moments[1][0],curdata->moments[1][3],curdata->moments[1][4],curdata->moments[1][5]);
printf("y1=%f,y2=%f\n", curdata->centers[0].y, curdata->centers[1].y);
#endif
#ifdef HVS_PROFILE
endtime = time(NULL);
timings.rk_step += (int)(endtime-starttime);
timings.rk_step = (int)(timings.rk_step/2);
#endif
return HVS_OK;
}
int init_coefs(hvs_coefs *coefs) {
int k,k1,k2,m,m1,m2,l,l1,l2,i,j;
#ifdef HVS_PROFILE
time_t starttime, endtime;
starttime = time(NULL);
#endif
#if HVS_DEBUG
printf("init_coefs\n");
#endif
#pragma omp parallel for default(none) shared(coefs) private(k,k1,k2,l,l1,l2,m,m1,m2,i,j)
for(k=0;k<NCOMBS;k++) {
k1=COMBS_IND1(k);
k2=COMBS_IND2(k);
for(l=0;l<NCOMBS;l++) {
l1=COMBS_IND1(l);
l2=COMBS_IND2(l);
for(m=0;m<NCOMBS;m++) {
m1=COMBS_IND1(m);
m2=COMBS_IND2(m);
for(i=0;i<=NMOMENTS;i++)
for(j=0;j<=NMOMENTS;j++) {
if ((i<=MIN(l1,k1-1))&&(j<=MIN(l2,k2))) {
coefs->gamma1[COEF_INDEX(k1,k2,l1,l2,m1,m2,i,j)]=(FLOAT_TYPE)POWN1(l1+l2)*
binomial(l1,i)*binomial(l2,j)*(POW2(i+1)*factorial(k1))/factorial(k1-i-1)*
(POW2(j)*factorial(k2))/factorial(k2-j);
}
if ((i<=MIN(l1,k1))&&(j<=MIN(l2,k2-1))) {
coefs->gamma2[COEF_INDEX(k1,k2,l1,l2,m1,m2,i,j)]=(FLOAT_TYPE)POWN1(l1+l2)*
binomial(l1,i)*binomial(l2,j)*(POW2(i)*factorial(k1))/factorial(k1-i)*
(POW2(j+1)*factorial(k2))/factorial(k2-j-1);
}
}
}
}
}
#ifdef HVS_PROFILE
endtime = time(NULL);
timings.init_coefs = (int)(endtime-starttime);
#endif
}
int step_solver(hvs_state *state, FLOAT_TYPE *tn, const hvs_params *params) {
int i,status;
#if HVS_DEBUG
printf("step_solver, t=%f\n",(float)(*tn));
#endif
if ((status = rk4_hvs_solve(state, (*tn), params->timestep, params->nu))!=HVS_OK) {
return status;
}
(*tn) = (*tn)+params->timestep;
#if HVS_DEBUG>2
printf("%f=%f\n",state->lambdasq,(*tn)*4.0*params->nu+params->lambda0*params->lambda0);
#endif
return HVS_OK;
}
| 2.171875 | 2 |
2024-11-18T19:53:12.406580+00:00
| 2021-06-03T11:54:47 |
c1b022e78c60caade577d10d514b223e2aae9208
|
{
"blob_id": "c1b022e78c60caade577d10d514b223e2aae9208",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-03T11:54:47",
"content_id": "3784636a0a0bf0453104cd881fa66dd5a6cf24ba",
"detected_licenses": [
"MIT"
],
"directory_id": "f2af2c1812865e7e0d240c70cedd8fc7927957d0",
"extension": "c",
"filename": "prolific.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 373489915,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1340,
"license": "MIT",
"license_type": "permissive",
"path": "/Project 1/prolific.c",
"provenance": "stackv2-0061.json.gz:7709",
"repo_name": "imartinovic-dzaja/CS-3013-Projects",
"revision_date": "2021-06-03T11:54:47",
"revision_id": "73674546ad30f5d05a45faa6ddb6652eceb1bd27",
"snapshot_id": "b35e71d44c6e57f3b56b8428d36016da925fc773",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/imartinovic-dzaja/CS-3013-Projects/73674546ad30f5d05a45faa6ddb6652eceb1bd27/Project 1/prolific.c",
"visit_date": "2023-05-07T11:48:43.418143"
}
|
stackv2
|
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <wait.h>
#include "util_random.h"
int main(int argc, char* argv[]) {
int seed = 0;
int lowerLimit = 10;
int upperLimit = 15;
read_seed("seed.txt", &seed);
printf("Read seed value %i\n", seed);
srand(seed);
int randomNumber = get_random_number(lowerLimit, upperLimit);
printf("Random Child Count: %i\n", randomNumber);
printf("I'm feeling prolific!\n");
int childNumbers[randomNumber];
for (int i = 0; i < randomNumber; ++i) {
childNumbers[i] = rand();
int rc = fork();
if ( rc < 0 ) {
printf("fork failed!\n");
exit(1);
} else if (rc == 0) {
//child is this code
int pid = (int) getpid();
int exitCode = (childNumbers[i] % 50 ) + 1;
int waitTime = (childNumbers[i] % 3) + 1;
printf("\t[Child, PID: %i]: I am the child and I will wait %i seconds and exit with code %i.\n"
, pid, waitTime, exitCode);
sleep(waitTime);
printf("\t[Child, PID: %i]: Now exiting...\n", pid);
return exitCode;
} else {
//parent is this code
int exitCode;
printf("[Parent]: I am waiting for PID %i to finish.\n", rc);
waitpid(rc, &exitCode, 0);
printf("[Parent]: Child %i finished with status code %i. Onward!\n", rc, WEXITSTATUS(exitCode));
}
}
return 0;
}
| 2.78125 | 3 |
2024-11-18T19:53:12.778946+00:00
| 2021-11-01T23:30:45 |
5cf6f745c0868af3c513d333b0e3758d22e2c265
|
{
"blob_id": "5cf6f745c0868af3c513d333b0e3758d22e2c265",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-01T23:31:34",
"content_id": "41f777ea4c600959305851d7e16237389d42283d",
"detected_licenses": [
"MIT"
],
"directory_id": "b38a71daf368c26414bc89925a33917842e0504e",
"extension": "h",
"filename": "bitset.h",
"fork_events_count": 0,
"gha_created_at": "2020-08-10T19:19:46",
"gha_event_created_at": "2020-10-08T23:11:33",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 286560098,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 513,
"license": "MIT",
"license_type": "permissive",
"path": "/projects/framegraph/fg/bitset.h",
"provenance": "stackv2-0061.json.gz:8094",
"repo_name": "tmpvar/rawkit",
"revision_date": "2021-11-01T23:30:45",
"revision_id": "0dee2bdf9e11e9033988a0d9d1e52603263c6aca",
"snapshot_id": "6884f4f9f5d97bed03350361ac24eb493dbc3e2b",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/tmpvar/rawkit/0dee2bdf9e11e9033988a0d9d1e52603263c6aca/projects/framegraph/fg/bitset.h",
"visit_date": "2023-06-19T15:44:19.770373"
}
|
stackv2
|
#pragma once
#include <rawkit/rawkit.h>
#include <roaring/roaring.h>
struct Bitset {
roaring_bitmap_t *_bitmap = nullptr;
Bitset(u32 capacity = 0) {
if (capacity) {
_bitmap = roaring_bitmap_create_with_capacity(capacity);
} else {
_bitmap = roaring_bitmap_create();
}
}
~Bitset() {
roaring_bitmap_free(_bitmap);
}
bool get(u32 idx) {
return roaring_bitmap_contains(this->_bitmap, idx);
}
void set(u32 idx) {
roaring_bitmap_add(this->_bitmap, idx);
}
};
| 2.28125 | 2 |
2024-11-18T19:53:12.886901+00:00
| 2019-07-15T19:11:25 |
c5a58cf95bad47355c10ee69c27f692e4bde9049
|
{
"blob_id": "c5a58cf95bad47355c10ee69c27f692e4bde9049",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-15T19:11:25",
"content_id": "c6d5f80f0b7185a638c65badcb32ba10a06cbeea",
"detected_licenses": [
"MIT"
],
"directory_id": "fb5fcfdc3600d979ae3b6fa513d5cf50aef9d619",
"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": 196258743,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 701,
"license": "MIT",
"license_type": "permissive",
"path": "/blink_nucleo64/main.c",
"provenance": "stackv2-0061.json.gz:8222",
"repo_name": "Wa1tee/Keil_projects",
"revision_date": "2019-07-15T19:11:25",
"revision_id": "e72848970dbe0a996afec42b35118771cbd49953",
"snapshot_id": "7c9ea1c7ec1523859c5b3555c91256049ee6e665",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Wa1tee/Keil_projects/e72848970dbe0a996afec42b35118771cbd49953/blink_nucleo64/main.c",
"visit_date": "2020-06-18T09:44:25.250069"
}
|
stackv2
|
#include<stdint.h>
#include<stdbool.h>
#include "Board_LED.h"
#include "Board_Buttons.h"
void delay (void)
{
uint32_t i = 0;
for( i = 0; i< 500000; i++);
}
void pointers3(void){
void (*jump_addr) (void) = 0x00000000;
jump_addr();
}
void pointers2(void){
pointers3();
}
void pointers(void){
pointers2();
}
int main(void){
bool ledstatus = false;
bool lastBtn = false;
LED_Initialize();
Buttons_Initialize();
while(1)
{
pointers();
if(Buttons_GetState() ==1){
//lastBtn = true;
if(ledstatus){
ledstatus = false;
delay();
}else{
ledstatus = true;
delay();
}
}
if(ledstatus){
LED_On(0);
}else{
LED_Off(0);
}
}
return 0;
}
| 2.484375 | 2 |
2024-11-18T19:53:13.042786+00:00
| 2021-03-26T15:30:16 |
4af43c4b91f32b2a88bfd8cca98eb587939f4b27
|
{
"blob_id": "4af43c4b91f32b2a88bfd8cca98eb587939f4b27",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-26T15:30:16",
"content_id": "fd55d702fceacdd3f0293efd7206f79c3a1100d2",
"detected_licenses": [
"MIT"
],
"directory_id": "89d7c92db50da9d4ff0fb992b7216229b2c31ea4",
"extension": "c",
"filename": "exercicio 11.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 351824526,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 327,
"license": "MIT",
"license_type": "permissive",
"path": "/Aulas/Exercicios/lista6/exercicio 11.c",
"provenance": "stackv2-0061.json.gz:8354",
"repo_name": "ThyagoHiggins/Linguagem-C",
"revision_date": "2021-03-26T15:30:16",
"revision_id": "9cc121ec93f26734caede3e2e9690942354a31aa",
"snapshot_id": "8c56ea32e7f53127bd8f0e90bef0e51bb46827a1",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ThyagoHiggins/Linguagem-C/9cc121ec93f26734caede3e2e9690942354a31aa/Aulas/Exercicios/lista6/exercicio 11.c",
"visit_date": "2023-03-28T23:57:28.304593"
}
|
stackv2
|
#include <stdio.h>
#include <locale.h>
int main()
{
setlocale (LC_CTYPE, "ptb");
int n, i;
do{
printf ("Informe um número: ");
scanf ("%d", &n);
if(n>500){
printf ("O programa acabou!!!!!");
}else {
for (i=0; i<n;i++) printf ("%d\n",n);}
}while (n<500);
return 0;
}
| 2.625 | 3 |
2024-11-18T20:30:35.938166+00:00
| 2023-08-10T19:48:51 |
132dfcf00cd35bb7c430ce53a6df08faf47654bf
|
{
"blob_id": "132dfcf00cd35bb7c430ce53a6df08faf47654bf",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T19:48:51",
"content_id": "e5133c49d367bc2371474ad19bfe8a2f5d9a45b4",
"detected_licenses": [
"MIT"
],
"directory_id": "bc1361593eb147f7f823ae3272f1810b6d13c350",
"extension": "c",
"filename": "hb_cache.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 211671347,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12906,
"license": "MIT",
"license_type": "permissive",
"path": "/src/hb_cache/hb_cache.c",
"provenance": "stackv2-0062.json.gz:274374",
"repo_name": "irov/hummingbird",
"revision_date": "2023-08-10T19:48:51",
"revision_id": "77e0550b70a73dc02d56bef5b94d355bd5b84df8",
"snapshot_id": "9473f8647c5937249bd64da13deb396d28b28468",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/irov/hummingbird/77e0550b70a73dc02d56bef5b94d355bd5b84df8/src/hb_cache/hb_cache.c",
"visit_date": "2023-08-21T12:50:27.117846"
}
|
stackv2
|
#include "hb_cache.h"
#include "hb_memory/hb_memory.h"
#include "hb_token/hb_token.h"
#include "hb_log/hb_log.h"
#pragma warning( push )
#pragma warning( disable : 4244 )
#include "hiredis.h"
#pragma warning( pop )
#include <string.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#if defined(HB_PLATFORM_WINDOWS)
#include <WinSock2.h>
#elif defined(HB_PLATFORM_LINUX)
#include <sys/time.h>
#elif defined(HB_PLATFORM_OSX)
#include <sys/time.h>
#endif
//////////////////////////////////////////////////////////////////////////
typedef struct hb_cache_handle_t
{
redisContext * context;
} hb_cache_handle_t;
//////////////////////////////////////////////////////////////////////////
static const char * __hb_redis_reply_str( int32_t _type )
{
const char * reply_str[15] = {"unknown", "string", "array", "integer", "nil", "status", "error", "double", "bool", "map", "set", "attr", "push", "bignum", "verb"};
const char * str = reply_str[_type];
return str;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_create( const char * _uri, uint16_t _port, uint32_t _timeout, hb_cache_handle_t ** _handle )
{
struct timeval tv_timeout;
tv_timeout.tv_sec = _timeout / 1000;
tv_timeout.tv_usec = (_timeout % 1000) * 1000;
redisContext * c = redisConnectWithTimeout( _uri, _port, tv_timeout ); //6379
if( c == HB_NULLPTR )
{
return HB_FAILURE;
}
if( c->err != REDIS_OK )
{
HB_LOG_MESSAGE_ERROR( "cache", "connect radis url:'%s' port: %u get error [%s:%d]"
, _uri
, _port
, c->errstr
, c->err
);
return HB_FAILURE;
}
HB_LOG_MESSAGE_INFO( "cache", "connect radis url:'%s' port: %u successful"
, _uri
, _port
);
if( redisEnableKeepAlive( c ) != REDIS_OK )
{
redisFree( c );
return HB_FAILURE;
}
HB_LOG_MESSAGE_INFO( "cache", "enable keep alive radis url:'%s' port: %u successful"
, _uri
, _port
);
hb_cache_handle_t * handle = HB_NEW( hb_cache_handle_t );
handle->context = c;
*_handle = handle;
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
void hb_cache_destroy( hb_cache_handle_t * _handle )
{
redisFree( _handle->context );
HB_DELETE( _handle );
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_set_value( const hb_cache_handle_t * _cache, const void * _key, hb_size_t _keysize, const void * _value, hb_size_t _valuesize )
{
if( _keysize == HB_UNKNOWN_STRING_SIZE )
{
_keysize = strlen( (const char *)_key );
}
redisReply * reply = redisCommand( _cache->context, "SET %b %b", _key, _keysize, _value, _valuesize );
if( reply == HB_NULLPTR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'SET' with error: '%s'"
, _cache->context->errstr
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_ERROR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'SET' with error: '%s'"
, reply->str
);
return HB_FAILURE;
}
freeReplyObject( reply );
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_get_value( const hb_cache_handle_t * _cache, const void * _key, hb_size_t _keysize, void * const _value, hb_size_t _capacity, hb_size_t * const _size )
{
if( _keysize == HB_UNKNOWN_STRING_SIZE )
{
_keysize = strlen( (const char *)_key );
}
redisReply * reply = redisCommand( _cache->context, "GET %b", _key, _keysize );
if( reply == HB_NULLPTR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'GET' with error: '%s'"
, _cache->context->errstr
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_ERROR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'GET' with error: '%s'"
, reply->str
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_NIL )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'GET' return nil" );
freeReplyObject( reply );
return HB_FAILURE;
}
if( reply->type != REDIS_REPLY_STRING )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'GET' return '%s' not 'string'"
, __hb_redis_reply_str( reply->type )
);
freeReplyObject( reply );
return HB_FAILURE;
}
if( reply->len > _capacity )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'GET' return '%s' len %zu more capacity %zu"
, reply->str
, reply->len
, _capacity
);
freeReplyObject( reply );
return HB_FAILURE;
}
memcpy( _value, reply->str, reply->len );
if( _size != HB_NULLPTR )
{
*_size = reply->len;
}
freeReplyObject( reply );
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_incrby_value( const hb_cache_handle_t * _cache, const void * _key, hb_size_t _keysize, uint64_t _increment, uint64_t * const _value )
{
if( _keysize == HB_UNKNOWN_STRING_SIZE )
{
_keysize = strlen( (const char *)_key );
}
redisReply * reply = redisCommand( _cache->context, "INCRBY %b %" SCNu64, _key, _keysize, _increment );
if( reply == HB_NULLPTR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'INCRBY' with error: '%s'"
, _cache->context->errstr
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_ERROR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'INCRBY' with error: '%s'"
, reply->str
);
return HB_FAILURE;
}
if( reply->type != REDIS_REPLY_INTEGER )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'INCRBY' type '%d' not integer"
, reply->type
);
freeReplyObject( reply );
return HB_FAILURE;
}
*_value = (uint64_t)reply->integer;
freeReplyObject( reply );
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_expire_value( const hb_cache_handle_t * _cache, const void * _key, hb_size_t _keysize, uint32_t _seconds )
{
if( _keysize == HB_UNKNOWN_STRING_SIZE )
{
_keysize = strlen( (const char *)_key );
}
redisReply * reply = redisCommand( _cache->context, "EXPIRE %b %u", _key, _keysize, _seconds );
if( reply == HB_NULLPTR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'EXPIRE' with error: '%s'"
, _cache->context->errstr
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_ERROR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'EXPIRE' with error: '%s'"
, reply->str
);
freeReplyObject( reply );
return HB_FAILURE;
}
freeReplyObject( reply );
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_get_token( const hb_cache_handle_t * _cache, const char * _token, uint32_t _seconds, void * _value, hb_size_t _capacity, hb_size_t * const _size )
{
hb_token_t token;
if( hb_token_base16_decode_string( _token, &token ) == HB_FAILURE )
{
return HB_FAILURE;
}
if( hb_cache_expire_value( _cache, token.value, sizeof( hb_token_t ), _seconds ) == HB_FAILURE )
{
return HB_FAILURE;
}
if( hb_cache_get_value( _cache, token.value, sizeof( hb_token_t ), _value, _capacity, _size ) == HB_FAILURE )
{
return HB_FAILURE;
}
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_zadd( const hb_cache_handle_t * _cache, const void * _key, hb_size_t _keysize, const void * _value, hb_size_t _valuesize, uint32_t _score )
{
if( _keysize == HB_UNKNOWN_STRING_SIZE )
{
_keysize = strlen( (const char *)_key );
}
if( _valuesize == HB_UNKNOWN_STRING_SIZE )
{
_valuesize = strlen( (const char *)_value );
}
redisReply * reply = redisCommand( _cache->context, "ZADD %b %u %b", _key, _keysize, _score, _value, _valuesize );
if( reply == HB_NULLPTR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZADD' with error: '%s'"
, _cache->context->errstr
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_ERROR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZADD' with error: '%s'"
, reply->str
);
return HB_FAILURE;
}
freeReplyObject( reply );
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_zrevrange( const hb_cache_handle_t * _cache, const void * _key, hb_size_t _keysize, uint32_t _begin, uint32_t _end, hb_cache_value_t * const _values, uint32_t * const _count )
{
redisReply * reply = redisCommand( _cache->context, "ZREVRANGE %b %u %u WITHSCORES", _key, _keysize, _begin, _end );
if( reply == HB_NULLPTR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZREVRANGE' with error: '%s'"
, _cache->context->errstr
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_ERROR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZREVRANGE' with error: '%s'"
, reply->str
);
return HB_FAILURE;
}
if( reply->type != REDIS_REPLY_ARRAY )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZREVRANGE' return '%s' not array"
, __hb_redis_reply_str( reply->type )
);
return HB_FAILURE;
}
for( hb_size_t index = 0; index != reply->elements; ++index )
{
struct redisReply * element = reply->element[index];
hb_cache_value_t * value = _values + index;
switch( element->type )
{
case REDIS_REPLY_BOOL:
{
value->type = e_hb_cache_boolean;
value->integer = (int64_t)element->integer;
}break;
case REDIS_REPLY_INTEGER:
{
value->type = e_hb_cache_integer;
value->integer = (int64_t)element->integer;
}break;
case REDIS_REPLY_DOUBLE:
{
value->type = e_hb_cache_double;
value->real = element->dval;
}break;
case REDIS_REPLY_STRING:
{
value->type = e_hb_cache_string;
if( element->len > 127 )
{
return HB_FAILURE;
}
memcpy( value->str, element->str, element->len );
value->str[element->len] = '\0';
}break;
default:
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZREVRANGE' element %zu type '%s' not array"
, index
, __hb_redis_reply_str( reply->type )
);
return HB_FAILURE;
}break;
}
}
*_count = (uint32_t)reply->elements;
freeReplyObject( reply );
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
hb_result_t hb_cache_zrevrank( const hb_cache_handle_t * _cache, const void * _key, hb_size_t _keysize, const void * _value, hb_size_t _valuesize, uint32_t * const _score, hb_bool_t * const _exist )
{
redisReply * reply = redisCommand( _cache->context, "ZREVRANK %b %b", _key, _keysize, _value, _valuesize );
if( reply == HB_NULLPTR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZREVRANGE' with error: '%s'"
, _cache->context->errstr
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_ERROR )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZREVRANK' with error: '%s'"
, reply->str
);
return HB_FAILURE;
}
if( reply->type == REDIS_REPLY_NIL )
{
freeReplyObject( reply );
*_exist = HB_FALSE;
return HB_SUCCESSFUL;
}
if( reply->type != REDIS_REPLY_INTEGER )
{
HB_LOG_MESSAGE_ERROR( "cache", "redis command 'ZREVRANK' return type '%s' not 'integer'"
, __hb_redis_reply_str( reply->type )
);
freeReplyObject( reply );
return HB_FAILURE;
}
uint32_t score = (uint32_t)reply->integer;
*_score = score;
*_exist = HB_TRUE;
freeReplyObject( reply );
return HB_SUCCESSFUL;
}
//////////////////////////////////////////////////////////////////////////
| 2.015625 | 2 |
2024-11-18T20:30:36.010717+00:00
| 2020-01-21T12:17:50 |
625a4d70a6a9dc161cf6210234d4e4fc207b76c5
|
{
"blob_id": "625a4d70a6a9dc161cf6210234d4e4fc207b76c5",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-21T12:17:50",
"content_id": "59d1417654753337d389fa863ef8c200c30ba22e",
"detected_licenses": [
"MIT"
],
"directory_id": "7ac2ea0e6f67a958dabf1d1396fd1e97791f70a5",
"extension": "c",
"filename": "plagueis.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 92707357,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3529,
"license": "MIT",
"license_type": "permissive",
"path": "/plagueis.c",
"provenance": "stackv2-0062.json.gz:274504",
"repo_name": "WinFutureX/plagueis",
"revision_date": "2020-01-21T12:17:50",
"revision_id": "86afb1aa0fbf12fc5f6e4ecb2d00960269f0c8cf",
"snapshot_id": "71dd3fe1896fb311a642e80ef4d4bd7f1b62e481",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/WinFutureX/plagueis/86afb1aa0fbf12fc5f6e4ecb2d00960269f0c8cf/plagueis.c",
"visit_date": "2021-01-22T11:32:12.958185"
}
|
stackv2
|
/* WinFutureX presents - Plagueis (or Reach the Man) version 1.1 (run from console!!) */
/* please subscribe to r/chinese_bootleg_memes thank you very much */
/* Copyright 2018 Kelsey Boey. */
/* plagueis is licensed under the MIT license. See LICENSE for full license terms. */
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
printf("\nWinFutureX PRESENTS - PLAGUEIS / REACH THE MAN v1.1\n\n");
for (int i = 1; i < argc; ++i)
{
if (!strcmp(argv[1], "-secret") || !strcmp(argv[1], "-s") || !strcmp(argv[1], "-S") || !strcmp(argv[1], "/S") || !strcmp(argv[1], "/s"))
{
printf("This is your own masterpiece\n");
}
else if (!strcmp(argv[1], "-backstroke") || !strcmp(argv[1], "-b") || !strcmp(argv[1], "-B") || !strcmp(argv[1], "/B") || !strcmp(argv[1], "/b"))
{
// backstroke (prequel memers don't know that our power will big outrun)
printf("Did you heard of the tragedy that reach the man? I think to be too is not. I\n");
printf("think that the hopeless situation elder also can't. That is a legend. Reaching\n");
printf("the man cloth space is the emperor. He is so strong and big he even can use the\n");
printf("original dint to create life. He is very deep to black influence understanding.\n");
printf("The black influence can the matter that many supermans. But other people thinks\n");
printf("that these are what can't attains. He become more and more strong and big. Lost\n");
printf("his power afterwards afterwards he died. In fact he teaches own the whole skills\n");
printf("all to disciple. Then his land killed him to let him going to bed. Satirizing\n");
printf("the meaning is he can let other people, but is incapable for dint to the\n");
printf("oneself.\n");
}
else
{
printf("special options:\n\n");
printf("-secret (/s or -s): does exactly what it says\n");
printf("-backstroke (/b or -b): same thing\n");
#ifndef _WIN32
printf("\n");
#endif
}
return 0;
}
printf("Did you ever hear the tragedy of Darth Plagueis the wise?\n");
printf("(Please answer with 'Y' or 'N'.)\n");
char answer = getchar();
if (answer == 'Y' || answer == 'y')
{
// prequel memer
printf("\nWe will watch your career with great interest.\n");
}
else if (answer == 'N' || answer == 'n')
{
// normie
printf("\nI thought not. It's not a story the Jedi would tell you. It's a Sith legend.\n");
printf("Darth Plagueis was a Dark Lord of the Sith, so powerful and so wise he could\n");
printf("use the Force to influence the midichlorians to create life... He had such a\n");
printf("knowledge of the dark side that he could even keep the ones he cared about from\n");
printf("dying. The dark side of the Force is a pathway to many abilities some consider\n");
printf("to be unnatural. He became so powerful... the only thing he was afraid of was\n");
printf("losing his power, which eventually, of course, he did. Unfortunately, he taught\n");
printf("his apprentice everything he knew, then his apprentice killed him in his sleep.\n");
printf("Ironic. He could save others from death, but not himself.\n");
}
else if (answer == 'B' || answer == 'b')
{
printf("\nnote: launch with \"-backstroke\" option next time\n");
}
else
{
// he's too dangerous to be left alive!
printf("\nSo uncivilised.\n");
#ifndef _WIN32
printf("\n");
#endif
return 1;
}
#ifndef _WIN32
printf("\n");
#endif
return 0;
}
| 2.640625 | 3 |
2024-11-18T20:30:36.123987+00:00
| 2017-02-20T20:25:46 |
1591adb8d30ba31a7fd632a416a3a46bf1b07223
|
{
"blob_id": "1591adb8d30ba31a7fd632a416a3a46bf1b07223",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-20T20:25:46",
"content_id": "1bddc16b3d485d6b71455e2c8924e1cfc0e7da90",
"detected_licenses": [
"MIT"
],
"directory_id": "f5e7040fc6bc3874199f59a6c3d5d006ec77d307",
"extension": "h",
"filename": "b64.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 81019977,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1938,
"license": "MIT",
"license_type": "permissive",
"path": "/src/b64.h",
"provenance": "stackv2-0062.json.gz:274636",
"repo_name": "hheld/b64",
"revision_date": "2017-02-20T20:25:46",
"revision_id": "a4b514434477dbb37ccdc46062fe4fab0f170e68",
"snapshot_id": "1fe2e5b9e1f959b9f14c930f2c44d837a68f0b1b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hheld/b64/a4b514434477dbb37ccdc46062fe4fab0f170e68/src/b64.h",
"visit_date": "2021-01-22T01:55:24.044209"
}
|
stackv2
|
/* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file in the project root
* for details.
*/
#ifndef B64_H
#define B64_H
/**
* Encode string \a s to base64.
*
* @param s string to be converted, must be 0 terminated
* @param numBytes number of bytes in \a s
* @param encodedNumBytes Will contain the length of the returned encoded contents, if the pointer is not NULL.
* If it is NULL, it is ignored.
* @return New string containing 0-terminated base64 encoded version of \a s. The caller is responsible for cleaning up.
*/
char *b64_encode(const char *s, const unsigned long numBytes, unsigned long *encodedNumBytes);
/**
* Decode string \a s from base64.
*
* @param s string to be converted, must be 0 terminated
* @param numBytes number of bytes in \a s
* @param decodedNumBytes Will contain the length of the returned decoded contents, if the pointer is not NULL.
* If it is NULL, it is ignored.
* @return New string containing 0-terminated decoded version of \a s. The caller is responsible for cleaning up.
*/
char* b64_decode(const char *s, const unsigned long numBytes, unsigned long *decodedNumBytes);
/**
* Encodes the contents of the given file \a fileName in Base64.
*
* @param fileName Name, i.e. path, of the file whose content is to be encoded
* @param numBytes Will contain the length of the returned encoded contents
* @return File content encoded in Base64
*/
char *b64_encodeFile(const char *fileName, unsigned long *numBytes);
/**
* Decodes the contents of the given file \a fileName from Base64.
*
* @param fileName Name, i.e. path, of the file whose content is to be decoded
* @param numBytes Will contain the length of the returned decoded contents
* @return File content decoded from Base64
*/
char *b64_decodeFile(const char *fileName, unsigned long *numBytes);
#endif // B64_H
| 2.296875 | 2 |
2024-11-18T20:30:36.292838+00:00
| 2023-01-03T16:21:45 |
29a1448af7210c4aecfeaef821380f762150cdf1
|
{
"blob_id": "29a1448af7210c4aecfeaef821380f762150cdf1",
"branch_name": "refs/heads/main",
"committer_date": "2023-01-03T16:21:45",
"content_id": "3b146d5ff785ea720272689e2c97fa4da5d6c49d",
"detected_licenses": [
"MIT",
"Python-2.0"
],
"directory_id": "316d3a3dd06baa40dd6ba1f6e44e9cc3f5643d4e",
"extension": "c",
"filename": "internal_pointOp.c",
"fork_events_count": 23,
"gha_created_at": "2018-06-15T20:01:10",
"gha_event_created_at": "2023-08-10T21:08:30",
"gha_language": "Jupyter Notebook",
"gha_license_id": "MIT",
"github_id": 137527035,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1405,
"license": "MIT,Python-2.0",
"license_type": "permissive",
"path": "/pyrtools/pyramids/c/internal_pointOp.c",
"provenance": "stackv2-0062.json.gz:274764",
"repo_name": "LabForComputationalVision/pyrtools",
"revision_date": "2023-01-03T16:21:45",
"revision_id": "37094ad9ee0278520b8ace876770b62f3e9c472e",
"snapshot_id": "4106b6e84787409093e812e7a2e12b1238777421",
"src_encoding": "UTF-8",
"star_events_count": 65,
"url": "https://raw.githubusercontent.com/LabForComputationalVision/pyrtools/37094ad9ee0278520b8ace876770b62f3e9c472e/pyrtools/pyramids/c/internal_pointOp.c",
"visit_date": "2023-02-20T05:51:08.809496"
}
|
stackv2
|
#include <stdio.h>
#include <math.h>
/* Use linear interpolation on a lookup table.
Taken from OBVIUS. EPS, Spring, 1987.
*/
void internal_pointop (im, res, size, lut, lutsize, origin, increment, warnings)
register double *im, *res, *lut;
register double origin, increment;
register int size, lutsize, warnings;
{
register int i, index;
register double pos;
register int l_unwarned = warnings;
register int r_unwarned = warnings;
lutsize = lutsize - 2; /* Maximum index value */
/* printf("size=%d origin=%f lutsize=%d increment=%f\n",size, origin, lutsize,
increment); */
if (increment > 0)
for (i=0; i<size; i++)
{
pos = (im[i] - origin) / increment;
index = (int) pos; /* Floor */
if (index < 0)
{
index = 0;
if (l_unwarned)
{
printf("Warning: Extrapolating to left of lookup table...\n");
l_unwarned = 0;
}
}
else if (index > lutsize)
{
index = lutsize;
if (r_unwarned)
{
printf("Warning: Extrapolating to right of lookup table...\n");
r_unwarned = 0;
}
}
res[i] = lut[index] + (lut[index+1] - lut[index]) * (pos - index);
if(isnan(res[i]))
printf("**NAN: lut[%d]=%f lut[%d]=%f pos=%f index=%d\n", index,
lut[index], index+1, lut[index+1], pos, index);
}
else
for (i=0; i<size; i++){
res[i] = *lut;
/*printf("res[%d]=%f\n", i, res[i]);*/
}
}
| 2.9375 | 3 |
2024-11-18T20:30:37.626308+00:00
| 2021-05-18T07:20:26 |
ea4108e04d2aa3910352082e5ff21ead8ab523d2
|
{
"blob_id": "ea4108e04d2aa3910352082e5ff21ead8ab523d2",
"branch_name": "refs/heads/master",
"committer_date": "2021-05-18T07:20:26",
"content_id": "8d5b2b9c42c617323e5c94dcff84653c009a87fd",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "af898999f56c9f30446cd9430afd3542d28e7c23",
"extension": "c",
"filename": "deque.c",
"fork_events_count": 1,
"gha_created_at": "2021-04-19T14:15:03",
"gha_event_created_at": "2021-04-19T14:15:04",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 359484611,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6688,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/deque.c",
"provenance": "stackv2-0062.json.gz:274895",
"repo_name": "aiporre/whisk",
"revision_date": "2021-05-18T07:20:26",
"revision_id": "e07c381bc5d0df4e5dcabd7d75c0c97d0de3ad2c",
"snapshot_id": "be6e25ad4ac95f8f013867ae3a25065246ce1ef8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aiporre/whisk/e07c381bc5d0df4e5dcabd7d75c0c97d0de3ad2c/src/deque.c",
"visit_date": "2023-04-24T09:34:03.409014"
}
|
stackv2
|
/* Author: Nathan Clack <clackn@janelia.hhmi.org>
* Date : May 2009
*
* Copyright 2010 Howard Hughes Medical Institute.
* All rights reserved.
* Use is subject to Janelia Farm Research Campus Software Copyright 1.1
* license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
/**
* DEQUE
*
* Implimented as a resizable array.
* Holds pointers to objects.
*
* TODO: Impliment as resizable circular buffer
* + front and back operations are symmetric
* + If the size of the active area of the store remains constant
* never reallocs.
*
* NOTE: This is unused right now
*/
#include "compat.h"
#include "common.h"
#include "utilities.h"
#include "error.h"
#include <string.h>
#include <assert.h>
#include "deque.h"
#if 0
#define TEST_DEQUE_1
#define WARNING_POP_FROM_EMPTY
#endif
SHARED_EXPORT
Deque *Deque_Alloc(int size_hint)
{ Deque *self = Guarded_Malloc( sizeof(Deque), "Deque_Alloc 1" );
size_hint = ( size_hint>1 ) ? size_hint : 2; // size must by >= 2
self->store = Guarded_Malloc( sizeof(void*)*size_hint, "Deque_Alloc 2");
self->size_bytes = size_hint*sizeof(void*);
self->front = size_hint/2-1; //when empty front points just behind back
self->back = size_hint/2;
return self;
}
SHARED_EXPORT
void Deque_Free(Deque *self)
{ if(self)
{ if(self->store) free(self->store);
free(self);
}
}
SHARED_EXPORT
void Deque_Reset ( Deque *self )
{ int n = self->size_bytes/sizeof(void*)/2;
memset( self->store, 0, self->size_bytes );
self->front = n-1;
self->back = 0;
}
SHARED_EXPORT
void Deque_Squeeze(Deque *self)
{ size_t f = self->front,
b = self->back;
size_t n = f - b + 1;
self->size_bytes = (n+2)*sizeof(void*);
memmove(self->store+1,self->store + b, self->size_bytes);
self->back = 1;
self->front = self->back + n - 1;
self->store = Guarded_Realloc( self->store, self->size_bytes , "Deque_Squeeze" );
}
SHARED_EXPORT
void *Deque_Front(Deque *self)
{ return self->store[self->front];
}
SHARED_EXPORT
void *Deque_Back(Deque *self)
{ return self->store[self->back];
}
SHARED_EXPORT
int Deque_Is_Empty(Deque *self)
{ return (self->front == self->back - 1);
}
SHARED_EXPORT
Deque *_Deque_Push_Front_Unsafe( Deque* self, void *item )
{ self->store[++self->front] = item;
return self;
}
SHARED_EXPORT
Deque *Deque_Push_Front( Deque* self, void *item )
{ size_t s = self->size_bytes/sizeof(void*);
if( self->front >= s - 2 )
self->store = request_storage( self->store, &self->size_bytes, sizeof(void*), s+1, "Deque: realloc on push front" );
return _Deque_Push_Front_Unsafe( self, item );
}
SHARED_EXPORT
void *_Deque_Pop_Front_Unsafe( Deque* self)
{ return self->store[self->front--];
}
SHARED_EXPORT
void *Deque_Pop_Front( Deque *self )
{ if( self->front >= self->back )
return _Deque_Pop_Front_Unsafe(self);
#ifdef WARNING_POP_FROM_EMPTY
else
warning("Pop front requested from empty Deque\n");
#endif
return NULL;
}
SHARED_EXPORT
Deque *_Deque_Push_Back_Unsafe( Deque* self, void *item )
{ self->store[--self->back] = item;
return self;
}
SHARED_EXPORT
Deque *Deque_Push_Back( Deque *self, void *item )
{ if( self->back <= 1 ) // then, need to move things
{ size_t f = self->front,
b = self->back,
s = self->size_bytes/sizeof(void*),
rem = s-f-2,
n = f-b+1;
// 1. Can we just move the store's active area? If not, then resize.
if( !rem )
self->store = request_storage( self->store, &self->size_bytes, sizeof(void*), s+1, "Deque: realloc on push back" );
// 2. Move active area of store to end
s = self->size_bytes/sizeof(void*);
rem = s-f-2;
n = f-b+1;
memmove( self->store+s-n-2, self->store+b-1, sizeof(void*)*(n+2) );
self->back = b + rem;
self->front = f + rem;
}
return _Deque_Push_Back_Unsafe(self,item);
}
SHARED_EXPORT
void *_Deque_Pop_Back_Unsafe( Deque* self)
{ return self->store[self->back++];
}
SHARED_EXPORT
void *Deque_Pop_Back( Deque *self )
{ if( self->front >= self->back )
return _Deque_Pop_Back_Unsafe(self);
#ifdef WARNING_POP_FROM_EMPTY
else
warning("Pop back requested from empty Deque\n");
#endif
return NULL;
}
#ifdef TEST_DEQUE_1
int main(int argc, char* argv[])
{
progress("Deque: test alloc and hinting\n");
{ int i=10;
while(i--)
{ Deque *d = Deque_Alloc( i );
Deque_Free(d);
}
}
progress("Deque: test push front\n");
{ int i = 10000000,
j = 0,
*p = NULL;
Deque *d = Deque_Alloc( i );
progress("\tPushing %d items on front.\n",i);
while(i--) Deque_Push_Front( d, &i );
Deque_Squeeze(d);
while( (p=Deque_Pop_Front(d)) )
{ assert(*p=i);
j++;
}
progress("\t%d Items popped from front.\n",j);
assert( d->front == d->back - 1 );
i=20000000, j=0;
progress("\tPushing %d items on front.\n",i);
while(i--) Deque_Push_Front( d, &i );
while( (p=Deque_Pop_Back(d)) )
{ assert(*p=i);
j++;
}
progress("\t%d Items popped from back.\n",j);
assert( d->front == d->back - 1 );
Deque_Free(d);
}
progress("Deque: test push back\n");
{ int i = 10000000,
j = 0,
*p = NULL;
Deque *d = Deque_Alloc( i );
progress("\tPushing %d items on back.\n",i);
while(i--) Deque_Push_Back( d, &i );
Deque_Squeeze(d);
while( (p=Deque_Pop_Front(d)) )
{ assert(*p=i);
j++;
}
progress("\t%d Items popped from front.\n",j);
assert( d->front == d->back - 1 );
i=20000000, j=0;
progress("\tPushing %d items on back.\n",i);
while(i--) Deque_Push_Back( d, &i );
while( (p=Deque_Pop_Back(d)) )
{ assert(*p=i);
j++;
}
progress("\t%d Items popped from back.\n",j);
assert( d->front == d->back - 1 );
Deque_Free(d);
}
progress("Deque: test push mixed\n");
{ int i = 10000000,
j = 0,
*p = NULL;
Deque *d = Deque_Alloc( i );
progress("\tPushing %d items on (mixed).\n",i);
while(i--)
if( i&1 )
Deque_Push_Back( d, &i );
else
Deque_Push_Front( d, &i );
Deque_Squeeze(d);
while( (p=Deque_Pop_Front(d)) )
{ assert(*p=i);
j++;
}
progress("\t%d Items popped from front.\n",j);
assert( d->front == d->back - 1 );
i=20000000, j=0;
progress("\tPushing %d items on (mixed).\n",i);
while(i--)
if( i&1 )
Deque_Push_Back( d, &i );
else
Deque_Push_Front( d, &i );
while( (p=Deque_Pop_Back(d)) )
{ assert(*p=i);
j++;
}
progress("\t%d Items popped from back.\n",j);
assert( d->front == d->back - 1 );
Deque_Free(d);
}
}
#endif
| 2.421875 | 2 |
2024-11-18T20:57:34.893304+00:00
| 2021-09-26T07:05:36 |
f122cf576ce17623bb36f6887ae1e8064b8ad13d
|
{
"blob_id": "f122cf576ce17623bb36f6887ae1e8064b8ad13d",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-26T07:05:36",
"content_id": "2ca65b55ddec7b5f37edb1e9eaa08cd7c5cb7a2e",
"detected_licenses": [
"MIT"
],
"directory_id": "864461586354c357c5751f8541bdab45a0f44d5f",
"extension": "c",
"filename": "light.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": 12797,
"license": "MIT",
"license_type": "permissive",
"path": "/oilchange/light.c",
"provenance": "stackv2-0064.json.gz:68434",
"repo_name": "SafirX/tinyc.games",
"revision_date": "2021-09-26T07:05:36",
"revision_id": "b0ea083fdc4410587366b758645c982e12c9943d",
"snapshot_id": "f87f56b820e436f017962ccd7eb3531aec91b042",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SafirX/tinyc.games/b0ea083fdc4410587366b758645c982e12c9943d/oilchange/light.c",
"visit_date": "2023-08-15T20:42:05.907172"
}
|
stackv2
|
#include "oilchange.h"
void sun_enqueue(int x, int y, int z, int base, unsigned char incoming_light)
{
if (incoming_light == 0)
return;
if (T_(x, y, z) == WATR)
incoming_light--; // water blocks more light
if (T_(x, y, z) == RLEF || T_(x, y, z) == YLEF)
{
incoming_light--; // leaves block more light
if (incoming_light) incoming_light--;
}
if (SUN_(x, y, z) >= incoming_light)
return; // already brighter
if (T_(x, y, z) < OPEN)
return; // no lighting for solid blocks
set_sunlight(x, y, z, incoming_light);
if (sq_next_len >= SUNQLEN)
{
sunq_outta_room++;
return; // out of room in sun queue
}
for (size_t i = base; i < sq_curr_len; i++)
if (sunq_curr[i].x == x && sunq_curr[i].y == y && sunq_curr[i].z == z)
return; // already queued in current queue
for (size_t i = 0; i < sq_next_len; i++)
if (sunq_next[i].x == x && sunq_next[i].y == y && sunq_next[i].z == z)
return; // already queued in next queue
sunq_next[sq_next_len].x = x;
sunq_next[sq_next_len].y = y;
sunq_next[sq_next_len].z = z;
sq_next_len++;
}
void glo_enqueue(int x, int y, int z, int base, unsigned char incoming_light)
{
if (incoming_light == 0)
return;
if (T_(x, y, z) == WATR)
incoming_light--; // water blocks more light
if (T_(x, y, z) == RLEF || T_(x, y, z) == YLEF)
{
incoming_light--; // leaves block more light
if (incoming_light) incoming_light--;
}
if (GLO_(x, y, z) >= incoming_light)
return; // already brighter
if (T_(x, y, z) < OPEN)
return; // no lighting for solid blocks
set_glolight(x, y, z, incoming_light);
if (gq_next_len >= GLOQLEN)
{
gloq_outta_room++;
return; // out of room in glo queue
}
for (size_t i = base; i < gq_curr_len; i++)
if (gloq_curr[i].x == x && gloq_curr[i].y == y && gloq_curr[i].z == z)
return; // already queued in current queue
for (size_t i = 0; i < gq_next_len; i++)
if (gloq_next[i].x == x && gloq_next[i].y == y && gloq_next[i].z == z)
return; // already queued in next queue
gloq_next[gq_next_len].x = x;
gloq_next[gq_next_len].y = y;
gloq_next[gq_next_len].z = z;
gq_next_len++;
}
int step_sunlight()
{
// swap the queues
sunq_curr = sunq_next;
sq_curr_len = sq_next_len;
sq_next_len = 0;
sunq_next = (sunq_curr == sunq0_) ? sunq1_ : sunq0_;
for (size_t i = 0; i < sq_curr_len; i++)
{
int x = sunq_curr[i].x;
int y = sunq_curr[i].y;
int z = sunq_curr[i].z;
char pass_on = SUN_(x, y, z);
if (pass_on) pass_on--; else continue;
if (x ) sun_enqueue(x-1, y , z , i+1, pass_on);
if (x < TILESW-1) sun_enqueue(x+1, y , z , i+1, pass_on);
if (y ) sun_enqueue(x , y-1, z , i+1, pass_on);
if (y < TILESH-1) sun_enqueue(x , y+1, z , i+1, pass_on);
if (z ) sun_enqueue(x , y , z-1, i+1, pass_on);
if (z < TILESD-1) sun_enqueue(x , y , z+1, i+1, pass_on);
}
return sq_curr_len;
}
int step_glolight()
{
// swap the queues
gloq_curr = gloq_next;
gq_curr_len = gq_next_len;
gq_next_len = 0;
gloq_next = (gloq_curr == gloq0_) ? gloq1_ : gloq0_;
for (size_t i = 0; i < gq_curr_len; i++)
{
int x = gloq_curr[i].x;
int y = gloq_curr[i].y;
int z = gloq_curr[i].z;
char pass_on = GLO_(x, y, z);
if (pass_on) pass_on--; else continue;
if (x ) glo_enqueue(x-1, y , z , i+1, pass_on);
if (x < TILESW-1) glo_enqueue(x+1, y , z , i+1, pass_on);
if (y ) glo_enqueue(x , y-1, z , i+1, pass_on);
if (y < TILESH-1) glo_enqueue(x , y+1, z , i+1, pass_on);
if (z ) glo_enqueue(x , y , z-1, i+1, pass_on);
if (z < TILESD-1) glo_enqueue(x , y , z+1, i+1, pass_on);
}
return gq_curr_len;
}
void recalc_corner_lighting(int xlo, int xhi, int zlo, int zhi)
{
for (int x = xlo; x < xhi; x++) for (int z = zlo; z < zhi; z++) for (int y = 0; y < TILESH; y++)
{
int x_ = (x == 0) ? 0 : x - 1;
int y_ = (y == 0) ? 0 : y - 1;
int z_ = (z == 0) ? 0 : z - 1;
CORN_(x, y, z) = 0.008f * (
SUN_(x_, y_, z_) + SUN_(x , y_, z_) + SUN_(x_, y , z_) + SUN_(x , y , z_) +
SUN_(x_, y_, z ) + SUN_(x , y_, z ) + SUN_(x_, y , z ) + SUN_(x , y , z ));
KORN_(x, y, z) = 0.008f * (
GLO_(x_, y_, z_) + GLO_(x , y_, z_) + GLO_(x_, y , z_) + GLO_(x , y , z_) +
GLO_(x_, y_, z ) + GLO_(x , y_, z ) + GLO_(x_, y , z ) + GLO_(x , y , z ));
}
}
void set_sunlight(int xlo, int ylo, int zlo, int light)
{
SUN_(xlo, ylo, zlo) = light;
for (int x = xlo; x < xlo + 2; x++) for (int z = zlo; z < zlo + 2; z++) for (int y = ylo; y < ylo + 2; y++)
{
int x_ = (x == 0) ? 0 : x - 1;
int y_ = (y == 0) ? 0 : y - 1;
int z_ = (z == 0) ? 0 : z - 1;
CORN_(x, y, z) = 0.008f * (
SUN_(x_, y_, z_) + SUN_(x , y_, z_) + SUN_(x_, y , z_) + SUN_(x , y , z_) +
SUN_(x_, y_, z ) + SUN_(x , y_, z ) + SUN_(x_, y , z ) + SUN_(x , y , z ));
}
}
void set_glolight(int xlo, int ylo, int zlo, int light)
{
GLO_(xlo, ylo, zlo) = light;
for (int x = xlo; x < xlo + 2; x++) for (int z = zlo; z < zlo + 2; z++) for (int y = ylo; y < ylo + 2; y++)
{
int x_ = (x == 0) ? 0 : x - 1;
int y_ = (y == 0) ? 0 : y - 1;
int z_ = (z == 0) ? 0 : z - 1;
KORN_(x, y, z) = 0.008f * (
GLO_(x_, y_, z_) + GLO_(x , y_, z_) + GLO_(x_, y , z_) + GLO_(x , y , z_) +
GLO_(x_, y_, z ) + GLO_(x , y_, z ) + GLO_(x_, y , z ) + GLO_(x , y , z ));
}
}
// remove direct or indirect sunlight
// before calling, set opacity, but not light value
void remove_sunlight(int px, int py, int pz)
{
// FIXME: remove when confident
static int recursions = 0;
if (++recursions > 1000000)
{
fprintf(stderr, "1 million remove_sunlight() recursions\n");
return;
}
int my_light = SUN_(px, py, pz);
int im_opaque = IS_OPAQUE(px, py, pz);
if (my_light < 1) return;
struct qitem check_list[6];
struct qitem recur_list[6];
int check_len = 0;
int recur_len = 0;
// FIXME: remove this when gndheight is already correct
for (int y = 0; y < TILESH-1; y++)
if (IS_OPAQUE(px, y, pz))
{
GNDH_(px, pz) = y;
break;
}
// i am in direct sunlight, no need to remove light
if (ABOVE_GROUND(px, py, pz))
return;
int incoming_light = 0;
int future_light = 0;
// find valid neighbors to check
if (px > 0 ) check_list[check_len++] = QITEM(px-1, py , pz );
if (px < TILESW-1) check_list[check_len++] = QITEM(px+1, py , pz );
if (py > 0 ) check_list[check_len++] = QITEM(px , py-1, pz );
// never spread sunlight value 15 upward:
if (py < TILESH-1 && SUN_(px,py+1,pz) != 15) check_list[check_len++] = QITEM(px , py+1, pz );
if (pz > 0 ) check_list[check_len++] = QITEM(px , py , pz-1);
if (pz < TILESD-1) check_list[check_len++] = QITEM(px , py , pz+1);
for (int i = 0; i < check_len; i++)
{
int x = check_list[i].x;
int y = check_list[i].y;
int z = check_list[i].z;
// no need to update my opaque neighbors
if (IS_OPAQUE(x, y, z)) continue;
// i am lit by a neighbor block as much or more than before
// so... there is no more light to remove in this branch
if (SUN_(x, y, z) > my_light && !im_opaque) return;
// i am [now] being lit by this neighbor
if (SUN_(x, y, z) == my_light && !im_opaque)
incoming_light = MAX(incoming_light, SUN_(x, y, z) - 1);
// keep track of brightest neighboring light for queueing later
if (SUN_(x, y, z) > future_light && !im_opaque)
future_light = SUN_(x, y, z);
// i could be the light source for this neighbor, need to recurse
if (SUN_(x, y, z) < my_light)
recur_list[recur_len++] = QITEM(x, y, z);
}
if (incoming_light >= my_light)
fprintf(stderr, "INCOMING LIGHT > MY LIGHT when darkening\n");
set_sunlight(px, py, pz, incoming_light);
// re-lighting may be needed here
if (future_light)
sun_enqueue(px, py, pz, 0, future_light - 1);
// i had no light to give anyway
if (my_light < 2) return;
for (int i = 0; i < recur_len; i++)
remove_sunlight(recur_list[i].x, recur_list[i].y, recur_list[i].z);
}
void remove_glolight(int px, int py, int pz)
{
// FIXME: remove when confident
static int recursions = 0;
if (++recursions > 1000000)
{
fprintf(stderr, "1 million remove_glolight() recursions\n");
return;
}
int my_light = GLO_(px, py, pz);
int im_opaque = IS_OPAQUE(px, py, pz);
if (my_light < 1) return;
struct qitem check_list[6];
struct qitem recur_list[6];
int check_len = 0;
int recur_len = 0;
int incoming_light = 0;
int future_light = 0;
// find valid neighbors to check
if (px > 0 ) check_list[check_len++] = QITEM(px-1, py , pz );
if (px < TILESW-1) check_list[check_len++] = QITEM(px+1, py , pz );
if (py > 0 ) check_list[check_len++] = QITEM(px , py-1, pz );
if (py < TILESH-1) check_list[check_len++] = QITEM(px , py+1, pz );
if (pz > 0 ) check_list[check_len++] = QITEM(px , py , pz-1);
if (pz < TILESD-1) check_list[check_len++] = QITEM(px , py , pz+1);
for (int i = 0; i < check_len; i++)
{
int x = check_list[i].x;
int y = check_list[i].y;
int z = check_list[i].z;
// no need to update my opaque neighbors
if (IS_OPAQUE(x, y, z)) continue;
// i am lit by a neighbor block as much or more than before
// so... there is no more light to remove in this branch
if (GLO_(x, y, z) > my_light && !im_opaque) return;
// i am [now] being lit by this neighbor
if (GLO_(x, y, z) == my_light && !im_opaque)
incoming_light = MAX(incoming_light, GLO_(x, y, z) - 1);
// keep track of brightest neighboring light for queueing later
if (GLO_(x, y, z) > future_light && !im_opaque)
future_light = GLO_(x, y, z);
// i could be the light source for this neighbor, need to recurse
if (GLO_(x, y, z) < my_light)
recur_list[recur_len++] = QITEM(x, y, z);
}
if (incoming_light >= my_light)
fprintf(stderr, "GLO: INCOMING LIGHT > MY LIGHT when darkening\n");
set_glolight(px, py, pz, incoming_light);
// re-lighting may be needed here
if (future_light)
glo_enqueue(px, py, pz, 0, future_light - 1);
// i had no light to give anyway
if (my_light < 2) return;
for (int i = 0; i < recur_len; i++)
remove_glolight(recur_list[i].x, recur_list[i].y, recur_list[i].z);
}
| 2.296875 | 2 |
2024-11-18T20:57:35.106427+00:00
| 2017-07-29T00:20:45 |
41ddc2d5396e499110589057d49575b1e00cb7ec
|
{
"blob_id": "41ddc2d5396e499110589057d49575b1e00cb7ec",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-29T00:20:45",
"content_id": "fedb1400d1e60a386f5b5ef1dc376cbd6b25ede4",
"detected_licenses": [
"MIT"
],
"directory_id": "aa39371348c767e1010a1aeb2da33c8edd8da99b",
"extension": "h",
"filename": "jetsonTX2Gpio.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 95135004,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1486,
"license": "MIT",
"license_type": "permissive",
"path": "/GPIO/jetsonTX2Gpio.h",
"provenance": "stackv2-0064.json.gz:68691",
"repo_name": "minhquannguyen/JetsonTx2",
"revision_date": "2017-07-29T00:20:45",
"revision_id": "f018c2b879cf8fc5c5b8ae1cb1aa0810a98a15ea",
"snapshot_id": "62450b402b28d01c3693f7386bab6d73a0c1edee",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/minhquannguyen/JetsonTx2/f018c2b879cf8fc5c5b8ae1cb1aa0810a98a15ea/GPIO/jetsonTX2Gpio.h",
"visit_date": "2020-04-05T12:33:08.887286"
}
|
stackv2
|
#ifndef TX2_GPIO_H
#define TX2_GPIO_H
#include "../Common/inc/jetsonStatus.h"
#include "../Common/inc/jetsonConstants.h"
#define GPIO_DIR "/sys/class/gpio"
typedef enum
{
gpio298 = 298, // Pin 31 GPIO9_MOTION_INT
gpio388 = 388, // pin 37 GPIO8_ALS_PROX_INT
gpio389 = 389, // Pin 33 GPIO11_AP_WAKE_BT
gpio398 = 398, // Pin 29 GPIO19_AUD_RST
gpio481 = 481 // Pin 18 GPIO16_MDM_WAKE_AP
} TX2_GPIO;
typedef enum
{
GPIO_FILE_MODE_READ = 0,
GPIO_FILE_MODE_WRITE
} GPIO_FILE_MODE;
typedef enum
{
GPIO_DIRECTION_INPUT = 0,
GPIO_DIRECTION_OUTPUT
} GPIO_PIN_DIRECTION;
typedef enum
{
GPIO_PIN_VALUE_LOW = 0,
GPIO_PIN_VALUE_HIGH
} GPIO_PIN_VALUE;
typedef enum
{
GPIO_PIN_EDGE_NONE = 0,
GPIO_PIN_EDGE_RISING,
GPIO_PIN_EDGE_FALLING,
GPIO_PIN_EDGE_BOTH
} GPIO_PIN_EDGE;
typedef enum
{
GPIO_ACTIVE_LOW_FALSE = 0,
GPIO_ACTIVE_LOW_TRUE
} GPIO_ACTIVE_LOW;
static Status _gpio_open_file(TX2_GPIO gpio, GPIO_FILE_MODE mode, char *dirToOpen, TxS32 *fd);
Status gpio_export(TX2_GPIO gpio);
Status gpio_unexport(TX2_GPIO gpio);
Status gpio_set_direction(TX2_GPIO gpio, GPIO_PIN_DIRECTION direction);
Status gpio_set_value(TX2_GPIO gpio, GPIO_PIN_VALUE value);
Status gpio_get_value(TX2_GPIO gpio, GPIO_PIN_VALUE *value);
Status gpio_set_edge(TX2_GPIO gpio, GPIO_PIN_EDGE edge);
Status gpio_active_low(TX2_GPIO gpio, GPIO_ACTIVE_LOW activeLow);
Status gpio_open(TX2_GPIO gpio, TxS32 *fd);
Status gpio_close(TxS32 *fd);
#endif
| 2.015625 | 2 |
2024-11-18T20:57:36.291108+00:00
| 2023-04-22T14:54:06 |
3f8f1b2275ae288a89f06dac10fa8c452d387e80
|
{
"blob_id": "3f8f1b2275ae288a89f06dac10fa8c452d387e80",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-22T14:54:06",
"content_id": "8294b713d1dbe743250506f1a48ccd0284a57adf",
"detected_licenses": [
"MIT"
],
"directory_id": "910df3314069d2d925fd2ac20709b3264872a904",
"extension": "c",
"filename": "tokenizer.c",
"fork_events_count": 6,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7246088,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 16378,
"license": "MIT",
"license_type": "permissive",
"path": "/compiler/tokenizer.c",
"provenance": "stackv2-0064.json.gz:68820",
"repo_name": "bl0ckeduser/new-bpf-tools",
"revision_date": "2023-04-22T14:54:06",
"revision_id": "1d2c438ce00759c74da629305ea300c3ee26a641",
"snapshot_id": "710cb2d0e028a927620ff3fef621a83aede528bd",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/bl0ckeduser/new-bpf-tools/1d2c438ce00759c74da629305ea300c3ee26a641/compiler/tokenizer.c",
"visit_date": "2023-05-02T18:10:24.720007"
}
|
stackv2
|
/*
* Tokenization code based on wannabe-regex.c,
* which I wrote September-August 2012.
* The tokenization is always "greedy".
* It works using my "wannabe-regex"
* NFA pseudo-regex compiler/matcher.
*
* On Aug. 31, 2013, the tokenization was
* heavily modified: now the NFAs themselves
* are always deterministic,
* and consequently the matching code is cleaner
* and faster.
*
* On Feb. 2014, keyword matching was updated to
* use a hash table.
*
* Okay this is kind of messy, but what it boils down
* to is: a graph whose edges are characters, and whose nodes
* are "states", and where egde-crossing deterministically
* leads you to a magic "state-node" that tells you what
* token your little character edge-walk just made up.
* (or if it doesn't then matching failed and it's an error!)
* It was far messier (and slower, etc)
* last year before I spent some time cleaning it up.
*
* Bl0ckeduser, December 2012 - updated Feb. 2014
*/
/*
* XXX: the automatons never get free()d
*/
#include "hashtable.h"
#include "tokenizer.h"
#include "tokens.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "general.h"
#include "diagnostics.h"
hashtab_t *keywords;
int *iptr;
enum {
NOT_INSIDE_A_COMMENT,
INSIDE_A_C_COMMENT,
INSIDE_A_CPP_COMMENT
};
/* ============================================ */
/*
* Result reporting structure for the NFA matcher
*/
typedef struct match_struct {
int success;
/* pointer to last character matched */
char* pos;
/* hash of match */
/*unsigned*/ int hash;
} match_t;
/*
* NFA (compiled pattern) structure
*/
typedef struct nfa_struct {
/* character edges */
struct nfa_struct* map[256];
/* epsilon edge */
struct nfa_struct* link;
/* accept state, if any (0 otherwise) */
int valid_token;
} nfa;
/* ============================================ */
/* "nfa" structure routines */
nfa* new_nfa(void)
{
nfa* t = malloc(sizeof(nfa));
int i;
if (!t)
fail("nfa allocation");
for(i = 0; i < 256; i++)
t->map[i] = NULL;
t->link = NULL;
t->valid_token = 0;
return t;
}
/* ============================================ */
/*
* The wannabe-regex string => NFA compiler
*/
void add_token(nfa* t, char* tok, int key)
{
int i, j;
int c;
nfa *hist[1024];
nfa *next;
int len = strlen(tok);
char* new_tok;
int n;
new_tok = malloc(len + 32);
if (!new_tok)
fail("buffer allocation");
strcpy(new_tok, tok);
for (i = 0, n = 0; c = new_tok[i], i < len && t; ++i)
{
hist[n] = t;
switch (c) {
case 'A': /* set of all letters */
next = new_nfa();
for(j = 'a'; j <= 'z'; j++)
t->map[j] = next;
for(j = 'A'; j <= 'Z'; j++)
t->map[j] = next;
t->map['_'] = next;
t = next;
++n;
break;
case 'B': /* set of all letters
+ all digits */
next = new_nfa();
for(j = 'a'; j <= 'z'; j++)
t->map[j] = next;
for(j = 'A'; j <= 'Z'; j++)
t->map[j] = next;
for(j = '0'; j <= '9'; j++)
t->map[j] = next;
t->map['_'] = next;
t = next;
++n;
break;
case 'D': /* set of all digits */
next = new_nfa();
for(j = '0'; j <= '9'; j++)
t->map[j] = next;
t = next;
++n;
break;
case 'W': /* whitespace */
next = new_nfa();
t->map[' '] = next;
t->map['\t'] = next;
t->map['\r'] = next; /* Macintosh / MS-DOS bullshit */
t = next;
++n;
break;
case '?': /* optional character */
sanity_requires(n > 0);
/*
* The previous node is allowed to
* go straight to this node, via
* an epsilon link.
*/
hist[n - 1]->link = t;
break;
case '*': /* 0 or more reps of a char */
case '+': /* 1 or more reps of a char */
sanity_requires(n > 0);
/*
* Make a new "buffer" node to keep things
* cleanly separated and avoid
* surprises when matching e.g.
* 'a+b+'. Epsilon-link to it.
*/
t->link = hist[++n] = new_nfa();
t = hist[n];
/*
* Repeat all the character edges from
* the node previous to the last character read,
* but this time make them go from the "buffer"
* node back to the node that came after the
* last character read.
*/
for (j = 0; j < 256; ++j)
if (hist[n - 2]->map[j] == hist[n - 1])
t->map[j] = hist[n - 1];
/*
* And finally make a clean
* new node for further work,
* and epsilon-link to it.
*/
t->link = hist[++n] = new_nfa();
t = hist[n];
if (c == '+')
break;
else {
/* make epsilon for the 0-repetitions case in '*' */
hist[n-3]->link = t;
break;
}
case 'Q': /* quotable chars */
next = new_nfa();
for(j = 0; j < 256; j++)
if (j != '"')
t->map[j] = next;
t = next;
++n;
break;
case '.': /* all chars (well, except \n) */
next = new_nfa();
for(j = 0; j < 256; j++)
if (j != '\n')
t->map[j] = next;
t = next;
++n;
break;
case 'N': /* \n */
next = new_nfa();
t->map['\n'] = next;
t = next;
++n;
break;
case '\\': /* escape to normal text */
if (++i == len)
fail("backslash expected char");
c = new_tok[i];
default: /* normal text */
if (!t->map[c])
t->map[c] = new_nfa();
t = t->map[c];
++n;
}
}
free(new_tok);
/*
* We have reached the accept-state node;
* mark it as such.
*/
t->valid_token = key;
}
/*
* wannabe-regex NFA matcher
*/
/*
* nfa* t : matching automaton / current node
* char* full_tok : full text
* char* tok : where we are now
*/
match_t match(nfa* t, char* full_tok, char* tok)
{
int i = 0;
char c;
int prev = -1;
match_t m;
int str_const = 0;
/*unsigned*/ int hash = 0;
/*
* Iterate the matching loop as long as there are
* characters left
*/
while (i <= strlen(tok)) {
/*
* The `c' variable is just being syntax sugar
* for "current character"
*/
c = tok[i];
/*
* HACK to deal with \" in string constants
*/
if (c == '"')
str_const = 1;
if (c == '\\' && str_const) {
i += 2;
continue;
}
/*
* If a character edge for the
* current character exists,
* follow it. Additionally,
* put in a sanity check that
* 0 <= c < 256. Otherwise,
* very strange things can happen.
*/
if (c >= 0 && c < 256 && t->map[c]) {
t = t->map[c];
++i;
/*
* incremental hashing (to spot keywords quickly;
* see later down in the file)
*/
if (prev == -1)
prev = c;
hash = hashtab_hash_char(c, prev, keywords->nbuck, hash);
prev = c;
}
/*
* Otherwise, check for an epsilon edge
* and follow it if it exists
*/
else if (t->link) {
t = t->link;
/*
* Otherwise: no epsilon, no character, no match;
* stop the loop
*/
} else
break;
if (t->valid_token)
break;
}
/*
* Set up the result-report structure
*/
if (t && t->valid_token) {
/* Match succeeded */
m.success = t->valid_token;
m.pos = tok + i;
m.hash = hash;
} else {
/* No match */
m.success = 0;
}
return m;
}
nfa *t[100];
int tc = 0;
/* #define TOK_FAIL(msg) { strcpy(fail_msg, msg); goto fail; } */
token_t* tokenize(char *buf)
{
match_t m;
match_t c;
char buf_2[1024];
char buf2[1024]; /* XXX: assumes no token is >1023 chars */
char fail_msg[1024] = "";
char *p;
char linemark[256];
char *curfile = "";
char *current_linemark = "";
char tokfile[1024];
int linemark_index;
char *substitution;
token_t *sub_toks;
char *old;
int max;
int i;
char *line_start = buf;
token_t *toks = malloc(4096 * sizeof(token_t));
int tok_alloc = 64;
int tok_count = 0;
int comstat = NOT_INSIDE_A_COMMENT;
int lineno = 1;
/*
* Build the keywords hash table
*/
keywords = new_hashtab();
for (i = 0; i < KW_COUNT; ++i) {
iptr = malloc(sizeof(int));
if (!iptr)
fail("couldn't get a few bytes of heap :(");
*iptr = kw_tab[i].tok;
hashtab_insert(keywords, kw_tab[i].str, iptr);
}
/* While there are characters left ... */
for (p = buf; *p;) {
/*
* Choose the matching pattern
* on the code-string from this offset
* that gives the longest match.
* One might observe that
* "shit is meta-greedy",
* because the the pattern-matcher is
* greedy for ambiguities within a
* single given pattern, and now
* this loop is being greedy about
* which pattern to choose.
*/
max = -1; /* clear record length */
old = p;
for (i = 0; i < tc; i++) {
/* try matching pattern number i */
m = match(t[i], buf, p);
/* check if match has succeeded */
if (m.success) {
/* if match length > record length */
if (m.pos - p > max) {
/* update record length to this one */
max = m.pos - p;
/* store this match as the new key */
c = m;
}
}
}
/*
* If inside a C comment, only look for
* comment close tokens. (otherwise some
* patterns will do nasty wrong things)
*/
if (comstat == INSIDE_A_C_COMMENT && m.success != C_CMNT_CLOSE) {
max = -1;
p = old;
}
if (max == -1) {
/*
* Matching from this offset failed
*/
if (comstat != NOT_INSIDE_A_COMMENT) {
/* It's okay to have non-tokens in comments,
* so just go forward and suck it up */
if (*p == '\n') {
++lineno;
line_start = p + 1;
}
++p;
continue;
}
else
/* Not in a comment, so tokenization has really failed */
fail("tokenization failed -- unknown pattern");
} else {
/*
* Matching from this offset has succeeded
*/
/*
* Spot keywords. They are initially
* recognized as identifiers, but we use
* a hash table (and inplace incremental
* hashing in the matching routine, a hack
* to save time) to discriminate them from
* identifiers.
*
* The same method is now used for preprocessor
* defines.
*/
if (c.success == TOK_IDENT) {
strncpy(buf2, p, max);
buf2[max] = 0;
/* keywords */
if ((iptr = hashtab_lookup_with_hash(keywords, buf2, c.hash)))
c.success = *iptr;
}
/*
* Line marks
*/
if (c.success == TOK_LINEMARK) {
p += max + 1;
linemark_index = 0;
while (*p && *p != '\n')
linemark[linemark_index++] = *p++;
linemark[linemark_index] = 0;
if (*p == '\n')
++p;
line_start = p;
sscanf(linemark, "%s %d", tokfile, &lineno);
curfile = my_strdup(tokfile);
continue;
}
/*
* And now: comment stuff
*/
/*
* Open a C comment if not already in one
*/
if (c.success == C_CMNT_OPEN) {
if (comstat == INSIDE_A_C_COMMENT)
fail("Please do not nest C comments");
comstat = INSIDE_A_C_COMMENT;
/*
* C comment closes are allowed if a C comment
* has already been opened
*/
} else if (c.success == C_CMNT_CLOSE) {
if (comstat == INSIDE_A_C_COMMENT) {
comstat = NOT_INSIDE_A_COMMENT;
goto advance;
} else {
fail("Dafuq is a */ doing there ?");
}
/*
* Start a C++ comment, unless already in a C comment
* (the string // inside a C comment is legal)
*/
} else if (c.success == CPP_CMNT) {
if (comstat != INSIDE_A_C_COMMENT)
comstat = INSIDE_A_CPP_COMMENT;
}
/*
* C++ comments end at the end of their line
*/
if (comstat == INSIDE_A_CPP_COMMENT
&& c.success == TOK_NEWLINE) {
comstat = NOT_INSIDE_A_COMMENT;
goto advance;
}
/*
* Add token to the tokens array
* if it's not inside a comment
* and it's not useless whitespace
*/
if (c.success != TOK_WHITESPACE
&& c.success != TOK_NEWLINE
&& comstat == NOT_INSIDE_A_COMMENT) {
/* Expand token array if necessary */
if (++tok_count >= tok_alloc) {
tok_alloc = tok_count + 64;
toks = realloc(toks,
tok_alloc * sizeof(token_t));
if (!toks)
fail("resize tokens array");
}
/*
* Build the token pointer stuff,
* and also add a bunch of debug tracing
* crap
*/
toks[tok_count - 1].type = c.success;
toks[tok_count - 1].start = p;
toks[tok_count - 1].len = max;
toks[tok_count - 1].lineptr = line_start;
toks[tok_count - 1].from_line = lineno;
toks[tok_count - 1].from_file = curfile;
toks[tok_count - 1].from_char = p -
line_start + 1;
}
if (c.success == TOK_NEWLINE) {
++lineno;
sprintf(buf_2, "%s:%d", tokfile, lineno);
current_linemark = my_strdup(buf_2);
line_start = p + 1;
}
advance:
/*
* Move forward in the string by the length
* of the match, or otherwise by 1 character
*/
p += max;
if (max == 0)
++p;
}
}
/* the final token is a bit special */
toks[tok_count].start = NULL;
toks[tok_count].len = 0;
toks[tok_count].from_line = lineno;
toks[tok_count].from_file = curfile;
toks[tok_count].lineptr = line_start;
toks[tok_count].from_char = p - line_start;
return toks;
fail:
compiler_fail(fail_msg,
NULL,
lineno, p - line_start + 1);
}
/*
* Set up the wannabe-regex automatons
* that match the various tokens. Maybe
* this could be rewritten as an array
* initializer...
*/
void setup_tokenizer(void)
{
int i = 0;
tc = 3;
for (i = 0; i < 3; ++i)
t[i] = new_nfa();
/*
* there are two NFAs: t[0] and t[1].
* this separation is required because
* the NFA compiler and matcher can't
* deal with ambiguities such as '&'
* vs. '&&', so e.g. '&' would go t[0]
* and '&&' in t[1], and then the main
* matching loop would choose the longest
* match between t[0] and t[1].
* Ideally, I should come up with some kind
* of automatic way of solving this kind of thing.
* Anyway, this like 10x faster than one NFA
* per token !
*
* Not sure how space efficient this is
* ("mildly" I guess. surely the upper bound is a few
* megabytes, which is not *so* bad in 2013)
*
* Update Oct 2013: now there's three of them
*/
/* D: any digit; B: letter or digit */
add_token(t[0], "0D+", TOK_OCTAL_INTEGER);
add_token(t[1], "0xB+", TOK_HEX_INTEGER);
add_token(t[1], "0XB+", TOK_HEX_INTEGER);
add_token(t[2], "D+", TOK_INTEGER);
/* W: any whitespace character */
add_token(t[0], "W+", TOK_WHITESPACE);
/*
* Preprocessor directive.
* Maybe I could instead have a pattern
* for each directive or whatever,
* e.g. maybe something like
* "#defineW*AB*W*.*N" for defines
*/
add_token(t[1], "@linemark", TOK_LINEMARK);
/* A: letter; B: letter or digit */
add_token(t[0], "AB*", TOK_IDENT);
/* operators */
add_token(t[0], "\\+", TOK_PLUS);
add_token(t[0], "-", TOK_MINUS);
add_token(t[0], "/", TOK_DIV);
add_token(t[0], "\\*", TOK_MUL);
add_token(t[0], "=", TOK_ASGN);
add_token(t[1], "==", TOK_EQ);
add_token(t[0], ">", TOK_GT);
add_token(t[0], "<", TOK_LT);
add_token(t[1], ">=", TOK_GTE);
add_token(t[1], "<=", TOK_LTE);
add_token(t[2], "<<", TOK_LSHIFT);
add_token(t[2], ">>", TOK_RSHIFT);
add_token(t[1], "!=", TOK_NEQ);
add_token(t[1], "\\+=", TOK_PLUSEQ);
add_token(t[1], "-=", TOK_MINUSEQ);
add_token(t[1], "/=", TOK_DIVEQ);
add_token(t[1], "\\*=", TOK_MULEQ);
add_token(t[1], "\\+\\+", TOK_PLUSPLUS);
add_token(t[1], "--", TOK_MINUSMINUS);
add_token(t[0], "%", TOK_MOD);
add_token(t[0], "&", TOK_ADDR);
add_token(t[1], "&&", TOK_CC_AND);
add_token(t[2], "&=", TOK_BAND_EQ);
add_token(t[1], "%=", TOK_MODEQ);
add_token(t[0], "||", TOK_CC_OR);
add_token(t[1], "|", TOK_PIPE);
add_token(t[2], "|=", TOK_BOR_EQ);
add_token(t[0], "!", TOK_CC_NOT);
add_token(t[0], "\\.", TOK_DOT);
add_token(t[1], "->", TOK_ARROW);
add_token(t[0], "\\?", TOK_QMARK);
add_token(t[0], "\\^", TOK_CARET);
add_token(t[1], "\\^=", TOK_BXOR_EQ);
/* special characters */
add_token(t[0], "{", TOK_LBRACE);
add_token(t[0], "}", TOK_RBRACE);
add_token(t[0], "(", TOK_LPAREN);
add_token(t[0], ")", TOK_RPAREN);
add_token(t[0], ";", TOK_SEMICOLON);
add_token(t[0], ",", TOK_COMMA);
add_token(t[0], "\n", TOK_NEWLINE);
add_token(t[0], ":", TOK_COLON);
add_token(t[0], "[", TOK_LBRACK);
add_token(t[0], "]", TOK_RBRACK);
/* comments */
add_token(t[2], "/\\*", C_CMNT_OPEN);
add_token(t[2], "\\*/", C_CMNT_CLOSE);
add_token(t[2], "//", CPP_CMNT);
/* string constants */
add_token(t[0], "\"Q*\"", TOK_STR_CONST);
/* character constant with an escape in it */
add_token(t[0], "'\\\\.'", TOK_CHAR_CONST_ESC);
/* character constant */
add_token(t[1], "'.'", TOK_CHAR_CONST);
}
| 2.390625 | 2 |
2024-11-18T20:57:36.355511+00:00
| 2018-05-23T06:55:18 |
d188479eb64422c451893e4c8139b336730fcb85
|
{
"blob_id": "d188479eb64422c451893e4c8139b336730fcb85",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-23T06:55:18",
"content_id": "9509f314e48d702b6e7428787ebf7afc8c3a0907",
"detected_licenses": [
"MIT"
],
"directory_id": "2bc3398063fd7251c46a2d93d2e301cd063befcd",
"extension": "c",
"filename": "zigai-jian.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 134525191,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4905,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/kungfu/skill/zigai-jian.c",
"provenance": "stackv2-0064.json.gz:68948",
"repo_name": "HKMUD/NT6",
"revision_date": "2018-05-23T06:55:18",
"revision_id": "bb518e2831edc6a83d25eccd99271da06eba8176",
"snapshot_id": "ae6a3c173ea07c156e8dc387b3ec21f3280ee0be",
"src_encoding": "GB18030",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/HKMUD/NT6/bb518e2831edc6a83d25eccd99271da06eba8176/nitan/kungfu/skill/zigai-jian.c",
"visit_date": "2020-03-18T08:44:12.400598"
}
|
stackv2
|
#include <ansi.h>
inherit SKILL;
mapping *action = ({
([ "action" : "$N左晃右蹿,手中$w突然刺向$n$l,正是一招「峰回路转」",
"force" : 45,
"dodge" : 20,
"parry" : 20,
"attack" : 10,
"damage" : 20,
"lvl" : 0,
"damage_type" : "刺伤",
"skill_name" : "峰回路转",
]),
([ "action" : "$N越攻越猛,突然间手中$w剑光暴涨,一招「姹紫嫣红」已然使出\n"
"$n只觉眼前剑光耀眼,不由得心中一惊",
"force" : 90,
"dodge" : 26,
"parry" : 40,
"attack" : 24,
"damage" : 35,
"lvl" : 25,
"damage_type" : "刺伤",
"skill_name" : "姹紫嫣红",
]),
([
"action" : "$N以攻为守,以进为退,手中$w刷的一剑「蜻蜓点水」,向$n$l刺去",
"force" : 110,
"dodge" : 35,
"parry" : 40,
"attack" : 30,
"damage" : 40,
"lvl" : 50,
"damage_type": "刺伤",
"skill_name": "蜻蜓点水",
]),
([
"action" : "$N轻啸一声,$w径直向$n$w,这一剑虽无任何招式,但是$N却使得不\n"
"卑不亢,毫无滞带,将「千山暮雪」这一招发挥到了及至",
"force" : 120,
"dodge" : 48,
"parry" : 45,
"attack" : 35,
"damage" : 48,
"lvl" : 75,
"damage_type" : "刺伤",
"skill_name" : "千山暮雪",
]),
([
"action" : "$N将$w一挥,长啸一声,腾空而起,使出一式「鹤翔紫盖」!这一招来得又\n"
"快又准,$w直指$n$l,",
"force" : 160,
"dodge" : 82,
"parry" : 66,
"attack" : 55,
"damage" : 60,
"lvl" : 100,
"damage_type" : "刺伤",
"skill_name" : "鹤翔紫盖",
]),
});
string main_skill()
{
return "wushen-jian";
}
int valid_learn(object me)
{
object ob;
if (me->query_skill("wushen-jian", 1) > 0)
return notify_fail("你已演练合成了衡山五神剑,不必再单独学习。\n");
if( !(ob=query_temp("weapon", me) )
|| query("skill_type", ob) != "sword" )
return notify_fail("你必须先找一把剑才能练剑法。\n");
if( query("max_neili", me)<300 )
return notify_fail("你的内力不够,没有办法练紫盖剑法。\n");
if ((int)me->query_skill("force") < 100)
return notify_fail("你的内功火候太浅。\n");
if ((int)me->query_skill("sword", 1) < 60)
return notify_fail("你的基本剑法火候不够,无法学习紫盖剑法。\n");
if (me->query_skill("sword", 1) < me->query_skill("zigai-jian", 1))
return notify_fail("你的基本剑法火候有限,无法领会更高深的紫盖剑法。\n");
return 1;
}
int valid_enable(string usage)
{
return usage == "sword" || usage == "parry";
}
string query_skill_name(int level)
{
int i;
for (i = sizeof(action) - 1; i >= 0; i--)
if (level >= action[i]["lvl"])
return action[i]["skill_name"];
}
mapping query_action(object me, object weapon)
{
int i, level;
level = (int) me->query_skill("zigai-jian", 1);
for (i = sizeof(action); i > 0; i--)
if (level > action[i - 1]["lvl"])
return action[NewRandom(i, 20, level / 5)];
}
int practice_skill(object me)
{
object weapon;
if( !objectp(weapon=query_temp("weapon", me) )
|| query("skill_type", weapon) != "sword" )
return notify_fail("你使用的武器不对。\n");
if( query("neili", me)<60 )
return notify_fail("你的内力不足,没有办法练习紫盖剑法。\n");
if( query("qi", me)<65 )
return notify_fail("你的体力不够练紫盖剑法。\n");
me->receive_damage("qi", 40);
addn("neili", -50, me);
return 1;
}
string perform_action_file(string action)
{
return __DIR__"zigai-jian/" + action;
}
void skill_improved(object me)
{
int lvl;
lvl = me->query_skill("zigai-jian", 1);
if( lvl > 120 &&
!query("can_perform/zigai-jian/hui", me) )
{
tell_object(me, WHT "你通晓了紫盖剑法「" HIC "紫盖回翔" WHT "」的奥秘。\n" NOR);
set("can_perform/zigai-jian/hui", 1, me);
me->improve_skill("martial-cognize", 1500000);
me->improve_skill("martial-cognize", 1500000);
me->improve_skill("martial-cognize", 1500000);
}
}
| 2.0625 | 2 |
2024-11-18T20:57:36.791444+00:00
| 2018-03-19T08:32:48 |
3fed570242a38fbc542c91ad1508ceb0c8fab383
|
{
"blob_id": "3fed570242a38fbc542c91ad1508ceb0c8fab383",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-19T08:32:48",
"content_id": "fae699ef6f76134deaf4453045c1f19dd8cd26f3",
"detected_licenses": [
"MIT"
],
"directory_id": "1980e0d73be49b6a26245e003130df9227267795",
"extension": "c",
"filename": "photon.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 32915587,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 357,
"license": "MIT",
"license_type": "permissive",
"path": "/photon.c",
"provenance": "stackv2-0064.json.gz:69076",
"repo_name": "woufrous/coton",
"revision_date": "2018-03-19T08:32:48",
"revision_id": "2cc7e298b37c31735813fad1389ebad191df562b",
"snapshot_id": "bbd896375340c0633165904432209c0b12278171",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/woufrous/coton/2cc7e298b37c31735813fad1389ebad191df562b/photon.c",
"visit_date": "2021-01-02T22:58:00.646056"
}
|
stackv2
|
#include "photon.h"
#include <stdlib.h>
Photon* new_Photon(Vec3D* pos, Vec3D* dir, double tau_r)
{
Photon* ret;
ret = (Photon*)malloc(sizeof(Photon));
ret->pos = (Vec3D*)malloc(sizeof(Vec3D));
*(ret->pos) = *pos;
ret->dir = (Vec3D*)malloc(sizeof(Vec3D));
*(ret->dir) = *dir;
ret->tau_r = tau_r;
ret->weight = 1.0;
ret->n_scat = 0;
return ret;
}
| 2.015625 | 2 |
2024-11-18T20:57:36.884601+00:00
| 2013-09-14T08:14:08 |
63199662dc83013ff1a2f5286875f055e6406d39
|
{
"blob_id": "63199662dc83013ff1a2f5286875f055e6406d39",
"branch_name": "refs/heads/master",
"committer_date": "2013-09-14T08:14:08",
"content_id": "93c26f40709e3ad66f8600e3f81d1fe5d993542e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "3a6018a0c82dc39c4e513da40dcd8cf5b1d23089",
"extension": "cc",
"filename": "10999788_AC_0MS_372K.cc",
"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": 561,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/emperorlu/1004/10999788_AC_0MS_372K.cc",
"provenance": "stackv2-0064.json.gz:69204",
"repo_name": "lulyon/poj-archive",
"revision_date": "2013-09-14T08:14:08",
"revision_id": "7ba5569d1780f8619621bc8b1adc0501b0d7ec51",
"snapshot_id": "2ff04082ff70e0afc997c7a49d23d3d31ce3ddbe",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lulyon/poj-archive/7ba5569d1780f8619621bc8b1adc0501b0d7ec51/emperorlu/1004/10999788_AC_0MS_372K.cc",
"visit_date": "2020-06-01T23:29:51.532319"
}
|
stackv2
|
/*************************************************************************
> File Name: 1004.cpp
> Author: luliang
> Mail: lulyon@126.com
> Created Time: 2012年11月09日 星期五 13时32分56秒
************************************************************************/
#include<stdio.h>
#define MONTH 12
float salary[MONTH + 1];
int main(void)
{
for(int i = 1; i <= MONTH; ++i)
scanf("%f", &salary[i]);
float sum = 0;
for(int i = 1; i <= MONTH; ++i)
sum += salary[i];
printf("$%.2f\n", sum / MONTH);
return 0;
}
| 2.90625 | 3 |
2024-11-18T20:57:37.235035+00:00
| 2023-08-11T13:02:43 |
e32862a10141538bf5e799c5346b3bf79e49d6fa
|
{
"blob_id": "e32862a10141538bf5e799c5346b3bf79e49d6fa",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-11T13:02:43",
"content_id": "c13fe28fe115d3912e73d0c1fabc9ecf084af671",
"detected_licenses": [
"MIT"
],
"directory_id": "751d837b8a4445877bb2f0d1e97ce41cd39ce1bd",
"extension": "c",
"filename": "a-bit-of-a-digital-xor.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115886967,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4349,
"license": "MIT",
"license_type": "permissive",
"path": "/codegolf/a-bit-of-a-digital-xor.c",
"provenance": "stackv2-0064.json.gz:69461",
"repo_name": "qeedquan/challenges",
"revision_date": "2023-08-11T13:02:43",
"revision_id": "56823e77cf502bdea68cce0e1221f5add3d64d6a",
"snapshot_id": "d55146f784a3619caa4541ac6f2b670b0a3dd8ba",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/qeedquan/challenges/56823e77cf502bdea68cce0e1221f5add3d64d6a/codegolf/a-bit-of-a-digital-xor.c",
"visit_date": "2023-08-11T20:35:09.726571"
}
|
stackv2
|
/*
Here are the first 100 numbers of a sequence:
1,2,33,4,55,66,777,8,99,11,111,12,133,141,1515,1,11,18,191,22,222,222,2232,24,252,266,2772,282,2922,3030,31313,3,33,33,335,36,377,383,3939,44,441,444,4443,444,4455,4464,44747,48,499,505,5151,522,5333,5445,55555,565,5757,5855,59559,6060,61611,62626,636363,6,66,66,676,66,666,770,7717,72,737,744,7557,767,7777,7878,79797,88,888,882,8838,888,8888,8886,88878,888,8898,9900,99119,9929,99399,99494,995959,96,979,988,9999,100
How does this sequence work?
n: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
binary: 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001
n extended: 1 22 33 444 555 666 777 8888 9999 1010 1111 1212 1313 1414 1515 16161 17171
1-bit digits: 1 2 33 4 5 5 66 777 8 9 9 1 1 1 11 12 13 3 141 1515 1 1 1
result: 1 2 33 4 55 66 777 8 99 11 111 12 133 141 1515 1 11
As you can see, the steps to get the output are as follows:
Convert integer n to a binary-string.
Extend integer n to the same length as this binary-string. (I.e. n=17 is 10001 in binary, which has a length of 5. So we extend the 17 to this same length of 5 by cycling it: 17171.)
Only keep the digits in the extended integer n at the positions of the 1s in the binary-string.
Join them together to form an integer†.
Challenge:
One of these options:
Given an integer n, output the nth number in the sequence.
Given an integer n, output the first n numbers of this sequence.
Output the sequence indefinitely without taking an input (or by taking an empty unused input).
Challenge rules:
†Step 4 isn't mandatory to some extent. You're also allowed to output a list of digits, but you aren't allowed to keep the falsey-delimiter. I.e. n=13 resulting in [1,3,3] or "1,3,3" instead of 133 is fine, but "13 3", [1,3,false,3], [1,3,-1,3], etc. is not allowed.
Although I don't think it makes much sense, with option 1 you are allowed to take a 0-based index m as input and output the (m+1)th value.
If you output (a part of) the sequence (options 2 or 3), you can use a list/array/stream; print to STDOUT with any non-digit delimiter (space, comma, newline, etc.); etc. Your call. If you're unsure about a certain output-format, feel free to ask in the comments.
Please state which of the three options you've used in your answer.
The input (with options 1 and 2) is guaranteed to be positive.
You'll have to support at least the first [1,10000] numbers. n=...,9998,9999,10000] result in ...,9899989,99999999,10010] (the largest output in terms of length within this range is n=8191→8191819181918).
General rules:
This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.
PS: For the 05AB1E code-golfers among us, 4 bytes is possible.
*/
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define nelem(x) (sizeof(x) / sizeof(x[0]))
unsigned
digitalxor(unsigned n)
{
unsigned b, i, l, r;
char s[128];
b = 1;
while (n / b)
b *= 2;
r = 0;
for (i = 0; b /= 2; i++) {
if (b & n) {
l = snprintf(s, sizeof(s), "%u", n);
r = (r * 10) + (s[i % l] - '0');
}
}
return r;
}
int
main(void)
{
static const unsigned tab[] = {1, 2, 33, 4, 55, 66, 777, 8, 99, 11, 111, 12, 133, 141, 1515, 1, 11, 18, 191, 22, 222, 222, 2232, 24, 252, 266, 2772, 282, 2922, 3030, 31313, 3, 33, 33, 335, 36, 377, 383, 3939, 44, 441, 444, 4443, 444, 4455, 4464, 44747, 48, 499, 505, 5151, 522, 5333, 5445, 55555, 565, 5757, 5855, 59559, 6060, 61611, 62626, 636363, 6, 66, 66, 676, 66, 666, 770, 7717, 72, 737, 744, 7557, 767, 7777, 7878, 79797, 88, 888, 882, 8838, 888, 8888, 8886, 88878, 888, 8898, 9900, 99119, 9929, 99399, 99494, 995959, 96, 979, 988, 9999, 100};
unsigned i;
for (i = 0; i < nelem(tab); i++)
assert(digitalxor(i + 1) == tab[i]);
return 0;
}
| 3.109375 | 3 |
2024-11-18T20:57:37.393149+00:00
| 2014-11-10T20:55:58 |
5d8f8c229c50543c833aa64c34ccbb4e74952da9
|
{
"blob_id": "5d8f8c229c50543c833aa64c34ccbb4e74952da9",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-10T20:55:58",
"content_id": "e71ef3e80074b3be5d35796b582caec36639cae8",
"detected_licenses": [
"MIT"
],
"directory_id": "8752214e539dd4a876a301a0e741f7b6ad593206",
"extension": "c",
"filename": "a2.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": 8118,
"license": "MIT",
"license_type": "permissive",
"path": "/src/com/exikle/c/a2.c",
"provenance": "stackv2-0064.json.gz:69717",
"repo_name": "Exikle/Snippets",
"revision_date": "2014-11-10T20:55:58",
"revision_id": "a761b10951d966f5ca7cd883fd6088293e5ebab6",
"snapshot_id": "e8a2999fd5cf6ddde92489965c5b13755b615d40",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Exikle/Snippets/a761b10951d966f5ca7cd883fd6088293e5ebab6/src/com/exikle/c/a2.c",
"visit_date": "2021-01-19T16:59:22.883085"
}
|
stackv2
|
/*************************a2.c****************************
Student Name: Dickson D'Cunha Student Number: 0904177
Date: 09/29/14 Course Name: CIS*1500_F14
I have exclusive control over this submission via my password.
By including this statement in this header comment, I certify that:
1) I have read and understood the University policy on academic integrity;
2) I have completed the Computing with Integrity Tutorial on Moodle; and
3) I have achieved at least 80% in the Computing with Integrity Self Test.
I assert that this work is my own. I have appropriately acknowledged any and all material
(data, images, ideas or words) that I have used, whether directly quoted or paraphrased.
Furthermore, I certify that this assignment was prepared by me specifically for this course.
****************************************************************************/
/*******************
Game must be able too play with these combinations.
Scissors cuts paper.
Paper covers rock.
Rock crushes lizard.
Lizard poisons Spock.
Spock smashes scissors.
Scissors decapitates lizard.
Lizard eats paper.
Paper disproves Spock.
Spock vaporizes rock.
Rock crushes scissors.
Needs to ask which game mode they want to play
1. rock-paper-scissors
2. rock-paper-scissors-lizard-Spock
Check how many times player wants to play(loop, duh)
For each loop (req decision statements )
..............
prompt the player for a numerical equivalent to rock-1, paper-2, sissors-3, (lizard-4, Spock-5)
int x;
srand(time(NULL));
x = (rand() % 3) + 1; OR x = (rand() % 5) + 1; (for lizard and spock)
Check who wins, count/ record the number
If loop finished, display statistics (wins ofr player, wins for computer, ties)
else LOOOOOP again
Sample Output ------------------------------------>
This program allows you to play Rock, Paper, Scissors
How many games do you want? 2
Game number 1
3=Rock, 2=Scissors, 1=Paper
What's your choice? 1
My choice is paper
Tie game - no winner
Game number 2
3=Rock, 2=Scissors, 1=Paper
What's your choice? 3
My choice is scissors
You win!!
Here is the final score
I have won 0 game(s),
you have won 1 game(s)
and 1 games ended in a tie
Thanks for playing!
*************************/
#include <stdlib.h>
#include <time.h>
int main()
{
int timesToLoop=0; //Amount of games to play
int playerScore=0; //Amount of times player won
int compScore=0; //Amount of times comp won
int tieCount=0; //Amount of times won
int playerChoice=0; //Which choice the player chose
int compChoice=0; //Which choice did the comp get
int gameType=0; // 1 - Regular, 2 - Big Bang Version
do
{
printf("What type of game would you like to play?\nRegular rock-paper-scissors = 1 OR rock-paper-scissors-lizard-Spock = 2\n");
scanf("%d", &gameType); //Gets players choice for game type
}while(gameType==0 || gameType>=3);
printf("How many times would you like to play? ");
scanf("%d", ×ToLoop); //Gets players choice for game type
for (int i=0;i<timesToLoop;i++)//Number of rounds - loop
{
//reset variables
playerChoice=0;
compChoice=0;
printf("\n");
printf("Game %d\n",i+1);
switch(gameType)
{
case 1:
do //repeats till player chooses the right number in range
{
printf("3=Rock, 2=Scissors, 1=Paper\n");
printf("Whats your choice? ");
scanf("%d", &playerChoice); //Gets players choice for game type
} while(playerChoice==0 || playerChoice>=4);
break;
case 2:
do //repeats till player chooses the right number in range
{
printf("5=Spock, 4=Lizard, 3=Rock, 2=Scissors, 1=Paper\n");
printf("Whats your choice? ");
scanf("%d", &playerChoice); //Gets players choice for game type
} while(playerChoice==0 || playerChoice>=6);
break;
}
printf("What I chose was ");
switch(gameType)
{
case 1:
srand(time(NULL));
compChoice = (rand() % 3) + 1;
break;
case 2:
srand(time(NULL));
compChoice = (rand() % 5) + 1;
break;
}
switch(compChoice)
{
case 1: printf("Paper.\n");
break;
case 2: printf("Scissors.\n");
break;
case 3: printf("Rock.\n");
break;
case 4: printf("Lizard.\n");
break;
case 5: printf("Spock.\n");
break;
}
printf("CALCULATING WINNER.\n"); //check who wins
if(playerChoice == 1) //Paper
{
switch(compChoice)
{
case 1: //Paper
printf("Tie game - no winner\n");
tieCount+=1;
break;
case 2: //Scissors
printf("Scissors cuts paper\nYou Lose...\n");
compScore+=1;
break;
case 3: //Rock
printf("Paper covers rock\nYou Win!!!!\n");
playerScore+=1;
break;
case 4: //Lizard
printf("Lizard eats Paper\nYou Lose...\n");
compScore+=1;
break;
case 5: //Spock
printf("Paper disproves Spock\nYou Win!!!!\n");
playerScore+=1;
break;
}
}
else if(playerChoice == 2) //Scissors
{
switch(compChoice)
{
case 1: //Paper
printf("Scissors cuts paper\nYou win!!!\n");
playerScore+=1;
break;
case 2: //Scissors
printf("Tie game - no winner\n");
tieCount+=1;
break;
case 3: //Rock
printf("Rock crushes scissors\nYou Lose...\n");
compScore+=1;
break;
case 4: //Lizard
printf("Scissors decapitates lizard\nYou Win!!!\n");
playerScore+=1;
break;
case 5: //Spock
printf("Spock smashes scissors\nYou lose...\n");
compScore+=1;
break;
}
}
else if(playerChoice == 3) //Rock
{
switch(compChoice)
{
case 1: //Paper
printf("Paper covers rock\nYou lose...\n");
compScore+=1;
break;
case 2: //Scissors
printf("Rock crushes scissors\nYou Win!!\n");
playerScore+=1;
break;
case 3: //Rock
printf("Tie game - no winner\n");
tieCount+=1;
break;
case 4: //Lizard
printf("Rock crushes lizard\nYou Lose...\n");
compScore+=1;
break;
case 5: //Spock
printf("Spock vaporizes rock\nYou lose...\n");
compScore+=1;
break;
}
}
else if(playerChoice == 4) //Lizard
{
switch(compChoice)
{
case 1: //Paper
printf("Lizard eats paper\nYou Win!!!!\n");
playerScore+=1;
break;
case 2: //Scissors
printf("Scissors decapitates Lizard\nYou lose...\n");
compScore+=1;
break;
case 3: //Rock
printf("Rock crushes lizard\nYou lose...\n");
compScore+=1;
break;
case 4: //Lizard
printf("Tie game - no winner\n");
tieCount+=1;
break;
case 5: //Spock
printf("Lizard poisons Spock\nYou win!!!\n");
playerScore+=1;
break;
}
}
else if(playerChoice == 5) //Spock
{
switch(compChoice)
{
case 1: //Paper
printf("Paper disproves Spock\nYou lose...\n");
compScore+=1;
break;
case 2: //Scissors
printf("Spock crushes scissors\nYou win!!!\n");
playerScore+=1;
break;
case 3: //Rock
printf("Spock vaporizes rock\nYou win!!!\n");
playerScore+=1;
break;
case 4: //Lizard
printf("Lizard poisons Spock\nYou lose!!!\n");
compScore+=1;
break;
case 5: //Spock
printf("Tie game - no winner\n");
tieCount+=1;
break;
}
}
}//Loops ends here
printf("\nHere is the final score\n");
printf("I have won %d game(s).\n", compScore);
printf("You have won %d game(s).\n", playerScore);
printf("We have tied %d game(s)\n", tieCount);
printf("Thanks for playing!\n");
return 0;
}
<<<<<<< HEAD
//possibly create a method to calculate the winner, probably will remove lots of code redundancy
=======
//possibly create a method to calculate the winner, probably will remove lots of code redundancy
>>>>>>> origin/master
| 2.765625 | 3 |
2024-11-18T20:57:37.571653+00:00
| 2023-08-10T04:39:39 |
874dd1355c55e7c74d10cf9fa7bd8f824d8a801d
|
{
"blob_id": "874dd1355c55e7c74d10cf9fa7bd8f824d8a801d",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T17:49:20",
"content_id": "64ce13938f09b91d906dab539ea1960d604a810c",
"detected_licenses": [
"MIT"
],
"directory_id": "cee92c2ef49a141806d48304c463a9e010b5fa21",
"extension": "c",
"filename": "coloranim.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 15328285,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7528,
"license": "MIT",
"license_type": "permissive",
"path": "/rgblamp/coloranim/coloranim.c",
"provenance": "stackv2-0064.json.gz:69975",
"repo_name": "dreamlayers/gadgets",
"revision_date": "2023-08-10T04:39:39",
"revision_id": "11d10edbacd1cfd13ad0dea5c3aa3d1d64ef1b9f",
"snapshot_id": "3ef9a52dc63f573cf2a3f8ebb80dd09c3e02dfa9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dreamlayers/gadgets/11d10edbacd1cfd13ad0dea5c3aa3d1d64ef1b9f/rgblamp/coloranim/coloranim.c",
"visit_date": "2023-08-30T00:48:03.831335"
}
|
stackv2
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include "coloranim.h"
static pixel temp_pix = NULL, cur_pix = NULL;
void fatal(const char *s) __attribute__ ((noreturn));
void fatal(const char *s)
{
fprintf(stderr, "Fatal error: %s\n", s);
exit(-1);
}
void *safe_malloc(unsigned int l)
{
void *p = malloc(l);
if (p == NULL) fatal("out of memory");
return p;
}
/* --- Timing section --- */
/* From https://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html */
static int
timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
static struct timeval starttime;
static void stopwatch_start(void) {
gettimeofday(&starttime, NULL);
}
static double stopwatch_elapsed(void) {
struct timeval thistime;
gettimeofday(&thistime, NULL);
struct timeval deltatv;
if (timeval_subtract(&deltatv, &thistime, &starttime) == 0) {
return deltatv.tv_sec + (double)deltatv.tv_usec / 1000000.0;
} else {
return 0.0;
}
}
pixel pix_alloc(void) {
pixel res = safe_malloc(sizeof(double) * COLORCNT * PIXCNT);
return res;
}
void pix_clear(pixel pix) {
int i;
for (i = 0; i < COLORCNT * PIXCNT; i++) {
pix[i] = 0.0;
}
}
void pix_free(pixel *p) {
if (*p != NULL) {
free(*p);
*p = NULL;
}
}
static void pix_copy(pixel dst, pixel src) {
memcpy(dst, src, sizeof(double) * COLORCNT * PIXCNT);
}
#ifdef DEBUG
static void pix_print(pixel pix) {
unsigned int i, j;
for (i = 0; i < PIXCNT; i++) {
DEBUG_PRINT("%u: ", i);
for (j = 0; j < COLORCNT; j++) {
DEBUG_PRINT("%f, ", pix[i * COLORCNT + j]);
}
DEBUG_PRINT("\n");
}
}
#endif /* DEBUG */
/* p = idx / (len - 1) */
static inline double interp_one(double a, double b, double p)
{
return a * (1.0 - p) + b * p;
}
static void interp_fade(const pixel a, const pixel b, double p, pixel r)
{
unsigned int i, cnt = COLORCNT * PIXCNT;
for (i = 0; i < cnt; i++) {
r[i] = interp_one(a[i], b[i], p);
}
}
#if PIXCNT > 1
static int interp_gradient(const pixel a, const pixel b, pixel r)
{
unsigned int i, j;
for (i = 0; i < COLORCNT; i++) {
if (a[i] < 0 || b[i] < 0) {
return -1;
}
}
for (i = 0; i < (PIXCNT * 3); i += 3) {
for (j = 0; j < COLORCNT; j++) {
r[i + j] = interp_one(a[j], b[j],
(double)i / (PIXCNT * 3 - 3));
}
}
return 0;
}
#endif
static void fx_fill(const pixel last_pix, const pixel clr,
pixel dest, int count)
{
unsigned int i, j, end = count * 3;
for (i = 0; i < end; i += 3) {
for (j = 0; j < COLORCNT; j++) {
dest[i + j] = (clr[j] >= 0.0) ? clr[j] : last_pix[i + j];
}
}
}
int fx_makestate(const pixel colorspec, const keyword *colorkw,
unsigned int numspec,
const pixel last_pix, pixel dest)
{
switch (colorkw[0]) {
case KW_NONE:
if (numspec == 1) {
fx_fill(&last_pix[0], &colorspec[0], dest, PIXCNT);
} else {
return -1; /* color keyword expected */
}
break;
#if PIXCNT > 1
case KW_GRADIENT:
if (numspec == 2) {
return interp_gradient(&colorspec[0], &colorspec[COLORCNT], dest);
} else {
return -1; /* multiple point gradient unimplemented */
}
break;
case KW_SOLID:
if (numspec == 2) {
fx_fill(&last_pix[0], &colorspec[0], &dest[0], PIXCNT / 2);
fx_fill(&last_pix[COLORCNT], &colorspec[COLORCNT],
&dest[(PIXCNT / 2) * COLORCNT], PIXCNT - PIXCNT / 2);
} else {
return -1; /* multiple point gradient unimplemented */
}
break;
#endif
default:
return -1; /* bad color keyword */
break;
}
return 0;
}
static int fx_crossfade(const pixel oldclr, const pixel newclr,
double seconds)
{
#ifdef PWR_TMOUT
/* Make sure power is on because turning it on takes some time */
render_power(1);
#endif
stopwatch_start();
while (1) {
double t;
t = stopwatch_elapsed();
if (t >= seconds) {
render(newclr);
return 1;
} else {
interp_fade(oldclr, newclr, t / seconds, temp_pix);
/* pix_print(cross); */
render(temp_pix);
}
if (cmd_cb_pollquit()) {
return 0;
}
}
}
static int fx_wait(double seconds)
{
stopwatch_start();
while (1) {
double t;
t = seconds - stopwatch_elapsed();
if (t <= 0) {
/* Wait completed */
return 1;
} else {
#define MAX_SLEEP 10000
if (t > MAX_SLEEP / 1000000) {
usleep(MAX_SLEEP);
} else {
usleep(t * 1000000);
}
}
if (cmd_cb_pollquit()) {
/* Wait interrupted */
return 0;
}
}
}
void coloranim_init(void)
{
temp_pix = pix_alloc();
cur_pix = pix_alloc();
render_get(cur_pix);
}
void coloranim_quit(void)
{
pix_free(&temp_pix);
pix_free(&cur_pix);
}
void coloranim_exec(struct coloranim *ca)
{
pixel last_pix = cur_pix;
struct coloranim_state *state = ca->states;
double fade = ca->first_fade;
pixel save_pix = NULL;
int ntfy = 1;
if (state == NULL) fatal("no states in animation");
while(!cmd_cb_pollquit()) {
if (fade > 0.0) {
/* TODO: Fading between solid colours could be optimized */
if (fx_crossfade(last_pix, state->pix, fade) == 0) {
/* Fade interrupted */
save_pix = temp_pix;
break;
} else {
/* Fade completed */
save_pix = state->pix;
}
} else if (fade == 0.0) {
render(state->pix);
save_pix = state->pix;
} else {
fatal("negative fade duration");
}
if (state->hold_for > 0) {
if (fx_wait(state->hold_for) == 0) break;
}
last_pix = state->pix;
state = state->next;
if (state == NULL) {
if (ca->repeat) {
if (ntfy) {
coloranim_notify();
ntfy = 0;
}
state = ca->states;
} else {
break;
}
}
fade = state->fade_to;
}
if (save_pix != NULL) {
pix_copy(cur_pix, save_pix);
}
}
int parse_and_run(void) {
struct coloranim *ca;
ca = coloranim_parse();
if (ca == NULL) return -1;
coloranim_exec(ca);
coloranim_free(&ca);
return 0;
}
| 3.0625 | 3 |
2024-11-18T20:57:37.787674+00:00
| 2017-11-14T11:44:03 |
6532e17ed24b9de4a447c7cd03b26bd9157cbc65
|
{
"blob_id": "6532e17ed24b9de4a447c7cd03b26bd9157cbc65",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-14T11:44:03",
"content_id": "c11e8314dc77fe7b5a9b8618a077e0586d40be34",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5459323235ad66754085b5c286b4d9614f706d1e",
"extension": "c",
"filename": "multisort-omp-dependencies.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93849114,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3781,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/boada/lab4/code/multisort-omp-dependencies.c",
"provenance": "stackv2-0064.json.gz:70232",
"repo_name": "felixarpa/PAR-Lab",
"revision_date": "2017-11-14T11:44:03",
"revision_id": "7b3bde3c3c95b61d0b53fc5992ea72dff182d0fe",
"snapshot_id": "4d275f7c29c10d3b42283fa0972e40ea0ed8bd79",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/felixarpa/PAR-Lab/7b3bde3c3c95b61d0b53fc5992ea72dff182d0fe/boada/lab4/code/multisort-omp-dependencies.c",
"visit_date": "2021-01-25T09:32:35.613365"
}
|
stackv2
|
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <sys/time.h>
double getusec_() {
struct timeval time;
gettimeofday(&time, NULL);
return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec);
}
#define START_COUNT_TIME stamp = getusec_();
#define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\
stamp = stamp/1e6;\
printf ("%s: %0.6f\n",(_m), stamp);
// N and MIN must be powers of 2
long N;
long MIN_SORT_SIZE;
long MIN_MERGE_SIZE;
#define BLOCK_SIZE 1024L
#define T int
void basicsort(long n, T data[n]);
void basicmerge(long n, T left[n], T right[n], T result[n*2], long start, long length);
void merge(long n, T left[n], T right[n], T result[n*2], long start, long length) {
if (length < MIN_MERGE_SIZE*2L) {
// Base case
basicmerge(n, left, right, result, start, length);
} else {
// Recursive decomposition
#pragma omp taskgroup
{
#pragma omp task
merge(n, left, right, result, start, length/2);
#pragma omp task
merge(n, left, right, result, start + length/2, length/2);
}
}
}
void multisort(long n, T data[n], T tmp[n]) {
if (n >= MIN_SORT_SIZE*4L) {
// Recursive decomposition
#pragma omp task depend(out: data[0])
multisort(n/4L, &data[0], &tmp[0]);
#pragma omp task depend(out: data[n/4L])
multisort(n/4L, &data[n/4L], &tmp[n/4L]);
#pragma omp task depend(out: data[n/2L])
multisort(n/4L, &data[n/2L], &tmp[n/2L]);
#pragma omp task depend(out: data[3L*n/4L])
multisort(n/4L, &data[3L*n/4L], &tmp[3L*n/4L]);
#pragma omp task depend(in: data[0], data[n/4L]) depend(out: tmp[0])
merge(n/4L, &data[0], &data[n/4L], &tmp[0], 0, n/2L);
#pragma omp task depend(in: data[n/2L], data[3L*n/4L]) depend(out: tmp[n/2L])
merge(n/4L, &data[n/2L], &data[3L*n/4L], &tmp[n/2L], 0, n/2L);
#pragma omp task depend(in: tmp[0], tmp[n/2L])
merge(n/2L, &tmp[0], &tmp[n/2L], &data[0], 0, n);
#pragma omp taskwait
} else {
// Base case
basicsort(n, data);
}
}
static void initialize(long length, T data[length]) {
long i;
for (i = 0; i < length; i++) {
if (i==0) {
data[i] = rand();
} else {
data[i] = ((data[i-1]+1) * i * 104723L) % N;
}
}
}
static void clear(long length, T data[length]) {
long i;
for (i = 0; i < length; i++) {
data[i] = 0;
}
}
void check_sorted(long n, T data[n])
{
int unsorted=0;
for (int i=1; i<n; i++)
if (data[i-1] > data[i]) unsorted++;
if (unsorted > 0)
printf ("\nERROR: data is NOT properly sorted. There are %d unordered positions\n\n",unsorted);
else {
// printf ("data IS ordered; ");
}
}
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <vector size in K> <sort size in K> <merge size in K>\n", argv[0]);
return 1;
}
N = atol(argv[1]) * BLOCK_SIZE;
MIN_SORT_SIZE = atol(argv[2]) * BLOCK_SIZE;
MIN_MERGE_SIZE = atol(argv[3]) * BLOCK_SIZE;
T *data = malloc(N*sizeof(T));
T *tmp = malloc(N*sizeof(T));
double stamp;
START_COUNT_TIME;
initialize(N, data);
clear(N, tmp);
STOP_COUNT_TIME("Initialization time in seconds");
START_COUNT_TIME;
#pragma omp parallel
#pragma omp single
multisort(N, data, tmp);
STOP_COUNT_TIME("Multisort execution time");
START_COUNT_TIME;
check_sorted (N, data);
STOP_COUNT_TIME("Check sorted data execution time");
fprintf(stdout, "Multisort program finished\n");
return 0;
}
| 2.65625 | 3 |
2024-11-18T20:57:38.626726+00:00
| 2017-05-10T09:50:21 |
8a42ab0bcb989159b349c7bc2dab0ab52eb72c3d
|
{
"blob_id": "8a42ab0bcb989159b349c7bc2dab0ab52eb72c3d",
"branch_name": "refs/heads/arm",
"committer_date": "2017-05-10T14:22:48",
"content_id": "54e4c20be440e1caf52e217eac1fae91aeed6214",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6af50a4b5b928211880dd9f1c6ce92c2afea828b",
"extension": "c",
"filename": "dht.c",
"fork_events_count": 0,
"gha_created_at": "2016-12-16T09:52:08",
"gha_event_created_at": "2020-02-04T19:16:46",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 76642373,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5857,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/drivers/sensor/dht/dht.c",
"provenance": "stackv2-0064.json.gz:71004",
"repo_name": "erwango/zephyr",
"revision_date": "2017-05-10T09:50:21",
"revision_id": "162f4574c781ae17d3fecfd4ac10df111e90ae3c",
"snapshot_id": "1c7aa447f613de76439291ba9dde1e4dc7c5786e",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/erwango/zephyr/162f4574c781ae17d3fecfd4ac10df111e90ae3c/drivers/sensor/dht/dht.c",
"visit_date": "2023-08-11T10:29:20.031948"
}
|
stackv2
|
/*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <device.h>
#include <gpio.h>
#include <misc/byteorder.h>
#include <misc/util.h>
#include <sensor.h>
#include <string.h>
#include <zephyr.h>
#include "dht.h"
/**
* @brief Measure duration of signal send by sensor
*
* @param drv_data Pointer to the driver data structure
* @param signal_val Value of signal being measured
*
* @return duration in usec of signal being measured,
* -1 if duration exceeds DHT_SIGNAL_MAX_WAIT_DURATION
*/
static s8_t dht_measure_signal_duration(struct dht_data *drv_data,
u32_t signal_val)
{
u32_t val;
u32_t elapsed_cycles;
u32_t max_wait_cycles = (u32_t)(
(u64_t)DHT_SIGNAL_MAX_WAIT_DURATION *
(u64_t)sys_clock_hw_cycles_per_sec /
(u64_t)USEC_PER_SEC
);
u32_t start_cycles = k_cycle_get_32();
do {
gpio_pin_read(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM, &val);
elapsed_cycles = k_cycle_get_32() - start_cycles;
if (elapsed_cycles >= max_wait_cycles) {
return -1;
}
} while (val == signal_val);
return (u64_t)elapsed_cycles *
(u64_t)USEC_PER_SEC /
(u64_t)sys_clock_hw_cycles_per_sec;
}
static int dht_sample_fetch(struct device *dev, enum sensor_channel chan)
{
struct dht_data *drv_data = dev->driver_data;
int ret = 0;
s8_t signal_duration[DHT_DATA_BITS_NUM];
s8_t max_duration, min_duration, avg_duration;
u8_t buf[5];
unsigned int i, j;
__ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL);
/* send start signal */
gpio_pin_write(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM, 0);
k_busy_wait(DHT_START_SIGNAL_DURATION);
gpio_pin_write(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM, 1);
/* switch to DIR_IN to read sensor signals */
gpio_pin_configure(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM,
GPIO_DIR_IN);
/* wait for sensor response */
if (dht_measure_signal_duration(drv_data, 1) == -1) {
ret = -EIO;
goto cleanup;
}
/* read sensor response */
if (dht_measure_signal_duration(drv_data, 0) == -1) {
ret = -EIO;
goto cleanup;
}
/* wait for sensor data */
if (dht_measure_signal_duration(drv_data, 1) == -1) {
ret = -EIO;
goto cleanup;
}
/* read sensor data */
for (i = 0; i < DHT_DATA_BITS_NUM; i++) {
/* LOW signal to indicate a new bit */
if (dht_measure_signal_duration(drv_data, 0) == -1) {
ret = -EIO;
goto cleanup;
}
/* HIGH signal duration indicates bit value */
signal_duration[i] = dht_measure_signal_duration(drv_data, 1);
if (signal_duration[i] == -1) {
ret = -EIO;
goto cleanup;
}
}
/*
* the datasheet says 20-40us HIGH signal duration for a 0 bit and
* 80us for a 1 bit; however, since dht_measure_signal_duration is
* not very precise, compute the threshold for deciding between a
* 0 bit and a 1 bit as the average between the minimum and maximum
* if the durations stored in signal_duration
*/
min_duration = signal_duration[0];
max_duration = signal_duration[0];
for (i = 1; i < DHT_DATA_BITS_NUM; i++) {
if (min_duration > signal_duration[i]) {
min_duration = signal_duration[i];
}
if (max_duration < signal_duration[i]) {
max_duration = signal_duration[i];
}
}
avg_duration = ((s16_t)min_duration + (s16_t)max_duration) / 2;
/* store bits in buf */
j = 0;
memset(buf, 0, sizeof(buf));
for (i = 0; i < DHT_DATA_BITS_NUM; i++) {
if (signal_duration[i] >= avg_duration) {
buf[j] = (buf[j] << 1) | 1;
} else {
buf[j] = buf[j] << 1;
}
if (i % 8 == 7) {
j++;
}
}
/* verify checksum */
if (((buf[0] + buf[1] + buf[2] + buf[3]) & 0xFF) != buf[4]) {
SYS_LOG_DBG("Invalid checksum in fetched sample");
ret = -EIO;
} else {
memcpy(drv_data->sample, buf, 4);
}
cleanup:
/* switch to DIR_OUT and leave pin to HIGH until next fetch */
gpio_pin_configure(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM,
GPIO_DIR_OUT);
gpio_pin_write(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM, 1);
return ret;
}
static int dht_channel_get(struct device *dev,
enum sensor_channel chan,
struct sensor_value *val)
{
struct dht_data *drv_data = dev->driver_data;
__ASSERT_NO_MSG(chan == SENSOR_CHAN_TEMP || chan == SENSOR_CHAN_HUMIDITY);
/* see data calculation example from datasheet */
#if defined(CONFIG_DHT_CHIP_DHT11)
/* use only integral data byte */
if (chan == SENSOR_CHAN_HUMIDITY) {
val->val1 = drv_data->sample[0] * 1000;
val->val2 = 0;
} else { /* chan == SENSOR_CHAN_TEMP */
val->val1 = drv_data->sample[2];
val->val2 = 0;
}
#elif defined(CONFIG_DHT_CHIP_DHT22)
/*
* use both integral and decimal data bytes; resulted 16bit data has
* a resolution of 0.1 units
*/
s16_t raw_val, sign;
if (chan == SENSOR_CHAN_HUMIDITY) {
raw_val = (drv_data->sample[0] << 8) | drv_data->sample[1];
val->val1 = raw_val * 100;
val->val2 = 0;
} else { /* chan == SENSOR_CHAN_TEMP */
raw_val = (drv_data->sample[2] << 8) | drv_data->sample[3];
sign = raw_val & 0x8000;
raw_val = raw_val & ~0x8000;
val->val1 = raw_val / 10;
val->val2 = (raw_val % 10) * 100000;
/* handle negative value */
if (sign) {
val->val1 = -val->val1;
val->val2 = -val->val2;
}
}
#endif
return 0;
}
static const struct sensor_driver_api dht_api = {
.sample_fetch = &dht_sample_fetch,
.channel_get = &dht_channel_get,
};
static int dht_init(struct device *dev)
{
struct dht_data *drv_data = dev->driver_data;
drv_data->gpio = device_get_binding(CONFIG_DHT_GPIO_DEV_NAME);
if (drv_data->gpio == NULL) {
SYS_LOG_ERR("Failed to get GPIO device.");
return -EINVAL;
}
gpio_pin_configure(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM,
GPIO_DIR_OUT);
gpio_pin_write(drv_data->gpio, CONFIG_DHT_GPIO_PIN_NUM, 1);
dev->driver_api = &dht_api;
return 0;
}
struct dht_data dht_data;
DEVICE_INIT(dht_dev, CONFIG_DHT_NAME, &dht_init, &dht_data,
NULL, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY);
| 2.546875 | 3 |
2024-11-18T20:57:38.717923+00:00
| 2021-03-08T23:53:54 |
2325ed95327702351d1df09dedf3145e49d9dd0a
|
{
"blob_id": "2325ed95327702351d1df09dedf3145e49d9dd0a",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-08T23:53:54",
"content_id": "351fa3af02fdd4776bb2164b6f9085c65d080523",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "57ba2b0527b50b2bd4eb1dd028fec0eaf875776f",
"extension": "c",
"filename": "Set.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 330815059,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1646,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/unit05_set_and_its_operation_advanced_exercise/Set.c",
"provenance": "stackv2-0064.json.gz:71135",
"repo_name": "a-flying-pig/Data-Structure-and-Algorithm-Practice",
"revision_date": "2021-03-08T23:53:54",
"revision_id": "4470312d517081c540b9effa26fb21e8361ef637",
"snapshot_id": "3e2955e55c2b8a8c992ffdb9fdc3d3498a3db6d6",
"src_encoding": "GB18030",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/a-flying-pig/Data-Structure-and-Algorithm-Practice/4470312d517081c540b9effa26fb21e8361ef637/unit05_set_and_its_operation_advanced_exercise/Set.c",
"visit_date": "2023-03-17T03:03:10.766198"
}
|
stackv2
|
/*
* Set.c
*
* Created on: 2020年7月7日
* Author: zhuhua
*/
#include <stdlib.h>
#include <stdio.h>
#include "Set.h"
int MaxSize;
int tmp;
SetType* CreateSetType(int size) {
MaxSize = size;
SetType* Set = malloc(sizeof(SetType) * MaxSize);
for (int i = 0; i < MaxSize; i++) {
Set[i] = -1;
}
return Set;
}
/*int Find(SetType S[], int X) {
if (X < 0 || X > MaxSize) {
printf("can not find %d\n", tmp);
return -1;
}
for ( ;S[X] >= 0; X = S[X]);
return X; // 返回的是树根的index,不是Data
}*/
// 采用路径压缩,进一步提高find效率
int Find(SetType S[], int X) {
if (X < 0 || X > MaxSize) {
printf("can not find %d\n", tmp);
return -1;
}
if (S[X] < 0) {
return X;
} else {
return S[X] = Find(S, S[X]); // 将子节点都汇集到一个父节点上,提高后续find效率。另外,尾递归,编译器会优化为循环,
// 不会造成栈溢出
}
return X; // 返回的是树根的index,不是Data
}
void Union(SetType S[], ElementType X1, ElementType X2) {
int root1 = Find(S, X1 - 1); // 减一才是data对应的index
int root2 = Find(S, X2 - 1); // 减一才是data对应的index
if (root1 != root2) {
if (root1 < root2) { // 按秩归并,避免树退化成链表,导致find效率降低(比大小,比比高度更适合与路径压缩一起用)
S[root1] += S[root2];
S[root2] = root1;
} else {
S[root2] += S[root1];
S[root1] = root2;
}
}
}
void PrintSetType(SetType S[]) {
printf("printSetType:\n");
for (int i = 0; i < MaxSize; i++) {
printf("index:%d, Data:%d, parent:%d\n", i, i + 1, S[i]);
}
}
| 3.015625 | 3 |
2024-11-18T20:57:38.774993+00:00
| 2014-12-06T07:46:34 |
7ef4c0c979bc125ae8f6478071917794eb8d934c
|
{
"blob_id": "7ef4c0c979bc125ae8f6478071917794eb8d934c",
"branch_name": "refs/heads/master",
"committer_date": "2014-12-06T07:46:34",
"content_id": "b42c970ec03f6866f20fcb8b65d219044ff3ad37",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4fa3310643632deb7f272e435e6897f572f66273",
"extension": "c",
"filename": "oduino_sensor.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": 1410,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/oduino_sensor.c",
"provenance": "stackv2-0064.json.gz:71264",
"repo_name": "TizenChameleon/virtualSensor",
"revision_date": "2014-12-06T07:46:34",
"revision_id": "45400eaf042bcc7b8f438d24137761ca4ad6e8b7",
"snapshot_id": "b5bf0239a126d3688e114431224312622fda66b7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TizenChameleon/virtualSensor/45400eaf042bcc7b8f438d24137761ca4ad6e8b7/oduino_sensor.c",
"visit_date": "2021-01-13T01:40:49.767297"
}
|
stackv2
|
#include <linux/module.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/sysfs.h>
#include <linux/device.h>
static int temp;
static int hum;
struct class *VsensorClass;
struct device *odev;
static ssize_t sensorShow(struct device *dev, struct device_attribute *attr,
char *buffer){
return sprintf(buffer, "%d %d\n", temp, hum);
}
static ssize_t sensorStore(struct device *dev, struct device_attribute *attr,
const char *buffer, size_t count){
sscanf(buffer, "%d %d", &temp, &hum);
return count;
}
DEVICE_ATTR(oduino_sensor, 0777, sensorShow, sensorStore);
static int __init oduinoSensor_init(void){
VsensorClass = class_create(THIS_MODULE, "Vsensor");
odev = device_create(VsensorClass, NULL, 0, NULL, "oduino");
//oduinoSensor = platform_device_register_simple("oduinoSensor", -1, NULL, 0);
device_create_file(odev, &dev_attr_oduino_sensor);
// sysfs_create_file(&oduinoSensor->dev.kobj, &dev_attr_oduino_sensor.attr);
return 0;
}
static void __exit oduinoSensor_exit (void){
// sysfs_remove_file(&oduinoSensor->dev.kobj, &dev_attr_oduino_sensor.attr);
// platform_device_unregister(oduinoSensor);
device_destroy(VsensorClass, 0);
class_destroy(VsensorClass);
device_remove_file(odev, &dev_attr_oduino_sensor);
return;
}
module_init(oduinoSensor_init);
module_exit(oduinoSensor_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("virtual input device");
| 2.203125 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.