added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T22:02:42.753113+00:00 | 2023-09-01T02:41:42 | f14771cc4aa223f13a1ac0b3c937bf602e7602ec | {
"blob_id": "f14771cc4aa223f13a1ac0b3c937bf602e7602ec",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T02:41:42",
"content_id": "a898f36815c7893dbe0c3790b6a4e49f31cf4579",
"detected_licenses": [
"MIT"
],
"directory_id": "461619a84c6617ceaf2b7913ef58c99ff32c0fb5",
"extension": "c",
"filename": "system_main.c",
"fork_events_count": 10,
"gha_created_at": "2014-12-12T06:22:49",
"gha_event_created_at": "2023-09-06T20:49:55",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 27908184,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1073,
"license": "MIT",
"license_type": "permissive",
"path": "/unixsyscall/system/system/src/system/system_main.c",
"provenance": "stackv2-0139.json.gz:110491",
"repo_name": "bg1bgst333/Sample",
"revision_date": "2023-09-01T02:41:42",
"revision_id": "298a4253dd8123b29bc90a3569f2117d7f6858f8",
"snapshot_id": "cf066e48facac8ecd203c56665251fa1aa103844",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/bg1bgst333/Sample/298a4253dd8123b29bc90a3569f2117d7f6858f8/unixsyscall/system/system/src/system/system_main.c",
"visit_date": "2023-09-02T00:46:31.139148"
} | stackv2 | /* ヘッダファイルのインクルード */
#include <stdio.h> /* 標準入出力 */
#include <stdlib.h> /* 標準ユーティリティ */
#include <sys/types.h> /* 派生型 */
#include <unistd.h> /* UNIX標準 */
/* main関数の定義 */
int main(void){
/* 変数の宣言 */
pid_t pid; /* getpidでプロセスIDを取得し, pidに格納. */
/* プロセスIDの取得 */
pid = getpid(); /* getpidでプロセスIDを取得し, pidに格納. */
printf("pid = %d\n", pid); /* printfでpidを出力. */
/* 1分間(60秒間)待つ. */
sleep(60); /* sleepで60秒間休止. */
/* systemを呼ぶ直前. */
printf("system before.\n"); /* "system before."を出力する. */
/* プロセスの実行. */
system("./system_sub 123 abc xyz"); /* systemで"./system_sub"を引数"123", "abb", "xyz"として実行.(systemにより, system_mainのプロセスとは別にsystem_subのプロセスが生成される.) */
/* 1分間(60秒間)待つ. */
sleep(60); /* sleepで60秒間休止. */
/* プログラムの終了 */
return 0;
}
| 3.046875 | 3 |
2024-11-18T22:02:42.852449+00:00 | 2018-09-21T21:38:30 | 9fdafc0e5d5b42f037224ea76522478aee55755c | {
"blob_id": "9fdafc0e5d5b42f037224ea76522478aee55755c",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-21T21:38:30",
"content_id": "30275eec6cc78d539bdfea7793d73b3a14404a62",
"detected_licenses": [
"Unlicense"
],
"directory_id": "0c209438be9dd6fc82116f0e13b9831aa755b5b4",
"extension": "h",
"filename": "tadItemMatriz.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147879649,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2073,
"license": "Unlicense",
"license_type": "permissive",
"path": "/tadItemMatriz.h",
"provenance": "stackv2-0139.json.gz:110619",
"repo_name": "lucassgomes/TPAEDS1_sistema_aereo",
"revision_date": "2018-09-21T21:38:30",
"revision_id": "b9eb056bb6b7ddfef3de5836ef43b5deca119a1c",
"snapshot_id": "1ae7aa7423d0ab0bb452f7a58a238468237f760e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lucassgomes/TPAEDS1_sistema_aereo/b9eb056bb6b7ddfef3de5836ef43b5deca119a1c/tadItemMatriz.h",
"visit_date": "2020-03-28T07:04:43.179536"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include "tadListaDeVoo.h"
//ED do TAD item da matriz
typedef struct {
tadListaVoo listaVoo;
int numVoos;
char horarioAtualizacao[9];
} tadItemMatriz;
/**
* Inicializa o TAD item da matriz
* @param itemMatriz Endereço para ED do TAD item da matriz
*/
void inicializarTadItemMatriz(tadItemMatriz *itemMatriz);
/**
* Retorna a lista encadeada a partir do endereço do TAD item da matriz
* @param itemMatriz Endereço para ED do TAD item da matriz
* @return tadListaVoo lista encadeada de voos
*/
tadListaVoo getListaVoo(tadItemMatriz* itemMatriz);
/**
* Retorna o número de voos a partir do endereço do TAD item da matriz
* @param itemMatriz Endereço para ED do TAD item da matriz
* @return int número de voos do TAD item da matriz
*/
int getNumVoos(tadItemMatriz* itemMatriz);
/**
* Retorna um ponteiro (início) da cadeia de caracteres que contém a hora de atualização do TAD item da matriz
* @param itemMatriz Endereço para ED do TAD item da matriz
* @return char hora de atualização do TAD item da matriz
*/
char* getHorarioAtualizacao(tadItemMatriz* itemMatriz);
/**
* Seta a (tadListaVoo) lista encadeada de voos e retorna 0 caso tenha sucesso
* @param itemMatriz Endereço para ED do TAD item da matriz
* @param listaVoo cópia da lista encadeada de voos
* @return int 0 caso tenha sucesso
*/
int setListaVoo(tadItemMatriz* itemMatriz, tadListaVoo listaVoo);
/**
* Seta a informação (INT) número de voos do TAD item da matriz
* @param itemMatriz Endereço para ED do TAD item da matriz
* @param numVoos int numero de voos do TAD item da matriz
* @return int 0 caso sucesso
*/
int setNumVoos(tadItemMatriz* itemMatriz, int numVoos);
/**
* Seta a informação (CHAR) horário de atualização de voos do TAD item da matriz
* @param itemMatriz Endereço para ED do TAD item da matriz
* @param horaAtualizacao char hora de atualização do TAD item da matriz
* @return int 0 caso sucesso
*/
int setHorarioAtualizacao(tadItemMatriz* itemMatriz, char horaAtualizacao[]);
| 2.84375 | 3 |
2024-11-18T22:02:44.505594+00:00 | 2020-02-06T18:43:51 | 4ecd72e5619bb89f1907d5365ea2311cc501faa3 | {
"blob_id": "4ecd72e5619bb89f1907d5365ea2311cc501faa3",
"branch_name": "refs/heads/develop",
"committer_date": "2020-02-06T18:43:51",
"content_id": "6328d6b35eff5efd850b028281cb77cdab82574b",
"detected_licenses": [
"MIT"
],
"directory_id": "97c44f18459163c0baa546ab2578339b716c3238",
"extension": "c",
"filename": "BREthereumHash.c",
"fork_events_count": 283,
"gha_created_at": "2015-06-16T01:22:12",
"gha_event_created_at": "2023-03-21T09:07:32",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 37500549,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3845,
"license": "MIT",
"license_type": "permissive",
"path": "/ethereum/base/BREthereumHash.c",
"provenance": "stackv2-0139.json.gz:110752",
"repo_name": "breadwallet/breadwallet-core",
"revision_date": "2020-02-06T18:43:51",
"revision_id": "73566cb79f753954eccbf07d5ab25ca54741198e",
"snapshot_id": "fe8a0ac99f3e47216860b2918c8ad14d3503b140",
"src_encoding": "UTF-8",
"star_events_count": 284,
"url": "https://raw.githubusercontent.com/breadwallet/breadwallet-core/73566cb79f753954eccbf07d5ab25ca54741198e/ethereum/base/BREthereumHash.c",
"visit_date": "2023-08-21T22:27:45.735652"
} | stackv2 | //
// BREthereumHash.c
// BRCore
//
// Created by Ed Gamble on 5/9/18.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "support/BRCrypto.h"
#include "ethereum/util/BRUtil.h"
#include "BREthereumHash.h"
static BREthereumHash emptyHash;
/**
* Create a Hash by converting from a hex-encoded string of a hash. The string must
* begin with '0x'.
*/
extern BREthereumHash
ethHashCreate (const char *string) {
if (NULL == string || '\0' == string[0] || 0 == strcmp (string, "0x")) return ethHashCreateEmpty();
assert (0 == strncmp (string, "0x", 2)
&& (2 + 2 * ETHEREUM_HASH_BYTES) == strlen (string));
BREthereumHash hash;
hexDecode(hash.bytes, ETHEREUM_HASH_BYTES, &string[2], 2 * ETHEREUM_HASH_BYTES);
return hash;
}
/**
* Create an empty (all zeros) Hash
*/
extern BREthereumHash
ethHashCreateEmpty (void) {
return emptyHash;
}
/**
* Creata a Hash by computing it from a arbitrary data set (using Keccak256)
*/
extern BREthereumHash
ethHashCreateFromData (BRRlpData data) {
BREthereumHash hash;
BRKeccak256(hash.bytes, data.bytes, data.bytesCount);
return hash;
}
/**
* Return the hex-encoded string
*/
extern char *
ethHashAsString (BREthereumHash hash) {
char result [2 + 2 * ETHEREUM_HASH_BYTES + 1];
result[0] = '0';
result[1] = 'x';
hexEncode(&result[2], 2 * ETHEREUM_HASH_BYTES + 1, hash.bytes, ETHEREUM_HASH_BYTES);
return strdup (result);
}
extern BREthereumHash
ethHashCopy(BREthereumHash hash) {
return hash;
}
extern BREthereumComparison
ethHashCompare(BREthereumHash hash1, BREthereumHash hash2) {
for (int i = 0; i < ETHEREUM_HASH_BYTES; i++) {
if (hash1.bytes[i] > hash2.bytes[i]) return ETHEREUM_COMPARISON_GT;
else if (hash1.bytes[i] < hash2.bytes[i]) return ETHEREUM_COMPARISON_LT;
}
return ETHEREUM_COMPARISON_EQ;
}
extern BREthereumBoolean
ethHashEqual (BREthereumHash hash1, BREthereumHash hash2) {
return AS_ETHEREUM_BOOLEAN (0 == memcmp (hash1.bytes, hash2.bytes, ETHEREUM_HASH_BYTES));
}
extern BRRlpItem
ethHashRlpEncode(BREthereumHash hash, BRRlpCoder coder) {
return rlpEncodeBytes(coder, hash.bytes, ETHEREUM_HASH_BYTES);
}
extern BREthereumHash
ethHashRlpDecode (BRRlpItem item, BRRlpCoder coder) {
BREthereumHash hash;
BRRlpData data = rlpDecodeBytes(coder, item);
assert (ETHEREUM_HASH_BYTES == data.bytesCount);
memcpy (hash.bytes, data.bytes, ETHEREUM_HASH_BYTES);
rlpDataRelease(data);
return hash;
}
extern BRRlpItem
ethHashEncodeList (BRArrayOf (BREthereumHash) hashes, BRRlpCoder coder) {
size_t itemCount = array_count(hashes);
BRRlpItem items[itemCount];
for (size_t index = 0; index < itemCount; index++)
items[index] = ethHashRlpEncode(hashes[index], coder);
return rlpEncodeListItems (coder, items, itemCount);
}
extern void
ethHashFillString (BREthereumHash hash,
BREthereumHashString string) {
string[0] = '0';
string[1] = 'x';
hexEncode(&string[2], 2 * ETHEREUM_HASH_BYTES + 1, hash.bytes, ETHEREUM_HASH_BYTES);
}
extern BRArrayOf(BREthereumHash)
ethHashesCopy (BRArrayOf(BREthereumHash) hashes) {
BRArrayOf(BREthereumHash) result;
array_new (result, array_count(hashes));
array_add_array (result, hashes, array_count(hashes));
return result;
}
extern ssize_t
ethHashesIndex (BRArrayOf(BREthereumHash) hashes,
BREthereumHash hash) {
for (size_t index = 0; index < array_count(hashes); index++)
if (ETHEREUM_BOOLEAN_IS_TRUE (ethHashEqual (hash, hashes[index])))
return index;
return -1;
}
| 2.484375 | 2 |
2024-11-18T22:02:44.700938+00:00 | 2018-11-21T13:04:09 | 0f8120da443af0fcebb78b2e1276f53b05636037 | {
"blob_id": "0f8120da443af0fcebb78b2e1276f53b05636037",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-21T13:04:09",
"content_id": "f34b205c8b34ee2f3450a8ef2e034ef1943db50b",
"detected_licenses": [
"MIT"
],
"directory_id": "cf6c5cde3a8d24891bd95887ad47867394490c17",
"extension": "c",
"filename": "block_group.c",
"fork_events_count": 0,
"gha_created_at": "2015-11-20T00:02:42",
"gha_event_created_at": "2018-11-21T13:04:10",
"gha_language": "C",
"gha_license_id": null,
"github_id": 46527954,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1078,
"license": "MIT",
"license_type": "permissive",
"path": "/Boss/SRC/block_group.c",
"provenance": "stackv2-0139.json.gz:111009",
"repo_name": "kaldoran/Send-file-P2P",
"revision_date": "2018-11-21T13:04:09",
"revision_id": "dcb8d44ccaecca70c99786f5e6ea92529b8e6aff",
"snapshot_id": "d1e3dc00b99bb1e5735ec0666ec69d579a9166a5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kaldoran/Send-file-P2P/dcb8d44ccaecca70c99786f5e6ea92529b8e6aff/Boss/SRC/block_group.c",
"visit_date": "2020-12-25T21:12:59.986652"
} | stackv2 | //----------------------------------------------------------
// AUTEUR : REYNAUD Nicolas |
// FICHIER : block_group.c |
// DATE : 10/02/15 |
//----------------------------------------------------------
#include <stdlib.h>
#include "error.h"
#include "group.h"
#include "block_group.h"
blockGroup* newBlockGroup() {
blockGroup* block_group;
if ( (block_group = calloc(1, sizeof(*block_group))) == NULL ) {
QUIT_MSG("Can't allocate memory for block group : ");
}
if ( (block_group->groups = calloc(MAX_GROUP, sizeof(block_group->groups))) == NULL ) {
QUIT_MSG("Can't allocate memory for block group of group : ");
}
block_group->flag = FALSE;
return block_group;
}
void freeBlockGroup(blockGroup* block_group) {
int i;
for ( i = 0; i < block_group->total; i++ ) {
freeGroup(block_group->groups[i]);
}
free(block_group->groups);
free(block_group);
return;
} | 2.3125 | 2 |
2024-11-18T22:02:44.810925+00:00 | 2021-06-26T03:38:58 | c1c070fea1456565604e88a9239e790af3f9c7c2 | {
"blob_id": "c1c070fea1456565604e88a9239e790af3f9c7c2",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-26T03:38:58",
"content_id": "83b6edf915c818c51431172848b4444edc7dcc6b",
"detected_licenses": [
"MIT"
],
"directory_id": "ae714b43b79f6498d775abdae780c126644e6ffa",
"extension": "c",
"filename": "JogodoBicho.c",
"fork_events_count": 0,
"gha_created_at": "2021-05-20T20:05:07",
"gha_event_created_at": "2021-06-08T03:27:35",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 369325514,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3124,
"license": "MIT",
"license_type": "permissive",
"path": "/Jogo do Bicho/JogodoBicho.c",
"provenance": "stackv2-0139.json.gz:111138",
"repo_name": "Gabriel7H/Linguagem-C",
"revision_date": "2021-06-26T03:38:58",
"revision_id": "a169b865abd9d6620ed20a8a11acf173a76ab62d",
"snapshot_id": "604faf5dc024295bcde58807d52c0b53ea62c672",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Gabriel7H/Linguagem-C/a169b865abd9d6620ed20a8a11acf173a76ab62d/Jogo do Bicho/JogodoBicho.c",
"visit_date": "2023-06-13T03:04:02.090423"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <locale.h>
int main(int argc, char *argv[]) {
int res, res1;
setlocale (LC_ALL, "Portuguese");
do{
printf ("====================================================\n");
printf (" QUAL É O ANIMAL? \n");
printf ("====================================================\n");
printf (" ATENÇÃO : Responda as perguntas com 1=sim ou 2=não \n");
printf ("====================================================\n");
printf (" É mamífero? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" É quadrúpede? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" É carnívoro? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é o Leão! \n");
break;
case 2:
printf (" Seu animal é o Cavalo! \n");
break;
}
break;
case 2:
printf (" É carnívoro? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é a baleia! \n");
break;
case 2:
printf (" É Voador? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é o morcego! \n");
break;
case 2:
printf (" Vive geralmente na floresta? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é o macaco \n");
break;
case 2:
printf (" O animal é o Homem \n");
break;
}
} break;
break;
}
break;
}
break;
case 2:
printf (" É quadrupede? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" É carnívoro? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é o crocodilo \n");
break;
case 2:
printf (" Seu animal é a tartaruga \n");
break;
}
break;
case 2:
printf (" É carnívoro? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" É voador? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é a águia \n");
break;
case 2:
printf (" Vive na floresta? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é a cobra \n");
break;
case 2:
printf (" Seu animal é o pinguim \n");
break;
}
break;
}
break;
case 2:
printf (" É voador? ");
scanf ("%d", &res);
switch (res){
case 1:
printf (" Seu animal é o pato \n");
break;
case 2:
printf (" Seu animal é o avestruz \n");
break;
}
break;
}
break;
}
break;
default:
printf (" Animal não encontrado \n");
}
printf (" Pressione 1 para continuar ou 0 para parar: ");
scanf ("%d", &res1);
system ("cls");
}while (res1 != 0);
system ("Pause");
return 0;
}
| 3.046875 | 3 |
2024-11-18T22:02:45.227124+00:00 | 2020-08-08T15:16:27 | 5a1547719ae28100c4c34654c2003a2e7c04fb31 | {
"blob_id": "5a1547719ae28100c4c34654c2003a2e7c04fb31",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-08T15:16:27",
"content_id": "90de80f6d75390089b81986f3a87b43d0656fdcb",
"detected_licenses": [
"MIT"
],
"directory_id": "f85a16180e5cc60e5382b6ff2b563002686f1f3e",
"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": 285613088,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5390,
"license": "MIT",
"license_type": "permissive",
"path": "/main.c",
"provenance": "stackv2-0139.json.gz:111523",
"repo_name": "powerboat9/pac",
"revision_date": "2020-08-08T15:16:27",
"revision_id": "7552a1e5c0e282d7c0c8343f692dec31bd9b8cbe",
"snapshot_id": "c4cbb6ac158e1a661490a0da5cbde537f2862cfe",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/powerboat9/pac/7552a1e5c0e282d7c0c8343f692dec31bd9b8cbe/main.c",
"visit_date": "2022-12-05T15:14:38.746508"
} | stackv2 | #define SIG_ERR -1
#define SIG_DONE -2
#define KEYWORD_AUTO 0
#define KEYWORD_BREAK 1
#define KEYWORD_CASE 2
#define KEYWORD_CHAR 3
#define KEYWORD_CONST 4
#define KEYWORD_CONTINUE 5
#define KEYWORD_DEFAULT 6
#define KEYWORD_DO 7
#define KEYWORD_DOUBLE 8
#define KEYWORD_ELSE 9
#define KEYWORD_ENUM 10
#define KEYWORD_EXTERN 11
#define KEYWORD_FLOAT 12
#define KEYWORD_FOR 13
#define KEYWORD_GOTO 14
#define KEYWORD_IF 15
#define KEYWORD_INT 16
#define KEYWORD_LONG 17
#define KEYWORD_REGISTER 18
#define KEYWORD_RETURN 19
#define KEYWORD_SHORT 20
#define KEYWORD_SIGNED 21
#define KEYWORD_SIZEOF 22
#define KEYWORD_STATIC 23
#define KEYWORD_STRUCT 24
#define KEYWORD_SWITCH 25
#define KEYWORD_TYPEDEF 26
#define KEYWORD_UNION 27
#define KEYWORD_UNSIGNED 28
#define KEYWORD_VOID 29
#define KEYWORD_VOLATILE 30
#define KEYWORD_WHILE 31
#define TOKEN_ADD
#define TOKEN_SUB
#define TOKEN_MUL
#define TOKEN_DIV
#define TOKEN_-
struct parse_state {
}
// Handles control lines, line count, tokenisation, etc.
#define CTRL_LINESTART
#define CTRL_PARSING_IDENT
#define CTRL_PARSING_NDEC
#define CTRL_PARSING_NZERO
#define CTRL_PARSING_NOCT
#define CTRL_PARSING_NHEX
#define CTRL_PARSING_HAD_PLUS
#define CTRL_PARSING_HAD_MINUS
#define CTRL_PARSING_HAD_STAR
#define CTRL_PARSING_HAD_
struct ctrl_state {
struct parse_state next;
long line;
long next_line;
int state;
union {
} state_data;
}
void start_ctrl(struct ctrl_state *state) {
}
void feed_ctrl(struct ctrl_state *state, char c) {
}
void end_ctrl(struct ctrl_state *state) {
}
// Handles line splicing
struct splice_state {
struct ctrl_state next;
int holding_back;
}
void start_splice(struct splice_state *state) {
state->holding_back = 0;
start_ctrl(&state->next);
}
void feed_splice(struct splice_state *state, char c) {
// Handles line splicing continuation
if (splice_state->holding_back) {
switch (c) {
default:
feed_ctrl(&state->next, '\\');
feed_ctrl(&state->next, c);
case '\n':
state->holding_back = 0;
return;
case '\\':
feed_ctrl(&state->next, '\\');
}
} else {
if (c == '\\') {
splice_state->holding_back = 1;
} else {
feed_ctrl(&state->next, c);
}
}
}
void end_splice(struct splice_state *state) {
if (state->holding_back) {
feed_ctrl(&state->next, '\\');
}
end_ctrl(&state->next);
}
// Handle trigraph sequences
struct trig_state {
struct splice_state next;
int cnt;
}
void start_trig(struct trig_state *state) {
state->cnt = 0;
start_splice(&state->next);
}
void feed_trig(struct trig_state *state, char c) {
switch (state->cnt) {
case 0:
if (c == '?') {
state->cnt = 1;
} else {
feed_splice(&state->next, c);
}
return;
case 1:
if (c == '?') {
state->cnt = 2;
} else {
feed_splice(&state->next, '?');
feed_splice(&state->next, c);
state->cnt = 0;
}
return;
case 2:
switch (c) {
case '=':
feed_splice(&state->next, '#');
state->cnt = 0;
return;
case '/':
feed_splice(&state->next, '\\');
state->cnt = 0;
return;
case '\'':
feed_splice(&state->next, '^');
state->cnt = 0;
return;
case '(':
feed_splice(&state->next, '[');
state->cnt = 0;
return;
case ')':
feed_splice(&state->next, ']');
state->cnt = 0;
return;
case '!':
feed_splice(&state->next, '|');
state->cnt = 0;
return;
case '<':
feed_splice(&state->next, '{');
state->cnt = 0;
return;
case '>':
feed_splice(&state->next, '}');
state->cnt = 0;
return;
case '-':
feed_splice(&state->next, '~');
state->cnt = 0;
return;
case '?':
feed_splice(&state->next, '?');
return;
default:
feed_splice(&state->next, '?');
feed_splice(&state->next, '?');
feed_splice(&state->next, c);
state->cnt = 0;
return;
}
}
}
void end_trig(struct trig_state *state) {
switch (state->cnt) {
case 1:
feed_splice(&state->next, '?');
case 2:
feed_splice(&state->next, '?');
}
end_splice(&state->next);
}
// Handle input
void parse_input(char *buf, size_t len) {
struct trig_state state;
start_trig(&state);
for (size_t i = 0; i < len; i++) {
feed_trig(&state, buf[i]);
}
end_trig(&state);
}
| 2.1875 | 2 |
2024-11-18T22:02:45.700593+00:00 | 2020-11-02T01:18:12 | 851c2f093f323ba58c63cf7f2a896d0c2319cfea | {
"blob_id": "851c2f093f323ba58c63cf7f2a896d0c2319cfea",
"branch_name": "refs/heads/main",
"committer_date": "2020-11-02T01:18:12",
"content_id": "2e809a65099af176cb9572b4356ea88916b78e02",
"detected_licenses": [
"MIT"
],
"directory_id": "bdd93c0637c372e10e676c14d11d7ff1b4f80bfd",
"extension": "c",
"filename": "Untitled1.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 309213804,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 501,
"license": "MIT",
"license_type": "permissive",
"path": "/EXERCICIOS_13_02_2013_16e05/E1_01a15_falta_7_11_13_15/E1_falta_7_11_13_15/Untitled1.c",
"provenance": "stackv2-0139.json.gz:111909",
"repo_name": "WilliamDeveloper/uniritter-algoritmos",
"revision_date": "2020-11-02T01:18:12",
"revision_id": "fc349fd7560cbe8319c86ee65beeca1d1b590237",
"snapshot_id": "fe35b30cfcb43a71390acbf8cada256ee06b6739",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/WilliamDeveloper/uniritter-algoritmos/fc349fd7560cbe8319c86ee65beeca1d1b590237/EXERCICIOS_13_02_2013_16e05/E1_01a15_falta_7_11_13_15/E1_falta_7_11_13_15/Untitled1.c",
"visit_date": "2023-01-06T08:11:04.875579"
} | stackv2 | #include <stdio.h>
int main ( )
{
int x[29],cont,cont1,val,cont_aux=0;
for(cont=0;cont<30;cont++)
{
printf("Digite n %d: ",cont+1);
scanf("%d",&val);
for(cont1=0;(cont1 < cont_aux) && (val != x[cont1]);cont1++)
{}
if (cont1 == cont_aux) {
x[cont_aux] = val;
cont_aux++;
}
}
printf("Tamanho do vetor sem tamanhos repetidos: %d\n",cont_aux);
for (cont=0;cont<cont_aux;cont++) {
printf("%d ", x[cont]);
}
system("pause");
}
| 2.90625 | 3 |
2024-11-18T22:02:45.957540+00:00 | 2022-07-13T17:40:32 | 589878d920ce6849727d64537ee123d74e94a338 | {
"blob_id": "589878d920ce6849727d64537ee123d74e94a338",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-13T17:40:32",
"content_id": "0ce08496744f3bab4611a92b42665c3556db3284",
"detected_licenses": [
"MIT"
],
"directory_id": "96e8b2039a8b85c75280c790e0a798ec2632fcda",
"extension": "c",
"filename": "ini.c",
"fork_events_count": 13,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 25109115,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 33538,
"license": "MIT",
"license_type": "permissive",
"path": "/source/push[exe]/ini.c",
"provenance": "stackv2-0139.json.gz:112039",
"repo_name": "Volkanite/Push",
"revision_date": "2022-07-13T17:40:32",
"revision_id": "de059a4d2dc5add01aa17610786d3a2acc6c3070",
"snapshot_id": "1a3941ccc9ebf5a57523936b3eaeea9ad348a65a",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/Volkanite/Push/de059a4d2dc5add01aa17610786d3a2acc6c3070/source/push[exe]/ini.c",
"visit_date": "2022-07-27T07:44:43.451520"
} | stackv2 | #include <sl.h>
#include <slfile.h>
#include <pushbase.h>
#include "push.h"
static const char bom_utf8[] = {0xEF,0xBB,0xBF};
typedef struct tagPROFILEKEY
{
WCHAR *Value;
struct tagPROFILEKEY *next;
WCHAR Name[1];
} PROFILEKEY;
typedef struct tagPROFILESECTION
{
struct tagPROFILEKEY *Key;
struct tagPROFILESECTION *next;
WCHAR Name[1];
} PROFILESECTION;
typedef struct
{
INTBOOL changed;
PROFILESECTION *section;
WCHAR *FileName;
FILETIME LastWriteTime;
//ENCODING encoding;
} PROFILE;
#define N_CACHED_PROFILES 10
#define INVALID_FILE_SIZE 0xFFFFFFFF
#define IS_TEXT_UNICODE_SIGNATURE 8
#define IS_TEXT_UNICODE_REVERSE_SIGNATURE 128
#define IS_TEXT_UNICODE_ODD_LENGTH 512
#define ERROR_FILE_NOT_FOUND 2
#define RtlUshortByteSwap(_x) _byteswap_ushort((WORD)(_x))
/* Cached profile files */
static PROFILE *MRUProfile[N_CACHED_PROFILES]={NULL};
#define CurrentProfile (MRUProfile[0])
/* Check for comments in profile */
#define IS_ENTRY_COMMENT(str) ((str)[0] == ';')
static const WCHAR wininiW[] = { 'w','i','n','.','i','n','i',0 };
extern RTL_CRITICAL_SECTION PROFILE_CritSect;
static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
{
0, 0, &PROFILE_CritSect,
{ &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
0, 0, 0
};
RTL_CRITICAL_SECTION PROFILE_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
typedef enum _RTL_PATH_TYPE
{
RtlPathTypeUnknown,
RtlPathTypeUncAbsolute,
RtlPathTypeDriveAbsolute,
RtlPathTypeDriveRelative,
RtlPathTypeRooted,
RtlPathTypeRelative,
RtlPathTypeLocalDevice,
RtlPathTypeRootLocalDevice,
} RTL_PATH_TYPE;
NTSTATUS __stdcall RtlGetFullPathName_UEx(
WCHAR* FileName,
ULONG BufferLength,
WCHAR* Buffer,
WCHAR** FilePart,
RTL_PATH_TYPE* InputPathType
);
BOOLEAN __stdcall RtlIsTextUnicode (
VOID* buf,
INT32 len,
INT32 * pf
);
NTSTATUS
__stdcall
RtlLeaveCriticalSection(
RTL_CRITICAL_SECTION* CriticalSection
);
/***********************************************************************
* PROFILE_Save
*
* Save a profile tree to a file.
*/
VOID
PROFILE_Save( VOID* FileHandle, PROFILESECTION* Section )
{
PROFILEKEY *key;
IO_STATUS_BLOCK isb;
WCHAR *buffer, *p, bom;
//write UTF16-LE encoding marker to the file
//PROFILE_WriteMarker(FileHandle);
bom = 0xFEFF;
NtWriteFile(
FileHandle,
NULL,
NULL,
NULL,
&isb,
&bom,
sizeof(bom),
NULL,
NULL
);
for ( ; Section; Section = Section->next)
{
int length = 0;
if (Section->Name[0]) length += String_GetLength( Section->Name ) + 4;
for (key = Section->Key; key; key = key->next)
{
length += String_GetLength(key->Name) + 2;
if (key->Value) length += String_GetLength(key->Value) + 1;
}
buffer = (WCHAR*) Memory_Allocate(length * sizeof(WCHAR));
if (!buffer) return;
p = buffer;
if (Section->Name[0])
{
*p++ = '[';
String_Copy(p, Section->Name);
p += String_GetLength(p);
*p++ = ']';
*p++ = '\r';
*p++ = '\n';
}
for (key = Section->Key; key; key = key->next)
{
String_Copy(p, key->Name);
p += String_GetLength(p);
if (key->Value)
{
*p++ = '=';
String_Copy(p, key->Value);
p += String_GetLength(p);
}
*p++ = '\r';
*p++ = '\n';
}
NtWriteFile(
FileHandle,
NULL,
NULL,
NULL,
&isb,
buffer,
length * sizeof(WCHAR),
NULL,
NULL
);
Memory_Free(buffer);
}
}
/***********************************************************************
* PROFILE_FlushFile
*
* Flush the current profile to disk if changed.
*/
BOOLEAN
PROFILE_FlushFile(void)
{
VOID* fileHandle = NULL;
FILETIME LastWriteTime;
NTSTATUS status;
if(!CurrentProfile)
{
return FALSE;
}
if (!CurrentProfile->changed) return TRUE;
status = File_Create(
&fileHandle,
CurrentProfile->FileName,
FILE_READ_ATTRIBUTES | SYNCHRONIZE | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
FILE_OVERWRITE_IF,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
NULL
);
if (!NT_SUCCESS(status))
{
return FALSE;
}
PROFILE_Save( fileHandle, CurrentProfile->section );
if (File_GetLastWriteTime(fileHandle, &LastWriteTime))
CurrentProfile->LastWriteTime=LastWriteTime;
NtClose(fileHandle);
CurrentProfile->changed = FALSE;
return TRUE;
}
VOID NtGetSystemTimeAsFileTime(FILETIME* lpFileTime);
/***********************************************************************
*
* Compares a file time with the current time. If the file time is
* at least 2.1 seconds in the past, return true.
*
* Intended as cache safety measure: The time resolution on FAT is
* two seconds, so files that are not at least two seconds old might
* keep their time even on modification, so don't cache them.
*/
BOOLEAN
is_not_current(FILETIME * ft)
{
FILETIME Now;
INT64 ftll, nowll;
NtGetSystemTimeAsFileTime(&Now);
ftll = ((INT64)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
nowll = ((INT64)Now.dwHighDateTime << 32) + Now.dwLowDateTime;
//TRACE("%08x;%08x\n",(unsigned)ftll+21000000,(unsigned)nowll);
return ftll + 21000000 < nowll;
}
/***********************************************************************
* PROFILE_Free
*
* Free a profile tree.
*/
static
VOID
PROFILE_Free( PROFILESECTION *Section )
{
PROFILESECTION *next_section;
PROFILEKEY *key, *next_key;
for ( ; Section; Section = next_section)
{
for (key = Section->Key; key; key = next_key)
{
next_key = key->next;
Memory_Free(key->Value);
Memory_Free(key);
}
next_section = Section->next;
Memory_Free(Section);
}
}
WCHAR
*memrchrW(const WCHAR *ptr, WCHAR ch, int n)
{
const WCHAR *end;
WCHAR *ret = NULL;
for (end = ptr + n; ptr < end; ptr++)
if (*ptr == ch)
ret = (WCHAR *)(UINT_B)ptr;
return ret;
}
/* returns 1 if a character white space else 0 */
static
INT32
PROFILE_isspaceW(WCHAR c)
{
/* ^Z (DOS EOF) is a space too (found on CD-ROMs) */
return _iswspace(c) || c == 0x1a;
}
/***********************************************************************
* PROFILE_Load
*
* Load a profile tree from a file.
*/
PROFILESECTION*
PROFILE_Load( VOID* FileHandle )
{
void *bufferBase, *pBuffer;
WCHAR * file;
const WCHAR *szLineStart, *szLineEnd;
const WCHAR *szValueStart, *szEnd, *next_line;
int line = 0, length;
PROFILESECTION *section, *firstSection;
PROFILESECTION **next_section;
PROFILEKEY *key, *prev_key, **next_key;
DWORD fileSize;
NTSTATUS status;
IO_STATUS_BLOCK isb;
FILE_STANDARD_INFORMATION fileInformation;
//fileSize = GetFileSize(FileHandle, NULL);
NtQueryInformationFile(
FileHandle,
&isb,
&fileInformation,
sizeof(FILE_STANDARD_INFORMATION),
FileStandardInformation
);
fileSize = fileInformation.EndOfFile.QuadPart;
if (fileSize == INVALID_FILE_SIZE || fileSize == 0)
return NULL;
bufferBase = Memory_Allocate(fileSize);
if (!bufferBase) return NULL;
status = NtReadFile(FileHandle, NULL, NULL, NULL, &isb, bufferBase, fileSize, NULL, NULL);
fileSize = isb.Information;
if (!NT_SUCCESS(status))
{
Memory_Free(bufferBase);
return NULL;
}
length = sizeof(WCHAR);
/* len is set to the number of bytes in the character marker.
* we want to skip these bytes */
pBuffer = (char *)bufferBase + length;
fileSize -= length;
file = (WCHAR*) pBuffer;
szEnd = (WCHAR *)((char *)pBuffer + fileSize);
firstSection = (PROFILESECTION*)Memory_Allocate(sizeof(*section));
if(firstSection == NULL)
{
if (file != pBuffer)
Memory_Free(file);
Memory_Free(bufferBase);
return NULL;
}
firstSection->Name[0] = 0;
firstSection->Key = NULL;
firstSection->next = NULL;
next_section = &firstSection->next;
next_key = &firstSection->Key;
prev_key = NULL;
next_line = file;
while (next_line < szEnd)
{
szLineStart = next_line;
next_line = Memory_FindFirstChar(szLineStart, '\n', szEnd - szLineStart);
if (!next_line) next_line = Memory_FindFirstChar(szLineStart, '\r', szEnd - szLineStart);
if (!next_line) next_line = szEnd;
else next_line++;
szLineEnd = next_line;
line++;
/* get rid of white space */
while (szLineStart < szLineEnd && PROFILE_isspaceW(*szLineStart)) szLineStart++;
while ((szLineEnd > szLineStart) && PROFILE_isspaceW(szLineEnd[-1])) szLineEnd--;
if (szLineStart >= szLineEnd) continue;
if (*szLineStart == '[') /* section start */
{
const WCHAR * szSectionEnd;
if (!(szSectionEnd = memrchrW( szLineStart, ']', szLineEnd - szLineStart )))
{
/*WARN("Invalid section header at line %d: %s\n",
line, debugstr_wn(szLineStart, (int)(szLineEnd - szLineStart)) );*/
}
else
{
szLineStart++;
length = (int)(szSectionEnd - szLineStart);
/* no need to allocate +1 for NULL terminating character as
* already included in structure */
/*if (!(section = HeapAlloc( GetProcessHeap(), 0, sizeof(*section) + length * sizeof(WCHAR) )))
break;*/
if (!(section = (PROFILESECTION*)Memory_Allocate(sizeof(*section) + length * sizeof(WCHAR))))
break;
ntdll_memcpy(section->Name, szLineStart, length * sizeof(WCHAR));
section->Name[length] = '\0';
section->Key = NULL;
section->next = NULL;
*next_section = section;
next_section = §ion->next;
next_key = §ion->Key;
prev_key = NULL;
//TRACE("New section: %s\n", debugstr_w(section->name));
continue;
}
}
/* get rid of white space after the name and before the start
* of the value */
length = szLineEnd - szLineStart;
if ((szValueStart = Memory_FindFirstChar( szLineStart, '=', szLineEnd - szLineStart )) != NULL)
{
const WCHAR *szNameEnd = szValueStart;
while ((szNameEnd > szLineStart) && PROFILE_isspaceW(szNameEnd[-1])) szNameEnd--;
length = szNameEnd - szLineStart;
szValueStart++;
while (szValueStart < szLineEnd && PROFILE_isspaceW(*szValueStart)) szValueStart++;
}
if (length || !prev_key || *prev_key->Name)
{
/* no need to allocate +1 for NULL terminating character as
* already included in structure */
//if (!(key = HeapAlloc( GetProcessHeap(), 0, sizeof(*key) + length * sizeof(WCHAR) ))) break;
if (!(key = (PROFILEKEY*)Memory_Allocate(sizeof(*key) + length * sizeof(WCHAR))))
break;
ntdll_memcpy(key->Name, szLineStart, length * sizeof(WCHAR));
key->Name[length] = '\0';
if (szValueStart)
{
length = (int)(szLineEnd - szValueStart);
//key->value = HeapAlloc( GetProcessHeap(), 0, (length + 1) * sizeof(WCHAR) );
key->Value = (WCHAR*)Memory_Allocate((length + 1) * sizeof(WCHAR));
ntdll_memcpy(key->Value, szValueStart, length * sizeof(WCHAR));
key->Value[length] = '\0';
}
else
{
key->Value = NULL;
}
key->next = NULL;
*next_key = key;
next_key = &key->next;
prev_key = key;
}
}
if (file != pBuffer)
Memory_Free(file);
Memory_Free(bufferBase);
return firstSection;
}
/***********************************************************************
* PROFILE_ReleaseFile
*
* Flush the current profile to disk and remove it from the cache.
*/
VOID PROFILE_ReleaseFile(void)
{
PROFILE_FlushFile();
PROFILE_Free( CurrentProfile->section );
Memory_Free(CurrentProfile->FileName);
CurrentProfile->changed = FALSE;
CurrentProfile->section = NULL;
CurrentProfile->FileName = NULL;
Memory_Clear(&CurrentProfile->LastWriteTime, sizeof(CurrentProfile->LastWriteTime));
}
/***********************************************************************
* PROFILE_Open
*
* Open a profile file, checking the cached file first.
*/
BOOLEAN
PROFILE_Open( WCHAR* Filename, BOOLEAN WriteAccess )
{
WCHAR buffer[260];
WCHAR* dummy;
WCHAR* dummy2;
VOID* fileHandle = INVALID_HANDLE_VALUE;
FILETIME LastWriteTime = {0};
int i,j;
PROFILE *tempProfile;
NTSTATUS status;
/* First time around */
if(!CurrentProfile)
for(i=0;i<N_CACHED_PROFILES;i++)
{
MRUProfile[i] = (PROFILE*)Memory_Allocate(sizeof(PROFILE));
if(MRUProfile[i] == NULL) break;
MRUProfile[i]->changed=FALSE;
MRUProfile[i]->section=NULL;
MRUProfile[i]->FileName=NULL;
Memory_Clear(&MRUProfile[i]->LastWriteTime, sizeof(FILETIME));
}
if (!Filename)
Filename = (WCHAR*) wininiW;
dummy2 = &dummy;
RtlGetFullPathName_UEx(Filename, sizeof(buffer), buffer, &dummy, (RTL_PATH_TYPE*) &dummy2);
status = File_Create(
&fileHandle,
buffer,
FILE_READ_ATTRIBUTES | SYNCHRONIZE | GENERIC_READ | (WriteAccess ? GENERIC_WRITE : 0),
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
NULL
);
if (!NT_SUCCESS(status) && status != STATUS_OBJECT_NAME_NOT_FOUND)
{
return FALSE;
}
for(i=0;i<N_CACHED_PROFILES;i++)
{
if ((MRUProfile[i]->FileName && !String_Compare( buffer, MRUProfile[i]->FileName )))
{
if(i)
{
PROFILE_FlushFile();
tempProfile=MRUProfile[i];
for(j=i;j>0;j--)
MRUProfile[j]=MRUProfile[j-1];
CurrentProfile=tempProfile;
}
if (fileHandle != INVALID_HANDLE_VALUE)
{
File_GetLastWriteTime(fileHandle, &LastWriteTime);
if (!ntdll_memcmp( &CurrentProfile->LastWriteTime, &LastWriteTime, sizeof(FILETIME) ) &&
is_not_current(&LastWriteTime))
{
}
else
{
PROFILE_Free(CurrentProfile->section);
CurrentProfile->section = PROFILE_Load(fileHandle);
CurrentProfile->LastWriteTime = LastWriteTime;
}
NtClose(fileHandle);
return TRUE;
}
}
}
/* Flush the old current profile */
PROFILE_FlushFile();
/* Make the oldest profile the current one only in order to get rid of it */
if(i==N_CACHED_PROFILES)
{
tempProfile=MRUProfile[N_CACHED_PROFILES-1];
for(i=N_CACHED_PROFILES-1;i>0;i--)
MRUProfile[i]=MRUProfile[i-1];
CurrentProfile=tempProfile;
}
if(CurrentProfile->FileName) PROFILE_ReleaseFile();
/* OK, now that CurProfile is definitely free we assign it our new file */
CurrentProfile->FileName = (WCHAR*)Memory_Allocate((String_GetLength(buffer)+1) * sizeof(WCHAR));
String_Copy(CurrentProfile->FileName, buffer);
if (fileHandle != INVALID_HANDLE_VALUE)
{
CurrentProfile->section = PROFILE_Load(fileHandle);
File_GetLastWriteTime(fileHandle, &CurrentProfile->LastWriteTime);
NtClose(fileHandle);
}
return TRUE;
}
/***********************************************************************
* PROFILE_DeleteSection
*
* Delete a section from a profile tree.
*/
static
BOOLEAN
PROFILE_DeleteSection( PROFILESECTION **Section, WCHAR* Name )
{
while (*Section)
{
//if ((*section)->Name[0] && !strcmpiW( (*section)->name, name ))
if ((*Section)->Name[0] && !String_Compare( (*Section)->Name, Name ))
{
PROFILESECTION *to_del = *Section;
*Section = to_del->next;
to_del->next = NULL;
PROFILE_Free( to_del );
return TRUE;
}
Section = &(*Section)->next;
}
return FALSE;
}
/***********************************************************************
* PROFILE_DeleteKey
*
* Delete a key from a profile tree.
*/
static
BOOLEAN
PROFILE_DeleteKey( PROFILESECTION **Section, WCHAR* SectionName, WCHAR* KeyName )
{
while (*Section)
{
if ((*Section)->Name[0] && !String_Compare( (*Section)->Name, SectionName ))
{
PROFILEKEY **key = &(*Section)->Key;
while (*key)
{
if (!String_Compare( (*key)->Name, KeyName ))
{
PROFILEKEY *to_del = *key;
*key = to_del->next;
Memory_Free(to_del->Value);
Memory_Free(to_del);
return TRUE;
}
key = &(*key)->next;
}
}
Section = &(*Section)->next;
}
return FALSE;
}
/***********************************************************************
* PROFILE_Find
*
* Find a key in a profile tree, optionally creating it.
*/
static PROFILEKEY *PROFILE_Find(
PROFILESECTION **Section,
WCHAR* SectionName,
WCHAR* KeyName,
BOOLEAN create,
BOOLEAN create_always
)
{
WCHAR* p;
int seclen, keylen;
while (PROFILE_isspaceW(*SectionName)) SectionName++;
if (*SectionName)
//p = section_name + strlenW(section_name) - 1;
p = SectionName + String_GetLength(SectionName) - 1;
else
p = SectionName;
while ((p > SectionName) && PROFILE_isspaceW(*p)) p--;
seclen = p - SectionName + 1;
while (PROFILE_isspaceW(*KeyName)) KeyName++;
if (*KeyName)
//p = key_name + strlenW(key_name) - 1;
p = KeyName + String_GetLength(KeyName) - 1;
else
p = KeyName;
while ((p > KeyName) && PROFILE_isspaceW(*p)) p--;
keylen = p - KeyName + 1;
while (*Section)
{
if ( ((*Section)->Name[0])
//&& (!(strncmpiW( (*section)->name, SectionName, seclen )))
&& (!(String_CompareN( (*Section)->Name, SectionName, seclen )))
&& (((*Section)->Name)[seclen] == '\0') )
{
PROFILEKEY **key = &(*Section)->Key;
while (*key)
{
/* If create_always is FALSE then we check if the keyname
* already exists. Otherwise we add it regardless of its
* existence, to allow keys to be added more than once in
* some cases.
*/
if(!create_always)
{
if ( (!(String_CompareN( (*key)->Name, KeyName, keylen )))
&& (((*key)->Name)[keylen] == '\0') )
return *key;
}
key = &(*key)->next;
}
if (!create) return NULL;
if (!(*key = (PROFILEKEY*)Memory_Allocate(sizeof(PROFILEKEY) + String_GetLength(KeyName) * sizeof(WCHAR) )))
{
return NULL;
}
String_Copy((*key)->Name, KeyName);
(*key)->Value = NULL;
(*key)->next = NULL;
return *key;
}
Section = &(*Section)->next;
}
if (!create) return NULL;
*Section = (PROFILESECTION*)Memory_Allocate(sizeof(PROFILESECTION) + String_GetLength(SectionName) * sizeof(WCHAR));
if(*Section == NULL) return NULL;
String_Copy((*Section)->Name, SectionName);
(*Section)->next = NULL;
if (!((*Section)->Key = (PROFILEKEY*)Memory_Allocate(sizeof(PROFILEKEY) + String_GetLength(KeyName) * sizeof(WCHAR) )))
{
Memory_Free(*Section);
return NULL;
}
String_Copy((*Section)->Key->Name, KeyName);
(*Section)->Key->Value = NULL;
(*Section)->Key->next = NULL;
return (*Section)->Key;
}
/***********************************************************************
* PROFILE_SetString
*
* Set a profile string.
*/
static
BOOLEAN
PROFILE_SetString(
WCHAR* section_name,
WCHAR* key_name,
WCHAR* Value,
BOOLEAN create_always
)
{
if (!key_name) /* Delete a whole section */
{
//TRACE("(%s)\n", debugstr_w(section_name));
CurrentProfile->changed |= PROFILE_DeleteSection( &CurrentProfile->section, section_name );
return TRUE; /* Even if PROFILE_DeleteSection() has failed,
this is not an error on application's level.*/
}
else if (!Value) /* Delete a key */
{
//TRACE("(%s,%s)\n", debugstr_w(section_name), debugstr_w(key_name) );
CurrentProfile->changed |= PROFILE_DeleteKey( &CurrentProfile->section, section_name, key_name );
return TRUE; /* same error handling as above */
}
else /* Set the key value */
{
PROFILEKEY *key = PROFILE_Find(&CurrentProfile->section, section_name,
key_name, TRUE, create_always );
/*TRACE("(%s,%s,%s):\n",
debugstr_w(section_name), debugstr_w(key_name), debugstr_w(value) );*/
if (!key) return FALSE;
/* strip the leading spaces. We can safely strip \n\r and
* friends too, they should not happen here anyway. */
while (PROFILE_isspaceW(*Value)) Value++;
if (key->Value)
{
if (!String_Compare( key->Value, Value ))
{
return TRUE; /* No change needed */
}
Memory_Free(key->Value );
}
key->Value = (WCHAR*)Memory_Allocate((String_GetLength(Value) + 1) * sizeof(WCHAR));
String_Copy(key->Value, Value);
CurrentProfile->changed = TRUE;
}
return TRUE;
}
static
INT32
PROFILE_GetSectionNames( WCHAR* buffer, DWORD len )
{
WCHAR* buf;
UINT32 buflen,tmplen;
PROFILESECTION *section;
//TRACE("(%p, %d)\n", buffer, len);
if (!buffer || !len)
return 0;
if (len==1) {
*buffer='\0';
return 0;
}
buflen=len-1;
buf=buffer;
section = CurrentProfile->section;
while ((section!=NULL)) {
if (section->Name[0])
{
tmplen = String_GetLength(section->Name);
if (tmplen >= buflen)
{
if (buflen > 0) {
ntdll_memcpy(buf, section->Name, (buflen-1) * sizeof(WCHAR));
buf += buflen-1;
*buf++='\0';
}
*buf='\0';
return len-2;
}
ntdll_memcpy(buf, section->Name, tmplen * sizeof(WCHAR));
buf += tmplen;
buflen -= tmplen;
}
section = section->next;
}
*buf='\0';
return buf-buffer;
}
/***********************************************************************
* PROFILE_CopyEntry
*
* Copy the content of an entry into a buffer, removing quotes, and possibly
* translating environment variables.
*/
static
VOID
PROFILE_CopyEntry(
WCHAR* Buffer,
WCHAR* Value,
UINT32 Length,
BOOLEAN strip_quote
)
{
WCHAR quote = '\0';
if(!Buffer) return;
if (strip_quote && ((*Value == '\'') || (*Value == '\"')))
{
if (Value[1] && (Value[String_GetLength(Value) - 1] == *Value)) quote = *Value++;
}
String_CopyN( Buffer, Value, Length);
if (quote && (Length >= String_GetLength(Value))) Buffer[String_GetLength(Buffer) - 1] = '\0';
}
/***********************************************************************
* PROFILE_GetSection
*
* Returns all keys of a section.
* If return_values is TRUE, also include the corresponding values.
*/
static
INT32
PROFILE_GetSection(
PROFILESECTION *Section,
WCHAR* SectionName,
WCHAR* Buffer,
DWORD Length,
BOOLEAN return_values
)
{
PROFILEKEY *key;
if(!Buffer) return 0;
while (Section)
{
if (Section->Name[0] && !String_Compare( Section->Name, SectionName ))
{
UINT32 oldlen = Length;
UINT32 bufferLength;
for (key = Section->Key; key; key = key->next)
{
if (Length <= 2)
break;
if (!*key->Name)
continue; /* Skip empty lines */
if (IS_ENTRY_COMMENT(key->Name))
continue; /* Skip comments */
if (!return_values && !key->Value)
continue; /* Skip lines w.o. '=' */
PROFILE_CopyEntry( Buffer, key->Name, Length - 1, 0 );
// Return if buffer too small
if (String_GetLength(key->Name) > (Length - 1))
return oldlen - 2;
bufferLength = String_GetLengthN( Buffer, Length ) + 1;
Length -= bufferLength;
Buffer += bufferLength;
if (Length < 2)
break;
if (return_values && key->Value)
{
Buffer[-1] = '=';
PROFILE_CopyEntry ( Buffer, key->Value, Length - 1, 0 );
Length -= String_GetLength( Buffer ) + 1;
Buffer += String_GetLength( Buffer ) + 1;
}
}
*Buffer = '\0';
if (Length <= 1)
// If either lpszSection or lpszKey is NULL and the supplied destination buffer is too small to hold all the
// strings, the last string is truncated and followed by two null characters. In this case, the return value is
// equal to cchReturnBuffer minus two.
{
Buffer[-1] = '\0';
return oldlen - 2;
}
return oldlen - Length;
}
Section = Section->next;
}
Buffer[0] = Buffer[1] = '\0';
return 0;
}
/***********************************************************************
* PROFILE_GetString
*
* Get a profile string.
*
* Tests with GetPrivateProfileString16, W95a,
* with filled buffer ("****...") and section "set1" and key_name "1" valid:
* section key_name def_val res buffer
* "set1" "1" "x" 43 [data]
* "set1" "1 " "x" 43 [data] (!)
* "set1" " 1 "' "x" 43 [data] (!)
* "set1" "" "x" 1 "x"
* "set1" "" "x " 1 "x" (!)
* "set1" "" " x " 3 " x" (!)
* "set1" NULL "x" 6 "1\02\03\0\0"
* "set1" "" "x" 1 "x"
* NULL "1" "x" 0 "" (!)
* "" "1" "x" 1 "x"
* NULL NULL "" 0 ""
*
*
*/
static
INT32
PROFILE_GetString(
WCHAR* section,
WCHAR* key_name,
WCHAR* def_val,
WCHAR* Buffer,
DWORD len
)
{
PROFILEKEY *key = NULL;
static const WCHAR empty_strW[] = { 0 };
if(!Buffer || !len) return 0;
if (!def_val) def_val = (WCHAR*) empty_strW;
if (key_name)
{
if (!key_name[0])
{
PROFILE_CopyEntry(Buffer, def_val, len, TRUE);
//return strlenW(buffer);
return String_GetLength( Buffer );
}
key = PROFILE_Find(
&CurrentProfile->section,
section,
key_name,
FALSE,
FALSE
);
PROFILE_CopyEntry(
Buffer,
(key && key->Value) ? key->Value : def_val,
len,
TRUE
);
/*TRACE("(%s,%s,%s): returning %s\n",
debugstr_w(section), debugstr_w(key_name),
debugstr_w(def_val), debugstr_w(Buffer) );*/
//return strlenW( Buffer );
return String_GetLength( Buffer );
}
/* no "else" here ! */
if (section && section[0])
{
INT32 ret = PROFILE_GetSection(
CurrentProfile->section,
section,
Buffer,
len,
FALSE
);
if (!Buffer[0]) /* no luck -> def_val */
{
PROFILE_CopyEntry(Buffer, def_val, len, TRUE);
//ret = strlenW(Buffer);
ret = String_GetLength(Buffer);
}
return ret;
}
Buffer[0] = '\0';
return 0;
}
/**
* Copies a string into the specified section of an initialization file.
* Synonymous to WritePrivateProfileString().
*
* \param Section Name of the section. Like lpAppName.
* \param Entry Name of the entry. Like lpKeyName.
* \param String The string. Like lpString.
* \param FileName The ini filename. Like lpFileName.
*/
BOOLEAN Ini_WriteString( WCHAR* section, WCHAR* entry, WCHAR* string, WCHAR* FileName )
{
BOOLEAN ret = FALSE;
RtlEnterCriticalSection( &PROFILE_CritSect );
if (!section && !entry && !string) /* documented "file flush" case */
{
if (PROFILE_Open(FileName, TRUE))
{
if (CurrentProfile) PROFILE_ReleaseFile(); /* always return FALSE in this case */
}
}
else if (PROFILE_Open(FileName, TRUE))
{
if (section)
{
ret = PROFILE_SetString(section, entry, string, FALSE);
PROFILE_FlushFile();
}
}
RtlLeaveCriticalSection( &PROFILE_CritSect );
return ret;
}
DWORD Ini_GetString( wchar_t* section, wchar_t* entry, wchar_t* def_val, wchar_t* Buffer, DWORD Length, wchar_t* FileName )
{
int ret;
WCHAR* defval_tmp = NULL;
/* strip any trailing ' ' of def_val. */
if (def_val)
{
//WCHAR* p = def_val + strlenW(def_val) - 1;
WCHAR* p = def_val + String_GetLength(def_val) - 1;
while (p > def_val && *p == ' ')
p--;
if (p >= def_val)
{
int length = (int)(p - def_val) + 1;
defval_tmp = (WCHAR*)Memory_Allocate((length + 1) * sizeof(WCHAR));
ntdll_memcpy(defval_tmp, def_val, length * sizeof(WCHAR));
defval_tmp[length] = '\0';
def_val = defval_tmp;
}
}
RtlEnterCriticalSection( &PROFILE_CritSect );
if (PROFILE_Open(FileName, FALSE))
{
if (section == NULL)
ret = PROFILE_GetSectionNames(Buffer, Length);
else
/* PROFILE_GetString can handle the 'entry == NULL' case */
ret = PROFILE_GetString( section, entry, def_val, Buffer, Length );
}
else if (Buffer && def_val)
{
String_CopyN(Buffer, def_val, Length);
ret = String_GetLength( Buffer );
}
else
{
ret = 0;
}
RtlLeaveCriticalSection( &PROFILE_CritSect );
if (defval_tmp)
{
Memory_Free(defval_tmp);
}
return ret;
}
VOID SlIniWriteBoolean( WCHAR* Section, WCHAR* Key, BOOLEAN bolValue )
{
WCHAR value[255];
String_Format(value, 255, L"%ls", bolValue ? L"True" : L"False");
Ini_WriteString(Section, Key, value, L".\\" PUSH_SETTINGS_FILE);
}
VOID SlIniWriteSubKey( WCHAR *Section, WCHAR *pszMasterKey, WCHAR *pszSubKey, WCHAR *Value )
{
WCHAR key[260];
String_Copy(key, L"(");
String_Concatenate(key, pszMasterKey);
String_Concatenate(key, L").");
String_Concatenate(key, pszSubKey);
Ini_WriteString(Section, key, Value, L".\\" PUSH_SETTINGS_FILE);
}
BOOLEAN Ini_ReadBoolean( WCHAR* Section, WCHAR* Key, BOOLEAN DefaultValue, WCHAR* FileName )
{
WCHAR result[255], defaultValue[255];
BOOLEAN bResult;
String_Format(defaultValue, 255, L"%ls", DefaultValue? L"True" : L"False");
Ini_GetString(Section, Key, defaultValue, result, 255, FileName);
bResult = (String_Compare(result, L"True") == 0 ||
String_Compare(result, L"true") == 0) ? TRUE : FALSE;
return bResult;
}
VOID Ini_ReadSubKey( WCHAR *section, WCHAR* MasterKey, WCHAR *subKey, WCHAR* DefaultString, WCHAR* Buffer, DWORD Length, WCHAR* FileName )
{
WCHAR key[260];
if (!MasterKey)
return;
String_Copy(key, L"(");
String_Concatenate(key, MasterKey);
String_Concatenate(key, L").");
String_Concatenate(key, subKey);
Ini_GetString(section, key, DefaultString, Buffer, Length, FileName);
}
| 2.03125 | 2 |
2024-11-18T22:02:48.330298+00:00 | 2017-11-07T03:33:05 | 026f386269f88bf9f34204f30d8d40b982158749 | {
"blob_id": "026f386269f88bf9f34204f30d8d40b982158749",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-07T03:33:05",
"content_id": "3a9b185a12a2430a42cbce3fc61f33ec445f6e57",
"detected_licenses": [
"Zlib"
],
"directory_id": "4b03b5b5813644d1cfce965e4b277ce903f48df2",
"extension": "h",
"filename": "ccntr_map.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 83794099,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6382,
"license": "Zlib",
"license_type": "permissive",
"path": "/include/ccntr_map.h",
"provenance": "stackv2-0139.json.gz:112168",
"repo_name": "iceignatius/ccntr",
"revision_date": "2017-11-07T03:33:05",
"revision_id": "f1190d7da1917e9f548d3ed340a48458f5fff2d2",
"snapshot_id": "32f944827742e9e27ad8d6f2495d17a63adcad3c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/iceignatius/ccntr/f1190d7da1917e9f548d3ed340a48458f5fff2d2/include/ccntr_map.h",
"visit_date": "2021-01-20T00:08:26.844739"
} | stackv2 | /**
* @file
* @brief Container: key map.
* @author 王文佑
* @date 2017/03/13
* @copyright ZLib Licence
*/
#ifndef _CCNTR_MAP_H_
#define _CCNTR_MAP_H_
#include <stddef.h>
#include <stdbool.h>
#include "ccntr_spinlock.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @class ccntr_map_node_t
* @brief Node of key map.
*/
typedef struct ccntr_map_node_t
{
struct ccntr_map_node_t *parent;
struct ccntr_map_node_t *left;
struct ccntr_map_node_t *right;
bool is_red;
/**
* Key of the node.
*
* @attention:
* The @a key member need to be set and managed by user manually,
* but do not modify it when the node is linked in a container.
*/
void *key;
} ccntr_map_node_t;
ccntr_map_node_t* ccntr_map_node_get_next(ccntr_map_node_t *self);
ccntr_map_node_t* ccntr_map_node_get_prev(ccntr_map_node_t *self);
ccntr_map_node_t* ccntr_map_node_get_next_postorder(ccntr_map_node_t *self);
static inline
const ccntr_map_node_t* ccntr_map_node_get_next_c(const ccntr_map_node_t *self)
{
/**
* @memberof ccntr_map_node_t
* @brief Get the next node (in order).
*
* @param self Object instance.
* @return The next node; or NULL if there does not have the next node.
*
* @remarks Visit nodes with in-order rule usually be suit for most usage,
* and nodes will be visited from the smaller key to the larger.
*/
return ccntr_map_node_get_next((ccntr_map_node_t*)self);
}
static inline
const ccntr_map_node_t* ccntr_map_node_get_prev_c(const ccntr_map_node_t *self)
{
/**
* @memberof ccntr_map_node_t
* @brief Get the previous node (in order).
*
* @param self Object instance.
* @return The previous node; or NULL if there does not have the previous node.
*
* @remarks Visit nodes with in-order rule usually be suit for most usage,
* and nodes will be visited from the larger key to the smaller.
*/
return ccntr_map_node_get_prev((ccntr_map_node_t*)self);
}
/**
* A function that compare two keys.
*
* @param key1 The first key.
* @param key2 The second key.
* @retval NEGATIVE The first key goes before the second key.
* @retval ZERO The first key is equivalent to the second key.
* @retval POSITIVE The first key goes after the second key.
*/
typedef int(*ccntr_map_compare_keys_t)(const void *key1, const void *key2);
/**
* @class ccntr_map_t
* @brief Key map container.
*/
typedef struct ccntr_map_t
{
ccntr_map_node_t *root;
unsigned count;
ccntr_map_compare_keys_t compare;
CCNTR_DECLARE_SPINLOCK(lock);
} ccntr_map_t;
void ccntr_map_init(ccntr_map_t *self, ccntr_map_compare_keys_t compare);
static inline
unsigned ccntr_map_get_count(const ccntr_map_t *self)
{
/**
* @memberof ccntr_map_t
* @brief Get nodes count.
*
* @param self Object instance.
* @return The nodes count.
*/
ccntr_spinlock_lock( (ccntr_spinlock_t*) &self->lock );
unsigned count = self->count;
ccntr_spinlock_unlock( (ccntr_spinlock_t*) &self->lock );
return count;
}
ccntr_map_node_t* ccntr_map_get_first(ccntr_map_t *self);
ccntr_map_node_t* ccntr_map_get_last(ccntr_map_t *self);
ccntr_map_node_t* ccntr_map_get_first_postorder(ccntr_map_t *self);
static inline
const ccntr_map_node_t* ccntr_map_get_first_c(const ccntr_map_t *self)
{
/**
* @memberof ccntr_map_t
* @brief Get the first node (in order).
*
* @param self Object instance.
* @return The first node; or NULL if no any nodes contained.
*
* @remarks Visit nodes with in-order rule usually be suit for most usage,
* and the first node will have the smallest key.
*/
return ccntr_map_get_first((ccntr_map_t*)self);
}
static inline
const ccntr_map_node_t* ccntr_map_get_last_c(const ccntr_map_t *self)
{
/**
* @memberof ccntr_map_t
* @brief Get the last node.
*
* @param self Object instance.
* @return The last node; or NULL if no any nodes contained.
*
* @remarks Visit nodes with in-order rule usually be suit for most usage,
* and the last node will have the largest key.
*/
return ccntr_map_get_last((ccntr_map_t*)self);
}
ccntr_map_node_t* ccntr_map_find(ccntr_map_t *self, const void *key);
static inline
const ccntr_map_node_t* ccntr_map_find_c(const ccntr_map_t *self, const void *key)
{
/**
* @memberof ccntr_map_t
* @brief Find node by key.
*
* @param self Object instance.
* @param key Key of the node.
* @return The node if found; and NULL if not found.
*/
return ccntr_map_find((ccntr_map_t*)self, key);
}
ccntr_map_node_t* ccntr_map_find_nearest_less(ccntr_map_t *self, const void *key);
static inline
const ccntr_map_node_t* ccntr_map_find_nearest_less_c(const ccntr_map_t *self, const void *key)
{
/**
* @memberof ccntr_map_t
* @brief Find nearest node which is less or equal than the specified key.
*
* @param self Object instance.
* @param key Key of the node.
* @return The node if found; and NULL if not found.
*/
return ccntr_map_find_nearest_less((ccntr_map_t*)self, key);
}
ccntr_map_node_t* ccntr_map_find_nearest_great(ccntr_map_t *self, const void *key);
static inline
const ccntr_map_node_t* ccntr_map_find_nearest_great_c(const ccntr_map_t *self, const void *key)
{
/**
* @memberof ccntr_map_t
* @brief Find nearest node which is greater or equal than the specified key.
*
* @param self Object instance.
* @param key Key of the node.
* @return The node if found; and NULL if not found.
*/
return ccntr_map_find_nearest_great((ccntr_map_t*)self, key);
}
ccntr_map_node_t* ccntr_map_link(ccntr_map_t *self, ccntr_map_node_t *node);
void ccntr_map_unlink(ccntr_map_t *self, ccntr_map_node_t *node);
ccntr_map_node_t* ccntr_map_unlink_by_key(ccntr_map_t *self, const void *key);
static inline
void ccntr_map_discard_all(ccntr_map_t *self)
{
/**
* @memberof ccntr_map_t
* @brief Discard all linkage of nodes in the container.
*
* @param self Object instance.
*/
ccntr_spinlock_lock(&self->lock);
self->root = NULL;
self->count = 0;
ccntr_spinlock_unlock(&self->lock);
}
#ifdef __cplusplus
} // extern "C"
#endif
#endif
| 2.59375 | 3 |
2024-11-18T22:02:48.618142+00:00 | 2022-01-19T01:26:16 | 2cbb2ef261473596149482513d83cca8ce350457 | {
"blob_id": "2cbb2ef261473596149482513d83cca8ce350457",
"branch_name": "refs/heads/master",
"committer_date": "2022-01-19T01:26:16",
"content_id": "1989322ea3ad9ec15e2fb0b3a8b01ae04bb701c3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "67305fcba68fdf469862aed2959ad1dd5b22a536",
"extension": "c",
"filename": "flexible_button.c",
"fork_events_count": 238,
"gha_created_at": "2018-12-10T07:21:46",
"gha_event_created_at": "2023-06-06T04:10:57",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 161133933,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 8463,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/examples/30_iot_board_demo/packages/FlexibleButton/flexible_button.c",
"provenance": "stackv2-0139.json.gz:112299",
"repo_name": "RT-Thread/IoT_Board",
"revision_date": "2022-01-19T01:26:16",
"revision_id": "2d218a4e06f06dbb356ec00767904f91d00db7cc",
"snapshot_id": "cdabf100a8d515fbcaa65ab0b72ec67acb0d2c9a",
"src_encoding": "UTF-8",
"star_events_count": 344,
"url": "https://raw.githubusercontent.com/RT-Thread/IoT_Board/2d218a4e06f06dbb356ec00767904f91d00db7cc/examples/30_iot_board_demo/packages/FlexibleButton/flexible_button.c",
"visit_date": "2023-09-04T16:51:34.485240"
} | stackv2 | /**
* @File: flexible_button.c
* @Author: MurphyZhao
* @Date: 2018-09-29
*
* Copyright (c) 2018-2018 MurphyZhao <[email protected]>
* https://github.com/zhaojuntao
* All rights reserved.
* License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*
* Change logs:
* Date Author Notes
* 2018-09-29 MurphyZhao First add
*
*/
#include "flexible_button.h"
#include <string.h>
#include <stdio.h>
static flex_button_t *btn_head = NULL;
#define EVENT_CB_EXECUTOR(button) if(button->cb) button->cb((flex_button_t*)button)
#define MAX_BUTTON_CNT 8
static unsigned char trg = 0;
static unsigned char cont = 0;
static uint8_t keydata = 0xFF;
static uint8_t key_rst_data = 0xFF;
static uint8_t button_cnt = 0;
/**
* @brief Register a user button
*
* @param button: button structure instance
* @return Number of keys that have been registered
*/
int8_t flex_button_register(flex_button_t *button)
{
flex_button_t *curr = btn_head;
if (!button && (button_cnt > MAX_BUTTON_CNT))
{
return -1;
}
while (curr)
{
if(curr == button)
{
return -1; //already exist.
}
curr = curr->next;
}
button->next = btn_head;
button->status = 0;
button->event = FLEX_BTN_PRESS_NONE;
button->scan_cnt = 0;
button->click_cnt = 0;
btn_head = button;
key_rst_data = key_rst_data << 1;
button_cnt ++;
return button_cnt;
}
/**
* @brief Read all key values in one scan cycle
*
* @param void
* @return none
*/
static void flex_button_read(void)
{
flex_button_t* target;
uint8_t read_data = 0;
keydata = key_rst_data;
int8_t i = 0;
for(target = btn_head, i = 0;
(target != NULL) && (target->usr_button_read != NULL);
target = target->next, i ++)
{
keydata = keydata |
(target->pressed_logic_level == 1 ?
((!(target->usr_button_read)()) << i) :
((target->usr_button_read)() << i));
}
read_data = keydata^0xff;
trg = read_data & (read_data ^ cont);
cont = read_data;
}
/**
* @brief Handle all key events in one scan cycle.
* Must be used after 'flex_button_read' API
*
* @param void
* @return none
*/
static void flex_button_process(void)
{
int8_t i = 0;
flex_button_t* target;
for (target = btn_head, i = 0; target != NULL; target = target->next, i ++)
{
if (target->status > 0)
{
target->scan_cnt ++;
}
switch (target->status)
{
case 0: /* is default */
if (trg & (1 << i)) /* is pressed */
{
target->scan_cnt = 0;
target->click_cnt = 0;
target->status = 1;
target->event = FLEX_BTN_PRESS_DOWN;
EVENT_CB_EXECUTOR(target);
}
else
{
target->event = FLEX_BTN_PRESS_NONE;
}
break;
case 1: /* is pressed */
if (!(cont & (1 << i))) /* is up */
{
target->status = 2;
}
else if ((target->scan_cnt >= target->short_press_start_tick) &&
(target->scan_cnt < target->long_press_start_tick))
{
target->status = 4;
target->event = FLEX_BTN_PRESS_SHORT_START;
EVENT_CB_EXECUTOR(target);
}
break;
case 2: /* is up */
if ((target->scan_cnt < target->click_start_tick))
{
target->click_cnt++; // 1
if (target->click_cnt == 1)
{
target->status = 3; /* double click check */
}
else
{
target->click_cnt = 0;
target->status = 0;
target->event = FLEX_BTN_PRESS_DOUBLE_CLICK;
EVENT_CB_EXECUTOR(target);
}
}
else if ((target->scan_cnt >= target->click_start_tick) &&
(target->scan_cnt < target->short_press_start_tick))
{
target->click_cnt = 0;
target->status = 0;
target->event = FLEX_BTN_PRESS_CLICK;
EVENT_CB_EXECUTOR(target);
}
else if ((target->scan_cnt >= target->short_press_start_tick) &&
(target->scan_cnt < target->long_press_start_tick))
{
target->click_cnt = 0;
target->status = 0;
target->event = FLEX_BTN_PRESS_SHORT_UP;
EVENT_CB_EXECUTOR(target);
}
else if ((target->scan_cnt >= target->long_press_start_tick) &&
(target->scan_cnt < target->long_hold_start_tick))
{
target->click_cnt = 0;
target->status = 0;
target->event = FLEX_BTN_PRESS_LONG_UP;
EVENT_CB_EXECUTOR(target);
}
else if (target->scan_cnt >= target->long_hold_start_tick)
{
/* long press hold up, not deal */
target->click_cnt = 0;
target->status = 0;
target->event = FLEX_BTN_PRESS_LONG_HOLD_UP;
EVENT_CB_EXECUTOR(target);
}
break;
case 3: /* double click check */
if (trg & (1 << i))
{
target->click_cnt++;
target->status = 2;
target->scan_cnt --;
}
else if (target->scan_cnt >= target->click_start_tick)
{
target->status = 2;
}
break;
case 4: /* is short pressed */
if (!(cont & (1 << i))) /* is up */
{
target->status = 2;
}
else if ((target->scan_cnt >= target->long_press_start_tick) &&
(target->scan_cnt < target->long_hold_start_tick))
{
target->status = 5;
target->event = FLEX_BTN_PRESS_LONG_START;
EVENT_CB_EXECUTOR(target);
}
break;
case 5: /* is long pressed */
if (!(cont & (1 << i))) /* is up */
{
target->status = 2;
}
else if (target->scan_cnt >= target->long_hold_start_tick)
{
target->status = 6;
target->event = FLEX_BTN_PRESS_LONG_HOLD;
EVENT_CB_EXECUTOR(target);
}
break;
case 6: /* is long pressed */
if (!(cont & (1 << i))) /* is up */
{
target->status = 2;
}
break;
}
}
}
/**
* flex_button_event_read
*
* @brief Get the button event of the specified button.
*
* @param button: button structure instance
* @return button event
*/
flex_button_event_t flex_button_event_read(flex_button_t* button)
{
return (flex_button_event_t)(button->event);
}
/**
* flex_button_scan
*
* @brief Start key scan.
* Need to be called cyclically within the specified period.
* Sample cycle: 5 - 20ms
*
* @param void
* @return none
*/
void flex_button_scan(void)
{
flex_button_read();
flex_button_process();
}
| 2.609375 | 3 |
2024-11-18T22:02:49.142898+00:00 | 2023-03-17T16:03:44 | f1049d794ab5f162843068693f6f542b99d24efc | {
"blob_id": "f1049d794ab5f162843068693f6f542b99d24efc",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-17T16:03:44",
"content_id": "7b1368d3a1c8d0e1185a3bafb7537c4361ee51a2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "93dc2677497a99d0a2df6b1f190af2434383367c",
"extension": "c",
"filename": "Nonlocal_TV_core.c",
"fork_events_count": 21,
"gha_created_at": "2017-03-29T15:42:18",
"gha_event_created_at": "2023-04-16T11:53:18",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 86600388,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7615,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/Core/regularisers_CPU/Nonlocal_TV_core.c",
"provenance": "stackv2-0139.json.gz:113454",
"repo_name": "vais-ral/CCPi-Regularisation-Toolkit",
"revision_date": "2023-03-17T16:03:44",
"revision_id": "fc67dc0db27807d4964af7b83f8ce4460abd9324",
"snapshot_id": "fdb3602bda96558f93daf343b9eea010e7467259",
"src_encoding": "UTF-8",
"star_events_count": 40,
"url": "https://raw.githubusercontent.com/vais-ral/CCPi-Regularisation-Toolkit/fc67dc0db27807d4964af7b83f8ce4460abd9324/src/Core/regularisers_CPU/Nonlocal_TV_core.c",
"visit_date": "2023-05-01T17:17:52.330090"
} | stackv2 | /*
* This work is part of the Core Imaging Library developed by
* Visual Analytics and Imaging System Group of the Science Technology
* Facilities Council, STFC and Diamond Light Source Ltd.
*
* Copyright 2017 Daniil Kazantsev
* Copyright 2017 Srikanth Nagella, Edoardo Pasca
* Copyright 2018 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Nonlocal_TV_core.h"
/* C-OMP implementation of non-local regulariser
* Weights and associated indices must be given as an input.
* Gauss-Seidel fixed point iteration requires ~ 3 iterations, so the main effort
* goes in pre-calculation of weights and selection of patches
*
*
* Input Parameters:
* 1. 2D/3D grayscale image/volume
* 2. AR_i - indeces of i neighbours
* 3. AR_j - indeces of j neighbours
* 4. AR_k - indeces of k neighbours (0 - for 2D case)
* 5. Weights_ij(k) - associated weights
* 6. regularisation parameter
* 7. iterations number
*
* Output:
* 1. denoised image/volume
* Elmoataz, Abderrahim, Olivier Lezoray, and Sébastien Bougleux. "Nonlocal discrete regularization on weighted graphs: a framework for image and manifold processing." IEEE Trans. Image Processing 17, no. 7 (2008): 1047-1060.
*
*/
/*****************************************************************************/
float Nonlocal_TV_CPU_main(float *A_orig, float *Output, unsigned short *H_i, unsigned short *H_j, unsigned short *H_k, float *Weights, int dimX, int dimY, int dimZ, int NumNeighb, float lambdaReg, int IterNumb, int switchM)
{
long i, j, k;
int iter;
lambdaReg = 1.0f/lambdaReg;
/*****2D INPUT *****/
if (dimZ == 0) {
copyIm(A_orig, Output, (long)(dimX), (long)(dimY), 1l);
/* for each pixel store indeces of the most similar neighbours (patches) */
for(iter=0; iter<IterNumb; iter++) {
#pragma omp parallel for shared (A_orig, Output, Weights, H_i, H_j, iter) private(i,j)
for(j=0; j<(long)(dimY); j++) {
for(i=0; i<(long)(dimX); i++) {
/*NLM_H1_2D(Output, A_orig, H_i, H_j, Weights, i, j, (long)(dimX), (long)(dimY), NumNeighb, lambdaReg);*/ /* NLM - H1 penalty */
if (switchM == 1) {
NLM_TV_2D(Output, A_orig, H_j, H_i, Weights, i, j, (long)(dimX), (long)(dimY), NumNeighb, lambdaReg); /* NLM - TV penalty */
}
else {
NLM_TV_2D(Output, A_orig, H_i, H_j, Weights, i, j, (long)(dimX), (long)(dimY), NumNeighb, lambdaReg); /* NLM - TV penalty */
}
}}
}
}
else {
/*****3D INPUT *****/
copyIm(A_orig, Output, (long)(dimX), (long)(dimY), (long)(dimZ));
/* for each pixel store indeces of the most similar neighbours (patches) */
for(iter=0; iter<IterNumb; iter++) {
#pragma omp parallel for shared (A_orig, Output, Weights, H_i, H_j, H_k, iter) private(i,j,k)
for(k=0; k<(long)(dimZ); k++) {
for(j=0; j<(long)(dimY); j++) {
for(i=0; i<(long)(dimX); i++) {
/* NLM_H1_3D(Output, A_orig, H_i, H_j, H_k, Weights, i, j, k, dimX, dimY, dimZ, NumNeighb, lambdaReg); */ /* NLM - H1 penalty */
NLM_TV_3D(Output, A_orig, H_i, H_j, H_k, Weights, i, j, k, (long)(dimX), (long)(dimY), (long)(dimZ), NumNeighb, lambdaReg); /* NLM - TV penalty */
}}}
}
}
return *Output;
}
/***********<<<<Main Function for NLM - H1 penalty>>>>**********/
float NLM_H1_2D(float *A, float *A_orig, unsigned short *H_i, unsigned short *H_j, float *Weights, long i, long j, long dimX, long dimY, int NumNeighb, float lambdaReg)
{
long x, i1, j1, index, index_m;
float value = 0.0f, normweight = 0.0f;
index_m = j*dimX+i;
for(x=0; x < NumNeighb; x++) {
index = (dimX*dimY*x) + j*dimX+i;
i1 = H_i[index];
j1 = H_j[index];
value += A[j1*dimX+i1]*Weights[index];
normweight += Weights[index];
}
A[index_m] = (lambdaReg*A_orig[index_m] + value)/(lambdaReg + normweight);
return *A;
}
/*3D version*/
float NLM_H1_3D(float *A, float *A_orig, unsigned short *H_i, unsigned short *H_j, unsigned short *H_k, float *Weights, long i, long j, long k, long dimX, long dimY, long dimZ, int NumNeighb, float lambdaReg)
{
long x, i1, j1, k1, index;
float value = 0.0f, normweight = 0.0f;
for(x=0; x < NumNeighb; x++) {
index = dimX*dimY*dimZ*x + (dimX*dimY*k) + j*dimX+i;
i1 = H_i[index];
j1 = H_j[index];
k1 = H_k[index];
value += A[(dimX*dimY*k1) + j1*dimX+i1]*Weights[index];
normweight += Weights[index];
}
A[(dimX*dimY*k) + j*dimX+i] = (lambdaReg*A_orig[(dimX*dimY*k) + j*dimX+i] + value)/(lambdaReg + normweight);
return *A;
}
/***********<<<<Main Function for NLM - TV penalty>>>>**********/
float NLM_TV_2D(float *A, float *A_orig, unsigned short *H_i, unsigned short *H_j, float *Weights, long i, long j, long dimX, long dimY, int NumNeighb, float lambdaReg)
{
long x, i1, j1, index, index_m;
float value = 0.0f, normweight = 0.0f, NLgrad_magn = 0.0f, NLCoeff;
index_m = j*dimX+i;
for(x=0; x < NumNeighb; x++) {
index = (dimX*dimY*x) + j*dimX+i; /*c*/
i1 = H_i[index];
j1 = H_j[index];
NLgrad_magn += powf((A[j1*dimX+i1] - A[index_m]),2)*Weights[index];
}
NLgrad_magn = sqrtf(NLgrad_magn); /*Non Local Gradients Magnitude */
NLCoeff = 2.0f*(1.0f/(NLgrad_magn + EPS));
for(x=0; x < NumNeighb; x++) {
index = (dimX*dimY*x) + j*dimX+i; /*c*/
i1 = H_i[index];
j1 = H_j[index];
value += A[j1*dimX+i1]*NLCoeff*Weights[index];
normweight += Weights[index]*NLCoeff;
}
A[index_m] = (lambdaReg*A_orig[index_m] + value)/(lambdaReg + normweight);
return *A;
}
/*3D version*/
float NLM_TV_3D(float *A, float *A_orig, unsigned short *H_i, unsigned short *H_j, unsigned short *H_k, float *Weights, long i, long j, long k, long dimX, long dimY, long dimZ, int NumNeighb, float lambdaReg)
{
long x, i1, j1, k1, index;
float value = 0.0f, normweight = 0.0f, NLgrad_magn = 0.0f, NLCoeff;
for(x=0; x < NumNeighb; x++) {
index = dimX*dimY*dimZ*x + (dimX*dimY*k) + j*dimX+i;
i1 = H_i[index];
j1 = H_j[index];
k1 = H_k[index];
NLgrad_magn += powf((A[(dimX*dimY*k1) + j1*dimX+i1] - A[(dimX*dimY*k1) + j*dimX+i]),2)*Weights[index];
}
NLgrad_magn = sqrtf(NLgrad_magn); /*Non Local Gradients Magnitude */
NLCoeff = 2.0f*(1.0f/(NLgrad_magn + EPS));
for(x=0; x < NumNeighb; x++) {
index = dimX*dimY*dimZ*x + (dimX*dimY*k) + j*dimX+i;
i1 = H_i[index];
j1 = H_j[index];
k1 = H_k[index];
value += A[(dimX*dimY*k1) + j1*dimX+i1]*NLCoeff*Weights[index];
normweight += Weights[index]*NLCoeff;
}
A[(dimX*dimY*k) + j*dimX+i] = (lambdaReg*A_orig[(dimX*dimY*k) + j*dimX+i] + value)/(lambdaReg + normweight);
return *A;
}
| 2.015625 | 2 |
2024-11-18T22:02:50.779538+00:00 | 2017-11-17T01:47:46 | 6626e07ac3fc169345b2e6ae5da791db9bd00997 | {
"blob_id": "6626e07ac3fc169345b2e6ae5da791db9bd00997",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-17T01:47:46",
"content_id": "ecae9633bce101587e8b3704f25b63dcdce576cd",
"detected_licenses": [
"MIT"
],
"directory_id": "3e7c6701b3ee6a12c2d0d6c82c609e73a5971a6c",
"extension": "c",
"filename": "recover_bst.c",
"fork_events_count": 1,
"gha_created_at": "2017-11-17T16:06:58",
"gha_event_created_at": "2017-11-17T16:07:35",
"gha_language": "C",
"gha_license_id": null,
"github_id": 111123396,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1429,
"license": "MIT",
"license_type": "permissive",
"path": "/099_recover_binary_search_tree/recover_bst.c",
"provenance": "stackv2-0139.json.gz:114105",
"repo_name": "apostolisly/leetcode",
"revision_date": "2017-11-17T01:47:46",
"revision_id": "b1e31afbd247f2bc09c10266c7c32156477a2437",
"snapshot_id": "98341716adddf783ce76585d42f0eeb5f6821925",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/apostolisly/leetcode/b1e31afbd247f2bc09c10266c7c32156477a2437/099_recover_binary_search_tree/recover_bst.c",
"visit_date": "2021-08-15T07:56:41.601226"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
static struct TreeNode *last = NULL;
static struct TreeNode *m1 = NULL;
static struct TreeNode *m2 = NULL;
static int wrong = 0;
static void traverse(struct TreeNode* node)
{
if (node->left != NULL) {
traverse(node->left);
}
if (last != NULL && node->val < last->val) {
if (++wrong == 2) {
int tmp = node->val;
node->val = m1->val;
m1->val = tmp;
}
m1 = last;
m2 = node;
}
last = node;
if (node->right != NULL) {
traverse(node->right);
}
}
static void recoverTree(struct TreeNode* root) {
if (root != NULL) {
last = NULL;
m1 = NULL;
m2 = NULL;
wrong = 0;
traverse(root);
if (wrong == 1) {
int tmp = m1->val;
m1->val = m2->val;
m2->val = tmp;
}
}
}
int main(int argc, char **argv)
{
struct TreeNode root;
struct TreeNode left;
struct TreeNode right;
root.val = 2;
root.left = &left;
root.right = &right;
left.val = 3;
left.left = NULL;
left.right = NULL;
right.val = 1;
right.left = NULL;
right.right = NULL;
recoverTree(&root);
printf("%d %d %d\n", root.val, left.val, right.val);
return 0;
}
| 3.421875 | 3 |
2024-11-18T22:02:50.855712+00:00 | 2023-05-26T07:03:59 | 3005c707567a2d315580941dab0dcf801f52db66 | {
"blob_id": "3005c707567a2d315580941dab0dcf801f52db66",
"branch_name": "refs/heads/hx20-hx30",
"committer_date": "2023-05-26T07:03:59",
"content_id": "9dc31ff1d441d20ad09dd43b6cd009322a782b46",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "f9e7d65cb784c01a0200145ba8d289afe41d4a56",
"extension": "h",
"filename": "led_pwm.h",
"fork_events_count": 48,
"gha_created_at": "2022-01-12T00:11:14",
"gha_event_created_at": "2023-05-26T07:04:59",
"gha_language": "C",
"gha_license_id": "BSD-3-Clause",
"github_id": 447021040,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1637,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/include/led_pwm.h",
"provenance": "stackv2-0139.json.gz:114234",
"repo_name": "FrameworkComputer/EmbeddedController",
"revision_date": "2023-05-26T07:03:59",
"revision_id": "f6d6b927eed71550d3475411cfc3e59abe5cef2a",
"snapshot_id": "ad7086769e87d0a4179eae96a7c9ff5e383ff54e",
"src_encoding": "UTF-8",
"star_events_count": 846,
"url": "https://raw.githubusercontent.com/FrameworkComputer/EmbeddedController/f6d6b927eed71550d3475411cfc3e59abe5cef2a/include/led_pwm.h",
"visit_date": "2023-08-08T20:45:10.621169"
} | stackv2 | /* Copyright 2018 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef __CROS_EC_LED_PWM_H
#define __CROS_EC_LED_PWM_H
#include "ec_commands.h"
#define PWM_LED_NO_CHANNEL -1
struct pwm_led {
enum pwm_channel ch0;
enum pwm_channel ch1;
enum pwm_channel ch2;
void (*enable)(enum pwm_channel ch, int enabled);
void (*set_duty)(enum pwm_channel ch, int percent);
};
enum pwm_led_id {
PWM_LED0 = 0,
#if CONFIG_LED_PWM_COUNT >= 2
PWM_LED1,
#endif /* CONFIG_LED_PWM_COUNT > 2 */
#if CONFIG_LED_PWM_COUNT >= 3
PWM_LED2,
#endif /* CONFIG_LED_PWM_COUNT > 3 */
};
/*
* A mapping of color to LED duty cycles per channel.
*
* This should be defined by the boards to declare what each color looks like.
* There should be an entry for every enum ec_led_colors value. For colors that
* are impossible for a given board, they should define a duty cycle of 0 for
* all applicable channels. (e.g. A bi-color LED which has a red and green
* channel should define all 0s for EC_LED_COLOR_BLUE and EC_LED_COLOR_WHITE.)
*/
extern struct pwm_led led_color_map[EC_LED_COLOR_COUNT];
/*
* A map of the PWM channels to logical PWM LEDs.
*
* A logical PWM LED would be considered as "per diffuser". There may be 1-3
* channels per diffuser and they should form a single entry in pwm_leds. If a
* channel is not used, simply define that channel as PWM_LED_NO_CHANNEL.
*/
extern struct pwm_led pwm_leds[CONFIG_LED_PWM_COUNT];
void set_pwm_led_color(enum pwm_led_id id, int color);
#endif /* defined(__CROS_EC_LED_PWM_H) */
| 2.453125 | 2 |
2024-11-18T22:02:50.934982+00:00 | 2023-08-07T08:40:16 | 78a6d70045d51a9e76391aab48f885a576263d72 | {
"blob_id": "78a6d70045d51a9e76391aab48f885a576263d72",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-07T08:40:16",
"content_id": "a849f20c1b7ceadfa823795fe4fd245ae67f1594",
"detected_licenses": [
"MIT"
],
"directory_id": "31311a8dee0ef6a1bff5e0510dea9f888d3fe0d3",
"extension": "c",
"filename": "screenrecorderrtmp.c",
"fork_events_count": 6,
"gha_created_at": "2017-08-23T08:56:18",
"gha_event_created_at": "2023-03-03T16:28:03",
"gha_language": "Java",
"gha_license_id": null,
"github_id": 101159660,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3753,
"license": "MIT",
"license_type": "permissive",
"path": "/mobile/android/app/libraries/library-livestreaming-push/src/main/cpp/rtmp/screenrecorderrtmp.c",
"provenance": "stackv2-0139.json.gz:114363",
"repo_name": "krmao/template",
"revision_date": "2023-08-07T08:40:16",
"revision_id": "3dac8cd9d329eb95a84286dcf28a0524a02e4f41",
"snapshot_id": "50d628ea22652a0a0b01383bf7cc9b19ecc1eeb3",
"src_encoding": "UTF-8",
"star_events_count": 40,
"url": "https://raw.githubusercontent.com/krmao/template/3dac8cd9d329eb95a84286dcf28a0524a02e4f41/mobile/android/app/libraries/library-livestreaming-push/src/main/cpp/rtmp/screenrecorderrtmp.c",
"visit_date": "2023-08-17T11:54:23.570440"
} | stackv2 | #include <jni.h>
#include <screenrecorderrtmp.h>
#include <malloc.h>
#include "rtmp.h"
JNIEXPORT jlong JNICALL Java_net_yrom_screenrecorder_rtmp_RtmpClient_open
(JNIEnv * env, jobject thiz, jstring url_, jboolean isPublishMode) {
const char *url = (*env)->GetStringUTFChars(env, url_, 0);
LOGD("RTMP_OPENING:%s",url);
RTMP* rtmp = RTMP_Alloc();
if (rtmp == NULL) {
LOGD("RTMP_Alloc=NULL");
return NULL;
}
RTMP_Init(rtmp);
int ret = RTMP_SetupURL(rtmp, url);
if (!ret) {
RTMP_Free(rtmp);
rtmp=NULL;
LOGD("RTMP_SetupURL=ret");
return NULL;
}
if (isPublishMode) {
RTMP_EnableWrite(rtmp);
}
ret = RTMP_Connect(rtmp, NULL);
if (!ret) {
RTMP_Free(rtmp);
rtmp=NULL;
LOGD("RTMP_Connect=ret");
return NULL;
}
ret = RTMP_ConnectStream(rtmp, 0);
if (!ret) {
ret = RTMP_ConnectStream(rtmp, 0);
RTMP_Close(rtmp);
RTMP_Free(rtmp);
rtmp=NULL;
LOGD("RTMP_ConnectStream=ret");
return NULL;
}
(*env)->ReleaseStringUTFChars(env, url_, url);
LOGD("RTMP_OPENED");
return rtmp;
}
/*
* Class: net_yrom_screenrecorder_rtmp_RtmpClient
* Method: read
* Signature: (J[BII)I
*/
JNIEXPORT jint JNICALL Java_net_yrom_screenrecorder_rtmp_RtmpClient_read
(JNIEnv * env, jobject thiz,jlong rtmp, jbyteArray data_, jint offset, jint size) {
char* data = malloc(size*sizeof(char));
int readCount = RTMP_Read((RTMP*)rtmp, data, size);
if (readCount > 0) {
(*env)->SetByteArrayRegion(env, data_, offset, readCount, data); // copy
}
free(data);
return readCount;
}
/*
* Class: net_yrom_screenrecorder_rtmp_RtmpClient
* Method: write
* Signature: (J[BIII)I
*/
JNIEXPORT jint JNICALL Java_net_yrom_screenrecorder_rtmp_RtmpClient_write
(JNIEnv * env, jobject thiz,jlong rtmp, jbyteArray data, jint size, jint type, jint ts) {
LOGD("start write");
jbyte *buffer = (*env)->GetByteArrayElements(env, data, NULL);
RTMPPacket *packet = (RTMPPacket*)malloc(sizeof(RTMPPacket));
RTMPPacket_Alloc(packet, size);
RTMPPacket_Reset(packet);
if (type == RTMP_PACKET_TYPE_INFO) { // metadata
packet->m_nChannel = 0x03;
} else if (type == RTMP_PACKET_TYPE_VIDEO) { // video
packet->m_nChannel = 0x04;
} else if (type == RTMP_PACKET_TYPE_AUDIO) { //audio
packet->m_nChannel = 0x05;
} else {
packet->m_nChannel = -1;
}
packet->m_nInfoField2 = ((RTMP*)rtmp)->m_stream_id;
LOGD("write data type: %d, ts %d", type, ts);
memcpy(packet->m_body, buffer, size);
packet->m_headerType = RTMP_PACKET_SIZE_LARGE;
packet->m_hasAbsTimestamp = FALSE;
packet->m_nTimeStamp = ts;
packet->m_packetType = type;
packet->m_nBodySize = size;
int ret = RTMP_SendPacket((RTMP*)rtmp, packet, 0);
RTMPPacket_Free(packet);
free(packet);
(*env)->ReleaseByteArrayElements(env, data, buffer, 0);
if (!ret) {
LOGD("end write error %d", sockerr);
return sockerr;
}else
{
LOGD("end write success");
return 0;
}
}
/*
* Class: net_yrom_screenrecorder_rtmp_RtmpClient
* Method: close
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_net_yrom_screenrecorder_rtmp_RtmpClient_close
(JNIEnv * env,jlong rtmp, jobject thiz) {
RTMP_Close((RTMP*)rtmp);
RTMP_Free((RTMP*)rtmp);
return 0;
}
/*
* Class: net_yrom_screenrecorder_rtmp_RtmpClient
* Method: getIpAddr
* Signature: (J)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_net_yrom_screenrecorder_rtmp_RtmpClient_getIpAddr
(JNIEnv * env,jobject thiz,jlong rtmp) {
if(rtmp!=0){
RTMP* r= (RTMP*)rtmp;
return (*env)->NewStringUTF(env, r->ipaddr);
}else {
return (*env)->NewStringUTF(env, "");
}
} | 2.171875 | 2 |
2024-11-18T22:02:51.092213+00:00 | 2018-03-25T07:59:34 | 0e09121eee54fac8e899a6ab47515df50fbf909a | {
"blob_id": "0e09121eee54fac8e899a6ab47515df50fbf909a",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-25T07:59:34",
"content_id": "fbc0e525b72093e09e2e68ed7bb6d8717c10d094",
"detected_licenses": [
"MIT"
],
"directory_id": "c1bd6b553b11ff0a5b4019217ab066c28a8b240c",
"extension": "c",
"filename": "speck.c",
"fork_events_count": 8,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 42380947,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2645,
"license": "MIT",
"license_type": "permissive",
"path": "/speck/speck.c",
"provenance": "stackv2-0139.json.gz:114493",
"repo_name": "openluopworld/block-ciphers",
"revision_date": "2018-03-25T07:59:34",
"revision_id": "30555b1d3b5e1cd58bd8acbf7e0729074fa5bd43",
"snapshot_id": "b1b110bcc7e86f3ffd10cf86e6da6c1e97dab1a6",
"src_encoding": "UTF-8",
"star_events_count": 17,
"url": "https://raw.githubusercontent.com/openluopworld/block-ciphers/30555b1d3b5e1cd58bd8acbf7e0729074fa5bd43/speck/speck.c",
"visit_date": "2021-09-10T11:08:46.028843"
} | stackv2 |
#include "speck.h"
#include "rotate.h"
/*
* round function
*/
#define roundFunction(x, y, k) \
x = ror32(x, SPECK_A); \
x += y; \
x ^= k; \
y = rol32(y, SPECK_B); \
y ^= x \
/*
* invert round function
*/
#define invertRoundFunction(x, y, k) \
y ^= x; \
y = ror32(y, SPECK_B); \
x ^= k; \
x -= y; \
x = rol32(x, SPECK_A) \
/*
* key schedule
* inputKey: the original keys
* keys: round keys
*/
void speck_64_96_key_schedule(const u8 * inputKey, u8 * keys ) {
u32 *rk = (u32*)keys;
const u32 *ik = (const u32*)inputKey;
u32 l[SPECK_ROUNDS_96 + SPECK_KEY_WORDS_96-2];
rk[0] = ik[0];
l[0] = ik[1];
l[1] = ik[2];
int i;
for ( i = 0; i < SPECK_ROUNDS_96-1; i++ ) {
l[i+SPECK_KEY_WORDS_96-1] = (rk[i] + ror32(l[i], SPECK_A)) ^ (u32)i;
rk[i+1] = rol32(rk[i], SPECK_B) ^ l[i+SPECK_KEY_WORDS_96-1];
}
}
void speck_64_128_key_schedule(const u8 * inputKey, u8 * keys ) {
u32 *rk = (u32*)keys;
const u32 *ik = (const u32*)inputKey;
u32 l[SPECK_ROUNDS_128 + SPECK_KEY_WORDS_128-2];
rk[0] = ik[0];
l[0] = ik[1];
l[1] = ik[2];
l[2] = ik[3];
int i;
for ( i = 0; i < SPECK_ROUNDS_128-1; i++ ) {
l[i+SPECK_KEY_WORDS_128-1] = (rk[i] + ror32(l[i], SPECK_A)) ^ (u32)i;
rk[i+1] = rol32(rk[i], SPECK_B) ^ l[i+SPECK_KEY_WORDS_128-1];
}
}
/*
* encrypt
* plainText: plainText has just one block.
* keys: round keys
*/
static void encrypt(u8 * plainText, const u8 * keys, int ROUNDS) {
u32 *plain = (u32*)plainText;
const u32* rk = (const u32*)keys;
int i;
for ( i = 0; i < ROUNDS; i++ ) {
roundFunction(plain[1], plain[0], rk[i]);
}
}
void speck_64_96_encrypt(u8 * plainText, const u8 * keys) {
encrypt(plainText, keys, SPECK_ROUNDS_96);
}
void speck_64_128_encrypt(u8 * plainText, const u8 * keys) {
encrypt(plainText, keys, SPECK_ROUNDS_128);
}
/*
* decrypt
* cipherText: cipherText has just one block.
* keys: round keys
*/
static void decrypt(u8 * cipherText, const u8 * keys, int ROUNDS) {
u32 *cipher = (u32*)cipherText;
const u32* rk = (const u32*)keys;
int i;
for ( i = ROUNDS-1; i >= 0; i-- ) {
invertRoundFunction(cipher[1], cipher[0], rk[i]);
//cipher[0] = ror32(cipher[1] ^ cipher[0], SPECK_B);
//cipher[1] = rol32(((cipher[1] ^ rk[i]) - cipher[0]), SPECK_A);
}
}
void speck_64_96_decrypt(u8 * cipherText, const u8 * keys) {
decrypt(cipherText, keys, SPECK_ROUNDS_96);
}
void speck_64_128_decrypt(u8 * cipherText, const u8 * keys) {
decrypt(cipherText, keys, SPECK_ROUNDS_128);
} | 2.859375 | 3 |
2024-11-18T22:02:51.384914+00:00 | 2017-12-15T14:00:03 | 050f38ec92f9abb917b43dafac252746722f9d25 | {
"blob_id": "050f38ec92f9abb917b43dafac252746722f9d25",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-15T14:00:03",
"content_id": "18c5476847fadcff69e114187c9e90166e73e8e2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b59165ebda7542b0c1a6f16d0e3e522819100813",
"extension": "c",
"filename": "fork.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 113856159,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 606,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/system_interface/other/fork.c",
"provenance": "stackv2-0139.json.gz:114623",
"repo_name": "victory1355/LinuxAPI",
"revision_date": "2017-12-15T14:00:03",
"revision_id": "bf61a57c59ff6cecfc2b128240065ba4525cfd86",
"snapshot_id": "387b28ff28431427640d8214603eaed8c7a1854f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/victory1355/LinuxAPI/bf61a57c59ff6cecfc2b128240065ba4525cfd86/system_interface/other/fork.c",
"visit_date": "2021-08-30T01:15:54.622547"
} | stackv2 | #include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pd;
int i = 10;
printf("test0 for fork\n");
pd = fork();
printf("test2 for fork\n");
if( pd == -1)
printf("fork child PID failure\n");
else if(pd == 0)
{
//printf("child PID\n");
//return 0;
printf("child pd = %d\n", pd);
printf("child process\n");
i = 30;
printf("child i = %d\n", i);
while(1);
}
else if(pd > 0)
{
sleep(1);
printf("parent pd = %d\n", pd);
printf("parent process\n");
printf("parent i = %d\n", i);
while(1);
//printf("parent PID\n");
}
printf("parent exit\n");
return 0;
}
| 2.8125 | 3 |
2024-11-18T22:02:51.659242+00:00 | 2022-06-14T13:55:09 | 74353d32c37f038e5c6abb9ba50e24fad37fc14e | {
"blob_id": "74353d32c37f038e5c6abb9ba50e24fad37fc14e",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-14T13:57:18",
"content_id": "f3d56fdb67533ffa529db8126175668aa86ce366",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "22bb6e674a53da4090c65abc44afce4825cf4915",
"extension": "c",
"filename": "backup.c",
"fork_events_count": 1,
"gha_created_at": "2019-06-07T14:15:31",
"gha_event_created_at": "2020-10-11T10:59:27",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 190755139,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7269,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/backup/backup.c",
"provenance": "stackv2-0139.json.gz:114751",
"repo_name": "benma/bitbox02-firmware",
"revision_date": "2022-06-14T13:55:09",
"revision_id": "8010cf4f5ba510bb20ab706b42aca55ac429a1b6",
"snapshot_id": "8125f9ce5f0f0d96647b4f32acf2e61abcda07d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/benma/bitbox02-firmware/8010cf4f5ba510bb20ab706b42aca55ac429a1b6/src/backup/backup.c",
"visit_date": "2023-08-03T12:25:50.547514"
} | stackv2 | // Copyright 2019 Shift Cryptosecurity AG
// Copyright 2020 Shift Crypto AG
//
// 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 "backup.h"
#include "restore.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <hardfault.h>
#include <memory/memory.h>
#include <sd.h>
#include <util.h>
#include <version.h>
#include <pb_encode.h>
#include <wally_crypto.h>
static void _cleanup_backup_bytes(uint8_t** backup_bytes)
{
util_zero(*backup_bytes, SD_MAX_FILE_SIZE);
}
size_t backup_encode(const Backup* backup, uint32_t max_size, uint8_t* output)
{
pb_ostream_t out_stream = pb_ostream_from_buffer(output, (unsigned int)max_size);
bool status_encode = pb_encode(&out_stream, Backup_fields, backup);
if (!status_encode) {
return 0;
}
return out_stream.bytes_written;
}
/**
* Get a directory name for the given seed. The directory name is the hash of the seed.
* @param[in] seed The seed to be backuped.
* @param[out] dir_name The name of the directory and must be 65 bytes (32 byte hex string + null
* terminator)..
*/
static void _get_directory_name(const uint8_t seed[32], char* dir_name)
{
uint8_t hmac_seed[HMAC_SHA256_LEN];
wally_hmac_sha256(
(const unsigned char*)"backup", strlens("backup"), seed, 32, hmac_seed, HMAC_SHA256_LEN);
util_uint8_to_hex(hmac_seed, sizeof(hmac_seed), dir_name);
}
/**
* Prepares the file name and writes it to file_name.
* @param[in] backup_create_timestamp The create timestamp from which we create the timestamp.
* @param[out] file_name The name of the file which includes a timestamp.
* @param[in] index The index of the backup.
*/
static void _get_file_name(uint32_t backup_create_timestamp, char* file_name, uint8_t index)
{
time_t local_timestamp = (time_t)backup_create_timestamp;
struct tm* local_time = localtime(&local_timestamp);
static char local_timestring[100] = {0};
strftime(local_timestring, sizeof(local_timestring), "%a_%Y-%m-%dT%H-%M-%SZ", local_time);
snprintf(file_name, 257, "backup_%s_%d.bin", local_timestring, index);
}
#define CLEANUP_BACKUP_BYTES(var) \
uint8_t* __attribute__((__cleanup__(_cleanup_backup_bytes))) var##_clean \
__attribute__((unused)) = var;
/**
* Checks whether the restore from backup was successful.
* Compares the backup restored from the given buffer with the passed backup.
* @return BACKUP_OK if the backup was good, BACKUP_ERR_CHECK if the check failed.
*/
static backup_error_t _check_backup(uint8_t* output, size_t output_length, const Backup* backup)
{
Backup __attribute__((__cleanup__(backup_cleanup_backup))) backup_check;
BackupData __attribute__((__cleanup__(backup_cleanup_backup_data))) backup_data_check;
restore_error_t res =
restore_from_buffer(output, output_length, &backup_check, &backup_data_check);
if (res != RESTORE_OK) {
return BACKUP_ERR_CHECK;
}
if (!MEMEQ(backup_check.backup_v1.content.checksum, backup->backup_v1.content.checksum, 32)) {
return BACKUP_ERR_CHECK;
}
return BACKUP_OK;
}
/**
* Creates a backup using the given timestamp.
*/
backup_error_t backup_create(uint32_t backup_create_timestamp, uint32_t seed_birthdate_timestamp)
{
Backup __attribute__((__cleanup__(backup_cleanup_backup))) backup;
BackupData __attribute__((__cleanup__(backup_cleanup_backup_data))) backup_data;
encode_data_t encode_data;
backup_error_t res = backup_fill(
DIGITAL_BITBOX_VERSION_SHORT,
backup_create_timestamp,
seed_birthdate_timestamp,
&backup,
&backup_data,
&encode_data);
if (res != BACKUP_OK) {
return res;
}
uint8_t output[SD_MAX_FILE_SIZE];
CLEANUP_BACKUP_BYTES(output);
size_t output_length = backup_encode(&backup, SD_MAX_FILE_SIZE, output);
if (output_length == 0) {
return BACKUP_ERR_ENCODE;
}
if (_check_backup(output, output_length, &backup) != BACKUP_OK) {
return BACKUP_ERR_CHECK;
}
char dir_name[65];
_get_directory_name(backup_data.seed, dir_name);
sd_list_t files __attribute__((__cleanup__(sd_free_list)));
if (!sd_list_subdir(&files, dir_name)) {
return BACKUP_ERR_SD_LIST;
}
for (int i = 0; i < 3; i++) {
char file_name[257];
_get_file_name(backup_create_timestamp, file_name, i);
if (!sd_write_bin(file_name, dir_name, (const uint8_t*)output, output_length, true)) {
return BACKUP_ERR_SD_WRITE;
}
// If the backup could not be decoded successfully, we should make sure
// that the previous backup (if any) isn't erased and that we return
// BACKUP_ERR_CHECK.
// The caller could try again.
uint8_t read_content[SD_MAX_FILE_SIZE];
CLEANUP_BACKUP_BYTES(read_content);
size_t read_length;
if (!sd_load_bin(file_name, dir_name, read_content, &read_length)) {
return BACKUP_ERR_SD_READ;
}
if (_check_backup(read_content, read_length, &backup) != BACKUP_OK) {
return BACKUP_ERR_CHECK;
}
}
bool is_stale = false;
for (size_t j = 0; j < files.num_files; j++) {
if (!sd_erase_file_in_subdir(files.files[j], dir_name)) {
is_stale = true;
}
}
if (is_stale) {
return BACKUP_STALE;
}
return BACKUP_OK;
}
backup_error_t backup_check(char* id_out, char* name_out, uint32_t* birthdate_out)
{
Backup __attribute__((__cleanup__(backup_cleanup_backup))) backup;
BackupData __attribute__((__cleanup__(backup_cleanup_backup_data))) backup_data;
encode_data_t encode_data;
backup_error_t backup_res = backup_fill("", 0, 0, &backup, &backup_data, &encode_data);
if (backup_res != BACKUP_OK) {
return backup_res;
}
char* dir_name = id_out;
_get_directory_name(backup_data.seed, dir_name);
Backup __attribute__((__cleanup__(backup_cleanup_backup))) backup_copy;
BackupData __attribute__((__cleanup__(backup_cleanup_backup_data))) backup_data_copy;
restore_error_t restore_res = restore_from_directory(dir_name, &backup_copy, &backup_data_copy);
if (restore_res != RESTORE_OK) {
return BACKUP_ERR_CHECK;
}
if (!MEMEQ(backup_data.seed, backup_data_copy.seed, 32) ||
backup_data.seed_length != backup_data_copy.seed_length) {
return BACKUP_ERR_CHECK;
}
if (name_out != NULL) {
snprintf(
name_out,
MEMORY_DEVICE_NAME_MAX_LEN,
"%s",
backup_copy.backup_v1.content.metadata.name);
}
if (birthdate_out != NULL) {
*birthdate_out = backup_data_copy.birthdate;
}
return BACKUP_OK;
}
| 2.0625 | 2 |
2024-11-18T22:02:52.657507+00:00 | 2023-08-20T18:47:17 | e9890bde4e76f853ef173ca0c5eaa314d4859934 | {
"blob_id": "e9890bde4e76f853ef173ca0c5eaa314d4859934",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-20T18:55:38",
"content_id": "7a377dc2837e9d3662cb63b9d621e0a05bd66878",
"detected_licenses": [
"MIT"
],
"directory_id": "367e9471f2b7c5598b3ddf3a8daab1e68b37290f",
"extension": "h",
"filename": "arithmetic_ansi.h",
"fork_events_count": 31,
"gha_created_at": "2017-10-03T21:47:47",
"gha_event_created_at": "2021-09-09T21:09:34",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 105706966,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3817,
"license": "MIT",
"license_type": "permissive",
"path": "/src/arithmetic_ansi.h",
"provenance": "stackv2-0139.json.gz:115270",
"repo_name": "david-cortes/cmfrec",
"revision_date": "2023-08-20T18:47:17",
"revision_id": "b29a11a32a7c80754b91bff0c1abe445293bbe40",
"snapshot_id": "ba76527dafbf7c42d5de2949fa35e4c4f04516ea",
"src_encoding": "UTF-8",
"star_events_count": 106,
"url": "https://raw.githubusercontent.com/david-cortes/cmfrec/b29a11a32a7c80754b91bff0c1abe445293bbe40/src/arithmetic_ansi.h",
"visit_date": "2023-08-31T18:07:59.697556"
} | stackv2 | /*
* ANSI C implementation of vector operations.
*
* Copyright (c) 2007-2010 Naoaki Okazaki
* All rights reserved.
*
* 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.
*/
/* $Id$ */
#include <stdlib.h>
#include <memory.h>
#include "cmfrec.h"
// #if LBFGS_FLOAT == 32 && LBFGS_IEEE_FLOAT
// #ifdef USE_FLOAT
// #define fsigndiff(x, y) (((*(uint32_t*)(x)) ^ (*(uint32_t*)(y))) & 0x80000000U)
// #else
#define fsigndiff(x, y) (*(x) * (*(y) / fabs(*(y))) < 0.)
// #endif/*LBFGS_IEEE_FLOAT*/
// #endif
// inline static void* vecalloc(size_t size)
// {
// void *memblock = malloc(size);
// if (memblock) {
// memset(memblock, 0, size);
// }
// return memblock;
// }
#define vecalloc calloc
inline static void vecfree(void *memblock)
{
free(memblock);
}
inline static void vecset(real_t *x, const real_t c, const size_t n)
{
size_t i;
for (i = 0;i < n;++i) {
x[i] = c;
}
}
inline static void veccpy(real_t *y, const real_t *x, const size_t n)
{
memcpy(y, x, n*sizeof(real_t));
}
inline static void vecncpy(real_t *restrict y, const real_t *restrict x, const size_t n)
{
size_t i;
for (i = 0;i < n;++i) {
y[i] = -x[i];
}
}
inline static void vecadd(real_t *y, const real_t *x, const real_t c, const size_t n)
{
if (n < (size_t)INT_MAX)
cblas_taxpy((int)n, c, x, 1, y, 1);
else
for (size_t ix = 0; ix < n; ix++)
y[ix] = fma_t(c, x[ix], y[ix]);
}
inline static void vecdiff(real_t *restrict z, const real_t *restrict x, const real_t *restrict y, const size_t n)
{
size_t i;
for (i = 0;i < n;++i) {
z[i] = x[i] - y[i];
}
}
inline static void vecscale(real_t *y, const real_t c, const size_t n)
{
if (n < (size_t)INT_MAX)
cblas_tscal((int)n, c, y, 1);
else
for (size_t ix = 0; ix < n; ix++)
y[ix] *= c;
}
inline static void vecmul(real_t *restrict y, const real_t *restrict x, const size_t n)
{
size_t i;
for (i = 0;i < n;++i) {
y[i] *= x[i];
}
}
inline static void vecdot(real_t* s, const real_t *x, const real_t *y, const size_t n)
{
if (n < (size_t)INT_MAX)
*s = cblas_tdot((int)n, x, 1, y, 1);
else {
ldouble_safe res = 0;
for (size_t ix = 0; ix < n; ix++)
res += x[ix]*y[ix];
*s = (real_t)res;
}
}
inline static void vec2norm(real_t* s, const real_t *x, const size_t n)
{
if (n < (size_t)INT_MAX)
*s = cblas_tnrm2((int_t)n, x, 1);
else {
ldouble_safe res = 0;
for (size_t ix = 0; ix < n; ix++)
res += square(x[ix]);
*s = (real_t)sqrtLD(res);
}
}
inline static void vec2norminv(real_t* s, const real_t *x, const size_t n)
{
vec2norm(s, x, n);
*s = (real_t)(1.0 / *s);
}
| 2.34375 | 2 |
2024-11-18T22:02:52.730387+00:00 | 2018-03-17T15:29:59 | dfc91b62680d2712dc2cd11d8110e8ad16bd706f | {
"blob_id": "dfc91b62680d2712dc2cd11d8110e8ad16bd706f",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-17T15:29:59",
"content_id": "9dd2c18374a36f7360ce8094797ecbd4896e6626",
"detected_licenses": [
"MIT"
],
"directory_id": "fd708f0829f136258939fafb98b39e44feec2a96",
"extension": "h",
"filename": "Exec.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": 921,
"license": "MIT",
"license_type": "permissive",
"path": "/Source/kernel/headers/Exec.h",
"provenance": "stackv2-0139.json.gz:115399",
"repo_name": "cat-anna/Supernova",
"revision_date": "2018-03-17T15:29:59",
"revision_id": "f8692e15e14b64cf2ee6fc1d3e1d2588eb7421b0",
"snapshot_id": "08152148431c8b6ec7472b674e07f2f6b08a84e8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cat-anna/Supernova/f8692e15e14b64cf2ee6fc1d3e1d2588eb7421b0/Source/kernel/headers/Exec.h",
"visit_date": "2023-07-06T18:16:31.572277"
} | stackv2 | #ifndef _EXEC_H_
#define _EXEC_H_
enum{
EXEC_TYPE_MASK = 0xFF,
EXEC_TYPE_ELF32 = 1,
EXEC_TYPE_BUILTIN = 10,
EXEC_FLAG_DYNAMIC_SECTION = (1 << 15),
EXEC_FLAG_DYNAMIC_SYMBOLS = (1 << 16),
};
typedef struct ExecImage_s{
uint32 ExecType; //type of executable image
uint32 ImageSize;
void* BaseAddress; //and image header
sint32 LoadOffset;
uint32 Entry;
void *DynamicData; //pointer to dynamic section
void *DynSymTable;
char *DynStrTable;
uint32 DynSymCount;
uint32 cr3;
}ExecImage_t, *ExecImage_p;
//elf.c
uint32 Elf32_LoadImage(void *ELF_header, uint32 Addr, uint32 DestMemFlags, ExecImage_p Image);
uint32 Elf32_ProcessDynamicSection(process_p proc);
void ElfDumpSymbolTable(const void *SymTab, const char *StrTab, uint32 SymTabCount);
#ifdef _HEADER_ELF_H_
uint32 ELF32_GetSymbol(ExecImage_p Image, const char *SymName, Elf32_Sym **Symbol);
#endif
#endif
| 2.1875 | 2 |
2024-11-18T22:02:52.877178+00:00 | 2019-07-18T08:33:31 | aa3a1c2e348acc6f8a076274bf7e80ca3d47bd50 | {
"blob_id": "aa3a1c2e348acc6f8a076274bf7e80ca3d47bd50",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-18T08:33:31",
"content_id": "597d044d9ab7704e0501832e0e91c685b611ae39",
"detected_licenses": [
"MIT"
],
"directory_id": "c9cd3684b853f3e4bf8ee7de1464bd8b6a07921c",
"extension": "c",
"filename": "RRsanity.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": 890,
"license": "MIT",
"license_type": "permissive",
"path": "/os_xv6_master/RRsanity.c",
"provenance": "stackv2-0139.json.gz:115658",
"repo_name": "AmirSalari/Operating-System",
"revision_date": "2019-07-18T08:33:31",
"revision_id": "fdaef2f4a58f4c68b779e8beb3173edffd9180f9",
"snapshot_id": "ca42925968edfe14aa9d90ebd61328a97f05cda4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AmirSalari/Operating-System/fdaef2f4a58f4c68b779e8beb3173edffd9180f9/os_xv6_master/RRsanity.c",
"visit_date": "2020-05-05T12:48:21.058830"
} | stackv2 | #include "user.h"
#define CHILD_NUMBER 10
#define N 1000
void
printing(int number)
{
int i;
for (i = 0; i < N; ++i) {
printf(1, "Child %d prints for the %d time.\n", number, i);
}
}
void
RRsanity(void)
{
int wTime[CHILD_NUMBER];
int rTime[CHILD_NUMBER];
int pid[CHILD_NUMBER];
int i;
for (i = 0; i < CHILD_NUMBER; i++) {
pid[i] = fork();
if(pid[i] == 0){
printing(i);
exit();
}
}
int j;
for (j = 0; j < CHILD_NUMBER; ++j) {
wait2(&wTime[j], &rTime[j]);
}
int k;
for (k = 0; k < CHILD_NUMBER; ++k) {
printf(1, "Wtime of %d child is %d\n", k, wTime[k]);
printf(1, "Rtime of %d child is %d\n", k, rTime[k]);
printf(1, "turn around time of %d child is %d\n", k, (wTime[k] + rTime[k]));
}
}
int
main(void)
{
RRsanity();
exit();
}
| 2.703125 | 3 |
2024-11-18T22:02:52.955703+00:00 | 2023-07-05T02:39:45 | f88a3411ed47462b9b54d56f21c573b623314d77 | {
"blob_id": "f88a3411ed47462b9b54d56f21c573b623314d77",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-05T02:39:45",
"content_id": "a6aa57ba2d5a5c005717a4d7ac7f24f3b3f49847",
"detected_licenses": [
"MIT"
],
"directory_id": "282a0d0b6aeb86964772e44042b2fac1614d28c2",
"extension": "c",
"filename": "base32.c",
"fork_events_count": 124,
"gha_created_at": "2020-06-01T09:18:20",
"gha_event_created_at": "2023-07-05T02:39:46",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 268476647,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6311,
"license": "MIT",
"license_type": "permissive",
"path": "/encode/base32.c",
"provenance": "stackv2-0139.json.gz:115786",
"repo_name": "ph4ntonn/Impost3r",
"revision_date": "2023-07-05T02:39:45",
"revision_id": "8694a51997ab5bd8b1cfc1c27f4850baa2b4f9c6",
"snapshot_id": "c144941c2acc41b0da97005ae852abde4252c9fe",
"src_encoding": "UTF-8",
"star_events_count": 558,
"url": "https://raw.githubusercontent.com/ph4ntonn/Impost3r/8694a51997ab5bd8b1cfc1c27f4850baa2b4f9c6/encode/base32.c",
"visit_date": "2023-07-05T11:28:45.043283"
} | stackv2 | #include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "./common.h"
static int is_valid_b32_input(const char *user_data, size_t data_len);
static int get_char_index(unsigned char c);
static const unsigned char b32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
char *
base32_encode(const unsigned char *user_data, size_t data_len, baseencode_error_t *err)
{
baseencode_error_t error;
check_input(user_data, data_len, MAX_ENCODE_INPUT_LEN, &error);
if (error != SUCCESS) {
*err = error;
if (error == EMPTY_STRING) {
return strdup("");
} else {
return NULL;
}
}
size_t user_data_chars = 0, total_bits = 0;
int num_of_equals = 0;
int i;
for (i = 0; i < data_len; i++) {
// As it's not known whether data_len is with or without the +1 for the null byte, a manual check is required.
if (user_data[i] != '\0') {
total_bits += 8;
user_data_chars += 1;
} else {
break;
}
}
switch (total_bits % 40) {
case 8:
num_of_equals = 6;
break;
case 16:
num_of_equals = 4;
break;
case 24:
num_of_equals = 3;
break;
case 32:
num_of_equals = 1;
break;
default:
break;
}
size_t output_length = (user_data_chars * 8 + 4) / 5;
char *encoded_data = calloc(output_length + num_of_equals + 1, 1);
if (encoded_data == NULL) {
*err = MEMORY_ALLOCATION;
return NULL;
}
uint64_t first_octet, second_octet, third_octet, fourth_octet, fifth_octet;
uint64_t quintuple;
int j;
for (i = 0, j = 0; i < user_data_chars;) {
first_octet = i < user_data_chars ? user_data[i++] : 0;
second_octet = i < user_data_chars ? user_data[i++] : 0;
third_octet = i < user_data_chars ? user_data[i++] : 0;
fourth_octet = i < user_data_chars ? user_data[i++] : 0;
fifth_octet = i < user_data_chars ? user_data[i++] : 0;
quintuple =
((first_octet >> 3) << 35) +
((((first_octet & 0x7) << 2) | (second_octet >> 6)) << 30) +
(((second_octet & 0x3F) >> 1) << 25) +
((((second_octet & 0x01) << 4) | (third_octet >> 4)) << 20) +
((((third_octet & 0xF) << 1) | (fourth_octet >> 7)) << 15) +
(((fourth_octet & 0x7F) >> 2) << 10) +
((((fourth_octet & 0x3) << 3) | (fifth_octet >> 5)) << 5) +
(fifth_octet & 0x1F);
encoded_data[j++] = b32_alphabet[(quintuple >> 35) & 0x1F];
encoded_data[j++] = b32_alphabet[(quintuple >> 30) & 0x1F];
encoded_data[j++] = b32_alphabet[(quintuple >> 25) & 0x1F];
encoded_data[j++] = b32_alphabet[(quintuple >> 20) & 0x1F];
encoded_data[j++] = b32_alphabet[(quintuple >> 15) & 0x1F];
encoded_data[j++] = b32_alphabet[(quintuple >> 10) & 0x1F];
encoded_data[j++] = b32_alphabet[(quintuple >> 5) & 0x1F];
encoded_data[j++] = b32_alphabet[(quintuple >> 0) & 0x1F];
}
for (i = 0; i < num_of_equals; i++) {
encoded_data[output_length + i] = '=';
}
encoded_data[output_length + num_of_equals] = '\0';
*err = SUCCESS;
return encoded_data;
}
unsigned char *
base32_decode(const char *user_data_untrimmed, size_t data_len, baseencode_error_t *err)
{
baseencode_error_t error;
check_input((unsigned char *)user_data_untrimmed, data_len, MAX_DECODE_BASE32_INPUT_LEN, &error);
if (error != SUCCESS) {
*err = error;
if (error == EMPTY_STRING) {
return (unsigned char *) strdup("");
} else {
return NULL;
}
}
char *user_data = strdup(user_data_untrimmed);
data_len -= strip_char(user_data, ' ');
if (!is_valid_b32_input(user_data, data_len)) {
*err = INVALID_B32_DATA;
free(user_data);
return NULL;
}
size_t user_data_chars = 0;
int i;
for (i = 0; i < data_len; i++) {
// As it's not known whether data_len is with or without the +1 for the null byte, a manual check is required.
if (user_data[i] != '=' && user_data[i] != '\0') {
user_data_chars += 1;
}
}
size_t output_length = (size_t) ((user_data_chars + 1.6 - 1) / 1.6); // round up
unsigned char *decoded_data = calloc(output_length + 1, 1);
if (decoded_data == NULL) {
*err = MEMORY_ALLOCATION;
free(user_data);
return NULL;
}
uint8_t mask = 0, current_byte = 0;
int bits_left = 8;
int j;
for (i = 0, j = 0; i < user_data_chars; i++) {
int char_index = get_char_index((unsigned char)user_data[i]);
if (bits_left > BITS_PER_B32_BLOCK) {
mask = (uint8_t) char_index << (bits_left - BITS_PER_B32_BLOCK);
current_byte = (uint8_t) (current_byte | mask);
bits_left -= BITS_PER_B32_BLOCK;
} else {
mask = (uint8_t) char_index >> (BITS_PER_B32_BLOCK - bits_left);
current_byte = (uint8_t) (current_byte | mask);
decoded_data[j++] = current_byte;
current_byte = (uint8_t) (char_index << (BITS_PER_BYTE - BITS_PER_B32_BLOCK + bits_left));
bits_left += BITS_PER_BYTE - BITS_PER_B32_BLOCK;
}
}
decoded_data[output_length] = '\0';
free(user_data);
*err = SUCCESS;
return decoded_data;
}
static int
is_valid_b32_input(const char *user_data, size_t data_len)
{
int i;
int j;
size_t found = 0, b32_alphabet_len = sizeof(b32_alphabet);
for (i = 0; i < data_len; i++) {
if (user_data[i] == '\0') {
found++;
break;
}
for(j = 0; j < b32_alphabet_len; j++) {
if(user_data[i] == b32_alphabet[j] || user_data[i] == '=') {
found++;
break;
}
}
}
if (found != data_len) {
return 0;
} else {
return 1;
}
}
static int
get_char_index(unsigned char c)
{
int i;
for (i = 0; i < sizeof(b32_alphabet); i++) {
if (b32_alphabet[i] == c) {
return i;
}
}
return -1;
} | 2.578125 | 3 |
2024-11-18T22:25:34.073541+00:00 | 2018-02-28T15:15:32 | 7e733bdb3b728263ce1dddc8adcf84380c9a250d | {
"blob_id": "7e733bdb3b728263ce1dddc8adcf84380c9a250d",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-28T15:15:32",
"content_id": "4d24c6473c1392f39a8f18a72a63c0bb52ce0d6b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "66321c94c561d60ceba6582e9e8c65a7352115d7",
"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": 122994170,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 300,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Iniciante/1005/main.c",
"provenance": "stackv2-0140.json.gz:155321",
"repo_name": "RodrigoFernandoSilva/C-UriOnlineJudge",
"revision_date": "2018-02-28T15:15:32",
"revision_id": "e3e355927d25da4ed625511df4c5aa9f4df46776",
"snapshot_id": "e7d46b929e31be3df327dd51f70c12f4f3776f37",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RodrigoFernandoSilva/C-UriOnlineJudge/e3e355927d25da4ed625511df4c5aa9f4df46776/Iniciante/1005/main.c",
"visit_date": "2021-01-24T08:47:19.695457"
} | stackv2 | #include <stdio.h>
#define peso1 3.5
#define peso2 7.5
int main() {
double nota1;
double nota2;
double media;
scanf("%lf", ¬a1);
scanf("%lf", ¬a2);
nota1 *= peso1;
nota2 *= peso2;
media = nota1 + nota2;
media /= (peso1 + peso2);
printf("MEDIA = %.5lf\n", media);
return 0;
} | 2.875 | 3 |
2024-11-18T22:25:34.563233+00:00 | 2023-04-06T05:08:12 | 9f52b62511da4005181ca9a15e3d52760e991fd4 | {
"blob_id": "9f52b62511da4005181ca9a15e3d52760e991fd4",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-06T05:08:12",
"content_id": "d65b438e1065da7eeaf62f5b0ec3b73caf5e3c49",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "6a86ce9191e89ecf9095b0cce34f16a86785f065",
"extension": "c",
"filename": "pmem_multithreads_onekind.c",
"fork_events_count": 129,
"gha_created_at": "2014-11-14T16:30:03",
"gha_event_created_at": "2023-06-14T10:53:15",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 26647213,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4159,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/examples/pmem_multithreads_onekind.c",
"provenance": "stackv2-0140.json.gz:155451",
"repo_name": "memkind/memkind",
"revision_date": "2023-04-06T05:08:12",
"revision_id": "c425635feb0367c43da8fa0deadb50a4bc127988",
"snapshot_id": "cb37b6f6ed7323f48710365128ea9f5c3c9b7d2d",
"src_encoding": "UTF-8",
"star_events_count": 370,
"url": "https://raw.githubusercontent.com/memkind/memkind/c425635feb0367c43da8fa0deadb50a4bc127988/examples/pmem_multithreads_onekind.c",
"visit_date": "2023-08-30T21:25:32.117774"
} | stackv2 | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright (C) 2018 - 2021 Intel Corporation. */
#include <memkind.h>
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 10
#define NUM_ALLOCS 100
static char path[PATH_MAX] = "/tmp/";
static void print_err_message(int err)
{
char error_message[MEMKIND_ERROR_MESSAGE_SIZE];
memkind_error_message(err, error_message, MEMKIND_ERROR_MESSAGE_SIZE);
fprintf(stderr, "%s\n", error_message);
}
struct arg_struct {
int id;
struct memkind *kind;
int **ptr;
};
void *thread_onekind(void *arg);
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int main(int argc, char *argv[])
{
struct memkind *pmem_kind_unlimited = NULL;
int err = 0;
if (argc > 2) {
fprintf(stderr, "Usage: %s [pmem_kind_dir_path]\n", argv[0]);
return 1;
} else if (argc == 2 && (realpath(argv[1], path) == NULL)) {
fprintf(stderr, "Incorrect pmem_kind_dir_path %s\n", argv[1]);
return 1;
}
fprintf(
stdout,
"This example shows how to use multithreading with one main pmem kind."
"\nPMEM kind directory: %s\n",
path);
int status = memkind_check_dax_path(path);
if (!status) {
fprintf(stdout, "PMEM kind %s is on DAX-enabled file system.\n", path);
} else {
fprintf(stdout, "PMEM kind %s is not on DAX-enabled file system.\n",
path);
}
// Create PMEM partition with unlimited size
err = memkind_create_pmem(path, 0, &pmem_kind_unlimited);
if (err) {
print_err_message(err);
return 1;
}
// Create a few threads which will access to our main pmem_kind
pthread_t pmem_threads[NUM_THREADS];
int *pmem_tint[NUM_THREADS][NUM_ALLOCS];
int t = 0, i = 0;
struct arg_struct *args[NUM_THREADS];
for (t = 0; t < NUM_THREADS; t++) {
args[t] = malloc(sizeof(struct arg_struct));
args[t]->id = t;
args[t]->ptr = &pmem_tint[t][0];
args[t]->kind = pmem_kind_unlimited;
if (pthread_create(&pmem_threads[t], NULL, thread_onekind,
(void *)args[t]) != 0) {
fprintf(stderr, "Unable to create a thread.\n");
return 1;
}
}
sleep(1);
if (pthread_cond_broadcast(&cond) != 0) {
fprintf(stderr, "Unable to broadcast a condition.\n");
return 1;
}
for (t = 0; t < NUM_THREADS; t++) {
if (pthread_join(pmem_threads[t], NULL) != 0) {
fprintf(stderr, "Thread join failed.\n");
return 1;
}
}
// Check if we can read the values outside of threads and free resources
for (t = 0; t < NUM_THREADS; t++) {
for (i = 0; i < NUM_ALLOCS; i++) {
if (*pmem_tint[t][i] != t) {
fprintf(
stderr,
"pmem_tint value has not been saved correctly in the thread.\n");
return 1;
}
memkind_free(args[t]->kind, *(args[t]->ptr + i));
}
free(args[t]);
}
fprintf(stdout,
"Threads successfully allocated memory in the PMEM kind.\n");
return 0;
}
void *thread_onekind(void *arg)
{
struct arg_struct *args = (struct arg_struct *)arg;
int i;
if (pthread_mutex_lock(&mutex) != 0) {
fprintf(stderr, "Failed to acquire mutex.\n");
return NULL;
}
if (pthread_cond_wait(&cond, &mutex) != 0) {
fprintf(stderr, "Failed to block mutex on condition.\n");
return NULL;
}
if (pthread_mutex_unlock(&mutex) != 0) {
fprintf(stderr, "Failed to release mutex.\n");
return NULL;
}
// Lets alloc int and put there thread ID
for (i = 0; i < NUM_ALLOCS; i++) {
*(args->ptr + i) = (int *)memkind_malloc(args->kind, sizeof(int));
if (*(args->ptr + i) == NULL) {
fprintf(stderr, "Unable to allocate pmem int.\n");
return NULL;
}
**(args->ptr + i) = args->id;
}
return NULL;
}
| 3.0625 | 3 |
2024-11-18T22:25:34.663208+00:00 | 2022-12-22T00:52:35 | 8cc3b0f46ce1864330cfb3844ebd89f32451181f | {
"blob_id": "8cc3b0f46ce1864330cfb3844ebd89f32451181f",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-22T00:52:35",
"content_id": "b7e41030cd3832e73ce91080a697b2affee199d6",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9e27698a1b2442d9480046573e1df54467b855b7",
"extension": "c",
"filename": "error.c",
"fork_events_count": 0,
"gha_created_at": "2020-02-25T20:25:50",
"gha_event_created_at": "2022-12-22T00:52:36",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 243095244,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 299,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/client/error.c",
"provenance": "stackv2-0140.json.gz:155583",
"repo_name": "RNO-G/control-uC",
"revision_date": "2022-12-22T00:52:35",
"revision_id": "352040e116d034586e8e8c1848d80a4b9bafe6ea",
"snapshot_id": "09f23dab6665fb00a3be044bef800cb64fb27956",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/RNO-G/control-uC/352040e116d034586e8e8c1848d80a4b9bafe6ea/client/error.c",
"visit_date": "2023-08-17T05:55:19.825511"
} | stackv2 | #include "error.h"
void errno_check(int func_return, char * func_name) {
if (func_return == -1) {
char msg[BUF_SIZE];
memset(msg, 0, BUF_SIZE);
strerror_r(errno, msg, BUF_SIZE);
fprintf(stderr, "%s : %s\n", func_name, msg);
exit(EXIT_FAILURE);
}
}
| 2.125 | 2 |
2024-11-18T22:25:34.936729+00:00 | 2021-01-24T15:48:30 | 83e01acc2116491f98041c5bd9dda3b0b49a2be3 | {
"blob_id": "83e01acc2116491f98041c5bd9dda3b0b49a2be3",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-24T15:48:30",
"content_id": "1f9b00202b563fdc83932c7cd012bebbeec6512b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "bba97ee4f94a225f213b8a6f042bf084bdee831d",
"extension": "c",
"filename": "sample.c",
"fork_events_count": 0,
"gha_created_at": "2020-06-14T10:45:41",
"gha_event_created_at": "2021-01-24T15:47:55",
"gha_language": "C",
"gha_license_id": null,
"github_id": 272181914,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2470,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/simon_game/sample.c",
"provenance": "stackv2-0140.json.gz:156109",
"repo_name": "gabrielganzer/ARM-LPC1768",
"revision_date": "2021-01-24T15:48:30",
"revision_id": "2704fd8590de6fea22d0751d429f607a03afd2af",
"snapshot_id": "a7372c7b2943cd201841a4d5285c14f636b80a40",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gabrielganzer/ARM-LPC1768/2704fd8590de6fea22d0751d429f607a03afd2af/simon_game/sample.c",
"visit_date": "2023-02-19T14:42:30.652336"
} | stackv2 | /*----------------------------------------------------------------------------
* Name: sample.c
*
* This software is supplied "AS IS" without warranties of any kind.
*
* Copyright (c) 2019 Politecnico di Torino. All rights reserved.
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include "LPC17xx.h" /* LPC17xx definitions */
#include "led/led.h"
#include "button/button.h"
#include "timer/timer.h"
enum {s0 = 0, s1 = 1, s2 = 2, s3 = 3, s4 = 4, s5 = 5, s6 = 6};
unsigned int state = s0, i, j, n, seq[256];
extern unsigned int flagT0, pressed, button, led, cnt;
/*----------------------------------------------------------------------------
Main Program
*----------------------------------------------------------------------------*/
int main (void)
{
LED_init(); /* LED Initialization */
BUTTON_init(); /* BUTTON Initialization */
init_timer(0,0x023C3460); /* TIMER0 Initialization */
init_timer(1,0x00BEBC20); /* TIMER1 Initialization */
while(1){
switch(state){
case s1:
enable_timer(0);
if(flagT0){
if (i == (n-1)){
led = LPC_TIM1->TC%3;
LED_On(led);
seq[i++] = led;
}
else {
LED_On(seq[i++]);
}
flagT0 = 0;
state = s2;
}
break;
case s2:
enable_timer(0);
if(flagT0){
all_LED_off();
flagT0 = 0;
if(cnt<n*2)
state = s1;
else {
cnt = 0;
state = s3;
}
}
break;
case s3:
if(pressed)
{
pressed = 0;
if(button == seq[j]){
j++;
state = s5;
}
else
state = s4;
}
break;
case s4:
LPC_GPIO2->FIOPIN = ++j;
if (pressed){
pressed = 0;
state = s0;
}
else
state = s4;
break;
case s5:
if(j<n)
state = s3;
else
state = s6;
break;
case s6:
LPC_GPIO2->FIOPIN = n;
i = 0;
j = 0;
if (pressed) {
n++;
pressed = 0;
all_LED_off();
state = s1;
}
else
state = s6;
break;
case s0:
default:
i = 0;
j = 0;
n = 1;
all_LED_off();
enable_timer(1);
state = s1;
break;
}
}
}
| 2.4375 | 2 |
2024-11-18T22:25:35.417295+00:00 | 2014-06-02T02:58:12 | 7b3278491d259f3bc72558ca2c029a3006c29b78 | {
"blob_id": "7b3278491d259f3bc72558ca2c029a3006c29b78",
"branch_name": "refs/heads/master",
"committer_date": "2014-06-02T02:58:12",
"content_id": "c3739a5c84bbea0e77ff6ff52b38185066837615",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "c55586eaac2187a7e8e96d8890214696b820b5f8",
"extension": "h",
"filename": "token.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": 990,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/token.h",
"provenance": "stackv2-0140.json.gz:156497",
"repo_name": "mtimkovich/calc",
"revision_date": "2014-06-02T02:58:12",
"revision_id": "1a51d9cfc64251fb57ab33fd38f672529c53639f",
"snapshot_id": "b0b059e5b6d53a81ad8215fbd3812771fa037d0b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mtimkovich/calc/1a51d9cfc64251fb57ab33fd38f672529c53639f/src/token.h",
"visit_date": "2020-09-22T15:44:44.478034"
} | stackv2 | enum tokentype
{
OPERATOR,
NUMBER
};
// The order here is important.
// It is ordered by precedence, and matches the order
// in the operators string in token.c
enum optype
{
PLUSOP,
MINUSOP,
TIMESOP,
DIVIDEOP,
MODOP,
POWEROP,
LPAREN,
RPAREN
};
enum datatype
{
INTEGER,
REAL
};
struct tokn
{
enum tokentype tokentype;
enum datatype datatype;
struct tokn* operands;
struct tokn* link;
char name;
union {
enum optype which;
int intnum;
int realnum;
} val;
};
typedef struct tokn *Token;
#define whichval val.which
#define intval val.intnum
#define realval val.realnum
#define ASCII 256
int optable[ASCII];
Token talloc();
void printtoken(Token);
void initsymbols();
Token cons(Token, Token);
int length(Token);
Token nreverse(Token);
void pplist(Token tree);
void printelem(Token tok);
Token op(Token tok);
Token lhs(Token tok);
Token rhs(Token tok);
void free_tree(Token tree);
| 2.21875 | 2 |
2024-11-18T22:25:35.583531+00:00 | 2013-10-04T07:10:33 | 36e7eb16afc70728ba40568e6953fe1303857766 | {
"blob_id": "36e7eb16afc70728ba40568e6953fe1303857766",
"branch_name": "refs/heads/master",
"committer_date": "2013-10-04T07:10:33",
"content_id": "54de9e0b68502e528dd0366b16d00d33e7ab90fb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a6563408adcf0e838320f546d08f8172e1bae79a",
"extension": "c",
"filename": "properties.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 13317618,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1657,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/colorspacing/properties.c",
"provenance": "stackv2-0140.json.gz:156627",
"repo_name": "DavidVorick/mkvsynth",
"revision_date": "2013-10-04T07:10:33",
"revision_id": "319a81b02a8f06e366bb3c26f65cf793c6efabe6",
"snapshot_id": "53afe0df66a90a04dacf099abd5ba97d2d7f3826",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/DavidVorick/mkvsynth/319a81b02a8f06e366bb3c26f65cf793c6efabe6/colorspacing/properties.c",
"visit_date": "2020-12-25T09:47:53.563644"
} | stackv2 | #include "properties.h"
// Returns the bit depth
int getDepth(MkvsynthMetaData *metaData) {
switch(metaData->colorspace) {
case MKVS_RGB48:
return 16;
case MKVS_RGB24:
return 8;
case MKVS_YUV444_48:
return 16;
case MKVS_YUV444_24:
return 8;
}
return -1;
}
// Returns the number of bytes in the frame
int getBytes(MkvsynthMetaData *metaData) {
switch(metaData->colorspace) {
case MKVS_RGB48:
return metaData->width * metaData->height * 6;
case MKVS_RGB24:
return metaData->width * metaData->height * 3;
case MKVS_YUV444_48:
return metaData->width * metaData->height * 6;
case MKVS_YUV444_24:
return metaData->width * metaData->height * 3;
}
return -1;
}
// Returns the number of bytes in 1 line of a frame
int getLinesize(MkvsynthMetaData *metaData) {
switch(metaData->colorspace) {
case MKVS_RGB48:
return metaData->width * 6;
case MKVS_RGB24:
return metaData->width * 3;
case MKVS_YUV444_48:
return metaData->width * 6;
case MKVS_YUV444_24:
return metaData->width * 3;
}
return -1;
}
// Some colorspaces have limitations like resolution that is divisible by 2
// At the moment, mkvsynth does not support any colorspaces with limitations
int isMetaDataValid(MkvsynthMetaData *metaData) {
if(metaData->colorspace >= 1 && metaData->colorspace <= 4) {
switch(metaData->colorspace) {
case MKVS_RGB48:
return 1;
case MKVS_RGB24:
return 1;
case MKVS_YUV444_48:
return 1;
case MKVS_YUV444_24:
return 1;
}
} else {
printf("Meta data checker: colorspace is not recognized\n");
printf("Color space value: %i\n", metaData->colorspace);
}
return -1;
}
| 2.59375 | 3 |
2024-11-18T22:25:35.759802+00:00 | 2022-11-03T16:59:32 | b9cac65973838afc63c237bb3fd56b9be228cc17 | {
"blob_id": "b9cac65973838afc63c237bb3fd56b9be228cc17",
"branch_name": "refs/heads/main",
"committer_date": "2022-11-03T16:59:32",
"content_id": "b4bcbf6211c4b28de4a17698dedbf4bf8ab7d1d8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ec67aaabcd3cb04c5e6bc547331ecbc718557c93",
"extension": "c",
"filename": "pklMacroExpansion.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 86256929,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2470,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/historical-stuff/historical-stuff-0.2/pkl/pklMacroExpansion.c",
"provenance": "stackv2-0140.json.gz:156888",
"repo_name": "danfuzz/archive",
"revision_date": "2022-11-03T16:59:32",
"revision_id": "c2d9c9fa1b5b68b8d907056dada3e22359c32196",
"snapshot_id": "a0dba5e9a2ea6342b24c9ca730e943935b9dd418",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/danfuzz/archive/c2d9c9fa1b5b68b8d907056dada3e22359c32196/historical-stuff/historical-stuff-0.2/pkl/pklMacroExpansion.c",
"visit_date": "2022-11-05T04:16:44.921404"
} | stackv2 | #include "pkl.h"
#include "pklParse.h"
#include "pklMacroExpansion.h"
PklRef macroExpansion (PklRef source)
{
if (! valIsList (source))
{
/* not a tree--no processing */
return (source);
}
else
{
PklRef potential = valCar (source);
if (valIsSymbol (potential))
{
PklRef macro = globalGetIfMacro (potential);
if (macro != NULL)
{
PklRef args[10];
PklCount count;
PklCount sz = valGetSize (source);
PRECONDITION (sz <= 11,
"Too many arguments for macro expander");
fprintf (stderr, "expand: ");
valPrintlnAsTree (stderr, source);
for (count = 1; count < sz; count++)
{
args[count-1] = valGetNth (source, count);
}
source = valCall (macro, count - 1, args);
fprintf (stderr, " into: ");
valPrintlnAsTree (stderr, source);
return (macroExpansion (source));
}
else
{
/* variable but not macro, skip the expansion of arg #1 */
PklRef result = valMakeList (valCar (source), NULL);
source = valCdr (source);
while (valIsList (source))
{
valAppendList (result, macroExpansion (valCar (source)));
source = valCdr (source);
}
PRECONDITION (source == constNil,
"Source list didn't end with nil");
return (result);
}
}
else
{
PklRef result = constNil;
PklBool first = 1;
PklBool firstIsDiff;
while (valIsList (source))
{
result = valAppendList (result,
macroExpansion (valCar (source)));
if (first)
{
firstIsDiff = !valEqual (valCar (source), valCar (result));
first = 0;
}
source = valCdr (source);
}
if (firstIsDiff)
{
result = macroExpansion (result);
}
return (result);
}
}
}
| 2.359375 | 2 |
2024-11-18T22:25:36.215270+00:00 | 2015-08-20T22:21:19 | b49552971ab4625d5747df8caaf358afe67b2404 | {
"blob_id": "b49552971ab4625d5747df8caaf358afe67b2404",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-20T22:21:19",
"content_id": "69236976f9db3b3647b9e0252d3030164ba40a64",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "76819d7ec89b0d59cc54c0e554ed176f6668ffa2",
"extension": "h",
"filename": "sd_iter.h",
"fork_events_count": 0,
"gha_created_at": "2015-02-02T15:34:03",
"gha_event_created_at": "2015-02-02T15:34:06",
"gha_language": "C",
"gha_license_id": null,
"github_id": 30193672,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3961,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/sophia/database/sd_iter.h",
"provenance": "stackv2-0140.json.gz:157147",
"repo_name": "clibs/sophia",
"revision_date": "2015-08-20T22:21:19",
"revision_id": "2b66cc065e96d8a7971056e87b617395b2961ca6",
"snapshot_id": "8099ecff20e791c2b03d5c7cae9c39fee9d89cc9",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/clibs/sophia/2b66cc065e96d8a7971056e87b617395b2961ca6/sophia/database/sd_iter.h",
"visit_date": "2021-01-16T22:43:19.753961"
} | stackv2 | #ifndef SD_ITER_H_
#define SD_ITER_H_
/*
* sophia database
* sphia.org
*
* Copyright (c) Dmitry Simonenko
* BSD License
*/
typedef struct sditer sditer;
struct sditer {
int validate;
int compression;
ssbuf *compression_buf;
ssbuf *transform_buf;
sdindex *index;
char *start, *end;
char *page;
char *pagesrc;
sdpage pagev;
uint32_t pos;
sdv *dv;
sv v;
sr *r;
} sspacked;
static inline void
sd_iterresult(sditer *i, int pos)
{
i->dv = sd_pagev(&i->pagev, pos);
if (sslikely(i->r->fmt_storage == SF_SRAW)) {
sv_init(&i->v, &sd_vif, i->dv, i->pagev.h);
return;
}
sd_pagekv_convert(&i->pagev, i->r, i->dv, i->transform_buf->s);
sv_init(&i->v, &sd_vrawif, i->transform_buf->s, NULL);
}
static inline int
sd_iternextpage(sditer *i)
{
char *page = NULL;
if (ssunlikely(i->page == NULL))
{
sdindexheader *h = i->index->h;
page = i->start + h->offset + sd_indexsize(i->index->h);
i->end = page + h->total;
} else {
page = i->pagesrc + sizeof(sdpageheader) + i->pagev.h->size;
}
if (ssunlikely(page >= i->end)) {
i->page = NULL;
return 0;
}
i->pagesrc = page;
i->page = i->pagesrc;
/* decompression */
if (i->compression) {
ss_bufreset(i->compression_buf);
/* prepare decompression buffer */
sdpageheader *h = (sdpageheader*)i->page;
int rc = ss_bufensure(i->compression_buf, i->r->a, h->sizeorigin + sizeof(sdpageheader));
if (ssunlikely(rc == -1)) {
i->page = NULL;
return sr_oom_malfunction(i->r->e);
}
/* copy page header */
memcpy(i->compression_buf->s, i->page, sizeof(sdpageheader));
ss_bufadvance(i->compression_buf, sizeof(sdpageheader));
/* decompression */
ssfilter f;
rc = ss_filterinit(&f, (ssfilterif*)i->r->compression, i->r->a, SS_FOUTPUT);
if (ssunlikely(rc == -1)) {
i->page = NULL;
sr_malfunction(i->r->e, "%s", "page decompression error");
return -1;
}
rc = ss_filternext(&f, i->compression_buf, i->page + sizeof(sdpageheader), h->size);
if (ssunlikely(rc == -1)) {
ss_filterfree(&f);
i->page = NULL;
sr_malfunction(i->r->e, "%s", "page decompression error");
return -1;
}
ss_filterfree(&f);
/* switch to decompressed page */
i->page = i->compression_buf->s;
}
/* checksum */
if (i->validate) {
sdpageheader *h = (sdpageheader*)i->page;
uint32_t crc = ss_crcs(i->r->crc, h, sizeof(sdpageheader), 0);
if (ssunlikely(crc != h->crc)) {
i->page = NULL;
sr_malfunction(i->r->e, "%s", "bad page header crc");
return -1;
}
}
sd_pageinit(&i->pagev, (void*)i->page);
i->pos = 0;
if (ssunlikely(i->pagev.h->count == 0)) {
i->page = NULL;
i->dv = NULL;
return 0;
}
sd_iterresult(i, 0);
return 1;
}
static inline int
sd_iter_open(ssiter *i, sr *r, sdindex *index, char *start, int validate,
int compression,
ssbuf *compression_buf,
ssbuf *transform_buf)
{
sditer *ii = (sditer*)i->priv;
ii->r = r;
ii->index = index;
ii->start = start;
ii->end = NULL;
ii->page = NULL;
ii->pagesrc = NULL;
ii->pos = 0;
ii->dv = NULL;
ii->validate = validate;
ii->compression = compression;
ii->compression_buf = compression_buf;
ii->transform_buf = transform_buf;
memset(&ii->v, 0, sizeof(ii->v));
return sd_iternextpage(ii);
}
static inline void
sd_iter_close(ssiter *i ssunused)
{
sditer *ii = (sditer*)i->priv;
(void)ii;
}
static inline int
sd_iter_has(ssiter *i)
{
sditer *ii = (sditer*)i->priv;
return ii->page != NULL;
}
static inline void*
sd_iter_of(ssiter *i)
{
sditer *ii = (sditer*)i->priv;
if (ssunlikely(ii->page == NULL))
return NULL;
assert(ii->dv != NULL);
return &ii->v;
}
static inline void
sd_iter_next(ssiter *i)
{
sditer *ii = (sditer*)i->priv;
if (ssunlikely(ii->page == NULL))
return;
ii->pos++;
if (sslikely(ii->pos < ii->pagev.h->count)) {
sd_iterresult(ii, ii->pos);
} else {
ii->dv = NULL;
sd_iternextpage(ii);
}
}
extern ssiterif sd_iter;
#endif
| 2.15625 | 2 |
2024-11-18T22:25:36.300854+00:00 | 2015-12-16T10:12:06 | f5714dba25e89426184c1a76d380fcab5aa2ec53 | {
"blob_id": "f5714dba25e89426184c1a76d380fcab5aa2ec53",
"branch_name": "refs/heads/master",
"committer_date": "2015-12-16T10:12:06",
"content_id": "4e88cadb635918f94487025ece21c3d26063f56e",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "ed68a1ac51764885be1d6cebeaaccc5f1b0f81bd",
"extension": "c",
"filename": "hash_table.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 47487655,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2701,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/hash_table.c",
"provenance": "stackv2-0140.json.gz:157276",
"repo_name": "a12e/matcc",
"revision_date": "2015-12-16T10:12:06",
"revision_id": "4b074e848be8f570d47d2d69a5a37f5025e2c845",
"snapshot_id": "f81eb8c980c28dc792f79b7e8385830555400995",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/a12e/matcc/4b074e848be8f570d47d2d69a5a37f5025e2c845/src/hash_table.c",
"visit_date": "2021-01-10T14:41:41.469448"
} | stackv2 | #include <stdlib.h>
#include <string.h>
#include "hash_table.h"
#include "utility.h"
int ht_keycmp(ht_key key1, ht_key key2) {
return strcmp(key1, key2);
}
ht_key ht_keycpy(ht_key key) {
return safe_strdup(key);
}
ht_hash ht_dohash(hashtable_t *ht, ht_key key) {
ht_hash sum = 0;
for(int i = 0; key[i] != '\0'; i++)
sum += key[i];
return sum % ht->size;
}
void ht_init(hashtable_t *ht, size_t size) {
if(size < 1) {
ht->last_error = HT_BAD_SIZE;
return;
}
ht->size = size;
ht->buckets = safe_calloc(size, sizeof(ht_bucket *));
ht->last_error = HT_OK;
}
void ht_put(hashtable_t *ht, ht_key key, ht_val value) {
ht_hash hash = ht_dohash(ht, key);
if(ht_exists(ht, key)) {
ht->last_error = HT_ALREADYEXISTS;
return;
}
ht_bucket *item = safe_malloc(sizeof(ht_bucket));
item->key = ht_keycpy(key);
item->value = value;
item->successor = ht->buckets[hash];
ht->buckets[hash] = item;
ht->last_error = HT_OK;
}
ht_val ht_get(hashtable_t *ht, ht_key key) {
ht_hash hash = ht_dohash(ht, key);
for(ht_bucket *item = ht->buckets[hash]; item != NULL; item = item->successor)
if(ht_keycmp(item->key, key) == 0) {
ht->last_error = HT_OK;
return item->value;
}
ht->last_error = HT_NOTFOUND;
return NULL;
}
int ht_exists(hashtable_t *ht, ht_key key) {
ht_get(ht, key);
if(ht->last_error != HT_NOTFOUND) {
ht->last_error = HT_OK;
return 1;
}
return 0;
}
size_t ht_size(hashtable_t *ht) {
size_t size = 0;
for(size_t i = 0; i < ht->size; i++)
if(ht->buckets[i] != NULL)
for(ht_bucket *item = ht->buckets[i]; item != NULL; item = item->successor)
size++;
return size;
}
void ht_free(hashtable_t *ht) {
for(size_t i = 0; i < ht->size; i++)
for(ht_bucket *item = ht->buckets[i]; item != NULL;) {
safe_free(item->key);
symbol_delete(item->value);
ht_bucket *successor = item->successor;
safe_free(item);
item = successor;
}
safe_free(ht->buckets);
}
void ht_dump(hashtable_t *ht) {
printf("hashtable (%lu buckets)\n", ht->size);
for(size_t i = 0; i < ht->size; i++)
if(ht->buckets[i] != NULL) {
printf(" bucket #%lu (%p)\n", i, ht->buckets[i]);
for(ht_bucket *item = ht->buckets[i]; item != NULL; item = item->successor)
printf(" - %s = %p\n", item->key, item->value);
}
}
ht_error ht_last_error(hashtable_t *ht) {
ht_error error = ht->last_error;
ht->last_error = HT_OK;
return error;
}
| 3.09375 | 3 |
2024-11-18T22:25:36.524854+00:00 | 2015-09-30T18:12:49 | b9ee482624374815c933cc97264cae24fc8a2bae | {
"blob_id": "b9ee482624374815c933cc97264cae24fc8a2bae",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-30T18:12:49",
"content_id": "8fc406cd39142becca85f94856d1b45e8768a898",
"detected_licenses": [
"Unlicense"
],
"directory_id": "1d201504615b58da4b39e660a9afdaa547e7c2dd",
"extension": "c",
"filename": "seven.c",
"fork_events_count": 0,
"gha_created_at": "2015-06-16T15:54:52",
"gha_event_created_at": "2015-09-30T18:12:50",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 37540346,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 997,
"license": "Unlicense",
"license_type": "permissive",
"path": "/C/Gookin_CAIO/book 4 - Advanced/old/seven.c",
"provenance": "stackv2-0140.json.gz:157408",
"repo_name": "Mugurell/Learning",
"revision_date": "2015-09-30T18:12:49",
"revision_id": "835a295c060807be9b98ad9bfc3d80f12e2542f5",
"snapshot_id": "6e9a20233c6abe4d8b30fadb0275988d6bff70b7",
"src_encoding": "WINDOWS-1250",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Mugurell/Learning/835a295c060807be9b98ad9bfc3d80f12e2542f5/C/Gookin_CAIO/book 4 - Advanced/old/seven.c",
"visit_date": "2021-01-19T18:10:43.330159"
} | stackv2 | #include <stdio.h>
#include <string.h>
void seven_1(void);
void seven_2(void);
int x;
int main()
{
seven_1();
printf("\n*******\n\n");
seven_2();
return 0;
}
void seven_1(void)
{
char dwarf[7][8];
strcpy(dwarf[0], "bashful");
strcpy(dwarf[1], "doc");
strcpy(dwarf[2], "dopey");
strcpy(dwarf[3], "grumpy");
strcpy(dwarf[4], "happy");
strcpy(dwarf[5], "sneezy");
strcpy(dwarf[6], "sleepy");
/*! You have to use the strcpy() function
to copy a string constant into a
structure’s string variable!
Asta daca nu ai definit structura bine de la inceput...
*/
for(x=0; x<7; x++)
printf("%10s\n" , dwarf[x]);
}
void seven_2(void)
{
const char *dwarf[] =
{
"bashful",
"doc",
"dopey",
"grumpy",
"happy",
"sneezy",
"sleepy"
};
for(x=0; x<7; x++)
{
printf("%-10s\n" , dwarf[x]);
}
}
| 3.296875 | 3 |
2024-11-18T22:25:36.831025+00:00 | 2010-11-15T02:46:03 | 824cd2fce4f8e26e25b4c8fa15378c14d0838d69 | {
"blob_id": "824cd2fce4f8e26e25b4c8fa15378c14d0838d69",
"branch_name": "refs/heads/master",
"committer_date": "2010-11-15T02:46:03",
"content_id": "5a11eb054ae45df2111fe35fa57dd198ece521b1",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "f1416989141e71e9073d68389e0470dc4b2c7d79",
"extension": "c",
"filename": "lcd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 837118,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1880,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/polybot_library/lcd.c",
"provenance": "stackv2-0140.json.gz:157671",
"repo_name": "trainman419/slash-atmel",
"revision_date": "2010-11-15T02:46:03",
"revision_id": "83b1ad5b702d56615b547eec74d66dbf730c6f4c",
"snapshot_id": "9aa612b2731b24296393ed7457fe4d3eabe2c424",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/trainman419/slash-atmel/83b1ad5b702d56615b547eec74d66dbf730c6f4c/polybot_library/lcd.c",
"visit_date": "2021-01-10T21:20:58.754998"
} | stackv2 | #include <string.h>
#include "globals.h"
#include <avr/io.h>
#include <avr/interrupt.h>
// LCD Ram addresses
#define HOME 0x80
#define LINE_2 0XC0
void write_lcd(u08 data) {
cli();
DDRC = 0xff; //make port C outputs
PORTC = data;
delay_us(1);
sbi(PORTB,0); //set the clock high for the LCD
delay_us(1);
cbi(PORTB,0); //set the clock low for the LCD
delay_us(1);
DDRC = 0x00; //make port C inputs again
sei();
}
void write_control(u08 data) {
cbi(PORTB,1); //set RS low
write_lcd(data);
}
void write_data(u08 data) {
sbi(PORTB,1); //set RS high
write_lcd(data);
}
void lcd_init(void) {
//initialize the LCD as described in the HD44780 datasheet
write_control(0x38); //function set
delay_ms(5);
write_control(0x38); //function set
delay_us(160);
write_control(0x38); //function set
delay_us(160);
write_control(0x38); //function set
delay_us(160);
write_control(0x08); //turn display off
delay_us(160);
write_control(0x01); //clear display
delay_us(4000);
write_control(0x06); //set entry mode
delay_us(160);
}
void print_string(char* string) {
u08 i;
u08 num_bytes = strlen(string);
for (i=0;i<num_bytes;i++) {
write_data(string[i]);
delay_us(100);
}
}
void print_int(u16 number) {
u08 test[7];
print_string((char*)itoa(number,test,10
));
}
void print_fp(float number) {
char s[10];
dtostre(number,s,3,0);
print_string(s);
}
void clear_screen(void) {
write_control(0x01); //clear display
delay_us(3400);
}
void next_line(void) {
write_control(0xc0); //go to the second line on the display
delay_us(100);
}
// Moves the LCD cursor to row <row> column <col>.
// <row> ranges from 0 to 1.
// <col> ranges from 0 to 16.
void lcd_cursor(u08 row, u08 col) {
write_control(HOME | (row << 6) | (col % 17));
delay_us(100);
}
| 2.9375 | 3 |
2024-11-18T22:25:36.961022+00:00 | 2021-06-06T21:28:21 | 18bae66da2ba92e05462329c7a00f838c7ae3db4 | {
"blob_id": "18bae66da2ba92e05462329c7a00f838c7ae3db4",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-06T21:28:21",
"content_id": "1ea1b78dcbac502ae939c391ac64d96e7b5a0466",
"detected_licenses": [
"MIT"
],
"directory_id": "0b82e6c340618e23bcdc1b81562921e79f58a13b",
"extension": "c",
"filename": "4-test-one-fork.c",
"fork_events_count": 0,
"gha_created_at": "2021-06-05T10:02:27",
"gha_event_created_at": "2021-06-05T10:02:27",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 374079844,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 706,
"license": "MIT",
"license_type": "permissive",
"path": "/labs/9-threads/code/4-test-one-fork.c",
"provenance": "stackv2-0140.json.gz:157932",
"repo_name": "aym-v/cs140e-21spr",
"revision_date": "2021-06-06T21:28:21",
"revision_id": "cb8460f5e4517ed03d47db40f81dd25470e1dab6",
"snapshot_id": "81f0ee46814778d8a3aa5169da035ca4c0068fd4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aym-v/cs140e-21spr/cb8460f5e4517ed03d47db40f81dd25470e1dab6/labs/9-threads/code/4-test-one-fork.c",
"visit_date": "2023-05-23T11:57:08.921107"
} | stackv2 | // going to run a single thread and exit: makes it easier to test.
#include "rpi.h"
#include "rpi-thread.h"
static void thread_code(void *arg) {
unsigned *x = arg;
// check tid
rpi_thread_t *t = rpi_cur_thread();
printk("in thread %p, tid=%d with %x\n", t, t->tid, *x);
assert(t->tid == 1 && *x == 0xdeadbeef);
printk("success: got to the first thread\n");
clean_reboot();
}
void notmain() {
uart_init();
kmalloc_init_set_start(1024 * 1024);
printk("about to fork and run one threa\n");
unsigned x = 0xdeadbeef;
rpi_fork(thread_code, &x);
rpi_thread_start();
panic("should not get here\n");
}
void print_and_die(void) { panic("should not call\n"); }
| 2.640625 | 3 |
2024-11-18T22:25:37.085187+00:00 | 2021-06-10T14:57:30 | 1bb29daf5d27e133b708063dc3a0ef946aef4fcb | {
"blob_id": "1bb29daf5d27e133b708063dc3a0ef946aef4fcb",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-10T14:57:30",
"content_id": "f90889dced85624641fdbe192624c84f55c1fd88",
"detected_licenses": [
"MIT"
],
"directory_id": "28bf7793cde66074ac6cbe2c76df92bd4803dab9",
"extension": "c",
"filename": "question1.c",
"fork_events_count": 135,
"gha_created_at": "2021-03-15T23:37:26",
"gha_event_created_at": "2021-06-10T14:57:31",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 348153476,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1254,
"license": "MIT",
"license_type": "permissive",
"path": "/answers/Kaushal Kishor Sharma/Day 12/question1.c",
"provenance": "stackv2-0140.json.gz:158063",
"repo_name": "Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021",
"revision_date": "2021-06-10T14:57:30",
"revision_id": "66c7d85025481074c93cfda7853b145c88a30da4",
"snapshot_id": "2dee33e057ba22092795a6ecc6686a9d31607c9d",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021/66c7d85025481074c93cfda7853b145c88a30da4/answers/Kaushal Kishor Sharma/Day 12/question1.c",
"visit_date": "2023-05-29T10:33:31.795738"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include <stdbool.h>
int main ()
{
int n, m;
char string[] = {};
printf("Enter the value of n(string chatacters): ");
scanf("%d", &n);
printf("\nEnter the value of m (operations): ");
scanf("%d", &m);
printf("\nEnter the string: ");
scanf("%s", string);
printf("\nEnter operations (with spaces): ");
while (n > 0)
{
int num, k, x;
scanf("%d, %d, %d", &num, &k, &x);
if (num == 1)
{
for (int i = 0; i < n; i++)
{
if (string[i] == string[k])
string[i] = 'X';
}
printf("%s", string);
}
else if (num == 2)
{
bool palindrome = true;
while (k < x)
{
if (string[k] == string[x])
{
k++;
x--;
}
else
{
palindrome = false;
break;
}
}
if ( palindrome == true)
printf("\n Yes \n");
else
printf("\n No \n");
}
n--;
}
return 0;
}
| 3.53125 | 4 |
2024-11-18T22:25:37.188590+00:00 | 2020-05-11T17:36:40 | ce8f7d2b2b2fd4b7b383532d57ad4b26c2441454 | {
"blob_id": "ce8f7d2b2b2fd4b7b383532d57ad4b26c2441454",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-11T17:36:40",
"content_id": "450bd246d6d81f16340a3742aab562eab0c93d2e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "022319c2727cb06020cdf97699c2c3b84bdad1e9",
"extension": "h",
"filename": "AH_Math.h",
"fork_events_count": 0,
"gha_created_at": "2020-06-20T05:39:16",
"gha_event_created_at": "2020-06-20T05:39:17",
"gha_language": null,
"gha_license_id": null,
"github_id": 273645863,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 655,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/HISSTools_IR_Toolbox_Dependencies/AH_Math.h",
"provenance": "stackv2-0140.json.gz:158193",
"repo_name": "joelbisson/HISSTools_Impulse_Response_Toolbox",
"revision_date": "2020-05-11T17:36:40",
"revision_id": "82cf6bf4cc4484a8eb25c0b0eb1ce8613ed5b53e",
"snapshot_id": "58c054f96430b8a0d10c7cbba7930c4ecc310bd3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/joelbisson/HISSTools_Impulse_Response_Toolbox/82cf6bf4cc4484a8eb25c0b0eb1ce8613ed5b53e/HISSTools_IR_Toolbox_Dependencies/AH_Math.h",
"visit_date": "2022-06-26T09:56:14.255854"
} | stackv2 |
/*
* AH_Math
*
* This header file provides definitions or code for math.h functions not present under Windows using Visual Studio
*
*/
#ifndef _AH_MATH_
#define _AH_MATH_
#ifndef __APPLE__
#define _USE_MATH_DEFINES
#include <math.h>
#include <float.h>
#ifdef isnan
#undef isnan
#endif
#ifdef isinf
#undef isinf
#endif
static __inline double round(double r)
{
return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
static __inline long isnan(double n)
{
return !(n == n);
}
static __inline long isinf(double n)
{
return !isnan(n) & isnan(n - n);
}
#endif
#endif /* _AH_MATH_ */
| 2.203125 | 2 |
2024-11-18T22:25:37.537673+00:00 | 2023-08-02T09:06:56 | da5753726707e25f7ed31440d73501fb9f8e700f | {
"blob_id": "da5753726707e25f7ed31440d73501fb9f8e700f",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-08T07:01:20",
"content_id": "16b7b7cff76e695057a62f8eaf8343b8c7dffa3d",
"detected_licenses": [
"Intel",
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "a8194cf6ffd12f7551eaba53572744080a0bfef3",
"extension": "c",
"filename": "tgt_node.c",
"fork_events_count": 1158,
"gha_created_at": "2015-07-13T23:15:15",
"gha_event_created_at": "2023-08-11T09:50:50",
"gha_language": "C",
"gha_license_id": "NOASSERTION",
"github_id": 39042157,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 32756,
"license": "Intel,BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/lib/iscsi/tgt_node.c",
"provenance": "stackv2-0140.json.gz:158585",
"repo_name": "spdk/spdk",
"revision_date": "2023-08-02T09:06:56",
"revision_id": "d62a3810364cb87be352c66acf7c7f968508ca17",
"snapshot_id": "51294f67104b8c3d18f19147d63a212e9486c687",
"src_encoding": "UTF-8",
"star_events_count": 2708,
"url": "https://raw.githubusercontent.com/spdk/spdk/d62a3810364cb87be352c66acf7c7f968508ca17/lib/iscsi/tgt_node.c",
"visit_date": "2023-08-08T16:07:41.263000"
} | stackv2 | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright (C) 2008-2012 Daisuke Aoyama <[email protected]>.
* Copyright (C) 2016 Intel Corporation.
* All rights reserved.
*/
#include "spdk/stdinc.h"
#include "spdk/sock.h"
#include "spdk/scsi.h"
#include "spdk/log.h"
#include "iscsi/iscsi.h"
#include "iscsi/conn.h"
#include "iscsi/tgt_node.h"
#include "iscsi/portal_grp.h"
#include "iscsi/init_grp.h"
#include "iscsi/task.h"
#define MAX_TMPBUF 4096
#define MAX_MASKBUF 128
#define MAX_TMP_NAME_BUF (11 /* TargetName= */ + MAX_TARGET_NAME + 1 /* null */)
#define MAX_TMP_ADDR_BUF (14 /* TargetAddress= */ + MAX_PORTAL_ADDR + 1 /* : */ + \
MAX_PORTAL_PORT + 1 /* , */ + 10 /* max length of int in Decimal */ + 1 /* null */)
static bool
iscsi_ipv6_netmask_allow_addr(const char *netmask, const char *addr)
{
struct in6_addr in6_mask;
struct in6_addr in6_addr;
char mask[MAX_MASKBUF];
const char *p;
size_t n;
int bits, bmask;
int i;
if (netmask[0] != '[') {
return false;
}
p = strchr(netmask, ']');
if (p == NULL) {
return false;
}
n = p - (netmask + 1);
if (n + 1 > sizeof mask) {
return false;
}
memcpy(mask, netmask + 1, n);
mask[n] = '\0';
p++;
if (p[0] == '/') {
bits = (int) strtol(p + 1, NULL, 10);
if (bits <= 0 || bits > 128) {
return false;
}
} else {
bits = 128;
}
#if 0
SPDK_DEBUGLOG(iscsi, "input %s\n", addr);
SPDK_DEBUGLOG(iscsi, "mask %s / %d\n", mask, bits);
#endif
/* presentation to network order binary */
if (inet_pton(AF_INET6, mask, &in6_mask) <= 0
|| inet_pton(AF_INET6, addr, &in6_addr) <= 0) {
return false;
}
/* check 128bits */
for (i = 0; i < (bits / 8); i++) {
if (in6_mask.s6_addr[i] != in6_addr.s6_addr[i]) {
return false;
}
}
if (bits % 8) {
bmask = (0xffU << (8 - (bits % 8))) & 0xffU;
if ((in6_mask.s6_addr[i] & bmask) != (in6_addr.s6_addr[i] & bmask)) {
return false;
}
}
/* match */
return true;
}
static bool
iscsi_ipv4_netmask_allow_addr(const char *netmask, const char *addr)
{
struct in_addr in4_mask;
struct in_addr in4_addr;
char mask[MAX_MASKBUF];
const char *p;
uint32_t bmask;
size_t n;
int bits;
p = strchr(netmask, '/');
if (p == NULL) {
p = netmask + strlen(netmask);
}
n = p - netmask;
if (n + 1 > sizeof mask) {
return false;
}
memcpy(mask, netmask, n);
mask[n] = '\0';
if (p[0] == '/') {
bits = (int) strtol(p + 1, NULL, 10);
if (bits <= 0 || bits > 32) {
return false;
}
} else {
bits = 32;
}
/* presentation to network order binary */
if (inet_pton(AF_INET, mask, &in4_mask) <= 0
|| inet_pton(AF_INET, addr, &in4_addr) <= 0) {
return false;
}
/* check 32bits */
bmask = (0xffffffffU << (32 - bits)) & 0xffffffffU;
if ((ntohl(in4_mask.s_addr) & bmask) != (ntohl(in4_addr.s_addr) & bmask)) {
return false;
}
/* match */
return true;
}
static bool
iscsi_netmask_allow_addr(const char *netmask, const char *addr)
{
if (netmask == NULL || addr == NULL) {
return false;
}
if (strcasecmp(netmask, "ANY") == 0) {
return true;
}
if (netmask[0] == '[') {
/* IPv6 */
if (iscsi_ipv6_netmask_allow_addr(netmask, addr)) {
return true;
}
} else {
/* IPv4 */
if (iscsi_ipv4_netmask_allow_addr(netmask, addr)) {
return true;
}
}
return false;
}
static bool
iscsi_init_grp_allow_addr(struct spdk_iscsi_init_grp *igp,
const char *addr)
{
struct spdk_iscsi_initiator_netmask *imask;
TAILQ_FOREACH(imask, &igp->netmask_head, tailq) {
SPDK_DEBUGLOG(iscsi, "netmask=%s, addr=%s\n",
imask->mask, addr);
if (iscsi_netmask_allow_addr(imask->mask, addr)) {
return true;
}
}
return false;
}
static int
iscsi_init_grp_allow_iscsi_name(struct spdk_iscsi_init_grp *igp,
const char *iqn, bool *result)
{
struct spdk_iscsi_initiator_name *iname;
TAILQ_FOREACH(iname, &igp->initiator_head, tailq) {
/* denied if iqn is matched */
if ((iname->name[0] == '!')
&& (strcasecmp(&iname->name[1], "ANY") == 0
|| strcasecmp(&iname->name[1], iqn) == 0)) {
*result = false;
return 0;
}
/* allowed if iqn is matched */
if (strcasecmp(iname->name, "ANY") == 0
|| strcasecmp(iname->name, iqn) == 0) {
*result = true;
return 0;
}
}
return -1;
}
static struct spdk_iscsi_pg_map *iscsi_tgt_node_find_pg_map(struct spdk_iscsi_tgt_node *target,
struct spdk_iscsi_portal_grp *pg);
bool
iscsi_tgt_node_access(struct spdk_iscsi_conn *conn,
struct spdk_iscsi_tgt_node *target, const char *iqn, const char *addr)
{
struct spdk_iscsi_portal_grp *pg;
struct spdk_iscsi_pg_map *pg_map;
struct spdk_iscsi_ig_map *ig_map;
int rc;
bool allowed = false;
if (conn == NULL || target == NULL || iqn == NULL || addr == NULL) {
return false;
}
pg = conn->portal->group;
SPDK_DEBUGLOG(iscsi, "pg=%d, iqn=%s, addr=%s\n",
pg->tag, iqn, addr);
pg_map = iscsi_tgt_node_find_pg_map(target, pg);
if (pg_map == NULL) {
return false;
}
TAILQ_FOREACH(ig_map, &pg_map->ig_map_head, tailq) {
rc = iscsi_init_grp_allow_iscsi_name(ig_map->ig, iqn, &allowed);
if (rc == 0) {
if (allowed == false) {
goto denied;
} else {
if (iscsi_init_grp_allow_addr(ig_map->ig, addr)) {
return true;
}
}
} else {
/* netmask is denied in this initiator group */
}
}
denied:
SPDK_DEBUGLOG(iscsi, "access denied from %s (%s) to %s (%s:%s,%d)\n",
iqn, addr, target->name, conn->portal_host,
conn->portal_port, conn->pg_tag);
return false;
}
static bool
iscsi_tgt_node_allow_iscsi_name(struct spdk_iscsi_tgt_node *target, const char *iqn)
{
struct spdk_iscsi_pg_map *pg_map;
struct spdk_iscsi_ig_map *ig_map;
int rc;
bool result = false;
if (target == NULL || iqn == NULL) {
return false;
}
TAILQ_FOREACH(pg_map, &target->pg_map_head, tailq) {
TAILQ_FOREACH(ig_map, &pg_map->ig_map_head, tailq) {
rc = iscsi_init_grp_allow_iscsi_name(ig_map->ig, iqn, &result);
if (rc == 0) {
return result;
}
}
}
return false;
}
static bool
iscsi_copy_str(char *data, int *total, int alloc_len,
int *previous_completed_len, int expected_size, char *src)
{
int len = 0;
assert(*previous_completed_len >= 0);
if (alloc_len - *total < 1) {
return true;
}
if (*previous_completed_len < expected_size) {
len = spdk_min(alloc_len - *total, expected_size - *previous_completed_len);
memcpy((char *)data + *total, src + *previous_completed_len, len);
*total += len;
*previous_completed_len = 0;
} else {
*previous_completed_len -= expected_size;
}
return false;
}
static int
iscsi_send_tgt_portals(struct spdk_iscsi_conn *conn,
struct spdk_iscsi_tgt_node *target,
uint8_t *data, int alloc_len, int total,
int *previous_completed_len, bool *no_buf_space)
{
char buf[MAX_TARGET_ADDR + 2];
struct spdk_iscsi_portal_grp *pg;
struct spdk_iscsi_pg_map *pg_map;
struct spdk_iscsi_portal *p;
char *host;
char tmp_buf[MAX_TMP_ADDR_BUF];
int len;
TAILQ_FOREACH(pg_map, &target->pg_map_head, tailq) {
pg = pg_map->pg;
if (pg->is_private) {
/* Skip the private portal group. Portals in the private portal group
* will be returned only by temporary login redirection responses.
*/
continue;
}
TAILQ_FOREACH(p, &pg->head, per_pg_tailq) {
host = p->host;
/* wildcard? */
if (strcasecmp(host, "[::]") == 0 || strcasecmp(host, "0.0.0.0") == 0) {
if (spdk_sock_is_ipv6(conn->sock)) {
snprintf(buf, sizeof buf, "[%s]", conn->target_addr);
host = buf;
} else if (spdk_sock_is_ipv4(conn->sock)) {
snprintf(buf, sizeof buf, "%s", conn->target_addr);
host = buf;
} else {
/* skip portal for the family */
continue;
}
}
SPDK_DEBUGLOG(iscsi, "TargetAddress=%s:%s,%d\n",
host, p->port, pg->tag);
memset(tmp_buf, 0, sizeof(tmp_buf));
/* Calculate the whole string size */
len = snprintf(NULL, 0, "TargetAddress=%s:%s,%d", host, p->port, pg->tag);
assert(len < MAX_TMPBUF);
/* string contents are not fully copied */
if (*previous_completed_len < len) {
/* Copy the string into the temporary buffer */
snprintf(tmp_buf, len + 1, "TargetAddress=%s:%s,%d", host, p->port, pg->tag);
}
*no_buf_space = iscsi_copy_str(data, &total, alloc_len, previous_completed_len,
len + 1, tmp_buf);
if (*no_buf_space) {
break;
}
}
}
return total;
}
int
iscsi_send_tgts(struct spdk_iscsi_conn *conn, const char *iiqn,
const char *tiqn, uint8_t *data, int alloc_len, int data_len)
{
struct spdk_iscsi_tgt_node *target;
int total;
int len;
int rc;
int previous_completed_size = 0;
bool no_buf_space = false;
char tmp_buf[MAX_TMP_NAME_BUF];
if (conn == NULL) {
return 0;
}
previous_completed_size = conn->send_tgt_completed_size;
total = data_len;
if (alloc_len < 1) {
return 0;
}
if (total >= alloc_len) {
total = alloc_len;
data[total - 1] = '\0';
return total;
}
pthread_mutex_lock(&g_iscsi.mutex);
TAILQ_FOREACH(target, &g_iscsi.target_head, tailq) {
if (strcasecmp(tiqn, "ALL") != 0
&& strcasecmp(tiqn, target->name) != 0) {
continue;
}
rc = iscsi_tgt_node_allow_iscsi_name(target, iiqn);
if (rc == 0) {
continue;
}
memset(tmp_buf, 0, sizeof(tmp_buf));
/* Calculate the whole string size */
len = snprintf(NULL, 0, "TargetName=%s", target->name);
assert(len < MAX_TMPBUF);
/* String contents are not copied */
if (previous_completed_size < len) {
/* Copy the string into the temporary buffer */
snprintf(tmp_buf, len + 1, "TargetName=%s", target->name);
}
no_buf_space = iscsi_copy_str(data, &total, alloc_len, &previous_completed_size,
len + 1, tmp_buf);
if (no_buf_space) {
break;
}
total = iscsi_send_tgt_portals(conn, target, data, alloc_len, total,
&previous_completed_size, &no_buf_space);
if (no_buf_space) {
break;
}
}
pthread_mutex_unlock(&g_iscsi.mutex);
/* Only set it when it is not successfully completed */
if (no_buf_space) {
conn->send_tgt_completed_size += total;
} else {
conn->send_tgt_completed_size = 0;
}
return total;
}
struct spdk_iscsi_tgt_node *
iscsi_find_tgt_node(const char *target_name)
{
struct spdk_iscsi_tgt_node *target;
if (target_name == NULL) {
return NULL;
}
TAILQ_FOREACH(target, &g_iscsi.target_head, tailq) {
if (strcasecmp(target_name, target->name) == 0) {
return target;
}
}
return NULL;
}
static int
iscsi_tgt_node_register(struct spdk_iscsi_tgt_node *target)
{
pthread_mutex_lock(&g_iscsi.mutex);
if (iscsi_find_tgt_node(target->name) != NULL) {
pthread_mutex_unlock(&g_iscsi.mutex);
return -EEXIST;
}
TAILQ_INSERT_TAIL(&g_iscsi.target_head, target, tailq);
pthread_mutex_unlock(&g_iscsi.mutex);
return 0;
}
static int
iscsi_tgt_node_unregister(struct spdk_iscsi_tgt_node *target)
{
struct spdk_iscsi_tgt_node *t;
TAILQ_FOREACH(t, &g_iscsi.target_head, tailq) {
if (t == target) {
TAILQ_REMOVE(&g_iscsi.target_head, t, tailq);
return 0;
}
}
return -1;
}
static struct spdk_iscsi_ig_map *
iscsi_pg_map_find_ig_map(struct spdk_iscsi_pg_map *pg_map,
struct spdk_iscsi_init_grp *ig)
{
struct spdk_iscsi_ig_map *ig_map;
TAILQ_FOREACH(ig_map, &pg_map->ig_map_head, tailq) {
if (ig_map->ig == ig) {
return ig_map;
}
}
return NULL;
}
static struct spdk_iscsi_ig_map *
iscsi_pg_map_add_ig_map(struct spdk_iscsi_pg_map *pg_map,
struct spdk_iscsi_init_grp *ig)
{
struct spdk_iscsi_ig_map *ig_map;
if (iscsi_pg_map_find_ig_map(pg_map, ig) != NULL) {
return NULL;
}
ig_map = malloc(sizeof(*ig_map));
if (ig_map == NULL) {
return NULL;
}
ig_map->ig = ig;
ig->ref++;
pg_map->num_ig_maps++;
TAILQ_INSERT_TAIL(&pg_map->ig_map_head, ig_map, tailq);
return ig_map;
}
static void
_iscsi_pg_map_delete_ig_map(struct spdk_iscsi_pg_map *pg_map,
struct spdk_iscsi_ig_map *ig_map)
{
TAILQ_REMOVE(&pg_map->ig_map_head, ig_map, tailq);
pg_map->num_ig_maps--;
ig_map->ig->ref--;
free(ig_map);
}
static int
iscsi_pg_map_delete_ig_map(struct spdk_iscsi_pg_map *pg_map,
struct spdk_iscsi_init_grp *ig)
{
struct spdk_iscsi_ig_map *ig_map;
ig_map = iscsi_pg_map_find_ig_map(pg_map, ig);
if (ig_map == NULL) {
return -ENOENT;
}
_iscsi_pg_map_delete_ig_map(pg_map, ig_map);
return 0;
}
static void
iscsi_pg_map_delete_all_ig_maps(struct spdk_iscsi_pg_map *pg_map)
{
struct spdk_iscsi_ig_map *ig_map, *tmp;
TAILQ_FOREACH_SAFE(ig_map, &pg_map->ig_map_head, tailq, tmp) {
_iscsi_pg_map_delete_ig_map(pg_map, ig_map);
}
}
static struct spdk_iscsi_pg_map *
iscsi_tgt_node_find_pg_map(struct spdk_iscsi_tgt_node *target,
struct spdk_iscsi_portal_grp *pg)
{
struct spdk_iscsi_pg_map *pg_map;
TAILQ_FOREACH(pg_map, &target->pg_map_head, tailq) {
if (pg_map->pg == pg) {
return pg_map;
}
}
return NULL;
}
static struct spdk_iscsi_pg_map *
iscsi_tgt_node_add_pg_map(struct spdk_iscsi_tgt_node *target,
struct spdk_iscsi_portal_grp *pg)
{
struct spdk_iscsi_pg_map *pg_map;
char port_name[MAX_TMPBUF];
int rc;
if (iscsi_tgt_node_find_pg_map(target, pg) != NULL) {
return NULL;
}
if (target->num_pg_maps >= SPDK_SCSI_DEV_MAX_PORTS) {
SPDK_ERRLOG("Number of PG maps is more than allowed (max=%d)\n",
SPDK_SCSI_DEV_MAX_PORTS);
return NULL;
}
pg_map = calloc(1, sizeof(*pg_map));
if (pg_map == NULL) {
return NULL;
}
snprintf(port_name, sizeof(port_name), "%s,t,0x%4.4x",
spdk_scsi_dev_get_name(target->dev), pg->tag);
rc = spdk_scsi_dev_add_port(target->dev, pg->tag, port_name);
if (rc != 0) {
free(pg_map);
return NULL;
}
TAILQ_INIT(&pg_map->ig_map_head);
pg_map->num_ig_maps = 0;
pg->ref++;
pg_map->pg = pg;
target->num_pg_maps++;
TAILQ_INSERT_TAIL(&target->pg_map_head, pg_map, tailq);
return pg_map;
}
static void
_iscsi_tgt_node_delete_pg_map(struct spdk_iscsi_tgt_node *target,
struct spdk_iscsi_pg_map *pg_map)
{
TAILQ_REMOVE(&target->pg_map_head, pg_map, tailq);
target->num_pg_maps--;
pg_map->pg->ref--;
spdk_scsi_dev_delete_port(target->dev, pg_map->pg->tag);
free(pg_map);
}
static int
iscsi_tgt_node_delete_pg_map(struct spdk_iscsi_tgt_node *target,
struct spdk_iscsi_portal_grp *pg)
{
struct spdk_iscsi_pg_map *pg_map;
pg_map = iscsi_tgt_node_find_pg_map(target, pg);
if (pg_map == NULL) {
return -ENOENT;
}
if (pg_map->num_ig_maps > 0) {
SPDK_DEBUGLOG(iscsi, "delete %d ig_maps forcefully\n",
pg_map->num_ig_maps);
}
iscsi_pg_map_delete_all_ig_maps(pg_map);
_iscsi_tgt_node_delete_pg_map(target, pg_map);
return 0;
}
static void
iscsi_tgt_node_delete_ig_maps(struct spdk_iscsi_tgt_node *target,
struct spdk_iscsi_init_grp *ig)
{
struct spdk_iscsi_pg_map *pg_map, *tmp;
TAILQ_FOREACH_SAFE(pg_map, &target->pg_map_head, tailq, tmp) {
iscsi_pg_map_delete_ig_map(pg_map, ig);
if (pg_map->num_ig_maps == 0) {
_iscsi_tgt_node_delete_pg_map(target, pg_map);
}
}
}
static void
iscsi_tgt_node_delete_all_pg_maps(struct spdk_iscsi_tgt_node *target)
{
struct spdk_iscsi_pg_map *pg_map, *tmp;
TAILQ_FOREACH_SAFE(pg_map, &target->pg_map_head, tailq, tmp) {
iscsi_pg_map_delete_all_ig_maps(pg_map);
_iscsi_tgt_node_delete_pg_map(target, pg_map);
}
}
static void
_iscsi_tgt_node_destruct(void *cb_arg, int rc)
{
struct spdk_iscsi_tgt_node *target = cb_arg;
iscsi_tgt_node_destruct_cb destruct_cb_fn = target->destruct_cb_fn;
void *destruct_cb_arg = target->destruct_cb_arg;
if (rc != 0) {
if (destruct_cb_fn) {
destruct_cb_fn(destruct_cb_arg, rc);
}
return;
}
pthread_mutex_lock(&g_iscsi.mutex);
iscsi_tgt_node_delete_all_pg_maps(target);
pthread_mutex_unlock(&g_iscsi.mutex);
pthread_mutex_destroy(&target->mutex);
free(target);
if (destruct_cb_fn) {
destruct_cb_fn(destruct_cb_arg, 0);
}
}
static int
iscsi_tgt_node_check_active_conns(void *arg)
{
struct spdk_iscsi_tgt_node *target = arg;
if (iscsi_get_active_conns(target) != 0) {
return SPDK_POLLER_BUSY;
}
spdk_poller_unregister(&target->destruct_poller);
spdk_scsi_dev_destruct(target->dev, _iscsi_tgt_node_destruct, target);
return SPDK_POLLER_BUSY;
}
static void
iscsi_tgt_node_destruct(struct spdk_iscsi_tgt_node *target,
iscsi_tgt_node_destruct_cb cb_fn, void *cb_arg)
{
if (target == NULL) {
if (cb_fn) {
cb_fn(cb_arg, -ENOENT);
}
return;
}
if (target->destructed) {
SPDK_ERRLOG("Destructing %s is already started\n", target->name);
if (cb_fn) {
cb_fn(cb_arg, -EBUSY);
}
return;
}
target->destructed = true;
target->destruct_cb_fn = cb_fn;
target->destruct_cb_arg = cb_arg;
iscsi_conns_request_logout(target, -1);
if (iscsi_get_active_conns(target) != 0) {
target->destruct_poller = SPDK_POLLER_REGISTER(iscsi_tgt_node_check_active_conns,
target, 10);
} else {
spdk_scsi_dev_destruct(target->dev, _iscsi_tgt_node_destruct, target);
}
}
static int
iscsi_tgt_node_delete_pg_ig_map(struct spdk_iscsi_tgt_node *target,
int pg_tag, int ig_tag)
{
struct spdk_iscsi_portal_grp *pg;
struct spdk_iscsi_init_grp *ig;
struct spdk_iscsi_pg_map *pg_map;
struct spdk_iscsi_ig_map *ig_map;
pg = iscsi_portal_grp_find_by_tag(pg_tag);
if (pg == NULL) {
SPDK_ERRLOG("%s: PortalGroup%d not found\n", target->name, pg_tag);
return -ENOENT;
}
ig = iscsi_init_grp_find_by_tag(ig_tag);
if (ig == NULL) {
SPDK_ERRLOG("%s: InitiatorGroup%d not found\n", target->name, ig_tag);
return -ENOENT;
}
pg_map = iscsi_tgt_node_find_pg_map(target, pg);
if (pg_map == NULL) {
SPDK_ERRLOG("%s: PortalGroup%d is not mapped\n", target->name, pg_tag);
return -ENOENT;
}
ig_map = iscsi_pg_map_find_ig_map(pg_map, ig);
if (ig_map == NULL) {
SPDK_ERRLOG("%s: InitiatorGroup%d is not mapped\n", target->name, pg_tag);
return -ENOENT;
}
_iscsi_pg_map_delete_ig_map(pg_map, ig_map);
if (pg_map->num_ig_maps == 0) {
_iscsi_tgt_node_delete_pg_map(target, pg_map);
}
return 0;
}
static int
iscsi_tgt_node_add_pg_ig_map(struct spdk_iscsi_tgt_node *target,
int pg_tag, int ig_tag)
{
struct spdk_iscsi_portal_grp *pg;
struct spdk_iscsi_pg_map *pg_map;
struct spdk_iscsi_init_grp *ig;
struct spdk_iscsi_ig_map *ig_map;
bool new_pg_map = false;
pg = iscsi_portal_grp_find_by_tag(pg_tag);
if (pg == NULL) {
SPDK_ERRLOG("%s: PortalGroup%d not found\n", target->name, pg_tag);
return -ENOENT;
}
ig = iscsi_init_grp_find_by_tag(ig_tag);
if (ig == NULL) {
SPDK_ERRLOG("%s: InitiatorGroup%d not found\n", target->name, ig_tag);
return -ENOENT;
}
/* get existing pg_map or create new pg_map and add it to target */
pg_map = iscsi_tgt_node_find_pg_map(target, pg);
if (pg_map == NULL) {
pg_map = iscsi_tgt_node_add_pg_map(target, pg);
if (pg_map == NULL) {
goto failed;
}
new_pg_map = true;
}
/* create new ig_map and add it to pg_map */
ig_map = iscsi_pg_map_add_ig_map(pg_map, ig);
if (ig_map == NULL) {
goto failed;
}
return 0;
failed:
if (new_pg_map) {
_iscsi_tgt_node_delete_pg_map(target, pg_map);
}
return -1;
}
int
iscsi_target_node_add_pg_ig_maps(struct spdk_iscsi_tgt_node *target,
int *pg_tag_list, int *ig_tag_list, uint16_t num_maps)
{
uint16_t i;
int rc;
pthread_mutex_lock(&g_iscsi.mutex);
for (i = 0; i < num_maps; i++) {
rc = iscsi_tgt_node_add_pg_ig_map(target, pg_tag_list[i],
ig_tag_list[i]);
if (rc != 0) {
SPDK_ERRLOG("could not add map to target\n");
goto invalid;
}
}
pthread_mutex_unlock(&g_iscsi.mutex);
return 0;
invalid:
for (; i > 0; --i) {
iscsi_tgt_node_delete_pg_ig_map(target, pg_tag_list[i - 1],
ig_tag_list[i - 1]);
}
pthread_mutex_unlock(&g_iscsi.mutex);
return -1;
}
int
iscsi_target_node_remove_pg_ig_maps(struct spdk_iscsi_tgt_node *target,
int *pg_tag_list, int *ig_tag_list, uint16_t num_maps)
{
uint16_t i;
int rc;
pthread_mutex_lock(&g_iscsi.mutex);
for (i = 0; i < num_maps; i++) {
rc = iscsi_tgt_node_delete_pg_ig_map(target, pg_tag_list[i],
ig_tag_list[i]);
if (rc != 0) {
SPDK_ERRLOG("could not delete map from target\n");
goto invalid;
}
}
pthread_mutex_unlock(&g_iscsi.mutex);
return 0;
invalid:
for (; i > 0; --i) {
rc = iscsi_tgt_node_add_pg_ig_map(target, pg_tag_list[i - 1],
ig_tag_list[i - 1]);
if (rc != 0) {
iscsi_tgt_node_delete_all_pg_maps(target);
break;
}
}
pthread_mutex_unlock(&g_iscsi.mutex);
return -1;
}
int
iscsi_tgt_node_redirect(struct spdk_iscsi_tgt_node *target, int pg_tag,
const char *host, const char *port)
{
struct spdk_iscsi_portal_grp *pg;
struct spdk_iscsi_pg_map *pg_map;
struct sockaddr_storage sa;
if (target == NULL) {
return -EINVAL;
}
pg = iscsi_portal_grp_find_by_tag(pg_tag);
if (pg == NULL) {
SPDK_ERRLOG("Portal group %d is not found.\n", pg_tag);
return -EINVAL;
}
if (pg->is_private) {
SPDK_ERRLOG("Portal group %d is not public portal group.\n", pg_tag);
return -EINVAL;
}
pg_map = iscsi_tgt_node_find_pg_map(target, pg);
if (pg_map == NULL) {
SPDK_ERRLOG("Portal group %d is not mapped.\n", pg_tag);
return -EINVAL;
}
if (host == NULL && port == NULL) {
/* Clear redirect setting. */
memset(pg_map->redirect_host, 0, MAX_PORTAL_ADDR + 1);
memset(pg_map->redirect_port, 0, MAX_PORTAL_PORT + 1);
} else {
if (iscsi_parse_redirect_addr(&sa, host, port) != 0) {
SPDK_ERRLOG("IP address-port pair is not valid.\n");
return -EINVAL;
}
if (iscsi_portal_grp_find_portal_by_addr(pg, port, host) != NULL) {
SPDK_ERRLOG("IP address-port pair must be chosen from a "
"different private portal group\n");
return -EINVAL;
}
snprintf(pg_map->redirect_host, MAX_PORTAL_ADDR + 1, "%s", host);
snprintf(pg_map->redirect_port, MAX_PORTAL_PORT + 1, "%s", port);
}
return 0;
}
bool
iscsi_tgt_node_is_redirected(struct spdk_iscsi_conn *conn,
struct spdk_iscsi_tgt_node *target,
char *buf, int buf_len)
{
struct spdk_iscsi_pg_map *pg_map;
if (conn == NULL || target == NULL || buf == NULL || buf_len == 0) {
return false;
}
pg_map = iscsi_tgt_node_find_pg_map(target, conn->portal->group);
if (pg_map == NULL) {
return false;
}
if (pg_map->redirect_host[0] == '\0' || pg_map->redirect_port[0] == '\0') {
return false;
}
snprintf(buf, buf_len, "%s:%s", pg_map->redirect_host, pg_map->redirect_port);
return true;
}
static int
check_iscsi_name(const char *name)
{
const unsigned char *up = (const unsigned char *) name;
size_t n;
/* valid iSCSI name no larger than 223 bytes */
if (strlen(name) > MAX_TARGET_NAME) {
return -1;
}
/* valid iSCSI name? */
for (n = 0; up[n] != 0; n++) {
if (up[n] > 0x00U && up[n] <= 0x2cU) {
return -1;
}
if (up[n] == 0x2fU) {
return -1;
}
if (up[n] >= 0x3bU && up[n] <= 0x40U) {
return -1;
}
if (up[n] >= 0x5bU && up[n] <= 0x60U) {
return -1;
}
if (up[n] >= 0x7bU && up[n] <= 0x7fU) {
return -1;
}
if (isspace(up[n])) {
return -1;
}
}
/* valid format? */
if (strncasecmp(name, "iqn.", 4) == 0) {
/* iqn.YYYY-MM.reversed.domain.name */
if (!isdigit(up[4]) || !isdigit(up[5]) || !isdigit(up[6])
|| !isdigit(up[7]) || up[8] != '-' || !isdigit(up[9])
|| !isdigit(up[10]) || up[11] != '.') {
SPDK_ERRLOG("invalid iqn format. "
"expect \"iqn.YYYY-MM.reversed.domain.name\"\n");
return -1;
}
} else if (strncasecmp(name, "eui.", 4) == 0) {
/* EUI-64 -> 16bytes */
/* XXX */
} else if (strncasecmp(name, "naa.", 4) == 0) {
/* 64bit -> 16bytes, 128bit -> 32bytes */
/* XXX */
}
/* OK */
return 0;
}
bool
iscsi_check_chap_params(bool disable, bool require, bool mutual, int group)
{
if (group < 0) {
SPDK_ERRLOG("Invalid auth group ID (%d)\n", group);
return false;
}
if ((!disable && !require && !mutual) || /* Auto */
(disable && !require && !mutual) || /* None */
(!disable && require && !mutual) || /* CHAP */
(!disable && require && mutual)) { /* CHAP Mutual */
return true;
}
SPDK_ERRLOG("Invalid combination of CHAP params (d=%d,r=%d,m=%d)\n",
disable, require, mutual);
return false;
}
struct spdk_iscsi_tgt_node *iscsi_tgt_node_construct(int target_index,
const char *name, const char *alias,
int *pg_tag_list, int *ig_tag_list, uint16_t num_maps,
const char *bdev_name_list[], int *lun_id_list, int num_luns,
int queue_depth,
bool disable_chap, bool require_chap, bool mutual_chap, int chap_group,
bool header_digest, bool data_digest)
{
char fullname[MAX_TMPBUF];
struct spdk_iscsi_tgt_node *target;
int rc;
if (!iscsi_check_chap_params(disable_chap, require_chap,
mutual_chap, chap_group)) {
return NULL;
}
if (num_maps == 0) {
SPDK_ERRLOG("num_maps = 0\n");
return NULL;
}
if (name == NULL) {
SPDK_ERRLOG("TargetName not found\n");
return NULL;
}
if (strncasecmp(name, "iqn.", 4) != 0
&& strncasecmp(name, "eui.", 4) != 0
&& strncasecmp(name, "naa.", 4) != 0) {
snprintf(fullname, sizeof(fullname), "%s:%s", g_iscsi.nodebase, name);
} else {
snprintf(fullname, sizeof(fullname), "%s", name);
}
if (check_iscsi_name(fullname) != 0) {
SPDK_ERRLOG("TargetName %s contains an invalid character or format.\n",
name);
return NULL;
}
target = calloc(1, sizeof(*target));
if (!target) {
SPDK_ERRLOG("could not allocate target\n");
return NULL;
}
rc = pthread_mutex_init(&target->mutex, NULL);
if (rc != 0) {
SPDK_ERRLOG("tgt_node%d: mutex_init() failed\n", target->num);
iscsi_tgt_node_destruct(target, NULL, NULL);
return NULL;
}
target->num = target_index;
memcpy(target->name, fullname, strlen(fullname));
if (alias != NULL) {
if (strlen(alias) > MAX_TARGET_NAME) {
iscsi_tgt_node_destruct(target, NULL, NULL);
return NULL;
}
memcpy(target->alias, alias, strlen(alias));
}
target->dev = spdk_scsi_dev_construct(fullname, bdev_name_list, lun_id_list, num_luns,
SPDK_SPC_PROTOCOL_IDENTIFIER_ISCSI, NULL, NULL);
if (!target->dev) {
SPDK_ERRLOG("Could not construct SCSI device\n");
iscsi_tgt_node_destruct(target, NULL, NULL);
return NULL;
}
TAILQ_INIT(&target->pg_map_head);
rc = iscsi_target_node_add_pg_ig_maps(target, pg_tag_list,
ig_tag_list, num_maps);
if (rc != 0) {
SPDK_ERRLOG("could not add map to target\n");
iscsi_tgt_node_destruct(target, NULL, NULL);
return NULL;
}
target->disable_chap = disable_chap;
target->require_chap = require_chap;
target->mutual_chap = mutual_chap;
target->chap_group = chap_group;
target->header_digest = header_digest;
target->data_digest = data_digest;
if (queue_depth > 0 && ((uint32_t)queue_depth <= g_iscsi.MaxQueueDepth)) {
target->queue_depth = queue_depth;
} else {
SPDK_DEBUGLOG(iscsi, "QueueDepth %d is invalid and %d is used instead.\n",
queue_depth, g_iscsi.MaxQueueDepth);
target->queue_depth = g_iscsi.MaxQueueDepth;
}
rc = iscsi_tgt_node_register(target);
if (rc != 0) {
SPDK_ERRLOG("register target is failed\n");
iscsi_tgt_node_destruct(target, NULL, NULL);
return NULL;
}
return target;
}
void
iscsi_shutdown_tgt_nodes(void)
{
struct spdk_iscsi_tgt_node *target;
pthread_mutex_lock(&g_iscsi.mutex);
while (!TAILQ_EMPTY(&g_iscsi.target_head)) {
target = TAILQ_FIRST(&g_iscsi.target_head);
TAILQ_REMOVE(&g_iscsi.target_head, target, tailq);
pthread_mutex_unlock(&g_iscsi.mutex);
iscsi_tgt_node_destruct(target, NULL, NULL);
pthread_mutex_lock(&g_iscsi.mutex);
}
pthread_mutex_unlock(&g_iscsi.mutex);
}
void
iscsi_shutdown_tgt_node_by_name(const char *target_name,
iscsi_tgt_node_destruct_cb cb_fn, void *cb_arg)
{
struct spdk_iscsi_tgt_node *target;
pthread_mutex_lock(&g_iscsi.mutex);
target = iscsi_find_tgt_node(target_name);
if (target != NULL) {
iscsi_tgt_node_unregister(target);
pthread_mutex_unlock(&g_iscsi.mutex);
iscsi_tgt_node_destruct(target, cb_fn, cb_arg);
return;
}
pthread_mutex_unlock(&g_iscsi.mutex);
if (cb_fn) {
cb_fn(cb_arg, -ENOENT);
}
}
bool
iscsi_tgt_node_is_destructed(struct spdk_iscsi_tgt_node *target)
{
return target->destructed;
}
int
iscsi_tgt_node_cleanup_luns(struct spdk_iscsi_conn *conn,
struct spdk_iscsi_tgt_node *target)
{
struct spdk_scsi_lun *lun;
struct spdk_iscsi_task *task;
for (lun = spdk_scsi_dev_get_first_lun(target->dev); lun != NULL;
lun = spdk_scsi_dev_get_next_lun(lun)) {
/* we create a fake management task per LUN to cleanup */
task = iscsi_task_get(conn, NULL, iscsi_task_mgmt_cpl);
if (!task) {
SPDK_ERRLOG("Unable to acquire task\n");
return -1;
}
task->scsi.target_port = conn->target_port;
task->scsi.initiator_port = conn->initiator_port;
task->scsi.lun = lun;
iscsi_op_abort_task_set(task, SPDK_SCSI_TASK_FUNC_LUN_RESET);
}
return 0;
}
void
iscsi_tgt_node_delete_map(struct spdk_iscsi_portal_grp *portal_group,
struct spdk_iscsi_init_grp *initiator_group)
{
struct spdk_iscsi_tgt_node *target;
pthread_mutex_lock(&g_iscsi.mutex);
TAILQ_FOREACH(target, &g_iscsi.target_head, tailq) {
if (portal_group) {
iscsi_tgt_node_delete_pg_map(target, portal_group);
}
if (initiator_group) {
iscsi_tgt_node_delete_ig_maps(target, initiator_group);
}
}
pthread_mutex_unlock(&g_iscsi.mutex);
}
int
iscsi_tgt_node_add_lun(struct spdk_iscsi_tgt_node *target,
const char *bdev_name, int lun_id)
{
struct spdk_scsi_dev *dev;
int rc;
if (target->num_active_conns > 0) {
SPDK_ERRLOG("Target has active connections (count=%d)\n",
target->num_active_conns);
return -1;
}
if (lun_id < -1) {
SPDK_ERRLOG("Specified LUN ID (%d) is negative\n", lun_id);
return -1;
}
dev = target->dev;
if (dev == NULL) {
SPDK_ERRLOG("SCSI device is not found\n");
return -1;
}
rc = spdk_scsi_dev_add_lun(dev, bdev_name, lun_id, NULL, NULL);
if (rc != 0) {
SPDK_ERRLOG("spdk_scsi_dev_add_lun failed\n");
return -1;
}
return 0;
}
int
iscsi_tgt_node_set_chap_params(struct spdk_iscsi_tgt_node *target,
bool disable_chap, bool require_chap,
bool mutual_chap, int32_t chap_group)
{
if (!iscsi_check_chap_params(disable_chap, require_chap,
mutual_chap, chap_group)) {
return -EINVAL;
}
pthread_mutex_lock(&target->mutex);
target->disable_chap = disable_chap;
target->require_chap = require_chap;
target->mutual_chap = mutual_chap;
target->chap_group = chap_group;
pthread_mutex_unlock(&target->mutex);
return 0;
}
static void
iscsi_tgt_node_info_json(struct spdk_iscsi_tgt_node *target,
struct spdk_json_write_ctx *w)
{
struct spdk_iscsi_pg_map *pg_map;
struct spdk_iscsi_ig_map *ig_map;
struct spdk_scsi_lun *lun;
spdk_json_write_object_begin(w);
spdk_json_write_named_string(w, "name", target->name);
if (target->alias[0] != '\0') {
spdk_json_write_named_string(w, "alias_name", target->alias);
}
spdk_json_write_named_array_begin(w, "pg_ig_maps");
TAILQ_FOREACH(pg_map, &target->pg_map_head, tailq) {
TAILQ_FOREACH(ig_map, &pg_map->ig_map_head, tailq) {
spdk_json_write_object_begin(w);
spdk_json_write_named_int32(w, "pg_tag", pg_map->pg->tag);
spdk_json_write_named_int32(w, "ig_tag", ig_map->ig->tag);
spdk_json_write_object_end(w);
}
}
spdk_json_write_array_end(w);
spdk_json_write_named_array_begin(w, "luns");
for (lun = spdk_scsi_dev_get_first_lun(target->dev); lun != NULL;
lun = spdk_scsi_dev_get_next_lun(lun)) {
spdk_json_write_object_begin(w);
spdk_json_write_named_string(w, "bdev_name", spdk_scsi_lun_get_bdev_name(lun));
spdk_json_write_named_int32(w, "lun_id", spdk_scsi_lun_get_id(lun));
spdk_json_write_object_end(w);
}
spdk_json_write_array_end(w);
spdk_json_write_named_int32(w, "queue_depth", target->queue_depth);
spdk_json_write_named_bool(w, "disable_chap", target->disable_chap);
spdk_json_write_named_bool(w, "require_chap", target->require_chap);
spdk_json_write_named_bool(w, "mutual_chap", target->mutual_chap);
spdk_json_write_named_int32(w, "chap_group", target->chap_group);
spdk_json_write_named_bool(w, "header_digest", target->header_digest);
spdk_json_write_named_bool(w, "data_digest", target->data_digest);
spdk_json_write_object_end(w);
}
static void
iscsi_tgt_node_config_json(struct spdk_iscsi_tgt_node *target,
struct spdk_json_write_ctx *w)
{
spdk_json_write_object_begin(w);
spdk_json_write_named_string(w, "method", "iscsi_create_target_node");
spdk_json_write_name(w, "params");
iscsi_tgt_node_info_json(target, w);
spdk_json_write_object_end(w);
}
void
iscsi_tgt_nodes_info_json(struct spdk_json_write_ctx *w)
{
struct spdk_iscsi_tgt_node *target;
TAILQ_FOREACH(target, &g_iscsi.target_head, tailq) {
iscsi_tgt_node_info_json(target, w);
}
}
void
iscsi_tgt_nodes_config_json(struct spdk_json_write_ctx *w)
{
struct spdk_iscsi_tgt_node *target;
TAILQ_FOREACH(target, &g_iscsi.target_head, tailq) {
iscsi_tgt_node_config_json(target, w);
}
}
| 2.265625 | 2 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.