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:34:56.890845+00:00
| 2017-06-08T02:15:07 |
be7cca6b293261594768a74f7450f095f56d7058
|
{
"blob_id": "be7cca6b293261594768a74f7450f095f56d7058",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-08T02:15:07",
"content_id": "e55c35a6f6381456ccab1c45dfe083ee258b1456",
"detected_licenses": [
"ISC"
],
"directory_id": "4a337c715921349cfe04bdf130a47431cbacb3af",
"extension": "c",
"filename": "date.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 83324336,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 476,
"license": "ISC",
"license_type": "permissive",
"path": "/assign1/src/date.c",
"provenance": "stackv2-0054.json.gz:1198",
"repo_name": "mariosal/uoa-syspro",
"revision_date": "2017-06-08T02:15:07",
"revision_id": "f6cfa0b71de4016d72519eae9d4c645a9aceac70",
"snapshot_id": "267fbc039e8b4449381c7bc863d71a1760ba21d2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mariosal/uoa-syspro/f6cfa0b71de4016d72519eae9d4c645a9aceac70/assign1/src/date.c",
"visit_date": "2021-03-27T09:56:55.012096"
}
|
stackv2
|
#include "date.h"
#include <stdio.h>
long long Num(const char* str) {
long long prefix;
long long num;
sscanf(str, "%3lld-%10lld", &prefix, &num);
return prefix * 10000000000 + num;
}
int Time(const char* str) {
int hours;
int mins;
sscanf(str, "%d:%d", &hours, &mins);
return hours * 100 + mins;
}
int Date(const char* str) {
int day;
int month;
int year;
sscanf(str, "%2d%2d%4d", &day, &month, &year);
return year * 10000 + month * 100 + day;
}
| 2.625 | 3 |
2024-11-18T19:34:57.040515+00:00
| 2023-04-26T13:58:57 |
dcd7c0e67902eb539ff13f61d95c2c319cae213c
|
{
"blob_id": "dcd7c0e67902eb539ff13f61d95c2c319cae213c",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-26T13:58:57",
"content_id": "d70b88594e9315bf11c6d4b90501a51ab80553d8",
"detected_licenses": [
"MIT"
],
"directory_id": "1b7bc0c8810624c79e1dade01bb63177058f1a28",
"extension": "c",
"filename": "sorber_get_command_line.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 109069731,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 683,
"license": "MIT",
"license_type": "permissive",
"path": "/Voltron/Source/LowC/sorber_get_command_line.c",
"provenance": "stackv2-0054.json.gz:1454",
"repo_name": "ernestyalumni/HrdwCCppCUDA",
"revision_date": "2023-04-26T13:58:57",
"revision_id": "ad067fd4e605c230ea87bdc36cc38341e681a1e0",
"snapshot_id": "61f123359fb585f279a32a19ba64dfdb60a4f66f",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/ernestyalumni/HrdwCCppCUDA/ad067fd4e605c230ea87bdc36cc38341e681a1e0/Voltron/Source/LowC/sorber_get_command_line.c",
"visit_date": "2023-07-21T06:00:51.881770"
}
|
stackv2
|
/* Jacob Sorber. Getting Command-Line Arguments in C
* https://youtu.be/6Dk8s0F2gow
*
* Example Usage
* ./hello Hello 1 2 53 45.0
* ./sorber_get_command_line Hello 1 2 53 45.0
*/
#include <stdio.h>
#include <stdlib.h> // atoi, atof
int main(int argc, char **argv) {
printf("Hello World - %d\n", argc);
for (int i=0; i < argc; i++) {
// atoi - short for ascii to int.
// cf. https://en.cppreference.com/w/cpp/string/byte/atoi
// If converted value falls out of range of corresponding return type,
// return value undefined. If no conversion can be performed, 0 returned.
printf("arg %d - %s, %i, %f\n",i,argv[i], atoi(argv[i]), atof(argv[i]));
}
}
| 3.234375 | 3 |
2024-11-18T19:34:57.346695+00:00
| 2022-04-02T14:01:00 |
64d34551a20b1b82b514d6f013b3f0f244abc461
|
{
"blob_id": "64d34551a20b1b82b514d6f013b3f0f244abc461",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-02T14:01:00",
"content_id": "1436e87b08b82e504b345a01779584245b1a4d75",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "edcb22d7b1192881e888d55301205ac1dd1c94fd",
"extension": "h",
"filename": "lzx_unpack.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49499707,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2814,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/external/lzx/lzx_unpack.h",
"provenance": "stackv2-0054.json.gz:1969",
"repo_name": "demozoo/open_depacker",
"revision_date": "2022-04-02T14:01:00",
"revision_id": "3d5b41cd159d5d3288de133c69c7ee7fb9605b6c",
"snapshot_id": "b202bfe3647e91f9fa054cea6d7e07c6c4ee9ffd",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/demozoo/open_depacker/3d5b41cd159d5d3288de133c69c7ee7fb9605b6c/external/lzx/lzx_unpack.h",
"visit_date": "2022-05-01T09:21:38.180466"
}
|
stackv2
|
/**
* dimgutil: disk image and archive utility
* Copyright (C) 2022 Alice Rowan <petrifiedrowan@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Unpacker for Amiga LZX compressed streams.
*/
#ifndef DIMGUTIL_LZX_UNPACK_H
#define DIMGUTIL_LZX_UNPACK_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h> /* size_t */
#include <stdint.h>
typedef uint8_t lzx_uint8;
typedef uint16_t lzx_uint16;
typedef uint32_t lzx_uint32;
typedef int32_t lzx_int32;
#ifdef _WIN32
#define LZX_RESTRICT
#else
#define LZX_RESTRICT __restrict__
#endif
enum lzx_method { LZX_M_UNPACKED = 0, LZX_M_PACKED = 2, LZX_M_MAX };
/**
* Determine if a given LZX method is supported.
*
* @param method compression method to test.
*
* @return 0 if a method is supported, otherwise -1.
*/
static inline int lzx_method_is_supported(int method) {
switch (method) {
case LZX_M_UNPACKED:
case LZX_M_PACKED:
return 0;
}
return -1;
}
/**
* Unpack a buffer containing an LZX compressed stream into an uncompressed
* representation of the stream. The unpacked method should be handled
* separately from this function since it doesn't need a second output buffer
* for the uncompressed data.
*
* @param dest destination buffer for the uncompressed stream.
* @param dest_len destination buffer size.
* @param src buffer containing the compressed stream.
* @param src_len size of the compressed stream.
* @param method LZX compression method (should be LZX_M_PACKED).
*
* @return 0 on success, otherwise -1.
*/
int lzx_unpack(unsigned char* dest, size_t dest_len, const unsigned char* src, size_t src_len, int method);
#ifdef __cplusplus
}
#endif
#endif /* DIMGUTIL_LZX_UNPACK_H */
| 2.296875 | 2 |
2024-11-18T19:34:57.416053+00:00
| 2020-06-09T21:15:37 |
ea854a0e8638c5e1b3d63ce38ce1df95b8b55576
|
{
"blob_id": "ea854a0e8638c5e1b3d63ce38ce1df95b8b55576",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-09T21:15:37",
"content_id": "64c23955cfff4c7aedec08c43f3d84ef3337952c",
"detected_licenses": [
"MIT"
],
"directory_id": "ca75f7099b93d8083d5b2e9c6db2e8821e63f83b",
"extension": "c",
"filename": "754844461.c",
"fork_events_count": 0,
"gha_created_at": "2020-05-08T10:10:47",
"gha_event_created_at": "2020-06-09T21:15:38",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 262290632,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2491,
"license": "MIT",
"license_type": "permissive",
"path": "/z2/part1/jm/random/754844461.c",
"provenance": "stackv2-0054.json.gz:2099",
"repo_name": "kozakusek/ipp-2020-testy",
"revision_date": "2020-06-09T21:15:37",
"revision_id": "09aa008fa53d159672cc7cbf969a6b237e15a7b8",
"snapshot_id": "210ed201eaea3c86933266bd57ee284c9fbc1b96",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kozakusek/ipp-2020-testy/09aa008fa53d159672cc7cbf969a6b237e15a7b8/z2/part1/jm/random/754844461.c",
"visit_date": "2022-10-04T18:55:37.875713"
}
|
stackv2
|
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include "gamma.h"
#include <stdbool.h>
#include <string.h>
int main() {
/*
scenario: test_random_actions
uuid: 754844461
*/
/*
random actions, total chaos
*/
gamma_t* board = gamma_new(7, 2, 3, 4);
assert( board != NULL );
assert( gamma_move(board, 1, 1, 0) == 1 );
assert( gamma_golden_move(board, 1, 1, 5) == 0 );
assert( gamma_move(board, 2, 4, 0) == 1 );
assert( gamma_busy_fields(board, 2) == 1 );
assert( gamma_move(board, 3, 1, 3) == 0 );
assert( gamma_move(board, 3, 5, 1) == 1 );
assert( gamma_move(board, 2, 1, 1) == 1 );
assert( gamma_move(board, 3, 0, 2) == 0 );
assert( gamma_move(board, 3, 5, 1) == 0 );
assert( gamma_move(board, 1, 5, 0) == 1 );
assert( gamma_free_fields(board, 2) == 9 );
assert( gamma_move(board, 3, 0, 0) == 1 );
assert( gamma_free_fields(board, 3) == 8 );
assert( gamma_move(board, 1, 1, 6) == 0 );
assert( gamma_move(board, 1, 5, 1) == 0 );
assert( gamma_move(board, 2, 1, 4) == 0 );
assert( gamma_move(board, 3, 0, 6) == 0 );
assert( gamma_golden_possible(board, 3) == 1 );
assert( gamma_move(board, 1, 1, 6) == 0 );
assert( gamma_move(board, 2, 1, 2) == 0 );
assert( gamma_move(board, 2, 2, 1) == 1 );
assert( gamma_move(board, 3, 3, 1) == 1 );
assert( gamma_move(board, 1, 0, 6) == 0 );
assert( gamma_move(board, 2, 0, 3) == 0 );
assert( gamma_move(board, 3, 4, 0) == 0 );
char* board740330466 = gamma_board(board);
assert( board740330466 != NULL );
assert( strcmp(board740330466,
".223.3.\n"
"31..21.\n") == 0);
free(board740330466);
board740330466 = NULL;
assert( gamma_move(board, 1, 0, 3) == 0 );
assert( gamma_move(board, 2, 2, 0) == 1 );
assert( gamma_move(board, 2, 4, 0) == 0 );
assert( gamma_free_fields(board, 2) == 5 );
assert( gamma_move(board, 3, 1, 6) == 0 );
assert( gamma_free_fields(board, 3) == 5 );
assert( gamma_move(board, 1, 1, 6) == 0 );
assert( gamma_move(board, 1, 0, 0) == 0 );
assert( gamma_busy_fields(board, 1) == 2 );
assert( gamma_move(board, 2, 4, 0) == 0 );
assert( gamma_move(board, 2, 2, 1) == 0 );
assert( gamma_busy_fields(board, 2) == 4 );
assert( gamma_move(board, 3, 0, 3) == 0 );
assert( gamma_move(board, 3, 4, 1) == 1 );
assert( gamma_move(board, 1, 0, 0) == 0 );
assert( gamma_move(board, 1, 1, 0) == 0 );
assert( gamma_move(board, 2, 0, 6) == 0 );
assert( gamma_move(board, 3, 1, 1) == 0 );
assert( gamma_busy_fields(board, 3) == 4 );
assert( gamma_move(board, 1, 0, 3) == 0 );
gamma_delete(board);
return 0;
}
| 2.34375 | 2 |
2024-11-18T19:34:57.947724+00:00
| 2019-11-17T02:35:24 |
6e071774260aaaac21472ed9cfbc3a746cc7f288
|
{
"blob_id": "6e071774260aaaac21472ed9cfbc3a746cc7f288",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-17T02:35:24",
"content_id": "d690184b431a44ec67ba239ee9bf95abda3f8a9f",
"detected_licenses": [
"Unlicense"
],
"directory_id": "4cdef1511f6c52153dec72008aebb1fdb60cb3f3",
"extension": "c",
"filename": "qotd.c",
"fork_events_count": 0,
"gha_created_at": "2019-11-16T20:15:46",
"gha_event_created_at": "2019-11-16T20:15:46",
"gha_language": null,
"gha_license_id": "Unlicense",
"github_id": 222154044,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 450,
"license": "Unlicense",
"license_type": "permissive",
"path": "/qotd/qotd.c",
"provenance": "stackv2-0054.json.gz:2483",
"repo_name": "Coinjuice/system_call",
"revision_date": "2019-11-17T02:35:24",
"revision_id": "86eb369b37648523409e15af0e6c53c5d20376c6",
"snapshot_id": "a1471495a58adf5262a1e2ea97b8600b8cb001a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Coinjuice/system_call/86eb369b37648523409e15af0e6c53c5d20376c6/qotd/qotd.c",
"visit_date": "2020-09-11T18:32:34.677413"
}
|
stackv2
|
#include <linux/kernel.h>
asmlinkage long sys_qotd(void){
char * quotes[] = {
"Spread love everywhere you go. Let no one ever come to you without leaving happier.'-Mother Teresa\n",
"Always rember that you are absolutely unique. Just like everyone else.'-Margaret Mead'\n"
};
int quotesnum = *("es+1)-quotes;
int i = 0;
for(;i<quotesnum;i++){
printk("quote: %s",quotes[i]);
}
return 0;
}
| 2.28125 | 2 |
2024-11-18T19:34:58.225991+00:00
| 2014-11-11T01:37:55 |
afbf4ebc95645510d81eb04170d312f0ed34a9c2
|
{
"blob_id": "afbf4ebc95645510d81eb04170d312f0ed34a9c2",
"branch_name": "refs/heads/master",
"committer_date": "2014-11-11T01:37:55",
"content_id": "2dd94c822f2893e4e1b19aa0f1be171ef3221adb",
"detected_licenses": [
"BSD-2-Clause",
"BSD-2-Clause-Views"
],
"directory_id": "be3a5f7960130c9783105f716a23f0a0a1cd7a64",
"extension": "h",
"filename": "PICKLIST.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": 1253,
"license": "BSD-2-Clause,BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/SRC/PICKLIST.H",
"provenance": "stackv2-0054.json.gz:2740",
"repo_name": "OS2World/APP-EDITOR-KEd",
"revision_date": "2014-11-11T01:37:55",
"revision_id": "8a093c3e6ada2db6dbb9e2fa9ced31b32b8d8913",
"snapshot_id": "7b314e923de5ff752cc12d9a461b7c9281a2cb72",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/OS2World/APP-EDITOR-KEd/8a093c3e6ada2db6dbb9e2fa9ced31b32b8d8913/SRC/PICKLIST.H",
"visit_date": "2020-12-24T16:58:37.430033"
}
|
stackv2
|
/* picklist.h */
/* this is a general purpose picklist that uses the windows system */
/* this is where in the window the picklist appears. If the list will scroll,
it is assumed that the border is set to match, so just the portal scrolls. */
struct picklist_portal {
SHORT startrow, startcol;
SHORT rows, columns;
byte cursor_color, normal_color;
};
/* this customizes the picklist. These functions are called to preform the
various actions. */
struct picklist_thunk {
bool (*keyfilter) (SHORT key);
/* if present, is called after each key is gotten. If return value is FALSE,
the picklist will ignore that key and loop. */
char const* (*fetch_choice) (SHORT index);
/* this is called to get the string for choice n. Called everytime that
string needs to be displayed, if the list scrolls. */
void (*tellme) (SHORT index);
/* if present, is called before getting a key. It is given the index number
of the choice where the bouncebar will appear. */
};
//SHORT picklist (struct picklist_portal *p, window_t w, struct picklist_thunk *t, SHORT count, SHORT location);
SHORT picklist (struct picklist_portal *p, struct picklist_thunk *t, SHORT count, SHORT location);
| 2.265625 | 2 |
2024-11-18T19:34:58.939320+00:00
| 2019-12-08T14:26:49 |
0e38462c4be2d528765b4d08e2352061fc05a96b
|
{
"blob_id": "0e38462c4be2d528765b4d08e2352061fc05a96b",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-08T14:26:49",
"content_id": "40422ebf81d167f77c5a31c71939b038e237fc52",
"detected_licenses": [
"MIT"
],
"directory_id": "13f9c5b8b141ab1df6ea4b8e9db700df4c2bec65",
"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": 223961397,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4954,
"license": "MIT",
"license_type": "permissive",
"path": "/client.c",
"provenance": "stackv2-0054.json.gz:3255",
"repo_name": "zhang1yong1/chat",
"revision_date": "2019-12-08T14:26:49",
"revision_id": "a89ee85f74f1db8c1acebfe30d30a04f55237c9d",
"snapshot_id": "30019749a0eb5d129f98efa2706a9bd273de38bf",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/zhang1yong1/chat/a89ee85f74f1db8c1acebfe30d30a04f55237c9d/client.c",
"visit_date": "2020-09-17T02:31:36.487062"
}
|
stackv2
|
//客户端
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <assert.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <pthread.h>
int sfd; //socket描述符
int size; //读取和发送文件的长度
int r; //函数返回值
int len; //要发送的文件名的长度
char buf[128]; //数据的缓存
struct sockaddr_in dr; //网络地址
struct epoll_event ev, events[20]; //ev用于注册事件,events用于回传要处理的事件
int epid = 0;
pthread_t pid,pid2;
char command_buff[512];
int sigign() {
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &sa, 0);
return 0;
}
int
firefly_start(){
printf("*******firefly client start*****\n");
printf("***list:show all online players*\n");
printf("***send:send one player message*\n");
}
void*
main_loop(void* data){
for (;;)
{
firefly_start();
//scanf("%s",command_buff);
fgets(command_buff,512,stdin);
//printf("%s\n",command_buff);
fputs(command_buff,stdout);
printf("len:%d\n",strlen(command_buff) );
int r = 0;
int a = strlen(command_buff)+1;
command_buff[a] ='\0';
r = send(sfd,&a,sizeof(a),MSG_WAITALL);
if (r < 0)
{
printf("send len error\n");
continue;
}
r = send(sfd,command_buff,strlen(command_buff)+1,MSG_WAITALL);
if (r < 0)
{
printf("send buff error\n");
continue;
}
}
}
void*
run(void* data){
for (;;)
{
int nfds = epoll_wait(epid,events,20,500);
for (int i =0; i < nfds; ++i )
{
printf("has event :%d\n",nfds);
if(events[i].events & EPOLLOUT){ //数据向外发送 //关闭的时候,也会走这个分支
printf("EPOLLOUT\n");
int a = 10;
r = send(events[i].data.fd,&a,sizeof(a),MSG_WAITALL); //2次给空的fd发消息,程序就会崩溃
if(r == -1){
//关闭socket
printf("socket close\n");
printf("2:%m\n"),close(sfd),exit(-1);
}
r = send(events[i].data.fd,"abcdefghig",10,MSG_WAITALL); //2次给空的fd发消息,程序就会崩溃
if(r == -1){
//关闭socket
printf("socket close\n");
printf("3:%m\n"),close(sfd),exit(-1);
}
printf("write success!\n");
struct epoll_event ev;
ev.data.fd = sfd;
ev.events = EPOLLIN|EPOLLET;//发送事件
epoll_ctl(epid,EPOLL_CTL_MOD,sfd,&ev);//事件为读
}
if (events[i].events & EPOLLIN){ //数据读
printf("EPOLLIN\n");
int n;
int a;
n = read(sfd,&a,sizeof(a));
if (n < 0)
{
printf("read error\n");
}
char* buff = (char*)malloc(a+1);
n = read(sfd,buff,a);
if (n < 0)
{
printf("read error\n");
}
printf("data:%d:%s\n", a,buff);
}
}
}
}
int
main(int argc, char const *argv[]){
sigign();
// int sfd; //socket描述符
// int size; //读取和发送文件的长度
// int r; //函数返回值
// int len; //要发送的文件名的长度
// char buf[128]; //数据的缓存
// struct sockaddr_in dr; //网络地址
// struct epoll_event ev, events[20]; //ev用于注册事件,events用于回传要处理的事件
epid = epoll_create(256);
//1.建立socket
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd==-1)
printf("1:%m\n"),exit(-1);
printf("socket成功!\n");
ev.data.fd = sfd;
ev.events = EPOLLIN|EPOLLET;//发送事件
epoll_ctl(epid,EPOLL_CTL_ADD,sfd,&ev);//事件为读
//2.连接到服务器
dr.sin_family=AF_INET;
dr.sin_port=htons(8888);
inet_aton("192.168.1.18",&dr.sin_addr);
r=connect(sfd,(struct sockaddr*)&dr,sizeof(dr));
if(r==-1)
printf("2:%m\n"),close(sfd),exit(-1);
printf("connect成功!\n");
//发送到服务器
// int a = 10;
// r = send(sfd,&a,sizeof(a),0);
// if(r == -1){
// printf("2:%m\n"),close(sfd),exit(-1);
// }
//连接成功后,把sfd放入epoll进行管理
pthread_create(&pid,0,run,0); //接收消息
pthread_create(&pid2,0,main_loop,0); //发送消息
pthread_join(pid,(void**)NULL);
pthread_join(pid2,(void**)NULL);
failed:
//6.读取到文件尾,发送0数据包
close(sfd);
printf("OK!\n");
}
| 2.640625 | 3 |
2024-11-18T19:34:59.429708+00:00
| 2014-06-17T16:51:31 |
b86cedcef745830694e90fdb3e8f6846656c4771
|
{
"blob_id": "b86cedcef745830694e90fdb3e8f6846656c4771",
"branch_name": "refs/heads/master",
"committer_date": "2014-06-17T16:51:31",
"content_id": "a20e4fd755ad7d4a69c58dcf1c55590e28fd21c2",
"detected_licenses": [
"Unlicense"
],
"directory_id": "240c1c1de1011af4a3f49f296841fd1871dd7e32",
"extension": "c",
"filename": "c_malloc.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": 405,
"license": "Unlicense",
"license_type": "permissive",
"path": "/parser/c_lib/c_malloc.c",
"provenance": "stackv2-0054.json.gz:3383",
"repo_name": "ChevalCorp/RayTracer",
"revision_date": "2014-06-17T16:51:31",
"revision_id": "2ddb6fa3059b2fcb6fc70e5f0d0a8ae203dde50d",
"snapshot_id": "ac129a0ef2546ee559b9f0615a63dd1b1415015c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ChevalCorp/RayTracer/2ddb6fa3059b2fcb6fc70e5f0d0a8ae203dde50d/parser/c_lib/c_malloc.c",
"visit_date": "2021-01-20T15:22:28.238544"
}
|
stackv2
|
/*
** c_malloc.c for c_malloc.c in /home/remy_o/rendu/C_lib_V1
**
** Made by Olivier Remy
** Login <remy_o@epitech.net>
**
** Started on Wed Apr 16 18:31:54 2014 Olivier Remy
** Last update Wed Apr 16 21:03:41 2014 Olivier Remy
*/
#include "langc.h"
void *c_malloc(size_t size)
{
void *ptr;
ptr = malloc(size);
if (ptr == NULL)
c_puterror("size is empty in c_malloc");
return (ptr);
}
| 2.21875 | 2 |
2024-11-18T19:35:00.370763+00:00
| 2019-09-24T20:14:14 |
3bd8051bc673fba7917e7e85c751ac9a7fcae2fe
|
{
"blob_id": "3bd8051bc673fba7917e7e85c751ac9a7fcae2fe",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-24T20:14:14",
"content_id": "4938c7521a7508d492ec5fc0db6746a501a179fe",
"detected_licenses": [
"MIT"
],
"directory_id": "9b72c2a0b7d6ad0e3879d1fbd30c56b3e1f0005b",
"extension": "h",
"filename": "btree.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 189270330,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4955,
"license": "MIT",
"license_type": "permissive",
"path": "/btree.h",
"provenance": "stackv2-0054.json.gz:3897",
"repo_name": "SpecificProtagonist/btree",
"revision_date": "2019-09-24T20:14:14",
"revision_id": "b60a4dd66e8f4984399dd7c1c44f05894b489d81",
"snapshot_id": "b24154dd3d21cadd3afba21223929629d3e0719d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SpecificProtagonist/btree/b60a4dd66e8f4984399dd7c1c44f05894b489d81/btree.h",
"visit_date": "2020-05-29T17:14:49.595730"
}
|
stackv2
|
#ifndef B_TREE_HEADER
#define B_TREE_HEADER
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
// B-Trees are balanced trees, typicaly with a high fanout,
// often used for file systems and other databases.
typedef struct btree btree;
typedef struct bt_alloc *bt_alloc_ptr;
typedef uint64_t bt_node_id;
typedef int (*bt_key_comp)(const void*, const void*, size_t);
// Some operations may result in underlying IO errors, e.g. running out of memory.
// You can set an error callback taking the errno (assuming bt_alloc_ptr alloc),
// if you don't the library will print an error to stderr and exit.
typedef void (*bt_error_callback)(bt_alloc_ptr, int error);
// Creates a new allocator that keeps each entire trees in RAM,
// can be freed with free().
// TODO: recommend default node_size (requires benchmark)
bt_alloc_ptr btree_new_ram_alloc(uint16_t node_size, bt_error_callback);
// Creates a new allocator that keeps trees in a file.
// Trees (or other data) already present there will be overriden.
// A small amount of data, e.g a bt_node_id, can be stored alongside the allocator,
// and a pointer to it will be stored in the location userdata points to.
// If creation fails, NULL is returned and errno is set.
bt_alloc_ptr btree_new_file_alloc(int fd, void **userdata, int userdata_size, bt_error_callback);
// Loads the allocator created with btree_new_file_alloc() from file.
// If creation fails, NULL is returned and errno is set.
bt_alloc_ptr btree_load_file_alloc(int fd, void **userdata, bt_error_callback);
// To load an existing btree, simply initialize the following structure
// with the correct values. If you created the tree with compare==NULL,
// you'll have to set compare to memcmp.
struct btree {
bt_alloc_ptr alloc;
bt_node_id root;
bt_key_comp compare;
};
// The following functions are multithreading safe only if no simultaneous
// operations are performed on btrees created with the same allocator
// Creates a new b-tree from the given allocator.
// userdata_size specifies the size of custom data (if any) stored along
// side the tree (should be much smaller than the allocators node_size).
// This is useful primarily for btrees stored in a file.
// You can specify the function for comparing keys, which is useful if you want
// to be able to traverse the tree in a specific order. If NULL, memcmp is used.
btree btree_create(bt_alloc_ptr, uint8_t key_size, uint8_t value_size,
bt_key_comp, uint16_t userdata_size);
// Gets a pointer to the userdata stored alongside the tree.
// This doesn't have a guaranteed alignment.
void *btree_load_userdata(btree);
// Indicate that the userdata pointer isn't in use anymore
void btree_unload_userdata(btree, void *userdata);
// Inserts the key and corresponding value,
// returns true if key was already present.
bool btree_insert(btree, const void *key, const void *value);
// Checks whether the btree is empty
bool btree_is_empty(btree);
// Checks whether the tree contains the key
bool btree_contains(btree, const void *key);
// Retrieves the corresponding value and, if found, stores it in *value_out.
// Returns whether the key was found.
bool btree_get(btree, const void *key, void *value_out);
// Traverses tree, calling callback() with a pointer to each key&value and params.
// If callback return true, end traversal early and return true, else return false.
bool btree_traverse(btree,
bool (*callback)(const void *key, void *value, void *param),
void* params, bool reverse);
// Remove the key from the tree, store the corresponding value (if value_out!=NULL).
// Return true if the tree did contain the key, else false.
bool btree_remove(btree, const void *key, void *value_out);
// Deletes a tree
void btree_delete(btree);
// Prints out a textual representation of the btree (intended for a monospace font)
// to stream. Expects utf-8 locale and VT1000. A function to print keys/values can
// be specified; if it is NULL, both are printed in hex format;
typedef void (*bt_printer_t)(FILE*, const void *key, const void *value, void *param);
void btree_debug_print(FILE *stream, btree, bt_printer_t, void *param);
// Allocators manage memory for b-trees. You can define your own,
// but the inbuild ones should be sufficient in most cases.
struct bt_alloc {
// Allocates space for a new node of size node_size.
// This may also be used to store data other than tree nodes.
// Node id 0 marks invalid node.
bt_node_id (*new)(void *this);
// Make sure that the node is in memory,
// which means doing nothing in case of bt_ram_allocator.
void *(*load)(btree, bt_node_id node);
// Indicate that the node doesn't have to be kept in memory anymore.
void (*unload)(btree, void *node);
// Deallocates a node (may not be called when loaded)
void (*free)(void* this, bt_node_id node);
// Size of a node in bytes
uint16_t node_size;
};
#endif
| 2.65625 | 3 |
2024-11-18T19:35:00.773946+00:00
| 2020-07-29T08:59:12 |
58376329020662478fc82a37594c4b05a63258f5
|
{
"blob_id": "58376329020662478fc82a37594c4b05a63258f5",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-29T08:59:12",
"content_id": "978077704af23a4a7d90cf56cb6668c5ffebf60b",
"detected_licenses": [
"MIT"
],
"directory_id": "8d7459d8801605d0516c461d3c4a71f38199c8be",
"extension": "c",
"filename": "tabela.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 277500159,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 440,
"license": "MIT",
"license_type": "permissive",
"path": "/Section6/tabela.c",
"provenance": "stackv2-0054.json.gz:4537",
"repo_name": "mevljas/Programming-Language-C",
"revision_date": "2020-07-29T08:59:12",
"revision_id": "b1964288327bfc63bc64f763c6a22f5eb368c5e1",
"snapshot_id": "1966d17669ea278811f9deb5586b9ca02469cdfb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mevljas/Programming-Language-C/b1964288327bfc63bc64f763c6a22f5eb368c5e1/Section6/tabela.c",
"visit_date": "2022-11-23T16:27:18.491149"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int tab[] = {1,2,3,4,5};
int *p1 = tab;
p1[1] = 15; //isto kot tab[1] = 15
int *p2; //imam kazalec
//p2 bi radi uporabili kot tabelo intov; v tabeli bomo imeli 10 stevilk
p2 = (int *) malloc(10 * sizeof(int)); //mallokc rezervira prostor nekje v pomnilniku. Dobro je da typecastamo. Lahko upriambo kot tabelo
p2[1] = 15; //vpisi 15 tja, kamor kaze p2
// deklrariran
}
| 2.984375 | 3 |
2024-11-18T19:35:00.867715+00:00
| 2021-08-13T18:16:47 |
add1ac051888da0b53969cee44c9435f930f8a99
|
{
"blob_id": "add1ac051888da0b53969cee44c9435f930f8a99",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-13T18:16:47",
"content_id": "96481cc9e940521ec94d5fa0b20bd22ae4a0c7bc",
"detected_licenses": [
"MIT"
],
"directory_id": "41845bc4d2cbf8efb92f8a107396bb95634ea592",
"extension": "c",
"filename": "xray.jit.cellvalue.c",
"fork_events_count": 1,
"gha_created_at": "2015-11-18T16:30:23",
"gha_event_created_at": "2015-11-18T16:30:23",
"gha_language": null,
"gha_license_id": null,
"github_id": 46431847,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7122,
"license": "MIT",
"license_type": "permissive",
"path": "/source/projects/xray.jit.cellvalue/xray.jit.cellvalue.c",
"provenance": "stackv2-0054.json.gz:4666",
"repo_name": "Cycling74/xray.jit-1",
"revision_date": "2021-08-13T18:16:47",
"revision_id": "58f9c891c5c3a0e4bd42ed9977f8328a71c581c2",
"snapshot_id": "d354e17cfba0f1a2ded6224710ef9f54875fd17d",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Cycling74/xray.jit-1/58f9c891c5c3a0e4bd42ed9977f8328a71c581c2/source/projects/xray.jit.cellvalue/xray.jit.cellvalue.c",
"visit_date": "2021-08-28T16:03:04.103613"
}
|
stackv2
|
/*
xray.jit.cellminmax
Wesley Smith
wesley.hoke@gmail.com
last modified: 12-7-2006
*/
#include "jit.common.h"
typedef struct _xray_jit_cellvalue {
t_object ob;
} t_xray_jit_cellvalue;
void *_xray_jit_cellvalue_class;
//jitter object/MOP methods
t_jit_err xray_jit_cellvalue_init(void);
t_xray_jit_cellvalue *xray_jit_cellvalue_new(void);
void xray_jit_cellvalue_free(t_xray_jit_cellvalue *x);
t_jit_err xray_jit_cellvalue_matrix_calc(t_xray_jit_cellvalue *x, void *inputs, void *outputs);
//data processing methods
void xray_jit_cellvalue_calculate_ndim(t_xray_jit_cellvalue *obj, long dimcount, long *dim, long planecount,
t_jit_matrix_info *in1_minfo, char *bip1,
t_jit_matrix_info *in2_minfo, char *bip2,
t_jit_matrix_info *out_minfo, char *bop);
t_jit_err xray_jit_cellvalue_init(void)
{
t_jit_object *mop,*o;
t_atom a[1];
_xray_jit_cellvalue_class = jit_class_new("xray_jit_cellvalue",(method)xray_jit_cellvalue_new,(method)xray_jit_cellvalue_free,
sizeof(t_xray_jit_cellvalue),0L);
//add mop - input 1 can be arbitrary 2D, input 2 is a 2-plane 2D float32 matrix
//the output is of the same type and planecont as in1 but of the same dimension as in2
mop = jit_object_new(_jit_sym_jit_mop,2,1);
jit_mop_input_nolink(mop,2);
o = jit_object_method(mop,_jit_sym_getinput,2);
jit_attr_setlong(o,_jit_sym_dimlink,0);
jit_attr_setlong(o,_jit_sym_typelink,0);
jit_attr_setlong(o,_jit_sym_planelink,0);
jit_object_method(o,_jit_sym_ioproc,jit_mop_ioproc_copy_adapt);
jit_atom_setsym(a,_jit_sym_float32);
jit_object_method(o,_jit_sym_types,1,a);
o = jit_object_method(mop,_jit_sym_getoutput,1);
jit_attr_setlong(o,_jit_sym_dimlink,0);
jit_class_addadornment(_xray_jit_cellvalue_class,mop);
//add methods
jit_class_addmethod(_xray_jit_cellvalue_class, (method)xray_jit_cellvalue_matrix_calc, "matrix_calc", A_CANT, 0L);
jit_class_register(_xray_jit_cellvalue_class);
return JIT_ERR_NONE;
}
t_jit_err xray_jit_cellvalue_matrix_calc(t_xray_jit_cellvalue *x, void *inputs, void *outputs)
{
t_jit_err err=JIT_ERR_NONE;
long in1_savelock, in2_savelock, out_savelock;
t_jit_matrix_info in1_minfo, in2_minfo, out_minfo;
char *in1_bp, *in2_bp, *out_bp;
long i,dimcount,planecount,dim[JIT_MATRIX_MAX_DIMCOUNT];
void *in1_matrix, *in2_matrix, *out_matrix;
in1_matrix = jit_object_method(inputs,_jit_sym_getindex,0);
in2_matrix = jit_object_method(inputs,_jit_sym_getindex,1);
out_matrix = jit_object_method(outputs,_jit_sym_getindex,0);
if (x&&in1_matrix&&in2_matrix&&out_matrix) {
in1_savelock = (long) jit_object_method(in1_matrix,_jit_sym_lock,1);
in2_savelock = (long) jit_object_method(in2_matrix,_jit_sym_lock,1);
out_savelock = (long) jit_object_method(out_matrix,_jit_sym_lock,1);
jit_object_method(in1_matrix,_jit_sym_getinfo,&in1_minfo);
jit_object_method(in2_matrix,_jit_sym_getinfo,&in2_minfo);
jit_object_method(in1_matrix,_jit_sym_getdata,&in1_bp);
jit_object_method(in2_matrix,_jit_sym_getdata,&in2_bp);
if (!in1_bp || !in2_bp) { err=JIT_ERR_INVALID_INPUT; goto out;}
//get dimensions/planecount
dimcount = in1_minfo.dimcount;
planecount = in1_minfo.planecount;
for (i=0;i<dimcount;i++) {
dim[i] = in1_minfo.dim[i];
if ((in1_minfo.dim[i]<dim[i])) dim[i] = in1_minfo.dim[i];
}
jit_object_method(out_matrix,_jit_sym_getinfo,&out_minfo);
out_minfo.dim[0] = in2_minfo.dim[0];
out_minfo.dim[1] = in2_minfo.dim[1];
out_minfo.planecount = in1_minfo.planecount;
out_minfo.type = in1_minfo.type;
jit_object_method(out_matrix, _jit_sym_setinfo, &out_minfo);
jit_object_method(out_matrix,_jit_sym_getinfo,&out_minfo);
jit_object_method(out_matrix,_jit_sym_getdata,&out_bp);
if (!out_bp) { err=JIT_ERR_INVALID_OUTPUT; goto out;}
xray_jit_cellvalue_calculate_ndim(x, dimcount, dim, planecount,
&in1_minfo, in1_bp,
&in2_minfo, in2_bp,
&out_minfo, out_bp);
}
else {
return JIT_ERR_INVALID_PTR;
}
out:
jit_object_method(out_matrix,gensym("lock"),out_savelock);
jit_object_method(in2_matrix,gensym("lock"),in2_savelock);
jit_object_method(in1_matrix,gensym("lock"),in1_savelock);
return err;
}
void xray_jit_cellvalue_calculate_ndim(t_xray_jit_cellvalue *obj, long dimcount, long *dim, long planecount,
t_jit_matrix_info *in1_minfo, char *bip1,
t_jit_matrix_info *in2_minfo, char *bip2,
t_jit_matrix_info *out_minfo, char *bop)
{
long i, j, k, width, height;
long width2, height2;
long in1planecount, in1colspan, in1rowspan;
long in2planecount, in2rowspan;
long outplanecount, outrowspan;
float *fip1, *fip2, *fop;
uchar *cip1, *cop;
t_int32 *lip1, *lop;
double *dip1, *dop;
if (dimcount<1) return; //safety
switch(dimcount) {
case 1:
dim[1]=1;
case 2:
width = dim[0];
height = dim[1];
width2 = in2_minfo->dim[0];
height2 = in2_minfo->dim[1];
in1planecount = in1_minfo->planecount;
in1colspan = in1_minfo->dimstride[0];
in1rowspan = in1_minfo->dimstride[1];
in2planecount = in2_minfo->planecount;
in2rowspan = in2_minfo->dimstride[1];
outplanecount = out_minfo->planecount;
outrowspan = out_minfo->dimstride[1];
if (out_minfo->type==_jit_sym_char) {
for(i=0; i < height2; i++) {
fip2 = (float *)(bip2 + i*in2rowspan);
cop = (uchar *)(bop + i*outrowspan);
for(j=0; j < width2; j++) {
cip1 = (uchar *)(bip1 + (long)(fip2[0])*in1colspan + (long)(fip2[1])*in1rowspan);
for(k=0; k < in1planecount; k++) {
cop[k] = cip1[k];
}
fip2 += in2planecount;
cop += outplanecount;
}
}
}
else if (out_minfo->type==_jit_sym_long) {
for(i=0; i < height2; i++) {
fip2 = (float *)(bip2 + i*in2rowspan);
lop = (t_int32 *)(bop + i*outrowspan);
for(j=0; j < width2; j++) {
lip1 = (t_int32 *)(bip1 + (long)(fip2[0])*in1colspan + (long)(fip2[1])*in1rowspan);
for(k=0; k < in1planecount; k++) {
lop[k] = lip1[k];
}
fip2 += in2planecount;
lop += outplanecount;
}
}
}
else if (out_minfo->type==_jit_sym_float32) {
for(i=0; i < height2; i++) {
fip2 = (float *)(bip2 + i*in2rowspan);
fop = (float *)(bop + i*outrowspan);
for(j=0; j < width2; j++) {
fip1 = (float *)(bip1 + (long)(fip2[0])*in1colspan + (long)(fip2[1])*in1rowspan);
for(k=0; k < in1planecount; k++) {
fop[k] = fip1[k];
}
fip2 += in2planecount;
fop += outplanecount;
}
}
}
else if (out_minfo->type==_jit_sym_float64) {
for(i=0; i < height2; i++) {
fip2 = (float *)(bip2 + i*in2rowspan);
dop = (double *)(bop + i*outrowspan);
for(j=0; j < width2; j++) {
dip1 = (double *)(bip1 + (long)(fip2[0])*in1colspan + (long)(fip2[1])*in1rowspan);
for(k=0; k < in1planecount; k++) {
dop[k] = dip1[k];
}
fip2 += in2planecount;
dop += outplanecount;
}
}
}
break;
default:
;
}
}
t_xray_jit_cellvalue *xray_jit_cellvalue_new(void)
{
t_xray_jit_cellvalue *x;
if (x=(t_xray_jit_cellvalue *)jit_object_alloc(_xray_jit_cellvalue_class)) {
//nothing to do
}
else {
x = NULL;
}
return x;
}
void xray_jit_cellvalue_free(t_xray_jit_cellvalue *x)
{
//nothing to do
}
| 2.296875 | 2 |
2024-11-18T19:35:01.356158+00:00
| 2021-02-25T03:26:58 |
ba29bf12cfd89027e4e1c88dbb30e88dd4202ac7
|
{
"blob_id": "ba29bf12cfd89027e4e1c88dbb30e88dd4202ac7",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-25T03:26:58",
"content_id": "663a38d0b3482066ee4c638addede009dcb29d30",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "cc55b7076d852e98c374599b450836f9244fd7de",
"extension": "c",
"filename": "drv_at24cxx.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 229898355,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4304,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/source/driver/drv_at24cxx.c",
"provenance": "stackv2-0054.json.gz:5309",
"repo_name": "FuxFox/MCU",
"revision_date": "2021-02-25T03:26:58",
"revision_id": "ce4d9ab008079a070b5e45c2f29dda4f06816cc9",
"snapshot_id": "ceec73f73ac7a039d149e44d1f9e25a32efd5438",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/FuxFox/MCU/ce4d9ab008079a070b5e45c2f29dda4f06816cc9/source/driver/drv_at24cxx.c",
"visit_date": "2021-07-10T08:31:32.653562"
}
|
stackv2
|
/*******************************************************************************
*
* Module: drv_at24cxx
*
* History:
* <author> <time> <version> <desc>
* FuxFox 2019/10/16 11:17 V1.0 build this file
*
*******************************************************************************/
/*!
* \file drv_at24cxx.c
* \brief
* \author FuxFox
* \version V1.0
* \date 2019/10/16
*******************************************************************************/
#ifndef DRV_AT24CXX_C
#define DRV_AT24CXX_C
#include "drv_at24cxx.h"
/*!*****************************************************************************
\brief initialize
\param[in] drv_at24cxx_instance_t * instance The parameter '_name' of DRV_AT24Cxx_INSTANCE()
\return bool TRUE if found the device
******************************************************************************/
bool drv_at24cxx_init(drv_at24cxx_instance_t* instance)
{
instance->driver.reg_addr_16bit = (instance->device_type > AT24C02);
if (instance->device_type == AT24C01) instance->page_size = 8;
else if (instance->device_type <= AT24C16) instance->page_size = 16;
else if (instance->device_type <= AT24C64) instance->page_size = 32;
else if (instance->device_type <= AT24C256) instance->page_size = 64;
return drv_iic_init(&instance->driver);
}
/*!*****************************************************************************
\brief is device ready ?
\details
\param[in] drv_at24cxx_instance_t * instance
\return bool TRUE if ready.
******************************************************************************/
bool drv_at24cxx_is_ready(drv_at24cxx_instance_t* instance)
{
return drv_iic_address(&instance->driver);
}
/*!*****************************************************************************
\brief wait device standby
\param[in] drv_at24cxx_instance_t * instance
\return bool return not zero if device ready, return zero if timeout
******************************************************************************/
bool drv_at24cxx_wait_ready(drv_at24cxx_instance_t* instance)
{
uint8_t i = 120;
while ((i-- > 0) && !drv_iic_address(&instance->driver));
return i;
}
/*!*****************************************************************************
\brief read
\param[in] drv_at24cxx_instance_t * instance
\param[in] uint16_t ptr The pointer of device memory to be read
\param[in] uint8_t * buf The buffer to receive data
\param[in] uint16_t len The number of bytes to read
\return bool TRUE if success.
******************************************************************************/
bool drv_at24cxx_read(drv_at24cxx_instance_t* instance, uint16_t ptr, uint8_t* buf, uint16_t len)
{
if (drv_at24cxx_wait_ready(instance))
{
return drv_iic_read(&instance->driver, ptr, buf, len);
}
return false;
}
/*!*****************************************************************************
\brief write, support page write
\param[in] drv_at24cxx_instance_t * instance
\param[in] uint16_t ptr The pointer of device memory to be write
\param[in] uint8_t * buf The buffer of data to be write
\param[in] uint16_t len The number of bytes to be write
\return bool TRUE if success
******************************************************************************/
bool drv_at24cxx_write(drv_at24cxx_instance_t* instance, uint16_t ptr, uint8_t* buf, uint16_t len)
{
if (drv_at24cxx_wait_ready(instance))
{
return false;
}
while (len)
{
if (len >= instance->page_size)
{
if (!drv_iic_write(&instance->driver, ptr, buf, instance->page_size))
{
return false;
}
len -= instance->page_size;
ptr += instance->page_size;
buf += instance->page_size;
}
else
{
return drv_iic_write(&instance->driver, ptr, buf, len);
}
app_delay_ms(20);
}
return true;
}
#endif // DRV_AT24CXX_C
| 2.171875 | 2 |
2024-11-18T19:35:01.411660+00:00
| 2020-07-18T12:43:35 |
d5d66c5d7a2f1869bb8e18082a6579ded3e1de24
|
{
"blob_id": "d5d66c5d7a2f1869bb8e18082a6579ded3e1de24",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-18T12:43:35",
"content_id": "e750d153510351af303ac0a6a24be64fd7d77e6e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fd51f79dfdf117d1decd343cea7fefade1fe1e0d",
"extension": "c",
"filename": "posix-download.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 280652584,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6560,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/examples/posix/posix-download.c",
"provenance": "stackv2-0054.json.gz:5437",
"repo_name": "MrDOS/librbr",
"revision_date": "2020-07-18T12:43:35",
"revision_id": "06f529bb7da9625dddab9822895e7ef4f12fc18a",
"snapshot_id": "7cc8964e3c81c10053fe58c4d4e14e616edb131c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MrDOS/librbr/06f529bb7da9625dddab9822895e7ef4f12fc18a/examples/posix/posix-download.c",
"visit_date": "2022-11-21T22:22:26.319492"
}
|
stackv2
|
/**
* \file posix-download.c
*
* \brief Example of using the library to download instrument data in a POSIX
* environment.
*
* \copyright
* Copyright (c) 2018 RBR Ltd.
* Licensed under the Apache License, Version 2.0.
*/
/* Prerequisite for PATH_MAX in limits.h. */
#define _POSIX_C_SOURCE 200112L
/* Required for errno. */
#include <errno.h>
/* Required for open. */
#include <fcntl.h>
/* Required for PATH_MAX. */
#include <limits.h>
/* Required for fprintf, printf, snprintf. */
#include <stdio.h>
/* Required for strerror. */
#include <string.h>
/* Required for open. */
#include <sys/stat.h>
/* Required for clock_gettime. */
#include <time.h>
/* Required for close, write. */
#include <unistd.h>
#include "posix-shared.h"
#define CHUNK_SIZE 4096
int main(int argc, char *argv[])
{
char *programName = argv[0];
char *devicePath;
int status = EXIT_SUCCESS;
int instrumentFd;
RBRInstrumentError err;
RBRInstrument *instrument = NULL;
if (argc < 2)
{
fprintf(stderr, "Usage: %s device\n", argv[0]);
return EXIT_FAILURE;
}
devicePath = argv[1];
if ((instrumentFd = openSerialFd(devicePath)) < 0)
{
fprintf(stderr, "%s: Failed to open serial device: %s!\n",
programName,
strerror(errno));
return EXIT_FAILURE;
}
fprintf(stderr,
"%s: Using %s v%s (built %s).\n",
programName,
RBRINSTRUMENT_LIB_NAME,
RBRINSTRUMENT_LIB_VERSION,
RBRINSTRUMENT_LIB_BUILD_DATE);
RBRInstrumentCallbacks callbacks = {
.time = instrumentTime,
.sleep = instrumentSleep,
.read = instrumentRead,
.write = instrumentWrite
};
if ((err = RBRInstrument_open(
&instrument,
&callbacks,
INSTRUMENT_COMMAND_TIMEOUT_MSEC,
(void *) &instrumentFd)) != RBRINSTRUMENT_SUCCESS)
{
fprintf(stderr, "%s: Failed to establish instrument connection: %s!\n",
programName,
RBRInstrumentError_name(err));
status = EXIT_FAILURE;
goto serialCleanup;
}
printf(
"Looks like I'm connected to a %s instrument.\n",
RBRInstrumentGeneration_name(RBRInstrument_getGeneration(instrument)));
RBRInstrumentId id;
RBRInstrument_getId(instrument, &id);
printf("The instrument is an %s (fwtype %d), serial number %06d, with "
"firmware v%s.\n",
id.model,
id.fwtype,
id.serial,
id.version);
RBRInstrumentHardwareRevision hwrev;
RBRInstrument_getHardwareRevision(instrument, &hwrev);
printf("It's PCB rev%c, CPU rev%s, BSL v%c.\n",
hwrev.pcb,
hwrev.cpu,
hwrev.bsl);
RBRInstrumentMemoryInfo meminfo;
meminfo.dataset = RBRINSTRUMENT_DATASET_STANDARD;
RBRInstrument_getMemoryInfo(instrument, &meminfo);
printf("Dataset %s is %0.2f%% full (%" PRIi32 "B used).\n",
RBRInstrumentDataset_name(meminfo.dataset),
((float) meminfo.used) / meminfo.size * 100,
meminfo.used);
RBRInstrumentMemoryFormat memformat;
RBRInstrument_getAvailableMemoryFormats(instrument, &memformat);
printf("It supports these memory formats:\n");
for (int i = RBRINSTRUMENT_MEMFORMAT_NONE + 1;
i <= RBRINSTRUMENT_MEMFORMAT_MAX;
i <<= 1)
{
if (memformat & i)
{
printf("\t%s\n", RBRInstrumentMemoryFormat_name(i));
}
}
RBRInstrument_getCurrentMemoryFormat(instrument, &memformat);
printf("It's currently storing data of format %s.\n",
RBRInstrumentMemoryFormat_name(memformat));
char filename[PATH_MAX + 1];
snprintf(filename, sizeof(filename), "%06d.bin", id.serial);
int downloadFd;
if ((downloadFd = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0644)) < 0)
{
fprintf(stderr, "%s: Failed to open output file: %s!\n",
programName,
strerror(errno));
status = EXIT_FAILURE;
goto instrumentCleanup;
}
struct stat stat;
if (fstat(downloadFd, &stat) < 0)
{
fprintf(stderr, "%s: Failed to stat output file: %s!\n",
programName,
strerror(errno));
status = EXIT_FAILURE;
goto fileCleanup;
}
int32_t initialOffset = stat.st_size;
if (initialOffset == 0)
{
printf("It looks like the output file, %s, is new. Downloading from "
"the beginning of instrument memory.\n",
filename);
}
else
{
printf("It looks like the output file, %s, already contains %" PRIi32
"B. I'll resume the instrument download from there.\n",
filename,
initialOffset);
}
uint8_t buf[CHUNK_SIZE];
RBRInstrumentData data = {
.dataset = meminfo.dataset,
.offset = initialOffset,
.data = buf
};
printf("Downloading:\n");
struct timespec start;
struct timespec now;
double elapsed = 0.0;
double rate = 0.0;
clock_gettime(CLOCK_MONOTONIC, &start);
while (data.offset < meminfo.used)
{
data.size = sizeof(buf);
err = RBRInstrument_readData(instrument, &data);
if (err == RBRINSTRUMENT_SUCCESS)
{
write(downloadFd, data.data, data.size);
data.offset += data.size;
}
else if (err == RBRINSTRUMENT_TIMEOUT)
{
printf("\nWarning: timeout. Retrying...\n");
}
else
{
printf("\nError: %s", RBRInstrumentError_name(err));
break;
}
clock_gettime(CLOCK_MONOTONIC, &now);
elapsed = now.tv_sec - start.tv_sec;
elapsed *= 1000000000L;
elapsed += now.tv_nsec - start.tv_nsec;
elapsed /= 1000000000L;
rate = elapsed > 0.0 ? (data.offset - initialOffset) / elapsed : 0.0;
printf("\r%0.2f%% (%" PRIi32 "B/%" PRIi32 "B; %0.3fs elapsed; "
"%0.3fB/s)",
(((float) data.offset) / meminfo.used) * 100,
data.offset,
meminfo.used,
elapsed,
rate);
}
printf("\nDone. Downloaded %" PRIi32 "B in %0.3fs (%0.3fB/s).\n",
data.offset,
elapsed,
rate);
fileCleanup:
close(downloadFd);
instrumentCleanup:
RBRInstrument_close(instrument);
serialCleanup:
close(instrumentFd);
return status;
}
| 2.5 | 2 |
2024-11-18T19:35:02.366318+00:00
| 2015-04-09T13:02:52 |
7adc7efc99c414da9e4207dd063605b27f454710
|
{
"blob_id": "7adc7efc99c414da9e4207dd063605b27f454710",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-09T13:02:52",
"content_id": "31f15b3e536d690f9e29a05eccf8d7e360695d1b",
"detected_licenses": [
"MIT"
],
"directory_id": "d3672b26d103616f61651c77c7ec9b3303d83763",
"extension": "c",
"filename": "compressFile.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": 4104,
"license": "MIT",
"license_type": "permissive",
"path": "/Marakulin/archiver/compressFile.c",
"provenance": "stackv2-0054.json.gz:5951",
"repo_name": "mostlybrainless/acroparallels2015",
"revision_date": "2015-04-09T13:02:52",
"revision_id": "0c9f8bd765c278bc5bd57670eedc445f5632133b",
"snapshot_id": "53b369d535a7fc9a68e69f7ae9ddc58728972d3b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mostlybrainless/acroparallels2015/0c9f8bd765c278bc5bd57670eedc445f5632133b/Marakulin/archiver/compressFile.c",
"visit_date": "2020-05-02T02:31:23.055688"
}
|
stackv2
|
#include "compressFile.h"
// Big file we divide into several small
#define BLOCK_SIZE 1048576
int compressFile(int fdIn, int fdOut)
{
struct stat inStat;
fstat(fdIn, &inStat);
// For output file
PrefixOfFile pF;
pF.st_mode = inStat.st_mode;
pF.st_size = inStat.st_size;
pF.numbBlocks = 0;
pF.offsetNextBlock = 0;
// Properties for dividing into blocks
off_t restToCompress = inStat.st_size;
uLongf destLen = 0;
uLongf destLenApprox = 0;
off_t offsetNextBlock = 0;
const Bytef* addr = (const Bytef*)mmap(NULL, pF.st_size, PROT_READ, MAP_PRIVATE, fdIn, 0);
// First Block
destLenApprox = compressBound( ((restToCompress < BLOCK_SIZE) ? restToCompress : BLOCK_SIZE) );
Bytef* outAddr = (Bytef*)calloc(destLenApprox+sizeof(PrefixOfFile), sizeof(Bytef));
destLen = destLenApprox;
if (Z_OK != compress(outAddr+sizeof(PrefixOfFile), &destLen, addr, (restToCompress < BLOCK_SIZE) ? restToCompress : BLOCK_SIZE ))
{
LOG(ERROR, "Error in compress %d block\n", pF.numbBlocks);
return -1;
}
pF.numbBlocks++;
pF.offsetNextBlock = sizeof(PrefixOfFile)+destLen;
offsetNextBlock = pF.offsetNextBlock;
memcpy(outAddr, &pF, sizeof(PrefixOfFile));
write(fdOut, outAddr, destLen+sizeof(PrefixOfFile));
restToCompress -= BLOCK_SIZE;
// Other blocks
while (restToCompress > 0)
{
destLen = destLenApprox;
if (Z_OK != compress(outAddr+sizeof(off_t), &destLen, addr+offsetNextBlock, (restToCompress < BLOCK_SIZE) ? restToCompress : BLOCK_SIZE))
{
LOG(ERROR, "Error in compress %d block\n", pF.numbBlocks);
return -1;
}
pF.numbBlocks++;
offsetNextBlock += (sizeof(off_t)+destLen);
memcpy(outAddr, &offsetNextBlock, sizeof(off_t));
write(fdOut, outAddr, destLen+sizeof(off_t));
restToCompress -= BLOCK_SIZE;
}
pF.hash = getHashSum(fdOut);
LOG(TRACE, "hash = %d", pF.hash);
lseek(fdOut, 0L, 0);
write(fdOut, &pF, sizeof(PrefixOfFile));
LOG(TRACE, "pF.st_mode = %d, pF.st_size = %d", pF.st_mode, pF.st_size);
free(outAddr);
munmap((void*)addr, pF.st_size);
return 0;
}
int uncompressFile(int fdIn, char* outFile)
{
struct stat inStat;
fstat(fdIn, &inStat);
LOG(TRACE, "inStat.st_size = %d", inStat.st_size);
PrefixOfFile pF;
off_t offsetNextBlock = 0;
off_t prevOffsetNextBlock = 0;
const Bytef* addr = (const Bytef*)mmap(NULL, inStat.st_size, PROT_READ, MAP_PRIVATE, fdIn, 0);
memcpy(&pF, addr, sizeof(PrefixOfFile));
if (pF.hash != getHashSum(fdIn))
{
printf("Don't lie me, it isn't .arc file!\n");
return -1;
}
LOG(TRACE, "pF.st_mode = %d, pF.st_size = %d", pF.st_mode, pF.st_size);
int fdOut = open(outFile, O_CREAT | O_WRONLY, pF.st_mode);
if (fdOut == -1)
{
munmap((void*)addr, inStat.st_size-sizeof(PrefixOfFile));
return -1;
}
offsetNextBlock = pF.offsetNextBlock;
prevOffsetNextBlock = sizeof(PrefixOfFile)-sizeof(off_t); // It is the difference in the beginning of the first and subsequent blocks
uLongf destLen = 0;
destLen = BLOCK_SIZE;
Bytef* outAddr = (Bytef*)calloc(((pF.st_size < BLOCK_SIZE) ? pF.st_size : BLOCK_SIZE), sizeof(Bytef));
int curBlock = 1;
while (curBlock <= pF.numbBlocks)
{
if (pF.numbBlocks == 1)
destLen = (pF.st_size % (int)BLOCK_SIZE);
if (Z_OK != uncompress(outAddr, &destLen, addr+sizeof(off_t)+prevOffsetNextBlock,
((curBlock == 1) ? (offsetNextBlock-sizeof(PrefixOfFile)) : (offsetNextBlock-prevOffsetNextBlock)) ))
{
LOG(ERROR, "error with decompress %d block\n", curBlock);
return -1;
}
write(fdOut, outAddr, destLen);
curBlock++;
prevOffsetNextBlock = offsetNextBlock;
if(curBlock <= pF.numbBlocks)
memcpy(&offsetNextBlock, addr+offsetNextBlock, sizeof(off_t));
}
close(fdOut);
munmap((void*)addr, inStat.st_size);
free(outAddr);
return 0;
}
| 2.546875 | 3 |
2024-11-18T19:35:03.305789+00:00
| 2018-04-02T05:27:09 |
d63b1e72ed55cbd0392ba6d23f23a8362a0b0f19
|
{
"blob_id": "d63b1e72ed55cbd0392ba6d23f23a8362a0b0f19",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-02T05:27:09",
"content_id": "b5e562571987d7db052fd9c19fdd288944dc76ca",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "19a55ecb3821aafaa51a90d05013cc57a8c85e67",
"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": 142988232,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 871,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0054.json.gz:6593",
"repo_name": "limboaz/CSE320-hw3",
"revision_date": "2018-04-02T05:27:09",
"revision_id": "2cc4321d81bf337d2c12e402ff1416f5a060eef6",
"snapshot_id": "41b6e085dc7350a7314c0afdeb0596913fbbc7f2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/limboaz/CSE320-hw3/2cc4321d81bf337d2c12e402ff1416f5a060eef6/main.c",
"visit_date": "2020-03-24T20:37:31.226350"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc, char** argv){
pid_t sh_pid;
char buf[256];
if (argc != 2){
printf("Invalid input.\n");
exit(0);
}
while(1){
printf("Please select from the following menu:\nsolver\ntrace\nfib\nquit\nchange\n");
scanf("%s", argv[0]);
if ( strcmp(argv[0], "quit") == 0){
exit(0);
//wait(NULL);
}
if ( strcmp(argv[0], "fib") == 0){
strcpy(buf, argv[1]);
FILE *f = fopen(argv[1], "r");
fscanf(f, "%s", argv[1]);
fclose(f);
}
if ( strcmp(argv[0], "change") == 0){
scanf("%s", argv[1]);
} else if ((sh_pid = fork()) == 0){
execve(argv[0], argv, NULL);
exit(0);
} else {
waitpid(sh_pid, NULL, 0);
}
if ( strcmp(argv[0], "fib") == 0)
strcpy(argv[1],buf);
wait(NULL);
}
return 0;
}
| 2.609375 | 3 |
2024-11-18T19:35:03.587071+00:00
| 2018-05-14T15:42:00 |
83d719ec65555ded53edee34ff5f422b7eac7904
|
{
"blob_id": "83d719ec65555ded53edee34ff5f422b7eac7904",
"branch_name": "refs/heads/develop",
"committer_date": "2018-05-14T15:42:00",
"content_id": "13b1e2ae2f485f387ddb5ff4cdcea21b4fbc4ed2",
"detected_licenses": [
"MIT"
],
"directory_id": "ece818f565ef286ea32f3b998ae65021f9ed7ea9",
"extension": "c",
"filename": "mccp.c",
"fork_events_count": 20,
"gha_created_at": "2018-01-25T23:12:54",
"gha_event_created_at": "2018-05-14T15:42:01",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 118978584,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3855,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mccp.c",
"provenance": "stackv2-0054.json.gz:7105",
"repo_name": "mudcoders/guildmud",
"revision_date": "2018-05-14T15:42:00",
"revision_id": "3771496b887573ca869b818770092e79211cd1c6",
"snapshot_id": "2dd815e93ecec6a8fe0810c8bd6d1dcddd2d371c",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/mudcoders/guildmud/3771496b887573ca869b818770092e79211cd1c6/src/mccp.c",
"visit_date": "2021-09-14T13:46:42.456768"
}
|
stackv2
|
/*
* mccp.c - support functions for the Mud Client Compression Protocol
*
* see http://www.randomly.org/projects/MCCP/
*
* Copyright (c) 1999, Oliver Jowett <oliver@randomly.org>
*
* This code may be freely distributed and used if this copyright
* notice is retained intact.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include "mud.h"
/* local functions */
bool processCompressed ( D_SOCKET *dsock );
const unsigned char enable_compress [] = { IAC, SB, TELOPT_COMPRESS, WILL, SE, 0 };
const unsigned char enable_compress2 [] = { IAC, SB, TELOPT_COMPRESS2, IAC, SE, 0 };
/*
* Memory management - zlib uses these hooks to allocate and free memory
* it needs
*/
void *zlib_alloc(void *opaque, unsigned int items, unsigned int size)
{
return calloc(items, size);
}
void zlib_free(void *opaque, void *address)
{
free(address);
}
/*
* Begin compressing data on `desc'
*/
bool compressStart(D_SOCKET *dsock, unsigned char teleopt)
{
z_stream *s;
/* already compressing */
if (dsock->out_compress)
return true;
/* allocate and init stream, buffer */
s = (z_stream *) malloc(sizeof(*s));
dsock->out_compress_buf = (unsigned char *) malloc(COMPRESS_BUF_SIZE);
s->next_in = NULL;
s->avail_in = 0;
s->next_out = dsock->out_compress_buf;
s->avail_out = COMPRESS_BUF_SIZE;
s->zalloc = zlib_alloc;
s->zfree = zlib_free;
s->opaque = NULL;
if (deflateInit(s, 9) != Z_OK)
{
free(dsock->out_compress_buf);
free(s);
return false;
}
/* version 1 or 2 support */
if (teleopt == TELOPT_COMPRESS)
text_to_socket(dsock, (char *) enable_compress);
else if (teleopt == TELOPT_COMPRESS2)
text_to_socket(dsock, (char *) enable_compress2);
else
{
bug("Bad teleoption %d passed", teleopt);
free(dsock->out_compress_buf);
free(s);
return false;
}
/* now we're compressing */
dsock->compressing = teleopt;
dsock->out_compress = s;
/* success */
return true;
}
/* Cleanly shut down compression on `desc' */
bool compressEnd(D_SOCKET *dsock, unsigned char teleopt, bool forced)
{
unsigned char dummy[1];
if (!dsock->out_compress)
return true;
if (dsock->compressing != teleopt)
return false;
dsock->out_compress->avail_in = 0;
dsock->out_compress->next_in = dummy;
dsock->top_output = 0;
/* No terminating signature is needed - receiver will get Z_STREAM_END */
if (deflate(dsock->out_compress, Z_FINISH) != Z_STREAM_END && !forced)
return false;
/* try to send any residual data */
if (!processCompressed(dsock) && !forced)
return false;
/* reset compression values */
deflateEnd(dsock->out_compress);
free(dsock->out_compress_buf);
free(dsock->out_compress);
dsock->compressing = 0;
dsock->out_compress = NULL;
dsock->out_compress_buf = NULL;
/* success */
return true;
}
/* Try to send any pending compressed-but-not-sent data in `desc' */
bool processCompressed(D_SOCKET *dsock)
{
int iStart, nBlock, nWrite, len;
if (!dsock->out_compress)
return true;
len = dsock->out_compress->next_out - dsock->out_compress_buf;
if (len > 0)
{
for (iStart = 0; iStart < len; iStart += nWrite)
{
nBlock = UMIN (len - iStart, 4096);
if ((nWrite = write(dsock->control, dsock->out_compress_buf + iStart, nBlock)) < 0)
{
if (errno == EAGAIN || errno == ENOSR)
break;
/* write error */
return false;
}
if (nWrite <= 0)
break;
}
if (iStart)
{
if (iStart < len)
memmove(dsock->out_compress_buf, dsock->out_compress_buf+iStart, len - iStart);
dsock->out_compress->next_out = dsock->out_compress_buf + len - iStart;
}
}
/* success */
return true;
}
| 2.390625 | 2 |
2024-11-18T19:35:03.754260+00:00
| 2020-11-22T03:30:00 |
0c64c61fabd7808cb30183a56e41e90d9d712683
|
{
"blob_id": "0c64c61fabd7808cb30183a56e41e90d9d712683",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-22T03:30:00",
"content_id": "51f8058d112a9df1bd66cd0d9324ba9c82b6a752",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "fe2e59c8e209be91bcfa332b1a0a2489ae053ab9",
"extension": "c",
"filename": "tdump.c",
"fork_events_count": 0,
"gha_created_at": "2019-11-24T04:17:13",
"gha_event_created_at": "2019-11-24T04:17:13",
"gha_language": null,
"gha_license_id": "BSD-3-Clause",
"github_id": 223691230,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2804,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/tdump.c",
"provenance": "stackv2-0054.json.gz:7233",
"repo_name": "tmiw/LPCNet",
"revision_date": "2020-11-22T03:30:00",
"revision_id": "2c17242409516ab45e2996e37c85f45383e2b526",
"snapshot_id": "33cdd316085498fd64ce63f4fc78b88d0f290223",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tmiw/LPCNet/2c17242409516ab45e2996e37c85f45383e2b526/src/tdump.c",
"visit_date": "2022-09-15T15:08:56.925473"
}
|
stackv2
|
/*
tdump.c
Feb 2019
Simplified version of dump_data.c, stepping stone to lpcnet API.
*/
/* Copyright (c) 2017-2018 Mozilla */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 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 FOUNDATION 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.
*/
#include <stdlib.h>
#include <stdio.h>
#include "lpcnet_dump.h"
int main(int argc, char **argv) {
FILE *f1;
FILE *ffeat;
LPCNET_DUMP *d;
d = lpcnet_dump_create();
if (argc != 3) {
fprintf(stderr, "Too few arguments\n");
fprintf(stderr, "usage: %s <speech> <features out>\n", argv[0]);
exit(1);
}
if (strcmp(argv[1], "-") == 0)
f1 = stdin;
else {
f1 = fopen(argv[1], "rb");
if (f1 == NULL) {
fprintf(stderr,"Error opening input .s16 16kHz speech input file: %s\n", argv[1]);
exit(1);
}
}
if (strcmp(argv[2], "-") == 0)
ffeat = stdout;
else {
ffeat = fopen(argv[2], "wb");
if (ffeat == NULL) {
fprintf(stderr,"Error opening output feature file: %s\n", argv[2]);
exit(1);
}
}
float x[FRAME_SIZE];
float features[LPCNET_NB_FEATURES];
int i;
int f=0;
int nread;
while (1) {
/* note one frame delay */
for (i=0;i<FRAME_SIZE;i++) x[i] = d->tmp[i];
nread = fread(&d->tmp, sizeof(short), FRAME_SIZE, f1);
if (nread != FRAME_SIZE) break;
lpcnet_dump(d,x,features);
fwrite(features, sizeof(float), LPCNET_NB_FEATURES, ffeat);
f++;
}
fprintf(stderr, "%d %d %d\n", f, FRAME_SIZE, LPCNET_NB_FEATURES);
fclose(f1);
fclose(ffeat);
lpcnet_dump_destroy(d);
return 0;
}
| 2.015625 | 2 |
2024-11-18T19:35:06.163518+00:00
| 2022-08-20T10:58:23 |
dab0576782e83b96e9916d7bf65f5dae3bd9b86f
|
{
"blob_id": "dab0576782e83b96e9916d7bf65f5dae3bd9b86f",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-20T10:58:23",
"content_id": "a0ebf1b53ef7aece0ecf4b39cf8c03521dfaf227",
"detected_licenses": [
"MIT"
],
"directory_id": "597b8448eb79e54d03ce0010d2cc3ae56f9dcfd1",
"extension": "c",
"filename": "ili9341.c",
"fork_events_count": 32,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 136807101,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8426,
"license": "MIT",
"license_type": "permissive",
"path": "/Lib/ili9341/ili9341.c",
"provenance": "stackv2-0054.json.gz:7361",
"repo_name": "afiskon/stm32-ili9341",
"revision_date": "2022-08-20T10:58:23",
"revision_id": "095939fe5891167cbbb6c9d6f6f6e5cddf2c9bfc",
"snapshot_id": "0d367871660804dbdeefd8a745931ad54950496e",
"src_encoding": "UTF-8",
"star_events_count": 80,
"url": "https://raw.githubusercontent.com/afiskon/stm32-ili9341/095939fe5891167cbbb6c9d6f6f6e5cddf2c9bfc/Lib/ili9341/ili9341.c",
"visit_date": "2022-09-05T18:58:42.742061"
}
|
stackv2
|
/* vim: set ai et ts=4 sw=4: */
#include "stm32f4xx_hal.h"
#include "ili9341.h"
static void ILI9341_Select() {
HAL_GPIO_WritePin(ILI9341_CS_GPIO_Port, ILI9341_CS_Pin, GPIO_PIN_RESET);
}
void ILI9341_Unselect() {
HAL_GPIO_WritePin(ILI9341_CS_GPIO_Port, ILI9341_CS_Pin, GPIO_PIN_SET);
}
static void ILI9341_Reset() {
HAL_GPIO_WritePin(ILI9341_RES_GPIO_Port, ILI9341_RES_Pin, GPIO_PIN_RESET);
HAL_Delay(5);
HAL_GPIO_WritePin(ILI9341_RES_GPIO_Port, ILI9341_RES_Pin, GPIO_PIN_SET);
}
static void ILI9341_WriteCommand(uint8_t cmd) {
HAL_GPIO_WritePin(ILI9341_DC_GPIO_Port, ILI9341_DC_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(&ILI9341_SPI_PORT, &cmd, sizeof(cmd), HAL_MAX_DELAY);
}
static void ILI9341_WriteData(uint8_t* buff, size_t buff_size) {
HAL_GPIO_WritePin(ILI9341_DC_GPIO_Port, ILI9341_DC_Pin, GPIO_PIN_SET);
// split data in small chunks because HAL can't send more then 64K at once
while(buff_size > 0) {
uint16_t chunk_size = buff_size > 32768 ? 32768 : buff_size;
HAL_SPI_Transmit(&ILI9341_SPI_PORT, buff, chunk_size, HAL_MAX_DELAY);
buff += chunk_size;
buff_size -= chunk_size;
}
}
static void ILI9341_SetAddressWindow(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) {
// column address set
ILI9341_WriteCommand(0x2A); // CASET
{
uint8_t data[] = { (x0 >> 8) & 0xFF, x0 & 0xFF, (x1 >> 8) & 0xFF, x1 & 0xFF };
ILI9341_WriteData(data, sizeof(data));
}
// row address set
ILI9341_WriteCommand(0x2B); // RASET
{
uint8_t data[] = { (y0 >> 8) & 0xFF, y0 & 0xFF, (y1 >> 8) & 0xFF, y1 & 0xFF };
ILI9341_WriteData(data, sizeof(data));
}
// write to RAM
ILI9341_WriteCommand(0x2C); // RAMWR
}
void ILI9341_Init() {
ILI9341_Select();
ILI9341_Reset();
// command list is based on https://github.com/martnak/STM32-ILI9341
// SOFTWARE RESET
ILI9341_WriteCommand(0x01);
HAL_Delay(1000);
// POWER CONTROL A
ILI9341_WriteCommand(0xCB);
{
uint8_t data[] = { 0x39, 0x2C, 0x00, 0x34, 0x02 };
ILI9341_WriteData(data, sizeof(data));
}
// POWER CONTROL B
ILI9341_WriteCommand(0xCF);
{
uint8_t data[] = { 0x00, 0xC1, 0x30 };
ILI9341_WriteData(data, sizeof(data));
}
// DRIVER TIMING CONTROL A
ILI9341_WriteCommand(0xE8);
{
uint8_t data[] = { 0x85, 0x00, 0x78 };
ILI9341_WriteData(data, sizeof(data));
}
// DRIVER TIMING CONTROL B
ILI9341_WriteCommand(0xEA);
{
uint8_t data[] = { 0x00, 0x00 };
ILI9341_WriteData(data, sizeof(data));
}
// POWER ON SEQUENCE CONTROL
ILI9341_WriteCommand(0xED);
{
uint8_t data[] = { 0x64, 0x03, 0x12, 0x81 };
ILI9341_WriteData(data, sizeof(data));
}
// PUMP RATIO CONTROL
ILI9341_WriteCommand(0xF7);
{
uint8_t data[] = { 0x20 };
ILI9341_WriteData(data, sizeof(data));
}
// POWER CONTROL,VRH[5:0]
ILI9341_WriteCommand(0xC0);
{
uint8_t data[] = { 0x23 };
ILI9341_WriteData(data, sizeof(data));
}
// POWER CONTROL,SAP[2:0];BT[3:0]
ILI9341_WriteCommand(0xC1);
{
uint8_t data[] = { 0x10 };
ILI9341_WriteData(data, sizeof(data));
}
// VCM CONTROL
ILI9341_WriteCommand(0xC5);
{
uint8_t data[] = { 0x3E, 0x28 };
ILI9341_WriteData(data, sizeof(data));
}
// VCM CONTROL 2
ILI9341_WriteCommand(0xC7);
{
uint8_t data[] = { 0x86 };
ILI9341_WriteData(data, sizeof(data));
}
// MEMORY ACCESS CONTROL
ILI9341_WriteCommand(0x36);
{
uint8_t data[] = { 0x48 };
ILI9341_WriteData(data, sizeof(data));
}
// PIXEL FORMAT
ILI9341_WriteCommand(0x3A);
{
uint8_t data[] = { 0x55 };
ILI9341_WriteData(data, sizeof(data));
}
// FRAME RATIO CONTROL, STANDARD RGB COLOR
ILI9341_WriteCommand(0xB1);
{
uint8_t data[] = { 0x00, 0x18 };
ILI9341_WriteData(data, sizeof(data));
}
// DISPLAY FUNCTION CONTROL
ILI9341_WriteCommand(0xB6);
{
uint8_t data[] = { 0x08, 0x82, 0x27 };
ILI9341_WriteData(data, sizeof(data));
}
// 3GAMMA FUNCTION DISABLE
ILI9341_WriteCommand(0xF2);
{
uint8_t data[] = { 0x00 };
ILI9341_WriteData(data, sizeof(data));
}
// GAMMA CURVE SELECTED
ILI9341_WriteCommand(0x26);
{
uint8_t data[] = { 0x01 };
ILI9341_WriteData(data, sizeof(data));
}
// POSITIVE GAMMA CORRECTION
ILI9341_WriteCommand(0xE0);
{
uint8_t data[] = { 0x0F, 0x31, 0x2B, 0x0C, 0x0E, 0x08, 0x4E, 0xF1,
0x37, 0x07, 0x10, 0x03, 0x0E, 0x09, 0x00 };
ILI9341_WriteData(data, sizeof(data));
}
// NEGATIVE GAMMA CORRECTION
ILI9341_WriteCommand(0xE1);
{
uint8_t data[] = { 0x00, 0x0E, 0x14, 0x03, 0x11, 0x07, 0x31, 0xC1,
0x48, 0x08, 0x0F, 0x0C, 0x31, 0x36, 0x0F };
ILI9341_WriteData(data, sizeof(data));
}
// EXIT SLEEP
ILI9341_WriteCommand(0x11);
HAL_Delay(120);
// TURN ON DISPLAY
ILI9341_WriteCommand(0x29);
// MADCTL
ILI9341_WriteCommand(0x36);
{
uint8_t data[] = { ILI9341_ROTATION };
ILI9341_WriteData(data, sizeof(data));
}
ILI9341_Unselect();
}
void ILI9341_DrawPixel(uint16_t x, uint16_t y, uint16_t color) {
if((x >= ILI9341_WIDTH) || (y >= ILI9341_HEIGHT))
return;
ILI9341_Select();
ILI9341_SetAddressWindow(x, y, x+1, y+1);
uint8_t data[] = { color >> 8, color & 0xFF };
ILI9341_WriteData(data, sizeof(data));
ILI9341_Unselect();
}
static void ILI9341_WriteChar(uint16_t x, uint16_t y, char ch, FontDef font, uint16_t color, uint16_t bgcolor) {
uint32_t i, b, j;
ILI9341_SetAddressWindow(x, y, x+font.width-1, y+font.height-1);
for(i = 0; i < font.height; i++) {
b = font.data[(ch - 32) * font.height + i];
for(j = 0; j < font.width; j++) {
if((b << j) & 0x8000) {
uint8_t data[] = { color >> 8, color & 0xFF };
ILI9341_WriteData(data, sizeof(data));
} else {
uint8_t data[] = { bgcolor >> 8, bgcolor & 0xFF };
ILI9341_WriteData(data, sizeof(data));
}
}
}
}
void ILI9341_WriteString(uint16_t x, uint16_t y, const char* str, FontDef font, uint16_t color, uint16_t bgcolor) {
ILI9341_Select();
while(*str) {
if(x + font.width >= ILI9341_WIDTH) {
x = 0;
y += font.height;
if(y + font.height >= ILI9341_HEIGHT) {
break;
}
if(*str == ' ') {
// skip spaces in the beginning of the new line
str++;
continue;
}
}
ILI9341_WriteChar(x, y, *str, font, color, bgcolor);
x += font.width;
str++;
}
ILI9341_Unselect();
}
void ILI9341_FillRectangle(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color) {
// clipping
if((x >= ILI9341_WIDTH) || (y >= ILI9341_HEIGHT)) return;
if((x + w - 1) >= ILI9341_WIDTH) w = ILI9341_WIDTH - x;
if((y + h - 1) >= ILI9341_HEIGHT) h = ILI9341_HEIGHT - y;
ILI9341_Select();
ILI9341_SetAddressWindow(x, y, x+w-1, y+h-1);
uint8_t data[] = { color >> 8, color & 0xFF };
HAL_GPIO_WritePin(ILI9341_DC_GPIO_Port, ILI9341_DC_Pin, GPIO_PIN_SET);
for(y = h; y > 0; y--) {
for(x = w; x > 0; x--) {
HAL_SPI_Transmit(&ILI9341_SPI_PORT, data, sizeof(data), HAL_MAX_DELAY);
}
}
ILI9341_Unselect();
}
void ILI9341_FillScreen(uint16_t color) {
ILI9341_FillRectangle(0, 0, ILI9341_WIDTH, ILI9341_HEIGHT, color);
}
void ILI9341_DrawImage(uint16_t x, uint16_t y, uint16_t w, uint16_t h, const uint16_t* data) {
if((x >= ILI9341_WIDTH) || (y >= ILI9341_HEIGHT)) return;
if((x + w - 1) >= ILI9341_WIDTH) return;
if((y + h - 1) >= ILI9341_HEIGHT) return;
ILI9341_Select();
ILI9341_SetAddressWindow(x, y, x+w-1, y+h-1);
ILI9341_WriteData((uint8_t*)data, sizeof(uint16_t)*w*h);
ILI9341_Unselect();
}
void ILI9341_InvertColors(bool invert) {
ILI9341_Select();
ILI9341_WriteCommand(invert ? 0x21 /* INVON */ : 0x20 /* INVOFF */);
ILI9341_Unselect();
}
| 2.46875 | 2 |
2024-11-18T19:35:06.431416+00:00
| 2020-04-11T01:31:26 |
05483bda524e9940b3c0726b1f43e4b9e74d8a4b
|
{
"blob_id": "05483bda524e9940b3c0726b1f43e4b9e74d8a4b",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-11T01:31:26",
"content_id": "d8afbd2689ba6391c73fbb8557557f620e7c5366",
"detected_licenses": [
"MIT"
],
"directory_id": "a957c4cdc11f6decc2432db16c96026bf13a274e",
"extension": "c",
"filename": "val_nvl.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": 2823,
"license": "MIT",
"license_type": "permissive",
"path": "/val_nvl.c",
"provenance": "stackv2-0054.json.gz:7745",
"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/val_nvl.c",
"visit_date": "2021-01-10T09:05:06.618918"
}
|
stackv2
|
/*
* Copyright (c) 2018 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/mem.h>
#include "val_impl.h"
static struct mem_cache *nvpair_cache;
static void __attribute__((constructor)) init_val_subsys(void)
{
nvpair_cache = mem_cache_create("nvpair-cache", sizeof(struct nvpair),
0);
ASSERT(!IS_ERR(nvpair_cache));
}
struct nvpair *__nvpair_alloc(struct str *name)
{
struct nvpair *pair;
pair = mem_cache_alloc(nvpair_cache);
if (!pair) {
str_putref(name);
return NULL;
}
/*
* Avoid returning with a NULL pointer. Of all the types, VT_NULL
* is the least out of place.
*
* (We use VAL_ALLOC_NULL here to make it painfully clear that
* ->value is valid later on, even though we could have used
* val_alloc_null directly as it never fails.)
*/
pair->name = name;
pair->value = VAL_ALLOC_NULL();
return pair;
}
void __nvpair_free(struct nvpair *pair)
{
str_putref(pair->name);
val_putref(pair->value);
mem_cache_free(nvpair_cache, pair);
}
static int val_nvl_cmp(const void *va, const void *vb)
{
const struct nvpair *a = va;
const struct nvpair *b = vb;
return str_cmp(a->name, b->name);
}
struct val *val_alloc_nvl(void)
{
struct val *val;
val = __val_alloc(VT_NVL);
if (IS_ERR(val))
return val;
rb_create(&val->_set_nvl.values, val_nvl_cmp, sizeof(struct nvpair),
offsetof(struct nvpair, node));
return val;
}
void __val_free_nvl(struct val *val)
{
struct rb_cookie cookie;
struct nvpair *cur;
ASSERT(val);
ASSERT3U(refcnt_read(&val->refcnt), ==, 0);
ASSERT3U(val->type, ==, VT_NVL);
memset(&cookie, 0, sizeof(struct rb_cookie));
while ((cur = rb_destroy_nodes(&val->_set_nvl.values, &cookie)))
__nvpair_free(cur);
rb_destroy(&val->_set_nvl.values);
}
| 2.328125 | 2 |
2024-11-18T19:35:06.572988+00:00
| 2023-08-07T16:46:22 |
1e6dcae48a5f61307f5bc5a6b160bed0f3cb98a7
|
{
"blob_id": "1e6dcae48a5f61307f5bc5a6b160bed0f3cb98a7",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-07T16:46:22",
"content_id": "1a1fcd6a7e5a14ecb2ce7ab35f50ab59085a612e",
"detected_licenses": [
"MIT"
],
"directory_id": "cfce52a79f3a7bf6de520fffa3dcf3ad89ed9f08",
"extension": "c",
"filename": "main.c",
"fork_events_count": 7,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 73624431,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3335,
"license": "MIT",
"license_type": "permissive",
"path": "/17 - EEPROM/main.c",
"provenance": "stackv2-0054.json.gz:8003",
"repo_name": "NevynUK/The-Way-of-the-Register",
"revision_date": "2023-08-07T16:46:22",
"revision_id": "2c1ed13977198da344a4292edead315ed60155bc",
"snapshot_id": "78065017ee5708bfbc67af85f1b51127398b6221",
"src_encoding": "UTF-8",
"star_events_count": 28,
"url": "https://raw.githubusercontent.com/NevynUK/The-Way-of-the-Register/2c1ed13977198da344a4292edead315ed60155bc/17 - EEPROM/main.c",
"visit_date": "2023-08-17T14:11:53.948640"
}
|
stackv2
|
//
// Write a series of bytes to the EEPROM of the STM8S105C6 and then
// verify that the data has been written correctly.
//
// This software is provided under the CC BY-SA 3.0 licence. A
// copy of this licence can be found at:
//
// http://creativecommons.org/licenses/by-sa/3.0/legalcode
//
#if defined DISCOVERY
#include <iostm8S105c6.h>
#else
#include <iostm8s103f3.h>
#endif
//
// Define where we will be working in the EEPROM.
//
#define EEPROM_BASE_ADDRESS 0x4000
#define EEPROM_INITIAL_OFFSET 0x0040
#define EEPROM_DATA_START (EEPROM_BASE_ADDRESS + EEPROM_INITIAL_OFFSET)
//
// Data to write into the EEPROM.
//
unsigned int _pulseLength[] = { 2000U, 27830U, 400U, 1580U, 400U, 3580U, 400U };
unsigned char _onOrOff[] = { 1, 0, 1, 0, 1, 0, 1 };
char numberOfValues = 7;
//--------------------------------------------------------------------------------
//
// Write the default values into EEPROM.
//
void SetDefaultValues()
{
//
// Check if the EEPROM is write-protected. If it is then unlock the EEPROM.
//
if (FLASH_IAPSR_DUL == 0)
{
FLASH_DUKR = 0xae;
FLASH_DUKR = 0x56;
}
//
// Write the data to the EEPROM.
//
char *address = (char *) EEPROM_DATA_START; // Data location in EEPROM.
*address++ = (char) numberOfValues;
for (int index = 0; index < numberOfValues; index++)
{
*address++ = (char) ((_pulseLength[index] >> 8) & 0xff);
*address++ = (char) (_pulseLength[index] & 0xff);
*address++ = _onOrOff[index];
}
//
// Now write protect the EEPROM.
//
FLASH_IAPSR_DUL = 0;
}
//--------------------------------------------------------------------------------
//
// Verify that the data in the EEPROM is the same as the data we
// wrote originally.
//
void VerifyEEPROMData()
{
PD_ODR_ODR2 = 1; // Checking the data
PD_ODR_ODR3 = 0; // No errors.
//
char *address = (char *) EEPROM_DATA_START; // Data location in EEPROM.
if (*address++ != numberOfValues)
{
PD_ODR_ODR3 = 1;
}
else
{
for (int index = 0; index < numberOfValues; index++)
{
unsigned int value = (*address++ << 8);
value += *address++;
if (value != _pulseLength[index])
{
PD_ODR_ODR3 = 1;
}
if (*address++ != _onOrOff[index])
{
PD_ODR_ODR3 = 1;
}
}
}
PD_ODR_ODR2 = 0; // Finished processing.
}
//--------------------------------------------------------------------------------
//
// Setup port D for data output.
//
void SetupPorts()
{
//
// Initialise Port D.
//
PD_ODR = 0; // All pins are turned off.
PD_DDR = 0xff; // All bits are output.
PD_CR1 = 0xff; // All pins are Push-Pull mode.
PD_CR2 = 0xff; // Pins can run up to 10 MHz.
}
//--------------------------------------------------------------------------------
//
// Main program loop.
//
void main()
{
SetupPorts();
SetDefaultValues();
VerifyEEPROMData();
}
| 2.828125 | 3 |
2024-11-18T19:35:06.729930+00:00
| 2023-01-26T12:45:32 |
4ca5a64f7054b65cc337e2c4e745fb0bd3a6ad90
|
{
"blob_id": "4ca5a64f7054b65cc337e2c4e745fb0bd3a6ad90",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-26T12:45:32",
"content_id": "224a992a5ce17aea45e043b174bf1a328321b38d",
"detected_licenses": [
"MIT"
],
"directory_id": "0ff5c3178e87a28a82165bfa908d9319cf7a2323",
"extension": "c",
"filename": "Linked List.c",
"fork_events_count": 963,
"gha_created_at": "2020-05-08T05:36:07",
"gha_event_created_at": "2023-03-25T14:22:10",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 262236251,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10701,
"license": "MIT",
"license_type": "permissive",
"path": "/10. Linked List/c lang/Linked List.c",
"provenance": "stackv2-0054.json.gz:8260",
"repo_name": "SR-Sunny-Raj/Hacktoberfest2021-DSA",
"revision_date": "2023-01-26T12:45:32",
"revision_id": "116526c093ed1ac7907483d001859df63c902cb3",
"snapshot_id": "40bf8385ed976fd81d27340514579b283c339c1f",
"src_encoding": "UTF-8",
"star_events_count": 261,
"url": "https://raw.githubusercontent.com/SR-Sunny-Raj/Hacktoberfest2021-DSA/116526c093ed1ac7907483d001859df63c902cb3/10. Linked List/c lang/Linked List.c",
"visit_date": "2023-01-31T07:46:26.016367"
}
|
stackv2
|
// 5. Practical : Linked List – 1
// Write a menu driven program to implement following operations on the singly linked list. Design a function create to create a link list (which is required to be called only for one time for a link list)
// (a) create [ node * create() ]
// (b) display [ void display(node *start) ]
// (c) length [ int length (node *start) ]
// (d) maximum [int maximum (node *start)]
// (e) merge (to merge two link list in to the third one) [node * merge(node *start1, node *start2)
// (f) sort [void sort(node *start) ]
// (g) reverse [ node * reverse (node *start)]
// (h) Insert a node at the front of the linked list. [ node * insert_front(node *start, int no) ]
// (i) Insert a node at the end of the linked list. [ node * insert_end(node *start, int no) ]
// (j) Insert a node such that linked list is in ascending order.(according to info. Field) [ node * insert_sort(node *start, int no) ]
// (k) Delete a first node of the linked list. [ node * delete_first(node *start) ]
// (l) Delete a node before specified position. [ node * delete_before(node *start, int pos) ]
// (m) Delete a node after specified position. [ node * delete_after(node *, int pos) ]
// (n) No search [ int search (node*, int x) ]
#include <stdio.h>
#include <stdlib.h>
struct node{
int info;
struct node *link;
};
struct node *create();
void display(struct node *start);
int length (struct node *start);
int maximum (struct node *start);
struct node * merge(struct node *start1, struct node *start2);
void sort(struct node *start);
struct node * reverse (struct node *start);
struct node * insert_front(struct node *start, int no);
struct node * insert_end(struct node *start, int no);
struct node * insert_sort(struct node *start, int no);
struct node * delete_first(struct node *start);
struct node * delete_before(struct node *start, int pos);
struct node * delete_after(struct node *start, int pos);
int search (struct node *start, int x);
int isNull(struct node *start);
int isEmpty();
void push(int *stack, int *top, int value);
int pop(int *stack, int *top);
int main(){
int operation, value, ans;
struct node *head = NULL, *head1;
printf("\n Ahmed Aghadi 200420107043\n");
do{
printf("\n****************************\n");
printf("\nEnter operation value\n");
printf("\n1. Create");
printf("\n2. Display");
printf("\n3. Length");
printf("\n4. Maximum");
printf("\n5. Merge");
printf("\n6. Sort");
printf("\n7. Reverse");
printf("\n8. Insert at front");
printf("\n9. insert at end");
printf("\n10. Insert by sort");
printf("\n11. Delete first");
printf("\n12. Delete before");
printf("\n13. Delete after");
printf("\n14. Search");
printf("\n15. Exit");
printf("\n****************************\n");
printf("Operation = ");
scanf("%d",&operation);
printf("\n");
if(operation>1&&operation<15){
if(isNull(head)){
continue;
}
}
switch(operation){
case 1:
head = create();
break;
case 2:
display(head);
break;
case 3:
ans = length(head);
printf("Length = %d", ans);
break;
case 4:
ans = maximum(head);
printf("Maximum = %d", ans);
break;
case 5:
printf("\nFor Second Linked List : \n");
head1 = create();
head = merge(head, head1);
display(head);
break;
case 6:
sort(head);
break;
case 7:
head = reverse(head);
display(head);
break;
case 8:
printf("Enter value to be inserted : ");
scanf("%d",&value);
head = insert_front(head, value);
break;
case 9:
printf("Enter value to be inserted : ");
scanf("%d",&value);
head = insert_end(head, value);
break;
case 10:
printf("Enter value to be inserted : ");
scanf("%d",&value);
head = insert_sort(head, value);
break;
case 11:
head = delete_first(head);
break;
case 12:
printf("Enter position : ");
scanf("%d",&value);
head = delete_before(head,value);
break;
case 13:
printf("Enter position : ");
scanf("%d",&value);
head = delete_after(head,value);
case 14:
printf("Enter value to be searched : ");
scanf("%d",&value);
ans = search(head, value);
if(ans==-1){
printf("Value not found");
break;
}
printf("Value is found at position %d",ans);
break;
case 15:
break;
default:
printf("\nEnter operation value between 1 and 15\n");
}
}while(operation!=15);
}
struct node *create(){
int value;
struct node *first;
first = (struct node *)malloc(sizeof(struct node));
if(first == NULL){
printf("Memory not allocated");
}
printf("Enter value of first node : ");
scanf("%d",&value);
first->info = value;
first->link = NULL;
return first;
}
void display(struct node *start){
while(start != NULL){
printf("\n%d",start->info);
start = start->link;
}
}
int length (struct node *start){
int len = 0;
while(start!=NULL){
len++;
start=start->link;
}
return len;
}
int maximum (struct node *start){
int max = start->info;
start = start->link;
while(start!=NULL){
if(start->info>max){
max = start->info;
}
start = start->link;
}
return max;
}
struct node * merge(struct node *start1, struct node *start2){
struct node *first;
first = (struct node *)malloc(sizeof(struct node));
if(length(start1)==0){
return start2;
}
if(length(start2)==0){
return start1;
}
first = start1;
while(start1->link!=NULL){
start1 = start1->link;
}
start1->link = start2;
return first;
}
void sort(struct node *start){
int i,j,temp,len;
struct node *current, *toCheck;
len = length(start);
current = start;
for(i = 0; i< len-1; i++){
toCheck = current->link;
for(j = i+1; j < len; j++){
if(toCheck->info<current->info){
temp = toCheck->info;
toCheck->info = current->info;
current->info = temp;
}
toCheck = toCheck->link;
}
current = current->link;
}
}
struct node * reverse (struct node *start){
int *stack = (int*)calloc(length(start),sizeof(int)), top = 1, i = 0, j = 0;
struct node *head = (struct node *)malloc(sizeof(struct node)), *temp;
if(length(start)==1){
head = start;
return head;
}
while(start!=NULL){
push(stack,&top,start->info);
start = start->link;
}
// head->info = pop(stack,&top);
temp = head;
while(1){
temp->info=pop(stack,&top);
if(top>1){
temp->link = (struct node *)malloc(sizeof(struct node));
temp = temp->link;
}
else{
temp->link = NULL;
break;
}
}
return head;
}
struct node * insert_front(struct node *start, int no){
struct node *first;
first = (struct node *)malloc(sizeof(struct node));
if(first == NULL){
printf("Memory not allocated");
}
first->info = no;
first->link=start;
return first;
}
struct node * insert_end(struct node *start, int no){
struct node *temp = start, *end;
end = (struct node *)malloc(sizeof(struct node));
end->info = no;
end->link = NULL;
while(temp->link!=NULL){
temp = temp->link;
}
temp->link = end;
return start;
}
struct node * insert_sort(struct node *start, int no){
struct node *toAdd, *temp = start;
toAdd = (struct node *)malloc(sizeof(struct node));
toAdd->info = no;
if(start->info>no){
toAdd->link = start;
return toAdd;
}
while(temp->link!=NULL){
if(temp->link->info>no){
toAdd->link = temp->link;
temp->link= toAdd;
return start;
}
temp = temp->link;
}
temp->link = toAdd;
toAdd->link = NULL;
return start;
}
struct node * delete_first(struct node *start){
struct node *head = start->link;
if(length(start)==1){
printf("\nLength of Linked List is 1 and thus first element can't be deleted.\n");
return start;
}
free(start);
return head;
}
struct node * delete_before(struct node *start, int pos){
struct node *temp = start, *toDelete = temp->link;
if(pos<2||pos>length(start)+1||length(start)==1){
printf("Invalid Position");
return start;
}
while(pos-->3){
temp = temp->link;
}
toDelete = temp->link;
temp->link = toDelete->link;
free(toDelete);
return start;
}
struct node * delete_after(struct node *start, int pos){
struct node *temp = start, *toDelete = temp->link;
if(pos<1||pos>length(start)-1||length(start)==1){
printf("Invalid Position");
return start;
}
while(pos-->1){
temp = temp->link;
}
toDelete = temp->link;
temp->link = toDelete->link;
free(toDelete);
return start;
}
int search (struct node *start, int x){
int i = 1;
while(start!=NULL){
if(start->info==x){
return i;
}
start = start->link;
i++;
}
return -1;
}
int isNull(struct node *start){
if(start == NULL){
printf("\nLinked List not created.\n");
return 1;
}
return 0;
}
int isEmpty(int top){
if(top==-1){
return 1;
}else{
return 0;
}
}
void push(int *stack, int *top, int value){
(*top)++;
stack[*top] = value;
}
int pop(int *stack, int *top){
if(isEmpty(*top)){
printf("Stack is Empty!");
exit(0);
}
(*top)--;
return stack[(*top)+1];
}
| 3.671875 | 4 |
2024-11-18T19:35:07.264364+00:00
| 2022-04-07T10:11:21 |
d5f5c0f10fc4d2e9e0426a554c200c3a495200d7
|
{
"blob_id": "d5f5c0f10fc4d2e9e0426a554c200c3a495200d7",
"branch_name": "refs/heads/zephyr",
"committer_date": "2022-04-07T10:33:32",
"content_id": "962fa3f03a98596bd468609cd3a7e082ad1fe028",
"detected_licenses": [
"MIT"
],
"directory_id": "a0bee85612fade5c6d775c8247c23cc301b69e07",
"extension": "c",
"filename": "cbor_buf_writer.c",
"fork_events_count": 11,
"gha_created_at": "2018-02-06T16:53:38",
"gha_event_created_at": "2022-04-07T10:33:33",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 120491777,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1773,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cbor_buf_writer.c",
"provenance": "stackv2-0054.json.gz:8644",
"repo_name": "zephyrproject-rtos/tinycbor",
"revision_date": "2022-04-07T10:11:21",
"revision_id": "9e1f34bc08123aaad7666d3652aaa839e8178b3b",
"snapshot_id": "ba268c058180c57e995f9eef18db29a0bfa4ed66",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/zephyrproject-rtos/tinycbor/9e1f34bc08123aaad7666d3652aaa839e8178b3b/src/cbor_buf_writer.c",
"visit_date": "2022-06-16T17:47:01.552059"
}
|
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.
*/
#include <tinycbor/cbor.h>
#include <tinycbor/cbor_buf_writer.h>
static inline int
would_overflow(struct cbor_buf_writer *cb, size_t len)
{
ptrdiff_t remaining = (ptrdiff_t)cb->end;
remaining -= (ptrdiff_t)cb->ptr;
remaining -= (ptrdiff_t)len;
return (remaining < 0);
}
int
cbor_buf_writer(struct cbor_encoder_writer *arg, const char *data, int len)
{
struct cbor_buf_writer *cb = (struct cbor_buf_writer *) arg;
if (would_overflow(cb, len)) {
return CborErrorOutOfMemory;
}
memcpy(cb->ptr, data, len);
cb->ptr += len;
cb->enc.bytes_written += len;
return CborNoError;
}
void
cbor_buf_writer_init(struct cbor_buf_writer *cb, uint8_t *buffer, size_t size)
{
cb->ptr = buffer;
cb->end = buffer + size;
cb->enc.bytes_written = 0;
cb->enc.write = cbor_buf_writer;
}
size_t
cbor_buf_writer_buffer_size(struct cbor_buf_writer *cb, const uint8_t *buffer)
{
return (size_t)(cb->ptr - buffer);
}
| 2.296875 | 2 |
2024-11-18T19:35:07.321348+00:00
| 2012-08-12T05:32:02 |
36df3d94bbdea0315c6bc6b47df40b2af78d7f02
|
{
"blob_id": "36df3d94bbdea0315c6bc6b47df40b2af78d7f02",
"branch_name": "refs/heads/master",
"committer_date": "2012-08-12T05:32:02",
"content_id": "04edb7e53dc53970e1e8ab0bd39eb7712de841a7",
"detected_licenses": [
"MIT"
],
"directory_id": "ab0a456142044eb81ad33851f121f78b7eeb4ff3",
"extension": "c",
"filename": "test_common.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4653648,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2239,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test_common.c",
"provenance": "stackv2-0054.json.gz:8772",
"repo_name": "jkew/intheory",
"revision_date": "2012-08-12T05:32:02",
"revision_id": "8fca5c5f7d71372a88773dbff64ae24a023f3bbd",
"snapshot_id": "dcc8fb66f2f3f04e7b1acd7ccbd83f38c1df7fa1",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/jkew/intheory/8fca5c5f7d71372a88773dbff64ae24a023f3bbd/test/test_common.c",
"visit_date": "2021-01-21T19:27:31.589033"
}
|
stackv2
|
#include "../src/include/intheory.h"
#include "../src/include/state_machine.h"
#include "../src/include/proposer.h"
#include "../src/include/acceptor.h"
#include "../src/include/learner.h"
#include "../src/include/network.h"
#include "../src/include/logger.h"
#include "include/test_common.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
long (*recv)[6];
long (*send)[6];
int sendidx = 0;
int recvidx = 0;
/*
* Run a role to completion
*/
void intheory_sm(enum role_t role) {
state s;
s = init_state(role, 0);
do {
switch(role) {
case PROPOSER:
s = sm_proposer(s);
break;
case ACCEPTOR:
s = sm_acceptor(s);
break;
case LEARNER:
s = sm_learner(s);
break;
case CLIENT:
break;
}
} while(s.state != S_DONE);
}
message * recv_from_scenario(int from_node, long slot, unsigned int mask) {
// handle a failure to receive within a 'time limit'
if (recv[recvidx][1] == -1) {
recvidx++;
return 0;
}
message *msg;
msg = malloc(sizeof(message));
if (recv[recvidx][0] == -1)
msg->from = from_node;
else
msg->from = recv[recvidx][0];
msg->type = recv[recvidx][1];
msg->ticket = recv[recvidx][2];
msg->slot = recv[recvidx][3];
msg->value = recv[recvidx][4];
msg->flags = recv[recvidx][5];
//log_message("<<<< RECIEVE ", msg);
log_graph(from_node, 0, msg->type, 1);
recvidx++;
return msg;
}
int send_to_scenario(int node, long ticket, unsigned int type, long slot, long value, unsigned short flags) {
trace("GOT Send - %d - node %d ticket %ld type %s slot %ld value %ld flags %ud",
sendidx, node, ticket, getMessageName(type), slot, value, flags);
trace("EXPECTED Send - %d - node %d ticket %ld type %s slot %ld value %ld flags %ud",
sendidx, send[sendidx][0], send[sendidx][2], getMessageName(send[sendidx][1]), send[sendidx][3], send[sendidx][4], send[sendidx][5]);
log_graph(0, node, type, 0);
if (send[sendidx][0] != -1)
assert(node == send[sendidx][0]);
assert(type == send[sendidx][1]);
assert(ticket == send[sendidx][2]);
assert(slot == send[sendidx][3]);
assert(value == send[sendidx][4]);
assert(flags == send[sendidx][5]);
sendidx++;
return 1;
}
| 2.59375 | 3 |
2024-11-18T19:35:07.506699+00:00
| 2023-08-24T05:39:38 |
f74f152193797db7e955882636003267ba7f4437
|
{
"blob_id": "f74f152193797db7e955882636003267ba7f4437",
"branch_name": "refs/heads/dev",
"committer_date": "2023-08-24T05:39:38",
"content_id": "d132e1c8eb0cb774a1831330dfe288d0d5856bed",
"detected_licenses": [
"MIT"
],
"directory_id": "683099532c562a6b6612a745022d65798fcf1fcc",
"extension": "c",
"filename": "config_nvidia.c",
"fork_events_count": 26,
"gha_created_at": "2019-11-06T21:17:28",
"gha_event_created_at": "2023-09-13T05:27:55",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 220091866,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1375,
"license": "MIT",
"license_type": "permissive",
"path": "/src/variorum/Nvidia_GPU/config_nvidia.c",
"provenance": "stackv2-0054.json.gz:8902",
"repo_name": "LLNL/variorum",
"revision_date": "2023-08-24T05:39:38",
"revision_id": "6d87426c63a5739f797b2494d09812b2c7036f83",
"snapshot_id": "973c39ecc47a2396b9d74a25693aba1674279d6b",
"src_encoding": "UTF-8",
"star_events_count": 50,
"url": "https://raw.githubusercontent.com/LLNL/variorum/6d87426c63a5739f797b2494d09812b2c7036f83/src/variorum/Nvidia_GPU/config_nvidia.c",
"visit_date": "2023-09-04T07:55:17.181532"
}
|
stackv2
|
// Copyright 2019-2023 Lawrence Livermore National Security, LLC and other
// Variorum Project Developers. See the top-level LICENSE file for details.
//
// SPDX-License-Identifier: MIT
#include <stdio.h>
#include <stdlib.h>
#include <config_nvidia.h>
#include <config_architecture.h>
#include <variorum_error.h>
uint64_t *detect_gpu_arch(void)
{
// Don't know what the architecture scheme is for Nvidia. This is the current hack for Volta.
uint64_t *model = (uint64_t *) malloc(sizeof(uint64_t));
*model = 1;
return model;
}
int set_nvidia_func_ptrs(int idx)
{
int err = 0;
if (*g_platform[idx].arch_id == VOLTA)
{
/* Initialize monitoring interfaces */
g_platform[idx].variorum_print_power = volta_get_power;
g_platform[idx].variorum_print_thermals = volta_get_thermals;
g_platform[idx].variorum_print_frequency = volta_get_clocks;
g_platform[idx].variorum_print_power_limit = volta_get_power_limits;
g_platform[idx].variorum_print_gpu_utilization = volta_get_gpu_utilization;
/* Initialize control interfaces */
g_platform[idx].variorum_cap_each_gpu_power_limit =
volta_cap_each_gpu_power_limit;
}
else
{
err = VARIORUM_ERROR_UNSUPPORTED_PLATFORM;
}
initNVML();
return err;
}
| 2 | 2 |
2024-11-18T19:35:07.666558+00:00
| 2019-03-26T01:17:15 |
64d4ab06f13cc53497cf1878240c09e19b83e306
|
{
"blob_id": "64d4ab06f13cc53497cf1878240c09e19b83e306",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-26T01:17:15",
"content_id": "3fdc949657c6b52c5181a479a2808e053bea5421",
"detected_licenses": [
"MIT"
],
"directory_id": "2c0d0f3622dc432867aaac40575033c9ebf7feb5",
"extension": "c",
"filename": "taskpools.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": 2419,
"license": "MIT",
"license_type": "permissive",
"path": "/src/taskpools.c",
"provenance": "stackv2-0054.json.gz:9159",
"repo_name": "stjordanis/partr",
"revision_date": "2019-03-26T01:17:15",
"revision_id": "1006a80756df65a53070555eb983c5cba5d7f2f5",
"snapshot_id": "32c0c5508584eec5c01c21755bfc014ec2d431c1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/stjordanis/partr/1006a80756df65a53070555eb983c5cba5d7f2f5/src/taskpools.c",
"visit_date": "2020-06-25T14:42:42.912748"
}
|
stackv2
|
/* partr -- parallel tasks runtime
taskpools for fast allocation/freeing
*/
#include <stdlib.h>
#include "partr.h"
#include "taskpools.h"
/* task pool for quick allocation/freeing of tasks */
typedef struct ptaskpool_tag {
int16_t num_tasks, next_avail;
ptask_t *tasks;
} ptaskpool_t;
/* a task pool for each thread */
static ptaskpool_t *ptaskpools;
/* taskpools_init()
*/
void taskpools_init()
{
ptaskpools = (ptaskpool_t *)calloc(nthreads, sizeof(ptaskpool_t));
for (int16_t i = 0; i < nthreads; ++i) {
ptaskpools[i].num_tasks = TASKS_PER_POOL;
ptaskpools[i].next_avail = 0;
ptaskpools[i].tasks = (ptask_t *)
calloc(TASKS_PER_POOL, sizeof(ptask_t));
for (int16_t j = 0; j < TASKS_PER_POOL; ++j) {
ptaskpools[i].tasks[j].ctx =
calloc(ctx_sizeof(), sizeof(uint8_t));
ptaskpools[i].tasks[j].stack =
calloc(TASK_STACK_SIZE, sizeof(uint8_t));
ptaskpools[i].tasks[j].pool = i;
ptaskpools[i].tasks[j].index = j;
ptaskpools[i].tasks[j].next_avail = j + 1;
}
ptaskpools[i].tasks[TASKS_PER_POOL-1].next_avail = -1;
}
LOG_INFO(plog, " %d tasks allocated per pool\n", TASKS_PER_POOL);
}
/* taskpools_destroy()
*/
void taskpools_destroy()
{
for (int16_t i = 0; i < nthreads; ++i) {
for (int16_t j = 0; j < TASKS_PER_POOL; ++j) {
free(ptaskpools[i].tasks[j].stack);
free(ptaskpools[i].tasks[j].ctx);
}
free(ptaskpools[i].tasks);
}
free(ptaskpools);
}
/* task_alloc()
*/
ptask_t *task_alloc()
{
int16_t candidate;
ptask_t *task;
ptaskpool_t *pool = &ptaskpools[tid];
do {
candidate = __atomic_load_n(&pool->next_avail, __ATOMIC_SEQ_CST);
if (candidate == -1) {
LOG_ERR(plog, " <%d> task allocation failed\n", tid);
return NULL;
}
task = &pool->tasks[candidate];
} while (!__atomic_compare_exchange_n(&pool->next_avail,
&candidate, task->next_avail,
0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED));
return task;
}
/* task_free()
*/
void task_free(ptask_t *task)
{
ptaskpool_t *pool = &ptaskpools[task->pool];
__atomic_exchange(&pool->next_avail, &task->index, &task->next_avail,
__ATOMIC_SEQ_CST);
}
| 2.859375 | 3 |
2024-11-18T19:35:07.961895+00:00
| 2017-06-14T13:56:23 |
923c27f4ac6615a6b5ac3c90a35a6e51f6945df8
|
{
"blob_id": "923c27f4ac6615a6b5ac3c90a35a6e51f6945df8",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-14T13:56:23",
"content_id": "d88d9fdb3f1f7c625a3fc1995313d7300ec54cd3",
"detected_licenses": [
"MIT"
],
"directory_id": "b2e17a845696931d265285455c5a7f3af60754cf",
"extension": "c",
"filename": "linked_list.c",
"fork_events_count": 1,
"gha_created_at": "2017-06-07T01:59:27",
"gha_event_created_at": "2017-06-14T13:56:24",
"gha_language": "C",
"gha_license_id": null,
"github_id": 93581441,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2217,
"license": "MIT",
"license_type": "permissive",
"path": "/linkedlists/linked_list.c",
"provenance": "stackv2-0054.json.gz:9545",
"repo_name": "ad-t/COMP1511-17s1-RevisionSession",
"revision_date": "2017-06-14T13:56:23",
"revision_id": "75bd7311c0bebdfa092957272e3b130f49112f70",
"snapshot_id": "d6f07d906efa530fc630505f9527d404d60b0e04",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ad-t/COMP1511-17s1-RevisionSession/75bd7311c0bebdfa092957272e3b130f49112f70/linkedlists/linked_list.c",
"visit_date": "2021-01-25T06:30:06.391827"
}
|
stackv2
|
#include "linked_list.h"
struct node * createNode(int data) {
struct node * newNode = malloc(sizeof(struct node));
if (newNode == NULL) {
printf("newNode is NULL!\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void append(struct node * list, int data) {
if (list == NULL) {
return;
}
struct node * curr = list;
while (curr->next != NULL) {
curr = curr->next;
}
struct node * newNode = createNode(data);
if (newNode == NULL) {
free(newNode);
return;
}
curr->next = newNode;
}
int listSize(struct node * list) {
if (list == NULL) {
return 0;
}
int size = 0;
struct node * curr = list;
while (curr != NULL) {
size++;
curr = curr->next;
}
return size;
}
struct node * listRemove(struct node * list, int data) {
if (list == NULL) {
return NULL;
} else if (list->next == NULL) {
if (list->data == data) {
free(list);
return NULL;
} else {
return list;
}
} else {
struct node * curr = list->next;
struct node * prev = list;
if (prev->data == data) {
free(prev);
return curr;
}
while (prev->next != NULL) {
if (curr->data == data) {
prev->next = curr->next;
free(curr);
return list;
}
prev = curr;
curr = curr->next;
}
}
return list;
}
int listMember(struct node * list, int data) {
if (list == NULL) {
return FALSE;
}
struct node * curr = list;
while (curr != NULL) {
if (curr->data == data) {
return TRUE;
}
curr = curr->next;
}
return FALSE;
}
void printList(struct node * list) {
if (list == NULL) {
printf("(empty list)\n");
return;
}
struct node * curr = list;
printf("[");
while (curr != NULL) {
printf("%d", curr->data);
if (curr->next != NULL) {
printf(", ");
}
curr = curr->next;
}
printf("]\n");
}
| 3.65625 | 4 |
2024-11-18T19:35:08.700101+00:00
| 2020-09-02T12:35:47 |
baf5220d075378c686240d939359081138a546cc
|
{
"blob_id": "baf5220d075378c686240d939359081138a546cc",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-02T12:35:47",
"content_id": "b2f25f9abda14d9ab80986607440868103ece570",
"detected_licenses": [
"MIT"
],
"directory_id": "e20a69eec4a537b9687cfa6904a1a7706511c76e",
"extension": "c",
"filename": "hello.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 292024130,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 257,
"license": "MIT",
"license_type": "permissive",
"path": "/src/hello.c",
"provenance": "stackv2-0054.json.gz:9802",
"repo_name": "sinseman44/yocto-test3",
"revision_date": "2020-09-02T12:35:47",
"revision_id": "ef790a3ef677e4e5625bb997f8eafbb31ef29969",
"snapshot_id": "8943b703fee6fd7dd822da03184045cfe0a13059",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sinseman44/yocto-test3/ef790a3ef677e4e5625bb997f8eafbb31ef29969/src/hello.c",
"visit_date": "2022-12-10T23:11:28.453930"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <world.h>
int main(int argc, char** argv) {
int ret = 0;
char str[64];
memset(str, 0, sizeof(str));
ret = world(sizeof(str), str);
printf("Hello World => %s\n", str);
return ret;
}
| 2.171875 | 2 |
2024-11-18T19:35:08.917339+00:00
| 2018-01-22T01:28:11 |
1a7f26d4e053477065811ce1552cdd3077c84df9
|
{
"blob_id": "1a7f26d4e053477065811ce1552cdd3077c84df9",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-22T01:28:11",
"content_id": "fff573a18f0193990a574bf4b9a1409e3b6add06",
"detected_licenses": [
"BSD-2-Clause-Views"
],
"directory_id": "8127bffa357a383994055d5dc1aeb7cfdc0b518f",
"extension": "c",
"filename": "sbush.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 118390224,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5057,
"license": "BSD-2-Clause-Views",
"license_type": "permissive",
"path": "/bin/sbush/sbush.c",
"provenance": "stackv2-0054.json.gz:9930",
"repo_name": "dhanashripp/SBUnix",
"revision_date": "2018-01-22T01:28:11",
"revision_id": "2183c5d3909184f155c80d0147112f353162884c",
"snapshot_id": "88260404aa27b003c07d15ca8d356a1cfd27448b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dhanashripp/SBUnix/2183c5d3909184f155c80d0147112f353162884c/bin/sbush/sbush.c",
"visit_date": "2021-05-10T10:40:28.533038"
}
|
stackv2
|
/* This is required to avoid implicit function declaration for execvpe */
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
/* Buffer size for max chars in input command */
#define MAX_IN_BUF_SIZE 200
/* Maximum parameters supported in a command including arguments */
#define MAX_PARAM_SUPP 50
char line[MAX_IN_BUF_SIZE];
char *s[MAX_PARAM_SUPP];
/* This character array stores prompt name. */
char p_name[70];
int ps_flag = 0;
char cur_dir[50];
extern char *usr_env_p[50];
int putc(int c, int fd);
void get_all_env();
int setenv(const char *name, const char *value);
size_t get_line(int fp, char *buf)
{
size_t pos = 0;
int x = EOF;
char c;
do {
x = read(fp, &c, 1);
//putc(c, 1);
buf[pos++] = c;
} while (x > 0 && c != '\n');
buf[pos - 1] = '\0';
return strlen(buf);
}
void parse_cmd(char *str, char *s[])
{
size_t i = 0;
s[i] = strtok(str, " ");
while (s[i]) {
#if 0
puts(s[i]);
#endif
s[++i] = strtok(NULL, " ");
}
#if 0
/* Replace all the dollar parameters with their values */
i = 0;
char par[40];
char *p_par = par;
while (s[i]) {
if (*(s[i]) == '$') {
p_par = strtok(s[i], "$");
s[i] = getenv(p_par);
/* Additional Check for PS1 */
if (!s[i]) {
if (!strncmp("PS1", p_par, strlen("PS1")))
s[i] = prompt_name;
}
}
i++;
}
#endif
}
void parse_env_var(char *str, char *s[])
{
size_t i = 0;
s[i] = strtok(str, "=");
while (s[i])
s[++i] = strtok(NULL, "=");
return;
}
void exec_cmd(const char *buf, char *argv[])
{
if (!strcmp("exit", buf)) {
/* TO DO : This might be problematic as the shell wont exit untill the child completes
* would even not allow to input any command to shell as it is stuck here.
*/
waitpid(0, NULL);
exit(EXIT_SUCCESS);
} else if (!strcmp("cd", buf)) {
if(!argv[1]) {
chdir("/rootfs/");
return;
}
chdir(argv[1]);
return;
} else if (!strcmp("env", buf)) {
get_all_env();
return;
} else if (!strcmp("help", buf)) {
int fd, x = 1, c = 0;
fd = open("/rootfs/etc/help", O_RDONLY);
if (fd < 0) {
return;
} else {
printf("\n");
while (x != 0) {
x = read(fd, &c, 1);
write(1, &c, 1);
}
close(fd);
}
return;
} else if (!strcmp("pwd", buf)) {
char pwd_buf[100];
if (!getcwd(pwd_buf, sizeof(pwd_buf)))
return;
else {
puts("\n");
puts(pwd_buf);
return;
}
} else if (!strcmp("export", buf)) {
/* Use of export to change PATH or PS1 var */
char *ls[MAX_PARAM_SUPP];
parse_env_var(argv[1], ls);
if (!strcmp("PS1", ls[0])) {
if(ls[1]) {
strcpy(p_name, ls[1]);
ps_flag = 1;
}
return;
/* Any other env variable user is trying to set/update */
} else {
/* If the env variable does not exist. The overwrite is zero here. */
if(ls[1])
setenv(ls[0], ls[1]);
return;
}
} else if (!strcmp("shutdown", buf)) {
shutdown();
} else
;
/* bg flag is used to check if a background process is requested. */
size_t i = 0, bg = 0;
/* -=2 signifies that the loop is at NULL + 1 after it exits. */
while (argv[i++]); i -= 2;
/* Assumed that & is always at the end of the complete command. */
if (!strcmp(argv[i], "&")) {
/* Remove & from the parameter char* array. */
argv[i] = NULL;
bg = 1;
}
size_t c_pid = fork();
if (c_pid == 0) {
execvpe(buf, argv, usr_env_p);
/* This will make sure that, even if exec returns with error, the process is freed */
exit(EXIT_SUCCESS);
}
if (bg) {
} else {
waitpid(c_pid, 0);
}
}
int main(int argc, char* argv[], char *envp[])
{
setenv("PATH", "/rootfs/bin");
int bufsize = 0;
/* This is for executing a shell script. */
if (argc >= 2) {
/* This is used to check if the input file starts with #!sbush
* Only then we will execute the file.
*/
size_t tmp = 0;
int f = open(argv[1], O_RDONLY);
int bufsize = 1;
if (f > 2) {
while (bufsize > 0) {
bufsize = get_line(f, line);
if (!tmp) {
tmp = 1;
if (strcmp(line, "#!sbush")) {
/* TO DO : Do not use printf. use exec cmd for echo. */
puts("\nThe File you provided does not begin with #!sbush");
return 0;
}
continue;
}
parse_cmd(line, s);
if (bufsize > 0)
exec_cmd(s[0], s);
/* terminate the string for safety */
line[0] = '\0';
}
} else {
puts("\nInvalid file");
}
close(f);
exit(EXIT_SUCCESS);
return 0;
}
while (1) {
if (!ps_flag) {
zero_out(p_name, 50);
char *p_str = p_name;
int p_name_size = strlen("user:~");
strcpy(p_str, "user:~");
p_str += p_name_size;
getcwd(cur_dir, 50);
strcpy(p_str, cur_dir);
p_str++;
p_name_size = strlen(p_name);
p_name[p_name_size] = '$';
p_name_size++;
p_name[p_name_size] = '\0';
}
puts("\n");
puts(p_name);
bufsize = read(0, line, 1);
parse_cmd(line, s);
if (bufsize > 1)
exec_cmd(s[0], s);
/* terminate the string for safety */
line[0] = '\0';
}
return 0;
}
| 2.734375 | 3 |
2024-11-18T19:35:09.320513+00:00
| 2021-02-15T18:43:56 |
7a3c3c5f4bdb807191a40972bf2e7f0354fed1dc
|
{
"blob_id": "7a3c3c5f4bdb807191a40972bf2e7f0354fed1dc",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-15T18:43:56",
"content_id": "bd0e2b69e284fb449ad408785b7b0b8725fe202a",
"detected_licenses": [
"MIT"
],
"directory_id": "7f829c0575ccad8433b0cb7493530fbe83b2f4ea",
"extension": "c",
"filename": "ct.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": 2328,
"license": "MIT",
"license_type": "permissive",
"path": "/ct.c",
"provenance": "stackv2-0054.json.gz:10058",
"repo_name": "trypolis464/ct",
"revision_date": "2021-02-15T18:43:56",
"revision_id": "9861987b6456497d781b9d5f7ae6797498c2200e",
"snapshot_id": "911bbc4f5d51b339f03c73eb30e269b1c6527cef",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trypolis464/ct/9861987b6456497d781b9d5f7ae6797498c2200e/ct.c",
"visit_date": "2023-03-02T14:17:12.712118"
}
|
stackv2
|
/*
* NOTE
* My changes to this code are under the MIT License. As I do not know who made this script initially, and there was no license with it, I am going to assume that the initial code wasn't licensed at all.
* Contributions will all be considered to be a part of the MIT License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef _MSC_VER
#include <sys/utime.h>
#else
#include <utime.h>
#endif
#define PE_SIGNATURE "00004550"
int readFourBytesHex(char *str, FILE *src);
int main(int argc, char *argv[])
{
FILE *fp;
int c;
int i;
int idx;
char temp[9];
unsigned long n;
time_t tm;
struct utimbuf new_times;
char *cTimeString;
if (argc != 2)
{
fprintf(stderr, "usage: %s <DLL/EXE>", argv[0]);
return 1;
}
fp = fopen(argv[1], "r");
if (fp == NULL)
{
fprintf(stderr, "error: failed to open the file.");
return 1;
}
for (i = 1; i <= 60; i++)
{
c = getc(fp);
if (c == EOF)
{
fprintf(stderr, "error: the file is not a windows object file.");
return -1;
}
}
temp[8] = '\0';
readFourBytesHex(temp, fp);
i += 4;
n = strtoul(temp, NULL, 16);
for (; i < n; i++)
{
c = getc(fp);
if (c == EOF)
{
fprintf(stderr, "error: the file is not a windows object file.");
return -1;
}
}
if (readFourBytesHex(temp, fp) != 0)
{
fprintf(stderr, "error: the file is not a windows object file.");
return -1;
}
i += 4;
if (strcmp(temp, PE_SIGNATURE) != 0)
{
fprintf(stderr, "File is not a PE or its header is corrupted.");
return -1;
}
i = 0;
for (; i < 4; i++)
{
c = getc(fp);
if (c == EOF)
{
fprintf(stderr, "error: the file is not a windows object file.");
return -1;
}
}
if (readFourBytesHex(temp, fp) != 0)
{
fprintf(stderr, "error: the file is not a windows object file.");
return -1;
}
n = strtoul(temp, NULL, 16);
tm = n;
cTimeString = ctime(&tm);
printf("Compile Date Time Stamp: %s", cTimeString);
new_times.modtime = n;
utime(argv[1], &new_times);
fclose(fp);
return 0;
}
// Reads four bytes in Hex in Little Endian format.
int readFourBytesHex(char *str, FILE *src)
{
char byteStr[2];
int i;
int c;
str += 6;
for (i = 0; i < 4; i++)
{
c = getc(src);
if (c == EOF)
{
return -1;
}
sprintf(byteStr, "%002x ", c);
strncpy(str, byteStr, 2);
str -= 2;
}
return 0;
}
| 2.859375 | 3 |
2024-11-18T19:35:09.526573+00:00
| 2023-05-05T02:26:49 |
f78635d4d3f0b69eaa9249a9293fb0ad7e992a83
|
{
"blob_id": "f78635d4d3f0b69eaa9249a9293fb0ad7e992a83",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-05T02:26:49",
"content_id": "4bc03aec3c86effe1dbb64de783609e40ac7038c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5efe877bf5ebc9da1e7edb8efabb66b88a78cee4",
"extension": "h",
"filename": "Strings.h",
"fork_events_count": 64,
"gha_created_at": "2018-05-14T21:53:46",
"gha_event_created_at": "2023-03-20T23:15:23",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 133425750,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3728,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/DcpmPkg/common/Strings.h",
"provenance": "stackv2-0054.json.gz:10314",
"repo_name": "intel/ipmctl",
"revision_date": "2023-05-05T02:26:49",
"revision_id": "c75bd840ea7820c8f93a5488fcff75d08beedd51",
"snapshot_id": "342996a882ea7f4d3abf06fd175ec5d5673829b3",
"src_encoding": "UTF-8",
"star_events_count": 176,
"url": "https://raw.githubusercontent.com/intel/ipmctl/c75bd840ea7820c8f93a5488fcff75d08beedd51/DcpmPkg/common/Strings.h",
"visit_date": "2023-08-11T03:49:16.000607"
}
|
stackv2
|
/*
* Copyright (c) 2018, Intel Corporation.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _STRINGS_H_
#define _STRINGS_H_
#include <Debug.h>
#include "Common.h"
/**
string_concat command
@param[in] str1 - string 1
@param[in] str2 - string 2
@param[in] free_when_done - if it should release the memory of the strings when done
@retval the concatenated string
**/
CHAR8* string_concat(
IN CHAR8* str1,
IN CHAR8* str2,
IN BOOLEAN free_when_done
);
/**
string concatenate command - THIS FREES THE PASSED STRINGS WHEN FINISHED
@param[in] str_array - string array
@param[in] string_count - the length of the string array
@param[in] free_when_done - if it should release the memory of the strings when done
@param[out] final_length - if it should release the memory of the strings when done
@retval the concatenated string
**/
CHAR8* string_array_concat(
IN CHAR8** str_array,
IN UINT64 string_count,
IN BOOLEAN free_when_done,
OUT UINT64* final_length
);
/*
string copy command
@param[in] source - the source string
@retval a copy of the string
*/
CHAR8* string_copy(
IN CHAR8* source
);
/*
get_empty_string command
@param[in] length - how long of a string that you want
@retval a string [length] long + terminator, initialized with 0 in each index
*/
CHAR8* get_empty_string(
IN UINT64 length
);
/*
string_length command
@param[in] str - the string to measure
@retval the length of the passed string
*/
UINT64 string_length(
IN CHAR8* str
);
/*
string_split command
@param[in] str - the string to split
@param[in] splitchar - the char to split on
@param[in] maxelements - 0 for unlimited, or > 0 to prevent too many resulting strings
@param[out] elements - the number of found elements
@retval an array of strings [elements] long
*/
CHAR8** string_split(
IN CHAR8* str,
IN CHAR8 splitchar,
IN UINT64 maxelements,
OUT UINT64* elements
);
/*
bytes_to_u32 command
@param[in] bytes - the bytes to convert (must be 4 or more)
@retval the UINT32 value of the passed string
*/
UINT32 bytes_to_u32(
IN UINT8* bytes
);
/*
a_to_u32 command
@param[in] str - the string to convert
@retval the UINT32 value of the passed string
*/
UINT32 a_to_u32(
IN CHAR8* str
);
/*
u32_to_a command
@param[in] val - the value to convert
@param[in] format_hex - if the output should be hex
@param[in] max_len - the max length of string to return
@param[in] uppercase - if upper case values should be used when hex
@retval the string representation of the passed value
*/
CHAR8* u32_to_a(
IN UINT32 val,
IN BOOLEAN format_hex,
IN UINT64 max_len,
IN BOOLEAN uppercase
);
/*
nlog_format command
@param[in] format - the string to base a format on (processes %X, %x and %d only)
@param[in] values - the values to add to the format str
@param[in] values_length - the length of the values array
@retval returns the formatted string
*/
CHAR8*
nlog_format(
IN CHAR8 *format,
IN UINT32** values,
IN UINT64 values_length
);
/*
Pads a string AND FREES THE PASSED ONE
@param[in] str - the string to pad
@param[in] pad_len - the length the final string should be
@param[in] pad_char - the char to use for padding
@param[in] free_when_done - if it should release the memory of the strings when done
@retval returns the padded string
*/
CHAR8*
pad_left(
IN CHAR8 *str,
IN UINT64 pad_len,
IN CHAR8 pad_char,
IN BOOLEAN free_when_done
);
/*
Copys one memory range's value to another
@param[in] dest - the string to pad
@param[in] len - the char to use for padding
@param[in] source - if it should release the memory of the strings when done
@retval returns a reference to the dest
*/
CHAR8*
MyMemCopy(
IN CHAR8* dest,
IN UINT64 len,
IN CHAR8* source
);
#endif
| 2.703125 | 3 |
2024-11-18T19:35:09.826972+00:00
| 2018-04-05T17:46:34 |
cb5b09a4be32f0e7b16fb3fe1d0f99176e1bd2c6
|
{
"blob_id": "cb5b09a4be32f0e7b16fb3fe1d0f99176e1bd2c6",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-05T17:46:34",
"content_id": "dacb3cc4a1838c7c2df0c382930d103fc067873f",
"detected_licenses": [
"MIT"
],
"directory_id": "c271f720664d1a1df10e012deef391d37d255167",
"extension": "c",
"filename": "graphics_win32.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": 7162,
"license": "MIT",
"license_type": "permissive",
"path": "/ral-viz/source/arch/win32/graphics_win32.c",
"provenance": "stackv2-0054.json.gz:10699",
"repo_name": "trinhvo/Raytracing",
"revision_date": "2018-04-05T17:46:34",
"revision_id": "9cb8b99e519cca592ddcc594320a4f21b44b5932",
"snapshot_id": "9f106a6198b40b3615c723db5901ecb07ccd40d2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trinhvo/Raytracing/9cb8b99e519cca592ddcc594320a4f21b44b5932/ral-viz/source/arch/win32/graphics_win32.c",
"visit_date": "2020-12-07T10:17:37.214437"
}
|
stackv2
|
/*------------------------------------------------------------------------------
* File: graphics_win32.c
* Created: September 12, 2015
* Last changed: September 12, 2015
*
* Author(s): Philip Arvidsson (contact@philiparvidsson.com)
*
* Description:
* Windows implementation of the graphics library.
*----------------------------------------------------------------------------*/
#ifdef _WIN32
/*------------------------------------------------
* INCLUDES
*----------------------------------------------*/
#include "graphics.h"
#include "arch/win32/utils_win32.h"
#include "arch/win32/win32_private.h"
#include "base/common.h"
#include "base/debug.h"
#include "graphics/pixmap.h"
#include <windows.h>
/*------------------------------------------------
* CONSTANTS
*----------------------------------------------*/
/*--------------------------------------
* Constant: ClassName
*
* Description:
* Name of the class used to create the window.
*------------------------------------*/
#define ClassName ("ral-viz__")
/*--------------------------------------
* Constant: WindowStyle
*
* Description:
* Window styles.
*------------------------------------*/
#define WindowStyle (~WS_MAXIMIZEBOX & WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME)
/*--------------------------------------
* Constant: WindowStyleEx
*
* Description:
* Extended window styles.
*------------------------------------*/
#define WindowStyleEx (WS_EX_LEFT)
/*------------------------------------------------
* GLOBALS
*----------------------------------------------*/
/*--------------------------------------
* Variable: window
*
* Description:
* Pointer to the window, if any.
*------------------------------------*/
static windowT* window = NULL;
/*------------------------------------------------
* FUNCTIONS
*----------------------------------------------*/
/*--------------------------------------
* Function: WindowProc()
*
* Description:
* http://en.wikipedia.org/wiki/WindowProc
*------------------------------------*/
static LRESULT CALLBACK WindowProc(_In_ HWND hwnd,
_In_ UINT uMsg,
_In_ WPARAM wParam,
_In_ LPARAM lParam)
{
switch (uMsg) {
case WM_CLOSE: {
window->hwnd = NULL;
break;
}
};
return (DefWindowProc(hwnd, uMsg, wParam, lParam));
}
/*--------------------------------------
* Function: registerWindowClass()
*------------------------------------*/
static void registerWindowClass(void) {
WNDCLASSEXW wcx = { 0 };
wchar_t* class_name = wstrdup(ClassName);
wcx.cbSize = sizeof(WNDCLASSEXW);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = WindowProc;
wcx.cbClsExtra = 0;
wcx.cbWndExtra = 0;
wcx.hInstance = GetModuleHandleW(NULL);
wcx.hIcon = LoadIconW(NULL, IDI_APPLICATION);
wcx.hCursor = LoadCursorW(NULL, IDC_ARROW);
wcx.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcx.lpszMenuName = NULL;
wcx.lpszClassName = class_name;
wcx.hIconSm = NULL;
if (!RegisterClassExW(&wcx)) {
free(class_name);
error("could not register window class");
}
free(class_name);
}
/*--------------------------------------
* Function: registerWindowClass()
*------------------------------------*/
static void unregisterWindowClass(void) {
wchar_t* class_name = wstrdup(ClassName);
if (!UnregisterClassW(class_name, GetModuleHandleW(NULL)))
warn("could not unregister window class");
free(class_name);
}
/*--------------------------------------
* Function: createWindow(title, width, height)
*------------------------------------*/
static void createWindow(const string* title, int width, int height) {
RECT window_rect = { 0 };
window_rect.right = width;
window_rect.bottom = height;
AdjustWindowRectEx(&window_rect, WindowStyle, FALSE, WindowStyleEx);
int window_width = window_rect.right - window_rect.left;
int window_height = window_rect.bottom - window_rect.top;
registerWindowClass();
window = malloc(sizeof(windowT));
wchar_t* class_name = wstrdup(ClassName);
wchar_t* window_name = wstrdup(title);
window->hwnd = CreateWindowExW(WindowStyleEx,
class_name,
window_name,
WindowStyle,
CW_USEDEFAULT,
CW_USEDEFAULT,
window_width,
window_height,
HWND_DESKTOP,
NULL,
GetModuleHandleW(NULL),
NULL);
free(class_name);
free(window_name);
assert(window->hwnd != NULL);
RECT desktop_rect;
GetClientRect(GetDesktopWindow(), &desktop_rect);
MoveWindow(window->hwnd,
(desktop_rect.right - desktop_rect.left - window_width ) / 2,
(desktop_rect.bottom - desktop_rect.top - window_height) / 2,
window_width,
window_height,
FALSE);
ShowWindow(window->hwnd, SW_SHOW);
window->hdc = GetDC(window->hwnd);
//assert(window->hdc != NULL);
window->width = width;
window->height = height;
}
/*--------------------------------------
* Function: getWindowPtr()
*------------------------------------*/
windowT* getWindowPtr(void) {
if (!window)
error("graphics not initialized");
return (window);
}
/*--------------------------------------
* Function: initGraphics(title, width, height)
*------------------------------------*/
bool initGraphics(const string* title, int width, int height) {
if (window)
error("graphics already initialized");
createWindow(title, width, height);
return (false);
}
/*--------------------------------------
* Function: exitGraphics()
*------------------------------------*/
void exitGraphics(void) {
if (!window)
return;
// @To-do: destroyWindow();
unregisterWindowClass();
free(window);
window = NULL;
}
/*--------------------------------------
* Function: updateDisplay()
*------------------------------------*/
void updateDisplay(void) {
if (!window)
error("graphics not initialized");
MSG msg;
while (window && PeekMessageW(&msg, window->hwnd, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
// @To-do: This is retarded.
Sleep(500);
}
/*--------------------------------------
* Function: windowIsOpen()
*------------------------------------*/
bool windowIsOpen(void) {
return (window && window->hwnd);
}
#endif // _WIN32
| 2.109375 | 2 |
2024-11-18T19:35:10.311042+00:00
| 2021-08-26T11:18:55 |
44ea9b4f15eca2ffc6bb218a6c8457fc6e85b6f3
|
{
"blob_id": "44ea9b4f15eca2ffc6bb218a6c8457fc6e85b6f3",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-26T11:18:55",
"content_id": "8a23c575e904841f8270f252fa82b12119033ee9",
"detected_licenses": [
"MIT"
],
"directory_id": "ae8047ad8a872854fd2299351b97aef959a5031b",
"extension": "c",
"filename": "uname.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": 741,
"license": "MIT",
"license_type": "permissive",
"path": "/kernel/uname.c",
"provenance": "stackv2-0054.json.gz:10827",
"repo_name": "reymontero/SynnixOS",
"revision_date": "2021-08-26T11:18:55",
"revision_id": "c26993479d78eae3881bdbad147b5bb4b5704844",
"snapshot_id": "241ac3d92cfa678b5a807da382b526208cd76622",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/reymontero/SynnixOS/c26993479d78eae3881bdbad147b5bb4b5704844/kernel/uname.c",
"visit_date": "2023-07-14T01:10:18.895693"
}
|
stackv2
|
#include <basic.h>
#include <errno.h>
#include <snx/string.h>
#include <snx/syscall.h>
#include <sys/utsname.h>
#include <snx/fs.h>
/** @file
* @brief Uname helpers
*
*/
#if X86_64
#define UNAME_ARCH "x86_64"
#endif
#ifndef SYNNIXOS_VERSION
#define SYNNIXOS_VERSION "Null"
#endif
char* getHostname() {
// TODO: Kernel space get hostname
return "synnixos";
}
sysret sys_uname(struct utsname *n) {
if (!n) return -EINVAL;
memset(n, 0, sizeof(struct utsname));
strcpy((char *)&n->sysname, "SynnixOS");
strcpy((char *)&n->nodename, getHostname());
strcpy((char *)&n->release, SYNNIXOS_VERSION);
strcpy((char *)&n->version, SYNNIXOS_VERSION);
strcpy((char *)&n->machine, UNAME_ARCH);
return 0;
}
| 2.03125 | 2 |
2024-11-18T19:35:10.372445+00:00
| 2014-05-18T23:09:40 |
4775cc86562cd0c14df8ed60644ce578bdfe1be4
|
{
"blob_id": "4775cc86562cd0c14df8ed60644ce578bdfe1be4",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-18T23:09:40",
"content_id": "aa27827f38074f0271b0a73153f88cbc9dba73ed",
"detected_licenses": [
"MIT"
],
"directory_id": "44f5e95f7f34ec63d35215de61e21d14dff212a2",
"extension": "c",
"filename": "collfs.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": 28702,
"license": "MIT",
"license_type": "permissive",
"path": "/collfs.c",
"provenance": "stackv2-0054.json.gz:10955",
"repo_name": "michaeldcruz/collfs",
"revision_date": "2014-05-18T23:09:40",
"revision_id": "e00c5d744c2646f8cab90dcace99639ce1fce12a",
"snapshot_id": "c5c28c936873936fb6df9f2aab2c63cb94e96bde",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/michaeldcruz/collfs/e00c5d744c2646f8cab90dcace99639ce1fce12a/collfs.c",
"visit_date": "2021-01-23T17:43:25.837740"
}
|
stackv2
|
#include "collfs.h"
#include "libc-collfs.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdint.h>
static int collfs_initialized;
/***********************************************************************
* Debugging and error reporting
***********************************************************************/
static int collfs_debug_level;
static void (*collfs_error_handler)(void);
#define ECOLLFS EREMOTEIO /* To set errno when MPI fails */
static void set_errno(int e) { errno = e; }
#ifdef COLLFS_PROFILE
struct FunctionProfile {
int calls;
double time;
};
struct CollfsProfile {
struct FunctionProfile collfs_fxstat64;
struct FunctionProfile collfs_xstat64;
struct FunctionProfile collfs_open;
struct FunctionProfile collfs_close;
struct FunctionProfile collfs_read;
struct FunctionProfile collfs_lseek;
struct FunctionProfile collfs_mmap;
struct FunctionProfile collfs_munmap;
};
static struct CollfsProfile collfs_profile;
#define CollfsFunctionStart \
double tstart,tend; \
tstart = MPI_Wtime();
/* Note that the below macros are not safe
where a single line is expected.
*/
#define CollfsFxstat64Return(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_fxstat64.time += tend-tstart; \
collfs_profile.collfs_fxstat64.calls++; \
return rval;
#define CollfsXstat64Return(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_xstat64.time += tend-tstart; \
collfs_profile.collfs_xstat64.calls++; \
return rval;
#define CollfsOpenReturn(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_open.time += tend-tstart; \
collfs_profile.collfs_open.calls++; \
return rval;
#define CollfsCloseReturn(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_close.time += tend-tstart; \
collfs_profile.collfs_close.calls++; \
return rval;
#define CollfsReadReturn(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_read.time += tend-tstart; \
collfs_profile.collfs_read.calls++; \
return rval;
#define CollfsLseekReturn(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_lseek.time += tend-tstart; \
collfs_profile.collfs_lseek.calls++; \
return rval;
#define CollfsMmapReturn(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_mmap.time += tend-tstart; \
collfs_profile.collfs_mmap.calls++; \
return rval;
#define CollfsMunmapReturn(rval) \
tend = MPI_Wtime(); \
collfs_profile.collfs_munmap.time += tend-tstart; \
collfs_profile.collfs_munmap.calls++; \
return rval;
#else
#define CollfsFunctionStart
#define CollfsFxstat64Return(rval) return rval;
#define CollfsXstat64Return(rval) return rval;
#define CollfsOpenReturn(rval) return rval;
#define CollfsCloseReturn(rval) return rval;
#define CollfsReadReturn(rval) return rval;
#define CollfsLseekReturn(rval) return rval;
#define CollfsMmapReturn(rval) return rval;
#define CollfsMunmapReturn(rval) return rval;
#endif
/* This macro should be used to log errors encountered within this file. */
#define set_error(e, ...) set_error_private(__FILE__, __LINE__, __func__, (e), __VA_ARGS__)
__attribute__((format(printf, 5, 6)))
static void set_error_private(const char *file, int line, const char *func, int e, const char *fmt, ...)
{
if (collfs_debug_level >= 1) {
char buf[2048];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof buf, fmt, ap);
fprintf(stderr,
"ERROR: %s\n, errno=%d \"%s\"\n"
"ERROR: at %s:%d in %s()\n", buf, e, strerror(e), file, line, func);
va_end(ap);
}
set_errno(e);
if (collfs_error_handler) collfs_error_handler();
}
#define CHECK_INIT(failcode) do { \
int mpiinitialized; \
if (!collfs_initialized) { \
set_error(ECOLLFS, "collfs is not initialized"); \
return (failcode); \
} \
MPI_Initialized(&mpiinitialized); \
if (!mpiinitialized) { \
set_error(ECOLLFS, "MPI has not been initialized"); \
} \
} while (0)
/* Do not call directly, use debug_printf() instead */
static int collfs_debug_vprintf(int level, const char *fmt, va_list ap)
{
char buf[2048], padding[10];
int i,rank;
if (level > collfs_debug_level) return 0;
vsnprintf(buf, sizeof buf, fmt, ap);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
for (i=0; i<level; i++) padding[i] = ' ';
padding[i++] = '*';
padding[i] = 0;
return fprintf(stderr, "[%d] %s %s\n", rank, padding, buf);
}
__attribute__((format(printf, 2, 3)))
static int debug_printf(int level, const char *fmt, ...)
{
va_list ap;
int ret = 0;
va_start(ap, fmt);
ret = collfs_debug_vprintf(level, fmt, ap);
va_end(ap);
return ret;
}
static size_t extend_to_page(size_t len) {
size_t totallen;
long pagesize = sysconf(_SC_PAGESIZE);
totallen = (len + (pagesize-1)) & ~(pagesize-1); /* Includes the whole page */
debug_printf(2, "%s() len: %zu, pagesize: %ld, totallen: %zu", __func__, len, pagesize, totallen);
return totallen;
}
/***********************************************************************
* Data structures and static variables
***********************************************************************/
/* Struct containing the collfs API used by libc_collfs, provided to libc_collfs_initialize() */
static struct libc_collfs_api unwrap;
/* One node in the list for each open file */
struct FileLink {
MPI_Comm comm;
int fd;
int refct;
char fname[MAXPATHLEN];
void *mem;
size_t totallen; /* bytes mapped/malloced */
size_t len; /* bytes in file */
size_t offset;
struct FileLink *next;
};
static struct FileLink *DLOpenFiles;
static const int BaseFD = 10000;
static int NextFD = 10001;
/* One node in the list for each mmaped region. */
struct MMapLink {
void *addr;
size_t len;
size_t offset;
int fd;
struct FileLink *link;
struct MMapLink *next;
};
static struct MMapLink *MMapRegions;
struct CommLink {
MPI_Comm comm;
struct CommLink *next;
};
static struct CommLink *CommStack;
/***********************************************************************
* Implementation of the collective file API
*
* These symbols need not be exported except for testing purposes because
* they should only be called by redirect through libc-collfs.
***********************************************************************/
/* Logically collective on the communicator used when the fd was created */
static int collfs_fxstat64(int vers, int fd, struct stat64 *buf)
{
int err;
struct FileLink *link;
CHECK_INIT(-1);
CollfsFunctionStart;
if (CommStack) {
debug_printf(2, "%s(%d) collective", __func__, fd);
for (link=DLOpenFiles; link; link=link->next) {
if (link->fd == fd) {
int rank,xerr = 0;
err = MPI_Comm_rank(link->comm, &rank);
if (err) {
CollfsFxstat64Return(-1);
}
if (!rank) xerr = ((collfs_fxstat64_fp) unwrap.fxstat64)(vers, fd, buf);
err = MPI_Bcast(&xerr, 1, MPI_INT, 0, link->comm);
if (err < 0) {
set_error(ECOLLFS, "MPI_Bcast failed to broadcast success of root fxstat64");
CollfsFxstat64Return(-1);
}
err = MPI_Bcast(buf, sizeof *buf, MPI_BYTE, 0, link->comm);
if (err < 0) {
set_error(ECOLLFS, "MPI_Bcast failed to broadcast struct");
CollfsFxstat64Return(-1);
} else {
CollfsFxstat64Return(0);
}
}
}
}
CollfsFxstat64Return(((collfs_fxstat64_fp) unwrap.fxstat64)(vers, fd, buf));
}
/* Collective on the communicator at the top of the collfs stack */
static int collfs_xstat64(int vers, const char *file, struct stat64 *buf)
{
CHECK_INIT(-1);
CollfsFunctionStart;
if (CommStack) {
debug_printf(2, "%s(\"%s\") collective", __func__, file);
int err,rank,xerr;
err = MPI_Comm_rank(CommStack->comm, &rank);
if (err) {
CollfsXstat64Return(-1);
}
if (!rank) xerr = ((collfs_xstat64_fp) unwrap.xstat64)(vers, file, buf);
err = MPI_Bcast(&xerr, 1, MPI_INT, 0, CommStack->comm);
if (err < 0) {
set_error(ECOLLFS, "MPI_Bcast failed to broadcast success of root xstat64");
CollfsXstat64Return(-1);
}
err = MPI_Bcast(buf, sizeof *buf, MPI_BYTE, 0, CommStack->comm);
if (err < 0) {
set_error(ECOLLFS, "MPI_Bcast failed to broadcast struct");
CollfsXstat64Return(-1);
}
else {
CollfsXstat64Return(0);
}
}
CollfsXstat64Return(((collfs_xstat64_fp) unwrap.xstat64)(vers, file, buf));
}
static int collfs_open(const char *pathname, int flags, mode_t mode)
{
int err, rank;
CHECK_INIT(-1);
CollfsFunctionStart;
// pass through to libc __open if no communicator has been pushed
if (!CommStack) {
debug_printf(2, "%s(\"%s\", x%x, o%o) independent", __func__, pathname, flags, mode);
CollfsOpenReturn(((collfs_open_fp) unwrap.open)(pathname, flags, mode));
}
err = MPI_Comm_rank(CommStack->comm, &rank);
if (err) {
set_error(ECOLLFS, "Error determining rank. Bad communicator?");
CollfsOpenReturn(-1);
}
#ifndef O_CLOEXEC
#define O_CLOEXEC O_RDONLY
#endif
if (flags == O_RDONLY || flags == (O_RDONLY | O_CLOEXEC)) { /* Read is collectively on comm */
int len, fd, gotmem;
long pagesize;
struct {int len, errno_save;} buf;
size_t totallen;
void *mem;
struct FileLink *link;
debug_printf(2, "%s(\"%s\", x%x, o%o) collective", __func__, pathname, flags, mode);
if (!rank) {
len = -1;
fd = ((collfs_open_fp) unwrap.open)(pathname, flags, mode);
if (fd >= 0) {
struct stat fdst;
if (fstat(fd, &fdst) < 0) ((collfs_close_fp) unwrap.close)(fd); /* fail cleanly */
else len = (int)fdst.st_size; /* Cast prevents using large files, but MPI would need workarounds too */
}
}
buf.len = len;
buf.errno_save = errno;
err = MPI_Bcast(&buf, 2, MPI_INT, 0, CommStack->comm);
if (err) {
CollfsOpenReturn(-1);
}
len = buf.len;
if (len < 0) {
set_error(buf.errno_save, "Error opening file");
CollfsOpenReturn(-1);
}
totallen = extend_to_page(len);
mem = NULL;
if (!rank) {
mem = ((collfs_mmap_fp) unwrap.mmap)(0, totallen, PROT_READ, MAP_PRIVATE, fd, 0);
((collfs_lseek_fp) unwrap.lseek)(fd, 0, SEEK_SET);
} else {
/* Don't use shm_open() here because the shared memory segment is fixed at boot time. */
fd = NextFD++;
pagesize = sysconf(_SC_PAGESIZE);
mem = ((collfs_mmap_fp) unwrap.mmap)(0, totallen, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, fd, 0);
((collfs_lseek_fp) unwrap.lseek)(fd, 0, SEEK_SET);
}
if (fd >= 0)
/* Make sure everyone found memory */
gotmem = !!mem;
err = MPI_Allreduce(MPI_IN_PLACE, &gotmem, 1, MPI_INT, MPI_LAND, CommStack->comm);
if (!gotmem) {
if (!rank) {
if (mem) ((collfs_munmap_fp) unwrap.munmap)(mem, totallen);
} else {
if (mem) ((collfs_munmap_fp) unwrap.munmap)(mem, totallen);
}
set_error(ECOLLFS, "Could not find memory: mmap() on rank 0, malloc otherwise");
CollfsOpenReturn(-1);
}
err = MPI_Bcast(mem, len, MPI_BYTE, 0, CommStack->comm);
if (err) {
CollfsOpenReturn(-1);
}
if (rank) fd = NextFD++; /* There is no way to make a proper file descriptor, this requires patching read() */
link = malloc(sizeof *link);
link->comm = CommStack->comm;
link->fd = fd;
link->refct = 1;
strcpy(link->fname, pathname);
link->mem = mem;
link->len = len;
link->totallen = totallen;
link->offset = 0;
/* Add new node to the list */
link->next = DLOpenFiles;
DLOpenFiles = link;
CollfsOpenReturn(fd);
}
/* more than read access needed, fall back to independent access */
debug_printf(2, "%s(\"%s\", x%x, o%o)", __func__, pathname, flags, mode);
CollfsOpenReturn(((collfs_open_fp) unwrap.open)(pathname, flags, mode));
}
/* Collective on the communicator used when the fd was created */
static int collfs_close(int fd)
{
struct FileLink **linkp;
int err;
CHECK_INIT(-1);
CollfsFunctionStart;
if (CommStack) {
for (linkp=&DLOpenFiles; linkp && *linkp; linkp=&(*linkp)->next) {
struct FileLink *link = *linkp;
debug_printf(2, "%s(%d) on file link %p with fd %d", __func__, fd, linkp, link->fd);
if (link->fd == fd) { /* remove it from the list */
int rank = 0, xerr = 0;
debug_printf(2, "%s(%d) collective", __func__, fd);
if (--link->refct > 0) {
debug_printf(2, "%s(%d) nonzero refcount %d", __func__, fd, link->refct);
CollfsCloseReturn(0);
}
err = MPI_Comm_rank(CommStack ? CommStack->comm : MPI_COMM_WORLD, &rank);
if (err) {
CollfsCloseReturn(-1);
}
if (!rank) {
((collfs_munmap_fp) unwrap.munmap)(link->mem, link->totallen);
xerr = ((collfs_close_fp) unwrap.close)(fd);
} else {
((collfs_munmap_fp) unwrap.munmap)(link->mem, link->totallen);
}
*linkp = link->next;
free(link);
debug_printf(2, "%s(%d) entering Bcast", __func__, fd);
err = MPI_Bcast(&xerr, 1, MPI_INT, 0, CommStack->comm);
debug_printf(2, "%s(%d) exiting Bcast", __func__, fd);
CollfsCloseReturn(err);
}
}
}
debug_printf(2, "%s(%d) independent", __func__, fd);
CollfsCloseReturn(((collfs_close_fp) unwrap.close)(fd));
}
/* Collective on the communicator used when the fd was created */
static ssize_t collfs_read(int fd, void *buf, size_t count)
{
struct FileLink *link;
CollfsFunctionStart;
CHECK_INIT(-1);
for (link=DLOpenFiles; link; link=link->next) { /* Could optimize to not always walk the list */
int rank = 0, err;
err = MPI_Comm_rank(link->comm, &rank);
if (err) {
CollfsReadReturn(-1);
}
if (fd == link->fd) {
debug_printf(2, "%s(%d, %p, %zu) collective", __func__, fd, buf, count);
if (!rank) {
CollfsReadReturn(((collfs_read_fp) unwrap.read)(fd, buf, count));
}
else {
if ((link->len - link->offset) < count) count = link->len - link->offset;
memcpy(buf, link->mem+link->offset, count);
link->offset += count;
CollfsReadReturn(count);
}
}
}
debug_printf(2, "%s(%d, %p, %zu) independent", __func__, fd, buf, count);
CollfsReadReturn(((collfs_read_fp) unwrap.read)(fd, buf, count));
}
static off_t collfs_lseek(int fildes, off_t offset, int whence)
{
struct FileLink *link;
CHECK_INIT(-1);
CollfsFunctionStart;
for (link=DLOpenFiles; link; link=link->next) {
if (link->fd == fildes) {
int rank = 0;
MPI_Comm_rank(link->comm,&rank);
debug_printf(2, "%s(%d, %lld, %d) collective", __func__, fildes, (long long)offset, whence);
if (!rank) {
/* Rank 0 has a normal fd */
CollfsLseekReturn(((collfs_lseek_fp) unwrap.lseek)(fildes, offset, whence));
}
switch (whence) {
case SEEK_SET:
link->offset = offset;
break;
case SEEK_CUR:
link->offset += offset;
break;
case SEEK_END:
link->offset = link->len + offset;
break;
}
CollfsLseekReturn(link->offset);
}
}
debug_printf(2, "%s(%d, %lld, %d) independent", __func__, fildes, (long long)offset, whence);
CollfsLseekReturn(((collfs_lseek_fp) unwrap.lseek)(fildes, offset, whence));
}
/* Collective on the communicator used when fildes was created
Note that we allow len > mlink-> len.
*/
static void *collfs_mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
{
struct FileLink *link;
int gotmem, rank;
size_t copylen;
void *mem;
CHECK_INIT(MAP_FAILED);
CollfsFunctionStart;
if (CommStack) {
if (off < 0) {
debug_printf(2, "%s() ERROR: off < 0", __func__);
set_error(ENXIO, "off < 0");
CollfsMmapReturn(MAP_FAILED);
}
for (link=DLOpenFiles; link; link=link->next) {
if (link->fd == fildes) {
struct MMapLink *mlink;
debug_printf(2, "%s(%p, %zu, %d, %d, %d, %lld) collective", __func__, addr, len, prot, flags, fildes, (long long)off);
if (prot & PROT_WRITE && !(flags & MAP_FIXED)) {
set_error(EACCES, "prot & PROT_WRITE && !(flags & MAP_FIXED)");
CollfsMmapReturn(MAP_FAILED);
}
if (flags & MAP_FIXED) {
if (off + len > link->totallen || off < 0) {
debug_printf(2, "%p requested of length %zd, but off + len = %zd and link->totallen = %zd",
addr, len, off+len, link->totallen);
set_error(EACCES, "addr < (void*) (char*) link->mem+link->totallen");
CollfsMmapReturn(MAP_FAILED);
}
MPI_Comm_rank(CommStack->comm, &rank);
if (!rank) {
mem = ((collfs_mmap_fp) unwrap.mmap)(addr, len, prot, flags, link->fd, off);
} else {
mem = ((collfs_mmap_fp) unwrap.mmap)(addr, len, PROT_READ | PROT_WRITE, flags | MAP_ANONYMOUS, link->fd, off);
}
gotmem = (mem != MAP_FAILED);
debug_printf(2, "%s() memory: %p, requested addr: %p", __func__, mem, addr);
MPI_Allreduce(MPI_IN_PLACE, &gotmem, 1, MPI_INT, MPI_LAND, CommStack->comm);
debug_printf(2, "%s() Exiting Allreduce", __func__);
if (!gotmem) {
debug_printf(2, "%s() ERROR: Could not find memory to reallocate", __func__);
set_error(ECOLLFS, "Could not find memory to reallocate");
CollfsMmapReturn(MAP_FAILED);
}
if (rank) {
debug_printf(2, "Moving %zd bytes from %p to %p [%p]",len,(void*)(char*)link->mem+off,addr,mem);
memmove(addr,(void*)(char*)link->mem+off,len);
mprotect(mem, len, prot);
}
mlink = malloc(sizeof *mlink);
mlink->addr = mem;
mlink->len = len;
mlink->offset = off;
mlink->fd = fildes;
mlink->next = MMapRegions;
MMapRegions = mlink;
debug_printf(2, "%s() Returning mlink->addr at %p (fixed)", __func__, mlink->addr);
CollfsMmapReturn(mlink->addr);
}
if (flags & MAP_SHARED ) {
debug_printf(2, "%s() ERROR: Cannot do MAP_SHARED for a collective fd", __func__);
set_error(ENOTSUP, "flags & MAP_SHARED: cannot do MAP_SHARED for a collective fd");
CollfsMmapReturn(MAP_FAILED);
}
size_t totallen;
totallen = extend_to_page(len);
debug_printf(2, "mmaping new size %zd (file size %zd) on offset %lld", totallen, link->totallen, (long long) off);
MPI_Comm_rank(CommStack->comm, &rank);
if (!rank) {
((collfs_munmap_fp) unwrap.munmap)(link->mem,link->totallen);
mem = ((collfs_mmap_fp) unwrap.mmap)(addr, totallen, prot, flags, link->fd, off);
} else {
mem = ((collfs_mmap_fp) unwrap.mmap)(0, totallen, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, link->fd, 0);
}
gotmem = (mem != MAP_FAILED);
debug_printf(2, "%s() memory: %p, requested addr: %p", __func__, mem, addr);
MPI_Allreduce(MPI_IN_PLACE, &gotmem, 1, MPI_INT, MPI_LAND, CommStack->comm);
if (!gotmem) {
debug_printf(2, "%s() ERROR: Could not find memory to reallocate", __func__);
set_error(ECOLLFS, "Could not find memory to reallocate");
CollfsMmapReturn(MAP_FAILED);
}
if (rank) {
// must copy no more than link->totallen (file size) or totallen (mmap size) bytes
if (link->totallen > totallen) {
copylen = totallen;
}
else {
copylen = link->totallen;
}
debug_printf(2, "Copying %zd bytes - from %p to %p", copylen, (void*)(char*)link->mem+off, mem);
memmove(mem, (void*)(char*)link->mem+off, copylen);
debug_printf(2, "Protecting %p", mem);
mprotect(mem, len, prot);
/* ((collfs_munmap_fp) unwrap.munmap)(link->mem,link->totallen); */
debug_printf(2, "Allocated %zd bytes range [%p %p]", totallen, mem, (void*)(char*)mem+totallen);
debug_printf(2, "Copied %zd bytes - range [%p %p]", copylen, mem, (void*)(char*)mem+link->len);
}
mlink = malloc(sizeof *mlink);
mlink->addr = mem;
mlink->len = len;
mlink->offset = off;
mlink->fd = fildes;
mlink->next = MMapRegions;
mlink->link = link;
MMapRegions = mlink;
link->refct++;
debug_printf(2, "%s() Returning mlink->addr at %p (extended)", __func__, mlink->addr);
CollfsMmapReturn(mlink->addr);
}
}
}
debug_printf(2, "%s(%p, %zu, %d, %d, %d, %lld) independent", __func__, addr, len, prot, flags, fildes, (long long)off);
CollfsMmapReturn(((collfs_mmap_fp) unwrap.mmap)(addr, len, prot, flags, fildes, off));
}
/* This implementation is not actually collective, but it relies on the fd being opened collectively */
static int collfs_munmap(__ptr_t addr, size_t len)
{
CHECK_INIT(-1);
CollfsFunctionStart;
if (CommStack) {
debug_printf(2, "%s(%p, %zu) collective", __func__, addr, len);
struct MMapLink *mlink;
for (mlink=MMapRegions; mlink; mlink=mlink->next) {
if (mlink->addr == addr) {
if (mlink->len != len) {
set_error(EINVAL, "Attempt to unmap region of length %zu when %zu was mapped", len, mlink->len);
CollfsMunmapReturn(-1);
}
mlink->link->refct--;
free(mlink);
CollfsMunmapReturn(((collfs_munmap_fp) unwrap.munmap)(addr, len));
}
}
set_error(EINVAL, "Address not mapped: %p", addr);
}
debug_printf(2, "%s(%p, %zu) independent", __func__, addr, len);
CollfsMunmapReturn(((collfs_munmap_fp) unwrap.munmap)(addr, len));
}
/***********************************************************************
* User-callable interface to collfs
***********************************************************************/
/* Symbol is exposed by patched ld.so */
extern struct libc_collfs_api _dl_collfs_api __attribute((weak));
int collfs_initialize(int level, void (*errhandler)(void))
{
collfs_debug_level = level;
collfs_error_handler = errhandler;
if (collfs_initialized) {
set_error(EALREADY, "collfs already initialized");
return -1;
}
typedef void (*void_fp)(void);
unwrap.fxstat64 = (void_fp) __fxstat64;
unwrap.xstat64 = (void_fp) __xstat64;
unwrap.open = (void_fp) open;
unwrap.close = (void_fp) close;
unwrap.read = (void_fp) read;
unwrap.lseek = (void_fp) lseek;
unwrap.mmap = (void_fp) mmap;
unwrap.munmap = (void_fp) munmap;
/* Make API visible to libc-rtld (ld.so) */
_dl_collfs_api.fxstat64 = (void_fp) collfs_fxstat64;
_dl_collfs_api.xstat64 = (void_fp) collfs_xstat64;
_dl_collfs_api.open = (void_fp) collfs_open;
_dl_collfs_api.close = (void_fp) collfs_close;
_dl_collfs_api.read = (void_fp) collfs_read;
_dl_collfs_api.lseek = (void_fp) collfs_lseek;
_dl_collfs_api.mmap = (void_fp) collfs_mmap;
_dl_collfs_api.munmap = (void_fp) collfs_munmap;
collfs_initialized = 1;
debug_printf(2, "collfs initialized");
#ifdef COLLFS_PROFILE
collfs_profile.collfs_fxstat64.calls = 0;
collfs_profile.collfs_fxstat64.time = 0;
collfs_profile.collfs_xstat64.calls = 0;
collfs_profile.collfs_xstat64.time = 0;
collfs_profile.collfs_open.calls = 0;
collfs_profile.collfs_open.time = 0;
collfs_profile.collfs_close.calls = 0;
collfs_profile.collfs_close.time = 0;
collfs_profile.collfs_read.calls = 0;
collfs_profile.collfs_read.time = 0;
collfs_profile.collfs_lseek.calls = 0;
collfs_profile.collfs_lseek.time = 0;
collfs_profile.collfs_mmap.calls = 0;
collfs_profile.collfs_mmap.time = 0;
collfs_profile.collfs_munmap.calls = 0;
collfs_profile.collfs_munmap.time = 0;
#endif
return 0;
}
int collfs_finalize()
{
CHECK_INIT(-1);
memset(&unwrap, 0, sizeof unwrap);
memset(&_dl_collfs_api, 0, sizeof(_dl_collfs_api));
collfs_initialized = 0;
collfs_error_handler = 0;
#ifdef COLLFS_PROFILE
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"fxstat64",
collfs_profile.collfs_fxstat64.calls,
collfs_profile.collfs_fxstat64.time,
collfs_profile.collfs_fxstat64.time/collfs_profile.collfs_fxstat64.calls);
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"xstat64",
collfs_profile.collfs_xstat64.calls,
collfs_profile.collfs_xstat64.time,
collfs_profile.collfs_xstat64.time/collfs_profile.collfs_xstat64.calls);
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"open",
collfs_profile.collfs_open.calls,
collfs_profile.collfs_open.time,
collfs_profile.collfs_open.time/collfs_profile.collfs_open.calls);
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"close",
collfs_profile.collfs_close.calls,
collfs_profile.collfs_close.time,
collfs_profile.collfs_close.time/collfs_profile.collfs_close.calls);
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"read",
collfs_profile.collfs_read.calls,
collfs_profile.collfs_read.time,
collfs_profile.collfs_read.time/collfs_profile.collfs_read.calls);
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"lseek",
collfs_profile.collfs_lseek.calls,
collfs_profile.collfs_lseek.time,
collfs_profile.collfs_lseek.time/collfs_profile.collfs_lseek.calls);
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"mmap",
collfs_profile.collfs_mmap.calls,
collfs_profile.collfs_mmap.time,
collfs_profile.collfs_mmap.time/collfs_profile.collfs_mmap.calls);
debug_printf(0, "%8.8s calls: %5.5d total: %5.5e avg: %5.5e",
"munmap",
collfs_profile.collfs_munmap.calls,
collfs_profile.collfs_munmap.time,
collfs_profile.collfs_munmap.time/collfs_profile.collfs_fxstat64.calls);
#endif
return 0;
}
int collfs_set_debug_level(int level)
{
CHECK_INIT(-1);
collfs_debug_level = level;
return 0;
}
int collfs_set_error_handler(void (*fp)(void))
{
CHECK_INIT(-1);
collfs_error_handler = fp;
return 0;
}
/* Logically collective, changes the communicator on which future IO is collective */
int collfs_comm_push(MPI_Comm comm)
{
struct CommLink *link;
CHECK_INIT(-1);
link = malloc(sizeof *link);
if (!link) {
debug_printf(2, "%s failed -- unable to malloc link", __func__);
return -1;
}
link->comm = comm;
link->next = CommStack;
CommStack = link;
#if DEBUG
MPI_Barrier(link->comm);
#endif
debug_printf(2, "%s comm %p", __func__, (void *) comm);
return 0;
}
/* Logically collective, changes the communicator on which future IO is collective */
int collfs_comm_pop(void)
{
struct CommLink *link = CommStack;
CHECK_INIT(-1);
if (!link) return -1;
CommStack = link->next;
#if DEBUG
MPI_Barrier(link->comm);
#endif
free(link);
return 0;
}
| 2.359375 | 2 |
2024-11-18T19:35:10.962456+00:00
| 2019-07-14T07:22:44 |
7efaafa608224c01a77e8c059a322d0b815a8a60
|
{
"blob_id": "7efaafa608224c01a77e8c059a322d0b815a8a60",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-14T07:22:44",
"content_id": "71bf67f155c0d23d369d599c24166ac85204a2f4",
"detected_licenses": [
"MIT"
],
"directory_id": "319884441ea89619ca8f1ca91063a70e141846e5",
"extension": "h",
"filename": "Util.h",
"fork_events_count": 24,
"gha_created_at": "2016-01-26T11:27:57",
"gha_event_created_at": "2019-07-14T07:22:45",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 50424410,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6939,
"license": "MIT",
"license_type": "permissive",
"path": "/TechniqueDemos/D3D12MemoryManagement/src/Util.h",
"provenance": "stackv2-0054.json.gz:11595",
"repo_name": "GPUOpen-LibrariesAndSDKs/nBodyD3D12",
"revision_date": "2019-07-14T07:22:44",
"revision_id": "08ea79b0c2f0dbd9e7f21b85f078ce856c87ad06",
"snapshot_id": "930a86508ea6fc024b9dfc12e18f2fb9c5ba8fbc",
"src_encoding": "UTF-8",
"star_events_count": 60,
"url": "https://raw.githubusercontent.com/GPUOpen-LibrariesAndSDKs/nBodyD3D12/08ea79b0c2f0dbd9e7f21b85f078ce856c87ad06/TechniqueDemos/D3D12MemoryManagement/src/Util.h",
"visit_date": "2023-08-12T07:50:47.774564"
}
|
stackv2
|
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#pragma once
//
// Converts the provided source WIC pixel format into the closest matching
// target format which we can use with tiled resources.
//
bool GetTargetPixelFormat(const GUID* pSourceFormat, GUID* pTargetFormat);
//
// Converts the WIC pixel format to the corresponding DXGI format. Returns
// DXGI_FORMAT_UNKNOWN if the pixel format is not supported.
//
DXGI_FORMAT GetDXGIFormatFromPixelFormat(const GUID* pPixelFormat);
//
// Gets the index to the least detailed mipmap for the specified resource.
//
inline UINT8 GetLeastDetailedMipIndex(_In_ const Resource* pResource)
{
return pResource->NumStandardMips + pResource->NumPackedMips - 1;
}
//
// Gets the index to the heap corresponding to the least detailed mipmap
// in the resource. All packed mipmaps share a single heap index, so this value
// is not equal to the least detailed mipmap index.
//
inline UINT8 GetLeastDetailedMipHeapIndex(_In_ const Resource* pResource)
{
if (pResource->NumPackedMips != 0)
{
return pResource->PackedMipHeapIndex;
}
return pResource->NumStandardMips - 1;
}
//
// Returns true if 'MipToCheck' is less detailed that 'CurrentMip'
//
inline bool IsLessDetailedMip(UINT8 CurrentMip, UINT8 MipToCheck)
{
return MipToCheck > CurrentMip;
}
//
// Returns true if 'MipToCheck' is more detailed that 'CurrentMip'
//
inline bool IsMoreDetailedMip(UINT8 CurrentMip, UINT8 MipToCheck)
{
return MipToCheck < CurrentMip;
}
//
// Calculates the mipmap level that would be used when sampling a resource, given
// the orthographic camera zoom level.
//
inline float CalculateRequiredMipLevel(_In_ const Resource* pResource, float ImageScale)
{
D3D12_RESOURCE_DESC Desc = pResource->pDeviceState->pD3DResource->GetDesc();
//
// Calculate rough derivative, knowing that the image is a screen-space quad.
// This should be equal to the ratio of texels per pixel (ImageScale is equal
// to the screen space pixel size of the texture with projection zoom applied).
//
float d = Desc.Width / ImageScale;
float dSqr = d * d;
//
// Mip = log2(DerivativeSquared) / 2
//
float Log = log(dSqr) / log(2.0f);
float Mip = 0.5f * Log;
return max(Mip, 0.0f);
}
//
// Gets the total number of mipmaps in this resource.
//
inline UINT8 GetResourceMipCount(_In_ const Resource* pResource)
{
return pResource->NumStandardMips + pResource->NumPackedMips;
}
//
// Gets the accent color for the generated image.
//
UINT GetGeneratedImageColor(UINT ImageIndex);
//
// Returns true if the two rectangles intersect.
//
inline bool RectIntersects(const RectF& a, const RectF& b)
{
return a.Left < b.Right && a.Right > b.Left &&
a.Top < b.Bottom && a.Bottom > b.Top;
}
//
// Returns true if the two rectangles are with the specified Tolerence distance from one another.
//
inline bool RectNearlyIntersects(const RectF& a, const RectF& b, float Tolerence)
{
return a.Left - Tolerence < b.Right && a.Right + Tolerence > b.Left &&
a.Top - Tolerence < b.Bottom && a.Bottom + Tolerence> b.Top;
}
//
// Inflates a rectangle by the specified size on all sides.
//
inline void InflateRectangle(RectF& Rectangle, float Size)
{
Rectangle.Bottom += Size;
Rectangle.Left -= Size;
Rectangle.Right += Size;
Rectangle.Top -= Size;
}
//
// Returns the more detailed of two mipmap levels.
//
inline UINT8 ChooseMoreDetailedMip(UINT8 MipA, UINT8 MipB)
{
return min(MipA, MipB);
}
//
// Returns the less detailed of two mipmap levels.
//
inline UINT8 ChooseLessDetailedMip(UINT8 MipA, UINT8 MipB)
{
return max(MipA, MipB);
}
//
// Returns the mip level after increasing the quality by 'IncreaseBy' levels of quality,
// and clamping the quality to 0.
//
inline UINT8 IncreaseMipQuality(UINT8 Mip, UINT8 IncreaseBy)
{
if (IncreaseBy > Mip)
{
return 0;
}
return Mip - IncreaseBy;
}
//
// Returns the mip level after decreasing the quality by 'DecreaseBy' levels of quality.
//
inline UINT8 DecreaseMipQuality(UINT8 Mip, UINT8 DecreaseBy)
{
return Mip + DecreaseBy;
}
//
// Translates a lowercase character to the equivalent virtual key
//
inline UINT GetVirtualKeyFromCharacter(char c)
{
return 0x41 + (c - 'a');
}
//
// Calculates the number of heaps required to page in the provided resource mipmap, based
// on the maximimum heap size.
//
inline UINT GetResourceMipHeapCount(const ResourceMip& rMip)
{
return ((rMip.Desc.WidthInTiles * rMip.Desc.HeightInTiles * TILE_SIZE) + MAX_HEAP_SIZE - 1) / MAX_HEAP_SIZE;
}
//
// Gets the heap index for a resource, given the mip level. All packed mipmaps
// share a single heap index.
//
inline UINT8 GetMipHeapIndexForResource(_In_ const Resource* pResource, UINT8 Mip)
{
UINT8 Index = Mip;
if (Index > pResource->PackedMipHeapIndex)
{
Index = pResource->PackedMipHeapIndex;
}
return Index;
}
//
// Calculates the size of a non-packed mipmap, in bytes.
//
inline UINT64 GetNonPackedMipSize(_In_ const Resource* pResource, UINT MipHeapIndex)
{
ResourceMip* pMip = &pResource->pDeviceState->Mips[MipHeapIndex];
return (UINT64)pMip->Desc.WidthInTiles * (UINT64)pMip->Desc.HeightInTiles * TILE_SIZE;
}
//
// Gets a friendly string for the provided D3D feature level.
//
inline LPCSTR GetFeatureLevelName(D3D_FEATURE_LEVEL FeatureLevel)
{
switch (FeatureLevel)
{
case D3D_FEATURE_LEVEL_9_1: return "9.1";
case D3D_FEATURE_LEVEL_9_2: return "9.2";
case D3D_FEATURE_LEVEL_9_3: return "9.3";
case D3D_FEATURE_LEVEL_10_0: return "10.0";
case D3D_FEATURE_LEVEL_10_1: return "10.1";
case D3D_FEATURE_LEVEL_11_0: return "11.0";
case D3D_FEATURE_LEVEL_11_1: return "11.1";
case D3D_FEATURE_LEVEL_12_0: return "12.0";
case D3D_FEATURE_LEVEL_12_1: return "12.1";
default: return "12.1+";
}
}
//
// Calculates the required size of a constant buffer, based on the D3D12 alignment
// restriction of constant buffers (256 bytes).
//
inline UINT32 CalculateConstantBufferSize(UINT32 Size)
{
//
// Constant buffers are required to be 256 byte aligned, and multiples of 256 bytes.
//
return (Size + (D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1)) & ~(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1);
}
//
// Get the absolute path to the running exe.
//
inline void GetWorkingDir(_Out_writes_z_(pathSize) WCHAR* path, UINT pathSize)
{
if (path == nullptr)
{
return;
}
DWORD size = GetModuleFileName(nullptr, path, pathSize);
if (size == 0 || size == pathSize)
{
// Method failed or path was truncated.
*path = L'\0';
return;
}
WCHAR* lastSlash = wcsrchr(path, L'\\');
if (lastSlash)
{
*(lastSlash+1) = L'\0';
}
}
| 2.28125 | 2 |
2024-11-18T19:35:11.570571+00:00
| 2023-07-13T03:58:47 |
4d99eb09c8443eb9e3a38eb4d567df62627d5af9
|
{
"blob_id": "4d99eb09c8443eb9e3a38eb4d567df62627d5af9",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-13T03:58:47",
"content_id": "8e8baf16807ae0e7c9f217f7ed4a125dbc6daa71",
"detected_licenses": [
"MIT"
],
"directory_id": "b09ef1d3b63118812df27e0e96d65db3b8171c75",
"extension": "c",
"filename": "BMSorting.c",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 177095238,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 490,
"license": "MIT",
"license_type": "permissive",
"path": "/AudioFilters/MathUtilities/BMSorting.c",
"provenance": "stackv2-0054.json.gz:11851",
"repo_name": "sirhans/AudioFiltersSubmodule",
"revision_date": "2023-07-13T03:58:47",
"revision_id": "eb4e73aa8a3ea05a72982352bc844f721a8036bd",
"snapshot_id": "2d8f58f4df5ab35faf2d27d33e7e58636e06cc35",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/sirhans/AudioFiltersSubmodule/eb4e73aa8a3ea05a72982352bc844f721a8036bd/AudioFilters/MathUtilities/BMSorting.c",
"visit_date": "2023-07-26T03:26:47.463949"
}
|
stackv2
|
//
// BMSorting.c
// SaturatorAU
//
// Created by hans anderson on 12/18/19.
// Copyright © 2019 bluemangoo. All rights reserved.
//
#include "BMSorting.h"
#include <stdbool.h>
/*!
*BMInsertionSort_size_t
*
* @abstract insertion sort on an array of size_t of length n
*/
void BMInsertionSort_size_t(size_t *a, size_t n) {
for(size_t i = 1; i < n; ++i) {
size_t tmp = a[i];
size_t j = i;
while(j > 0 && tmp < a[j - 1]) {
a[j] = a[j - 1];
--j;
}
a[j] = tmp;
}
}
| 2.453125 | 2 |
2024-11-18T19:35:11.637456+00:00
| 2021-05-31T17:30:16 |
5bede0ad2939e5b847d67d36547b5a5e0d11f786
|
{
"blob_id": "5bede0ad2939e5b847d67d36547b5a5e0d11f786",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-31T17:30:16",
"content_id": "d3747ff1d2545552dcf35fbf2ff2daba3da3a55c",
"detected_licenses": [
"MIT"
],
"directory_id": "f664fd968847bc05fa4cadf4d87ee195b616e2b9",
"extension": "c",
"filename": "vuln_2.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 345124830,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 285,
"license": "MIT",
"license_type": "permissive",
"path": "/3. Fortify/vuln_2.c",
"provenance": "stackv2-0054.json.gz:11979",
"repo_name": "MBWlodarczyk/bso_project",
"revision_date": "2021-05-31T17:30:16",
"revision_id": "a4620fb18d7f789d917627232dc85ef9bcad7e3d",
"snapshot_id": "564317a39857e71b2839e0e75a80efdf548cbf13",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MBWlodarczyk/bso_project/a4620fb18d7f789d917627232dc85ef9bcad7e3d/3. Fortify/vuln_2.c",
"visit_date": "2023-05-08T04:58:40.268939"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
struct personal_data{
char name[5];
char surname[5];
};
int main(){
struct personal_data data;
memset(data.name,0,sizeof(data.name));
memset(data.name,0,sizeof(data));
memset(data.name,0,sizeof(data)+1);
printf(data.name);
return 0;
}
| 2.390625 | 2 |
2024-11-18T19:35:12.076009+00:00
| 2023-05-31T23:22:47 |
ff7874f6531edfb3b1e3479defed7bafa3755961
|
{
"blob_id": "ff7874f6531edfb3b1e3479defed7bafa3755961",
"branch_name": "refs/heads/main",
"committer_date": "2023-05-31T23:22:47",
"content_id": "f346ef832a7a456deab67977de5b639d625eb677",
"detected_licenses": [
"MIT"
],
"directory_id": "4a727ce379e9d21826895699d09164cdac4836d5",
"extension": "c",
"filename": "mmap_file_example.c",
"fork_events_count": 95,
"gha_created_at": "2018-11-09T22:21:21",
"gha_event_created_at": "2022-11-26T19:09:25",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 156924419,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1265,
"license": "MIT",
"license_type": "permissive",
"path": "/labs/lab04/mmap_file_example.c",
"provenance": "stackv2-0054.json.gz:12492",
"repo_name": "RHIT-CSSE/csse332",
"revision_date": "2023-05-31T23:22:47",
"revision_id": "7b9e292381062d25934c18210e6bbe7241392cdc",
"snapshot_id": "83e58d6c377e67d4cfcc37e2f20f18991c5063bf",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/RHIT-CSSE/csse332/7b9e292381062d25934c18210e6bbe7241392cdc/labs/lab04/mmap_file_example.c",
"visit_date": "2023-06-08T11:16:43.095931"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/mman.h>
#include <unistd.h>
#include "forth_embed.h"
#define STACKHEAP_MEM_START 0xf9f8c000
void main() {
//create the file and use lseek to ensure that it has enough space
//to contain the full page
int fd = open("page_0.dat", O_RDWR | O_CREAT, S_IRWXU);
if(fd < 0) {
perror("error loading linked file");
exit(25);
}
char data = '\0';
lseek(fd, getpagesize() - 1, SEEK_SET);
write(fd, &data, 1);
lseek(fd, 0, SEEK_SET);
char* result = mmap((void*) STACKHEAP_MEM_START,
getpagesize(),
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_FIXED | MAP_SHARED,
fd, 0);
//lets put some data in the file
for(int i = 0; i < getpagesize(); i++)
result[i] = 'Q';
// now lets unmap and close the file to ensure everything gets written
int munmap_result = munmap((void*) STACKHEAP_MEM_START, getpagesize());
if(munmap_result < 0) {
perror("munmap failed");
exit(6);
}
close(fd);
printf("done\n");
// take a look at the file to see if the write worked!
}
| 2.71875 | 3 |
2024-11-18T19:35:12.477560+00:00
| 2019-11-27T20:57:30 |
03ffd21bb4c95cb77fd0b964a11ae8757c4a1bc6
|
{
"blob_id": "03ffd21bb4c95cb77fd0b964a11ae8757c4a1bc6",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-27T20:57:30",
"content_id": "5a37bb35dcd0df63dc4f9f637c0f4d83871d01f3",
"detected_licenses": [
"MIT"
],
"directory_id": "478d0d3e8d715bed43bb94f1bd85c65193afa402",
"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": 203258458,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1233,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0054.json.gz:12878",
"repo_name": "Giancarl021/LAN-Murder",
"revision_date": "2019-11-27T20:57:30",
"revision_id": "1ffc2efd0d1d03e80ae86a0b7b02835822c58db2",
"snapshot_id": "ca4ad427d8a518a3ad04d3f13bb4fabf8194776c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Giancarl021/LAN-Murder/1ffc2efd0d1d03e80ae86a0b7b02835822c58db2/main.c",
"visit_date": "2020-07-07T05:00:40.055286"
}
|
stackv2
|
#include "lib"
int main(int argc, char *argv[]) {
init();
// char *map_path = "map/3-type.map";
// Map m = *parse_map(read_file(map_path));
// char ch;
// int position = 0,
// w = m.width,
// h = m.height;
// map_renderer(m, 0);
// do {
// ch = toupper(getch());
// if(ch != 'W' && ch != 'A' && ch != 'S' && ch != 'D') continue;
// system("cls");
// position = map_move(m, position, (ch == 'W' ? MV_UP : (ch == 'S' ? MV_DOWN : (ch == 'A' ? MV_LEFT : MV_RIGHT))));
// map_renderer(m, position);
// } while(ch != ' ');
//
// Environment *e = create_environment(m);
//
// generate_item(e);
// generate_item(e);
// generate_item(e);
// generate_item(e);
// generate_item(e);
//
// int i;
// for(i = 0; i < e->items_size; i++) {
// printf("\ntype: %d\ntag: %s\nlocation: %d", e->items[i].type, e->items[i].tag, e->items[i].location);
// }
if(!check_file("config.txt")) {
char address[256];
surround_text("BEM-VINDO AO LAN-MURDER!!!", '*');
printf("\n\nAntes de iniciar, poderia informar o endereco da pasta de salas?\n\n > ");
input(address, 255);
write_file("config.txt", address);
}
const char *a = read_file("config.txt");
printf("%s", a);
printf("\n\n%s", read_file(a));
printf("\n\n");
return 0;
}
| 2.1875 | 2 |
2024-11-18T19:35:12.821478+00:00
| 2023-08-29T11:30:11 |
25a80b0322662c4dc58b9ccaf211f36dbb57b0fa
|
{
"blob_id": "25a80b0322662c4dc58b9ccaf211f36dbb57b0fa",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-29T11:30:11",
"content_id": "e1c4141ac29b0f335f51c56d4055261fd642d717",
"detected_licenses": [
"BSD-3-Clause",
"BSD-4-Clause-UC"
],
"directory_id": "07664200f77c4d87baf972e367e772be8d5a65cd",
"extension": "c",
"filename": "yylex.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 206938721,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2334,
"license": "BSD-3-Clause,BSD-4-Clause-UC",
"license_type": "permissive",
"path": "/contrib/ingres/source/scanner/yylex.c",
"provenance": "stackv2-0054.json.gz:13264",
"repo_name": "TheSledgeHammer/2.11BSD_X44",
"revision_date": "2023-08-29T11:30:11",
"revision_id": "a342c2465bd295632d1b0ff1e3d11903bd9b2f4a",
"snapshot_id": "77e0f9cab93eb3abb337dd6ab7530a317cceecbd",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/TheSledgeHammer/2.11BSD_X44/a342c2465bd295632d1b0ff1e3d11903bd9b2f4a/contrib/ingres/source/scanner/yylex.c",
"visit_date": "2023-08-29T12:24:17.677815"
}
|
stackv2
|
# include "../ingres.h"
# include "../scanner.h"
/*
** YYLEX
** This is the control program for the scanner (lexical analyzer).
** Each call to yylex() returns a token for the next syntactic unit.
** If the object is of type I2CONST, I4CONST, F8CONST, SCONST or NAME, that
** object will also be entered in the symbol table, indexed by 'yylval'.
** If the object is not one of these types, yylval is the opcode field of
** the operator or keyword tables.
** The end-of-file token is zero.
*/
yylex()
{
register char chr;
register int rtval;
extern char Cmap[];
rtval = -1;
Lastok.tokop = 0;
/* GET NEXT TOKEN */
do
{
if((chr = gtchar()) <= 0)
{
# ifdef xSTR2
tTfp(72, 8, "end-of-file\n");
# endif
rtval = 0;
break;
}
switch(Cmap[chr])
{
case ALPHA:
rtval = name(chr);
break;
case NUMBR:
rtval = number(chr);
break;
case OPATR:
if ((rtval = operator(chr)) == 0)
rtval = -1;
break;
case PUNCT:
continue;
case CNTRL:
/* already converted number ? */
if (Pars)
switch (chr)
{
case CVAR_I2:
rtval = getcvar(Tokens.i2const, 2);
break;
case CVAR_I4:
rtval = getcvar(Tokens.i4const, 4);
break;
case CVAR_F8:
rtval = getcvar(Tokens.f8const, 8);
break;
case CVAR_S:
rtval = getcvar(Tokens.sconst, 0);
break;
default:
printf("funny character 0%o ingnored\n", chr);
continue;
}
break;
default:
syserr("invalid type in yylex()");
}
} while (rtval == -1);
if (rtval == 0)
{
Lastok.tokop = GOVAL;
Lastok.tok = 0;
Lastok.toktyp = 0;
}
return (rtval);
}
getcvar(type, len)
int type;
int len;
{
extern char *yylval;
extern char Cmap[];
register int save;
char buf[MAXSTRING + 1];
char *syment();
save = Lcase;
Lcase = 0;
yylval = buf;
if (len)
while ((yylval - buf) < len)
*yylval++ = gtchar();
else
{
do
{
*yylval = gtchar();
if ((yylval - buf) > MAXSTRING)
{
Lcase = save;
yyerror(STRLONG, 0);
}
if (Cmap[*yylval] == CNTRL && *yylval != '\0')
{
Lcase = save;
/* control char in string from equel */
yyerror(CNTRLCHR, 0);
}
} while (*yylval++);
len = yylval - buf;
}
Lcase = save;
yylval = syment(buf, len);
Lastok.tok = yylval;
Lastok.toktyp = type;
return (type);
}
| 2.671875 | 3 |
2024-11-18T19:35:12.876057+00:00
| 2021-03-14T20:29:54 |
a99e6fdf575a7fc4e4e5b1d7e044af0181971b13
|
{
"blob_id": "a99e6fdf575a7fc4e4e5b1d7e044af0181971b13",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-14T20:29:54",
"content_id": "90fec5861a035fc7d3d19c0c822c36609acc1da8",
"detected_licenses": [
"MIT"
],
"directory_id": "ec53de34881276a7bd5348f1f550483347cd5db4",
"extension": "h",
"filename": "uart2.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 345367411,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1961,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/STM8_headers/examples/calculate_CRC/uart2.h",
"provenance": "stackv2-0054.json.gz:13392",
"repo_name": "maxgerhardt/stm8-headers-pio",
"revision_date": "2021-03-14T20:29:54",
"revision_id": "25e3552560df30445cdd1d8dee9cc95454ca92a8",
"snapshot_id": "58c63ea7fdb591a23845acac89bf7cc863c5128a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/maxgerhardt/stm8-headers-pio/25e3552560df30445cdd1d8dee9cc95454ca92a8/lib/STM8_headers/examples/calculate_CRC/uart2.h",
"visit_date": "2023-04-04T23:36:23.861835"
}
|
stackv2
|
/**
\file uart2.h
\author G. Icking-Konert
\date 2017-02-19
\version 0.1
\brief declaration of UART2 functions/macros
declaration of UART2 functions.
*/
/*-----------------------------------------------------------------------------
MODULE DEFINITION FOR MULTIPLE INCLUSION
-----------------------------------------------------------------------------*/
#ifndef _UART2_H_
#define _UART2_H_
/*----------------------------------------------------------
INCLUDE FILES
----------------------------------------------------------*/
#include <stdint.h>
#include "config.h"
/*-----------------------------------------------------------------------------
DECLARATION OF GLOBAL VARIABLES
-----------------------------------------------------------------------------*/
// declare or reference to global variables, depending on '_MAIN_'
#if defined(_MAIN_)
volatile uint8_t g_key; ///< byte received. Stored in Rx ISR
#else // _MAIN_
extern volatile uint8_t g_key;
#endif // _MAIN_
/*----------------------------------------------------------
GLOBAL MACROS
----------------------------------------------------------*/
/// read received byte from UART2
#define UART2_read() (sfr_UART2.DR.byte)
/// send byte via UART2
#define UART2_write(x) { while (!(sfr_UART2.SR.TXE)); sfr_UART2.DR.byte = x; }
/// flush UART2
#define UART2_flush() { while (!(sfr_UART2.SR.TC)); }
/*----------------------------------------------------------
GLOBAL FUNCTIONS
----------------------------------------------------------*/
/// initialize UART2
void UART2_begin(uint32_t BR);
/// ISR for UART2 receive
ISR_HANDLER(UART2_RXNE_ISR, _UART2_R_RXNE_VECTOR_);
/*-----------------------------------------------------------------------------
END OF MODULE DEFINITION FOR MULTIPLE INLUSION
-----------------------------------------------------------------------------*/
#endif // _UART2_H_
| 2.15625 | 2 |
2024-11-18T19:35:13.442414+00:00
| 2023-06-23T10:11:23 |
bf28998bf894cf0cb81177512dd56dad518fd3d4
|
{
"blob_id": "bf28998bf894cf0cb81177512dd56dad518fd3d4",
"branch_name": "refs/heads/main",
"committer_date": "2023-06-23T10:11:23",
"content_id": "e557ff0c13801a44a7813c4519a2cb0e520caa45",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "803898f95f34521f4fc08ff42534888367ff4028",
"extension": "c",
"filename": "select_group.c",
"fork_events_count": 29,
"gha_created_at": "2012-06-19T15:15:17",
"gha_event_created_at": "2023-06-23T10:11:24",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 4715296,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5039,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/gempak/source/programs/gui/ntrans/select_group.c",
"provenance": "stackv2-0054.json.gz:13649",
"repo_name": "Unidata/gempak",
"revision_date": "2023-06-23T10:11:23",
"revision_id": "f3997c88469be1c08cd265ef553c812a28778284",
"snapshot_id": "17057d45ad92512f56193155dd0d6ad0301965d8",
"src_encoding": "UTF-8",
"star_events_count": 53,
"url": "https://raw.githubusercontent.com/Unidata/gempak/f3997c88469be1c08cd265ef553c812a28778284/gempak/source/programs/gui/ntrans/select_group.c",
"visit_date": "2023-07-13T19:39:57.114715"
}
|
stackv2
|
#include "geminc.h"
#include "gemprm.h"
#include "interface.h"
#include "panel.h"
#include "panelstr.h"
#include "Nxm.h"
extern Widget ggroup_listW;
Widget group_listW;
Widget fileLabelW;
void create_gpctrB ( Widget parent );
void SelGroup_Pushb_Callback ( Widget, long, XtPointer );
/************************************************************************
* SELECT_GROUP.C *
* *
* Module to take care of creating group selection panel. *
* *
* Log: *
* Chien Lin/EAI 10/92 *
* G. Krueger/EAI 9/97 Updated NxmWarning to NxmWarn_Show *
* G. Krueger/EAI 11/97 Renamed NxmHelp functions *
* I. Durham/GSC 5/98 Changed call for underscore *
* J. Wu/GSC 5/01 free XmStrings *
************************************************************************/
void create_selectgroup ( Widget parent )
{
Widget group_pane, form, frame, rowcol, bb;
XmString xmstr;
/*---------------------------------------------------------------------*/
/* Create a popup shell & list widget for the file list. */
group_select_toplevel = XmCreateBulletinBoardDialog(parent,
"groupselect",NULL, 0);
group_pane = XtVaCreateManagedWidget("group_pane",
xmPanedWindowWidgetClass,
group_select_toplevel,
XmNsashWidth, 1,
XmNsashHeight, 1,
NULL);
form = XtVaCreateManagedWidget("ListGroupForm",
xmFormWidgetClass, group_pane,
NULL );
bb = XtVaCreateManagedWidget("bb1",
xmBulletinBoardWidgetClass, form,
NULL );
xmstr = XmStringCreateLocalized("File:");
fileLabelW = XtVaCreateManagedWidget ("fileLb",
xmLabelWidgetClass, bb,
XmNlabelString, xmstr,
NULL );
XmStringFree( xmstr );
frame = XtVaCreateManagedWidget("List_Group",
xmFrameWidgetClass, form,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, bb,
XmNleftAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM,
NULL );
group_listW = create_grouplist(frame);
bb = XtVaCreateManagedWidget("bb2",
xmBulletinBoardWidgetClass, form,
XmNtopAttachment, XmATTACH_WIDGET,
XmNtopWidget, frame,
NULL );
rowcol = XtVaCreateManagedWidget("Model_Group",
xmRowColumnWidgetClass, bb,
XmNnumColumns, 1,
XmNorientation, XmHORIZONTAL,
XmNradioBehavior, False,
NULL );
create_gpctrB(rowcol);
MultipanelFrame = XtVaCreateManagedWidget("MultiPanel",
xmFrameWidgetClass, group_pane,
NULL );
create_multipanel(MultipanelFrame);
}
/*=====================================================================*/
void create_gpctrB ( Widget parent )
{
char *labels[] = { "Clear Screen", "Help","Close" };
Arg args[4];
long ii;
Cardinal argcnt;
Widget pushbutton;
/*---------------------------------------------------------------------*/
for( ii = 0; ii< (long)XtNumber(labels); ii++) {
argcnt = 0;
XtSetArg(args[argcnt], XmNshadowThickness,3); argcnt++;
pushbutton = XtCreateManagedWidget(labels[ii],
xmPushButtonWidgetClass,
parent,
args,
argcnt);
XtAddCallback(pushbutton, XmNactivateCallback,
(XtCallbackProc)SelGroup_Pushb_Callback,
(XtPointer)ii);
}
}
/*=====================================================================*/
/* ARGSUSED */
void SelGroup_Pushb_Callback ( Widget w, long which, XtPointer call )
{
int status = 0;
/*---------------------------------------------------------------------*/
switch (which) {
case 0: /* CLEAR SCREEN */
ClearAreas(NULL, NULL, NULL);
status = 0;
break;
case 1: /* HELP */
NxmHelp_helpBtnCb( NULL, 6, NULL );
status = 0;
break;
case 2: /* CANCEL */
status = 1;
break;
default:
status = 1;
break;
}
if (status)
XtUnmanageChild(group_select_toplevel);
}
/*=====================================================================*/
/* ARGSUSED */
void ClearAreas ( Widget w, XtPointer clnt, XtPointer call )
{
int i;
int iret;
/*---------------------------------------------------------------------*/
if ( !NxmPrt_isPrtFlgSet() ) {
for(i = 0; i < PixmapData.old_pixmap_no; i ++ ) {
if ( i == 0 ) {
gstanm ( &iret );
}
else {
gsplot ( &iret );
}
gclear ( &iret );
}
genanm ( &iret );
geplot ( &iret );
PixmapData.current_pixmap = 0;
display_pixmap();
}
}
/*=====================================================================*/
void ok_select ( Widget widget )
{
int selct, iret;
/*---------------------------------------------------------------------*/
XtVaGetValues(group_listW,
XmNselectedItemCount, &selct,
NULL);
if ( selct == 0 ) {
NxmWarn_show( widget, " Please Select a Group. ");
}
else {
if ( !MpanelMode || ViewFrame == 1 )
gclear(&iret);
GroupLoadFlag = 1;
ViewFrame = 0;
strcpy (panelSrc.group_name[CurrentPanel],GroupList[SelectGroupNo-1].groupname);
load_group(SelectGroupNo);
}
}
/*=====================================================================*/
void delete_grouplist ( void )
{
XmListDeleteAllItems(group_listW);
XmListDeleteAllItems(ggroup_listW);
}
| 2.046875 | 2 |
2024-11-18T19:35:13.819354+00:00
| 2022-10-30T16:12:24 |
2f92ab3dc7fbcd29328dc912c06c76efc1fef98c
|
{
"blob_id": "2f92ab3dc7fbcd29328dc912c06c76efc1fef98c",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-30T16:12:24",
"content_id": "b494974164a11824792305cd95c916b841a3ed4d",
"detected_licenses": [
"MIT"
],
"directory_id": "04132a0e5bb04c5df3c81b54aa90fae60fec6853",
"extension": "cpp",
"filename": "reverse-a-linked-list.cpp",
"fork_events_count": 91,
"gha_created_at": "2018-07-07T06:09:14",
"gha_event_created_at": "2022-10-30T16:12:24",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 140057670,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 414,
"license": "MIT",
"license_type": "permissive",
"path": "/Data-Structures/Linked-Lists/reverse-a-linked-list.cpp",
"provenance": "stackv2-0054.json.gz:13905",
"repo_name": "rajat19/Hackerrank",
"revision_date": "2022-10-30T16:12:24",
"revision_id": "d261d8d3ec103a66674931121c3d6f05ef6571ed",
"snapshot_id": "9d7b8f7fb7ce6a78438f729823db34c83d3b199c",
"src_encoding": "UTF-8",
"star_events_count": 30,
"url": "https://raw.githubusercontent.com/rajat19/Hackerrank/d261d8d3ec103a66674931121c3d6f05ef6571ed/Data-Structures/Linked-Lists/reverse-a-linked-list.cpp",
"visit_date": "2022-11-11T03:15:04.032460"
}
|
stackv2
|
// Complete the reverse function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
SinglyLinkedListNode* reverse(SinglyLinkedListNode* p) {
if (p->next == NULL) {
return p;
}
SinglyLinkedListNode* head = reverse(p->next);
SinglyLinkedListNode* q = p->next;
q->next = p;
p->next = NULL;
return head;
}
| 3.0625 | 3 |
2024-11-18T19:35:14.084756+00:00
| 2020-02-04T14:25:27 |
4178a478cc3d86d0810ac621ac4f40722b2316c6
|
{
"blob_id": "4178a478cc3d86d0810ac621ac4f40722b2316c6",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-04T14:25:27",
"content_id": "261faf161a6b27774f3c865e5f4e5a9b8f3f33ae",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "5f41d9f61168d13ba41f67588219ef566f1eb87b",
"extension": "c",
"filename": "word_count-seq.c",
"fork_events_count": 1,
"gha_created_at": "2017-01-31T14:23:48",
"gha_event_created_at": "2020-02-04T14:25:29",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 80527160,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7116,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/phoenix/word_count/src/word_count-seq.c",
"provenance": "stackv2-0054.json.gz:14035",
"repo_name": "tudinfse/intel_mpx_explained",
"revision_date": "2020-02-04T14:25:27",
"revision_id": "9a3d7b060742d8fe89c1b56898f2b2e3617b670b",
"snapshot_id": "0671a667006bd43c436ddfc0c2cee43fa35d4db8",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/tudinfse/intel_mpx_explained/9a3d7b060742d8fe89c1b56898f2b2e3617b670b/src/phoenix/word_count/src/word_count-seq.c",
"visit_date": "2022-04-06T00:50:14.193509"
}
|
stackv2
|
/* Copyright (c) 2007-2009, Stanford University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Stanford University nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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.
*/
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <pthread.h>
#include "map_reduce.h"
#include "stddefines.h"
#include "sort-pthread.h"
#define DEFAULT_DISP_NUM 10
#define START_ARRAY_SIZE 2000
typedef struct {
char* word;
int count;
} wc_count_t;
typedef struct {
long flen;
char *fdata;
} wc_data_t;
enum {
IN_WORD,
NOT_IN_WORD
};
wc_count_t* words;
int use_len;
int length;
void wordcount_getword(void *args_in);
void wordcount_addword(char* word, int len) ;
/** wordcount_cmp()
* Comparison function to compare 2 words
*/
int wordcount_cmp(const void *v1, const void *v2)
{
wc_count_t* w1 = (wc_count_t*)v1;
wc_count_t* w2 = (wc_count_t*)v2;
int i1 = w1->count;
int i2 = w2->count;
if (i1 < i2) return 1;
else if (i1 > i2) return -1;
else return 0;
}
/** wordcount_splitter()
* Memory map the file and divide file on a word border i.e. a space.
*/
void wordcount_splitter(void *data_in)
{
int i;
wc_data_t * data = (wc_data_t *)data_in;
words = (wc_count_t*)calloc(START_ARRAY_SIZE,sizeof(wc_count_t));
length = START_ARRAY_SIZE;
use_len = 0;
for(i=0;i<START_ARRAY_SIZE;i++)
words[i].count = 0;
map_args_t* out = (map_args_t*)malloc(sizeof(map_args_t));
out->data = data->fdata;
out->length = data->flen;
wordcount_getword(out);
free(out);
}
/** wordcount_map()
* Go through the file and update the count for each unique word
*/
void wordcount_getword(void *args_in)
{
map_args_t* args = (map_args_t*)args_in;
char *curr_start;
char curr_ltr;
int state = NOT_IN_WORD;
int i;
assert(args);
char *data = (char *)(args->data);
curr_start = data;
assert(data);
//printf("args_len is %d\n", args->length);
for (i = 0; i < args->length; i++)
{
char curr_ltr = data[i];
if( curr_ltr >= 'a' && curr_ltr <= 'z') curr_ltr -= ('a' - 'A');
switch (state)
{
case IN_WORD:
data[i] = curr_ltr;
if ((curr_ltr < 'A' || curr_ltr > 'Z') && curr_ltr != '\'')
{
data[i] = 0;
//printf("\nthe word is %s\n\n",curr_start);
wordcount_addword(curr_start, &data[i] - curr_start + 1);
state = NOT_IN_WORD;
}
break;
default:
case NOT_IN_WORD:
if (curr_ltr >= 'A' && curr_ltr <= 'Z')
{
curr_start = &data[i];
data[i] = curr_ltr;
state = IN_WORD;
}
break;
}
}
// Add the last word
if (state == IN_WORD)
{
data[args->length] = 0;
//printf("\nthe word is %s\n\n",curr_start);
wordcount_addword(curr_start, &data[i] - curr_start + 1);
}
}
/** dobsearch()
* Search for a specific word in the array
*/
int dobsearch(char* word)
{
int cmp, high = use_len, low = -1, next;
// Binary search the array to find the key
while (high - low > 1)
{
next = (high + low) / 2;
cmp = strcmp(word, words[next].word);
if (cmp == 0)
return next;
else if (cmp < 0)
high = next;
else
low = next;
}
return high;
}
/** wordcount_addword()
* Add a new word to the array in the correct sorted postion
*/
void wordcount_addword(char* word, int len)
{
int pos = dobsearch(word);
if (pos >= use_len)
{
// at end
words[use_len].word = word;
words[use_len].count = 1;
use_len++;
}
else if (pos < 0)
{
// at front
memmove(&words[1], words, use_len*sizeof(wc_count_t));
words[0].word = word;
words[0].count = 1;
use_len++;
}
else if (strcmp(word, words[pos].word) == 0)
{
// match
words[pos].count++;
}
else
{
// insert at pos
memmove(&words[pos+1], &words[pos], (use_len-pos)*sizeof(wc_count_t));
words[pos].word = word;
words[pos].count = 1;
use_len++;
}
if(use_len == length)
{
length *= 2;
words = (wc_count_t*)realloc(words,length*sizeof(wc_count_t));
}
}
int main(int argc, char *argv[]) {
int i;
int fd;
char * fdata;
int disp_num;
struct stat finfo;
char * fname, * disp_num_str;
// Make sure a filename is specified
if (argv[1] == NULL)
{
printf("USAGE: %s <filename> [Top # of results to display]\n", argv[0]);
exit(1);
}
fname = argv[1];
disp_num_str = argv[2];
printf("Wordcount: Running...\n");
// Read in the file
CHECK_ERROR((fd = open(fname, O_RDONLY)) < 0);
// Get the file info (for file length)
CHECK_ERROR(fstat(fd, &finfo) < 0);
// Memory map the file
CHECK_ERROR((fdata = mmap(0, finfo.st_size + 1,
PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0)) == NULL);
// Get the number of results to display
CHECK_ERROR((disp_num = (disp_num_str == NULL) ?
DEFAULT_DISP_NUM : atoi(disp_num_str)) <= 0);
// Setup splitter args
wc_data_t wc_data;
wc_data.flen = finfo.st_size;
wc_data.fdata = fdata;
printf("Wordcount Serial: Running\n");
wordcount_splitter(&wc_data);
qsort(words, use_len, sizeof(wc_count_t), wordcount_cmp);
dprintf("Use len is %d\n", use_len);
for(i=0; i< disp_num && i < use_len ; i++)
{
wc_count_t* temp = &(words[i]);
dprintf("The word is %s and count is %d\n", temp->word, temp->count);
}
free(words);
CHECK_ERROR(munmap(fdata, finfo.st_size + 1) < 0);
CHECK_ERROR(close(fd) < 0);
return 0;
}
| 2.140625 | 2 |
2024-11-18T19:35:14.200113+00:00
| 2021-06-17T17:18:00 |
cbe37dc97ddc9bc852e909b7558fc52ce47bd561
|
{
"blob_id": "cbe37dc97ddc9bc852e909b7558fc52ce47bd561",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-17T17:18:00",
"content_id": "a88f41f2bf2ab6a1b40a66eda788244d923dc0f9",
"detected_licenses": [
"MIT"
],
"directory_id": "d0d6212681620c73de57744e019cf554e3576dc9",
"extension": "c",
"filename": "q2.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 342943974,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 459,
"license": "MIT",
"license_type": "permissive",
"path": "/Atividades/Recursão/q2.c",
"provenance": "stackv2-0054.json.gz:14291",
"repo_name": "Pedro-costa99/inf029-pedrocosta",
"revision_date": "2021-06-17T17:18:00",
"revision_id": "3d9fce4f943c034f74db34a2d072b43f88dcffae",
"snapshot_id": "686f738642f29af1f2bb03778053a3abb66970a4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Pedro-costa99/inf029-pedrocosta/3d9fce4f943c034f74db34a2d072b43f88dcffae/Atividades/Recursão/q2.c",
"visit_date": "2023-05-28T14:55:30.323218"
}
|
stackv2
|
#include<stdio.h>
#include <stdlib.h>
int fibonacci(int valor);
int main(void){
int valor;
printf("Informe a quantidade de termos da sequência: ");
scanf("%d", &valor);
int i = 0;
printf("%d ", i);
for(i = 0; i < valor - 1; i++){
printf("%d ", fibonacci(i + 1));
}
return 0;
}
int fibonacci(int valor){
if (valor <= 1)
return valor;
return fibonacci(valor - 1) + fibonacci(valor - 2);
}
| 3.890625 | 4 |
2024-11-18T19:35:14.366035+00:00
| 2020-05-22T14:13:15 |
142dd43e19ab1baec30f5289c7c47c21c5394bd4
|
{
"blob_id": "142dd43e19ab1baec30f5289c7c47c21c5394bd4",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-22T14:13:15",
"content_id": "4c79ee8bd989f6a91acc3a9b875666bc4dd108e5",
"detected_licenses": [
"MIT"
],
"directory_id": "3de500cb89ae59c62c7d43d47b3af98dfcba2ffc",
"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": 266121852,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 874,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0054.json.gz:14547",
"repo_name": "ZeroBone/GarbageSet",
"revision_date": "2020-05-22T14:13:15",
"revision_id": "89fb26b6b1eb40651fa493984ff1b89fd06fd6d4",
"snapshot_id": "d1f39e093f9079ad8aced78256465cac554accfd",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ZeroBone/GarbageSet/89fb26b6b1eb40651fa493984ff1b89fd06fd6d4/main.c",
"visit_date": "2022-07-31T16:17:49.652962"
}
|
stackv2
|
#include <stdio.h>
#include <assert.h>
#include "src/garbageset.h"
#define TEST_CAPACITY 1793
int main() {
int testPayload;
garbageset_t set;
garbageset_init(&set, TEST_CAPACITY, sizeof(int));
for (int i = 0; i < TEST_CAPACITY; i++) {
assert(garbageset_get(&set, i) == NULL);
}
for (int i = 0; i < TEST_CAPACITY; i += 2) {
testPayload = i;
garbageset_write(&set, i, &testPayload);
}
for (int i = 0; i < TEST_CAPACITY; i++) {
if (i % 2 == 0) {
assert(garbageset_isset(&set, i));
assert(*(int*)garbageset_get(&set, i) == i);
assert(*(int*)garbageset_getUnsafe(&set, i) == i);
}
else {
assert(!garbageset_isset(&set, i));
assert(garbageset_get(&set, i) == NULL);
}
}
printf("Hello, World/!\n");
return 0;
}
| 2.734375 | 3 |
2024-11-18T19:35:14.770859+00:00
| 2013-04-17T18:42:40 |
599e25fc4322268d6c95258c2cd84a84e3679bf6
|
{
"blob_id": "599e25fc4322268d6c95258c2cd84a84e3679bf6",
"branch_name": "refs/heads/master",
"committer_date": "2013-04-17T18:42:40",
"content_id": "639f0aaf868eca99b7fccacd9b57a7d4535b8b1a",
"detected_licenses": [
"MIT"
],
"directory_id": "bb108c3ea7d235e6fee0575181b5988e6b6a64ef",
"extension": "c",
"filename": "ami_dsk.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": 2064,
"license": "MIT",
"license_type": "permissive",
"path": "/mame/src/lib/formats/ami_dsk.c",
"provenance": "stackv2-0054.json.gz:14804",
"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/lib/formats/ami_dsk.c",
"visit_date": "2021-01-20T05:31:15.086981"
}
|
stackv2
|
/*********************************************************************
formats/ami_dsk.c
Amiga disk images
*********************************************************************/
#include <string.h>
#include "formats/ami_dsk.h"
#include "formats/basicdsk.h"
/*****************************************************************************
Amiga floppy core functions
*****************************************************************************/
static FLOPPY_IDENTIFY( amiga_dsk_identify )
{
UINT64 size;
*vote = 100;
/* first check the size of the image */
size = floppy_image_size(floppy);
if ((size != 901120) && (size != 1802240))
*vote = 0;
return FLOPPY_ERROR_SUCCESS;
}
static FLOPPY_CONSTRUCT( amiga_dsk_construct )
{
struct basicdsk_geometry geometry;
/* setup geometry with standard values */
memset(&geometry, 0, sizeof(geometry));
geometry.heads = 2;
geometry.tracks = 80;
geometry.first_sector_id = 0;
geometry.sector_length = 512;
if (params)
{
/* create */
geometry.sectors = option_resolution_lookup_int(params, PARAM_SECTORS);
}
else
{
/* open */
UINT64 size = floppy_image_size(floppy);
geometry.sectors = size/512/80/2;
if (geometry.sectors != 11 && geometry.sectors != 22)
return FLOPPY_ERROR_INVALIDIMAGE;
}
return basicdsk_construct(floppy, &geometry);
}
/*****************************************************************************
Amiga floppy options
*****************************************************************************/
FLOPPY_OPTIONS_START( amiga )
FLOPPY_OPTION(
ami_dsk,
"adf",
"Amiga floppy disk image",
amiga_dsk_identify,
amiga_dsk_construct,
NULL,
HEADS([2])
TRACKS([80])
SECTORS([11]/22)
)
FLOPPY_OPTIONS_END
FLOPPY_OPTIONS_START( amiga_only )
FLOPPY_OPTION(
ami_dsk,
"adf",
"Amiga floppy disk image",
amiga_dsk_identify,
amiga_dsk_construct,
NULL,
HEADS([2])
TRACKS([80])
SECTORS([11]/22)
)
FLOPPY_OPTIONS_END0
| 2.1875 | 2 |
2024-11-18T19:35:15.704725+00:00
| 2020-03-07T19:51:19 |
35b58176a2d7e88409e120584822d9e2b209a6d1
|
{
"blob_id": "35b58176a2d7e88409e120584822d9e2b209a6d1",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-07T19:51:19",
"content_id": "fa243edd12e0a469be09b62b2fdd3728f195013c",
"detected_licenses": [
"MIT"
],
"directory_id": "eba3c38502d9d98203005985e455086b7a49db49",
"extension": "c",
"filename": "paging.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-01T19:23:39",
"gha_event_created_at": "2020-03-07T19:44:18",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 237665808,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1007,
"license": "MIT",
"license_type": "permissive",
"path": "/paging.c",
"provenance": "stackv2-0054.json.gz:15574",
"repo_name": "sigops-uiuc/flaum",
"revision_date": "2020-03-07T19:51:19",
"revision_id": "cca6796216240764f0b194e4de873d2c0b76a652",
"snapshot_id": "b92d1ca314a57694fddef0f1302fd4967fd92857",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/sigops-uiuc/flaum/cca6796216240764f0b194e4de873d2c0b76a652/paging.c",
"visit_date": "2020-12-26T22:18:57.195592"
}
|
stackv2
|
#include "paging.h"
extern uint8_t __end;
// The size of this array should be determined by the amount of memory the hardware actually has. (total_mem/page_size)
///@todo declare somewhere else?
page_flags_t page_table[PAGE_NUM_TMP];
void init_pages(){
int i;
uint32_t kernel_pages;
kernel_pages = ((uint32_t)&__end) / PAGE_SIZE;
for(i = 0; i < kernel_pages; i++){
page_table[i].allocated = 1;
page_table[i].kernel = 1;
page_table[i].mapped_addr = 4096 * i;
}
for(; i < PAGE_NUM_TMP; i++){
page_table[i].allocated = 0;
page_table[i].kernel = 0;
page_table[i].mapped_addr = 4096 * i;
}
return;
}
void *alloc_page() {
for (int i = 0; i < PAGE_NUM_TMP; i++) {
if (page_table[i].allocated == 0) {
return (void *) page_table[i].mapped_addr;
}
}
return (void *) ERR_NO_PAGE;
}
void free_page(void *ptr) {
int mapped_page = (int)ptr / PAGE_SIZE;
page_table[mapped_page].allocated = 0;
}
| 2.84375 | 3 |
2024-11-18T19:35:16.153506+00:00
| 2015-03-18T12:19:28 |
d49e0d1a58e93d77b861c492342879d28812b65e
|
{
"blob_id": "d49e0d1a58e93d77b861c492342879d28812b65e",
"branch_name": "refs/heads/master",
"committer_date": "2015-03-18T12:19:28",
"content_id": "2a2e115623b9d246d30aee6d4d390801b3bbe472",
"detected_licenses": [
"MIT"
],
"directory_id": "f9a09e292d3a1b7b6470a610320954757004a87b",
"extension": "c",
"filename": "cim_instance.c",
"fork_events_count": 0,
"gha_created_at": "2009-12-20T19:26:21",
"gha_event_created_at": "2015-03-18T12:20:42",
"gha_language": "C",
"gha_license_id": null,
"github_id": 443969,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 10844,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/sfcc/cim_instance.c",
"provenance": "stackv2-0054.json.gz:15702",
"repo_name": "dmacvicar/ruby-sfcc",
"revision_date": "2015-03-18T12:19:28",
"revision_id": "a2688603dc64f6980e744833f1243f094cac1a3b",
"snapshot_id": "40231b9d1140ef8913b7985de92422c3f29bde2a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dmacvicar/ruby-sfcc/a2688603dc64f6980e744833f1243f094cac1a3b/ext/sfcc/cim_instance.c",
"visit_date": "2016-08-05T17:01:50.146374"
}
|
stackv2
|
#include "cim_instance.h"
#include "cim_object_path.h"
#include "cim_client.h"
static void
mark(rb_sfcc_instance *rsi)
{
if (!NIL_P(rsi->client))
rb_gc_mark(rsi->client);
}
static void
dealloc(rb_sfcc_instance *rsi)
{
/* fprintf(stderr, "Sfcc_dealloc_cim_instance %p\n", inst); */
rsi->inst->ft->release(rsi->inst);
free(rsi);
}
/**
* call-seq:
* property(name) -> Cim::Data
*
* Gets a named property value, where name is a Symbol or String
*/
static VALUE property(VALUE self, VALUE name)
{
CIMCInstance *ptr;
CIMCStatus status;
CIMCData data;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
data = ptr->ft->getProperty(ptr, to_charptr(name), &status);
if ( !status.rc )
return sfcc_cimdata_to_value(&data, rsi->client);
sfcc_rb_raise_if_error(status, "Can't retrieve property '%s'", to_charptr(name));
return Qnil;
}
/**
* call-seq:
* instance.each_property do |name, value|
* ...
* end
*
* enumerates properties yielding the property name and
* its value
*
*/
static VALUE each_property(VALUE self)
{
CIMCInstance *ptr;
CIMCStatus status;
int k=0;
int num_props=0;
CIMCString *property_name = NULL;
CIMCData data;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
num_props = ptr->ft->getPropertyCount(ptr, &status);
if (!status.rc) {
for (; k < num_props; ++k) {
data = ptr->ft->getPropertyAt(ptr, k, &property_name, &status);
if (!status.rc) {
rb_yield_values(2, (property_name ? rb_str_intern(rb_str_new2(property_name->ft->getCharPtr(property_name, NULL))) : Qnil), sfcc_cimdata_to_value(&data, rsi->client));
}
else {
sfcc_rb_raise_if_error(status, "Can't retrieve property #%d", k);
}
if (property_name) property_name->ft->release(property_name);
}
}
else {
sfcc_rb_raise_if_error(status, "Can't retrieve property count");
}
return Qnil;
}
/**
* call-seq:
* property_count()
*
* Gets the number of properties contained in this Instance
*/
static VALUE property_count(VALUE self)
{
CIMCInstance *ptr;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
return UINT2NUM(ptr->ft->getPropertyCount(ptr, NULL));
}
/**
* call-seq:
* set_property(name, value)
*
* Adds/replaces a names property
*/
static VALUE set_property(VALUE self, VALUE name, VALUE value)
{
CIMCInstance *ptr;
CIMCData data;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
data = sfcc_value_to_cimdata(value);
ptr->ft->setProperty(ptr, to_charptr(name), &data.value, data.type);
return value;
}
/**
* call-seq:
* object_path() -> ObjectPath
*
* Generates an ObjectPath out of the nameSpace, classname and
* key propeties of this Instance.
*/
static VALUE object_path(VALUE self)
{
CIMCInstance *ptr;
CIMCObjectPath *op;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
op = ptr->ft->getObjectPath(ptr, NULL);
return Sfcc_wrap_cim_object_path(op, rsi->client);
}
/**
* call-seq:
* set_property_filter(property_list, keys)
*
* Directs CIMC to ignore any setProperty operations for this
* instance for any properties not in this list.
*
* +property_list+ If not nil, the members of the array define one
* or more Property names to be accepted by set_property operations.
*
* +keys+ Array of key property names of this instance. This array
* must be specified.
*
*/
static VALUE set_property_filter(VALUE self, VALUE property_list, VALUE keys)
{
CIMCStatus status;
CIMCInstance *ptr;
char **prop_a;
char **key_a;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
prop_a = sfcc_value_array_to_string_array(property_list);
key_a = sfcc_value_array_to_string_array(keys);
status = ptr->ft->setPropertyFilter(ptr, prop_a, key_a);
free(prop_a);
free(key_a);
sfcc_rb_raise_if_error(status, "Can't set property filter");
return self;
}
/**
* call-seq:
* qualifier(name)
*
* gets a named qualifier value
*/
static VALUE qualifier(VALUE self, VALUE name)
{
CIMCInstance *ptr;
CIMCStatus status;
CIMCData data;
rb_sfcc_instance *rsi;
memset(&status, 0, sizeof(CIMCStatus));
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
data = ptr->ft->getQualifier(ptr, to_charptr(name), &status);
if ( !status.rc )
return sfcc_cimdata_to_value(&data, rsi->client);
sfcc_rb_raise_if_error(status, "Can't retrieve qualifier '%s'", to_charptr(name));
return Qnil;
}
/**
* call-seq:
* cimclass.each_qualifier do |name, value|
* ...
* end
*
* enumerates properties yielding the qualifier name and
* its value
*
*/
static VALUE each_qualifier(VALUE self)
{
CIMCInstance *ptr;
CIMCStatus status;
int k=0;
int num_props=0;
CIMCString *qualifier_name = NULL;
CIMCData data;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
num_props = ptr->ft->getQualifierCount(ptr, &status);
if (!status.rc) {
for (; k < num_props; ++k) {
data = ptr->ft->getQualifierAt(ptr, k, &qualifier_name, &status);
if (!status.rc) {
rb_yield_values(2, (qualifier_name ? rb_str_new2(qualifier_name->ft->getCharPtr(qualifier_name, NULL)) : Qnil), sfcc_cimdata_to_value(&data, rsi->client));
}
else {
sfcc_rb_raise_if_error(status, "Can't retrieve qualifier #%d", k);
}
if (qualifier_name) qualifier_name->ft->release(qualifier_name);
}
}
else {
sfcc_rb_raise_if_error(status, "Can't retrieve qualifier count");
}
return Qnil;
}
/**
* call-seq:
* qualifier_count()
*
* Gets the number of qualifiers in this instance
*/
static VALUE qualifier_count(VALUE self)
{
CIMCInstance *ptr;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
return UINT2NUM(ptr->ft->getQualifierCount(ptr, NULL));
}
/**
* call-seq:
* property_qualifier(property_name, qualifier_name)
*
* gets a named property qualifier value
*/
static VALUE property_qualifier(VALUE self, VALUE property_name, VALUE qualifier_name)
{
CIMCInstance *ptr;
CIMCStatus status;
CIMCData data;
rb_sfcc_instance *rsi;
memset(&status, 0, sizeof(CIMCStatus));
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
data = ptr->ft->getPropertyQualifier(ptr, to_charptr(property_name),
to_charptr(qualifier_name), &status);
if ( !status.rc )
return sfcc_cimdata_to_value(&data, rsi->client);
sfcc_rb_raise_if_error(status, "Can't retrieve property qualifier '%s'", to_charptr(qualifier_name));
return Qnil;
}
/**
* call-seq:
* cimclass.each_property_qualifier(property_name) do |name, value|
* ...
* end
*
* enumerates properties yielding the property qualifier name and
* its value
*
*/
static VALUE each_property_qualifier(VALUE self, VALUE property_name)
{
CIMCInstance *ptr;
CIMCStatus status;
int k=0;
int num_props=0;
rb_sfcc_instance *rsi;
CIMCString *property_qualifier_name = NULL;
CIMCData data;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
num_props = ptr->ft->getPropertyQualifierCount(ptr, to_charptr(property_name), &status);
if (!status.rc) {
for (; k < num_props; ++k) {
data = ptr->ft->getPropertyQualifierAt(ptr, to_charptr(property_name), k, &property_qualifier_name, &status);
if (!status.rc) {
rb_yield_values(2, (property_qualifier_name ? rb_str_new2(property_qualifier_name->ft->getCharPtr(property_qualifier_name, NULL)) : Qnil), sfcc_cimdata_to_value(&data, rsi->client));
}
else {
sfcc_rb_raise_if_error(status, "Can't retrieve property qualifier #%d", k);
}
if (property_qualifier_name) property_qualifier_name->ft->release(property_qualifier_name);
}
}
else {
sfcc_rb_raise_if_error(status, "Can't retrieve property qualifier count");
}
return Qnil;
}
/**
* call-seq:
* property_qualifier_count(property_name)
*
* Gets the number of qualifiers contained in this property
*/
static VALUE property_qualifier_count(VALUE self, VALUE property_name)
{
CIMCInstance *ptr;
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
ptr = rsi->inst;
return UINT2NUM(ptr->ft->getPropertyQualifierCount(ptr, to_charptr(property_name), NULL));
}
/**
* call-seq
* new()
*
* Creates an instance from in +object_path+
*
*/
static VALUE new(int argc, VALUE *argv)
{
CIMCStatus status;
CIMCInstance *ptr;
rb_sfcc_object_path *rso;
VALUE object_path;
VALUE client = Qnil;
rb_scan_args(argc, argv, "11", &object_path, &client);
Data_Get_Struct(object_path, rb_sfcc_object_path, rso);
ptr = cimcEnv->ft->newInstance(cimcEnv, rso->op, &status);
if (!status.rc)
return Sfcc_wrap_cim_instance(ptr, client);
sfcc_rb_raise_if_error(status, "Can't create instance");
return Qnil;
}
/**
* call-seq:
* instance.client -> Client
*
* returns the client associated with the instance
*
*/
static VALUE client(VALUE self)
{
rb_sfcc_instance *rsi;
Data_Get_Struct(self, rb_sfcc_instance, rsi);
return rsi->client;
}
VALUE
Sfcc_wrap_cim_instance(CIMCInstance *instance, VALUE client)
{
rb_sfcc_instance *rsi = (rb_sfcc_instance *)malloc(sizeof(rb_sfcc_instance));
if (!rsi)
rb_raise(rb_eNoMemError, "Cannot alloc rb_sfcc_instance");
rsi->inst = instance;
rsi->client = client;
return Data_Wrap_Struct(cSfccCimInstance, mark, dealloc, rsi);
}
VALUE cSfccCimInstance;
void init_cim_instance()
{
VALUE sfcc = rb_define_module("Sfcc");
VALUE cimc = rb_define_module_under(sfcc, "Cim");
/**
* an instance of a CIM class
*/
VALUE klass = rb_define_class_under(cimc, "Instance", rb_cObject);
cSfccCimInstance = klass;
rb_define_singleton_method(klass, "new", new, -1);
rb_define_method(klass, "property", property, 1);
rb_define_method(klass, "each_property", each_property, 0);
rb_define_method(klass, "property_count", property_count, 0);
rb_define_method(klass, "set_property", set_property, 2);
rb_define_method(klass, "object_path", object_path, 0);
rb_define_method(klass, "set_property_filter", set_property_filter, 3);
rb_define_method(klass, "qualifier", qualifier, 1);
rb_define_method(klass, "each_qualifier", each_qualifier, 0);
rb_define_method(klass, "qualifier_count", qualifier_count, 0);
rb_define_method(klass, "property_qualifier", property_qualifier, 2);
rb_define_method(klass, "each_property_qualifier", each_property_qualifier, 1);
rb_define_method(klass, "property_qualifier_count", property_qualifier_count, 1);
rb_define_method(klass, "client", client, 0);
}
| 2.125 | 2 |
2024-11-18T19:35:16.947045+00:00
| 2019-01-07T22:42:44 |
3af42e220f72a25982b71c2a53541a07a90d4fc6
|
{
"blob_id": "3af42e220f72a25982b71c2a53541a07a90d4fc6",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-07T22:42:44",
"content_id": "cacf89f01095460deb6b92145f8467955b5b73d6",
"detected_licenses": [
"MIT"
],
"directory_id": "1847f49b7fee5fa6abe668cf85860d80c83e59b1",
"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": 150432124,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4798,
"license": "MIT",
"license_type": "permissive",
"path": "/Part1_Expressions/utils.c",
"provenance": "stackv2-0054.json.gz:15958",
"repo_name": "rodrigoAMF/compilador-simples",
"revision_date": "2019-01-07T22:42:44",
"revision_id": "4a53b5394e892eefb4b84f3837c8633e04b98069",
"snapshot_id": "35d44033b7b0e0575d79275bcbc40b7754dee572",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/rodrigoAMF/compilador-simples/4a53b5394e892eefb4b84f3837c8633e04b98069/Part1_Expressions/utils.c",
"visit_date": "2020-03-29T22:38:27.646879"
}
|
stackv2
|
/*---------------------------------------------------------
* Estruturas e Rotinas Utilitarias do Compilador
*
* Por Luiz Eduardo da Silva
*--------------------------------------------------------*/
/*---------------------------------------------------------
* Limites das estruturas
*--------------------------------------------------------*/
#define TAM_TSIMB 100 /* Tamanho da tabela de simbolos */
#define TAM_PSEMA 100 /* Tamanho da pilha semantica */
/*---------------------------------------------------------
* Variaveis globais
*--------------------------------------------------------*/
int TOPO_TSIMB = 0; /* TOPO da tabela de simbolos */
int TOPO_PSEMA = 0; /* TOPO da pilha semantica */
int TOPO_PAUX = 0; /* TOPO da pilha auxiliar */
int ROTULO = 0; /* Proximo numero de rotulo */
int CONTA_VARS = 0; /* Numero de variaveis */
int POS_SIMB; /* Pos. na tabela de simbolos */
int aux; /* variavel auxiliar */
int numLinha = 1; /* numero da linha no programa */
char atomo[100]; /* nome de um identif. ou numero */
char expr[100]; /*Vetor aux para guardar a expressao*/
char exprParenteses[100];
char* vetAux; /* vetor para concaTENAR O ( E ) */
/*---------------------------------------------------------
* Rotina geral de tratamento de erro
*--------------------------------------------------------*/
void ERRO (char *msg, ...) {
char formato [255];
va_list arg;
va_start (arg, msg);
sprintf (formato, "\n%d: ", numLinha);
strcat (formato, msg);
strcat (formato, "\n\n");
printf ("\nERRO no programa");
vprintf (formato, arg);
va_end (arg);
exit (1);
}
/*---------------------------------------------------------
* Tabela de Simbolos
*--------------------------------------------------------*/
struct elem_tab_simbolos {
char id[100];
int tipo;
} TSIMB [TAM_TSIMB], elem_tab;
/*---------------------------------------------------------
* Pilha Semantica & Pilha Auxiliar
*--------------------------------------------------------*/
int PSEMA[TAM_PSEMA];
char PAUX[TAM_PSEMA][100];
/*---------------------------------------------------------
* Funcao que BUSCA um simbolo na tabela de simbolos.
* Retorna -1 se o simbolo nao esta' na tabela
* Retorna i, onde i e' o indice do simbolo na tabela
* se o simbolo esta' na tabela
*--------------------------------------------------------*/
int busca_simbolo (char *ident)
{
int i = TOPO_TSIMB-1;
for (;strcmp (TSIMB[i].id, ident) && i >= 0; i--);
return i;
}
/*---------------------------------------------------------
* Funcao que INSERE um simbolo na tabela de simbolos.
* Se ja' existe um simbolo com mesmo nome e mesmo nivel
* uma mensagem de erro e' apresentada e o programa e'
* interrompido.
*--------------------------------------------------------*/
void insere_simbolo (struct elem_tab_simbolos *elem)
{
if (TOPO_TSIMB == TAM_TSIMB) {
ERRO ("OVERFLOW - tabela de simbolos");
}
else {
// Verifico se o simbolo já existe
POS_SIMB = busca_simbolo (elem->id);
// Se já existe sai do programa
if (POS_SIMB != -1) {
ERRO ("Identificador [%s] duplicado", elem->id);
}
// se não existe insere no topo da tabela de simbolos TSIMB, e incrementa o topo da tabela de símbolos
TSIMB [TOPO_TSIMB] = *elem;
TOPO_TSIMB++;
}
}
/*---------------------------------------------------------
* Funcao de insercao de uma variavel na tabela de simbolos
*---------------------------------------------------------*/
// EX: LOGICO a -> *ident = a, tipo = 1
void insere_variavel (char *ident,int tipo) {
strcpy (elem_tab.id, ident);
elem_tab.tipo = tipo;
insere_simbolo (&elem_tab);
}
/*---------------------------------------------------------
* Rotinas para manutencao da PILHA SEMANTICA
*--------------------------------------------------------*/
void empilha (int n) {
// verifica se a pilha está cheia, se estiver retorna um erro
if (TOPO_PSEMA == TAM_PSEMA) {
ERRO ("OVERFLOW - Pilha Semantica");
}
PSEMA[TOPO_PSEMA++] = n;
}
int desempilha () {
// verifica se a pilha está vazia, se estiver retorna um erro
if (TOPO_PSEMA == 0) {
ERRO ("UNDERFLOW - Pilha Semantica");
}
return PSEMA[--TOPO_PSEMA];
}
void empilhaChar(char* termo){
if(TOPO_PAUX == TAM_PSEMA){
ERRO ("OVERFLOW - Pilha Auxiliar");
}
strcpy(PAUX[TOPO_PAUX++], termo);
}
char* desempilhaChar () {
// verifica se a pilha está vazia, se estiver retorna um erro
if (TOPO_PAUX == 0) {
ERRO ("UNDERFLOW - Pilha Auxiliar");
}
return PAUX[--TOPO_PAUX];
}
| 2.828125 | 3 |
2024-11-18T19:35:20.404885+00:00
| 2019-01-04T21:58:29 |
6eb33bd5bfa58cfdf010ff8ddbdc08b7d348c502
|
{
"blob_id": "6eb33bd5bfa58cfdf010ff8ddbdc08b7d348c502",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-04T21:58:29",
"content_id": "689aab1d00986d669e70e06b419dff0a5e273ccd",
"detected_licenses": [
"MIT"
],
"directory_id": "a15f4cb71d235c255d6d82b609ad119b7b25742b",
"extension": "h",
"filename": "compress.h",
"fork_events_count": 2,
"gha_created_at": "2016-06-04T09:22:18",
"gha_event_created_at": "2019-01-04T21:05:11",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 60402767,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2781,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/compress.h",
"provenance": "stackv2-0054.json.gz:20897",
"repo_name": "nibrunie/LZ17",
"revision_date": "2019-01-04T21:58:29",
"revision_id": "526360cfa5d85598e353ecc1e24bb26075af7a6f",
"snapshot_id": "875d820acec96c4f153cf4f9af2f445b381fec34",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nibrunie/LZ17/526360cfa5d85598e353ecc1e24bb26075af7a6f/lib/compress.h",
"visit_date": "2021-01-19T02:32:14.727811"
}
|
stackv2
|
/** \defgroup compress compress
* \brief compression functions using LZ17 algorithms and format
* @{
*/
#include "arith_coding.h"
typedef enum {
/** lz17 compression without arithmetic coding */
LZ17_NO_ENTROPY_CODING = 0,
/** lz17 compression with arithmetic coding */
LZ17_AC_ENTROPY_CODING = 1
} lz17_entropy_mode_t;
/** compression internal state */
typedef struct {
/** entropy mode selected */
lz17_entropy_mode_t entropy_mode;
/** If arithmetic coding is used, store internal coder/decoder state */
ac_state_t* ac_state;
/** amount of currently available room in output buffer */
int avail_out;
/** next byte to be written in output buffer */
char* next_out;
/** number of symbol encoded since last symbol probability table update */
int update_count;
/** number of symbol to encode between two symbol probability table updates */
int update_range;
/** enable clearing of symbol probability table during each update */
int range_clear;
/** amount of input bytes available */
int avail_in;
/** next address to be read in input buffer */
char* next_in;
} lz17_state_t;
/** Initialize compression state
* @param state compression internal state
* @param entropy_mode mode for entropy coding
*/
void lz17_compressInit(lz17_state_t* state, lz17_entropy_mode_t entropy_mode);
/** Try to compress @p avail_in from @p in buffer into @p out without exceeding @p avail_out bytes
* @param zstate internal compression state
* @param out output buffer
* @param avail_out available size in @p out
* @param in input data
* @param avail_in size of input data
* @return positive compressed size on success, otherwise negative error code
*/
int lz17_compressBufferToBuffer(lz17_state_t* zstate, char* out, size_t avail_out, char* in, size_t avail_in);
/** Decompress from a byte buffer into a byte buffer
* @param out output buffer to receive decompress data
* @param avail_out size of available space for decompression in @p out
* @param int input buffer containing compress frame
* @param avail_in size of input data
* @return positive compressed size on success, otherwise negative error code
*/
int lz17_decompressBufferToBuffer(char* out, size_t avail_out, char* in, size_t avail_in);
/** Extract the expanded size as stored in a lz17 buffer, assuming lz17 is a
* complete buffer with lz17 header
* @param in input buffer
* @return expanded size of decompressed @in
*/
int lz17_bufferExtractExpandedSize(char* in);
/** Display the content (lz17 commands) of a compressed stream
* @param in input stream (compressed)
* @param avail_in size of input stream
* @return error code on error, LZ17_OK on success
*/
int lz17_displayCompressedStream(char* in, size_t avail_in);
/** @} */
| 2.671875 | 3 |
2024-11-18T19:35:22.474908+00:00
| 2020-07-16T18:49:32 |
2b30f4f72996176a37350d9668fa992dc10c0fea
|
{
"blob_id": "2b30f4f72996176a37350d9668fa992dc10c0fea",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-16T18:49:32",
"content_id": "d02cfd8eb5659d1f13d61e5032c7ee161dcdfc54",
"detected_licenses": [
"MIT"
],
"directory_id": "d51886c7455eb4d388d5d730e3965b175624eb15",
"extension": "c",
"filename": "forLoopsXAndY.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 278452268,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 344,
"license": "MIT",
"license_type": "permissive",
"path": "/forLoopsXAndY.c",
"provenance": "stackv2-0054.json.gz:21283",
"repo_name": "rodrigowe1988/More-C-Language-Exercices",
"revision_date": "2020-07-16T18:49:32",
"revision_id": "3a5cb8dcb8559b1749e786b5b3bcd716aefbfeaa",
"snapshot_id": "cce8f42fd411082ca632ce4376f265fa466c0da1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/rodrigowe1988/More-C-Language-Exercices/3a5cb8dcb8559b1749e786b5b3bcd716aefbfeaa/forLoopsXAndY.c",
"visit_date": "2022-11-17T16:28:06.969918"
}
|
stackv2
|
//
// main.c
// forLoopsXAndY
//
// Created by Rodrigo Weber on 05/07/20.
// Copyright © 2020 Rodrigo Weber. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
for (int x = 5, y = 10; x < y; x++, y--) {
printf("%d %d\n", x, y);
}
printf("Hello, World!\n");
return 0;
}
| 2.828125 | 3 |
2024-11-18T19:35:22.575667+00:00
| 2020-04-04T13:07:57 |
c2ab4dcea3838cfc2af571bd820e7facfbd6177e
|
{
"blob_id": "c2ab4dcea3838cfc2af571bd820e7facfbd6177e",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-04T13:07:57",
"content_id": "1bf8225a7011b5adc551959d03f8d83527850bc1",
"detected_licenses": [
"MIT"
],
"directory_id": "d8b35ec03c297c106008e67e63cf350a2f5ae07c",
"extension": "c",
"filename": "49_텍스트 파일 분석.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 245755678,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 625,
"license": "MIT",
"license_type": "permissive",
"path": "/49_텍스트 파일 분석.c",
"provenance": "stackv2-0054.json.gz:21412",
"repo_name": "DojunPark/C_Programming",
"revision_date": "2020-04-04T13:07:57",
"revision_id": "c9c71c8a022573200043448e08339439ac01b424",
"snapshot_id": "b44f5da3378404a164fde55ffeb9f441629947e7",
"src_encoding": "UHC",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DojunPark/C_Programming/c9c71c8a022573200043448e08339439ac01b424/49_텍스트 파일 분석.c",
"visit_date": "2021-03-01T05:05:28.719133"
}
|
stackv2
|
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp;
char fname[256];
char buffer[256];
char word[256];
int line = 0;
printf("파일 이름을 입력하세요: ");
scanf("%s", fname);
printf("탐색할 단어를 입력하세요: ");
scanf("%s", word);
if ((fp = fopen(fname, "r")) == NULL)
{
fprintf(stderr, "파일을 열 수 없습니다.\n", fname);
return 0;
}
while(fgets(buffer, 256, fp))
{
line++;
if(strstr(buffer, word))
{
printf("라인 %d : 단어 %s이(가) 발견되었습니다.\n", line, word);
}
}
fclose(fp);
return 0;
}
| 3.171875 | 3 |
2024-11-18T19:35:22.970776+00:00
| 2018-10-22T04:14:27 |
e96cff54494f85f49b43270d9dc7f5e851daa941
|
{
"blob_id": "e96cff54494f85f49b43270d9dc7f5e851daa941",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-22T04:14:27",
"content_id": "545d6dac436e7c64a4634141f58a56c9dbda926f",
"detected_licenses": [
"MIT"
],
"directory_id": "20d0306b253d42538d670e0edcfea122e2fca950",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 139213403,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3909,
"license": "MIT",
"license_type": "permissive",
"path": "/FPGA/software/controller/test.c",
"provenance": "stackv2-0054.json.gz:21798",
"repo_name": "daparker2/blastit",
"revision_date": "2018-10-22T04:14:27",
"revision_id": "adb6c18a2ca762a860b5a34b571274a3c527b459",
"snapshot_id": "979aa699a333094563153b74948a840476c2e703",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/daparker2/blastit/adb6c18a2ca762a860b5a34b571274a3c527b459/FPGA/software/controller/test.c",
"visit_date": "2020-03-21T23:54:54.247029"
}
|
stackv2
|
/*
* test.c
*
* Firmware test panel
*
*/
#include "sys/alt_stdio.h"
#include "system.h"
#include "altera_avalon_pio_regs.h"
#include "controller_system.h"
#include "controller.h"
#include "uart.h"
#include "obd2.h"
#include "display.h"
#include <stdbool.h>
#include <stdio.h>
#ifdef TEST
//#define TEST_OBD2_INIT_LOOP
//#define TEST_UART_ECHO_LINE
//#define TEST_UART_ECHO
#define TEST_DISPLAY
#ifdef TEST_OBD2_INIT_LOOP
void test()
{
obd2_init();
do
{
if (!obd2_update())
{
alt_putstr("Test aborted\n");
break;
}
}
while (obd2_state != Obd2StateCILBr);
alt_printf("OBD2 final state: boost=%x afr=%x oil=%x coolant=%x intake=%x load=%x\n",
(int)display_params.Boost, (int)display_params.Afr, (int)display_params.OilTemp,
(int)display_params.CoolantTemp, (int)display_params.IntakeTemp, (int)display_params.Load);
obd2_shutdown();
}
#endif // TEST_OBD2_INIT_LOOP
#ifdef TEST_UART_ECHO_LINE
#define BUFSZ (1 << 8)
//#define SYNC
void test()
{
dword_t sf = 0;
uart_eol = '\r';
#ifdef SYNC
sf = UART_FLAG_SYNC;
#endif
for (;;)
{
char str[BUFSZ] = {};
int rc;
rc = uart_readline(str, BUFSZ, sf);
if (0 <= rc)
{
rc = uart_sendline(str, sf);
if (0 > rc)
{
alt_printf("uart_sendline failed: %x (%s)\n", rc, uart_etos(rc));
}
}
else if (UartErrorRxBusy != rc)
{
alt_printf("uart_readline failed: %x (%s)\n", rc, uart_etos(rc));
}
}
}
#endif
#ifdef TEST_UART_ECHO
void test()
{
dword_t status = 0;
// Echo test
for (;;)
{
dword_t new_status = uart1_read_status();
char ch;
if (new_status != status)
{
uart1_print_status(new_status);
status = new_status;
}
ch = uart1_rx();
uart1_tx(ch);
}
}
#endif // TEST_UART_ECHO
#ifdef TEST_DISPLAY
void test()
{
int i, j;
bool daylight = false;
byte_t bcd_out[BCD_MAX] = {};
// Dan's test function
warn_set_brightness(WARN_BRIGHTNESS_MAX >> 4);
warn_set_en(true);
status_led_on(STATUS_LED_0 | STATUS_LED_1 | STATUS_LED_2 | STATUS_LED_3);
leds_set_brightness(LedArray1, LEDS_BRIGHTNESS_MAX);
leds_set_brightness(LedArray2, LEDS_BRIGHTNESS_MAX);
for (i = 0; i < LEDS_MAX; ++i)
{
leds_enable_led(LedArray1, i, true);
leds_enable_led(LedArray2, i, true);
}
sseg_set_brightness(SSEG_BRIGHTNESS_MAX);
for (i = 0; i < SSEG_MAX; ++i)
{
sseg_set_bcd(i, SSEG_VAL_EN | SSEG_DP, i);
}
wait_tick(1000);
bcd_convert(1234, bcd_out);
alt_printf("1234 -> %x %x %x %x\n", bcd_out[0], bcd_out[1], bcd_out[2], bcd_out[3]);
bcd_convert(-1234, bcd_out);
alt_printf("-1234 -> -%x %x %x %x\n", bcd_out[0], bcd_out[1], bcd_out[2], bcd_out[3]);
i = 0;
for (;;)
{
bool new_daylight = is_daylight();
if (daylight != new_daylight)
{
daylight = new_daylight;
if (daylight)
{
alt_putstr("daylight\n");
}
else
{
alt_putstr("not daylight\n");
}
}
if (i++ % 2 == 0)
{
status_led_on(STATUS_LED_0 | STATUS_LED_2);
status_led_off(STATUS_LED_1 | STATUS_LED_3);
for (j = 0; j < LEDS_MAX; ++j)
{
leds_enable_led(LedArray1, j, (j % 2) == 0);
leds_enable_led(LedArray2, j, (j % 2) == 0);
}
for (j = 0; j < SSEG_MAX; ++j)
{
sseg_set_bcd(j, SSEG_VAL_EN | SSEG_DP, i);
}
}
else
{
status_led_on(STATUS_LED_1 | STATUS_LED_3);
status_led_off(STATUS_LED_0 | STATUS_LED_2);
for (j = 0; j < LEDS_MAX; ++j)
{
leds_enable_led(LedArray1, j, (j % 2) != 0);
leds_enable_led(LedArray2, j, (j % 2) != 0);
}
for (j = 0; j < SSEG_MAX; ++j)
{
if (j % 2 == 0)
{
sseg_set_bcd(j, SSEG_VAL_EN | SSEG_SIGN, 0);
}
else
{
sseg_set_bcd(j, 0, 0);
}
}
}
wait_tick(250);
}
}
#endif // TEST_DISPLAY
#endif // TEST
| 2.21875 | 2 |
2024-11-18T19:35:23.210040+00:00
| 2015-04-17T17:56:20 |
f7306af7f3a7a3b8d01913493fdc02fcab9d8966
|
{
"blob_id": "f7306af7f3a7a3b8d01913493fdc02fcab9d8966",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-17T17:56:20",
"content_id": "a7d069b339b1980ba51f6252d34da525a8f88ffa",
"detected_licenses": [
"ISC"
],
"directory_id": "66bdc05e3e7e0a2069cbf59a8dad1fdf7a52caef",
"extension": "c",
"filename": "pkgopt.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 7389536,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3660,
"license": "ISC",
"license_type": "permissive",
"path": "/gcc/cmassoc/pkgopt.c",
"provenance": "stackv2-0054.json.gz:22054",
"repo_name": "razzlefratz/MotleyTools",
"revision_date": "2015-04-17T17:56:20",
"revision_id": "3c69c574351ce6f4b7e687c13278d4b6cbb200f3",
"snapshot_id": "5e44f1315baa1be6fe5221916ccc834a96b59ca6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/razzlefratz/MotleyTools/3c69c574351ce6f4b7e687c13278d4b6cbb200f3/gcc/cmassoc/pkgopt.c",
"visit_date": "2020-05-19T05:01:58.992424"
}
|
stackv2
|
/*====================================================================*
*
* pkgopt.c - extract package configuration options from stdin;
*
*. Motley Tools by Charles Maier;
*: Copyright (c) 2001-2006 by Charles Maier Associates Limited;
*; Licensed under the Internet Software Consortium License;
*
*--------------------------------------------------------------------*/
#define _GETOPT_H
/*====================================================================*
* system header files;
*--------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../tools/cmassoc.h"
#include "../files/files.h"
/*====================================================================*
* custom source files;
*--------------------------------------------------------------------*/
#ifndef MAKEFILE
#include "../tools/getoptv.c"
#include "../tools/putoptv.c"
#include "../tools/version.c"
#include "../tools/efreopen.c"
#include "../tools/error.c"
#endif
/*====================================================================*
*
* void func (char const *charset, flag_t flags);
*
* read stdin and write stdout; search for lines starting with two
* spaces then two dashes; output the two dashes and trailing text;
* prefix output lines with a hash and a tab; suffix lines with a
* space and a backslash;
*
*. Motley Tools by Charles Maier;
*: Copyright (c) 2001-2006 by Charles Maier Associates Limited;
*; Licensed under the Internet Software Consortium License;
*
*--------------------------------------------------------------------*/
void func (flag_t flags)
{
signed c;
while ((c = getc (stdin)) != EOF)
{
if (c == ' ')
{
if ((c = getc (stdin)) == ' ')
{
if ((c = getc (stdin)) == '-')
{
if ((c = getc (stdin)) == '-')
{
putc ('#', stdout);
putc ('\t', stdout);
putc ('-', stdout);
putc ('-', stdout);
c = getc (stdin);
while (isalnum (c) || (c == '-'))
{
putc (c, stdout);
c = getc (stdin);
}
if (c == '=')
{
putc (c, stdout);
c = getc (stdin);
if (c == '\"')
{
do
{
putc (c, stdout);
c = getc (stdin);
}
while ((c != EOF) && (c != '\"'));
putc ('\"', stdout);
c = getc (stdin);
}
else while (! isspace (c))
{
putc (c, stdout);
c = getc (stdin);
}
}
else while (! isspace (c))
{
putc (c, stdout);
c = getc (stdin);
}
putc (' ', stdout);
putc ('\\', stdout);
putc ('\n', stdout);
}
}
}
}
while (nobreak (c))
{
c = getc (stdin);
}
}
return;
}
/*====================================================================*
* main program;
*--------------------------------------------------------------------*/
int main (int argc, char const * argv [])
{
static char const * optv [] =
{
"extract package configuration options from stdin",
PUTOPTV_S_FUNNEL,
"",
(char const *) (0)
};
flag_t flags = (flag_t) (0);
signed c;
while (~ (c = getoptv (argc, argv, optv)))
{
switch (c)
{
default:
break;
}
}
argc -= optind;
argv += optind;
if (! argc)
{
func (flags);
}
while ((argc) && (* argv))
{
if (efreopen (* argv, "rb", stdin))
{
func (flags);
}
argc--;
argv++;
}
exit (0);
}
| 2.390625 | 2 |
2024-11-18T19:35:23.587098+00:00
| 2022-04-02T09:37:52 |
918a0b9ae49ea722f4dea6bd138023a2dc1a792f
|
{
"blob_id": "918a0b9ae49ea722f4dea6bd138023a2dc1a792f",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-02T09:37:52",
"content_id": "3d22da4bafb6d571dd10c188a2493d8562d04545",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7a20b3db1a185ecdf12ad86f38edaa03742abd7b",
"extension": "h",
"filename": "SkBitmapProcState_matrix.h",
"fork_events_count": 26,
"gha_created_at": "2019-08-18T14:24:21",
"gha_event_created_at": "2022-04-02T09:37:52",
"gha_language": "C++",
"gha_license_id": "BSD-3-Clause",
"github_id": 203015081,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2841,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/core/SkBitmapProcState_matrix.h",
"provenance": "stackv2-0054.json.gz:22182",
"repo_name": "revery-ui/esy-skia",
"revision_date": "2022-04-02T09:37:52",
"revision_id": "29349b9279ed24a73ec41acd7082caea9bd8c04e",
"snapshot_id": "7ef96ceeca94d001264684b7dc1ac24db0381ad4",
"src_encoding": "UTF-8",
"star_events_count": 24,
"url": "https://raw.githubusercontent.com/revery-ui/esy-skia/29349b9279ed24a73ec41acd7082caea9bd8c04e/src/core/SkBitmapProcState_matrix.h",
"visit_date": "2022-05-29T17:50:23.722723"
}
|
stackv2
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkMath.h"
#include "SkMathPriv.h"
#define SCALE_FILTER_NAME MAKENAME(_filter_scale)
#define PACK_FILTER_X_NAME MAKENAME(_pack_filter_x)
#define PACK_FILTER_Y_NAME MAKENAME(_pack_filter_y)
#ifndef PREAMBLE
#define PREAMBLE(state)
#define PREAMBLE_PARAM_X
#define PREAMBLE_PARAM_Y
#define PREAMBLE_ARG_X
#define PREAMBLE_ARG_Y
#endif
// declare functions externally to suppress warnings.
void SCALE_FILTER_NAME(const SkBitmapProcState& s,
uint32_t xy[], int count, int x, int y);
static inline uint32_t PACK_FILTER_Y_NAME(SkFixed f, unsigned max,
SkFixed one PREAMBLE_PARAM_Y) {
unsigned i = TILEY_PROCF(f, max);
i = (i << 4) | EXTRACT_LOW_BITS(f, max);
return (i << 14) | (TILEY_PROCF((f + one), max));
}
static inline uint32_t PACK_FILTER_X_NAME(SkFixed f, unsigned max,
SkFixed one PREAMBLE_PARAM_X) {
unsigned i = TILEX_PROCF(f, max);
i = (i << 4) | EXTRACT_LOW_BITS(f, max);
return (i << 14) | (TILEX_PROCF((f + one), max));
}
void SCALE_FILTER_NAME(const SkBitmapProcState& s,
uint32_t xy[], int count, int x, int y) {
SkASSERT((s.fInvType & ~(SkMatrix::kTranslate_Mask |
SkMatrix::kScale_Mask)) == 0);
SkASSERT(s.fInvKy == 0);
PREAMBLE(s);
const unsigned maxX = s.fPixmap.width() - 1;
const SkFixed one = s.fFilterOneX;
const SkFractionalInt dx = s.fInvSxFractionalInt;
SkFractionalInt fx;
{
const SkBitmapProcStateAutoMapper mapper(s, x, y);
const SkFixed fy = mapper.fixedY();
const unsigned maxY = s.fPixmap.height() - 1;
// compute our two Y values up front
*xy++ = PACK_FILTER_Y_NAME(fy, maxY, s.fFilterOneY PREAMBLE_ARG_Y);
// now initialize fx
fx = mapper.fractionalIntX();
}
#ifdef CHECK_FOR_DECAL
const SkFixed fixedFx = SkFractionalIntToFixed(fx);
const SkFixed fixedDx = SkFractionalIntToFixed(dx);
if (can_truncate_to_fixed_for_decal(fixedFx, fixedDx, count, maxX)) {
decal_filter_scale(xy, fixedFx, fixedDx, count);
} else
#endif
{
do {
SkFixed fixedFx = SkFractionalIntToFixed(fx);
*xy++ = PACK_FILTER_X_NAME(fixedFx, maxX, one PREAMBLE_ARG_X);
fx += dx;
} while (--count != 0);
}
}
#undef MAKENAME
#undef TILEX_PROCF
#undef TILEY_PROCF
#ifdef CHECK_FOR_DECAL
#undef CHECK_FOR_DECAL
#endif
#undef SCALE_FILTER_NAME
#undef PREAMBLE
#undef PREAMBLE_PARAM_X
#undef PREAMBLE_PARAM_Y
#undef PREAMBLE_ARG_X
#undef PREAMBLE_ARG_Y
#undef EXTRACT_LOW_BITS
| 2.015625 | 2 |
2024-11-18T19:35:23.975036+00:00
| 2016-03-02T09:59:43 |
96c5ef605a8e7ead0f57962498e4ec45b71ce05a
|
{
"blob_id": "96c5ef605a8e7ead0f57962498e4ec45b71ce05a",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-02T09:59:43",
"content_id": "00ff8e1004fbd2d97bf9e6f797ced166c07e25e8",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "4be5adaabba36685985aa09914d8dd3b6ebd37d7",
"extension": "c",
"filename": "TimeDaemon.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 52004404,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2328,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/programming/c/ProcThreads/Aufgabe_4.11/TimeDaemon.c",
"provenance": "stackv2-0054.json.gz:22438",
"repo_name": "owalch/oliver",
"revision_date": "2016-03-02T09:59:43",
"revision_id": "faf6cc6381085d5b48e828cebdc476c21852b404",
"snapshot_id": "78f681cc8cebb7782889876e697b3fe5dd6b3df9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/owalch/oliver/faf6cc6381085d5b48e828cebdc476c21852b404/programming/c/ProcThreads/Aufgabe_4.11/TimeDaemon.c",
"visit_date": "2021-01-10T06:04:19.639988"
}
|
stackv2
|
/******************************************************************************
* File: TimeDaemon.cc
* Aufgabe: the daemon code
* Autor: M. Thaler, ZHW
* Datum: Februar 2000 (Rev. 8/2004, Rev. 3/2008)
* History: 29/03/2008 M. Thaler: single connection socket server
******************************************************************************/
//*****************************************************************************
// system includes
//*****************************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
#include <netdb.h>
#include <time.h>
//*****************************************************************************
// local includes
//*****************************************************************************
#include "TimeDaemon.h"
#include "TimeDaemonDefs.h"
#include "IPsockCom.h"
//*****************************************************************************
// Function: TimeDeamon
// Parameter: data: expects here pointer to string
//*****************************************************************************
void TimeDaemon(void *data) {
TimeData tData;
char buffer[COM_BUF_SIZE];
struct tm MyTime;
time_t ActualTime;
int sfd, cfd;
printf("%s\n", (char *)data);
// start server
sfd = StartTimeServer(TIME_PORT);
if (sfd < 0) {
perror("could not start socket server");
exit(-1);
}
while (1) {
cfd = WaitForClient(sfd, buffer);
if ((strcmp(buffer, REQUEST_STRING) == 0) && (cfd >= 0)) {
time(&ActualTime);
MyTime = *localtime(&ActualTime);
tData.hours = MyTime.tm_hour;
tData.minutes = MyTime.tm_min;
tData.seconds = MyTime.tm_sec;
tData.day = MyTime.tm_mday;
tData.month = MyTime.tm_mon + 1;
tData.year = MyTime.tm_year + 1900;
write(cfd, (char *)(&tData), sizeof(tData));
}
}
// if we should somehow come here (how ?)
close(sfd);
exit(0);
}
//*****************************************************************************
| 2.265625 | 2 |
2024-11-18T19:35:24.215173+00:00
| 2020-11-21T00:15:16 |
8ad358bc5aa424bb370f4694387797d853460d00
|
{
"blob_id": "8ad358bc5aa424bb370f4694387797d853460d00",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-21T00:15:16",
"content_id": "a44392c6ba53b85c3abbd3d24e81b727f3639acc",
"detected_licenses": [
"MIT"
],
"directory_id": "dd45626ee5c4150b0b2fafc102a20b485477278d",
"extension": "c",
"filename": "sprite_position.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": 10393,
"license": "MIT",
"license_type": "permissive",
"path": "/sprites/sprite_position.c",
"provenance": "stackv2-0054.json.gz:22823",
"repo_name": "nsauzede/super-miyamoto-sprint",
"revision_date": "2020-11-21T00:15:16",
"revision_id": "a2d446397a9e3d9db21f2a6d3ccd093f78da047d",
"snapshot_id": "abc0a33ac96ad8aabca4212c09fb83fa2cd995e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nsauzede/super-miyamoto-sprint/a2d446397a9e3d9db21f2a6d3ccd093f78da047d/sprites/sprite_position.c",
"visit_date": "2023-01-14T16:42:56.014193"
}
|
stackv2
|
#include "sprite_position.h"
#include "math_util.h"
#include "assert.h"
#include "sprite_actor.h"
#include "sprite_block_interaction.h"
#include "vdp.h"
#include "camera.h"
#include "sound_effects.h"
#include "hero.h"
const int32_t Q_1 = 0x10000;
static bool onscreen(int32_t screen_x,
int32_t screen_y,
int32_t padding_x,
int32_t padding_top,
int32_t padding_bottom);
SpriteDirection sa_direction_flipped(SpriteDirection direction) {
return (direction == LEFT ? RIGHT : LEFT);
}
void sa_apply_velocity(const SpriteVelocity *velocity, SpritePosition *position) {
position->x_full += velocity->x;
position->y_full += velocity->y;
}
// Returns true if grounded
bool sa_apply_velocity_with_gravity(SpriteActor *actor, const SpriteBoundingBox *box) {
// Based on values for Hero
const int32_t gravity_accel = Q_1 / 4;
const int32_t fall_speed_max = 5 * Q_1;
// Only apply gravity if sprite isn't on a platform
bool grounded = false;
SpriteActorHandle platform_handle = actor->ridden_sprite_handle;
if (!sa_handle_live(platform_handle)) {
actor->velocity.y += gravity_accel;
actor->velocity.y = MIN(actor->velocity.y, fall_speed_max);
} else {
const PlatformSprite *platform = &sa_get(platform_handle)->platform;
sa_apply_offset(&platform->frame_offset, &actor->position);
grounded = true;
}
sa_apply_velocity(&actor->velocity, &actor->position);
// Inside-bottom check (based on hero)
SpriteBlockInteractionResult bottom_result;
if (sa_inside_block_bottom(&actor->position, box, &bottom_result)) {
actor->position.y += bottom_result.overlap;
if (actor->velocity.y < 0) {
actor->velocity.y = 0;
}
}
// Grounding check since we're also applying gravity here
if (sa_block_ground_test(&actor->position, &actor->velocity, box, NULL)) {
// (This is based on Hero, could potentially reuse this)
int32_t displacement = actor->position.y & 15;
actor->position.y = actor->position.y & ~15;
actor->position.y_fraction = 0;
sa_grounded_update(actor, displacement);
grounded = true;
}
return grounded;
}
void sa_grounded_update(SpriteActor *actor, int32_t displacement) {
// An inert carryable sprite has a default bounce when it hits the ground
bool should_bounce = actor->can_be_carried && (actor->velocity.y > Q_1);
if (should_bounce) {
// The sprite may have "entered the ground" so compensate for this
actor->position.y -= displacement;
actor->velocity.y = -actor->velocity.y / 4;
} else {
actor->velocity.y = 0;
}
// Carryable sprites also maintain horizontal inertia unless they're on ground
// (optional extra is a little smoke effect at the base when sliding)
if (actor->can_be_carried) {
const int32_t horizontal_decel = Q_1 / 2;
sa_horizontal_deceleration(&actor->velocity, horizontal_decel);
}
}
void sa_horizontal_deceleration(SpriteVelocity *velocity, int32_t decel) {
if (!velocity->x) {
return;
}
int32_t directional_decel = (velocity->x > 0) ? decel : -decel;
velocity->x -= directional_decel;
if (SIGN(directional_decel) != SIGN(velocity->x)) {
velocity->x = 0;
}
}
void sa_horizontal_acceleration(SpriteVelocity *velocity, SpriteDirection direction, int32_t accel, int32_t max_speed) {
int32_t directional_accel = sa_velocity_from_speed(accel, direction);
velocity->x += directional_accel;
if (ABS(velocity->x) >= max_speed) {
velocity->x = sa_velocity_from_speed(max_speed, direction);
}
}
void sa_apply_horizontal_block_interaction_updates(SpriteActor *actor,
const SpriteBoundingBox *box)
{
SpriteBlockInteractionResult left_result, right_result;
sa_inside_block_horizontal(&actor->position, box, &left_result, &right_result);
bool mirror_x_velocity = false;
if (left_result.solid) {
actor->position.x -= left_result.overlap;
actor->direction = LEFT;
mirror_x_velocity = (actor->velocity.x > 0);
} else if (right_result.solid) {
actor->position.x += right_result.overlap;
actor->direction = RIGHT;
mirror_x_velocity = (actor->velocity.x < 0);
}
if (actor->invert_velocity_upon_hitting_wall && mirror_x_velocity) {
actor->velocity.x = -actor->velocity.x;
if (actor->thud_sound_upon_hitting_wall) {
se_thud();
}
}
}
bool sa_within_live_bounds(const SpritePosition *position, const Camera *camera) {
const int32_t live_bounds = 96;
// Allowed distance off bottom of screen
const int32_t padding_bottom = 16;
// Allowed distance off top of screen (i.e. item that is kicked up)
const int32_t padding_top = 300;
int32_t x = position->x - camera->scroll.x;
int32_t y = position->y - camera->scroll.y;
return onscreen(x, y, live_bounds, padding_top, padding_bottom);
}
bool sa_remove_if_outside_bounds(SpriteActor *actor, const Camera *camera) {
bool in_bounds = sa_within_live_bounds(&actor->position, camera);
if (!in_bounds) {
sa_free(actor);
}
return in_bounds;
}
// Returns true is a default movement was done
// The actor shouldn't try its own movement if so
bool sa_perform_default_movement(SpriteActor *actor) {
if (!(actor->killed && actor->falls_off_when_killed)) {
return false;
}
// Sprite is dead and falling off the screen
const int32_t max_fall_speed = Q_1 * 4;
const int32_t fall_accel = Q_1 / 8;
actor->velocity.x = 0;
actor->velocity.y = MIN(max_fall_speed, actor->velocity.y + fall_accel);
sa_apply_velocity(&actor->velocity, &actor->position);
return true;
}
bool sa_perform_carryable_movement(SpriteActor *actor, const Hero *hero) {
// Is this particular hero carrying this sprite?
if (!hero_carrying_sprite(hero, actor->handle)) {
return false;
}
// ..if so, its own flag should be set by the time we get here
assert(actor->carried);
// Position "in hero's hands", wherever that happens to be
HeroSpriteCarryContext context = hero_sprite_carry_context(hero);
actor->position = context.position;
actor->direction = context.direction;
actor->velocity.x = 0;
actor->velocity.y = 0;
return true;
}
void sa_bounding_box_abs(const SpritePosition *position,
const SpriteBoundingBox *box,
SpriteBoundingBoxAbs *abs)
{
abs->top = position->y + box->offset.y;
abs->bottom = position->y + box->offset.y + box->size.height;
abs->left = position->x + box->offset.x;
abs->right = position->x + box->offset.x + box->size.width;
}
void sa_bounding_box_overlap(const SpriteBoundingBoxAbs *a1,
const SpriteBoundingBoxAbs *a2,
SpriteBoundingBoxAbs *result)
{
result->top = MAX(a1->top, a2->top);
result->bottom = MIN(a1->bottom, a2->bottom);
result->left = MAX(a1->left, a2->left);
result->right = MIN(a1->right, a2->right);
}
void sa_bounding_box_center(const SpriteBoundingBoxAbs *box_abs, SpritePosition *center) {
center->x = box_abs->left + (box_abs->right - box_abs->left) / 2;
center->y = box_abs->top + (box_abs->bottom - box_abs->top) / 2;
}
// Updates the sprite (or Hero) assuming that it overlaps with a rideable platform
// It may or may not start riding the platform based on other checks
// This function should only be called if the sprites are actually colliding
bool sa_platform_ride_check(SpriteActor *platform,
SpriteVelocity *velocity,
SpritePosition *position,
SpriteActorHandle *rider_handle)
{
bool should_ride = (velocity->y >= 0);
// Sprite's feet must be within this number of pixels from the top of the platform
// The faster sprites can fall onto platform, the higher this needs to be..
// ..or else sprites will just fall through the platform
const int16_t floor_padding = 7;
int16_t platform_height = platform->bounding_box.size.height;
should_ride &= ((position->y + platform_height) - platform->position.y - floor_padding) < 0;
if (should_ride) {
*rider_handle = platform->handle;
// Fix Y position to the platform
// Note velocity->y is not set here, it is left to the caller
// This makes bounce effects etc. less complicated
position->y = platform->position.y - platform_height + 1;
} else if (sa_handle_equal(*rider_handle, platform->handle)) {
sa_platform_dismount(platform, velocity, rider_handle);
}
return should_ride;
}
void sa_platform_dismount(const SpriteActor *platform, SpriteVelocity *velocity, SpriteActorHandle *rider_handle) {
// This applies the platforrm velocity when rider dismounts
// May or may not take effect depending on the sprite
velocity->x += platform->velocity.x;
sa_handle_clear(rider_handle);
}
void sa_apply_offset(const SpriteOffset *offset, SpritePosition *position) {
position->x += offset->x;
position->y += offset->y;
}
void sa_apply_offset_flip(const SpriteOffset *offset, SpritePosition *position, SpriteDirection direction) {
position->x += (direction == LEFT ? offset->x : -offset->x);
position->y += offset->y;
}
static bool onscreen(int32_t screen_x,
int32_t screen_y,
int32_t padding_x,
int32_t padding_top,
int32_t padding_bottom)
{
return
(screen_x + padding_x >= 0) &&
(screen_x - padding_x < SCREEN_ACTIVE_WIDTH) &&
(screen_y + padding_top >= 0) &&
(screen_y - padding_bottom < SCREEN_ACTIVE_HEIGHT);
}
int32_t sa_velocity_from_speed(int32_t speed, SpriteDirection direction) {
return (direction == LEFT ? -speed : speed);
}
SpriteDirection sa_direction_facing_hero(const SpriteActor *actor, const Hero *hero) {
return (actor->position.x < hero->position.x ? RIGHT : LEFT);
}
bool sa_above_hero(const SpriteActor *actor, const Hero *hero) {
return (actor->position.y < hero->position.y - 24);
}
| 2.40625 | 2 |
2024-11-18T19:35:24.281714+00:00
| 2017-03-22T13:38:56 |
615f03df148e3b7913cc2d804078794fab4c5193
|
{
"blob_id": "615f03df148e3b7913cc2d804078794fab4c5193",
"branch_name": "refs/heads/master",
"committer_date": "2017-03-22T13:38:56",
"content_id": "ddaa1674f689fb83663e93e2ad671e1b066abd58",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8e5a001dd2463fe16b0396881a540fd27821437a",
"extension": "c",
"filename": "hello.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": 770,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/H5/hello.c",
"provenance": "stackv2-0054.json.gz:22952",
"repo_name": "ptd29/CS283",
"revision_date": "2017-03-22T13:38:56",
"revision_id": "4e4bc5b9fb3c024d68a0e230ef5ac0156e963454",
"snapshot_id": "518c4b75e3d7b24697bd5ac82b910806ec540df5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ptd29/CS283/4e4bc5b9fb3c024d68a0e230ef5ac0156e963454/H5/hello.c",
"visit_date": "2021-04-27T03:19:24.040003"
}
|
stackv2
|
#include "csapp.h"
void *thread(void *vargp);
int main(int argc, char* argv[])
{
if(argc != 2)
{
printf("Invalid number of parameters\n");
return -1;
}
int num_threads = atoi(argv[1]);
int i,rv;
pthread_t tid[num_threads];
printf("Creating threads\n");
for(i=0; i<num_threads; i++)
{
Pthread_create(&tid[i], NULL, thread, NULL);
if(rv)
printf("Error creating threads %d\n",i);
}
printf("Joining threads\n");
for(i=0;i<num_threads; i++)
{
Pthread_join(tid[i], NULL);
if(rv)
printf("Error joinging threads %d\n",i);
}
exit(0);
}
void *thread(void *vargp) /* Thread routine */
{
printf("Hello, world!\n");
return NULL;
}
| 3.25 | 3 |
2024-11-18T19:35:25.151510+00:00
| 2020-06-08T20:44:54 |
dafd58d3fab2441607353ff59c961b54bca1a0bb
|
{
"blob_id": "dafd58d3fab2441607353ff59c961b54bca1a0bb",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-08T20:44:54",
"content_id": "afb671e957143f91e5e8bd6233e1bed027453c5a",
"detected_licenses": [
"MIT"
],
"directory_id": "b2c739168b358d9b9ae24f83493c351fb4578009",
"extension": "c",
"filename": "vertexbuffer.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": 1065,
"license": "MIT",
"license_type": "permissive",
"path": "/src/datatypes/vertexbuffer.c",
"provenance": "stackv2-0054.json.gz:23209",
"repo_name": "mbrukman/c-ray",
"revision_date": "2020-06-08T20:44:54",
"revision_id": "1d1e1643fefa07a61fb5bdb3ec30627eb7cfce36",
"snapshot_id": "33a8b822b21a8de4753e74dbe93cb55b54578e36",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mbrukman/c-ray/1d1e1643fefa07a61fb5bdb3ec30627eb7cfce36/src/datatypes/vertexbuffer.c",
"visit_date": "2022-10-14T00:55:02.165955"
}
|
stackv2
|
//
// vertexbuffer.h
// C-ray
//
// Created by Valtteri Koskivuori on 02/04/2019.
// Copyright © 2015-2020 Valtteri Koskivuori. All rights reserved.
//
//Main vertex arrays
/*
Note:
C-Ray stores all vectors and polygons in shared arrays, and uses data structures
to keep track of them.
*/
#include "../includes.h"
#include "poly.h"
#include "vector.h"
#include "../utils/assert.h"
struct vector *vertexArray;
int vertexCount;
struct vector *normalArray;
int normalCount;
struct coord *textureArray;
int textureCount;
void allocVertexBuffer() {
ASSERT(!vertexArray);
vertexArray = calloc(1, sizeof(*vertexArray));
normalArray = calloc(1, sizeof(*normalArray));
textureArray = calloc(1, sizeof(*textureArray));
polygonArray = calloc(1, sizeof(*polygonArray));
vertexCount = 0;
normalCount = 0;
textureCount = 0;
polyCount = 0;
}
void destroyVertexBuffer() {
if (vertexArray) {
free(vertexArray);
}
if (normalArray) {
free(normalArray);
}
if (textureArray) {
free(textureArray);
}
if (polygonArray) {
free(polygonArray);
}
}
| 2.234375 | 2 |
2024-11-18T19:35:26.505130+00:00
| 2018-07-03T16:12:12 |
252262f34e7778cc004861059d414d9661df0f8e
|
{
"blob_id": "252262f34e7778cc004861059d414d9661df0f8e",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-03T16:12:12",
"content_id": "41e4110be413c3609b5712bf108b19a91de5ed03",
"detected_licenses": [
"BSD-3-Clause",
"NCSA",
"MIT"
],
"directory_id": "144fdeec6dec6ed22e702f8902f94d77ba0d6059",
"extension": "c",
"filename": "__builtin_isgreaterequal.c",
"fork_events_count": 1,
"gha_created_at": "2016-09-01T07:06:28",
"gha_event_created_at": "2016-09-01T07:06:28",
"gha_language": null,
"gha_license_id": null,
"github_id": 67107046,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 498,
"license": "BSD-3-Clause,NCSA,MIT",
"license_type": "permissive",
"path": "/tests/com.oracle.truffle.llvm.tests.sulong/c/builtin_gcc/__builtin_isgreaterequal.c",
"provenance": "stackv2-0054.json.gz:23467",
"repo_name": "pointhi/sulong",
"revision_date": "2018-07-03T16:12:12",
"revision_id": "5446c54d360f486f9e97590af5f466cf1f5cd1f7",
"snapshot_id": "cb9dc61f54a113e988911f1e3654d6e5792c2859",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/pointhi/sulong/5446c54d360f486f9e97590af5f466cf1f5cd1f7/tests/com.oracle.truffle.llvm.tests.sulong/c/builtin_gcc/__builtin_isgreaterequal.c",
"visit_date": "2021-01-16T22:17:36.966183"
}
|
stackv2
|
int main() {
volatile float pos1 = 1.;
volatile float neg1 = -1.;
volatile float posZero = 0.;
volatile float negZero = -0.;
if (__builtin_isgreaterequal(neg1, neg1) == 0) {
return 1;
}
if (__builtin_isgreaterequal(posZero, negZero) == 0) {
return 1;
}
if (__builtin_isgreaterequal(pos1, pos1) == 0) {
return 1;
}
if (__builtin_isgreaterequal(neg1, pos1) != 0) {
return 1;
}
if (__builtin_isgreaterequal(pos1, neg1) == 0) {
return 1;
}
return 0;
}
| 2.484375 | 2 |
2024-11-18T19:35:27.968178+00:00
| 2023-07-08T03:47:15 |
d93532eef1cc837585ed19fb1dc290b32e30ebbb
|
{
"blob_id": "d93532eef1cc837585ed19fb1dc290b32e30ebbb",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-08T03:47:15",
"content_id": "c1205e267d23c2b330befb016532cb04ffaa92ba",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "982388ac2f7daea571aa13f067881cb27076b8ae",
"extension": "c",
"filename": "timer_sample.c",
"fork_events_count": 64,
"gha_created_at": "2018-08-21T08:17:13",
"gha_event_created_at": "2023-07-08T03:47:16",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 145530497,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1617,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/zh/timer_sample.c",
"provenance": "stackv2-0054.json.gz:23596",
"repo_name": "RT-Thread-packages/kernel-sample",
"revision_date": "2023-07-08T03:47:15",
"revision_id": "d7af6fafa03c071f3b8673c4cd35775c1b0a2179",
"snapshot_id": "eae94662030a218b1ae87fc1cf33dacb45e4b3bc",
"src_encoding": "UTF-8",
"star_events_count": 75,
"url": "https://raw.githubusercontent.com/RT-Thread-packages/kernel-sample/d7af6fafa03c071f3b8673c4cd35775c1b0a2179/zh/timer_sample.c",
"visit_date": "2023-07-23T05:50:20.401381"
}
|
stackv2
|
/*
* Copyright (c) 2006-2022, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018-08-24 yangjie the first version
*/
/*
* 程序清单:定时器例程
*
* 这个例程会创建两个动态定时器,一个是单次定时,一个是周期性定时
* 并让周期定时器运行一段时间后停止运行
*/
#include <rtthread.h>
/* 定时器的控制块 */
static rt_timer_t timer1;
static rt_timer_t timer2;
static int cnt = 0;
/* 定时器1超时函数 */
static void timeout1(void *parameter)
{
rt_kprintf("periodic timer is timeout %d\n", cnt);
/* 运行第10次,停止周期定时器 */
if (cnt++ >= 9)
{
rt_timer_stop(timer1);
rt_kprintf("periodic timer was stopped! \n");
}
}
/* 定时器2超时函数 */
static void timeout2(void *parameter)
{
rt_kprintf("one shot timer is timeout\n");
}
int timer_sample(void)
{
/* 创建定时器1 周期定时器 */
timer1 = rt_timer_create("timer1", timeout1,
RT_NULL, 10,
RT_TIMER_FLAG_PERIODIC);
/* 启动定时器1 */
if (timer1 != RT_NULL)
rt_timer_start(timer1);
/* 创建定时器2 单次定时器 */
timer2 = rt_timer_create("timer2", timeout2,
RT_NULL, 30,
RT_TIMER_FLAG_ONE_SHOT);
/* 启动定时器2 */
if (timer2 != RT_NULL)
rt_timer_start(timer2);
return 0;
}
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(timer_sample, timer sample);
| 2.65625 | 3 |
2024-11-18T19:35:28.288632+00:00
| 2023-08-13T07:00:15 |
355b754a1da4c8e9c26e56844f645baa0832d5b4
|
{
"blob_id": "355b754a1da4c8e9c26e56844f645baa0832d5b4",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-13T07:00:15",
"content_id": "d8962da9e1fa33bf9eaf55c5d0e8421aed3ca05a",
"detected_licenses": [
"MIT"
],
"directory_id": "2266eb133fc3121daf0aa7f4560626b46b94afe0",
"extension": "c",
"filename": "passwd.c",
"fork_events_count": 49,
"gha_created_at": "2017-11-28T03:05:14",
"gha_event_created_at": "2023-02-01T03:42:14",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 112278568,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9183,
"license": "MIT",
"license_type": "permissive",
"path": "/cmds/usr/passwd.c",
"provenance": "stackv2-0054.json.gz:23724",
"repo_name": "oiuv/mud",
"revision_date": "2023-08-13T07:00:15",
"revision_id": "e9ff076724472256b9b4bd88c148d6bf71dc3c02",
"snapshot_id": "6fbabebc7b784279fdfae06d164f5aecaa44ad90",
"src_encoding": "UTF-8",
"star_events_count": 99,
"url": "https://raw.githubusercontent.com/oiuv/mud/e9ff076724472256b9b4bd88c148d6bf71dc3c02/cmds/usr/passwd.c",
"visit_date": "2023-08-18T20:18:37.848801"
}
|
stackv2
|
// passwd.c
#include <getconfig.h>
#include <ansi.h>
inherit F_CLEAN_UP;
int main(object me, string arg)
{
object ob;
if (me != this_player(1)) return 0;
if (arg == "?")
{
write("特殊功能:SHUTDOWN、ADMIN。\n");
return 1;
}
if (stringp(arg))
{
if (! SECURITY_D->valid_grant(me, "(admin)"))
{
write("你没有权限修改别人的口令。\n");
return 1;
}
if (wiz_level(me) < wiz_level(arg))
{
write("你没有权限修改这个人的口令。\n");
return 1;
}
seteuid(getuid());
ob = find_player(arg);
if (! ob)
{
ob = new(LOGIN_OB);
ob->set("id", arg);
if (! ob->restore())
{
destruct(ob);
return notify_fail("没有这个玩家。\n");
}
ob->set_temp("create_temp", 1);
}
else
{
ob = ob->query_temp("link_ob");
while (ob && ob->is_character())
ob = ob->query_temp("link_ob");
if (! ob)
{
ob = new(LOGIN_OB);
ob->set("id", arg);
if (! ob->restore())
{
destruct(ob);
return notify_fail("这个人物缺少连接信息,请重新LOGIN。\n");
}
ob->set_temp("create_temp", 1);
}
}
write("请输入(" + ob->query("id") + ")的新管理密码:");
input_to("get_new_ad_pass", 1, ob);
return 1;
}
ob = me->query_temp("link_ob");
if (! ob)
return notify_fail("你的人物缺少连接信息,请重新LOGIN。\n");
while (ob && ob->is_character()) ob = ob->query_temp("link_ob");
write("为了安全起见,请先输入您管理密码:");
input_to("get_old_pass", 1, ob);
return 1;
}
private void get_old_pass(string pass, object ob)
{
string old_pass;
if (! objectp(ob))
{
write("无法找到连接对象,此次操作中止了。\n");
return;
}
write("\n");
old_pass = ob->query("ad_password");
if (! stringp(old_pass) || (crypt(pass, old_pass) != old_pass && oldcrypt(pass, old_pass) != old_pass))
{
write(HIR "密码错误!请注意:你需要输入的是管理密码。\n" NOR);
return;
}
write("请选择你下一步操作:\n"
"1. 修改管理密码\n"
"2. 修改普通密码\n"
"3. 不修改。\n"
"你选择(如果你不方便输入数字,可以输入select1、select2):");
input_to("select_fun", ob);
}
private void select_fun(string fun, object ob)
{
if (! objectp(ob))
{
write("无法找到连接对象,此次操作中止了。\n");
return;
}
switch (fun)
{
case "1":
case "select1":
write("请你输入新的管理密码:");
input_to("get_new_ad_pass", 1, ob);
return;
case "2":
case "select2":
write("请你输入新的普通密码:");
input_to("get_new_pass", 1, ob);
return;
case "":
case "3":
write("操作完毕。\n");
return;
default:
write("没有这项功能。\n");
return;
}
}
string trans_char(int c)
{
return sprintf("%c ", c);
}
private void get_new_pass(string pass, object ob)
{
string old_pass;
if (! objectp(ob))
{
write("无法找到连接对象,此次操作中止了。\n");
return;
}
if (pass == "")
{
write("操作取消了。\n");
return;
}
if (strlen(pass) < 3)
{
write("对不起,你的普通密码长度必须大于三位,请重新输入:");
input_to("get_new_pass", 1, ob);
return;
}
old_pass = ob->query("ad_password");
if (stringp(old_pass) && crypt(pass, old_pass) == old_pass)
{
write(HIR "\n为了安全起见,普通密码和管理密码不能一样。\n\n" NOR);
write("请重新输入你的普通密码:");
input_to("get_new_pass", 1, ob);
return;
}
write("\n请再输入一次新的普通密码:");
input_to("confirm_new_pass", 1, ob, crypt(pass, 0));
}
private void confirm_new_pass(string pass, object ob, string new_pass)
{
object me;
if (! objectp(ob))
{
write("无法找到连接对象,此次操作中止了。\n");
return;
}
write("\n");
if (crypt(pass, new_pass) != new_pass)
{
write("对不起,您两次输入的并不相同,请重新输入你的普通密码:");
input_to("get_new_pass", 1, ob);
return;
}
seteuid(getuid());
if (! ob->set("password", new_pass))
{
write("普通密码变更失败!\n");
return;
}
ob->save();
me = this_player();
log_file("static/passwd", sprintf("%s %s's normal passwd changed by %s(%s)\n",
log_time(),
ob->query("id"),
geteuid(me),
interactive(me) ? query_ip_name(me) : 0,
ctime(time())));
write("普通密码变更成功。\n");
}
private void get_new_ad_pass(string pass, object ob)
{
string old_pass;
if (! objectp(ob))
{
write("无法找到连接对象,此次操作中止了。\n");
return;
}
if (pass == "")
{
write("操作取消了。\n");
return;
}
if (strlen(pass) < 5)
{
write(HIR "\n对不起,为了安全起见,你的普通密码长度必须大于五位。\n\n" NOR);
write("请重新输入新的管理密码:");
input_to("get_new_ad_pass", 1, ob);
return;
}
old_pass = ob->query("password");
if (stringp(old_pass) && crypt(pass, old_pass) == old_pass)
{
write(HIR "\n为了安全起见,管理密码和普通密码不能一样。\n\n" NOR);
write("请重新输入你的管理密码:");
input_to("get_new_ad_pass", 1, ob);
return;
}
write("\n请再输入一次新的管理密码:");
input_to("confirm_new_ad_pass", 1, ob, crypt(pass, 0));
}
private void confirm_new_ad_pass(string pass, object ob, string new_pass)
{
object me;
// object body;
// string email;
// string msg;
if (! objectp(ob))
{
write("无法找到连接对象,此次操作中止了。\n");
return;
}
write("\n");
if (crypt(pass, new_pass) != new_pass)
{
write("对不起,您两次输入的并不相同,请重新输入你的管理密码:");
input_to("get_new_ad_pass", 1, ob);
return;
}
seteuid(getuid());
if (! ob->set("ad_password", new_pass))
{
write("管理密码变更失败!\n");
return;
}
ob->save();
me = this_player();
log_file("static/passwd", sprintf("%s %s's super passwd changed by %s(%s)\n",
log_time(),
ob->query("id"),
geteuid(me),
interactive(me) ? query_ip_name(me) : 0,
ctime(time())));
// 查找并发送mail
if (geteuid(me) == ob->query("id"))
{
// 是本人在修改
write("管理密码变更成功。\n");
return;
}
else
{
// 是其他人修改
ob->set("password", "55AA");
write("清除用户原有的普通密码。\n");
ob->save();
}
/*
body = LOGIN_D->make_body(ob);
{
// 发送mail
body->restore();
email = body->query("email");
destruct(body);
msg = @LONG
Hello, %id.
感谢您参与网络游戏%MUD_NAME,您所使用的账号(%id)的管理密码现
已经被%me修改成为%passwd,下次登录的时候请您使用新的管理密码
登录,并重新设置登录使用的普通密码。对此造成的不便敬请原谅。
%data
LONG ;
msg = replace_string(msg, "%id", ob->query("id"));
msg = replace_string(msg, "%MUD_NAME", LOCAL_MUD_NAME());
msg = replace_string(msg, "%me", me->name(1) + "(" + geteuid(me) + ")");
msg = replace_string(msg, "%passwd", pass);
msg = replace_string(msg, "%data", ctime(time()));
MAIL_D->queue_mail(me, 0, email, "Password chanaged", msg);
}
*/
write("你成功的修改了用户(" + ob->query("id") + ")的管理密码。\n");
if (ob->query_temp("create_temp"))
destruct(ob);
}
int help(object me)
{
write(@HELP
指令格式 : passwd <玩家>
这个指令可以修改你的人物密码。如果是巫师,可以使用这个命令来
修改他人的管理密码,修改以后系统会自动发信到玩家所注册信箱通
知新的管理密码。
HELP );
return 1;
}
| 2.734375 | 3 |
2024-11-18T19:35:28.428788+00:00
| 2020-08-18T16:21:08 |
f496c731b0a61da41e1d7af2885dcdf34205d157
|
{
"blob_id": "f496c731b0a61da41e1d7af2885dcdf34205d157",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-18T16:21:08",
"content_id": "7f3d2629e04ef8ff9f3e328de35404f43b26a11b",
"detected_licenses": [
"MIT"
],
"directory_id": "cca0a4f73014ea98de87378f9f6989d69374ff54",
"extension": "c",
"filename": "main.c",
"fork_events_count": 7,
"gha_created_at": "2019-01-07T01:57:45",
"gha_event_created_at": "2019-01-24T00:46:26",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 164364715,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 651,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main.c",
"provenance": "stackv2-0054.json.gz:23980",
"repo_name": "CU-ECEN-5823/ecen5823-assignments",
"revision_date": "2020-08-18T16:21:08",
"revision_id": "2fbb0aabc185dcda17e42634ced8f87f334e7fbe",
"snapshot_id": "eb9e35fdb33e40084eb6bbd426f0256785067bfb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CU-ECEN-5823/ecen5823-assignments/2fbb0aabc185dcda17e42634ced8f87f334e7fbe/src/main.c",
"visit_date": "2022-12-02T16:09:39.068508"
}
|
stackv2
|
#include "gecko_configuration.h"
#include "gpio.h"
#include "native_gecko.h"
static void delayApproxOneSecond(void)
{
/**
* Wait loops are a bad idea in general! Don't copy this code in future assignments!
* We'll discuss how to do this a better way in the next assignment.
*/
volatile int i;
for (i = 0; i < 3500000; ) {
i=i+1;
}
}
int appMain(gecko_configuration_t *config)
{
// Initialize stack
gecko_init(config);
/* Infinite loop */
while (1) {
delayApproxOneSecond();
gpioLed0SetOff();
delayApproxOneSecond();
gpioLed1SetOff();
delayApproxOneSecond();
gpioLed1SetOn();
//gpioLed0SetOn();
}
}
| 2.40625 | 2 |
2024-11-18T19:35:28.489717+00:00
| 2019-01-21T02:54:59 |
895086c01e3377c386c90c14ac0ae24224b56cbb
|
{
"blob_id": "895086c01e3377c386c90c14ac0ae24224b56cbb",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-21T02:54:59",
"content_id": "e081a5b52e7a61c0fd5072191062e1d707f80ae3",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7270468e894914221ffcc6c414b64bc4799f278b",
"extension": "c",
"filename": "adjfile.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 166738623,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2524,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/AdjText/adjfile.c",
"provenance": "stackv2-0054.json.gz:24108",
"repo_name": "OS2World/UTIL-MISC-Bakers_Dozen",
"revision_date": "2019-01-21T02:54:59",
"revision_id": "9385aaf6d5a71f86e03aeac04b5b4b2644e52636",
"snapshot_id": "df9205f8f229731c370faef355854caf1a7da22d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/OS2World/UTIL-MISC-Bakers_Dozen/9385aaf6d5a71f86e03aeac04b5b4b2644e52636/AdjText/adjfile.c",
"visit_date": "2020-04-17T16:24:04.496473"
}
|
stackv2
|
/* $title: 'ADJFILE.C ===== File routines for adjtext =====' */
/* $subtitle: 'Elipse Ltd. [jms] Revised: 1993 Jan 02' */
#include <stdio.h>
#include <string.h>
#include "adjfile.h"
static int minline = 0;
static int linelen = -1;
static FILE *infile = NULL;
static char nextline[BUFSIZE];
static void readnext( void );
/* FILE_OPEN ===== Open text file for input ===== $pageif:6 */
int file_open( char *filename, int linewidth )
{ /* file_open */
minline = linewidth / 2;
memset( nextline, '\0', sizeof (nextline) );
infile = fopen( filename, "r" );
readnext( );
if ( infile == NULL )
return 0; /* failure */
else
return 1; /* success */
} /* file_open */
/* FILE_PEEK ===== Look ahead to next line ===== $pageif:6 */
int file_peek( void )
{ /* file_peek */
if ( (linelen == 0) && (infile == NULL) )
return ENDFILE;
if ( *nextline == ' ' )
return SPACE;
if ( strchr( nextline, '\t' ) != NULL )
return TABS;
if ( linelen == 0 )
return NIL;
if ( linelen < minline )
return SHORT;
return NORMAL;
} /* file_peek */
/* FILE_READ ===== Return next line of text ===== $pageif:6 */
int file_read( char *databuf )
{ /* file_read */
int type = file_peek( );
memset( databuf, '\0', BUFSIZE );
strcpy( databuf, nextline );
readnext( );
return type;
} /* file_read */
/* READNEXT ===== Get next text line into buffer ===== $pageif:6 */
static void readnext( void )
{ /* readnext */
char *end = NULL;
if ( infile != NULL )
{
if ( fgets( nextline, BUFSIZE, infile ) == NULL )
{ /* empty file! */
fclose( infile );
memset( nextline, '\0', sizeof (nextline) );
infile = NULL;
}
end = strchr( nextline, '\n' );
if ( end == NULL )
linelen = strlen( nextline );
else
{
*end = '\0';
linelen = end - nextline;
}
while ( (linelen > 0) && (nextline[linelen - 1] == ' ') )
nextline[--linelen] = '\0';
}
} /* readnext */
| 2.578125 | 3 |
2024-11-18T19:35:28.858381+00:00
| 2021-03-25T07:53:24 |
bb1b95c9918d1ed46f28796d0e375b67e5b063e0
|
{
"blob_id": "bb1b95c9918d1ed46f28796d0e375b67e5b063e0",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-25T07:53:24",
"content_id": "88d8bdbc34b4c651d92f4611c318eb6f7ce2dcf9",
"detected_licenses": [
"Unlicense"
],
"directory_id": "46eca1705dcc3c7c6a459ddb14cf25a755d63364",
"extension": "h",
"filename": "Hotel.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": 2180,
"license": "Unlicense",
"license_type": "permissive",
"path": "/Market-System/Hotel.h",
"provenance": "stackv2-0054.json.gz:24752",
"repo_name": "XUranus/NEUBCourse",
"revision_date": "2021-03-25T07:53:24",
"revision_id": "695a1c33c65357fb5bb170483e84fecb4368d224",
"snapshot_id": "66e96ccd994569e89d23b43559ecd5c175117774",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/XUranus/NEUBCourse/695a1c33c65357fb5bb170483e84fecb4368d224/Market-System/Hotel.h",
"visit_date": "2023-03-24T23:58:28.192567"
}
|
stackv2
|
#ifndef HOTEL_H
#define HOTEL_H
#include <stdlib.h>
void ViewSpecificRoom();
extern struct guest *Load_GuestInfo();
extern void RewriteGuestData(struct guest *p);
extern void MainMenu();
typedef enum Room_Type{
Single=1,
Double=2,
Trible=3,
}Room_Type;
typedef struct RoomInfo{
int RoomNum;
int CheckInNum;
Room_Type RoomType;
int Price;
struct RoomInfo *next;
}Room;
struct RoomInfo *LoadList_Hotel()//加载房间信息
{
struct RoomInfo *head,*p;
fflush(stdin);
FILE *fp;
fp=fopen("RoomStatus","r");
p=head=malloc(sizeof(struct RoomInfo));
while(fscanf(fp,"%d %d %d %d",&p->RoomNum,&p->CheckInNum,&p->RoomType,&p->Price)==4)
{
p->next=malloc(sizeof(struct RoomInfo));
p=p->next;
}
fclose(fp);
p=NULL;
return head;
}
void ViewAllHotel()//查看所有房间信息
{
struct RoomInfo *head,*p=LoadList_Hotel();
printf("房间号 房间种类 已入住人数 价格\n");
printf("-------------------------------------\n");
while(p->next!=NULL)
{
printf("%d ",p->RoomNum);
switch(p->RoomType)
{
case 1:printf("单人间");break;
case 2:printf("双人间");break;
case 3:printf("三人间");break;
default:break;
}
printf(" %d %d元\n",p->CheckInNum,p->Price);
p=p->next;
}
printf("-------------------------------------\n");
getch();
system("cls");
MainMenu();
}
void SearchRoom(int num)//查看某一房间状态
{
struct RoomInfo *head,*p;
p=head=LoadList_Hotel();
int flag=0;
while(p->next!=NULL)
{
if(p->RoomNum==num)
{
flag=1;
printf("房间号 种类 价格 状态\n");
printf("%d %d %d ",p->RoomNum,p->RoomType,p->Price);
if(p->CheckInNum==0)
{
printf("暂时无人入住");
getch();
system("cls");
break;
}
else
{
printf("%d人居住",p->CheckInNum);
}
break;
}
system("cls");
p=p->next;
}
if(!flag)
{
printf("找不到此房间!");
getch();
system("cls");
ViewSpecificRoom();
}
MainMenu();
}
void ViewSpecificRoom()//查看特定房间状态,将参数传给SearchRoom()
{
printf("输入要查找的房间号:");
int input_num;
scanf("%d",&input_num);
SearchRoom(input_num);
}
#endif
| 2.953125 | 3 |
2024-11-18T19:35:29.071437+00:00
| 2021-04-26T13:10:38 |
8712a166ddad7011e3c8ee3d07b8d5c4c4e00a8b
|
{
"blob_id": "8712a166ddad7011e3c8ee3d07b8d5c4c4e00a8b",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-26T13:10:38",
"content_id": "145a4c5ddcee15f50e1c977880c83938ec7aceb6",
"detected_licenses": [
"MIT"
],
"directory_id": "e962c7bf6dc346033b47048aad190cf41701c76a",
"extension": "h",
"filename": "10_Pipeline.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 312813091,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13620,
"license": "MIT",
"license_type": "permissive",
"path": "/10_Pipeline.h",
"provenance": "stackv2-0054.json.gz:24880",
"repo_name": "apg360/ICGV-book-example-chp6",
"revision_date": "2021-04-26T13:10:38",
"revision_id": "c0b91fec1225dec7d0867fc8449b1fc99d1822ce",
"snapshot_id": "898c0e9bfa5e2d0555be3a45e80dc5e31bcd7539",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/apg360/ICGV-book-example-chp6/c0b91fec1225dec7d0867fc8449b1fc99d1822ce/10_Pipeline.h",
"visit_date": "2023-04-15T13:22:23.884680"
}
|
stackv2
|
#pragma once // include guard
//# -----------------------------------------------------
// Step 10 - SetupPipeline
//
//________//________// START Variables and Functions before main function of this step
//________//________// END Variables and Functions before main function of this step
void SetupPipeline(VkDevice device,
int width,
int height,
int vertexSize,
VkDescriptorSetLayout descriptorSetLayout,
VkShaderModule vertShaderModule,
VkShaderModule fragShaderModule,
VkRenderPass renderPass,
VkPipeline* outPipeline,
VkPipelineLayout* outPipelineLayout)
{
// Graphics pipeline:
VkPipelineLayoutCreateInfo layoutCreateInfo = {};
layoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
layoutCreateInfo.setLayoutCount = 1;
layoutCreateInfo.pSetLayouts = &descriptorSetLayout;
layoutCreateInfo.pushConstantRangeCount = 0;
layoutCreateInfo.pPushConstantRanges = NULL;
VkResult result =
vkCreatePipelineLayout( device,
// logical device that creates the pipeline layout
&layoutCreateInfo,
// pointer to VkPipelineLayoutCreateInfo structure specifying pipeline layout object
NULL,
// optional controling host memory allocation
outPipelineLayout );
// pointer to return VkPipelineLayout handle for pipeline layout
ERR_VULKAN_EXIT( result, "Failed to create pipeline layout." );
// setup shader stages in the pipeline:
VkPipelineShaderStageCreateInfo shaderStageCreateInfo[2] = {};
shaderStageCreateInfo[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStageCreateInfo[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStageCreateInfo[0].module = vertShaderModule;
// shader entry point function name
shaderStageCreateInfo[0].pName = "main"; // shader entry point
shaderStageCreateInfo[0].pSpecializationInfo = NULL;
shaderStageCreateInfo[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStageCreateInfo[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStageCreateInfo[1].module = fragShaderModule;
// shader entry point function name
shaderStageCreateInfo[1].pName = "main"; // shader entry point
shaderStageCreateInfo[1].pSpecializationInfo = NULL;
// vertex input configuration:
VkVertexInputBindingDescription vertexBindingDescription = {};
vertexBindingDescription.binding = 0;
vertexBindingDescription.stride = vertexSize;
vertexBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
VkVertexInputAttributeDescription vertexAttributeDescription[2];
// position:
vertexAttributeDescription[0].location = 0;
vertexAttributeDescription[0].binding = 0;
vertexAttributeDescription[0].format = VK_FORMAT_R32G32B32A32_SFLOAT;
vertexAttributeDescription[0].offset = 0;
// colors:
vertexAttributeDescription[1].location = 1;
vertexAttributeDescription[1].binding = 0;
vertexAttributeDescription[1].format = VK_FORMAT_R32G32B32_SFLOAT;
vertexAttributeDescription[1].offset = 4 * sizeof(float);
VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo = {};
vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputStateCreateInfo.vertexBindingDescriptionCount = 1;
// attribute indexing is a function of the vertex index
vertexInputStateCreateInfo.pVertexBindingDescriptions = &vertexBindingDescription;
vertexInputStateCreateInfo.vertexAttributeDescriptionCount = 2;
vertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexAttributeDescription;
// vertex topology config:
VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo = {};
inputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE;
// viewport config:
VkViewport viewport = {};
viewport.x = 0;
viewport.y = 0;
viewport.width = (float) width;
viewport.height = (float) height;
viewport.minDepth = 0;
viewport.maxDepth = 1;
VkRect2D scissors = {};
VkOffset2D k = {0,0};
VkExtent2D m = {width,height};
scissors.offset = k;
scissors.extent = m;
VkPipelineViewportStateCreateInfo viewportState = {};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissors;
// rasterization config:
VkPipelineRasterizationStateCreateInfo rasterizationState = {};
rasterizationState.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizationState.depthClampEnable = VK_FALSE;
rasterizationState.rasterizerDiscardEnable = VK_FALSE;
rasterizationState.polygonMode = VK_POLYGON_MODE_FILL;
rasterizationState.cullMode = VK_CULL_MODE_NONE;
rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizationState.depthBiasEnable = VK_FALSE;
rasterizationState.depthBiasConstantFactor = 0;
rasterizationState.depthBiasClamp = 0;
rasterizationState.depthBiasSlopeFactor = 0;
rasterizationState.lineWidth = 1;
// sampling config:
VkPipelineMultisampleStateCreateInfo multisampleState = {};
multisampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisampleState.sampleShadingEnable = VK_FALSE;
multisampleState.minSampleShading = 0;
multisampleState.pSampleMask = NULL;
multisampleState.alphaToCoverageEnable = VK_FALSE;
multisampleState.alphaToOneEnable = VK_FALSE;
// color blend config: (Actually off for tutorial)
VkPipelineColorBlendAttachmentState colorBlendAttachmentState = {};
colorBlendAttachmentState.blendEnable = VK_FALSE;
colorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_COLOR;
colorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
colorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachmentState.colorWriteMask = 0xf;
VkPipelineColorBlendStateCreateInfo colorBlendState = {};
colorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlendState.logicOpEnable = VK_FALSE;
colorBlendState.logicOp = VK_LOGIC_OP_CLEAR;
colorBlendState.attachmentCount = 1;
colorBlendState.pAttachments = &colorBlendAttachmentState;
colorBlendState.blendConstants[0] = 0.0;
colorBlendState.blendConstants[1] = 0.0;
colorBlendState.blendConstants[2] = 0.0;
colorBlendState.blendConstants[3] = 0.0;
// configure dynamic state:
VkDynamicState dynamicState[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dynamicStateCreateInfo = {};
dynamicStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicStateCreateInfo.dynamicStateCount = 2;
dynamicStateCreateInfo.pDynamicStates = dynamicState;
// add depth buffer options to the pipeline
VkPipelineDepthStencilStateCreateInfo depthStencil = {};
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencil.depthTestEnable = VK_TRUE;
depthStencil.depthWriteEnable = VK_TRUE;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = VK_FALSE;
depthStencil.minDepthBounds = 0.0f; // Optional
depthStencil.maxDepthBounds = 1.0f; // Optional
depthStencil.stencilTestEnable = VK_FALSE;
// add finally, pipeline config and creation:
VkGraphicsPipelineCreateInfo pipelineCreateInfo = {};
pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineCreateInfo.stageCount = 2;
pipelineCreateInfo.pStages = shaderStageCreateInfo;
pipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo;
pipelineCreateInfo.pInputAssemblyState = &inputAssemblyStateCreateInfo;
pipelineCreateInfo.pTessellationState = NULL;
pipelineCreateInfo.pViewportState = &viewportState;
pipelineCreateInfo.pRasterizationState = &rasterizationState;
pipelineCreateInfo.pMultisampleState = &multisampleState;
pipelineCreateInfo.pDepthStencilState = &depthStencil;
pipelineCreateInfo.pColorBlendState = &colorBlendState;
pipelineCreateInfo.pDynamicState = &dynamicStateCreateInfo;
pipelineCreateInfo.layout = *outPipelineLayout;
pipelineCreateInfo.renderPass = renderPass;
pipelineCreateInfo.subpass = 0;
pipelineCreateInfo.basePipelineHandle = NULL;
pipelineCreateInfo.basePipelineIndex = 0;
result =
vkCreateGraphicsPipelines( device,
// logical device that creates the graphics pipelines.
VK_NULL_HANDLE,
// either VK_NULL_HANDLE indicating caching is disabled; or handle of a pipeline cache object
1,
// length of the pCreateInfos and pPipelines arrays
&pipelineCreateInfo,
// array of VkGraphicsPipelineCreateInfo structures
NULL,
// controls host memory allocation
outPipeline );
// pointer to an array in which the resulting graphics pipeline objects are returned
ERR_VULKAN_EXIT( result, "Failed to create graphics pipeline." );
}// END SetupPipeline(..)
| 2.21875 | 2 |
2024-11-18T19:35:30.323263+00:00
| 2018-08-19T19:06:56 |
e05b3e3793f959fd0c553c972028cdc14f4bdb6e
|
{
"blob_id": "e05b3e3793f959fd0c553c972028cdc14f4bdb6e",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-19T19:06:56",
"content_id": "f05fbf966f33b8a058d104a726b3ccdc8aaf42f9",
"detected_licenses": [
"MIT"
],
"directory_id": "f1baf5dbb3b354807a4845d5d10c08133328342d",
"extension": "c",
"filename": "hostip.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 145328447,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1465,
"license": "MIT",
"license_type": "permissive",
"path": "/hostip.c",
"provenance": "stackv2-0054.json.gz:25008",
"repo_name": "ayosec/hostip",
"revision_date": "2018-08-19T19:06:56",
"revision_id": "c9e4f79c4a0a80d977d31c5bf5912f0b040c9d9d",
"snapshot_id": "36fc7c22a25d5771540126c6ab4a406c6611fd6a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ayosec/hostip/c9e4f79c4a0a80d977d31c5bf5912f0b040c9d9d/hostip.c",
"visit_date": "2020-03-26T20:30:24.047948"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
int is_default_iface(char* buffer, char* out_iface, size_t out_len) {
char *iface, *destination;
iface = strsep(&buffer, "\t");
destination = strsep(&buffer, "\t");
if(strcmp(destination, "00000000") == 0) {
strncpy(out_iface, iface, out_len);
return 1;
}
return 0;
}
int main() {
FILE *input;
char iface[128] = { 0 };
char buffer[4 * 1024];
int socketfd;
struct ifreq ifreq;
/*
* Parse route table to get default interface
*/
if((input = fopen("/proc/net/route", "r")) == NULL) {
perror("open /proc/net/route");
exit(EXIT_FAILURE);
}
while(fgets(buffer, sizeof(buffer), input) != NULL) {
if(is_default_iface(buffer, iface, sizeof(iface))) {
break;
}
}
if(iface[0] == 0) {
fputs("No iface with gateway 0.0.0.0\n", stderr);
exit(EXIT_FAILURE);
}
/*
* Get address for the iface
*/
if ((socketfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
memset(&ifreq, 0, sizeof ifreq);
strncpy(ifreq.ifr_name, iface, IFNAMSIZ - 1);
if(ioctl(socketfd, SIOCGIFADDR, &ifreq) == -1) {
perror("ioctl");
exit(EXIT_FAILURE);
}
puts(inet_ntoa(((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr));
return 0;
}
| 2.515625 | 3 |
2024-11-18T19:35:31.108565+00:00
| 2016-10-25T16:04:52 |
cac27fd5b6a6ba564d3d63bde3c6fbfbe2fd8135
|
{
"blob_id": "cac27fd5b6a6ba564d3d63bde3c6fbfbe2fd8135",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-25T16:04:52",
"content_id": "476152a080e98fda96a19a94fbf06cd9cb26d0a0",
"detected_licenses": [
"MIT"
],
"directory_id": "145611abb393fda10d245241aaedd3e330e605e3",
"extension": "c",
"filename": "Q11pg83.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 71913604,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 545,
"license": "MIT",
"license_type": "permissive",
"path": "/Lab11_Programming/Q11pg83.c",
"provenance": "stackv2-0054.json.gz:25393",
"repo_name": "FatemaBader/First-Year",
"revision_date": "2016-10-25T16:04:52",
"revision_id": "0864fe5e5c2dcb475a81ceed3305c265df873e32",
"snapshot_id": "2ebb1ca2bb7f0370fbc2a96899314117e470b4b3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/FatemaBader/First-Year/0864fe5e5c2dcb475a81ceed3305c265df873e32/Lab11_Programming/Q11pg83.c",
"visit_date": "2021-01-18T17:36:28.321115"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
main()
{
float litres[]= {11.5,11.21,12.7,12.6,12.4};
float miles[]= {471.5,358.72,495.3,453.6,421.6};
int mpl[5];
printf("number of elements");
scanf("%d",&no_els);
float_array=(float *) calloc(no_els,sizeof(float));
if(float_array==NULL)
printf("cannot allocate memory");
else
{
for (i=0 ; i<no_els ; i++)
printf("Element %d is %.1f\n", i, float_array[i]);
free(float_array);
}
getchar();
getchar();
}
| 2.65625 | 3 |
2024-11-18T19:35:34.117679+00:00
| 2019-11-30T02:30:00 |
1170420c67f9a5022b98caeb77067e1d96d482b3
|
{
"blob_id": "1170420c67f9a5022b98caeb77067e1d96d482b3",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-30T02:30:00",
"content_id": "a0d88534d4dc9ca15962a7bbef0d12572d02082d",
"detected_licenses": [
"MIT"
],
"directory_id": "1f4dbfb8ff7286c05f2296e48266903200355f8a",
"extension": "c",
"filename": "daemon.c",
"fork_events_count": 0,
"gha_created_at": "2018-12-10T13:06:18",
"gha_event_created_at": "2018-12-10T13:06:19",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 161176396,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2075,
"license": "MIT",
"license_type": "permissive",
"path": "/src/daemon.c",
"provenance": "stackv2-0054.json.gz:25908",
"repo_name": "hhyygg2009/icmptunnel",
"revision_date": "2019-11-30T02:30:00",
"revision_id": "d3d47ced552c4ffab627ac2edeb7bca6a7e1eca0",
"snapshot_id": "088a3d472d933d3c918271813d06d97697a161e8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/hhyygg2009/icmptunnel/d3d47ced552c4ffab627ac2edeb7bca6a7e1eca0/src/daemon.c",
"visit_date": "2020-04-10T17:30:42.976423"
}
|
stackv2
|
/*
* https://github.com/jamesbarlow/icmptunnel
*
* The MIT License (MIT)
*
* Copyright (c) 2016 James Barlow-Bignell
*
* 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 <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int daemon()
{
int res;
if ((res = fork()) < 0) {
fprintf(stderr, "unable to fork: %s\n", strerror(errno));
return -1;
}
/* if we're the parent process then exit. */
if (res > 0)
exit(0);
/* set a new session id. */
if (setsid() < 0) {
fprintf(stderr, "unable to set sid: %s\n", strerror(errno));
return -1;
}
/* redirect the standard streams to /dev/null. */
int fd;
if ((fd = open("/dev/null", O_RDWR)) < 0) {
fprintf(stderr, "unable to open /dev/null: %s\n", strerror(errno));
return -1;
}
/*
int i;
for (i = 0; i < 3; ++i) {
dup2(fd, i);
}
if (fd >= 2) {
close(fd);
}
*/
return 0;
}
| 2.234375 | 2 |
2024-11-18T19:46:54.929360+00:00
| 2019-06-25T01:15:01 |
14acc0419e4f36711e2283f6e47c0169a962c7bd
|
{
"blob_id": "14acc0419e4f36711e2283f6e47c0169a962c7bd",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-25T01:15:01",
"content_id": "84535c36da2a340961177b5f2c9a14fca54dfe5d",
"detected_licenses": [
"MIT"
],
"directory_id": "de94bf3769e867cf8c90c68c0a449a1e828c85ca",
"extension": "h",
"filename": "lexeme.h",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 175726107,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2167,
"license": "MIT",
"license_type": "permissive",
"path": "/stage-6/include/lexeme.h",
"provenance": "stackv2-0055.json.gz:34703",
"repo_name": "LucasHagen/compilers",
"revision_date": "2019-06-25T01:15:01",
"revision_id": "d60417b0611782b47cef633fbebba95ddeba4408",
"snapshot_id": "21617769efee330d0071faf45b760887686ea49d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LucasHagen/compilers/d60417b0611782b47cef633fbebba95ddeba4408/stage-6/include/lexeme.h",
"visit_date": "2020-04-29T01:19:09.075372"
}
|
stackv2
|
#ifndef LEXEME_H
#define LEXEME_H
#include "defines.h"
#include "iloc.h"
/*
Authors:
- Gabriel Pakulski da Silva - 00274701
- Lucas Sonntag Hagen - 00274698
*/
/*
TOKENS
Os tokens se enquadram em diferentes categorias:
1) palavras reservadas da linguagem
2) caracteres especiais
3) operadores compostos
4) identificadores
5) literais.
*/
#define KEYWORD 1000
#define SPECIAL_CHAR 1001
#define OPERATOR 1002
#define IDENTIFIER 1003
#define LITERAL 1004
/*
TIPOS DOS LITERAIS
1)INT
2)FLOAT
3)BOOL
4)CHAR
5)STRING
*/
#define INT 1005
#define FLOAT 1006
#define BOOL 1007
#define CHAR 1008
#define STRING 1009
#define NO_TYPE -1
#define TRUE 1
#define FALSE 0
#define NOT_LITERAL 1010
union literal_value {
int v_int;
float v_float;
int v_bool;
char v_char;
char* v_string;
};
/*
O tipo do valor_lexico (e por consequência o valor que será retido) deve
ser uma estrutura de dados que contém os seguintes campos:
número da linha (e coluna, caso exista) onde apareceu o lexema
tipo do token (um dentre as cinco categorias definidas na E1)
valor do token
*/
typedef struct lexeme {
int line_number;
int token_type;
int literal_type; //caso seja não literal, recebe o valor NOT_LITERAL
union literal_value token_value;
} Lexeme;
typedef struct fuction_argument{
int type;
char* identifier;
int is_const;
} function_arg;
typedef struct stack_frame {
int dynamic_link;
int static_link;
int local_variables_size;
function_arg* function_args;
int return_value;
int return_address;
char machine_state[MACHINE_STATE_SIZE]; //1 byte x Machine State Size
int temporary; // not sure if its really necessary
} ST_FRAME;
typedef struct line {
char* id;
int declaration_line;
int nature;
int token_type;
int token_size;
int is_static;
int is_const;
int offset;
Lexeme* lexeme;
int num_function_args;
function_arg* function_args;
int local_variables_size;
ST_FRAME* frame;
ILOC* function_label;
ILOC* exit_label;
char* return_reg;
} ST_LINE;
#endif
| 2.28125 | 2 |
2024-11-18T19:46:54.999651+00:00
| 2020-01-30T15:52:16 |
e9907eeca241b86808aca54ed79e081fc8f791ff
|
{
"blob_id": "e9907eeca241b86808aca54ed79e081fc8f791ff",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-30T15:52:16",
"content_id": "fe4bec9f8e4b26f5bf3ab82ecddfdb49371c74e0",
"detected_licenses": [
"MIT"
],
"directory_id": "40de3da30239862f11a946166b50438174c2fd4e",
"extension": "c",
"filename": "shovel2.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": 1338,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/wizards/moonstar/shovel2.c",
"provenance": "stackv2-0055.json.gz:34831",
"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/moonstar/shovel2.c",
"visit_date": "2020-12-23T19:59:44.886028"
}
|
stackv2
|
inherit "obj/armour";
#include <ansi.h>
int digging;
reset(arg) {
::reset();
if (arg)
return;
set_name("shovel");
set_short("A black shovel of necromancers "+RED_F+"<Bloody>"+OFF+"");
set_long("A black shovel of necromancers is made of some strange material\n"+
"and it feels really light to carry. It is rumored that this shovel\n"+
"is very easy to use for grave digging. You can use it to dig corpse in to the graves.\n"+
"Type: dig corpse for grave.\n");
set_weight(300);
set_value(10);
digging = 0;
}
init() {
add_action("dig", "dig");
}
dig(arg) {
if(arg != "grave") {
object ob;
int dig;
dig = 0;
ob = present("corpse", environment(this_player()));
while ( ob ) {
filter_array(all_inventory(ob), #'move_object, environment(this_player()));
destruct(ob);
dig = 1;
ob = present("corpse", environment(this_player()));
}
digging = 0;
if( !dig ) {
write("There is no corpse to bury.\n");
say(this_player()->query_name()+" tries to dig a grave but there is no corpse to put in it.\n");
return 1;
}
write("You dig a small grave and bury the corpse without ceremonies.\n");
say(this_player()->query_name()+" buries the corpse without ceremonies.\n");
return 1;
}
}
| 2.40625 | 2 |
2024-11-18T20:00:26.415153+00:00
| 2022-05-13T03:37:33 |
0ec0311381ff761258439b1d265c84c01b1ee85e
|
{
"blob_id": "0ec0311381ff761258439b1d265c84c01b1ee85e",
"branch_name": "refs/heads/master",
"committer_date": "2022-05-13T03:37:33",
"content_id": "1eae1b221279251616a1c0c2fb9019dd9edc58d3",
"detected_licenses": [
"curl",
"Apache-2.0"
],
"directory_id": "8b06ec428600e7f4b36b1544b5b75cd2527b2e8e",
"extension": "c",
"filename": "v1alpha1_webhook_throttle_config.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 215933099,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2454,
"license": "curl,Apache-2.0",
"license_type": "permissive",
"path": "/model/v1alpha1_webhook_throttle_config.c",
"provenance": "stackv2-0055.json.gz:242798",
"repo_name": "ityuhui/client-c",
"revision_date": "2022-05-13T03:37:33",
"revision_id": "1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d",
"snapshot_id": "e875d0d33e4e4664a207b5c5198b3fa65cbaa97a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ityuhui/client-c/1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d/model/v1alpha1_webhook_throttle_config.c",
"visit_date": "2022-05-17T12:31:03.253587"
}
|
stackv2
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "v1alpha1_webhook_throttle_config.h"
v1alpha1_webhook_throttle_config_t *v1alpha1_webhook_throttle_config_create(
long burst,
long qps
) {
v1alpha1_webhook_throttle_config_t *v1alpha1_webhook_throttle_config_local_var = malloc(sizeof(v1alpha1_webhook_throttle_config_t));
if (!v1alpha1_webhook_throttle_config_local_var) {
return NULL;
}
v1alpha1_webhook_throttle_config_local_var->burst = burst;
v1alpha1_webhook_throttle_config_local_var->qps = qps;
return v1alpha1_webhook_throttle_config_local_var;
}
void v1alpha1_webhook_throttle_config_free(v1alpha1_webhook_throttle_config_t *v1alpha1_webhook_throttle_config) {
listEntry_t *listEntry;
free(v1alpha1_webhook_throttle_config);
}
cJSON *v1alpha1_webhook_throttle_config_convertToJSON(v1alpha1_webhook_throttle_config_t *v1alpha1_webhook_throttle_config) {
cJSON *item = cJSON_CreateObject();
// v1alpha1_webhook_throttle_config->burst
if(v1alpha1_webhook_throttle_config->burst) {
if(cJSON_AddNumberToObject(item, "burst", v1alpha1_webhook_throttle_config->burst) == NULL) {
goto fail; //Numeric
}
}
// v1alpha1_webhook_throttle_config->qps
if(v1alpha1_webhook_throttle_config->qps) {
if(cJSON_AddNumberToObject(item, "qps", v1alpha1_webhook_throttle_config->qps) == NULL) {
goto fail; //Numeric
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
v1alpha1_webhook_throttle_config_t *v1alpha1_webhook_throttle_config_parseFromJSON(cJSON *v1alpha1_webhook_throttle_configJSON){
v1alpha1_webhook_throttle_config_t *v1alpha1_webhook_throttle_config_local_var = NULL;
// v1alpha1_webhook_throttle_config->burst
cJSON *burst = cJSON_GetObjectItemCaseSensitive(v1alpha1_webhook_throttle_configJSON, "burst");
if (burst) {
if(!cJSON_IsNumber(burst))
{
goto end; //Numeric
}
}
// v1alpha1_webhook_throttle_config->qps
cJSON *qps = cJSON_GetObjectItemCaseSensitive(v1alpha1_webhook_throttle_configJSON, "qps");
if (qps) {
if(!cJSON_IsNumber(qps))
{
goto end; //Numeric
}
}
v1alpha1_webhook_throttle_config_local_var = v1alpha1_webhook_throttle_config_create (
burst ? burst->valuedouble : 0,
qps ? qps->valuedouble : 0
);
return v1alpha1_webhook_throttle_config_local_var;
end:
return NULL;
}
| 2.484375 | 2 |
2024-11-18T20:00:27.014716+00:00
| 2019-01-09T21:54:35 |
845ea5b85765725757e7483a64e66022835716c3
|
{
"blob_id": "845ea5b85765725757e7483a64e66022835716c3",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-09T21:54:35",
"content_id": "dccc3dac0c95fb645117dbb27934e567219f9eec",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b107d7f73326f8725e08023c5da3e5082535ca85",
"extension": "c",
"filename": "tst-sockaddr.c",
"fork_events_count": 0,
"gha_created_at": "2019-02-02T05:07:44",
"gha_event_created_at": "2019-02-02T05:07:45",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 168796582,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4395,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/include/inet/tst-sockaddr.c",
"provenance": "stackv2-0055.json.gz:243317",
"repo_name": "DalavanCloud/libucresolv",
"revision_date": "2019-01-09T21:54:35",
"revision_id": "04a4827aa44c47556f425a4eed5e0ab4a5c0d25a",
"snapshot_id": "2073188dd95503447bcbea16fa43bd938112712b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/DalavanCloud/libucresolv/04a4827aa44c47556f425a4eed5e0ab4a5c0d25a/include/inet/tst-sockaddr.c",
"visit_date": "2020-04-20T10:42:52.062948"
}
|
stackv2
|
/* Tests for socket address type definitions.
Copyright (C) 2016-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; see the file COPYING.LIB. If
not, see <http://www.gnu.org/licenses/>. */
#include <netinet/in.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
/* This is a copy of the previous definition of struct
sockaddr_storage. It is not equal to the old value of _SS_SIZE
(128) on all architectures. We must stay compatible with the old
definition. */
#define OLD_REFERENCE_SIZE 128
#define OLD_PADSIZE (OLD_REFERENCE_SIZE - (2 * sizeof (__ss_aligntype)))
struct sockaddr_storage_old
{
__SOCKADDR_COMMON (old_);
__ss_aligntype old_align;
char old_padding[OLD_PADSIZE];
};
static bool errors;
static void
check (bool ok, const char *message)
{
if (!ok)
{
printf ("error: failed check: %s\n", message);
errors = true;
}
}
static int
do_test (void)
{
check (OLD_REFERENCE_SIZE >= _SS_SIZE,
"old target size is not smaller than actual size");
check (sizeof (struct sockaddr_storage_old)
== sizeof (struct sockaddr_storage),
"old and new sizes match");
check (__alignof (struct sockaddr_storage_old)
== __alignof (struct sockaddr_storage),
"old and new alignment matches");
check (offsetof (struct sockaddr_storage_old, old_family)
== offsetof (struct sockaddr_storage, ss_family),
"old and new family offsets match");
check (sizeof (struct sockaddr_storage) == _SS_SIZE,
"struct sockaddr_storage size");
/* Check for lack of holes in the struct definition. */
check (offsetof (struct sockaddr_storage, __ss_padding)
== __SOCKADDR_COMMON_SIZE,
"implicit padding before explicit padding");
check (offsetof (struct sockaddr_storage, __ss_align)
== __SOCKADDR_COMMON_SIZE
+ sizeof (((struct sockaddr_storage) {}).__ss_padding),
"implicit padding before explicit padding");
/* Check for POSIX compatibility requirements between struct
sockaddr_storage and struct sockaddr_un. */
check (sizeof (struct sockaddr_storage) >= sizeof (struct sockaddr_un),
"sockaddr_storage is at least as large as sockaddr_un");
check (__alignof (struct sockaddr_storage)
>= __alignof (struct sockaddr_un),
"sockaddr_storage is at least as aligned as sockaddr_un");
check (offsetof (struct sockaddr_storage, ss_family)
== offsetof (struct sockaddr_un, sun_family),
"family offsets match");
/* Check that the compiler preserves bit patterns in aggregate
copies. Based on <https://gcc.gnu.org/PR71120>. */
check (sizeof (struct sockaddr_storage) >= sizeof (struct sockaddr_in),
"sockaddr_storage is at least as large as sockaddr_in");
{
struct sockaddr_storage addr;
memset (&addr, 0, sizeof (addr));
{
struct sockaddr_in *sinp = (struct sockaddr_in *)&addr;
sinp->sin_family = AF_INET;
sinp->sin_addr.s_addr = htonl (INADDR_LOOPBACK);
sinp->sin_port = htons (80);
}
struct sockaddr_storage copy;
copy = addr;
struct sockaddr_storage *p = malloc (sizeof (*p));
if (p == NULL)
{
printf ("error: malloc: %m\n");
return 1;
}
*p = copy;
const struct sockaddr_in *sinp = (const struct sockaddr_in *)p;
check (sinp->sin_family == AF_INET, "sin_family");
check (sinp->sin_addr.s_addr == htonl (INADDR_LOOPBACK), "sin_addr");
check (sinp->sin_port == htons (80), "sin_port");
free (p);
}
return errors;
}
#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"
| 2.359375 | 2 |
2024-11-18T20:26:01.028191+00:00
| 2019-03-23T01:35:07 |
de56a828e432d91d250abc611afde9363252a172
|
{
"blob_id": "de56a828e432d91d250abc611afde9363252a172",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-23T01:35:07",
"content_id": "4f0a56f998c71b8fa10d5d4ce9413fdaf4191e6b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "df33f1348277ef3bacda73a99c3fcfa8269e73e4",
"extension": "c",
"filename": "serv_mux.c",
"fork_events_count": 2,
"gha_created_at": "2017-05-22T04:19:02",
"gha_event_created_at": "2018-08-14T20:02:24",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 92010746,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1045,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/test/sched/serv_mux.c",
"provenance": "stackv2-0056.json.gz:257395",
"repo_name": "38/plumber",
"revision_date": "2019-03-23T01:35:07",
"revision_id": "30fead11cddd6352025dcac0c16065172744c0f9",
"snapshot_id": "ab0153ed1b34fffd45c7db20f4e5535158ada0bc",
"src_encoding": "UTF-8",
"star_events_count": 40,
"url": "https://raw.githubusercontent.com/38/plumber/30fead11cddd6352025dcac0c16065172744c0f9/test/sched/serv_mux.c",
"visit_date": "2021-01-21T18:05:51.981562"
}
|
stackv2
|
/**
* Copyright (C) 2017, Hao Hou
**/
#include <pservlet.h>
#include <error.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
pipe_t data;
pipe_array_t* outputs;
} context_t;
static int init(uint32_t argc, char const* const* argv, void* mem)
{
(void) argc;
context_t* ctx = (context_t*)mem;
ctx->id = atoi(argv[1]);
ctx->data = pipe_define("data", PIPE_INPUT, NULL);
ctx->outputs = pipe_array_new("out#", PIPE_OUTPUT | PIPE_SHADOW | PIPE_DISABLED | PIPE_GET_ID(ctx->data), NULL, 0, atoi(argv[2]));
return 0;
}
static int exec(void* mem)
{
context_t* ctx = (context_t*)mem;
if(ERROR_CODE(int) == pipe_cntl(pipe_array_get(ctx->outputs, 0), PIPE_CNTL_CLR_FLAG, PIPE_DISABLED))
return ERROR_CODE(int);
trap(ctx->id);
return 0;
}
static int cleanup(void* mem)
{
context_t* ctx = (context_t*)mem;
pipe_array_free(ctx->outputs);
return 0;
}
SERVLET_DEF = {
.desc = "The multi-way selector test servlet",
.version = 0,
.size = sizeof(context_t),
.init = init,
.exec = exec,
.unload = cleanup
};
| 2.25 | 2 |
2024-11-18T20:26:01.265086+00:00
| 2019-05-28T15:36:43 |
ad4b652bafcd4c91f336c361b21735c41239145f
|
{
"blob_id": "ad4b652bafcd4c91f336c361b21735c41239145f",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-28T15:36:43",
"content_id": "215064d625f0b2f4da7a2895026bf3024621d872",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "e2f05a06837c10fcd1ce9ee11311f87f4b42c955",
"extension": "c",
"filename": "io.c",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 186339230,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 310,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/sandia-hand/firmware/f2/std/io.c",
"provenance": "stackv2-0056.json.gz:257783",
"repo_name": "ldgcug/erlecopter_gazebo8",
"revision_date": "2019-05-28T15:36:43",
"revision_id": "22731c5abdca3c74b9e85c6550270c3db48aaa52",
"snapshot_id": "d1fef6540e19b04f3b68a99ef1c3bc75f76199f7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ldgcug/erlecopter_gazebo8/22731c5abdca3c74b9e85c6550270c3db48aaa52/sandia-hand/firmware/f2/std/io.c",
"visit_date": "2020-05-22T12:29:43.358184"
}
|
stackv2
|
#include "io.h"
#include "pins.h"
void io_led(bool on)
{
if (on)
PIO_Set(&pin_led);
else
PIO_Clear(&pin_led);
}
void io_led_toggle()
{
static int io_led_prev_state = 0;
if (io_led_prev_state)
PIO_Set(&pin_led);
else
PIO_Clear(&pin_led);
io_led_prev_state = !io_led_prev_state;
}
| 2.09375 | 2 |
2024-11-18T20:26:01.444856+00:00
| 2023-06-30T15:42:13 |
b637142d14165152b65d5cb20b3e843145be5023
|
{
"blob_id": "b637142d14165152b65d5cb20b3e843145be5023",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-24T13:35:30",
"content_id": "3f138982b3bba6f2d6de114266b6a2724cda0efc",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "54df06e1c0cdda4445838d203334d0615bd2cd40",
"extension": "c",
"filename": "stats_task.c",
"fork_events_count": 29,
"gha_created_at": "2017-07-21T17:46:49",
"gha_event_created_at": "2022-01-25T12:33:24",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 97973205,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8399,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/VNFs/DPPD-PROX/stats_task.c",
"provenance": "stackv2-0056.json.gz:258042",
"repo_name": "opnfv/samplevnf",
"revision_date": "2023-06-30T15:42:13",
"revision_id": "090efc9c81c8b1943d162249d965a3e40502d50e",
"snapshot_id": "b2a0ad40ee0a87f8476d8b182c1cf66b7b837ed8",
"src_encoding": "UTF-8",
"star_events_count": 24,
"url": "https://raw.githubusercontent.com/opnfv/samplevnf/090efc9c81c8b1943d162249d965a3e40502d50e/VNFs/DPPD-PROX/stats_task.c",
"visit_date": "2023-08-03T08:03:09.389406"
}
|
stackv2
|
/*
// Copyright (c) 2010-2017 Intel Corporation
//
// 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 <stddef.h>
#include "stats_task.h"
#include "prox_cfg.h"
#include "prox_globals.h"
#include "lconf.h"
struct lcore_task_stats {
struct task_stats task_stats[MAX_TASKS_PER_CORE];
};
#define TASK_STATS_RX 0x01
#define TASK_STATS_TX 0x02
extern int last_stat;
static struct lcore_task_stats lcore_task_stats_all[RTE_MAX_LCORE];
static struct task_stats *task_stats_set[RTE_MAX_LCORE * MAX_TASKS_PER_CORE];
static uint8_t nb_tasks_tot;
int stats_get_n_tasks_tot(void)
{
return nb_tasks_tot;
}
struct task_stats *stats_get_task_stats(uint32_t lcore_id, uint32_t task_id)
{
return &lcore_task_stats_all[lcore_id].task_stats[task_id];
}
struct task_stats_sample *stats_get_task_stats_sample(uint32_t lcore_id, uint32_t task_id, int l)
{
return &lcore_task_stats_all[lcore_id].task_stats[task_id].sample[l == last_stat];
}
void stats_task_reset(void)
{
struct task_stats *cur_task_stats;
for (uint8_t task_id = 0; task_id < nb_tasks_tot; ++task_id) {
cur_task_stats = task_stats_set[task_id];
cur_task_stats->tot_rx_pkt_count = 0;
cur_task_stats->tot_tx_pkt_count = 0;
cur_task_stats->tot_drop_tx_fail = 0;
cur_task_stats->tot_drop_discard = 0;
cur_task_stats->tot_drop_handled = 0;
cur_task_stats->tot_rx_non_dp = 0;
cur_task_stats->tot_tx_non_dp = 0;
}
}
uint64_t stats_core_task_tot_rx(uint8_t lcore_id, uint8_t task_id)
{
return lcore_task_stats_all[lcore_id].task_stats[task_id].tot_rx_pkt_count;
}
uint64_t stats_core_task_tot_tx(uint8_t lcore_id, uint8_t task_id)
{
return lcore_task_stats_all[lcore_id].task_stats[task_id].tot_tx_pkt_count;
}
uint64_t stats_core_task_tot_tx_fail(uint8_t lcore_id, uint8_t task_id)
{
return lcore_task_stats_all[lcore_id].task_stats[task_id].tot_drop_tx_fail;
}
uint64_t stats_core_task_tot_drop(uint8_t lcore_id, uint8_t task_id)
{
return lcore_task_stats_all[lcore_id].task_stats[task_id].tot_drop_tx_fail +
lcore_task_stats_all[lcore_id].task_stats[task_id].tot_drop_discard +
lcore_task_stats_all[lcore_id].task_stats[task_id].tot_drop_handled;
}
uint64_t stats_core_task_tot_tx_non_dp(uint8_t lcore_id, uint8_t task_id)
{
return lcore_task_stats_all[lcore_id].task_stats[task_id].tot_tx_non_dp;
}
uint64_t stats_core_task_tot_rx_non_dp(uint8_t lcore_id, uint8_t task_id)
{
return lcore_task_stats_all[lcore_id].task_stats[task_id].tot_rx_non_dp;
}
uint64_t stats_core_task_last_tsc(uint8_t lcore_id, uint8_t task_id)
{
return lcore_task_stats_all[lcore_id].task_stats[task_id].sample[last_stat].tsc;
}
static void init_core_port(struct task_stats *ts, struct task_rt_stats *stats, uint8_t flags)
{
ts->stats = stats;
ts->flags |= flags;
}
void stats_task_post_proc(void)
{
for (uint8_t task_id = 0; task_id < nb_tasks_tot; ++task_id) {
struct task_stats *cur_task_stats = task_stats_set[task_id];
const struct task_stats_sample *last = &cur_task_stats->sample[last_stat];
const struct task_stats_sample *prev = &cur_task_stats->sample[!last_stat];
/* no total stats for empty loops */
cur_task_stats->tot_rx_pkt_count += last->rx_pkt_count - prev->rx_pkt_count;
cur_task_stats->tot_tx_pkt_count += last->tx_pkt_count - prev->tx_pkt_count;
cur_task_stats->tot_drop_tx_fail += last->drop_tx_fail - prev->drop_tx_fail;
cur_task_stats->tot_drop_discard += last->drop_discard - prev->drop_discard;
cur_task_stats->tot_drop_handled += last->drop_handled - prev->drop_handled;
cur_task_stats->tot_rx_non_dp += last->rx_non_dp - prev->rx_non_dp;
cur_task_stats->tot_tx_non_dp += last->tx_non_dp - prev->tx_non_dp;
}
}
void stats_task_update(void)
{
uint64_t before, after;
for (uint8_t task_id = 0; task_id < nb_tasks_tot; ++task_id) {
struct task_stats *cur_task_stats = task_stats_set[task_id];
struct task_rt_stats *stats = cur_task_stats->stats;
struct task_stats_sample *last = &cur_task_stats->sample[last_stat];
/* Read TX first and RX second, in order to prevent displaying
a negative packet loss. Depending on the configuration
(when forwarding, for example), TX might be bigger than RX. */
before = rte_rdtsc();
last->tx_pkt_count = stats->tx_pkt_count;
last->drop_tx_fail = stats->drop_tx_fail;
last->drop_discard = stats->drop_discard;
last->drop_handled = stats->drop_handled;
last->rx_pkt_count = stats->rx_pkt_count;
last->empty_cycles = stats->idle_cycles;
last->tx_bytes = stats->tx_bytes;
last->rx_bytes = stats->rx_bytes;
last->drop_bytes = stats->drop_bytes;
last->rx_non_dp = stats->rx_non_dp;
last->tx_non_dp = stats->tx_non_dp;
after = rte_rdtsc();
last->tsc = (before >> 1) + (after >> 1);
}
}
void stats_task_get_host_rx_tx_packets(uint64_t *rx, uint64_t *tx, uint64_t *tsc)
{
const struct task_stats *t;
*rx = 0;
*tx = 0;
for (uint8_t task_id = 0; task_id < nb_tasks_tot; ++task_id) {
t = task_stats_set[task_id];
if (t->flags & TASK_STATS_RX)
*rx += t->tot_rx_pkt_count;
if (t->flags & TASK_STATS_TX)
*tx += t->tot_tx_pkt_count;
}
if (nb_tasks_tot)
*tsc = task_stats_set[nb_tasks_tot - 1]->sample[last_stat].tsc;
}
/* Populate active_stats_set for stats reporting, the order of the
cores is important for gathering the most accurate statistics. TX
cores should be updated before RX cores (to prevent negative Loss
stats). The total number of tasks are saved in nb_tasks_tot. */
void stats_task_init(void)
{
struct lcore_cfg *lconf;
uint32_t lcore_id;
/* add cores that are receiving from and sending to physical ports first */
lcore_id = -1;
while(prox_core_next(&lcore_id, 0) == 0) {
lconf = &lcore_cfg[lcore_id];
for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
struct task_args *targ = &lconf->targs[task_id];
struct task_rt_stats *stats = &lconf->tasks_all[task_id]->aux->stats;
if (targ->nb_rxrings == 0 && targ->nb_txrings == 0) {
struct task_stats *ts = &lcore_task_stats_all[lcore_id].task_stats[task_id];
init_core_port(ts, stats, TASK_STATS_RX | TASK_STATS_TX);
task_stats_set[nb_tasks_tot++] = ts;
}
}
}
/* add cores that are sending to physical ports second */
lcore_id = -1;
while(prox_core_next(&lcore_id, 0) == 0) {
lconf = &lcore_cfg[lcore_id];
for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
struct task_args *targ = &lconf->targs[task_id];
struct task_rt_stats *stats = &lconf->tasks_all[task_id]->aux->stats;
if (targ->nb_rxrings != 0 && targ->nb_txrings == 0) {
struct task_stats *ts = &lcore_task_stats_all[lcore_id].task_stats[task_id];
init_core_port(ts, stats, TASK_STATS_TX);
task_stats_set[nb_tasks_tot++] = ts;
}
}
}
/* add cores that are receiving from physical ports third */
lcore_id = -1;
while(prox_core_next(&lcore_id, 0) == 0) {
lconf = &lcore_cfg[lcore_id];
for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
struct task_args *targ = &lconf->targs[task_id];
struct task_rt_stats *stats = &lconf->tasks_all[task_id]->aux->stats;
if (targ->nb_rxrings == 0 && targ->nb_txrings != 0) {
struct task_stats *ts = &lcore_task_stats_all[lcore_id].task_stats[task_id];
init_core_port(ts, stats, TASK_STATS_RX);
task_stats_set[nb_tasks_tot++] = ts;
}
}
}
/* add cores that are working internally (no physical ports attached) */
lcore_id = -1;
while(prox_core_next(&lcore_id, 0) == 0) {
lconf = &lcore_cfg[lcore_id];
for (uint8_t task_id = 0; task_id < lconf->n_tasks_all; ++task_id) {
struct task_args *targ = &lconf->targs[task_id];
struct task_rt_stats *stats = &lconf->tasks_all[task_id]->aux->stats;
if (targ->nb_rxrings != 0 && targ->nb_txrings != 0) {
struct task_stats *ts = &lcore_task_stats_all[lcore_id].task_stats[task_id];
init_core_port(ts, stats, 0);
task_stats_set[nb_tasks_tot++] = ts;
}
}
}
}
| 2.1875 | 2 |
2024-11-18T20:26:01.593578+00:00
| 2016-05-29T09:16:42 |
9622c3d13e35bac1044d52afd750d6b40add4f06
|
{
"blob_id": "9622c3d13e35bac1044d52afd750d6b40add4f06",
"branch_name": "refs/heads/master",
"committer_date": "2016-05-29T09:16:42",
"content_id": "576c9c22098cb702359bb9cc6faa26e1c7fe5f7a",
"detected_licenses": [
"NCSA"
],
"directory_id": "3d80d68564da1f1d650988a1fafe221d749cdc31",
"extension": "c",
"filename": "klee_range.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 189500579,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 809,
"license": "NCSA",
"license_type": "permissive",
"path": "/runtime/Intrinsic/klee_range.c",
"provenance": "stackv2-0056.json.gz:258298",
"repo_name": "heyitsanthony/klee-mc",
"revision_date": "2016-05-29T09:16:42",
"revision_id": "184a809930c4f7823526a11474b1446dd7d92afb",
"snapshot_id": "ede73456fa0e928e67529ae19ae4723d483acfd3",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/heyitsanthony/klee-mc/184a809930c4f7823526a11474b1446dd7d92afb/runtime/Intrinsic/klee_range.c",
"visit_date": "2020-05-30T03:18:24.188711"
}
|
stackv2
|
//===-- klee_range.c ------------------------------------------------------===//
//
// The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <assert.h>
#include <klee/klee.h>
int64_t klee_range(int64_t start, int64_t end, const char* name)
{
int64_t x;
if (start >= end)
klee_uerror("invalid range", "user");
if (start+1==end)
return start;
klee_make_symbolic(&x, sizeof x, name);
if (start==0) {
/* Make nicer constraint when simple... */
klee_assume_ult(x, end);
} else {
klee_assume_sge(x, start); /* x >= start */
klee_assume_slt(x, end); /* x < end */
}
return x;
}
| 2.28125 | 2 |
2024-11-18T20:26:01.751669+00:00
| 2013-01-08T02:24:14 |
25256a455abcb70bd625b846a5c36cc824b6aa87
|
{
"blob_id": "25256a455abcb70bd625b846a5c36cc824b6aa87",
"branch_name": "refs/heads/master",
"committer_date": "2013-01-08T02:24:14",
"content_id": "b41f718368aed7cc30121e3663bbbe6e8bf7cfa2",
"detected_licenses": [
"MIT"
],
"directory_id": "d4564ea02cbf86d768b265f807f7ae64417d6a1f",
"extension": "h",
"filename": "decisiontree.h",
"fork_events_count": 5,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 2807894,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 938,
"license": "MIT",
"license_type": "permissive",
"path": "/decisiontree.h",
"provenance": "stackv2-0056.json.gz:258557",
"repo_name": "2hanson/DecisionTree",
"revision_date": "2013-01-08T02:24:14",
"revision_id": "ee82f45163a8741d226a5e6f849d3d1aec8ee452",
"snapshot_id": "a06c5a88bdf768de73b0132b659d0a8e8660f54b",
"src_encoding": "UTF-8",
"star_events_count": 8,
"url": "https://raw.githubusercontent.com/2hanson/DecisionTree/ee82f45163a8741d226a5e6f849d3d1aec8ee452/decisiontree.h",
"visit_date": "2021-01-01T05:37:17.231693"
}
|
stackv2
|
//Copyright at ICT
#define MAXLEN 100
#define MAXLEVELNUM 200
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef struct
{
char attributeName[MAXLEN];
char **attributes;
int attributeNum;
int isConsecutive; // isConsecutive == 1, then it is consecutive
int splitValue; //if is consecutive, the value is the split point;
int *attributeValue;
}AttributeMap;
typedef struct tree_node
{
uint32_t classify;
uint32_t selfLevel;
uint32_t majorClass;
uint32_t pathAttributeName[MAXLEVELNUM];
uint32_t pathAttributeValue[MAXLEVELNUM];
uint32_t pathFlag[MAXLEVELNUM];
struct tree_node* childNode;
struct tree_node* siblingNode;
struct tree_node* nextInnerNode;
struct tree_node* preLeaf;
struct tree_node* nextLeaf;
uint32_t isLeaf;
double infoGainRatio;
}TreeNode;
| 2.109375 | 2 |
2024-11-18T20:59:39.098027+00:00
| 2017-01-14T17:26:11 |
0ec0c2812df8d1c287cd7361183a78afe99870af
|
{
"blob_id": "0ec0c2812df8d1c287cd7361183a78afe99870af",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-14T17:26:11",
"content_id": "53810f2820710fc0d4c5535f168c3a9075e98af6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5e7c64bccab2f2465dd4ab31428481daccadb71d",
"extension": "c",
"filename": "serialize.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": 2370,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/common/serialize.c",
"provenance": "stackv2-0058.json.gz:498",
"repo_name": "xianlimei/CPS",
"revision_date": "2017-01-14T17:26:11",
"revision_id": "29d4892cf07b350ffa246f477d841628f4ea6cdb",
"snapshot_id": "66a6b08a56ce3827da1857fa1e08d47865dc0f03",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xianlimei/CPS/29d4892cf07b350ffa246f477d841628f4ea6cdb/src/common/serialize.c",
"visit_date": "2020-04-19T21:59:30.774099"
}
|
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.
*/
#include "serialize.h"
membuffer *serialize_syscall_info(syscall_intercept_info *i){
membuffer *buffer = new(sizeof(membuffer));
buffer->data = NULL;
buffer->len = 0;
if(!add_chunk(buffer, (void *)i->pname, strlen(i->pname) + 1)){
return NULL;
}
if(!add_chunk(buffer, (void *)&i->pid, sizeof(pid_t))){
return NULL;
}
if(!add_chunk(buffer, (void *)i->operation, strlen(i->operation) + 1)){
return NULL;
}
if(!add_chunk(buffer, (void *)i->path, strlen(i->path) + 1)){
return NULL;
}
if(!add_chunk(buffer, (void *)i->result, strlen(i->result) + 1)){
return NULL;
}
if(!add_chunk(buffer, (void *)i->details, strlen(i->details) + 1)){
return NULL;
}
if(!add_chunk(buffer, (void *)&i->proc_inum, sizeof(unsigned int))) {
return NULL;
}
if(!add_chunk(buffer, (void *)&i->devid, sizeof(dev_t))) {
return NULL;
}
return buffer;
}
int add_chunk(membuffer *buffer, void *chunk, size_t size){
byte *tmp;
if(buffer->data == NULL){
tmp = new(sizeof(size_t) + size);
if(!tmp){
return 0;
}else{
buffer->data = tmp;
}
buffer->len = sizeof(size_t) + size;
memcpy(buffer->data, &size, sizeof(size_t));
memcpy(buffer->data + sizeof(size_t), chunk, size);
}else{
tmp = renew(buffer->data, buffer->len + sizeof(size_t) + size);
if(!tmp){
del(buffer->data);
del(buffer);
return 0;
}else{
buffer->data = tmp;
}
memcpy(buffer->data + buffer->len, &size, sizeof(size_t));
memcpy(buffer->data + buffer->len + sizeof(size_t), chunk, size);
buffer->len += sizeof(size_t) + size;
}
return 1;
}
| 2.171875 | 2 |
2024-11-18T20:59:39.357864+00:00
| 2022-01-31T04:36:44 |
752c261d500b634a549272bf2293b82c9528c2ef
|
{
"blob_id": "752c261d500b634a549272bf2293b82c9528c2ef",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-31T04:36:44",
"content_id": "3a81f0c74e859c6db05aa31a552b62d9e28f84cb",
"detected_licenses": [
"MIT"
],
"directory_id": "e1c02087e71617b1bdfb6ed8f139a35f0e8ce9c7",
"extension": "c",
"filename": "if-not-boolean.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 186742104,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 258,
"license": "MIT",
"license_type": "permissive",
"path": "/c/if-not-boolean.c",
"provenance": "stackv2-0058.json.gz:627",
"repo_name": "CrazyJ36/c",
"revision_date": "2022-01-31T04:36:44",
"revision_id": "ac37b0af76ef273199eeb0d3796549cc6bd06dc0",
"snapshot_id": "fe21422de23ac93d3e6f8c3e20e1d45ddb55a33a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CrazyJ36/c/ac37b0af76ef273199eeb0d3796549cc6bd06dc0/c/if-not-boolean.c",
"visit_date": "2022-02-06T01:43:51.313389"
}
|
stackv2
|
/* If not boolean. typed as:
if (!(expression)) {
}
Put the '!' expression in perenthesis
due to precedence.
*/
#include <stdio.h>
int main()
{
int x = 2;
printf("x is 2\n");
if (!(x < 1)) {
printf("x is not less than 1\n");
}
}
| 3.109375 | 3 |
2024-11-18T19:02:21.231157+00:00
| 2016-12-09T14:15:11 |
332cc7d16653aef7bc3168006bbe01c262a79bb0
|
{
"blob_id": "332cc7d16653aef7bc3168006bbe01c262a79bb0",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-09T14:15:11",
"content_id": "52bb4885bfbc228d4ab99c103c85e36a93189031",
"detected_licenses": [
"MIT"
],
"directory_id": "1339ce384f187897a6300186da8fde33305484f5",
"extension": "c",
"filename": "i2c0-master.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 14237848,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6382,
"license": "MIT",
"license_type": "permissive",
"path": "/klipos/hw/drivers/lpc1xxx/i2c/i2c0-master.c",
"provenance": "stackv2-0058.json.gz:149704",
"repo_name": "batitous/klipos",
"revision_date": "2016-12-09T14:15:11",
"revision_id": "d42bca3dd584e102b6e7b2fbd006b61f6900b9e5",
"snapshot_id": "bf8b36136a5d88d3f7bc56202690490617068ab5",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/batitous/klipos/d42bca3dd584e102b6e7b2fbd006b61f6900b9e5/klipos/hw/drivers/lpc1xxx/i2c/i2c0-master.c",
"visit_date": "2020-12-13T04:20:25.096746"
}
|
stackv2
|
/*
The MIT License (MIT)
Copyright (c) 2013 Baptiste Burles, Christophe Casson, Sylvain Fay-Chatelard
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 "i2c-master-common.h"
static uint32_t i2c0_write(uint8_t data);
#define I2C_CNT 65536
static uint32_t private_i2c0_getStat(void)
{
uint32_t cnt = I2C_CNT;
while( (I2C_I2CONSET & 0x08) == 0)
{
cnt--;
waitSomeTimeInUs(1);
if(cnt==0)
{
return I2C_TIMEOUT;
}
}
return 0;
}
#define GET_I2C_STATUS() if( private_i2c0_getStat()!=0){ return I2C_TIMEOUT;}\
status = I2C_I2STAT
static uint32_t private_i2c0_send(uint8_t data)
{
uint32_t cnt = I2C_CNT;
while( i2c0_write(data) == I2C_BUSY)
{
cnt--;
waitSomeTimeInUs(1);
if(cnt==0)
{
return I2C_TIMEOUT;
}
}
return 0;
}
#define SEND_AND_WAIT(data) if( private_i2c0_send(data)!=0) { return I2C_TIMEOUT;}\
if( i2c0_wait_after_write() != I2C_OK) return I2C_ERROR_SEND
#define SEND_ACK() I2C_I2CONSET |= 0x04; /*AA=1*/ I2C_I2CONCLR = 0x08 /*clear SI flag*/
#define SEND_NACK() I2C_I2CONCLR = 0x04; I2C_I2CONCLR = 0x08 /*clear SI flag*/
static uint32_t i2c0_start(void)
{
// uint32_t cnt;
uint32_t result;
uint8_t status;
//start
I2C_I2CONSET = 0x20;
while(1)
{
GET_I2C_STATUS();
//start transmitted
if((status == 0x08) || (status == 0x10))
{
result = I2C_OK;
break;
}
//error
else if(status != 0xf8)
{
result = I2C_ERROR;
break;
}
else
{
//clear SI flag
I2C_I2CONCLR = 0x08;
}
}
//clear start flag
I2C_I2CONCLR = 0x20;
return result;
}
static void i2c0_stop(void)
{
uint32_t cnt = I2C_CNT;
I2C_I2CONSET |= 0x10; //STO = 1, set stop flag
I2C_I2CONCLR = 0x08; //clear SI flag
//wait for STOP detected (while STO = 1)
while((I2C_I2CONSET & 0x10) == 0x10)
{
cnt--;
waitSomeTimeInUs(1);
if(cnt==0)
{
return;
}
}
}
static uint32_t i2c0_write(uint8_t data)
{
//check if I2C Data register can be accessed
if((I2C_I2CONSET & 0x08) != 0) //if SI = 1
{
/* send data */
I2C_I2DAT = data;
I2C_I2CONCLR = 0x08; //clear SI flag
return I2C_OK;
}
else
{
//data register not ready
return I2C_BUSY;
}
}
static uint32_t i2c0_wait_after_write(void)
{
uint8_t status;
//DebugPrintf("i2c0_wait_after_write\r\n");
//wait until data transmitted
while(1)
{
//get new status
GET_I2C_STATUS();
/*
* SLA+W transmitted, ACK received or
* data byte transmitted, ACK received
*/
if( (status == 0x18) || (status == 0x28) )
{
//data transmitted and ACK received
return I2C_OK;
}
//no relevant status information
else if(status != 0xf8 )
{
//DebugPrintf("i2c0_wait_after_write status = %x\r\n", status);
return I2C_ERROR;
}
}
}
static uint32_t i2c0_read(uint8_t *data)
{
//check if I2C Data register can be accessed
if((I2C_I2CONSET & 0x08) != 0) //SI = 1
{
//read data
*data = I2C_I2DAT;
return I2C_OK;
}
else
{
//No data available
return I2C_EMPTY;
}
}
uint32_t sendBufferToI2c0(uint8_t addr, uint8_t *buffer, uint32_t len)
{
uint32_t i;
//send start condition
if(i2c0_start()!=I2C_OK)
{
//i2c0_stop();
//DebugPrintf("SendBufferToI2C0.i2c0_start\r\n");
return I2C_ERROR_START;
}
//send address
SEND_AND_WAIT(addr);
for(i=0;i<len;i++)
{
SEND_AND_WAIT(buffer[i]);
}
i2c0_stop();
//DebugPrintf("SendBufferToI2C0 I2C_OK\r\n");
return I2C_OK;
}
uint32_t getBufferFromI2c0(uint8_t addr, uint8_t *buffer, uint32_t len)
{
uint32_t i;
uint8_t status;
uint8_t *ptr;
ptr = buffer;
if( i2c0_start()!=I2C_OK)
{
//DebugPrintf("GetBufferFromI2C0.i2c0_start I2C_ERROR\r\n");
//i2c0_stop();
return I2C_ERROR;
}
addr = addr|1;
while( i2c0_write(addr) == I2C_BUSY);
for(i=0;i<len;i++)
{
while(1)
{
GET_I2C_STATUS();
/*
* SLA+R transmitted, ACK received or
* SLA+R transmitted, ACK not received
* data byte received in master mode, ACK transmitted
*/
if((status == 0x40 ) || (status == 0x48 ) || (status == 0x50 ))
{
if(i==len-1)
{
SEND_NACK();
}
else
{
SEND_ACK();
}
while(i2c0_read(ptr)==I2C_EMPTY);
ptr++;
break;
}
else if(status != 0xf8 )
{
i2c0_stop();
//DebugPrintf("GetBufferFromI2C0 I2C_ERROR\r\n");
return I2C_ERROR;
}
}//while(1)
}//for
i2c0_stop();
return I2C_OK;
}
| 2.265625 | 2 |
2024-11-18T19:02:21.322527+00:00
| 2016-10-07T23:03:46 |
4a2df1d6a5920059960dc4cd6c0ba9674a4d93fd
|
{
"blob_id": "4a2df1d6a5920059960dc4cd6c0ba9674a4d93fd",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-07T23:03:46",
"content_id": "bb2027e250a602e9e69bbfb1c75b0165a39f555e",
"detected_licenses": [
"MIT"
],
"directory_id": "b98c20d5242010bcd533ea52444dadc44c8e6c5a",
"extension": "c",
"filename": "server.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3119,
"license": "MIT",
"license_type": "permissive",
"path": "/server.c",
"provenance": "stackv2-0058.json.gz:149833",
"repo_name": "zmumbauer/gw-http",
"revision_date": "2016-10-07T23:03:46",
"revision_id": "1bc2c8051a34eabf27b86b0b6fb7f60077c6e7dd",
"snapshot_id": "c29070e6f6ff75b6d2e32bc1956df5da2cc8ed1a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zmumbauer/gw-http/1bc2c8051a34eabf27b86b0b6fb7f60077c6e7dd/server.c",
"visit_date": "2021-06-06T02:45:42.142017"
}
|
stackv2
|
/**
* MIT License
*
* Copyright (c) 2012 Gabriel Parmer
*
* 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 <sys/types.h>
#include <sys/socket.h>
//#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <arpa/inet.h>
// #include <malloc.h>
#include <unistd.h>
/*
* Create the file descriptor to accept on. Return -1 otherwise.
*/
int
server_create(short int port)
{
// Creates a new file descriptor
int fd;
// Create new sockaddr_in struct (declared in library)
struct sockaddr_in server;
// Check if socket is not established
if ((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("Establishing socket");
// Return error code
return -1;
}
// Set value to default values Address Family(AF) vs Protocol Family (PF)
server.sin_family = AF_INET;
// Set port value to passed in port
server.sin_port = htons(port);
// Uses inet_aton function (in library) to get host address
// INADDR_ANY allows unknown host IP
server.sin_addr.s_addr = htonl(INADDR_ANY);
// Binds the socket (fd) to the server
if (bind(fd, (struct sockaddr *)&server, sizeof(server))) {
perror("binding receive socket");
return -1;
}
// Permits accepting incoming connections, adds a queue limit (10)
if(listen(fd, 10) < 0) {
perror("listen call failed");
return -1;
}
// Returns the file descriptor (socket)
return fd;
}
/*
* Pass in the accept file descriptor returned from
* server_create. Return a new file descriptor or -1 on error.
*/
int
server_accept(int fd)
{
// Create new sockaddr_in struct (declared in library)
struct sockaddr_in sai;
// Creates new file descriptor
int new_fd;
// Creates a variable for the length of the sai struct
unsigned int len = sizeof(sai);
// Sets the local file descriptor to an accepted file descriptor
new_fd = accept(fd, (struct sockaddr *)&sai, &len);
// Error handling
if (-1 == new_fd) {
perror("accept");
return -1;
}
// Returns accepted file descriptor
return new_fd;
}
| 2.75 | 3 |
2024-11-18T19:02:21.520391+00:00
| 2018-01-30T05:13:25 |
a3ddc5aeb4edefba1e69518921a34a251473df91
|
{
"blob_id": "a3ddc5aeb4edefba1e69518921a34a251473df91",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-30T05:13:25",
"content_id": "fc1e04e12f45cef895d531e23fe6f92d54481d7d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "25c4c0f5d7fd6f8708f13f2d13eb585bf4abc987",
"extension": "c",
"filename": "n-control.c",
"fork_events_count": 0,
"gha_created_at": "2015-11-19T11:20:10",
"gha_event_created_at": "2015-11-19T11:20:11",
"gha_language": null,
"gha_license_id": null,
"github_id": 46487619,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 31818,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/core/n-control.c",
"provenance": "stackv2-0058.json.gz:150091",
"repo_name": "IngoHohmann/ren-c",
"revision_date": "2018-01-30T05:13:25",
"revision_id": "970396baf2d3c6a7a4eb2635e4f63b3b6cd6028f",
"snapshot_id": "7c704619fd050f7ec1d63c5a834fed713f73ec62",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/IngoHohmann/ren-c/970396baf2d3c6a7a4eb2635e4f63b3b6cd6028f/src/core/n-control.c",
"visit_date": "2021-01-16T22:15:26.751130"
}
|
stackv2
|
//
// File: %n-control.c
// Summary: "native functions for control flow"
// Section: natives
// Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)"
// Homepage: https://github.com/metaeducation/ren-c/
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2012 REBOL Technologies
// Copyright 2012-2017 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information.
//
// 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.
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Control constructs in Ren-C differ from R3-Alpha in some ways:
//
// * If they do not run their body, they evaluate to void ("unset!") and not
// blank ("none!"). Otherwise the last result of the body evaluation, as
// in R3-Alpha and Rebol2...but this is forced to blank if it was void,
// so that THEN and ELSE can distinguish whether a condition ran.
//
// * It is possible to ask the return result to not be "blankified", but
// give back the possibly-void value, with the /ONLY refinement. This is
// specialized as functions ending in *. (IF*, EITHER*, CASE*, SWITCH*...)
//
// * Other specializations exist returning a logic of whether the body ever
// ran by using the /? refinement. So CASE? does not return the branch
// values, just true or false based on whether a branch ran. This is
// based on testing the result for void.
//
// * Zero-arity function values used as branches will be executed, and
// single-arity functions used as branches will also be executed--but passed
// the value of the triggering condition. See Run_Branch_Throws().
//
// * If the /ONLY option is not used, then there is added checking on the
// condition and branches. The condition is not allowed to be a literal
// block, e.g. `[x = 10]`, but may be an expression evaluating to a block.
// The branches are not allowed to be evaluative *unless* they evaluate to
// a block...literals such as strings or integers may be used, but not
// variables or expressions that evaluate to strings or integers.
//
#include "sys-core.h"
//
// if: native [
//
// {If TRUTHY? condition, take branch (blocks and functions evaluated)}
//
// return: [<opt> any-value!]
// {void on FALSEY? condition, else branch result (BLANK! if void)}
// condition [any-value!]
// branch [block! function!]
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(if)
{
INCLUDE_PARAMS_OF_IF;
if (IS_CONDITIONAL_FALSE(ARG(condition), REF(only)))
return R_VOID;
if (Run_Branch_Throws(D_OUT, ARG(condition), ARG(branch), REF(only)))
return R_OUT_IS_THROWN;
return R_OUT;
}
//
// unless: native [
//
// {If FALSEY? condition, take branch (blocks and functions evaluated)}
//
// return: [<opt> any-value!]
// {void on TRUTHY? condition, else branch result (BLANK! if void)}
// condition [any-value!]
// branch [block! function!]
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(unless)
{
INCLUDE_PARAMS_OF_UNLESS;
if (IS_CONDITIONAL_TRUE(ARG(condition), REF(only)))
return R_VOID;
if (Run_Branch_Throws(D_OUT, ARG(condition), ARG(branch), REF(only)))
return R_OUT_IS_THROWN;
return R_OUT;
}
//
// either: native [
//
// {If TRUTHY? condition, take first branch, else take second branch.}
//
// return: [<opt> any-value!]
// condition [any-value!]
// true-branch [block! function!]
// false-branch [block! function!]
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(either)
{
INCLUDE_PARAMS_OF_EITHER;
if (Run_Branch_Throws(
D_OUT,
ARG(condition),
IS_CONDITIONAL_TRUE(ARG(condition), REF(only))
? ARG(true_branch)
: ARG(false_branch),
REF(only)
)){
return R_OUT_IS_THROWN;
}
return R_OUT;
}
//
// either-test: native [
//
// {If value passes test, return that value, otherwise take the branch.}
//
// return: [<opt> any-value!]
// {Input value if it matched, or branch result (BLANK! if void)}
// test [function! datatype! typeset! block! logic!]
// {Typeset membership, LOGIC! to test TRUTHY?, filter function}
// value [<opt> any-value!]
// branch [block! function!]
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(either_test)
{
INCLUDE_PARAMS_OF_EITHER_TEST;
REBVAL *test = ARG(test);
REBVAL *value = ARG(value);
if (IS_LOGIC(test)) {
if (IS_VOID(value) || VAL_LOGIC(test) != IS_TRUTHY(value))
goto test_failed;
return R_FROM_BOOL(VAL_LOGIC(test));
}
// Force single items into array style access so only one version of the
// code needs to be written.
//
RELVAL *item;
REBSPC *specifier;
if (IS_BLOCK(test)) {
item = VAL_ARRAY_AT(test);
specifier = VAL_SPECIFIER(test);
}
else {
Move_Value(D_CELL, test);
item = D_CELL; // implicitly terminated
specifier = SPECIFIED;
}
REB_R r; // goto crosses initialization
r = R_UNHANDLED;
for (; NOT_END(item); ++item) {
//
// If we're dealing with a single item for the test, provided e.g.
// as :even?, then it's already fetched. But if it was a block like
// [:even? integer!] we enumerate it in word form and have to get it.
//
const RELVAL *var = IS_WORD(item)
? Get_Opt_Var_May_Fail(item, specifier)
: item;
if (IS_DATATYPE(var)) {
if (VAL_TYPE_KIND(var) == VAL_TYPE(value))
r = R_TRUE; // any type matching counts
else if (r == R_UNHANDLED)
r = R_FALSE; // at least one type has to speak up now
}
else if (IS_TYPESET(var)) {
if (TYPE_CHECK(var, VAL_TYPE(value)))
r = R_TRUE; // any typeset matching counts
else if (r == R_UNHANDLED)
r = R_FALSE; // at least one type has to speak up now
}
else if (IS_FUNCTION(var)) {
const REBOOL fully = TRUE;
if (Apply_Only_Throws(D_OUT, fully, const_KNOWN(var), value, END))
return R_OUT_IS_THROWN;
if (IS_VOID(D_OUT))
fail (Error_No_Return_Raw());
if (IS_FALSEY(D_OUT))
goto test_failed; // any function failing breaks it
// At least one function matching tips the balance, but
// can't alone outmatch no types matching, if any types
// were matched at all.
//
if (r == R_UNHANDLED)
r = R_TRUE;
continue;
}
else
fail (Error_Invalid_Type(VAL_TYPE(var)));
}
if (r == R_UNHANDLED) {
//
// !!! When the test is just [], what's that? People aren't likely to
// write it literally, but it could happen from a COMPOSE or similar.
//
fail ("No tests found in EITHER-TEST.");
}
if (r == R_FALSE) {
//
// This means that some types didn't match and were not later
// redeemed by a type that did match. Consider it failure.
//
goto test_failed;
}
// Someone spoke up for test success and was not overridden.
//
assert(r == R_TRUE);
Move_Value(D_OUT, ARG(value));
return R_OUT;
test_failed:
if (Run_Branch_Throws(D_OUT, ARG(value), ARG(branch), REF(only)))
return R_OUT_IS_THROWN;
return R_OUT;
}
//
// either-test-void: native [
//
// {If value is void, return void, otherwise take the branch.}
//
// return: [<opt> any-value!]
// {Void if input is void, or branch result (BLANK! if void)}
// value [<opt> any-value!]
// branch [block! function!]
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(either_test_void)
//
// Native optimization of `specialize 'either-test-value [test: :void?]`
// Worth it to write because this is the functionality enfixed as ALSO.
{
INCLUDE_PARAMS_OF_EITHER_TEST_VOID;
if (IS_VOID(ARG(value)))
return R_VOID;
if (Run_Branch_Throws(D_OUT, ARG(value), ARG(branch), REF(only)))
return R_OUT_IS_THROWN;
return R_OUT;
}
//
// either-test-value: native [
//
// {If value is not void, return the value, otherwise take the branch.}
//
// return: [<opt> any-value!]
// {Input value if not void, or branch result (BLANK! if void)}
// value [<opt> any-value!]
// branch [block! function!]
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(either_test_value)
//
// Native optimization of `specialize 'either-test-value [test: :any-value?]`
// Worth it to write because this is the functionality enfixed as ELSE.
{
INCLUDE_PARAMS_OF_EITHER_TEST_VALUE;
if (!IS_VOID(ARG(value))) {
Move_Value(D_OUT, ARG(value));
return R_OUT;
}
if (Run_Branch_Throws(D_OUT, ARG(value), ARG(branch), REF(only)))
return R_OUT_IS_THROWN;
return R_OUT;
}
//
// all: native [
//
// {Short-circuiting variant of AND, using a block of expressions as input.}
//
// return: [<opt> any-value!]
// {Product of last evaluation if all TRUE?, else a BLANK! value.}
// block [block!]
// "Block of expressions. Void evaluations are ignored."
// ]
//
REBNATIVE(all)
{
INCLUDE_PARAMS_OF_ALL;
assert(IS_END(D_OUT)); // guaranteed by the evaluator
DECLARE_FRAME (f);
Push_Frame(f, ARG(block));
while (FRM_HAS_MORE(f)) {
if (Do_Next_In_Frame_Throws(D_CELL, f)) {
Drop_Frame(f);
Move_Value(D_OUT, D_CELL);
return R_OUT_IS_THROWN;
}
if (IS_VOID(D_CELL)) // voids do not "vote" true or false
continue;
if (IS_FALSEY(D_CELL)) { // a failed ALL returns BLANK!
Drop_Frame(f);
return R_BLANK;
}
Move_Value(D_OUT, D_CELL); // preserve (not overwritten by later voids)
}
Drop_Frame(f);
// If IS_END(out), no successes or failures found (all opt-outs)
//
return R_OUT_VOID_IF_UNWRITTEN;
}
//
// any: native [
//
// {Short-circuiting version of OR, using a block of expressions as input.}
//
// return: [<opt> any-value!]
// {The first TRUE? evaluative result, or BLANK! value if all FALSE?}
// block [block!]
// "Block of expressions. Void evaluations are ignored."
// ]
//
REBNATIVE(any)
{
INCLUDE_PARAMS_OF_ANY;
DECLARE_FRAME (f);
Push_Frame(f, ARG(block));
REBOOL voted = FALSE;
while (FRM_HAS_MORE(f)) {
if (Do_Next_In_Frame_Throws(D_OUT, f)) {
Drop_Frame(f);
return R_OUT_IS_THROWN;
}
if (IS_VOID(D_OUT)) // voids do not "vote" true or false
continue;
if (IS_TRUTHY(D_OUT)) { // successful ANY returns the value
Drop_Frame(f);
return R_OUT;
}
voted = TRUE; // signal at least one non-void result was seen
}
Drop_Frame(f);
if (voted)
return R_BLANK;
return R_VOID; // all opt-outs
}
//
// none: native [
//
// {Short circuiting version of NOR, using a block of expressions as input.}
//
// return: [<opt> bar! blank!]
// {TRUE if all expressions are FALSE?, or BLANK if any are TRUE?}
// block [block!]
// "Block of expressions. Void evaluations are ignored."
// ]
//
REBNATIVE(none)
//
// !!! In order to reduce confusion and accidents in the near term, the
// %mezz-legacy.r renames this to NONE-OF and makes NONE report an error.
{
INCLUDE_PARAMS_OF_NONE;
DECLARE_FRAME (f);
Push_Frame(f, ARG(block));
REBOOL voted = FALSE;
while (FRM_HAS_MORE(f)) {
if (Do_Next_In_Frame_Throws(D_OUT, f)) {
Drop_Frame(f);
return R_OUT_IS_THROWN;
}
if (IS_VOID(D_OUT)) // voids do not "vote" true or false
continue;
if (IS_TRUTHY(D_OUT)) { // any true results mean failure
Drop_Frame(f);
return R_BLANK;
}
voted = TRUE; // signal that at least one non-void result was seen
}
Drop_Frame(f);
if (voted)
return R_BAR;
return R_VOID; // all opt-outs
}
// Shared code for CASE (which runs BLOCK! clauses as code) and CHOOSE (which
// returns values as-is, e.g. `choose [true [print "hi"]]` => `[print "hi]`
//
static REB_R Case_Choose_Core(
REBVAL *out,
REBVAL *cell, // scratch "D_CELL", GC safe (and implicitly terminated)
REBVAL *block, // "choices" or "cases", GC safe
REBOOL all,
REBOOL only,
REBOOL choose // do not evaluate blocks, just "choose" them
){
DECLARE_FRAME (f);
Push_Frame(f, block);
// With the block argument pushed in the enumerator, that frame slot is
// available for scratch space in the rest of the routine.
while (FRM_HAS_MORE(f)) {
if (IS_BAR(f->value)) { // interstitial BAR! legal, `case [1 2 | 3 4]`
Fetch_Next_In_Frame(f);
continue;
}
// Perform a DO/NEXT's worth of evaluation on a "condition" to test
if (Do_Next_In_Frame_Throws(cell, f)) {
Move_Value(out, cell);
Drop_Frame(f);
return R_OUT_IS_THROWN;
}
if (IS_VOID(cell)) // no void conditions allowed (as with IF)
fail (Error_No_Return_Raw());
if (FRM_AT_END(f)) // require conditions and branches in pairs
fail (Error_Past_End_Raw());
if (IS_BAR(f->value)) // BAR! out of sync between condition and branch
fail (Error_Bar_Hit_Mid_Case_Raw());
// Regardless of whether a "condition" was true or false, it's
// necessary to evaluate the next "branch" to know how far to skip:
//
// condition: true
// case [condition 10 + 20 true {hello}] ;-- returns 30
//
// condition: false
// case [condition 10 + 20 true {hello}] ;-- returns {hello}
//
// This uses the safe form, so you can't say `case [[x] [y]]` because
// the [x] condition is a literal block. However you can say
// `foo: [x] | case [foo [y]]`, since it is evaluated, or use a
// GROUP! as in `case [([x]) [y]]`.
//
// We need to hang onto the condition in the cell slot, in case the
// branch is an arity-1 FUNCTION! and wants to be passed what that
// condition evaluated to. Move it into the block rebval, which we no
// longer need (the frame captured it). Note that we can't evaluate
// into arguments directly...
//
Move_Value(block, cell);
if (Do_Next_In_Frame_Throws(cell, f)) {
Move_Value(out, cell);
Drop_Frame(f);
return R_OUT_IS_THROWN;
}
// CHOOSE simply sets the out slot to the matched value as-is. But
// when the condition is TRUE?, CASE actually does a double evaluation
// if a block is yielded as the branch:
//
// stuff: [print "This will be printed"]
// case [true stuff]
//
// Similar to IF TRUE STUFF, so CASE can act like many IFs at once.
//
// !!! Optimization note: if the previous evaluation had gone into
// D_OUT directly it could just stay there in some cases; and even
// block evaluation doesn't need the copy. Review how this shared
// code might get more efficient if the data were already in D_OUT.
//
if (choose) {
if (IS_CONDITIONAL_FALSE(block, only))
continue;
Move_Value(out, cell);
}
else {
// The check for IS_CONDITIONAL_FALSE is deferred until after we
// see if it's a CASE or a CHOOSE, so that when running CASE we
// ensure any evaluated but *non-taken* branches are type-checked
//
if (NOT(IS_FUNCTION(cell)) && NOT(IS_BLOCK(cell)))
fail (Error_Invalid_Arg_Raw(cell));
if (IS_CONDITIONAL_FALSE(block, only))
continue;
// Note that block now holds the cached evaluated condition
//
if (Run_Branch_Throws(out, block, cell, only)) {
Drop_Frame(f);
return R_OUT_IS_THROWN;
}
}
if (NOT(all)) {
Drop_Frame(f);
return R_OUT;
}
// keep matching if /ALL
}
// CASE/ALL can get here even if D_OUT not written
Drop_Frame(f);
return R_OUT_VOID_IF_UNWRITTEN;
}
//
// case: native [
//
// {Evaluates each condition, and when true, evaluates what follows it.}
//
// return: [<opt> any-value!]
// {Last matched case evaluation, or void if no cases matched}
// cases [block!]
// "Block of cases (conditions followed by branches)"
// /all
// {Evaluate all cases (do not stop at first TRUTHY? case)}
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(case)
{
INCLUDE_PARAMS_OF_CASE;
const REBOOL choose = FALSE;
return Case_Choose_Core(
D_OUT, D_CELL, ARG(cases), REF(all), REF(only), choose
);
}
//
// choose: native [
//
// {Evaluates each condition, and gives back the value that follows it}
//
// return: [<opt> any-value!]
// {Last matched choice value, or void if no choices matched}
// choices [block!]
// {Evaluate all choices (do not stop at first TRUTHY? choice)}
// /all
// {Return the value for the last matched choice (instead of first)}
// ]
//
REBNATIVE(choose)
{
INCLUDE_PARAMS_OF_CHOOSE;
// There's no need to worry about "blankification" here, though the value
// might be void. For now assume that means it's not a valid choice,
// and give an error. Review.
//
const REBOOL only = FALSE;
const REBOOL choose = TRUE;
return Case_Choose_Core(
D_OUT, D_CELL, ARG(choices), REF(all), only, choose
);
}
//
// switch: native [
//
// {Selects a choice and evaluates the block that follows it.}
//
// return: [<opt> any-value!]
// {Last case evaluation, or void if no cases matched}
// value [any-value!]
// "Target value"
// cases [block!]
// "Block of cases (comparison lists followed by block branches)"
// /default
// "Default case if no others found"
// default-case [function! block!]
// "Block to execute or function to run if no cases match"
// /all
// "Evaluate all matches (not just first one)"
// /strict
// {Use STRICT-EQUAL? when comparing cases instead of EQUAL?}
// /only
// "If branch runs and returns void, do not convert it to BLANK!"
// ]
//
REBNATIVE(switch)
//
// !!! SWITCH historically has had a /DEFAULT refinement. However, with the
// rise of the void-means-no-result convention and THEN and ELSE, it is
// somewhat inelegant. Consider removing it, when a suitable way to let
// users create expanded versions of functions with their own refinements
// exists, so that creating compatibility can be easy/performant.
{
INCLUDE_PARAMS_OF_SWITCH;
DECLARE_FRAME (f);
Push_Frame(f, ARG(cases));
// The evaluator always initializes the out slot to an END marker. That
// makes sure it gets overwritten with a value (or void) before returning.
// But here SWITCH also lets END indicate no matching cases ran yet.
assert(IS_END(D_OUT));
REBVAL *value = ARG(value);
// If /ONLY is not used, then do a safety check to see if someone wrote
// `switch [x] [...]` with a literal block, as that is likely a mistake.
//
if (
NOT(REF(only))
&& IS_BLOCK(value)
&& GET_VAL_FLAG(value, VALUE_FLAG_UNEVALUATED)
){
fail (Error_Block_Switch_Raw(value));
}
// SWITCH's extra D_CELL is a temporary GC-safe location for holding
// evaluations. Initialize it to void, as it holds the last test so that
// `switch 9 [1 ["a"] 2 ["b"] "c"]` is "c". (Empirically this is about
// twice as fast as using `switch/default`, another reason to kill it.)
Init_Void(D_CELL); // used for "fallout"
while (FRM_HAS_MORE(f)) {
//
// If a branch is seen at this point, it doesn't correspond to any
// condition to match. If no more tests are run, let it suppress the
// feature of the last value "falling out" the bottom of the switch
//
// (Note a FUNCTION! literal is likely only to be in the switch if
// it was composed into the block. This is a speculative feature.)
if (IS_BLOCK(f->value) || IS_FUNCTION(f->value)) {
Init_Void(D_CELL);
Fetch_Next_In_Frame(f);
continue;
}
// GROUP!, GET-WORD! and GET-PATH! are evaluated in Ren-C's SWITCH
// All other types are seen as-is (hence words act "quoted")
//
if (IS_QUOTABLY_SOFT(f->value)) {
if (Eval_Value_Core_Throws(D_CELL, f->value, f->specifier)) {
Move_Value(D_OUT, D_CELL);
Drop_Frame(f);
return R_OUT_IS_THROWN;
}
}
else
Derelativize(D_CELL, f->value, f->specifier);
// It's okay that we are letting the comparison change `value`
// here, because equality is supposed to be transitive. So if it
// changes 0.01 to 1% in order to compare it, anything 0.01 would
// have compared equal to so will 1%. (That's the idea, anyway,
// required for `a = b` and `b = c` to properly imply `a = c`.)
//
// !!! This means fallout can be modified from its intent. Rather
// than copy here, this is a reminder to review the mechanism by
// which equality is determined--and why it has to mutate.
//
// !!! A branch composed into the switch cases block may want to see
// the un-mutated condition value, in which case this should not
// be changing D_CELL
if (!Compare_Modify_Values(ARG(value), D_CELL, REF(strict) ? 1 : 0)) {
Fetch_Next_In_Frame(f);
continue;
}
// Skip ahead to try and find a block, to treat as code for the match
do {
Fetch_Next_In_Frame(f);
if (FRM_AT_END(f))
goto return_defaulted;
} while (!IS_BLOCK(f->value) && !IS_FUNCTION(f->value));
// Run the code if it was found. Because it writes D_OUT with a value
// (or void), it won't be END--we'll know at least one case has run.
//
// Derelativize the FUNCTION! or BLOCK! into the cases cell, which is
// available because the frame already captured it.
//
// !!! We only have to derelativize because we're not using plain
// Do_At_Throws()...which takes a specifier. If the literal-FUNCTION!
// in the cases feature turns out to be superfluous, use that instead.
//
Derelativize(ARG(cases), f->value, f->specifier);
if (Run_Branch_Throws(D_OUT, D_CELL, ARG(cases), REF(only))) {
Drop_Frame(f);
return R_OUT_IS_THROWN;
}
// Only keep processing if the /ALL refinement was specified
if (NOT(REF(all))) {
Drop_Frame(f);
return R_OUT;
}
}
if (NOT_END(D_OUT)) { // at least one case body ran and overwrote D_OUT
Drop_Frame(f);
return R_OUT;
}
return_defaulted:
assert(IS_END(D_OUT)); // nothing should have been written into D_OUT
Drop_Frame(f);
if (NOT(REF(default))) {
Move_Value(D_OUT, D_CELL); // last test "falls out", might be void
return R_OUT;
}
// The default branch is run, but the condition triggering it is said to
// be a void. Hence if the default case is a single-arity function, that
// is the argument it will be receiving. (Loops like FOREVER pass in
// END, so only single-arity functions can be used, but by using void
// here it allows a common function to take the default.)
//
if (Run_Branch_Throws(D_OUT, VOID_CELL, ARG(default_case), REF(only)))
return R_OUT_IS_THROWN;
return R_OUT;
}
//
// catch: native [
//
// {Catches a throw from a block and returns its value.}
//
// return: [<opt> any-value!]
// block [block!] "Block to evaluate"
// /name
// "Catches a named throw" ;-- should it be called /named ?
// names [block! word! function! object!]
// "Names to catch (single name if not block)"
// /quit
// "Special catch for QUIT native"
// /any
// {Catch all throws except QUIT (can be used with /QUIT)}
// /with
// "Handle thrown case with code"
// handler [block! function!]
// "If FUNCTION!, spec matches [value name]"
// /?
// "Instead of result or catch, return LOGIC! of if a catch occurred"
// ]
//
REBNATIVE(catch)
//
// There's a refinement for catching quits, and CATCH/ANY will not alone catch
// it (you have to CATCH/ANY/QUIT). Currently the label for quitting is the
// NATIVE! function value for QUIT.
{
INCLUDE_PARAMS_OF_CATCH; // ? is renamed as "q"
// /ANY would override /NAME, so point out the potential confusion
//
if (REF(any) && REF(name))
fail (Error_Bad_Refines_Raw());
if (Do_Any_Array_At_Throws(D_OUT, ARG(block))) {
if (
(
REF(any)
&& (!IS_FUNCTION(D_OUT) || VAL_FUNC_DISPATCHER(D_OUT) != &N_quit)
)
|| (
REF(quit)
&& (IS_FUNCTION(D_OUT) && VAL_FUNC_DISPATCHER(D_OUT) == &N_quit)
)
) {
goto was_caught;
}
if (REF(name)) {
//
// We use equal? by way of Compare_Modify_Values, and re-use the
// refinement slots for the mutable space
REBVAL *temp1 = ARG(quit);
REBVAL *temp2 = ARG(any);
// !!! The reason we're copying isn't so the VALUE_FLAG_THROWN bit
// won't confuse the equality comparison...but would it have?
if (IS_BLOCK(ARG(names))) {
//
// Test all the words in the block for a match to catch
RELVAL *candidate = VAL_ARRAY_AT(ARG(names));
for (; NOT_END(candidate); candidate++) {
//
// !!! Should we test a typeset for illegal name types?
//
if (IS_BLOCK(candidate))
fail (ARG(names));
Derelativize(temp1, candidate, VAL_SPECIFIER(ARG(names)));
Move_Value(temp2, D_OUT);
// Return the THROW/NAME's arg if the names match
// !!! 0 means equal?, but strict-equal? might be better
//
if (Compare_Modify_Values(temp1, temp2, 0))
goto was_caught;
}
}
else {
Move_Value(temp1, ARG(names));
Move_Value(temp2, D_OUT);
// Return the THROW/NAME's arg if the names match
// !!! 0 means equal?, but strict-equal? might be better
//
if (Compare_Modify_Values(temp1, temp2, 0))
goto was_caught;
}
}
else {
// Return THROW's arg only if it did not have a /NAME supplied
//
if (IS_BLANK(D_OUT))
goto was_caught;
}
// Throw name is in D_OUT, thrown value is held task local
//
return R_OUT_IS_THROWN;
}
if (REF(q)) return R_FALSE;
return R_OUT;
was_caught:
if (REF(with)) {
REBVAL *handler = ARG(handler);
// We again re-use the refinement slots, but this time as mutable
// space protected from GC for the handler's arguments
//
REBVAL *thrown_arg = ARG(any);
REBVAL *thrown_name = ARG(quit);
CATCH_THROWN(thrown_arg, D_OUT);
Move_Value(thrown_name, D_OUT); // THROWN bit cleared by CATCH_THROWN
if (IS_BLOCK(handler)) {
//
// There's no way to pass args to a block (so just DO it)
//
if (Do_Any_Array_At_Throws(D_OUT, ARG(handler)))
return R_OUT_IS_THROWN;
if (REF(q)) return R_TRUE;
return R_OUT;
}
else if (IS_FUNCTION(handler)) {
//
// This calls the function but only does a DO/NEXT. Hence the
// function might be arity 0, arity 1, or arity 2. If it has
// greater arity it will process more arguments.
//
if (Apply_Only_Throws(
D_OUT,
FALSE, // do not alert if handler doesn't consume all args
handler,
thrown_arg,
thrown_name,
END
)){
return R_OUT_IS_THROWN;
}
if (REF(q)) return R_TRUE;
return R_OUT;
}
}
// If no handler, just return the caught thing
//
CATCH_THROWN(D_OUT, D_OUT);
if (REF(q)) return R_TRUE;
return R_OUT;
}
//
// throw: native [
//
// "Throws control back to a previous catch."
//
// value [<opt> any-value!]
// "Value returned from catch"
// /name
// "Throws to a named catch"
// name-value [word! function! object!]
// ]
//
REBNATIVE(throw)
//
// Choices are currently limited for what one can use as a "name" of a THROW.
// Note blocks as names would conflict with the `name_list` feature in CATCH.
//
// !!! Should parameters be /NAMED and NAME ?
{
INCLUDE_PARAMS_OF_THROW;
REBVAL *value = ARG(value);
if (IS_ERROR(value)) {
//
// We raise an alert from within the implementation of throw for
// trying to use it to trigger errors, because if THROW just didn't
// take errors in the spec it wouldn't guide what *to* use.
//
fail (Error_Use_Fail_For_Error_Raw(value));
// Note: Caller can put the ERROR! in a block or use some other
// such trick if it wants to actually throw an error.
// (Better than complicating via THROW/ERROR-IS-INTENTIONAL!)
}
if (REF(name))
Move_Value(D_OUT, ARG(name_value));
else {
// Blank values serve as representative of THROWN() means "no name"
//
Init_Blank(D_OUT);
}
CONVERT_NAME_TO_THROWN(D_OUT, value);
return R_OUT_IS_THROWN;
}
| 2.046875 | 2 |
2024-11-18T19:02:21.706741+00:00
| 2022-12-09T19:54:39 |
b5b320cbe4c4b393fd3a411b16b16ead98e06fd5
|
{
"blob_id": "b5b320cbe4c4b393fd3a411b16b16ead98e06fd5",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-09T19:54:39",
"content_id": "0b2fd3e9af32c4a18f46112904e24f463ae23307",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "fa294a32c055a07adb2497b77144c5a2f7f74df4",
"extension": "c",
"filename": "str_len.c",
"fork_events_count": 1,
"gha_created_at": "2017-02-04T20:33:51",
"gha_event_created_at": "2022-10-01T20:54:00",
"gha_language": "C",
"gha_license_id": "BSD-2-Clause",
"github_id": 80946676,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 140,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/libs/appengine/base/strings/str_len.c",
"provenance": "stackv2-0058.json.gz:150347",
"repo_name": "dpt/PrivateEye",
"revision_date": "2022-12-09T19:54:39",
"revision_id": "5ddc82168d1267165d29c11b7e35eba279e50d98",
"snapshot_id": "4464610aa902a3499b17b908c29e882e38c8fb47",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/dpt/PrivateEye/5ddc82168d1267165d29c11b7e35eba279e50d98/libs/appengine/base/strings/str_len.c",
"visit_date": "2022-12-10T23:35:48.318548"
}
|
stackv2
|
#include "appengine/base/strings.h"
int str_len(const char *s)
{
const char *p;
for (p = s; *p >= ' '; p++)
;
return p - s;
}
| 2.203125 | 2 |
2024-11-18T19:02:22.760974+00:00
| 2019-11-06T15:32:59 |
4717d89c6c023651f18586fef0ba7339345281be
|
{
"blob_id": "4717d89c6c023651f18586fef0ba7339345281be",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-06T15:32:59",
"content_id": "bf6342430796d8790434c3d8ff87bf4910aec460",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9f74f22d1ed6ae77b82f2154cacf25b9c73c9938",
"extension": "c",
"filename": "sum.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 219988910,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 324,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/C Programs/chap07/sum.c",
"provenance": "stackv2-0058.json.gz:150733",
"repo_name": "csitedexperts/CSE1321Review_CPP",
"revision_date": "2019-11-06T15:32:59",
"revision_id": "e3b763c54df8b8d93b9cdce39dd434733ff94862",
"snapshot_id": "3843824c906ee7e161f3f9567ba4ad2f693c662e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/csitedexperts/CSE1321Review_CPP/e3b763c54df8b8d93b9cdce39dd434733ff94862/C Programs/chap07/sum.c",
"visit_date": "2020-09-05T04:57:45.950045"
}
|
stackv2
|
/* Save This Function as (C:\Sum.c) */
int Sum() // Function Definition
{
int Value1, Value2, Sum;
printf("Enter Value1 : ");
scanf("%d", &Value1);
printf("Enter Value2 : ");
scanf("%d", &Value2);
Sum = Value1 + Value2;
printf("Value1 = %d \nValue2 = %d", Value1, Value2);
printf("\nSum =%d", Sum);
return (Sum);
}
| 3.421875 | 3 |
2024-11-18T19:02:22.880607+00:00
| 2021-08-13T13:57:26 |
4e5d82ac0d61ff6f0e982ba11e71f6a901b51379
|
{
"blob_id": "4e5d82ac0d61ff6f0e982ba11e71f6a901b51379",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-13T13:57:26",
"content_id": "5fec78a91fbba81b9cf0b405e79d544dd759787e",
"detected_licenses": [
"Zlib"
],
"directory_id": "7cef0e3621d4d37f2029fe1e809d1a7302879d73",
"extension": "c",
"filename": "dragon4_values.c",
"fork_events_count": 1,
"gha_created_at": "2020-12-10T11:37:04",
"gha_event_created_at": "2021-05-31T22:22:48",
"gha_language": "C",
"gha_license_id": null,
"github_id": 320253390,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4526,
"license": "Zlib",
"license_type": "permissive",
"path": "/lib/libft/ft_dtoa/dragon4_values.c",
"provenance": "stackv2-0058.json.gz:150990",
"repo_name": "hakolao/doom3d",
"revision_date": "2021-08-13T13:57:26",
"revision_id": "f9eb82e051a813e926469fdace56e4de77814a97",
"snapshot_id": "437cc73db0c4a9d66f575654f0e7dd8c4a06c84f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/hakolao/doom3d/f9eb82e051a813e926469fdace56e4de77814a97/lib/libft/ft_dtoa/dragon4_values.c",
"visit_date": "2023-07-08T13:10:26.188941"
}
|
stackv2
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* dragon4_values.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ohakola <ohakola@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/24 18:57:09 by ohakola #+# #+# */
/* Updated: 2021/05/04 15:48:14 by ohakola ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_dtoa.h"
/*
** Values are scaled based on the digit exponent estimation.
** "if the digit exponent is smaller than the smallest desired digit for
** fractional cutoff, pull the digit back into legal range at which point we
** will round to the appropriate value."
*/
void scale_values_after_exponent_estimation(t_big_int *scale,
t_big_int *scaled_value, t_big_int **scaled_margins,
int32_t *digit_exponent)
{
t_big_int temp;
t_big_int pow10;
if (*digit_exponent > 0)
big_int_mul_pow_10(scale, *digit_exponent, scale);
else if (*digit_exponent < 0)
{
big_int_pow_10(-*digit_exponent, &pow10);
big_int_mul(scaled_value, &pow10, &temp);
big_int_copy(&temp, scaled_value);
big_int_mul(scaled_margins[0], &pow10, &temp);
big_int_copy(&temp, scaled_margins[0]);
if (big_int_cmp(scaled_margins[1], scaled_margins[0]) != 0)
big_int_mul_2(scaled_margins[0], scaled_margins[1]);
}
if (big_int_cmp(scaled_value, scale) >= 0)
*digit_exponent = *digit_exponent + 1;
else
{
big_int_mul_10_modif(scaled_value);
big_int_mul_10_modif(scaled_margins[0]);
if (big_int_cmp(scaled_margins[1], scaled_margins[0]) != 0)
big_int_mul_2(scaled_margins[0], scaled_margins[1]);
}
}
/*
** Normalized numbers represent the majority of floating point values.
** This function scales the input values so that later the algorithm can divide
** value = scaled_value / scale in the case of normalized floating point
** values
*/
void normalized_initial_state(t_dragon4_params params,
t_big_int *scale, t_big_int *scaled_value,
t_big_int **scaled_margins)
{
big_int_set_u64(scaled_value, params.mantissa);
if (params.exponent > 0)
{
big_int_shift_left(params.exponent + 2, scaled_value);
big_int_set_u32(scale, 4);
big_int_pow_2(params.exponent, scaled_margins[0]);
big_int_pow_2(params.exponent + 1, scaled_margins[1]);
}
else
{
big_int_shift_left(2, scaled_value);
big_int_pow_2(-params.exponent + 2, scale);
big_int_set_u32(scaled_margins[0], 1);
big_int_set_u32(scaled_margins[1], 2);
}
}
/*
** Denormalized numbers represent a set of floating point values that are
** too small to fit in the normalized range. This function scales the
** input values so that later the algorithm can divide
** value = scaled_value / scale in the case of denormalized floating point
** values
*/
void denormalized_initial_state(t_dragon4_params params,
t_big_int *scale, t_big_int *scaled_value,
t_big_int **scaled_margins)
{
big_int_set_u64(scaled_value, params.mantissa);
if (params.exponent > 0)
{
big_int_shift_left(params.exponent + 1, scaled_value);
big_int_set_u32(scale, 2);
big_int_pow_2(params.exponent, scaled_margins[0]);
}
else
{
big_int_shift_left(1, scaled_value);
big_int_pow_2(-params.exponent + 1, scale);
big_int_set_u32(scaled_margins[0], 1);
}
scaled_margins[1] = scaled_margins[0];
}
/*
** Before dividing values, they need to be scaled up so that denominator
** highest block is >= 8 and <= 429496729 (highest number that can be
** multiplied by 10 without overflowing the 32 bit block)
*/
void prepare_values_for_division(t_big_int *scale,
t_big_int *scaled_value, t_big_int **scaled_margins)
{
uint32_t high_block;
uint32_t shift;
high_block = scale->blocks[scale->length - 1];
if (high_block < 8 || high_block > 429496729)
{
shift = (32 + 27 - log_base2_32(high_block)) % 32;
big_int_shift_left(shift, scale);
big_int_shift_left(shift, scaled_value);
big_int_shift_left(shift, scaled_margins[0]);
if (big_int_cmp(scaled_margins[1], scaled_margins[0]) != 0)
big_int_mul_2(scaled_margins[0], scaled_margins[1]);
}
}
| 2.75 | 3 |
2024-11-18T19:02:28.698629+00:00
| 2018-11-02T00:25:17 |
9428c6828a215214f15dd4c18bfcea9801de2e51
|
{
"blob_id": "9428c6828a215214f15dd4c18bfcea9801de2e51",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-02T00:25:17",
"content_id": "701228eca8d0eae869d06193e4eee55e71b6129f",
"detected_licenses": [
"MIT"
],
"directory_id": "81fd7e72a4040020ffe116c3fd34b781004ca04f",
"extension": "c",
"filename": "hello.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 150924960,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 474,
"license": "MIT",
"license_type": "permissive",
"path": "/Chapter-1/1-1/hello.c",
"provenance": "stackv2-0058.json.gz:151246",
"repo_name": "Lornatang/C-programming-language-exercises",
"revision_date": "2018-11-02T00:25:17",
"revision_id": "8eeecc343009f9248340154c2e20dd54ebcd76a6",
"snapshot_id": "73faeb967e19ff3bb3c9d809dd18b281f9a381b3",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Lornatang/C-programming-language-exercises/8eeecc343009f9248340154c2e20dd54ebcd76a6/Chapter-1/1-1/hello.c",
"visit_date": "2020-03-30T07:14:10.768317"
}
|
stackv2
|
/*
* Filename: hello.c
* Author: Thomas van der Burgt <thomas@thvdburgt.nl>
* Date: 25-FEB-2010
*
* The C Programming Language, second edition,
* by Brian Kernighan and Dennis Ritchie
*
* Exercise 1-1, page 8
*
* Run the "Hello, world" program on your system. Experiment with
* leaving out parts of the program, to see what error messages you get.
*/
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("hello world!\n");
return 0;
}
| 2.796875 | 3 |
2024-11-18T19:02:28.960050+00:00
| 2020-05-29T11:42:36 |
423c835c159d2bc05d73fb537e4a66d4ad2e7999
|
{
"blob_id": "423c835c159d2bc05d73fb537e4a66d4ad2e7999",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-29T11:42:36",
"content_id": "4944f2781441311800a2a3c2a1950275723faff2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4c5608f20fa2580774d734d94198dd10648e4339",
"extension": "c",
"filename": "gbp_itf.c",
"fork_events_count": 0,
"gha_created_at": "2019-06-28T09:50:05",
"gha_event_created_at": "2022-12-08T05:17:31",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 194249816,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5146,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/plugins/gbp/gbp_itf.c",
"provenance": "stackv2-0058.json.gz:151634",
"repo_name": "mojtaba-eshghie/VPP-In-Situ-IOAM",
"revision_date": "2020-05-29T11:42:36",
"revision_id": "efebd91195eb1b0d98a4a1f5efd962ae79c77be6",
"snapshot_id": "3d1c3d01752a7934d2f060326674280e0bd93413",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/mojtaba-eshghie/VPP-In-Situ-IOAM/efebd91195eb1b0d98a4a1f5efd962ae79c77be6/src/plugins/gbp/gbp_itf.c",
"visit_date": "2022-12-10T13:37:04.644952"
}
|
stackv2
|
/*
* Copyright (c) 2018 Cisco and/or its affiliates.
* 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 <plugins/gbp/gbp_itf.h>
/**
* Attributes and configurations attached to interfaces by GBP
*/
typedef struct gbp_itf_t_
{
/**
* Number of references to this interface
*/
u32 gi_locks;
u32 gi_sw_if_index;
u32 gi_bd_index;
/**
* L2/L3 Features configured by each user
*/
u32 *gi_l2_input_fbs;
u32 gi_l2_input_fb;
u32 *gi_l2_output_fbs;
u32 gi_l2_output_fb;
} gbp_itf_t;
static gbp_itf_t *gbp_itfs;
static gbp_itf_t *
gbp_itf_get (index_t gii)
{
vec_validate (gbp_itfs, gii);
return (&gbp_itfs[gii]);
}
static index_t
gbp_itf_get_itf (u32 sw_if_index)
{
return (sw_if_index);
}
index_t
gbp_itf_add_and_lock (u32 sw_if_index, u32 bd_index)
{
gbp_itf_t *gi;
gi = gbp_itf_get (gbp_itf_get_itf (sw_if_index));
if (0 == gi->gi_locks)
{
gi->gi_sw_if_index = sw_if_index;
gi->gi_bd_index = bd_index;
if (~0 != gi->gi_bd_index)
set_int_l2_mode (vlib_get_main (), vnet_get_main (),
MODE_L2_BRIDGE, sw_if_index, bd_index,
L2_BD_PORT_TYPE_NORMAL, 0, 0);
}
gi->gi_locks++;
return (sw_if_index);
}
void
gbp_itf_unlock (index_t gii)
{
gbp_itf_t *gi;
gi = gbp_itf_get (gii);
ASSERT (gi->gi_locks > 0);
gi->gi_locks--;
if (0 == gi->gi_locks)
{
if (~0 != gi->gi_bd_index)
set_int_l2_mode (vlib_get_main (), vnet_get_main (), MODE_L3,
gi->gi_sw_if_index, 0, L2_BD_PORT_TYPE_NORMAL, 0, 0);
vec_free (gi->gi_l2_input_fbs);
vec_free (gi->gi_l2_output_fbs);
memset (gi, 0, sizeof (*gi));
}
}
void
gbp_itf_set_l2_input_feature (index_t gii,
index_t useri, l2input_feat_masks_t feats)
{
u32 diff_fb, new_fb, *fb, feat;
gbp_itf_t *gi;
gi = gbp_itf_get (gii);
if (gi->gi_bd_index == ~0)
return;
vec_validate (gi->gi_l2_input_fbs, useri);
gi->gi_l2_input_fbs[useri] = feats;
new_fb = 0;
vec_foreach (fb, gi->gi_l2_input_fbs)
{
new_fb |= *fb;
}
/* add new features */
diff_fb = (gi->gi_l2_input_fb ^ new_fb) & new_fb;
/* *INDENT-OFF* */
foreach_set_bit (feat, diff_fb,
({
l2input_intf_bitmap_enable (gi->gi_sw_if_index, (1 << feat), 1);
}));
/* *INDENT-ON* */
/* remove unneeded features */
diff_fb = (gi->gi_l2_input_fb ^ new_fb) & gi->gi_l2_input_fb;
/* *INDENT-OFF* */
foreach_set_bit (feat, diff_fb,
({
l2input_intf_bitmap_enable (gi->gi_sw_if_index, (1 << feat), 0);
}));
/* *INDENT-ON* */
gi->gi_l2_input_fb = new_fb;
}
void
gbp_itf_set_l2_output_feature (index_t gii,
index_t useri, l2output_feat_masks_t feats)
{
u32 diff_fb, new_fb, *fb, feat;
gbp_itf_t *gi;
gi = gbp_itf_get (gii);
if (gi->gi_bd_index == ~0)
return;
vec_validate (gi->gi_l2_output_fbs, useri);
gi->gi_l2_output_fbs[useri] = feats;
new_fb = 0;
vec_foreach (fb, gi->gi_l2_output_fbs)
{
new_fb |= *fb;
}
/* add new features */
diff_fb = (gi->gi_l2_output_fb ^ new_fb) & new_fb;
/* *INDENT-OFF* */
foreach_set_bit (feat, diff_fb,
({
l2output_intf_bitmap_enable (gi->gi_sw_if_index, (1 << feat), 1);
}));
/* *INDENT-ON* */
/* remove unneeded features */
diff_fb = (gi->gi_l2_output_fb ^ new_fb) & gi->gi_l2_output_fb;
/* *INDENT-OFF* */
foreach_set_bit (feat, diff_fb,
({
l2output_intf_bitmap_enable (gi->gi_sw_if_index, (1 << feat), 0);
}));
/* *INDENT-ON* */
gi->gi_l2_output_fb = new_fb;
}
u8 *
format_gbp_itf (u8 * s, va_list * args)
{
index_t gii = va_arg (*args, index_t);
gbp_itf_t *gi;
gi = gbp_itf_get (gii);
s = format (s, "%U locks:%d bd-index:%d input-feats:%U output-feats:%U",
format_vnet_sw_if_index_name, vnet_get_main (),
gi->gi_sw_if_index, gi->gi_locks,
gi->gi_bd_index,
format_l2_input_features, gi->gi_l2_input_fb, 0,
format_l2_output_features, gi->gi_l2_output_fb, 0);
return (s);
}
static clib_error_t *
gbp_itf_show (vlib_main_t * vm,
unformat_input_t * input, vlib_cli_command_t * cmd)
{
u32 gii;
vlib_cli_output (vm, "Interfaces:");
vec_foreach_index (gii, gbp_itfs)
{
vlib_cli_output (vm, " [%d] %U", gii, format_gbp_itf, gii);
}
return (NULL);
}
/*?
* Show Group Based Interfaces
*
* @cliexpar
* @cliexstart{show gbp contract}
* @cliexend
?*/
/* *INDENT-OFF* */
VLIB_CLI_COMMAND (gbp_contract_show_node, static) = {
.path = "show gbp interface",
.short_help = "show gbp interface\n",
.function = gbp_itf_show,
};
/* *INDENT-ON* */
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
| 2.0625 | 2 |
2024-11-18T19:02:29.170882+00:00
| 2017-04-07T15:40:56 |
3fd15ab1be03ec89338db73d8e7972da46d0a9e4
|
{
"blob_id": "3fd15ab1be03ec89338db73d8e7972da46d0a9e4",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-07T15:40:56",
"content_id": "684b939e2ddfde6088c7801a4b273977c11b9351",
"detected_licenses": [
"MIT"
],
"directory_id": "93350df374e44b3227e0c7c88def46eabba557f1",
"extension": "c",
"filename": "os.c",
"fork_events_count": 0,
"gha_created_at": "2017-02-09T22:01:22",
"gha_event_created_at": "2017-04-07T15:40:57",
"gha_language": "C",
"gha_license_id": null,
"github_id": 81499244,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 31171,
"license": "MIT",
"license_type": "permissive",
"path": "/project_2/os.c",
"provenance": "stackv2-0058.json.gz:151891",
"repo_name": "JoshuaPortelance/CSC460-Spring2017",
"revision_date": "2017-04-07T15:40:56",
"revision_id": "002d1de2f775e76eb0fff52e8d36913874b1a757",
"snapshot_id": "0a4b7fed8603b5962e0b6008e07cc9d91daf96f5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JoshuaPortelance/CSC460-Spring2017/002d1de2f775e76eb0fff52e8d36913874b1a757/project_2/os.c",
"visit_date": "2021-01-22T04:05:15.969608"
}
|
stackv2
|
/*
* os.c
*
* Created: 3/10/2017 10:26:07 AM
* Author: Josh
*/
#define F_CPU 16000000L // Specify oscillator frequency
#include <util/delay.h>
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
#include "os.h"
#include "kernel.h"
#include "error_codes.h"
#include "user_space.h"
/* Debugging pins
DDRC = 0b1111111
PORTC
Pin 37 - Bit 0 - Kernel_Idle_Task
Pin 36 - Bit 1 - 1kHz ISR
Pin 35 - Bit 2 - 100Hz ISR
Pin 34 - Bit 3 - Kernel_Request_Handler
Pin 33 - Bit 4 - Kernel_Dispatch
Pin 32 - Bit 5 -
Pin 31 - Bit 6 -
Pin 30 - Bit 7 -
*/
BOOL debug = FALSE; // If DEBUG is true, then PORTB will be used to display timings as per the above comment.
/*
* Globals.
*/
static PD Process[MAXTHREAD];
static CHAND channel_descriptors[MAXCHAN];
static PD* system_queue[MAXTHREAD];
volatile static unsigned int system_queue_front = 0;
volatile static unsigned int system_queue_rear = -1;
volatile static unsigned int system_queue_size = 0;
static PD* rr_queue[MAXTHREAD];
volatile static unsigned int rr_queue_front = 0;
volatile static unsigned int rr_queue_rear = -1;
volatile static unsigned int rr_queue_size = 0;
static PD* periodic_lookup[MAXTHREAD];
volatile static PD* ready_periodic_task;
volatile static PD* Cp;
volatile unsigned char *KernelSp;
unsigned char *CurrentSp;
volatile static unsigned int KernelActive;
volatile static unsigned int Tasks;
volatile static unsigned int Periodic_Tasks;
volatile static unsigned int System_Tasks;
volatile static unsigned int RR_Tasks;
volatile static unsigned int Channels;
volatile static unsigned int current_time; // The current time in milliseconds since Kernel_OS_Init.
/*
* API Function Prototypes.
*/
void OS_Abort(unsigned int error);
PID Task_Create_System(void (*f)(void), int arg);
PID Task_Create_RR(void (*f)(void), int arg);
PID Task_Create_Period(void (*f)(void), int arg, TICK period, TICK wcet, TICK offset);
void Task_Next(void);
int Task_GetArg(void);
CHAN Chan_Init();
void Send(CHAN ch, int v);
int Recv(CHAN ch);
void Write(CHAN ch, int v);
unsigned int Now();
/*
* Kernel Function Prototypes.
*/
// Context switching functions.
extern void CSwitch();
extern void Exit_Kernel(); /* this is the same as CSwitch() */
extern void Enter_Kernel();
// Kernel functions.
void Kernel_OS_Init(void);
void Kernel_OS_Start(void);
void Kernel_Idle_Task(void);
void Kernel_OS_Abort(unsigned int error);
void Kernel_Request_Handler(void);
void Kernel_Dispatch(void);
// Task functions.
void Kernel_Task_Create_System(void (*f)(void), int arg);
void Kernel_Task_Create_Round_Robin(void (*f)(void), int arg);
void Kernel_Task_Create_Periodic(void (*f)(void), int arg, TICK period, TICK wcet, TICK offset);
void Kernel_Create_Task_At(volatile PD *p, voidfuncptr f, int arg, PID pid, PROCESS_PRIORITIES priority, TICK period, TICK wcet, TICK offset);
void Kernel_Task_Terminate(void);
// Channel functions.
void Kernel_Chan_Init();
void Kernel_Send(CHAN ch, int v);
void Kernel_Recv(CHAN ch);
void Kernel_Write(CHAN ch, int v);
// Queue functions.
void enqueue_system(volatile PD* p);
PD* dequeue_system(void);
void enqueue_rr(volatile PD* p);
PD* dequeue_rr(void);
/*
* API Functions.
* ================================================================================================
* ================================================================================================
* ================================================================================================
*/
/*
* OS_Abort
*
* Aborts the RTOS and enters a "non-executing" state with an error code.
*
* Params:
* unsigned int error - The error code related to the abort.
*/
void OS_Abort(unsigned int error)
{
if (KernelActive)
{
Disable_Interrupt();
Cp->request = ABORT;
Cp->error = error;
Enter_Kernel();
}
else
{
Kernel_OS_Abort(error);
}
}
/*
* Task_Create_System
*
* Creates a task with System level priority.
*
* Params:
* void (*f)(void) - Pointer to the function the tasks will run.
* int arg - An integer number to be assigned to this process instance.
* Return:
* PID - Zero if unsuccessful, otherwise a positive integer.
*/
PID Task_Create_System(void (*f)(void), int arg)
{
if (KernelActive)
{
Disable_Interrupt();
Cp->request = CREATESY;
Cp->priority = SYSTEM;
Cp->code = f;
Cp->creation_arg = arg;
Enter_Kernel();
}
else
{
// Call the RTOS function directly.
Kernel_Task_Create_System(f, arg);
}
return Cp->pid;
}
/*
* Task_Create_RR
*
* Creates a task with RR level priority.
*
* Params:
* void (*f)(void) - Pointer to the function the tasks will run.
* int arg - An integer number to be assigned to this process instance.
* Return:
* PID - Zero if unsuccessful, otherwise a positive integer.
*/
PID Task_Create_RR(void (*f)(void), int arg)
{
if (KernelActive)
{
Disable_Interrupt();
Cp->request = CREATERR;
Cp->priority = ROUNDROBIN;
Cp->code = f;
Cp->creation_arg = arg;
Enter_Kernel();
}
else
{
// Call the RTOS function directly.
Kernel_Task_Create_Round_Robin(f, arg);
}
return Cp->pid;
}
/*
* Task_Create_Period
*
* Creates a periodic task with the periodic priority level.
*
* Params:
* void (*f)(void) - Pointer to the function the tasks will run.
* int arg - An integer number to be assigned to this process instance.
* TICK period - Tasks execution period in TICKs.
* TICK wcet - Worst case execution time of the task in TICKs; must be less then period.
* TICK offset - Tasks start offset in TICKs.
* Return:
* PID - Zero if unsuccessful, otherwise a positive integer.
*/
PID Task_Create_Period(void (*f)(void), int arg, TICK period, TICK wcet, TICK offset)
{
if (KernelActive)
{
Disable_Interrupt();
Cp->request = CREATEPD;
Cp->priority = PERIODIC;
Cp->code = f;
Cp->creation_arg = arg;
Cp->period = period;
Cp->wcet = wcet;
Cp->offset = offset;
Enter_Kernel();
}
else
{
// Call the RTOS function directly.
Kernel_Task_Create_Periodic(f, arg, period, wcet, offset);
}
return Cp->pid;
}
/*
* Task_Next
*
* Switches to the next highest priority task.
*/
void Task_Next(void)
{
if (KernelActive)
{
Disable_Interrupt();
Cp ->request = NEXT;
Enter_Kernel();
}
}
/*
* Task_GetArg
*
* Gets the integer that was assigned to the task when created.
*
* Return:
* int - The arg that was used when creating the task.
*/
int Task_GetArg(void)
{
return Cp->creation_arg;
}
/*
* Chan_Init
*
* Initializes a channel.
*
* Return:
* CHAN - Zero if unsuccessful, otherwise a positive integer representing the channel number.
*/
CHAN Chan_Init()
{
if (KernelActive)
{
Disable_Interrupt();
Cp->request = CHANINIT;
Enter_Kernel();
}
int temp_return_value = Cp->return_value;
Cp->return_value = 0;
return temp_return_value;
}
/*
* Send
*
* Sends the message v over channel ch.
* - If there are no receivers the calling task is blocked.
* - Else if there is already a sender on this channel the RTOS will abort in an error state.
* - Else the message will be sent over the channel and the task will not be blocked.
*
* Params:
* CHAN ch - Channel to send the message over.
* int v - Message to send over the channel.
*/
void Send(CHAN ch, int v)
{
if (KernelActive)
{
Disable_Interrupt();
Cp->channel = ch;
Cp->message = v;
Cp->request = SEND;
Enter_Kernel();
}
}
/*
* Recv
*
* Receives a message over channel ch.
* - If there is no sender on the channel the calling task will be blocked.
* - Else the message will be received and the calling task will not be blocked
*
* Params:
* CHAN ch - The channel to receive a message over.
* Return:
* int - The message that was received.
*/
int Recv(CHAN ch)
{
if (KernelActive)
{
Disable_Interrupt();
Cp->channel = ch;
Cp->request = RECV;
Enter_Kernel();
}
return Cp->message;
}
/*
* Write
*
* Sends the message v over channel ch, but do not wait if there are no receivers.
* - If there is already a sender on the channel the RTOS will abort in an error state.
* - Else send the message over the channel; the calling task will not be blocked.
*
* Params:
* CHAN ch - Channel to send the message over.
* int v - Message to send over the channel.
*/
void Write(CHAN ch, int v)
{
if (KernelActive)
{
Disable_Interrupt();
Cp->channel = ch;
Cp->message = v;
Cp->request = WRITE;
Enter_Kernel();
}
}
/*
* Now
*
* Returns the number of milliseconds since Kernel_OS_Init().
*
* Return:
* unsigned int - The number of milliseconds since Kernel_OS_Init().
*/
unsigned int Now()
{
return current_time;
}
/*
* Kernel Functions.
* ================================================================================================
* ================================================================================================
* ================================================================================================
*/
/*
* Kernel_OS_Init
*
* Initializes the data structure and globals needed for execution.
*/
void Kernel_OS_Init(void)
{
int x;
if(debug){DDRC = 0b11111111;}
Tasks = 0;
KernelActive = 0;
Periodic_Tasks = 0;
System_Tasks = 0;
RR_Tasks = 0;
current_time = 0;
Channels = 0;
ready_periodic_task = NULL;
// Reminder: Clear the memory for the task on creation.
for (x = 0; x < MAXTHREAD; x++) {
memset(&(Process[x]),0,sizeof(PD));
Process[x].state = DEAD;
}
// Initialize timer ISR for 1kHz.
Disable_Interrupt();
TCCR3A = 0;
TCCR3B = 0;
TCNT3 = 0; // Set timer to 0
TCCR3B |= (1<<WGM32); // Set to CTC (mode 4)
TCCR3B |= (1<<CS31); // Set to 8 prescaler
OCR3A = 2000; // Setting timer target
TIMSK3 |= (1<<OCIE3A); // Enable interrupt A for timer 3.
// Initialize priority task scheduler ISR for 100Hz.
TCCR4A = 0;
TCCR4B = 0;
TCNT4 = 0; // Set timer to 0
TCCR4B |= (1<<WGM42); // Set to CTC (mode 4)
TCCR4B |= (1<<CS42); // Set to 256 prescaler
OCR4A = 625; // Setting timer target
TIMSK4 |= (1<<OCIE4A); // Enable interrupt A for timer 4.
Enable_Interrupt();
}
/*
* ISR to:
* - keep track of milliseconds sense Kernel_OS_Init.
* - monitoring for preemption and acting on it.
* - interrupting RR tasks that ran for more than 1 TICK.
*/
ISR(TIMER3_COMPA_vect)
{
if(debug)
{
PORTC ^= 0b00000010;
}
int preempted = 0;
current_time++; // Update timer.
// Check and act on preemption.
if(Cp->priority == ROUNDROBIN && (system_queue_size > 0 || ready_periodic_task != NULL))
{
Cp->state = READY;
preempted = 1;
}
else if(Cp->priority == PERIODIC && system_queue_size > 0)
{
Cp->state = READY;
preempted = 1;
}
// End any RR going over 1 TICK.
if(Cp->priority == ROUNDROBIN)
{
Cp->num_ticks_remaining--;
if(Cp->num_ticks_remaining == 0)
{
Cp->num_ticks_remaining = MSECPERTICK;
Cp->state = READY;
preempted = 1;
}
}
// Reschedule if preempted.
if(preempted == 1)
{
switch(Cp->priority)
{
case SYSTEM:
enqueue_system(Cp);
break;
case PERIODIC:
if(ready_periodic_task == NULL)
{
ready_periodic_task = Cp;
}
else
{
Kernel_OS_Abort(MILTIPLE_READY_PERIODIC_TASKS);
}
break;
case ROUNDROBIN:
enqueue_rr(Cp);
break;
default:
Kernel_OS_Abort(DEFUALT_PRIORITY);
break;
}
Task_Next();
}
if(debug)
{
PORTC ^= 0b00000010;
}
}
/*
* ISR to:
* - Update the num_remaining_ticks for all periodic tasks.
* - Look for one that just become 0, reset it to its period, and make it ready.
*/
ISR(TIMER4_COMPA_vect)
{
if(debug)
{
PORTC ^= 0b00000100;
}
// Updating periodic num_remaining_ticks and checking for any that are zero.
int i;
for(i = 0; i < Periodic_Tasks; i++)
{
periodic_lookup[i]->num_ticks_remaining--;
if(periodic_lookup[i]->num_ticks_remaining == 0)
{
periodic_lookup[i]->num_ticks_remaining = periodic_lookup[i]->period;
periodic_lookup[i]->state = READY;
if(ready_periodic_task == NULL)
{
ready_periodic_task = periodic_lookup[i];
continue;
}
else
{
Kernel_OS_Abort(MILTIPLE_READY_PERIODIC_TASKS);
}
}
}
if(debug)
{
PORTC ^= 0b00000100;
}
}
/*
* Kernel_OS_Start
*
* Starts the RTOS.
*/
void Kernel_OS_Start(void)
{
if ((! KernelActive) && (Tasks > 0))
{
Disable_Interrupt();
KernelActive = 1;
Kernel_Request_Handler(); // Should never return. If it does this is handled in main().
}
}
/*
* Kernel_OS_Abort
*
* Aborts the RTOS and enters a "non-executing" state with an error code.
* This is done by entering an infinite loop that blinks the on-board LED
* to try to communicate the error. The number of blinks in a cycle is
* related to the enum value defined in error_codes.h.
*
* Params:
* unsigned int error - The error code related to the abort.
*/
void Kernel_OS_Abort(unsigned int error)
{
// Initializing the on-board LED.
DDRB = 0b11111111;
PORTB = 0b00000000;
unsigned int i;
for(;;)
{
PORTB &= 0b01111111; // Turn LED off.
_delay_ms(5000);
for(i=0; i < error; i++)
{
PORTB |= 0b10000000; // Turn LED On.
_delay_ms(250);
PORTB &= 0b01111111; // Turn LED Off.
_delay_ms(250);
}
}
}
/*
* Kernel_Idle
*
* Idle task.
*/
void Kernel_Idle_Task(void)
{
for (;;)
{
if(debug)
{
PORTC ^= 0b00000001;
PORTC ^= 0b00000001;
}
Task_Next();
}
}
/*
* Kernel_Request_Handler
*
* Handles all system requests. This function is only called once by
* Kernel_OS_Start and never terminates.
*/
void Kernel_Request_Handler(void)
{
Kernel_Dispatch(); // Select a new task to run.
while(1)
{
Cp->request = NONE; // Clear its request.
// Activate this newly selected task.
CurrentSp = Cp->sp;
if(debug)
{
PORTC ^= 0b00001000;
}
Exit_Kernel();
// If this new task makes a system call, it will return to here!
if(debug)
{
PORTC ^= 0b00001000;
}
// Save CP's stack pointer.
Cp->sp = CurrentSp;
switch(Cp->request)
{
case ABORT:
Kernel_OS_Abort(Cp->error);
break;
case CREATESY:
Kernel_Task_Create_System(Cp->code, Cp->creation_arg);
break;
case CREATEPD:
Kernel_Task_Create_Periodic(Cp->code, Cp->creation_arg, Cp->period, Cp->wcet, Cp->offset);
break;
case CREATERR:
Kernel_Task_Create_Round_Robin(Cp->code, Cp->creation_arg);
break;
case NEXT:
case NONE:
switch(Cp->priority)
{
case SYSTEM:
Cp->state = READY;
enqueue_system(Cp);
break;
case PERIODIC:
Cp->state = WAITING;
break;
case ROUNDROBIN:
Cp->state = READY;
enqueue_rr(Cp);
break;
default:
Kernel_OS_Abort(DEFUALT_PRIORITY);
break;
}
Kernel_Dispatch();
break;
case TERMINATE:
// Deallocate all resources used by this task.
Cp->state = DEAD;
Kernel_Dispatch();
break;
case CHANINIT:
Kernel_Chan_Init();
break;
case SEND:
Kernel_Send(Cp->channel, Cp->message);
break;
case RECV:
Kernel_Recv(Cp->channel);
break;
case WRITE:
Kernel_Write(Cp->channel, Cp->message);
break;
default:
// Houston! we have a problem here!
Kernel_OS_Abort(DEFUALT_REQUEST);
break;
}
}
}
/*
* Kernel_Dispatch
*
* Determines which task will run next. This is our scheduler.
*/
void Kernel_Dispatch(void)
{
if(debug)
{
PORTC ^= 0b00010000;
}
// Find the next READY task.
if(system_queue_size > 0)
{
Cp = dequeue_system();
}
else if(ready_periodic_task != NULL)
{
Cp = ready_periodic_task;
ready_periodic_task = NULL;
}
else if(rr_queue_size > 0)
{
Cp = dequeue_rr();
}
CurrentSp = Cp->sp;
Cp->state = RUNNING;
if(debug)
{
PORTC ^= 0b00010000;
}
}
/*
* Kernel_Create_Task_At
*
* Basically just initializes the stack for the new process. This function
* is only ever called by the other create functions.
*
* Params:
* PD *p - The process to create.
* void (*f)(void) - Pointer to the function the tasks will run.
* PID pid - The pid to give to the function.
* PROCESS_PRIORITIES priority - The priority of the new task.
* TICK period - The period of the new task. If periodic priority, else 0.
* TICK wcet - The worse case running time of the task. If periodic priority, else 0.
* TICK offset - The offset of the new task. If periodic priority, else 0.
*/
void Kernel_Create_Task_At(volatile PD *p, voidfuncptr f, int arg, PID pid, PROCESS_PRIORITIES priority, TICK period, TICK wcet, TICK offset)
{
unsigned char *sp;
// Changed -2 to -1 to fix off by one error.
sp = (unsigned char *) &(p->workSpace[WORKSPACE-1]);
// Clear the contents of the workspace.
memset(&(p->workSpace),0,WORKSPACE);
// Store terminate at the bottom of stack to protect against stack under run.
*(unsigned char *)sp-- = ((unsigned int)Kernel_Task_Terminate) & 0xff;
*(unsigned char *)sp-- = (((unsigned int)Kernel_Task_Terminate) >> 8) & 0xff;
// This catches Tasks that returned instead of looping forever.
*(unsigned char *)sp-- = 0;
// Place return address of function at bottom of stack.
*(unsigned char *)sp-- = ((unsigned int)f) & 0xff;
*(unsigned char *)sp-- = (((unsigned int)f) >> 8) & 0xff;
// Fixing part of the 17-bit problem.
*(unsigned char *)sp-- = 0;
// Place stack pointer at top of stack.
sp = sp - 34;
p->sp = sp; // Stack pointer into the "workSpace".
p->code = f; // Function to be executed as a task.
p->request = NONE;
p->creation_arg = arg;
p->pid = pid;
p->priority = priority;
p->period = period;
p->wcet = wcet;
p->offset = offset;
p->num_ticks_remaining = offset;
p->state = READY;
switch(p->priority)
{
case SYSTEM:
++System_Tasks;
enqueue_system(p);
break;
case PERIODIC:
periodic_lookup[Periodic_Tasks++] = p;
break;
case ROUNDROBIN:
p->num_ticks_remaining = MSECPERTICK; // An RR task can only run for 1 tick at a time. But this is checked and updated every 1ms so set to MSECPERTICK.
++RR_Tasks;
enqueue_rr(p);
break;
default:
Kernel_OS_Abort(DEFUALT_PRIORITY);
break;
}
++Tasks;
}
/*
* Kernel_Task_Create_System
*
* Creates a task with System level priority.
*
* Params:
* void (*f)(void) - Pointer to the function the tasks will run.
* int arg - An integer number to be assigned to this process instance.
*/
void Kernel_Task_Create_System(void (*f)(void), int arg)
{
int x;
if (Tasks == MAXTHREAD)
{
Cp->pid = 0; // Too many task!
}
else
{
// Find a DEAD PD that we can use.
for (x = 0; x < MAXTHREAD; x++)
{
if (Process[x].state == DEAD) break;
}
Kernel_Create_Task_At(&(Process[x]), f, arg, x, SYSTEM, 0, 0, 0);
}
}
/*
* Kernel_Task_Create_Round_Robin
*
* Creates a task with RR level priority.
*
* Params:
* void (*f)(void) - Pointer to the function the tasks will run.
* int arg - An integer number to be assigned to this process instance.
*/
void Kernel_Task_Create_Round_Robin(void (*f)(void), int arg)
{
int x;
if (Tasks == MAXTHREAD)
{
Cp->pid = 0; // Too many task!
}
else
{
// Find a DEAD PD that we can use.
for (x = 0; x < MAXTHREAD; x++)
{
if (Process[x].state == DEAD) break;
}
Kernel_Create_Task_At(&(Process[x]), f, arg, x, ROUNDROBIN, 0, 0, 0);
}
}
/*
* Kernel_Task_Create_Periodic
*
* Creates a periodic task with the periodic priority level.
*
* Params:
* void (*f)(void) - Pointer to the function the tasks will run.
* int arg - An integer number to be assigned to this process instance.
* TICK period - Tasks execution period in TICKs.
* TICK wcet - Worst case execution time of the task in TICKs; must be less then period.
* TICK offset - Tasks start offset in TICKs.
*/
void Kernel_Task_Create_Periodic(void (*f)(void), int arg, TICK period, TICK wcet, TICK offset)
{
int x;
if (Tasks == MAXTHREAD)
{
Cp->pid = 0; // Too many task!
}
else
{
// Find a DEAD PD that we can use.
for (x = 0; x < MAXTHREAD; x++)
{
if (Process[x].state == DEAD) break;
}
Kernel_Create_Task_At(&(Process[x]), f, arg, x, PERIODIC, period, wcet, offset);
}
}
/*
* Kernel_Task_Terminate
*
* Terminates the calling task.
*/
void Kernel_Task_Terminate()
{
if (KernelActive)
{
Disable_Interrupt();
Cp -> request = TERMINATE;
switch(Cp->priority)
{
case SYSTEM:
System_Tasks--;
break;
case PERIODIC:
Periodic_Tasks--;
break;
case ROUNDROBIN:
RR_Tasks--;
break;
default:
Kernel_OS_Abort(DEFUALT_PRIORITY);
break;
}
Tasks--;
Enter_Kernel(); // Never returns here.
}
}
/*
* Kernel_Chan_Init
*
* Initializes a channel.
*/
void Kernel_Chan_Init()
{
if(Channels >= MAXCHAN)
{
Cp->return_value = 0; // No more uninitialized channels.
}
else
{
channel_descriptors[Channels].sender = NULL;
channel_descriptors[Channels].num_receivers = 0;
Channels++;
channel_descriptors[Channels].number = Channels;
Cp->return_value = Channels;
}
}
/*
* Kernel_Send
*
* Sends the message v over channel ch.
* - If there are no receivers the calling task is blocked.
* - Else if there is already a sender on this channel the RTOS will abort in an error state.
* - Else the message will be sent over the channel and the task will not be blocked.
*
* Params:
* CHAN ch - The CHAN number to send the message over.
* int v - Message to send over the channel.
*/
void Kernel_Send(CHAN ch, int v)
{
// Error checking.
if(ch > MAXCHAN || ch < 1)
{
Kernel_OS_Abort(CHAN_NUM_OUT_OF_RANGE);
}
else if(ch > Channels)
{
Kernel_OS_Abort(CHAN_NOT_INITIALIZED);
}
else if(Cp->priority == PERIODIC)
{
Kernel_OS_Abort(PERIODIC_TASK_CALLING_BLOCKING_FUNCTION);
}
else if(channel_descriptors[ch].sender != NULL && channel_descriptors[ch].sender == Cp)
{
Kernel_OS_Abort(MULTIPLE_SENDERS);
}
channel_descriptors[ch].sender = Cp;
if(channel_descriptors[ch].num_receivers == 0)
{
Cp->state = BLOCKED;
Kernel_Dispatch();
}
int i;
for(i = channel_descriptors[ch].num_receivers - 1; i >= 0; i--)
{
channel_descriptors[ch].receivers[i]->state = READY;
channel_descriptors[ch].num_receivers--;
channel_descriptors[ch].receivers[i]->message = v;
switch(channel_descriptors[ch].receivers[i]->priority)
{
case SYSTEM:
enqueue_system(channel_descriptors[ch].receivers[i]);
break;
case ROUNDROBIN:
enqueue_rr(channel_descriptors[ch].receivers[i]);
break;
default:
Kernel_OS_Abort(DEFUALT_PRIORITY);
break;
}
}
channel_descriptors[ch].num_receivers = 0;
channel_descriptors[ch].sender = NULL;
}
/*
* Kernel_Recv
*
* Receives a message over channel ch.
* - If there is no sender on the channel the calling task will be blocked.
* - Else the message will be received and the calling task will not be blocked
*
* Params:
* CHAN ch - The channel to receive a message over.
*/
void Kernel_Recv(CHAN ch)
{
// Error checking.
if(ch > MAXCHAN || ch < 1)
{
Kernel_OS_Abort(CHAN_NUM_OUT_OF_RANGE);
}
else if(ch > Channels)
{
Kernel_OS_Abort(CHAN_NOT_INITIALIZED);
}
else if(Cp->priority == PERIODIC)
{
Kernel_OS_Abort(PERIODIC_TASK_CALLING_BLOCKING_FUNCTION);
}
if(channel_descriptors[ch].sender == NULL)
{
channel_descriptors[ch].receivers[channel_descriptors[ch].num_receivers++] = Cp;
Cp->state = BLOCKED;
Kernel_Dispatch();
}
else
{
channel_descriptors[ch].sender->state = READY;
}
}
/*
* Kernel_Write
*
* Sends the message v over channel ch, but do not wait if there are no receivers.
* - If there is already a sender on the channel the RTOS will abort in an error state.
* - Else send the message over the channel; the calling task will not be blocked.
*
* Params:
* CHAN ch - Channel to send the message over.
* int v - Message to send over the channel.
*/
void Kernel_Write(CHAN ch, int v)
{
// Error checking.
if(ch > MAXCHAN || ch < 1)
{
Kernel_OS_Abort(CHAN_NUM_OUT_OF_RANGE);
}
else if(ch > Channels)
{
Kernel_OS_Abort(CHAN_NOT_INITIALIZED);
}
else if(channel_descriptors[ch].sender != NULL)
{
Kernel_OS_Abort(MULTIPLE_SENDERS);
}
int i;
for(i = channel_descriptors[ch].num_receivers - 1; i >= 0; i--)
{
channel_descriptors[ch].receivers[i]->state = READY;
channel_descriptors[ch].num_receivers--;
channel_descriptors[ch].receivers[i]->return_value = v;
switch(channel_descriptors[ch].receivers[i]->priority)
{
case SYSTEM:
enqueue_system(channel_descriptors[ch].receivers[i]);
break;
case ROUNDROBIN:
enqueue_rr(channel_descriptors[ch].receivers[i]);
break;
default:
Kernel_OS_Abort(DEFUALT_PRIORITY);
break;
}
}
}
/*
* enqueue_system
*
* Enqueues the PD of a ready system task into the system ready queue.
*
* Params:
* PD* p - Pointer to the tasks process descriptor.
*/
void enqueue_system(volatile PD* p)
{
if(system_queue_size < MAXTHREAD)
{
if(system_queue_rear == MAXTHREAD - 1)
{
system_queue_rear = -1;
}
system_queue[++system_queue_rear] = p;
system_queue_size++;
}
}
/*
* dequeue_system
*
* Dequeues the PD of the task that is going to be ran form the system ready queue.
*
* Return:
* PD* p - Pointer to the tasks process descriptor that was removed.
*/
PD* dequeue_system(void)
{
PD* p = system_queue[system_queue_front++];
if(system_queue_front == MAXTHREAD)
{
system_queue_front = 0;
}
system_queue_size--;
return p;
}
/*
* enqueue_rr
*
* Enqueues the PD of a ready round robin task into the round robin ready queue.
*
* Params:
* PD* p - Pointer to the tasks process descriptor.
*/
void enqueue_rr(volatile PD* p)
{
if(rr_queue_size < MAXTHREAD)
{
if(rr_queue_rear == MAXTHREAD - 1)
{
rr_queue_rear = -1;
}
rr_queue[++rr_queue_rear] = p;
rr_queue_size++;
}
}
/*
* dequeue_rr
*
* Dequeues the PD of the task that is going to be ran form the round robin ready queue.
*
* Return:
* PD* p - Pointer to the tasks process descriptor that was removed.
*/
PD* dequeue_rr(void)
{
PD* p = rr_queue[rr_queue_front++];
if(rr_queue_front == MAXTHREAD)
{
rr_queue_front = 0;
}
rr_queue_size--;
return p;
}
int main(void)
{
// Initialize OS.
Kernel_OS_Init();
// Create the idle task.
Kernel_Task_Create_Round_Robin(Kernel_Idle_Task, 0);
// Call user space main so all user tasks can be created.
//Kernel_Task_Create_System(main_a, 0);
main_a();
// Start the OS. This should never return.
Kernel_OS_Start();
// If Kernel_OS_Start returns go into abort state.
Kernel_OS_Abort(OS_START_RETURNED);
return 1;
}
| 2.234375 | 2 |
2024-11-18T19:02:29.359235+00:00
| 2015-09-25T15:56:48 |
58b12b5c2ae8d74be9e7e986ec10f2a33f977618
|
{
"blob_id": "58b12b5c2ae8d74be9e7e986ec10f2a33f977618",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-25T15:56:48",
"content_id": "f59b78dd15c687b023f6adb8dbf2841d1626a44f",
"detected_licenses": [
"Unlicense"
],
"directory_id": "02bf92ac87c9a9bf9126c006d90bd7fcace5523f",
"extension": "c",
"filename": "check_arithmetic.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 40046204,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 27293,
"license": "Unlicense",
"license_type": "permissive",
"path": "/check_arithmetic.c",
"provenance": "stackv2-0058.json.gz:152148",
"repo_name": "sahandKashani/prime-field-arithmetic-AVX2",
"revision_date": "2015-09-25T15:56:48",
"revision_id": "cb186011079d4500ec6ad8866273c7228c9848d2",
"snapshot_id": "b564aa19fb9d187f84f5358cdf04ca6cf6be64cc",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/sahandKashani/prime-field-arithmetic-AVX2/cb186011079d4500ec6ad8866273c7228c9848d2/check_arithmetic.c",
"visit_date": "2021-01-15T13:48:22.490641"
}
|
stackv2
|
#include <stdio.h>
#include "check_arithmetic.h"
#include "gmp_int.h"
#include "constants.h"
#include "limb.h"
#include "utilities.h"
#include "prime_field.h"
bool test_add_num_num(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t res_gmp;
gmp_int_t mod_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(res_gmp);
gmp_int_init(mod_gmp);
limb_t op1[NUM_LIMBS];
limb_t op2[NUM_LIMBS];
limb_t res[NUM_LIMBS];
limb_t carry_in;
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
three_sorted_gmp operands = get_three_sorted_gmp(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
gmp_int_set(op1_gmp, operands.small);
gmp_int_set(op2_gmp, operands.middle);
gmp_int_set(mod_gmp, operands.big);
zero_num(op1, NUM_LIMBS);
zero_num(op2, NUM_LIMBS);
zero_num(res, NUM_LIMBS);
zero_num(&carry_in, 1);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(op2, op2_gmp, NUM_LIMBS);
gmp_int_add(res_gmp, op1_gmp, op2_gmp);
add_num_num(res, op1, op2, NUM_LIMBS, carry_in);
if (!is_equal_num_gmp(res, res_gmp, NUM_LIMBS)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, NUM_LIMBS);
print_num(op2, NUM_LIMBS);
print_num_gmp(res_gmp, NUM_LIMBS);
print_num(res, NUM_LIMBS);
success = false;
add_num_num(res, op1, op2, NUM_LIMBS, carry_in);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(res_gmp);
gmp_int_clear(mod_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_add_num_limb(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t res_gmp;
gmp_int_t mod_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(res_gmp);
gmp_int_init(mod_gmp);
limb_t op1[NUM_LIMBS];
limb_t op2;
limb_t res[NUM_LIMBS];
limb_t carry_in;
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
three_sorted_gmp operands = get_three_sorted_gmp(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
gmp_int_set(op1_gmp, operands.middle);
gmp_int_set(mod_gmp, operands.big);
generate_random_gmp_number(op2_gmp, BASE_EXPONENT, gmp_random_state);
zero_num(op1, NUM_LIMBS);
zero_num(&op2, 1);
zero_num(res, NUM_LIMBS);
zero_num(&carry_in, 1);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(&op2, op2_gmp, 1);
gmp_int_add(res_gmp, op1_gmp, op2_gmp);
add_num_limb(res, op1, op2, NUM_LIMBS, carry_in);
if (!is_equal_num_gmp(res, res_gmp, NUM_LIMBS)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, 1);
print_num(&op2, 1);
print_num_gmp(res_gmp, NUM_LIMBS);
print_num(res, NUM_LIMBS);
success = false;
add_num_limb(res, op1, op2, NUM_LIMBS, carry_in);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(res_gmp);
gmp_int_clear(mod_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_sub_num_num(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t res_gmp;
gmp_int_t mod_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(res_gmp);
gmp_int_init(mod_gmp);
limb_t op1[NUM_LIMBS];
limb_t op2[NUM_LIMBS];
limb_t res[NUM_LIMBS];
limb_t borrow_in;
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
three_sorted_gmp operands = get_three_sorted_gmp(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
/* op2 has to be smaller than op1 since this is normal subtraction (not modular) */
gmp_int_set(op1_gmp, operands.middle);
gmp_int_set(op2_gmp, operands.small);
gmp_int_set(mod_gmp, operands.big);
zero_num(op1, NUM_LIMBS);
zero_num(op2, NUM_LIMBS);
zero_num(res, NUM_LIMBS);
zero_num(&borrow_in, 1);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(op2, op2_gmp, NUM_LIMBS);
gmp_int_sub(res_gmp, op1_gmp, op2_gmp);
sub_num_num(res, op1, op2, NUM_LIMBS, borrow_in);
if (!is_equal_num_gmp(res, res_gmp, NUM_LIMBS)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, NUM_LIMBS);
print_num(op2, NUM_LIMBS);
print_num_gmp(res_gmp, NUM_LIMBS);
print_num(res, NUM_LIMBS);
success = false;
sub_num_num(res, op1, op2, NUM_LIMBS, borrow_in);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(res_gmp);
gmp_int_clear(mod_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_mul_limb_limb(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t res_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(res_gmp);
limb_t op1;
limb_t op2;
limb_t res[2];
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
generate_random_gmp_number(op1_gmp, BASE_EXPONENT, gmp_random_state);
generate_random_gmp_number(op2_gmp, BASE_EXPONENT, gmp_random_state);
zero_num(&op1, 1);
zero_num(&op2, 1);
zero_num(res, 2);
convert_gmp_to_num(&op1, op1_gmp, 1);
convert_gmp_to_num(&op2, op2_gmp, 1);
gmp_int_mul(res_gmp, op1_gmp, op2_gmp);
struct d_limb_t tmp = mul_limb_limb(op1, op2);
#if !FULL_LIMB_PRECISION
tmp = reduce_to_base_d_limb_t(tmp);
#endif
res[1] = tmp.hi;
res[0] = tmp.lo;
if (!is_equal_num_gmp(res, res_gmp, 2)) {
print_num_gmp(op1_gmp, 1);
print_num(&op1, 1);
print_num_gmp(op2_gmp, 1);
print_num(&op2, 1);
print_num_gmp(res_gmp, 2);
print_num(res, 2);
success = false;
mul_limb_limb(op1, op2);
}
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(res_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_mul_num_limb(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t res_gmp;
gmp_int_t mod_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(res_gmp);
gmp_int_init(mod_gmp);
limb_t op1[NUM_LIMBS];
limb_t op2;
limb_t res[NUM_LIMBS + 1];
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
three_sorted_gmp operands = get_three_sorted_gmp(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
gmp_int_set(op1_gmp, operands.middle);
gmp_int_set(mod_gmp, operands.big);
generate_random_gmp_number(op2_gmp, BASE_EXPONENT, gmp_random_state);
zero_num(op1, NUM_LIMBS);
zero_num(&op2, 1);
zero_num(res, NUM_LIMBS);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(&op2, op2_gmp, 1);
gmp_int_mul(res_gmp, op1_gmp, op2_gmp);
mul_num_limb(res, op1, op2, NUM_LIMBS);
if (!is_equal_num_gmp(res, res_gmp, NUM_LIMBS + 1)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, 1);
print_num(&op2, 1);
print_num_gmp(res_gmp, NUM_LIMBS + 1);
print_num(res, NUM_LIMBS + 1);
success = false;
mul_num_limb(res, op1, op2, NUM_LIMBS);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(res_gmp);
gmp_int_clear(mod_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_mul_num_num(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t res_gmp;
gmp_int_t mod_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(res_gmp);
gmp_int_init(mod_gmp);
limb_t op1[NUM_LIMBS];
limb_t op2[NUM_LIMBS];
limb_t res[2 * NUM_LIMBS];
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
three_sorted_gmp operands = get_three_sorted_gmp(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
gmp_int_set(op1_gmp, operands.small);
gmp_int_set(op2_gmp, operands.middle);
gmp_int_set(mod_gmp, operands.big);
zero_num(op1, NUM_LIMBS);
zero_num(op2, NUM_LIMBS);
zero_num(res, 2 * NUM_LIMBS);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(op2, op2_gmp, NUM_LIMBS);
gmp_int_mul(res_gmp, op1_gmp, op2_gmp);
mul_num_num(res, op1, op2, NUM_LIMBS);
if (!is_equal_num_gmp(res, res_gmp, 2 * NUM_LIMBS)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, NUM_LIMBS);
print_num(op2, NUM_LIMBS);
print_num_gmp(res_gmp, 2 * NUM_LIMBS);
print_num(res, 2 * NUM_LIMBS);
success = false;
mul_num_num(res, op1, op2, NUM_LIMBS);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(res_gmp);
gmp_int_clear(mod_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_add_mod_num_num(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t mod_gmp;
gmp_int_t res_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(mod_gmp);
gmp_int_init(res_gmp);
limb_t op1[NUM_LIMBS];
limb_t op2[NUM_LIMBS];
limb_t mod[NUM_LIMBS];
limb_t res[NUM_LIMBS];
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
three_sorted_gmp operands = get_three_sorted_gmp(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
gmp_int_set(op1_gmp, operands.small);
gmp_int_set(op2_gmp, operands.middle);
gmp_int_set(mod_gmp, operands.big);
zero_num(op1, NUM_LIMBS);
zero_num(op2, NUM_LIMBS);
zero_num(mod, NUM_LIMBS);
zero_num(res, NUM_LIMBS);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(op2, op2_gmp, NUM_LIMBS);
convert_gmp_to_num(mod, mod_gmp, NUM_LIMBS);
gmp_int_add_mod(res_gmp, op1_gmp, op2_gmp, mod_gmp);
add_mod_num_num(res, op1, op2, mod, NUM_LIMBS);
if (!is_equal_num_gmp(res, res_gmp, NUM_LIMBS)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, NUM_LIMBS);
print_num(op2, NUM_LIMBS);
print_num_gmp(mod_gmp, NUM_LIMBS);
print_num(mod, NUM_LIMBS);
print_num_gmp(res_gmp, NUM_LIMBS);
print_num(res, NUM_LIMBS);
success = false;
add_mod_num_num(res, op1, op2, mod, NUM_LIMBS);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(mod_gmp);
gmp_int_clear(res_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_sub_mod_num_num(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t mod_gmp;
gmp_int_t res_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(mod_gmp);
gmp_int_init(res_gmp);
limb_t op1[NUM_LIMBS];
limb_t op2[NUM_LIMBS];
limb_t mod[NUM_LIMBS];
limb_t res[NUM_LIMBS];
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
three_sorted_gmp operands = get_three_sorted_gmp(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
gmp_int_set(op1_gmp, operands.small);
gmp_int_set(op2_gmp, operands.middle);
gmp_int_set(mod_gmp, operands.big);
zero_num(op1, NUM_LIMBS);
zero_num(op2, NUM_LIMBS);
zero_num(mod, NUM_LIMBS);
zero_num(res, NUM_LIMBS);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(op2, op2_gmp, NUM_LIMBS);
convert_gmp_to_num(mod, mod_gmp, NUM_LIMBS);
gmp_int_sub_mod(res_gmp, op1_gmp, op2_gmp, mod_gmp);
sub_mod_num_num(res, op1, op2, mod, NUM_LIMBS);
if (!is_equal_num_gmp(res, res_gmp, NUM_LIMBS)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, NUM_LIMBS);
print_num(op2, NUM_LIMBS);
print_num_gmp(mod_gmp, NUM_LIMBS);
print_num(mod, NUM_LIMBS);
print_num_gmp(res_gmp, NUM_LIMBS);
print_num(res, NUM_LIMBS);
success = false;
sub_mod_num_num(res, op1, op2, mod, NUM_LIMBS);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(mod_gmp);
gmp_int_clear(res_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_mul_montgomery_num_num(unsigned int number_of_tests, unsigned int seed) {
gmp_randstate_t gmp_random_state;
gmp_randinit_default(gmp_random_state);
gmp_randseed_ui(gmp_random_state, seed);
gmp_int_t op1_gmp;
gmp_int_t op2_gmp;
gmp_int_t mod_gmp;
gmp_int_t mod_prime_gmp;
gmp_int_t res_gmp;
gmp_int_t base_gmp;
gmp_int_t R_gmp;
gmp_int_t invR_gmp;
gmp_int_init(op1_gmp);
gmp_int_init(op2_gmp);
gmp_int_init(mod_gmp);
gmp_int_init(mod_prime_gmp);
gmp_int_init(res_gmp);
gmp_int_init(base_gmp);
gmp_int_init(R_gmp);
gmp_int_init(invR_gmp);
gmp_int_ui_pow_ui(base_gmp, 2, BASE_EXPONENT);
gmp_int_ui_pow_ui(R_gmp, 2, BASE_EXPONENT * NUM_LIMBS);
limb_t op1[NUM_LIMBS];
limb_t op2[NUM_LIMBS];
limb_t mod[NUM_LIMBS];
limb_t mod_prime;
limb_t res[NUM_LIMBS];
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i++) {
generate_random_gmp_number(mod_gmp, PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state);
three_sorted_gmp operands = get_three_sorted_gmp_with_inverse(PRIME_FIELD_BINARY_BIT_LENGTH, gmp_random_state, mod_gmp);
gmp_int_neg(mod_prime_gmp, mod_prime_gmp);
gmp_int_mod(mod_prime_gmp, mod_prime_gmp, base_gmp);
gmp_int_invert(NULL, invR_gmp, R_gmp, mod_gmp);
zero_num(op1, NUM_LIMBS);
zero_num(op2, NUM_LIMBS);
zero_num(mod, NUM_LIMBS);
zero_num(&mod_prime, 1);
zero_num(res, NUM_LIMBS);
convert_gmp_to_num(op1, op1_gmp, NUM_LIMBS);
convert_gmp_to_num(op2, op2_gmp, NUM_LIMBS);
convert_gmp_to_num(mod, mod_gmp, NUM_LIMBS);
convert_gmp_to_num(&mod_prime, mod_prime_gmp, 1);
gmp_int_mul(res_gmp, op1_gmp, op2_gmp);
gmp_int_mul(res_gmp, res_gmp, invR_gmp);
gmp_int_mod(res_gmp, res_gmp, mod_gmp);
mul_montgomery_num_num(res, op1, op2, mod, mod_prime, NUM_LIMBS);
if (!is_equal_num_gmp(res, res_gmp, NUM_LIMBS)) {
print_num_gmp(op1_gmp, NUM_LIMBS);
print_num(op1, NUM_LIMBS);
print_num_gmp(op2_gmp, NUM_LIMBS);
print_num(op2, NUM_LIMBS);
print_num_gmp(mod_gmp, NUM_LIMBS);
print_num(mod, NUM_LIMBS);
print_num_gmp(res_gmp, NUM_LIMBS);
print_num(res, NUM_LIMBS);
success = false;
mul_montgomery_num_num(res, op1, op2, mod, mod_prime, NUM_LIMBS);
}
clear_three_sorted_gmp(operands);
}
gmp_int_clear(op1_gmp);
gmp_int_clear(op2_gmp);
gmp_int_clear(mod_gmp);
gmp_int_clear(mod_prime_gmp);
gmp_int_clear(res_gmp);
gmp_int_clear(base_gmp);
gmp_int_clear(R_gmp);
gmp_int_clear(invR_gmp);
gmp_randclear(gmp_random_state);
return success;
}
bool test_point_addition(unsigned int number_of_tests) {
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i += 2) {
struct curve_point p1;
struct curve_point_gmp p1_gmp;
curve_point_init_gmp(&p1_gmp);
struct curve_point p2;
struct curve_point_gmp p2_gmp;
curve_point_init_gmp(&p2_gmp);
struct curve_point p3;
struct curve_point_gmp p3_gmp;
curve_point_init_gmp(&p3_gmp);
/* set p1 */
gmp_int_set(p1_gmp.x, points_x_glo_gmp[i]);
gmp_int_set(p1_gmp.y, points_y_glo_gmp[i]);
copy_num(p1.x, points_x_glo[i], NUM_LIMBS);
copy_num(p1.y, points_y_glo[i], NUM_LIMBS);
/* set p2 */
gmp_int_set(p2_gmp.x, points_x_glo_gmp[i+1]);
gmp_int_set(p2_gmp.y, points_y_glo_gmp[i+1]);
copy_num(p2.x, points_x_glo[i+1], NUM_LIMBS);
copy_num(p2.y, points_y_glo[i+1], NUM_LIMBS);
/* to montgomery representation */
standard_to_montgomery_representation_point_gmp(&p1_gmp);
standard_to_montgomery_representation_point_gmp(&p2_gmp);
standard_to_montgomery_representation_point(&p1);
standard_to_montgomery_representation_point(&p2);
/* point addition */
add_point_point_gmp(&p3_gmp, &p1_gmp, &p2_gmp);
add_point_point(&p3, &p1, &p2, NUM_LIMBS);
montgomery_to_standard_representation_point(&p1);
montgomery_to_standard_representation_point_gmp(&p1_gmp);
montgomery_to_standard_representation_point(&p2);
montgomery_to_standard_representation_point_gmp(&p2_gmp);
montgomery_to_standard_representation_point(&p3);
montgomery_to_standard_representation_point_gmp(&p3_gmp);
bool on_curve = is_on_curve_point(p3, NUM_LIMBS);
bool on_curve_gmp = is_on_curve_point_gmp(p3_gmp);
if (!(on_curve && on_curve_gmp)) {
print_num(p1.x, NUM_LIMBS);
print_num(p1.y, NUM_LIMBS);
print_num(p2.x, NUM_LIMBS);
print_num(p2.y, NUM_LIMBS);
print_num(p3.x, NUM_LIMBS);
print_num(p3.y, NUM_LIMBS);
print_num_gmp(p1_gmp.x, NUM_LIMBS);
print_num_gmp(p1_gmp.y, NUM_LIMBS);
print_num_gmp(p2_gmp.x, NUM_LIMBS);
print_num_gmp(p2_gmp.y, NUM_LIMBS);
print_num_gmp(p3_gmp.x, NUM_LIMBS);
print_num_gmp(p3_gmp.y, NUM_LIMBS);
success = false;
}
curve_point_clear_gmp(&p1_gmp);
curve_point_clear_gmp(&p2_gmp);
curve_point_clear_gmp(&p3_gmp);
}
return success;
}
bool test_point_double(unsigned int number_of_tests) {
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i += 1) {
struct curve_point p1;
struct curve_point_gmp p1_gmp;
curve_point_init_gmp(&p1_gmp);
struct curve_point p2;
struct curve_point_gmp p2_gmp;
curve_point_init_gmp(&p2_gmp);
/* set p1 */
gmp_int_set(p1_gmp.x, points_x_glo_gmp[i]);
gmp_int_set(p1_gmp.y, points_y_glo_gmp[i]);
copy_num(p1.x, points_x_glo[i], NUM_LIMBS);
copy_num(p1.y, points_y_glo[i], NUM_LIMBS);
/* to montgomery representation */
standard_to_montgomery_representation_point_gmp(&p1_gmp);
standard_to_montgomery_representation_point(&p1);
/* point double */
double_point_gmp(&p2_gmp, &p1_gmp);
double_point(&p2, &p1, NUM_LIMBS);
montgomery_to_standard_representation_point(&p1);
montgomery_to_standard_representation_point_gmp(&p1_gmp);
montgomery_to_standard_representation_point(&p2);
montgomery_to_standard_representation_point_gmp(&p2_gmp);
bool on_curve = is_on_curve_point(p2, NUM_LIMBS);
bool on_curve_gmp = is_on_curve_point_gmp(p2_gmp);
if (!(on_curve && on_curve_gmp)) {
printf("on_curve = %d\n", on_curve);
printf("on_curve_gmp = %d\n", on_curve_gmp);
print_num(p1.x, NUM_LIMBS);
print_num(p1.y, NUM_LIMBS);
print_num(p2.x, NUM_LIMBS);
print_num(p2.y, NUM_LIMBS);
print_num_gmp(p1_gmp.x, NUM_LIMBS);
print_num_gmp(p1_gmp.y, NUM_LIMBS);
print_num_gmp(p2_gmp.x, NUM_LIMBS);
print_num_gmp(p2_gmp.y, NUM_LIMBS);
success = false;
}
curve_point_clear_gmp(&p1_gmp);
curve_point_clear_gmp(&p2_gmp);
}
return success;
}
bool test_point_neg(unsigned int number_of_tests) {
bool success = true;
for (unsigned int i = 0; (i < (number_of_tests / NUM_ENTRIES_IN_LIMB)) && success; i += 1) {
struct curve_point p1;
struct curve_point_gmp p1_gmp;
curve_point_init_gmp(&p1_gmp);
struct curve_point p2;
struct curve_point_gmp p2_gmp;
curve_point_init_gmp(&p2_gmp);
/* set p1 */
gmp_int_set(p1_gmp.x, points_x_glo_gmp[i]);
gmp_int_set(p1_gmp.y, points_y_glo_gmp[i]);
copy_num(p1.x, points_x_glo[i], NUM_LIMBS);
copy_num(p1.y, points_y_glo[i], NUM_LIMBS);
/* to montgomery representation */
standard_to_montgomery_representation_point_gmp(&p1_gmp);
standard_to_montgomery_representation_point(&p1);
/* point neg */
neg_point_gmp(&p2_gmp, &p1_gmp);
neg_point(&p2, &p1, NUM_LIMBS);
montgomery_to_standard_representation_point(&p1);
montgomery_to_standard_representation_point_gmp(&p1_gmp);
montgomery_to_standard_representation_point(&p2);
montgomery_to_standard_representation_point_gmp(&p2_gmp);
bool on_curve = is_on_curve_point(p2, NUM_LIMBS);
bool on_curve_gmp = is_on_curve_point_gmp(p2_gmp);
if (!(on_curve && on_curve_gmp)) {
print_num(p1.x, NUM_LIMBS);
print_num(p1.y, NUM_LIMBS);
print_num(p2.x, NUM_LIMBS);
print_num(p2.y, NUM_LIMBS);
print_num_gmp(p1_gmp.x, NUM_LIMBS);
print_num_gmp(p1_gmp.y, NUM_LIMBS);
print_num_gmp(p2_gmp.x, NUM_LIMBS);
print_num_gmp(p2_gmp.y, NUM_LIMBS);
success = false;
}
curve_point_clear_gmp(&p1_gmp);
curve_point_clear_gmp(&p2_gmp);
}
return success;
}
void check_add_num_num(unsigned int number_of_tests, unsigned int seed) {
printf("Add:\n");
if (test_add_num_num(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_add_num_limb(unsigned int number_of_tests, unsigned int seed) {
printf("add_num_limb:\n");
if (test_add_num_limb(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_sub_num_num(unsigned int number_of_tests, unsigned int seed) {
printf("Sub:\n");
if (test_sub_num_num(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_mul_limb_limb(unsigned int number_of_tests, unsigned int seed) {
printf("mul_limb_limb:\n");
if (test_mul_limb_limb(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_mul_num_limb(unsigned int number_of_tests, unsigned int seed) {
printf("mul_num_limb:\n");
if (test_mul_num_limb(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_mul_num_num(unsigned int number_of_tests, unsigned int seed) {
printf("Mul:\n");
if (test_mul_num_num(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_add_mod_num_num(unsigned int number_of_tests, unsigned int seed) {
printf("Add Mod:\n");
if (test_add_mod_num_num(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_sub_mod_num_num(unsigned int number_of_tests, unsigned int seed) {
printf("Sub Mod:\n");
if (test_sub_mod_num_num(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_mul_montgomery_num_num(unsigned int number_of_tests, unsigned int seed) {
printf("Mul Montgomery:\n");
if (test_mul_montgomery_num_num(number_of_tests, seed)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_add_point_point(unsigned int number_of_tests) {
printf("Point addition:\n");
if (test_point_addition(number_of_tests)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_double_point(unsigned int number_of_tests) {
printf("Point double:\n");
if (test_point_double(number_of_tests)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
void check_neg_point(unsigned int number_of_tests) {
printf("Point neg:\n");
if (test_point_neg(number_of_tests)) {
printf("Success\n");
} else {
printf("Failed\n");
}
printf("\n");
}
| 2.375 | 2 |
2024-11-18T19:02:29.693422+00:00
| 2022-10-12T16:28:09 |
56501327f6fa1f53347870deaea437728bea70a0
|
{
"blob_id": "56501327f6fa1f53347870deaea437728bea70a0",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-12T16:28:09",
"content_id": "b4ade487a53ea318dccd81b0cc184e698790b6e5",
"detected_licenses": [
"MIT"
],
"directory_id": "899253a3ed2475cf2771a526de257d35d0e7caa9",
"extension": "c",
"filename": "trace.c",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 44961889,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15636,
"license": "MIT",
"license_type": "permissive",
"path": "/trace.c",
"provenance": "stackv2-0058.json.gz:152276",
"repo_name": "nachshonc/AutomaticOptimisticAccess",
"revision_date": "2022-10-12T16:28:09",
"revision_id": "dad63a79e971bc70b086fe2be84e77689ce9100d",
"snapshot_id": "d8b1a3cf3769fa5c89236f637edadc00e0f4b0f0",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/nachshonc/AutomaticOptimisticAccess/dad63a79e971bc70b086fe2be84e77689ce9100d/trace.c",
"visit_date": "2022-10-20T11:11:33.983745"
}
|
stackv2
|
#include "allocator.h"
#include "globals.h" //for dirtyRecord.
#include "lfl.h"
#include "lfhash.h"
#include <assert.h>
#include <stdlib.h>
#include "debugging.h"
int usleep(unsigned int);
extern void *NAME(heapmem)[MAX_CHUNKS];
extern int NAME(heapmemcnt);
#define HEADER_MASK ((long)(~(CHUNK_SIZE-1l)))
#define OFFSET_MASK ((long)(CHUNK_SIZE-1))
#ifndef UNMARK
#define UNMARK(obj) ((void*)(((long)(obj))&(~3ul)))
#endif
#define CLEAR_PTR(obj) (UNMARK((obj)))
static void finishTraceArr(struct localAlloc *local, void ** arr,int len,u64* bits,
void **markstack,u64 localSweep, const unsigned long *const globalSweepPtr);
typedef unsigned long mtype;
#define BITS_PER_MTYPE (sizeof(mtype)*8)
static inline void get_mark_params(void *ptr, mtype **out_h_ptr,
mtype *out_mask){
void *base = (void*)((long)ptr & HEADER_MASK);
int offset = (long)ptr & OFFSET_MASK;
offset/=NODE_SIZE;
*out_h_ptr = (mtype*)base + offset/(BITS_PER_MTYPE/2);
*out_mask= (mtype)1<<(offset&(BITS_PER_MTYPE/2-1));
}
static inline int is_marked(void *ptr){
mtype *h_ptr, mask;
get_mark_params(ptr, &h_ptr, &mask);
return (*h_ptr)&mask;
}
//@localPhase: the phase reside at the highest 32 bits. The other bits are zeros.
static inline int __mark(mtype *h_ptr, mtype mask, mtype old,unsigned long localPhase){
if(unlikely(!is_cur_phase(old, localPhase)))
return 0;
if(CAS(h_ptr, old, old|mask)) return 1;
do{
old=*h_ptr;
if(old&mask) return 0;
//should be optimized for the common case..
if(!is_cur_phase(old, localPhase))
return 0;
}while(!CAS(h_ptr, old, old|mask));
return 1;
}
//@localPhase: the phase reside at the highest 32 bits. The other bits are zeros.
static inline int mark(void *ptr, unsigned long localPhase){
mtype *h_ptr, mask;
get_mark_params(ptr, &h_ptr, &mask);
mtype old = *h_ptr;
if(old&mask) return 0;
return __mark(h_ptr, mask, old, localPhase);
}
//--------------------------------------------------handle global roots.
void **roots[MAX_NUMBER_OF_ROOTS];
void *arr_marktable[MAX_NUMBER_OF_ROOTS];
int rootLen[MAX_NUMBER_OF_ROOTS];
int NAME(currentRoot)=0;
void NAME(addGlobalRoot)(void **root, int len){
int idx = __sync_fetch_and_add(&NAME(currentRoot), 1); assert(idx<MAX_NUMBER_OF_ROOTS);
roots[idx]=root;
rootLen[idx]=len;
if(len>1){
//allocate marktable for the array, and an additional synchronization counter.
int array_marktable_size = (len+ENTRIES_PER_WORD-1)/(ENTRIES_PER_WORD)*sizeof(u64);
arr_marktable[idx]=malloc(array_marktable_size + sizeof(u64));
memset(arr_marktable[idx], 0, array_marktable_size + sizeof(u64));
}
}
static inline void clearRootsMark(struct localAlloc *local){
for(int i=0; i<NAME(currentRoot); ++i){
if(rootLen[i]!=1){
int array_marktable_size = (rootLen[i]+ENTRIES_PER_WORD-1)/(ENTRIES_PER_WORD)*sizeof(u64);
clearArrMarks(local, local->localVer, arr_marktable[0], array_marktable_size+sizeof(u64));
}
}
}
static void traceArr(void **arr, const int len, void *base, struct localAlloc *local);
static void traceRoots(struct localAlloc *local, int *pcounter){
for(int i=0; i<NAME(currentRoot); ++i){
if(rootLen[i]!=1){
traceArr(roots[i], rootLen[i], arr_marktable[i], local);
}
else{
void *child=CLEAR_PTR(roots[i][0]);
if(child!=NULL)
local->markstack[++(*pcounter)]=child;
}
}
}
//--------------------------------------------------End handle global roots.
static inline void resetSweepCounter(struct localAlloc *local){
struct allocator *alc = local->global;
unsigned long sweep_ctr, lsweep_ctr;
do{
sweep_ctr=alc->sweep_counter;
if(PHASE(sweep_ctr)>=local->localVer) return;
assert(PHASE(sweep_ctr)==local->localVer-2);
lsweep_ctr = MAKE_SC(0, local->localVer);
}while(!CAS(&alc->sweep_counter, sweep_ctr, lsweep_ctr));
}
static int CheckFinish(struct localAlloc *local, void **markstack, int *counterPtr){
//Check Finish:
struct allocator *alc=local->global;
const int T = alc->numThreads;
const long localVer = local->localVer;
int curPhases[T];
void *tracing[T];
int counter=0;
CheckFinish:
usleep(10);
for(int i=0; i<T; ++i){
struct localAlloc *ai = &alc->locals[i];
curPhases[i]=ai->localVer;
void *trptr = ai->markstack[0];
tracing[i]=trptr;
if(((long)trptr & 1) || curPhases[i]!=localVer)
continue;
void *ptr;
for(int j=1; (ptr=ai->markstack[j])!=NULL; ++j){
if(is_marked(ptr)==0 && counter<10){ //an unmarked pointer.
markstack[++counter]=ptr;
//goto CheckFinish;
}
}
if(is_marked(trptr)==0)
markstack[++counter]=trptr;
}
if(counter>=1){
usleep(2);
*counterPtr=counter;
if(localVer!=alc->phase.phase){//is it relevant to help?
for(int i=1; markstack[i]!=NULL; ++i)
markstack[i]=NULL;
return 1;//Not relevant - finish
}
return 0;//Still in current phase - help (and do not finish)
}
for(int i=0; i<T; ++i){
struct localAlloc *ai = &alc->locals[i];
void *trptr = ai->markstack[0];
if(trptr!=tracing[i] || ai->localVer!=curPhases[i]) goto CheckFinish;
}
return 1;
}
static inline void *getChild(void *obj, int offset){
void **ptr = (void*)(((char*)obj) + offset);
return CLEAR_PTR(*ptr);
}
#if NCHILDS == 1
static inline void traceObj(void *cur, void **markstack, int *pcounter,
unsigned long localSweep){
mtype *h_ptr, mask, old;
get_mark_params(cur, &h_ptr, &mask);
old = *h_ptr;//read mark-bit word
if(old&mask) //if is marked
return; //no need to trace
markstack[0]=cur; //publish
void *nxt = getChild(cur, CHILD1_OFFSET);
if(nxt==NULL) {
__mark(h_ptr, mask, old, localSweep);
}
else{
markstack[*pcounter+1]=nxt;//By TSO this write comes after markstack[0]=cur;
if(__mark(h_ptr, mask, old, localSweep)){
(*pcounter)++;//commit previous write
}
else
markstack[(*pcounter)+1]=NULL;
}
}
#else
static inline void traceObj(void *cur, void **markstack, int *pcounter,
unsigned long localSweep){
if(is_marked(cur, localSweep))
return;
markstack[0]=cur;
int cctr=0;
void *c = getChild(cur, CHILD1_OFFSET);
if(c!=NULL)
markstack[*pcounter+(++cctr)]=c;//put child, tentatively increase counter.
c = getChild(cur, CHILD2_OFFSET);
if(c!=NULL)
markstack[*pcounter+(++cctr)]=c;//put child, tentatively increase counter.
#if NCHILDS > 2
c = getChild(cur, CHILD3_OFFSET);
if(c!=NULL)
markstack[*pcounter+(++cctr)]=c;//put child, tentatively increase counter.
#endif
if(mark(cur, localSweep))
*pcounter += cctr;//commit increase counter.
else
for(int i=1; i<=cctr; ++i)//abort increase counter.
markstack[*pcounter+i]=NULL;//remove written fields.
}
#endif
static void traceMarkstack(void **markstack, int counter, const unsigned long * const globalSweepPtr,
unsigned long localSweep, struct localAlloc *local){
while(counter>=1){
Entry *cur=markstack[counter--];
_assert(cur!=NULL && assert_in_heap(cur));
traceObj(cur, markstack, &counter, localSweep);
}
}
static inline void copyPartOfArr(void **markstack, void **arr, int begin, int *pcounter){
*pcounter=0;
for(int k=0; k<ARR_ENTRIES_PER_BIT; ++k){
void *ptr=arr[begin+k];
if(ptr){
markstack[++(*pcounter)]=ptr;
}
}
}
static int get_arr_chunk(u64 *syn_ctr, int len, u64 localSweep){
u64 ctr=*syn_ctr;
//optimistically check whether the task was already finished before changing the counter.
if((unsigned)ctr*ARR_ENTRIES_PER_BIT>=len) return -1;
if(!is_cur_phase(ctr, localSweep)) return -1; //not the right phase.
ctr=__sync_fetch_and_add(syn_ctr, 1);
if((unsigned)ctr*ARR_ENTRIES_PER_BIT>=len) return -1;
if(!is_cur_phase(ctr, localSweep)) return -1; //not the right phase.
return (int)(ctr&0x7FFFFFFF);
}
//mark an array bit as finished.This signify that the array chunk is already
//copied to the markstack. If successfully mark the chunk continue with marking children.
static int sign_bit(u64 *bits_ptr, int bit, u64 localSweep){
u64 mask = 1ull<<bit, old;
do{
old = *bits_ptr;
if(!is_cur_phase(old, localSweep)) return 0;//false
if(old&mask) return 0;
}while(!CAS(bits_ptr, old, old|mask));
return 1;
}
static void traceArr(void **arr, const int len, void *base, struct localAlloc *local){
const unsigned long localSweep=MAKE_SC(0, local->localVer);
const unsigned long *const globalSweepPtr=&local->global->sweep_counter;
void **markstack=local->markstack;
u64 *syn_ctr=(u64 *)base;//atomic counter to optimistically synchronize effort.
u64 *bits=syn_ctr+1;//markbits to fine tune synchronized effort.
int ctr=0;
while(1){
ctr = get_arr_chunk(syn_ctr, len, localSweep);
if(ctr==-1) break;
int counter=0;
copyPartOfArr(markstack, arr, ctr*ARR_ENTRIES_PER_BIT, &counter);
markstack[0]=markstack[counter];
if(sign_bit(bits+(ctr/32), ctr%32, localSweep))
traceMarkstack(markstack, counter, globalSweepPtr, localSweep, local);
markstack[0]=(void*)((long)markstack[0]|1);//not processing anything right now.
}
finishTraceArr(local, arr, len, bits, markstack, localSweep, globalSweepPtr);
}
//help to finish moving the array into markstacks.
static void finishTraceArr(struct localAlloc *local, void ** arr, int len,u64* bits,
void **markstack,u64 localSweep, const unsigned long *const globalSweepPtr){
int num_markwords = (len/ARR_ENTRIES_PER_BIT)/32;
for(int i=0; i<num_markwords; ++i){
u64 val = bits[i];
if( !is_cur_phase(val, localSweep)) break;
unsigned uval=(unsigned)val;
if(uval==0xFFFFFFFF) continue;//work finished for this qword
for(int j=0; j<32; ++j){
if((uval&(1<<j))==0){
int counter=0;
copyPartOfArr(markstack, arr, (i*32+j)*ARR_ENTRIES_PER_BIT, &counter);
markstack[0]=markstack[counter];
if(sign_bit(bits+i, j, localSweep))
traceMarkstack(markstack, counter, globalSweepPtr, localSweep, local);
markstack[0]=(void*)((long)markstack[0]|1);//not processing anything right now.
}
}
}
}
static void trace(void *HPs[], int len, struct localAlloc *local){
int counter=0;
const unsigned long localSweep=MAKE_SC(0, local->localVer);
const unsigned long *const globalSweepPtr=&local->global->sweep_counter;
void **markstack=local->markstack;
traceRoots(local, &counter);
for(int i=0; i<len; ++i){
assert(HPs[i]!=NULL && CLEAR_PTR(HPs[i])==HPs[i]);
markstack[++counter]=HPs[i];
}
traceMarkstack(markstack, counter, globalSweepPtr, localSweep, local);
markstack[0]=(void*)((long)markstack[0]|1);//I finished.
while(!CheckFinish(local, markstack, &counter)){
traceMarkstack(markstack, counter, globalSweepPtr, localSweep, local);
markstack[0]=(void*)((long)markstack[0]|1);//I finished.
}
//move sweep counter to current phase
resetSweepCounter(local);
}
//TODO: optimize. perf reveals that verCAS takes more that 1% of the total exec time for hash 64 threads.
static int pReturnCache(struct localAlloc *local){
struct allocator *alc = local->global;
struct allocEntry *toalloc=local->alloc_cache;
struct verEntry old, newitem;
do{ //push toalloc to head.
old = alc->head;
if(old.ver != local->localVer){
local->alloc_cache->free=1;//discard allocation cache. Just let the loop continue until it finishes.
return 0;
}
toalloc->next = old.head;
newitem.head=toalloc;
newitem.ver=local->localVer;
}while(!verCAS(&alc->head, old, newitem));
local->alloc_cache=NULL;
return 1;
}
static void setAsFree(struct localAlloc *local, void *obj){
if(local->alloc_cache!=NULL){
if(local->alloc_cache->free < ENTRIES_PER_CACHE){
local->alloc_cache->ptrs[local->alloc_cache->free++] = obj;
PRINTF2("pReturnAlloc %p. cache=%p[%d]\n", obj,local->alloc_cache,
local->alloc_cache->free);
return;
}
else{
pReturnCache(local);
}
}
struct allocator *alc = local->global;
local->alloc_cache = getAllocEntry();
local->alloc_cache->size = alc->entrySize;
local->alloc_cache->free = 1;
local->alloc_cache->ptrs[0]=obj;
}
static int process_sweep_page(unsigned page_number, struct localAlloc *local){
char *page = (char*)NAME(heapmem)[page_number/SWEEP_PAGES_PER_CHUNK]+(page_number%SWEEP_PAGES_PER_CHUNK)*SWEEP_PAGE;
void *base = (void*)((long)page & HEADER_MASK);
int offset = (long)page & OFFSET_MASK;
offset/=MEM_PER_BYTE;
unsigned long *h_ptr = (unsigned long*)((unsigned char*)base + offset);
assert(((long)h_ptr&7) == 0);
const int OBJ_SIZE = local->global->entrySize;
assert(OBJ_SIZE==NODE_SIZE);
assert((OBJ_SIZE&(OBJ_SIZE-1))==0);//obj_size must be a power of 2.
char *obj = page;
if(page==(char*)base){//MUST not sweep the header!
unsigned u64ignores=HEADER_SIZE/(MEM_PER_BYTE*sizeof(unsigned long));
//assert(u64ignores!=0);//HEADER SIZE must be bigger than MEM_PER_BYTE*sizeof(unsigned long)
h_ptr+=u64ignores;
if(u64ignores)
obj+=HEADER_SIZE;
}
while(obj<page+SWEEP_PAGE){
unsigned long mark_bits = *h_ptr;
for(unsigned int mask=1; mask!=0u/*1<<32*/; mask<<=1){
if(!(mark_bits&mask)){
DALLOW_SMALL_SP(if(((long)obj&OFFSET_MASK)>=HEADER_SIZE))
setAsFree(local, obj);
}
obj += OBJ_SIZE;
}
h_ptr++;
}
return 0;
}
static void sweep(struct localAlloc *local){
local->alloc_cache=NULL;//contains candidates for current phase.
struct allocator *alc = local->global;
const int num_sweep_pages = NAME(heapmemcnt)*SWEEP_PAGES_PER_CHUNK;
unsigned phase = local->localVer;
unsigned long lsweep, newlsweep;
int ctr=0;
while(1){
do{//take a single sweep page.
lsweep=alc->sweep_counter;
if(PHASE(lsweep)!=phase || SCOUNTER(lsweep)>=num_sweep_pages){
if(local->alloc_cache!=NULL)
pReturnCache(local);
local->alloc_cache=NULL;
return; //a new phase already started or sweep finished.
}
newlsweep=lsweep+1;
}while(!CAS(&alc->sweep_counter, lsweep, newlsweep));
//if some thread is in middle of clearing marks, do not sweep that page.
ctr += process_sweep_page(SCOUNTER(lsweep), local);
}
}
static void clearArrMarks(struct localAlloc *local, unsigned long phaseNum, void *markbits, int len){
phaseNum<<=32;//contains a clear mark: phase number in high 32 bits, 0 in lower 32 bits.
unsigned long *s=(unsigned long*)markbits, *e=(unsigned long*)((char*)markbits+len);
for(unsigned long *h=s, old; h<e; h++){
do{
old=*h;
if(old>=phaseNum) break;
}while(!CAS(h, old, phaseNum));
}
/* An alternative option - do not improve performance.
unsigned long *h=s+local->tid/4, *he=h, old;
do{
do{
old=*h;
if(old>=phaseNum) break;
}while(!CAS(h, old, phaseNum));
h++;
if(h==e) h=s;
}while(h!=he);*/
}
static void clearMarks(struct localAlloc *local, unsigned long phaseNum){
phaseNum<<=32;//contains a clear mark: phase number in high 32 bits, 0 in lower 32 bits.
const unsigned long tot_quota=HEADER_SIZE/sizeof(unsigned long);
const unsigned long quota = tot_quota / local->global->numThreads;
const int tid = local->tid;
for(int i=0; i<NAME(heapmemcnt); ++i){//for each chunk
char *curheap = NAME(heapmem)[i];
unsigned long *s=(unsigned long*)curheap, *e=(unsigned long*)(curheap+HEADER_SIZE);
unsigned long *first=s+ tid*quota;
unsigned long *h=first;
do{
unsigned long old;
do{//*h=phaseNum;
old=*h;
if(old>=phaseNum) break;
}while(!CAS(h, old, phaseNum));
h=(h+1<e)?h+1:s;//if wrapping start from beginning..
if(h==first) break;//finished.
}while(1);
}
}
/*static inline int test_and_set_bit(int nr, volatile unsigned long *addr)
{
int oldbit;
__asm__ volatile("lock;" "bts %2,%1\n\t"
"sbb %0,%0" : "=r" (oldbit), "+m" (*(volatile long *) (addr)) : "Ir" (nr) : "memory");
return oldbit;
}
int mark2(void *ptr){
ON AMD, nr to test_and_set_bit must be 0<=nr<32
void *base = (void*)((long)ptr & HEADER_MASK);
int offset = (long)ptr & OFFSET_MASK;
offset/=MEM_PER_BIT;
return test_and_set_bit(offset, (volatile unsigned long*)base);
}*/
| 2.1875 | 2 |
2024-11-18T19:02:30.372051+00:00
| 2021-05-22T07:20:33 |
f75b271f98cd8bb6d68ca3647f13a55e11881104
|
{
"blob_id": "f75b271f98cd8bb6d68ca3647f13a55e11881104",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-22T07:20:33",
"content_id": "4e643a5d9e53bac3b736b405cafed4575a742758",
"detected_licenses": [
"MIT"
],
"directory_id": "464d1374a04b3410bd6e515bc8bd4d6417661546",
"extension": "c",
"filename": "Cube.c",
"fork_events_count": 0,
"gha_created_at": "2020-01-12T16:58:55",
"gha_event_created_at": "2020-01-14T14:30:20",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 233426678,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 405,
"license": "MIT",
"license_type": "permissive",
"path": "/Source Codes/Volume & Surface Area/Cube.c",
"provenance": "stackv2-0058.json.gz:152788",
"repo_name": "kaazima/C",
"revision_date": "2021-05-22T07:20:33",
"revision_id": "26da10360aa676c965129263a85fbf9f4d2564ea",
"snapshot_id": "419d428b7eeae33db1ed62a5c70f49e8113e71d2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kaazima/C/26da10360aa676c965129263a85fbf9f4d2564ea/Source Codes/Volume & Surface Area/Cube.c",
"visit_date": "2021-07-01T05:23:38.350757"
}
|
stackv2
|
// Write a C program to find the volume and surface area of cube
#include <stdio.h>
int main()
{
float a,area,vol;
printf("Enter side-length of cube\n");
scanf("%f",&a);
area=6*a*a;
vol=a*a*a;
printf("Surface-area of the cube is %0.3f\nVolume of the cube is %0.3f",area,vol);
}
/*Output:
Enter side-length of cube
5.5
Surface-area of the cube is 181.500
Volume of the cube is 166.375*/
| 3.21875 | 3 |
2024-11-18T19:02:31.423278+00:00
| 2016-01-17T10:37:34 |
2f7e6e0e63cb5a343eae857d830d6cce4b34bedc
|
{
"blob_id": "2f7e6e0e63cb5a343eae857d830d6cce4b34bedc",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-17T10:37:34",
"content_id": "df7f9fc74b4df90ff5f3cd7e338e5b08758e235e",
"detected_licenses": [
"MIT"
],
"directory_id": "e75ea1edc35af3d4e39ec92af6efc07dd941175e",
"extension": "h",
"filename": "b32.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 49806784,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 968,
"license": "MIT",
"license_type": "permissive",
"path": "/b32.h",
"provenance": "stackv2-0058.json.gz:153559",
"repo_name": "jayramafisher/b32.c",
"revision_date": "2016-01-17T10:37:34",
"revision_id": "b35ea08175a3c30470017be882df18325319979c",
"snapshot_id": "90249fd40ba941387d0e1353654a9d236c4603fd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jayramafisher/b32.c/b35ea08175a3c30470017be882df18325319979c/b32.h",
"visit_date": "2021-01-23T04:23:11.818379"
}
|
stackv2
|
/**
* `b32.h' - b32
*
* copyright (c) 2016 jay rama fisher
* copyright (c) 2014 joseph werle
*/
#ifndef B32_H
#define B32_H 1
/**
* Base32 index table.
*/
static const char b32_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '2', '3', '4', '5', '6', '7'
};
#ifdef __cplusplus
extern "C" {
#endif
/**
* Encode `unsigned char *' source with `size_t' size.
* Returns a `char *' base64 encoded string.
*/
char *
b32_encode (const unsigned char *, size_t);
/**
* Dencode `char *' source with `size_t' size.
* Returns a `unsigned char *' base32 decoded string.
*/
unsigned char *
b32_decode (const char *, size_t);
/**
* Dencode `char *' source with `size_t' size.
* Returns a `unsigned char *' base32 decoded string + size of decoded string.
*/
unsigned char *
b32_decode_ex (const char *, size_t, size_t *);
#ifdef __cplusplus
}
#endif
#endif
| 2.0625 | 2 |
2024-11-18T19:02:31.508724+00:00
| 2021-05-28T20:05:09 |
1e4a57e5f7a6315a2563edbef6944cc7875571f9
|
{
"blob_id": "1e4a57e5f7a6315a2563edbef6944cc7875571f9",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-28T20:05:09",
"content_id": "85b6e482dee75dff777057ce8daba6af1aee723f",
"detected_licenses": [
"Unlicense"
],
"directory_id": "3c9442902e7fc0c7768cd9218e3c188e3545109f",
"extension": "c",
"filename": "04 - arboles.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 371807458,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1541,
"license": "Unlicense",
"license_type": "permissive",
"path": "/II/parcialitos/04 - arboles.c",
"provenance": "stackv2-0058.json.gz:153688",
"repo_name": "Floating-Island/C-Exercises-_2012_ES_",
"revision_date": "2021-05-28T20:05:09",
"revision_id": "c4e8408cafc1fe0e7d1d9fa51be11854c9582b59",
"snapshot_id": "3f3b4e2765814ad1a055f9cdfd7e23694e6d976b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Floating-Island/C-Exercises-_2012_ES_/c4e8408cafc1fe0e7d1d9fa51be11854c9582b59/II/parcialitos/04 - arboles.c",
"visit_date": "2023-05-05T18:29:07.313957"
}
|
stackv2
|
#include <stdio.h>
#include <stdlib.h>
typedef struct s_arbol
{
int dato;
struct s_arbol *izq,*der;
}*t_arbol;
void cargar(t_arbol*,int);
void inorder(t_arbol);
void preorder(t_arbol);
void posorder(t_arbol);
int main()
{
t_arbol raiz=NULL;
int entero;
printf("ingrese numeros enteros:\n");
do
{
scanf("%d",&entero);
if(entero%2!=0)
cargar(&raiz,entero);
}while(entero!=0);
printf("\nlos impares en inorder son : ");
inorder(raiz);
printf("\nlos impares en preorder son: ");
preorder(raiz);
printf("\nlos impares en posorder son: ");
posorder(raiz);
printf("\nlos impares por niveles son: ");
posorder(raiz);
return 0;
}
void cargar(t_arbol *r,int val)
{
if(*r!=NULL)
{
if(val<=(*r)->dato)
cargar(&((*r)->izq),val);
if (val>(*r)->dato)
cargar(&((*r)->der),val);
}
else
{
*r=(struct s_arbol*)malloc(sizeof(struct s_arbol));
if(*r==NULL)
exit(0);
(*r)->dato=val;
(*r)->izq=NULL;
(*r)->der=NULL;
}
}
void inorder(t_arbol a)
{
if(a!=NULL)
{
inorder(a->izq);
printf("%d ",a->dato);
inorder(a->der);
}
}
void preorder(t_arbol ar)
{
if(ar!=NULL)
{
printf("%d ",ar->dato);
preorder(ar->izq);
preorder(ar->der);
}
}
void posorder(t_arbol arb)
{
if(arb!=NULL)
{
posorder(arb->izq);
posorder(arb->der);
printf("%d ",arb->dato);
}
}
| 3.234375 | 3 |
2024-11-18T19:02:33.127491+00:00
| 2020-02-14T05:19:13 |
718ec3b38688f6b0d9febb65db6df8f220311a5b
|
{
"blob_id": "718ec3b38688f6b0d9febb65db6df8f220311a5b",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-14T05:19:13",
"content_id": "a609bd6cddc47dc44d943ef379d09fb36e98fb2c",
"detected_licenses": [
"MIT"
],
"directory_id": "6ea698a581a65248450a29f547b2741970f66bc2",
"extension": "c",
"filename": "sysproc.c",
"fork_events_count": 0,
"gha_created_at": "2020-01-16T02:44:01",
"gha_event_created_at": "2020-02-14T05:19:15",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 234219783,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1541,
"license": "MIT",
"license_type": "permissive",
"path": "/sysproc.c",
"provenance": "stackv2-0058.json.gz:153944",
"repo_name": "AnthonyH45/xv6-public",
"revision_date": "2020-02-14T05:19:13",
"revision_id": "b34f1adc7998d000f438cc985a6d29cf8d91f14d",
"snapshot_id": "18b7ab16b09a2d2f454cbf3eaafe9350e800e42b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/AnthonyH45/xv6-public/b34f1adc7998d000f438cc985a6d29cf8d91f14d/sysproc.c",
"visit_date": "2020-12-12T20:19:40.139306"
}
|
stackv2
|
#include "types.h"
#include "x86.h"
#include "defs.h"
#include "date.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
int
sys_fork(void)
{
return fork();
}
// we rewrite sys_exit to use
// the new exit(), that is
// exit(int status) instead
int
sys_exit(int status)
{
exit(status);
return 0; // not reached
}
int
sys_wait(void)
{
return wait(0);
}
int
sys_kill(void)
{
int pid;
if(argint(0, &pid) < 0)
return -1;
return kill(pid);
}
int
sys_getpid(void)
{
return myproc()->pid;
}
int
sys_sbrk(void)
{
int addr;
int n;
if(argint(0, &n) < 0)
return -1;
addr = myproc()->sz;
if(growproc(n) < 0)
return -1;
return addr;
}
int
sys_sleep(void)
{
int n;
uint ticks0;
if(argint(0, &n) < 0)
return -1;
acquire(&tickslock);
ticks0 = ticks;
while(ticks - ticks0 < n){
if(myproc()->killed){
release(&tickslock);
return -1;
}
sleep(&ticks, &tickslock);
}
release(&tickslock);
return 0;
}
// return how many clock tick interrupts have occurred
// since start.
int
sys_uptime(void)
{
uint xticks;
acquire(&tickslock);
xticks = ticks;
release(&tickslock);
return xticks;
}
int
sys_waitpid(void)
{
//int pid = myproc()->pid;
int pid;
int* status;
argint(0, &pid);
if (argptr(1, (void*)&status, sizeof(*status)) < 0)
return -1;
return waitpid(pid, status, 0);
}
int
sys_setpriority(void)
{
// set currproc->priority = to_set
int to_set = 10;
argint(0, &to_set);
return setpriority(to_set);
}
| 2.53125 | 3 |
2024-11-18T19:02:33.223518+00:00
| 2021-04-26T20:42:25 |
42cc82b1721842f7f065f031e0e08a7383d1247f
|
{
"blob_id": "42cc82b1721842f7f065f031e0e08a7383d1247f",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-26T20:42:25",
"content_id": "09a71ceb88aa1f62bef7ee378f457f5e24e1abda",
"detected_licenses": [
"MIT"
],
"directory_id": "bd4f08c4a1bcb5eb5d82f7bd5dcacc02491b14d0",
"extension": "c",
"filename": "compat-5.1.c",
"fork_events_count": 9,
"gha_created_at": "2010-03-14T19:17:08",
"gha_event_created_at": "2022-11-02T01:07:56",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 562215,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3078,
"license": "MIT",
"license_type": "permissive",
"path": "/src/compat-5.1r5/compat-5.1.c",
"provenance": "stackv2-0058.json.gz:154073",
"repo_name": "hleuwer/luasnmp",
"revision_date": "2021-04-26T20:42:25",
"revision_id": "a369ad9a1271d9c6327d0c3548b08d63c250ab74",
"snapshot_id": "cb7b527f796d78682726a6a35b717f09f613e9eb",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/hleuwer/luasnmp/a369ad9a1271d9c6327d0c3548b08d63c250ab74/src/compat-5.1r5/compat-5.1.c",
"visit_date": "2022-11-21T20:31:55.515117"
}
|
stackv2
|
/*
** Compat-5.1
** Copyright Kepler Project 2004-2006 (http://www.keplerproject.org/compat)
** $Id: compat-5.1.c,v 1.1 2006/04/09 19:51:39 leuwer Exp $
*/
#include <stdio.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "compat-5.1.h"
static void getfield(lua_State *L, int idx, const char *name) {
const char *end = strchr(name, '.');
lua_pushvalue(L, idx);
while (end) {
lua_pushlstring(L, name, end - name);
lua_gettable(L, -2);
lua_remove(L, -2);
if (lua_isnil(L, -1)) return;
name = end+1;
end = strchr(name, '.');
}
lua_pushstring(L, name);
lua_gettable(L, -2);
lua_remove(L, -2);
}
static void setfield(lua_State *L, int idx, const char *name) {
const char *end = strchr(name, '.');
lua_pushvalue(L, idx);
while (end) {
lua_pushlstring(L, name, end - name);
lua_gettable(L, -2);
/* create table if not found */
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_newtable(L);
lua_pushlstring(L, name, end - name);
lua_pushvalue(L, -2);
lua_settable(L, -4);
}
lua_remove(L, -2);
name = end+1;
end = strchr(name, '.');
}
lua_pushstring(L, name);
lua_pushvalue(L, -3);
lua_settable(L, -3);
lua_pop(L, 2);
}
LUALIB_API void luaL_module(lua_State *L, const char *libname,
const luaL_reg *l, int nup) {
if (libname) {
getfield(L, LUA_GLOBALSINDEX, libname); /* check whether lib already exists */
if (lua_isnil(L, -1)) {
int env, ns;
lua_pop(L, 1); /* get rid of nil */
lua_pushliteral(L, "require");
lua_gettable(L, LUA_GLOBALSINDEX); /* look for require */
lua_getfenv(L, -1); /* getfenv(require) */
lua_remove(L, -2); /* remove function require */
env = lua_gettop(L);
lua_newtable(L); /* create namespace for lib */
ns = lua_gettop(L);
getfield(L, env, "package.loaded"); /* get package.loaded table */
if (lua_isnil(L, -1)) { /* create package.loaded table */
lua_pop(L, 1); /* remove previous result */
lua_newtable(L);
lua_pushvalue(L, -1);
setfield(L, env, "package.loaded");
}
else if (!lua_istable(L, -1))
luaL_error(L, "name conflict for library `%s'", libname);
lua_pushstring(L, libname);
lua_pushvalue(L, ns);
lua_settable(L, -3); /* package.loaded[libname] = ns */
lua_pop(L, 1); /* get rid of package.loaded table */
lua_pushvalue(L, ns); /* copy namespace */
setfield(L, LUA_GLOBALSINDEX, libname);
lua_remove (L, env); /* remove env */
}
lua_insert(L, -(nup+1)); /* move library table to below upvalues */
}
for (; l->name; l++) {
int i;
lua_pushstring(L, l->name);
for (i=0; i<nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -(nup+1));
lua_pushcclosure(L, l->func, nup);
lua_settable(L, -(nup+3));
}
lua_pop(L, nup); /* remove upvalues */
}
| 2.234375 | 2 |
2024-11-18T19:02:33.297401+00:00
| 2014-05-05T09:49:49 |
9b3ef3ed54259d347637a6f331ee0dfdf0924249
|
{
"blob_id": "9b3ef3ed54259d347637a6f331ee0dfdf0924249",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-05T09:49:49",
"content_id": "032cdec15080da00bda071ce863bd3b7a5becede",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "ae1fdf1ba32469b45c393d5f71cc589cc80484f9",
"extension": "c",
"filename": "coordcube.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 4777219,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14343,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/coordcube.c",
"provenance": "stackv2-0058.json.gz:154201",
"repo_name": "isdaniarf/cube-tracker",
"revision_date": "2014-05-05T09:49:49",
"revision_id": "d8802514b0d6622478cef6ab28b7818860b63033",
"snapshot_id": "3dd80c051283acaca10f85e3a67c7162fec23b2a",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/isdaniarf/cube-tracker/d8802514b0d6622478cef6ab28b7818860b63033/coordcube.c",
"visit_date": "2021-01-13T01:36:32.909047"
}
|
stackv2
|
//FILE COORDCUBE.C
#include "cubedefs.h"
extern CubieCube basicCubeMove[6];
extern CubieCube idCube;
//***************************** helper functions*****************************
//***************************************************************************
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int Cnk(unsigned char n, unsigned char k)
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int s;
unsigned char i,j;
if (n<k) return 0;
if (k>n/2) k=n-k;
for (s=1,i=n,j=1; i!=n-k; i--,j++) {s *= i; s /= j;}
return s;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void rotateLeft(int arr[], int l, int r)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Left rotation of all array elements between l and r
{
int i, temp = arr[l];
for (i=l;i<r;i++)
arr[i] = arr[i+1];
arr[r] = temp;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void rotateRight(int arr[], int l, int r)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Right rotation of all array elements between l and r
{
int i, temp = arr[r];
for (i=r;i>l;i--) arr[i] = arr[i-1];
arr[l] = temp;
}
//**************************end helper functions*******************************
//*****************************************************************************
//********indexing functions and move tables without symmetry reduction********
//*****************************************************************************
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
unsigned short int twist(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
short int ret=0;
Corner c;
for (c=URF;c<DRB;c++) ret = 3*ret + cc.co[c].o;
return ret;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CubieCube invTwist(unsigned short int twist)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int c;
CubieCube ccRet=idCube;
int twistParity=0;
for (c= DRB-1;c>=URF;c--) {twistParity += ccRet.co[c].o = twist%3; twist /=3;}
ccRet.co[DRB].o = (3 - twistParity%3)%3;
return ccRet;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
unsigned short int flip(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
short int ret=0;
Edge e;
for (e=UR;e<BR;e++) ret = 2*ret + cc.eo[e].o;
return ret;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CubieCube invFlip(unsigned short int flip)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int e;
CubieCube ccRet=idCube;
int flipParity=0;
for (e= BR-1;e>=UR;e--){flipParity += ccRet.eo[e].o = flip%2; flip /=2;}
ccRet.eo[BR].o = (2 - flipParity%2)%2;
return ccRet;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
unsigned short int slice(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int a=0,x=0,j;
//compute the index a for combination (< 12 choose 4).
for (j=BR;j>=UR;j--) if (FR<=cc.eo[j].e && cc.eo[j].e<=BR ) a += Cnk(11-j,x++ +1);
return a;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CubieCube invSlice(unsigned short int slice)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int a=slice,j,x,perm[4]={8,9,10,11};
CubieCube ccRet=idCube;
for (j=UR;j<=BR;j++) ccRet.eo[j].e =255;//Invalidate all edges
x = 3;//generate combination and set edges
for (j=UR;j<=BR;j++)
if (a - Cnk(11-j,x+1)>=0) {ccRet.eo[j].e = perm[x]; a -=Cnk(11-j,x-- +1);}
for (j=UR,x=0;j<=BR;j++)//set the remaining edges 0..7
if (ccRet.eo[j].e == 255) ccRet.eo[j].e = x++;
return ccRet;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
unsigned short int corn6Pos(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int a=0,b,x=0,j,k,perm[6];
//compute the index a < (8 choose 6) and the permutation array perm.
for (j=URF;j<=DRB;j++)
if (cc.co[j].c<=DLF) {a += Cnk(j,x+1);perm[x++] = cc.co[j].c;}
for (j=5,b=0;j>0;j--)//compute the index b < 6! for the permutation in perm
{
k = 0;
while (perm[j] != j) {rotateLeft(perm,0,j);k++;}
b = (j+1)*b + k;
}
return 720*a + b;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CubieCube invCorn6Pos(unsigned short int idx)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int j, k, x, perm[6]={0,1,2,3,4,5};
int b = idx%720; //Permutation
int a = idx/720; //Combination
CubieCube ccRet=idCube;
for (j=URF;j<=DRB;j++) ccRet.co[j].c =255;//Invalidate all corners
for (j=1;j<6;j++)//generate permutation from index b
{
k = b%(j+1); b /= j+1;
while (k-- >0) rotateRight(perm,0,j);
}
x = 5;//generate combination and set corners
for (j=DRB;j>=0;j--)
if (a-Cnk(j,x+1)>=0) {ccRet.co[j].c = perm[x]; a -=Cnk(j,x-- +1);}
return ccRet;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int edge6Pos(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int a=0,b,x=0,j,k,perm[6];
//compute the index a < (12 choose 6) and the permutation array perm.
for (j=UR;j<=BR;j++)
if (cc.eo[j].e<=DF) {a += Cnk(j,x+1);perm[x++] = cc.eo[j].e;}
for (j=5,b=0;j>0;j--)//compute the index b < 6! for the permutation in perm
{
k = 0;
while (perm[j] != j) {rotateLeft(perm,0,j);k++;}
b = (j+1)*b + k;
}
return 720*a + b;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CubieCube invEdge6Pos(int idx)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int j, k, x, perm[6]={0,1,2,3,4,5};
int b = idx%720; //Permutation
int a = idx/720; //Combination
CubieCube ccRet=idCube;
for (j=UR;j<=BR;j++) ccRet.eo[j].e =255;//Invalidate all edges
for (j=1;j<6;j++)//generate permutation from index b
{
k = b%(j+1); b /= j+1;
while (k-- >0) rotateRight(perm,0,j);
}
x = 5;//generate combination and set edges
for (j=BR;j>=0;j--)
if (a-Cnk(j,x+1)>=0) {ccRet.eo[j].e = perm[x]; a -=Cnk(j,x-- +1);}
return ccRet;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int edge4Pos(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int a=0,b,x=0,j,k,perm[4];
//compute the index a < (12 choose 4) and the permutation array perm.
//for (j=UR;j<=BR;j++)
//if (cc.eo[j].e<=DF) {a += Cnk(j,x+1);perm[x++] = cc.eo[j].e;}
for (j=BR;j>=UR;j--)
if (FR<=cc.eo[j].e && cc.eo[j].e<=BR )
{a += Cnk(11-j,x+1); perm[3- x++] = cc.eo[j].e;}
for (j= 3,b=0;j>0;j--)//compute the index b < 4! for the permutation in perm
{
k = 0;
while (perm[j] != j +8) {rotateLeft(perm,0,j);k++;}
b = (j+1)*b + k;
}
return 24*a + b;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CubieCube invEdge4Pos(int idx)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int j, k, x, perm[4]={8,9,10,11};
int b = idx%24; //Permutation
int a = idx/24; //Combination
CubieCube ccRet=idCube;
for (j=UR;j<=BR;j++) ccRet.eo[j].e =255;//Invalidate all edges
for (j=1;j<4;j++)//generate permutation from index b
{
k = b%(j+1); b /= j+1;
while (k-- >0) rotateRight(perm,0,j);
}
x = 3;//generate combination and set edges
for (j=UR;j<=BR;j++)
if (a - Cnk(11-j,x+1)>=0) {ccRet.eo[j].e = perm[3 -x]; a -=Cnk(11-j,x-- +1);}
for (j=UR,x=0;j<=BR;j++)//set the remaining edges 0..7
if (ccRet.eo[j].e == 255) ccRet.eo[j].e = x++;
return ccRet;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int cornerParity(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int i,j,s=0;
for (i=DRB;i>=URF+1;i--)
for (j=i-1;j>=URF;j--)
if (cc.co[j].c>cc.co[i].c) s++;
return s%2;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int edgeParity(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int i,j,s=0;
for (i=BR;i>=UR+1;i--)
for (j=i-1;j>=UR;j--)
if (cc.eo[j].e>cc.eo[i].e) s++;
return s%2;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void initTwistMove()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
CubieCube a,b,c,d;
int i,j,m;
for (i=0;i<NTWIST;i++)
{
a = invTwist(i);
for (j=mU1;j<=mB3;j+=2)
{
m = j>>1;//extract the move axis
cornerMultiply(&a,&basicCubeMove[m],&b);
twistMove[i][j] = twist(b);
cornerMultiply(&b,&basicCubeMove[m],&c);
cornerMultiply(&c,&basicCubeMove[m],&d);
twistMove[i][j+1] = twist(d);
cornerMultiply(&d,&basicCubeMove[m],&a);
}
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void initCorn6PosMove()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
CubieCube a,b,c,d;
int i,j,m;
for (i=0;i<NCORN6POS;i++)
{
a = invCorn6Pos(i);
for (j=mU1;j<=mB3;j+=2)
{
m = j>>1;//extract the move axis
cornerMultiply(&a,&basicCubeMove[m],&b);
corn6PosMove[i][j] = corn6Pos(b);
cornerMultiply(&b,&basicCubeMove[m],&c);
cornerMultiply(&c,&basicCubeMove[m],&d);
corn6PosMove[i][j+1] = corn6Pos(d);
cornerMultiply(&d,&basicCubeMove[m],&a);
}
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void initEdge6PosMove()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
CubieCube a,b,c,d;
int i,j,m;
for (i=0;i<NEDGE6POS;i++)
{
if (!(i%40000)) pp();
a = invEdge6Pos(i);
for (j=mU1;j<=mB3;j+=2)
{
m = j>>1;//extract the move axis
edgeMultiply(&a,&basicCubeMove[m],&b);
edge6PosMove[i][j] = edge6Pos(b);
edgeMultiply(&b,&basicCubeMove[m],&c);
edgeMultiply(&c,&basicCubeMove[m],&d);
edge6PosMove[i][j+1] = edge6Pos(d);
edgeMultiply(&d,&basicCubeMove[m],&a);
}
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void initEdge4PosMove()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
CubieCube a,b,c,d;
int i,j,m;
for (i=0;i<NEDGE4POS;i++)
{
a = invEdge4Pos(i);
for (j=mU1;j<=mB3;j+=2)
{
m = j>>1;//extract the move axis
edgeMultiply(&a,&basicCubeMove[m],&b);
edge4PosMove[i][j] = edge4Pos(b);
edgeMultiply(&b,&basicCubeMove[m],&c);
edgeMultiply(&c,&basicCubeMove[m],&d);
edge4PosMove[i][j+1] = edge4Pos(d);
edgeMultiply(&d,&basicCubeMove[m],&a);
}
}
}
//******end indexing functions and move tables without symmetry reduction******
//*****************************************************************************
//*********indexing functions and move tables with symmetry reduction**********
//*****************************************************************************
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int symFlipSlice(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int symIdx=0, classIdx, rawFlipSlice, rep=NFLIP*NSLICE, rBound, lBound, i;
CubieCube ccRep;
for (i=0;i<NSYM_D4h;i++)
{
ccRep = edgeConjugate(cc,i);
rawFlipSlice = NFLIP*slice(ccRep) + flip(ccRep);
if (rawFlipSlice<rep) {rep = rawFlipSlice; symIdx = i;}
}
//rep not holds the rawFlipSlice coordinate of the representant ccRep
//in the equivalence class of cube cc.
//We have cc = symCube[idx]^-1*ccRep*symCube[idx]
//Get the index of the ccRep-equivalence class from table rawFlipSliceRep now:
rBound = NFLIPSLICE;
lBound = 0;
classIdx = -1;
do
{
classIdx = (lBound + rBound)/2;
if (rep<rawFlipSliceRep[classIdx]) rBound = classIdx;
else if (rep>rawFlipSliceRep[classIdx]) lBound = classIdx;
}
while (rep!=rawFlipSliceRep[classIdx]);
return (classIdx<<4) + symIdx;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void initSymFlipSliceClassMove()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int i,j,rep,flip,slice,m,n;
CubieCube ccFlip,ccSlice,b,c,d;
for(i=0;i<NFLIPSLICE;i++)
{
if (!(i%2000)) pp();
rep = rawFlipSliceRep[i];
flip = rep%NFLIP;
slice =rep/NFLIP;
ccSlice = invSlice(slice);
ccFlip = invFlip(flip);
for (n=0;n<12;n++) ccFlip.eo[n].e = ccSlice.eo[n].e;//merge cubes
for (j=mU1;j<=mB3;j+=2)
{
m = j>>1;//extract move axis
edgeMultiply(&ccFlip,&basicCubeMove[m],&b);
symFlipSliceClassMove[i][j] = symFlipSlice(b);
edgeMultiply(&b,&basicCubeMove[m],&c);
edgeMultiply(&c,&basicCubeMove[m],&d);
symFlipSliceClassMove[i][j+1] = symFlipSlice(d);
edgeMultiply(&d,&basicCubeMove[m],&ccFlip);
}
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
int symFlipSliceMove(int a, int m)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
int aSym,aClass,bSym,bClass,mConj,b;
//With the abbreviations A = invSymFlipSlice(a),
//M = moveCube[m] and ASYM = symCube[aSym]
//we have A = ASYM^-1*ACLASS*ASYM with some representant ACLASS
//so A*M = ASYM^-1*ACLASS*ASYM*M = ASYM^-1*ACLASS*(ASYM *M*ASYM^-1)*ASYM
//Defining MCONJ = ASYM *M*ASYM^-1
//we have A*M = ASYM^-1*ACLASS*MCONJ*ASYM
//Define B = ACLASS*MCONJ then we have A*M = ASYM^-1*B*ASYM
//With the abbreviation BSYM = symCube[bSym]
//We have B = BSYM^-1*BCLASS*BSYM with some representant BCLASS
//So A*M = ASYM^-1* BSYM^-1*BCLASS*BSYM*ASYM
//= (BSYM*ASYM)^-1*BCLASS*(BSYM*ASYM)
aClass = a>>4;aSym = a&15;
mConj = moveConjugate[m][aSym];
b = symFlipSliceClassMove[aClass][mConj];
bClass = b>>4; bSym = b&15;
return (bClass<<4) + symIdxMultiply[bSym][aSym];
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CoordCube cubieCubeToCoordCube(CubieCube cc)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{
CoordCube co;
co.corn6Pos = corn6Pos(cc);
co.edge6Pos = edge6Pos(cc);
co.edge4Pos = edge4Pos(cc);
co.parity = cornerParity(cc);
co.symFlipSlice = symFlipSlice(cc);
co.twist = twist(cc);
return co;
}
//*******end indexing functions and move tables with symmetry reduction********
//*****************************************************************************
| 2.53125 | 3 |
2024-11-18T19:02:33.357408+00:00
| 2019-05-15T22:06:11 |
cbb598879130f718912c37a648f4121a62591273
|
{
"blob_id": "cbb598879130f718912c37a648f4121a62591273",
"branch_name": "refs/heads/develop",
"committer_date": "2019-05-15T22:06:11",
"content_id": "4dfd648ca4d948526b803e815c5e50b6cb6c78e7",
"detected_licenses": [
"MIT"
],
"directory_id": "7cc03603e365c30a3b751498775a0b8a10d58456",
"extension": "c",
"filename": "queue.c",
"fork_events_count": 1,
"gha_created_at": "2019-05-15T22:26:28",
"gha_event_created_at": "2020-02-05T17:09:58",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 186911034,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9097,
"license": "MIT",
"license_type": "permissive",
"path": "/src/queue/queue.c",
"provenance": "stackv2-0058.json.gz:154329",
"repo_name": "wes-b/Azure-Kinect-Sensor-SDK-1",
"revision_date": "2019-05-15T22:06:11",
"revision_id": "cd55fd4b5aac4a26ca8918fc79550f3d5752d084",
"snapshot_id": "f079358c4cecc598741251016a008d368d96a552",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/wes-b/Azure-Kinect-Sensor-SDK-1/cd55fd4b5aac4a26ca8918fc79550f3d5752d084/src/queue/queue.c",
"visit_date": "2020-05-23T19:22:09.653115"
}
|
stackv2
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// This library
#include <k4ainternal/queue.h>
// Dependent libraries
#include <k4ainternal/allocator.h>
#include <azure_c_shared_utility/lock.h>
#include <azure_c_shared_utility/condition.h>
#include <azure_c_shared_utility/threadapi.h>
// System dependencies
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef struct _queue_entry_t
{
k4a_capture_t capture;
} queue_entry_t;
typedef struct _queue_context_t
{
bool enabled;
bool error;
uint32_t queue_pop_blocked; // number of waiting threads for queue_pop so complete
uint32_t read_location; // current location to read frokm
uint32_t write_location; // current location to write to
queue_entry_t *queue; // the queue array
uint32_t depth; // 1 element larger than the max elements the queue can hold.
const char *name; // Queue name in logger
uint32_t dropped_count; // Count of the dropped captures
LOCK_HANDLE lock;
COND_HANDLE condition;
} queue_context_t;
K4A_DECLARE_CONTEXT(queue_t, queue_context_t);
// This queue is empty if read and write pointers index the same location. The queue is full when the write pointer is
// one away from pointing at the read location. This means that while we allocate a size of N, we can only hold N-1
// elements. This allows us to maintain state through the read and write pointers only.
#define inc_read_write_location(queue, location) (((location) + 1) % (queue)->depth)
#define is_queue_empty(queue) ((queue)->write_location == (queue)->read_location)
#define is_queue_full(queue) (inc_read_write_location((queue), (queue)->write_location) == (queue)->read_location)
k4a_result_t queue_create(uint32_t queue_depth, const char *queue_name, queue_t *queue_handle)
{
k4a_result_t result;
queue_context_t *queue = queue_t_create(queue_handle);
RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, queue_depth == 0);
RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, queue_depth > 10000); // Sanity Check
queue->depth = queue_depth + 1; // Adding one; see comment on inc_read_write_location()
queue->name = queue_name;
if (queue->name == NULL)
{
queue->name = "Unknown queue";
}
queue->queue = malloc(sizeof(queue_entry_t) * queue->depth);
result = K4A_RESULT_FROM_BOOL(queue->queue != NULL);
if (K4A_SUCCEEDED(result))
{
queue->lock = Lock_Init();
result = K4A_RESULT_FROM_BOOL(queue->lock != NULL);
}
if (K4A_SUCCEEDED(result))
{
queue->condition = Condition_Init();
}
else
{
if (queue)
{
queue_destroy(*queue_handle);
*queue_handle = NULL;
}
}
return result;
}
static k4a_capture_t queue_pop_internal_locked(queue_context_t *queue)
{
if (is_queue_empty(queue) == false)
{
queue_entry_t *entry = &queue->queue[queue->read_location];
queue->read_location = inc_read_write_location(queue, queue->read_location);
return entry->capture;
}
return NULL;
}
k4a_wait_result_t queue_pop(queue_t queue_handle, int32_t wait_in_ms, k4a_capture_t *out_capture)
{
RETURN_VALUE_IF_HANDLE_INVALID(K4A_WAIT_RESULT_FAILED, queue_t, queue_handle);
RETURN_VALUE_IF_ARG(K4A_WAIT_RESULT_FAILED, out_capture == NULL);
queue_context_t *queue = queue_t_get_context(queue_handle);
k4a_capture_t capture = NULL;
k4a_wait_result_t wresult = K4A_WAIT_RESULT_SUCCEEDED;
Lock(queue->lock);
if (queue->enabled != true)
{
LOG_ERROR("%s: capture popped from disabled queue", queue->name);
wresult = K4A_WAIT_RESULT_FAILED;
}
if (wresult == K4A_WAIT_RESULT_SUCCEEDED)
{
wresult = K4A_WAIT_RESULT_TIMEOUT;
queue->queue_pop_blocked++;
capture = queue_pop_internal_locked(queue);
if (capture != NULL)
{
wresult = K4A_WAIT_RESULT_SUCCEEDED;
}
else if (wait_in_ms != 0)
{
// Anything less than 0 is a wait forever condition in the lower level calls.
// K4A_WAIT_INFINITE (-1) is defined for the user for this purpose
if (wait_in_ms < 0)
{
wait_in_ms = 0; // infinite to Condition_wait
}
// NOTE: The event used by Condition_Wait only gets set when a thread is actively
// waiting. There is a bit of a race condition between Condition_Post, Condition_Wait
// and how waiting_thread_count is used. So the queue may have data in it with no event set.
COND_RESULT cond_result = Condition_Wait(queue->condition, queue->lock, wait_in_ms);
if (cond_result == COND_OK)
{
capture = queue_pop_internal_locked(queue);
wresult = K4A_WAIT_RESULT_SUCCEEDED;
// Condition_Wait should only return COND_OK if there is data or if we are shutting down.
assert(capture != NULL || queue->enabled == false);
}
else if (cond_result != COND_TIMEOUT)
{
K4A_RESULT_FROM_BOOL(cond_result != COND_ERROR);
assert(cond_result == COND_TIMEOUT || cond_result == COND_OK);
wresult = K4A_WAIT_RESULT_FAILED;
}
}
queue->queue_pop_blocked--;
}
if (queue->enabled == false)
{
wresult = K4A_WAIT_RESULT_FAILED;
if (capture)
{
// drop the capture
capture_dec_ref(capture);
capture = NULL;
}
}
if (queue->dropped_count != 0)
{
LOG_WARNING("%s: Dropped oldest %d captures from queue", queue->name, queue->dropped_count);
queue->dropped_count = 0;
}
Unlock(queue->lock);
// We are transfering the ref we had to the caller.
// capture_dec_ref(capture);
*out_capture = capture;
return wresult;
}
static void queue_push_internal_locked(queue_context_t *queue, k4a_capture_t capture)
{
queue_entry_t *entry = &queue->queue[queue->write_location];
entry->capture = capture;
queue->write_location = inc_read_write_location(queue, queue->write_location);
}
void queue_push_w_dropped(queue_t queue_handle, k4a_capture_t capture, k4a_capture_t *dropped)
{
RETURN_VALUE_IF_HANDLE_INVALID(VOID_VALUE, queue_t, queue_handle);
RETURN_VALUE_IF_ARG(VOID_VALUE, capture == NULL);
queue_context_t *queue = queue_t_get_context(queue_handle);
Lock(queue->lock);
if (queue->enabled == false)
{
LOG_WARNING("Capture pushed into disabled queue", queue->name);
}
else
{
if (is_queue_full(queue))
{
if (dropped == NULL)
{
queue->dropped_count++;
capture_dec_ref(queue_pop_internal_locked(queue));
}
else
{
*dropped = queue_pop_internal_locked(queue);
}
}
// We are accepting this into our queue, so add a ref to prevent it
// from being freed
capture_inc_ref(capture);
queue_push_internal_locked(queue, capture);
Condition_Post(queue->condition);
}
Unlock(queue->lock);
}
void queue_push(queue_t queue_handle, k4a_capture_t capture)
{
queue_push_w_dropped(queue_handle, capture, NULL);
}
void queue_destroy(queue_t queue_handle)
{
RETURN_VALUE_IF_HANDLE_INVALID(VOID_VALUE, queue_t, queue_handle);
queue_context_t *queue = queue_t_get_context(queue_handle);
queue_disable(queue_handle);
if (queue->condition)
{
Condition_Deinit(queue->condition);
}
if (queue->queue)
{
free(queue->queue);
}
Lock_Deinit(queue->lock);
queue_t_destroy(queue_handle);
}
void queue_enable(queue_t queue_handle)
{
RETURN_VALUE_IF_HANDLE_INVALID(VOID_VALUE, queue_t, queue_handle);
queue_context_t *queue = queue_t_get_context(queue_handle);
Lock(queue->lock);
queue->enabled = true;
queue->error = false;
Unlock(queue->lock);
}
void queue_disable(queue_t queue_handle)
{
RETURN_VALUE_IF_HANDLE_INVALID(VOID_VALUE, queue_t, queue_handle);
queue_context_t *queue = queue_t_get_context(queue_handle);
Lock(queue->lock);
queue->enabled = false;
while (queue->queue_pop_blocked != 0)
{
LOG_WARNING("Waiting for blocking call to complete", 0);
Condition_Post(queue->condition);
Unlock(queue->lock);
ThreadAPI_Sleep(25);
Lock(queue->lock);
}
while (is_queue_empty(queue) == false)
{
capture_dec_ref(queue_pop_internal_locked(queue));
}
Unlock(queue->lock);
}
void queue_error(queue_t queue_handle)
{
queue_context_t *queue = queue_t_get_context(queue_handle);
Lock(queue->lock);
queue->error = true;
Unlock(queue->lock);
LOG_WARNING("Error detected, shutting down queue and notifying consumers", 0);
queue_disable(queue_handle);
}
| 2.453125 | 2 |
2024-11-18T19:02:33.533538+00:00
| 2022-07-03T21:30:55 |
8d99f99095f7caa25ee7ded560d72b12f5f85bcf
|
{
"blob_id": "8d99f99095f7caa25ee7ded560d72b12f5f85bcf",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-03T21:30:55",
"content_id": "c5b3eda4dad22860aebc83d227a593d781c416d9",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "4a8bfb4e650f80911b9ce247c19080474c564730",
"extension": "c",
"filename": "compare_bytecode_with_internal.c",
"fork_events_count": 1,
"gha_created_at": "2015-09-18T01:37:49",
"gha_event_created_at": "2022-07-03T22:12:31",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 42692468,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1868,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/test/compare_bytecode_with_internal.c",
"provenance": "stackv2-0058.json.gz:154586",
"repo_name": "ChrisHixon/chpeg",
"revision_date": "2022-07-03T21:30:55",
"revision_id": "603752fd7785e767d3119685df32026bb9d53480",
"snapshot_id": "19d9f653ffc3e41b7e811b1b35f2afd0d1595e7c",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/ChrisHixon/chpeg/603752fd7785e767d3119685df32026bb9d53480/test/compare_bytecode_with_internal.c",
"visit_date": "2022-07-12T00:56:39.417010"
}
|
stackv2
|
// test to see if internal compiler byte code matches byte code compiled from a file
// originally used to compare the Ruby generated byte code with byte code created with C version
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define DEBUG_MEM 1
#if DEBUG_MEM
#include <mcheck.h>
#endif
#include "chpeg/mem.h"
#include "chpeg/parser.h"
#include "chpeg/compiler.h"
int main(int argc, char *argv[])
{
int ret = 0;
int fd = -1;
unsigned char *input = NULL;
ChpegByteCode *byte_code = NULL;
#if DEBUG_MEM
mtrace();
#endif
if (argc != 2) {
printf("usage: %s <grammar_file>\n", argv[0]);
ret = 2;
goto done;
}
struct stat st;
if (stat(argv[1], &st) != 0) {
perror(argv[1]);
ret = 3;
goto done;
}
input = (unsigned char*)CHPEG_MALLOC(st.st_size);
if (!input) {
ret = 255;
goto done;
}
fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror(argv[1]);
ret = 4;
goto done;
}
int size = read(fd, input, st.st_size);
if (size != st.st_size) {
perror(argv[1]);
ret = 5;
goto done;
}
close(fd);
fd = -1;
if ((ret = chpeg_compile(input, st.st_size, &byte_code, 0)) != 0) {
fprintf(stderr, "chpeg_compile failed:% d\n", ret);
return ret;
}
ChpegByteCode_print(byte_code);
ret = ChpegByteCode_compare(chpeg_default_bytecode(), byte_code);
printf("ChpegByteCode_compare(chpeg_default_bytecode(), byte_code) = %d\n", ret);
done:
if (byte_code) {
ChpegByteCode_free(byte_code);
}
if (input) {
CHPEG_FREE(input);
}
if (fd >= 0) {
close(fd);
}
#if DEBUG_MEM
muntrace();
#endif
return ret;
}
| 2.4375 | 2 |
2024-11-18T19:02:34.640647+00:00
| 2023-06-23T10:11:23 |
4547acacbe0eed45c5e1302214d24ab533af6aef
|
{
"blob_id": "4547acacbe0eed45c5e1302214d24ab533af6aef",
"branch_name": "refs/heads/main",
"committer_date": "2023-06-23T10:11:23",
"content_id": "81d7293e60d79b21194a5946b3e74487f498d51c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "803898f95f34521f4fc08ff42534888367ff4028",
"extension": "c",
"filename": "grcsetr.c",
"fork_events_count": 29,
"gha_created_at": "2012-06-19T15:15:17",
"gha_event_created_at": "2023-06-23T10:11:24",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 4715296,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1780,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/gempak/source/diaglib/grc/grcsetr.c",
"provenance": "stackv2-0058.json.gz:154715",
"repo_name": "Unidata/gempak",
"revision_date": "2023-06-23T10:11:23",
"revision_id": "f3997c88469be1c08cd265ef553c812a28778284",
"snapshot_id": "17057d45ad92512f56193155dd0d6ad0301965d8",
"src_encoding": "UTF-8",
"star_events_count": 53,
"url": "https://raw.githubusercontent.com/Unidata/gempak/f3997c88469be1c08cd265ef553c812a28778284/gempak/source/diaglib/grc/grcsetr.c",
"visit_date": "2023-07-13T19:39:57.114715"
}
|
stackv2
|
#include "geminc.h"
#include "gemprm.h"
void grc_setr ( int *kxin, int *kyin, int *ishft, int *iret )
/************************************************************************
* grc_setr *
* *
* This subroutine sets the shift position needed to rearrange a globe *
* wrapping grid on either a CED or MER projection. The rearrangement *
* must be done for any display map projection when the grid discon- *
* tinuity occurs within the map area. The rearrangement creates a *
* continuous grid of data over the map area. *
* *
* Warning: This subroutine resets the grid navigation in GPLT to be *
* that of the re-arranged grid. *
* *
* grc_setr ( kxin, kyin, ishft, iret ) *
* *
* Input parameters: *
* kxin int Number of input points in x dir *
* kyin int Number of input points in y dir *
* *
* Output parameters: *
* ishft int X index shift number needed by *
* subroutine GR_DORG *
* *
* Output parameters: *
* iret int Return code *
* 0 = normal return *
* -21 = cannot fix wrap around *
* -22 = no map projection is set *
** *
* Log: *
* K. Brill/HPC 08/02 Created from original GR_RARG code with *
* added longitude buffer zone and check *
* at +/-5 grid pts from grd discontinuity *
* K. Brill/HPC 09/02 Do only check at columns KX-5, KX, and 5*
* S. Jacobs/NCEP 10/02 Removed check for +/-5 grid pt columns *
* D.W.Plummer/NCEP 2/06 Translated from FORTRAN *
***********************************************************************/
{
/*----------------------------------------------------------------------*/
gr_setr ( kxin, kyin, ishft, iret );
return;
}
| 2.125 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.