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-18T21:28:17.496392+00:00
2021-06-20T22:42:29
cb462a13efc36d0c6fd8910284b2587830a8676a
{ "blob_id": "cb462a13efc36d0c6fd8910284b2587830a8676a", "branch_name": "refs/heads/master", "committer_date": "2021-06-20T22:42:29", "content_id": "d35094753f7b09bb77af39a3838e4fc0822b10bf", "detected_licenses": [ "MIT" ], "directory_id": "d87f9e9d55b36ec1e97687bc0ee6999b6fe44b70", "extension": "h", "filename": "texto.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": 4537, "license": "MIT", "license_type": "permissive", "path": "/src/Objetos/Outros/texto.h", "provenance": "stackv2-0104.json.gz:14657", "repo_name": "felipedallmann/Estrutura-de-Dados", "revision_date": "2021-06-20T22:42:29", "revision_id": "99407b3f415be3f73bcc798d67405d7b6f80a03f", "snapshot_id": "a100e40d1cdc19b7f05db42aadd8242c3235ffe3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/felipedallmann/Estrutura-de-Dados/99407b3f415be3f73bcc798d67405d7b6f80a03f/src/Objetos/Outros/texto.h", "visit_date": "2023-06-01T09:04:28.870541" }
stackv2
#ifndef TEXTO_H #define TEXTO_H /* Este módulo define um Texto, permitindo exibir textos no arquivo svg. Possui como propriedades seu identificador, coordenadas espaciais e para alterar sua visualização no arquivo svg cores de borda e preenchimento. Suas propriedades são: id: Identificador do texto. x: Coordenada x do texto no plano. y: Coordenada y do texto no plano. cor da borda cor de preenchimento conteudo */ #include <stdbool.h> #include <stdio.h> /* Foi usado 'typedef struct *' em vez de 'typedef void *' para permitir ao compilador diferenciar os tipos, não afetando o encapsulamento de dados! O struct *não é definido neste header* e sim em seu arquivo .c correspondente, o ponteiro deste tipo não pode ser criado sem seu construtor, assim como suas propriedades não podem ser acessadas sem uso de getters/setters. */ typedef struct Texto_s *Texto; enum TextoAlinhamento { TEXTO_ESQUERDA, TEXTO_CENTRO }; /* Cria e inicializa um Texto com os valores passados. A largura e altura devem ser maiores que 0. O id e as cores não podem ser nulos. O usuário é responsável por liberar a memória alocada! */ Texto texto_criar(const char id[100], double x, double y, const char cor_borda[20], const char cor_preenchimento[20], const char conteudo[1024]); /* Cria e inicializa um Texto a partir de um texto obtido no arquivo .geo. O parâmetro linha não pode ser nulo. O usuário é responsável por liberar a memória alocada! */ Texto texto_ler(const char *linha); /* Escreve todas as informações presentes em um texto em um arquivo. Nenhum dos parâmetros podem ser nulos. O arquivo deve estar aberto para escrita! */ void texto_escrever_informacoes(Texto texto, FILE *arquivo); /* Escreve todas as informações presentes em um texto em um arquivo. Nenhum dos parâmetros podem ser nulos. O arquivo deve estar aberto para escrita! */ void texto_escrever_svg(Texto texto, FILE *arquivo); /* Obtém o conteúdo de um texto. O parâmetro retangulo não pode ser nulo. Retorna o conteúdo de um texto. */ const char *texto_obter_conteudo(Texto texto); /* Obtém o id de um texto. O parâmetro retangulo não pode ser nulo. Retorna o id de um texto. */ const char *texto_obter_id(Texto texto); /* Obtém a coordenada x de um texto. O parâmetro retangulo não pode ser nulo. Retorna a coordenada x de um texto. */ double texto_obter_x(Texto texto); /* Obtém a coordenada y de um texto. O parâmetro retangulo não pode ser nulo. Retorna a coordenada y de um texto. */ double texto_obter_y(Texto texto); /* Obtém a coordenada x onde um texto termina. O parâmetro retangulo não pode ser nulo. Retorna a coordenada x onde um texto termina. */ double texto_obter_x_fim(Texto texto); /* Obtém a coordenada y onde um texto termina. O parâmetro retangulo não pode ser nulo. Retorna a coordenada y onde um texto termina. */ double texto_obter_y_fim(Texto texto); /* Obtém a coordenada x onde o centro de um texto se encontra. O parâmetro retangulo não pode ser nulo. Retorna a coordenada x onde o centro de um texto se encontra. */ double texto_obter_x_centro(Texto texto); /* Obtém a coordenada y onde o centro de um texto se encontra. O parâmetro retangulo não pode ser nulo. Retorna a coordenada y onde o centro de um texto se encontra. */ double texto_obter_y_centro(Texto texto); /* Obtém a cor da borda de um texto. O parâmetro retangulo não pode ser nulo. Retorna a cor da borda de um texto. */ const char *texto_obter_cor_borda(Texto texto); /* Define a cor da borda de um texto. Nenhum dos parâmetros podem ser nulos. */ void texto_definir_cor_borda(Texto texto, const char *cor_borda); /* Obtém a cor de preenchimento de um texto. O parâmetro retangulo não pode ser nulo. Retorna a cor de preenchimento de um texto. */ const char *texto_obter_cor_preenchimento(Texto texto); /* Define a cor de preenchimento de um texto. Nenhum dos parâmetros podem ser nulos. */ void texto_definir_cor_preenchimento(Texto texto, const char *cor_preenchimento); /* Define o alinhamento de um texto, definindo qual posição do texto as coordenas x e y representam. O parâmetro texto não pode ser nulo. */ void texto_definir_alinhamento(Texto texto, enum TextoAlinhamento alinhamento); /* Libera a memória alocada por um texto. O parâmetro retangulo não pode ser nulo e deve apontar para um espaço de memória reservada. Libera a memória alocada. O ponteiro não poderá ser utilizado após isso! */ void texto_destruir(Texto texto); #endif
2.78125
3
2024-11-18T21:28:17.746723+00:00
2021-11-10T08:35:04
43c6c53e11aa0f3a6fc66da2e1964f71cdaec32a
{ "blob_id": "43c6c53e11aa0f3a6fc66da2e1964f71cdaec32a", "branch_name": "refs/heads/master", "committer_date": "2021-11-10T08:35:04", "content_id": "55b17ca30f204b863b77fb1ac56eac8761173244", "detected_licenses": [ "MIT" ], "directory_id": "7152b3c381bfe8ed13d0b62e6c35db36bc6291a3", "extension": "c", "filename": "battery.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 408345256, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 783, "license": "MIT", "license_type": "permissive", "path": "/src/measurement/battery.c", "provenance": "stackv2-0104.json.gz:14913", "repo_name": "inu1997/raspi-pilot", "revision_date": "2021-11-10T08:35:04", "revision_id": "26e79fbe25b1ed7bc42bda57a29d4fdf6a164531", "snapshot_id": "81ff147635daadb7a44f6697d6f3471ec3f79fad", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/inu1997/raspi-pilot/26e79fbe25b1ed7bc42bda57a29d4fdf6a164531/src/measurement/battery.c", "visit_date": "2023-08-29T04:22:08.610446" }
stackv2
#include "battery.h" #include "util/loop.h" #include "util/logger.h" #include "util/debug.h" static float _voltage; static float _current; static float _comsumed_current; static float _remain_time_sec; int battery_init() { LOG("Initiating Battery measurement.\n"); _voltage = 0; _current = 0; _comsumed_current = 0; _remain_time_sec = 0; LOG("Done.\n"); return 0; } void battery_update() { _comsumed_current += _current * loop_get_interval(); } float battery_get_voltage() { return _voltage; } float battery_get_current() { return _current; } float battery_get_comsumed_current() { return _comsumed_current; } float battery_get_remain_time_sec() { return _remain_time_sec; }
2.265625
2
2024-11-18T22:09:25.473190+00:00
2021-01-13T16:30:06
649e81f1ea84240ae8608fa2035a11269ef6659a
{ "blob_id": "649e81f1ea84240ae8608fa2035a11269ef6659a", "branch_name": "refs/heads/main", "committer_date": "2021-01-13T16:30:06", "content_id": "9888786c0e2959aeee85da1eca23768f3eeba259", "detected_licenses": [ "MIT" ], "directory_id": "78c10b52ad45b69c1d6485adb66076d0b5af053e", "extension": "h", "filename": "Intersection.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 329295568, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1405, "license": "MIT", "license_type": "permissive", "path": "/C++ Game/Intersection.h", "provenance": "stackv2-0106.json.gz:32828", "repo_name": "alexnoddings/UniTrimmed", "revision_date": "2021-01-13T16:30:06", "revision_id": "82d437b8c722dd770eb8366ec8e1a1f4d3ae65e1", "snapshot_id": "bc977c2df1be933b49e2e545e35de97759346741", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alexnoddings/UniTrimmed/82d437b8c722dd770eb8366ec8e1a1f4d3ae65e1/C++ Game/Intersection.h", "visit_date": "2023-02-16T21:20:57.353380" }
stackv2
/** * Functions for calculating intersection. * * @author Alexander Noddings <b7029792@ncl.ac.uk> */ #pragma once #include "Piece.h" #include "Circle.h" #include "Square.h" // do intersect between shapes bool do_intersect(const Circle circle, const Square square); bool do_intersect(const Square square, const Circle circle); bool do_intersect(const Square square1, const Square square2); bool do_intersect(const Circle circle1, const Circle circle2); // do intersect between pieces bool do_intersect(const Circle circle, const Piece* piece2); bool do_intersect(const Square square, const Piece* piece2); bool do_intersect(const Piece* piece1, const Piece* piece2); // will intersect between shapes bool will_intersect(const Circle circle, const Point new_position, const Square square); bool will_intersect(const Square square, const Point new_position, const Circle circle); bool will_intersect(const Square square1, const Point new_position, const Square square2); bool will_intersect(const Circle circle1, const Point new_position, const Circle circle2); // will intersect between pieces bool will_intersect(const Circle moving_circle, const Point new_position, const Piece* static_piece); bool will_intersect(const Square moving_square, const Point new_position, const Piece* static_piece); bool will_intersect(const Piece* moving_piece, const Point new_position, const Piece* static_piece);
2.578125
3
2024-11-18T22:09:26.064812+00:00
2023-08-31T16:38:00
8d86925a14fe7163a468775f535c8753ee73f08e
{ "blob_id": "8d86925a14fe7163a468775f535c8753ee73f08e", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T16:38:00", "content_id": "d3e2bba4cdf816110115aee45aaa2451fad8efc5", "detected_licenses": [ "BSD-2-Clause", "BSD-2-Clause-Patent" ], "directory_id": "1efd2de8bf77ec00eb2fcaf5749278495946d920", "extension": "h", "filename": "heap.h", "fork_events_count": 300, "gha_created_at": "2016-09-27T19:21:29", "gha_event_created_at": "2023-09-14T18:55:15", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 69390670, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3734, "license": "BSD-2-Clause,BSD-2-Clause-Patent", "license_type": "permissive", "path": "/src/common/dav/heap.h", "provenance": "stackv2-0106.json.gz:32959", "repo_name": "daos-stack/daos", "revision_date": "2023-08-31T16:38:00", "revision_id": "ed5eed5df43a68571afe123132a743824c02637a", "snapshot_id": "6f55bf3061fd830d5b8d28506e1295e2d3a27c38", "src_encoding": "UTF-8", "star_events_count": 631, "url": "https://raw.githubusercontent.com/daos-stack/daos/ed5eed5df43a68571afe123132a743824c02637a/src/common/dav/heap.h", "visit_date": "2023-08-31T21:43:37.606145" }
stackv2
/* SPDX-License-Identifier: BSD-3-Clause */ /* Copyright 2015-2021, Intel Corporation */ /* * heap.h -- internal definitions for heap */ #ifndef __DAOS_COMMON_HEAP_H #define __DAOS_COMMON_HEAP_H 1 #include <stddef.h> #include <stdint.h> #include "memblock.h" #include "bucket.h" #include "memops.h" #include "palloc.h" #include "os_thread.h" #include "dav_internal.h" extern enum dav_arenas_assignment_type Default_arenas_assignment_type; extern size_t Default_arenas_max; #define HEAP_OFF_TO_PTR(heap, off) ((void *)((char *)((heap)->base) + (off))) #define HEAP_PTR_TO_OFF(heap, ptr)\ ((uintptr_t)(ptr) - (uintptr_t)((heap)->base)) #define BIT_IS_CLR(a, i) (!((a) & (1ULL << (i)))) #define HEAP_ARENA_PER_THREAD (0) int heap_boot(struct palloc_heap *heap, void *heap_start, uint64_t heap_size, uint64_t *sizep, void *base, struct mo_ops *p_ops, struct stats *stats, struct pool_set *set); int heap_init(void *heap_start, uint64_t heap_size, uint64_t *sizep, struct mo_ops *p_ops); void heap_cleanup(struct palloc_heap *heap); int heap_check(void *heap_start, uint64_t heap_size); int heap_check_remote(void *heap_start, uint64_t heap_size, struct remote_ops *ops); int heap_buckets_init(struct palloc_heap *heap); int heap_create_alloc_class_buckets(struct palloc_heap *heap, struct alloc_class *c); int heap_extend(struct palloc_heap *heap, struct bucket *defb, size_t size); struct alloc_class * heap_get_best_class(struct palloc_heap *heap, size_t size); struct bucket * heap_bucket_acquire(struct palloc_heap *heap, uint8_t class_id, uint16_t arena_id); void heap_bucket_release(struct bucket *b); int heap_get_bestfit_block(struct palloc_heap *heap, struct bucket *b, struct memory_block *m); os_mutex_t *heap_get_run_lock(struct palloc_heap *heap, uint32_t chunk_id); void heap_force_recycle(struct palloc_heap *heap); void heap_discard_run(struct palloc_heap *heap, struct memory_block *m); void heap_memblock_on_free(struct palloc_heap *heap, const struct memory_block *m); int heap_free_chunk_reuse(struct palloc_heap *heap, struct bucket *bucket, struct memory_block *m); void heap_foreach_object(struct palloc_heap *heap, object_callback cb, void *arg, struct memory_block start); struct alloc_class_collection *heap_alloc_classes(struct palloc_heap *heap); void *heap_end(struct palloc_heap *heap); unsigned heap_get_narenas_total(struct palloc_heap *heap); unsigned heap_get_narenas_max(struct palloc_heap *heap); int heap_set_narenas_max(struct palloc_heap *heap, unsigned size); unsigned heap_get_narenas_auto(struct palloc_heap *heap); unsigned heap_get_thread_arena_id(struct palloc_heap *heap); int heap_arena_create(struct palloc_heap *heap); struct bucket_locked ** heap_get_arena_buckets(struct palloc_heap *heap, unsigned arena_id); int heap_get_arena_auto(struct palloc_heap *heap, unsigned arena_id); int heap_set_arena_auto(struct palloc_heap *heap, unsigned arena_id, int automatic); void heap_set_arena_thread(struct palloc_heap *heap, unsigned arena_id); unsigned heap_get_procs(void); void heap_vg_open(struct palloc_heap *heap, object_callback cb, void *arg, int objects); static inline struct chunk_header * heap_get_chunk_hdr(struct palloc_heap *heap, const struct memory_block *m) { return GET_CHUNK_HDR(heap->layout, m->zone_id, m->chunk_id); } static inline struct chunk * heap_get_chunk(struct palloc_heap *heap, const struct memory_block *m) { return GET_CHUNK(heap->layout, m->zone_id, m->chunk_id); } static inline struct chunk_run * heap_get_chunk_run(struct palloc_heap *heap, const struct memory_block *m) { return GET_CHUNK_RUN(heap->layout, m->zone_id, m->chunk_id); } #endif /* __DAOS_COMMON_HEAP_H */
2.015625
2
2024-11-18T22:09:26.397081+00:00
2017-09-26T09:48:33
ed441ee05686033b4bac1c3549d316a78fafdd5b
{ "blob_id": "ed441ee05686033b4bac1c3549d316a78fafdd5b", "branch_name": "refs/heads/master", "committer_date": "2017-09-26T09:48:33", "content_id": "fc3038ece113379bbb8647740d60298a64cde92b", "detected_licenses": [ "MIT" ], "directory_id": "f223bc46490f2d0a3cf2ffc4fe149c754833ac48", "extension": "h", "filename": "graph.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 104866669, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 838, "license": "MIT", "license_type": "permissive", "path": "/inc/graph.h", "provenance": "stackv2-0106.json.gz:33217", "repo_name": "benjyup/Lemin", "revision_date": "2017-09-26T09:48:33", "revision_id": "c384d92a70adedf112b1024cf2e88d3ac322ad25", "snapshot_id": "459d624241633b11d1743a40c63cb987e7e9f6ec", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/benjyup/Lemin/c384d92a70adedf112b1024cf2e88d3ac322ad25/inc/graph.h", "visit_date": "2021-05-14T23:20:48.315075" }
stackv2
/* ** graph.h for in /home/puente_t/rendu/CPE/CPE_2015_Lemin ** ** Made by Timothée Puentes ** Login <puente_t@epitech.net> ** ** Started on Mon Apr 18 12:00:52 2016 Timothée Puentes ** Last update Tue Apr 19 16:26:42 2016 Vincent Florian */ #ifndef GRAPH_H_ # define GRAPH_H_ # define SUCCESS 0 # define ERR 1 # define PNT_ERR (void*)-1 typedef struct s_path { char *name; struct s_path *next; } t_path; t_path **find_path(t_room_list *root, t_leminfo *data); void free_path(t_path *path); t_path *cpy_new_path(t_path *old, char *new_name); int recur_path(t_path **list_path, t_path *act_path, t_room_list *graph_root, t_leminfo *data); void add_path_at_end(t_path *root, t_path *new); t_path *create_a_path(char *str); void print_all_path(t_path *path); #endif /* !GRAPH_H_ */
2.09375
2
2024-11-18T22:09:26.482913+00:00
2021-05-25T20:02:44
1dc19676a8e5d3d48ae0019f5e95ea30e27f6e70
{ "blob_id": "1dc19676a8e5d3d48ae0019f5e95ea30e27f6e70", "branch_name": "refs/heads/main", "committer_date": "2021-05-25T20:02:44", "content_id": "1cf0d6922e1ade0783cfda28c7df14447c5092cf", "detected_licenses": [ "MIT" ], "directory_id": "c216d89c418e998513d0bccbe308f46be9222dd4", "extension": "c", "filename": "b_d_lecture.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 359409672, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1037, "license": "MIT", "license_type": "permissive", "path": "/challenge/challenge_bit_manipulation/b_d_lecture.c", "provenance": "stackv2-0106.json.gz:33345", "repo_name": "liangcorp/learning_c", "revision_date": "2021-05-25T20:02:44", "revision_id": "5d77d0beec5557d7f077fc0760e6c8513d820403", "snapshot_id": "8235b00a776864eaeef6c4bddd9271e993ce1134", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/liangcorp/learning_c/5d77d0beec5557d7f077fc0760e6c8513d820403/challenge/challenge_bit_manipulation/b_d_lecture.c", "visit_date": "2023-05-06T09:11:26.263777" }
stackv2
#include <stdio.h> #include <math.h> int convert_binary_to_decimal(long long n); long long convert_decimal_to_binary(int n); int main(void) { long long b_num; int result = 0; int n = 0; printf("Enter a binary number: "); scanf("%d", &b_num); result = convert_binary_to_decimal(b_num); printf("%lld in binary = %d in decimal", b_num, result); printf("Enter a decimal number: "); scanf("%d", &n); b_num = convert_decimal_to_binary(n); return 0; } int convert_binary_to_decimal(long long n) { int decimal_number = 0; int i = 0; int remainder = 0; while (n != 0) { remainder = n % 10; n = n / 10; decimal_number += remainder * pow(2, i); i++; } return decimal_number; } long long convert_decimal_to_binary(int n) { long long b_num = 0; int remainder = 0; int i = 0; while (n != 0) { remainder = n % 2; n = n / 2; b_num += remainder * i; i *= 10; } return b_num; }
3.65625
4
2024-11-18T22:09:26.590216+00:00
2017-09-18T08:51:19
997dab05d74527d033a541390a3e82ce6cf454c7
{ "blob_id": "997dab05d74527d033a541390a3e82ce6cf454c7", "branch_name": "refs/heads/master", "committer_date": "2017-09-18T08:51:19", "content_id": "1a781c4337be435705d4667bf4c19bcc2b7e47dc", "detected_licenses": [ "MIT" ], "directory_id": "838601059adbd0976e30cf4e2f9d621799d83639", "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": 103914926, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1677, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0106.json.gz:33475", "repo_name": "siddarthareddyt/maze_solving_robot", "revision_date": "2017-09-18T08:51:19", "revision_id": "a42cae27a286c7fee396f8c74757a2690623975e", "snapshot_id": "9fd72635e6121f0b8449d2339f60523f390a5d08", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/siddarthareddyt/maze_solving_robot/a42cae27a286c7fee396f8c74757a2690623975e/main.c", "visit_date": "2021-06-30T15:10:47.929443" }
stackv2
#include <pololu/3pi.h> #include <avr/pgmspace.h> #include "bargraph.h" #include "maze-solve.h" const char welcome_line1[] PROGMEM = " Pololu"; const char welcome_line2[] PROGMEM = "3\xf7 Robot"; const char demo_name_line1[] PROGMEM = "Maze"; const char demo_name_line2[] PROGMEM = "solver"; const char welcome[] PROGMEM = ">g32>>c32"; const char go[] PROGMEM = "L16 cdegreg4"; void initialize() { unsigned int counter; unsigned int sensors[5]; pololu_3pi_init(2000); load_custom_characters(); print_from_program_space(welcome_line1); lcd_goto_xy(0,1); print_from_program_space(welcome_line2); play_from_program_space(welcome); delay_ms(1000); clear(); print_from_program_space(demo_name_line1); lcd_goto_xy(0,1); print_from_program_space(demo_name_line2); delay_ms(1000); while(!button_is_pressed(BUTTON_B)) { int bat = read_battery_millivolts(); clear(); print_long(bat); print("mV"); lcd_goto_xy(0,1); print("Press B"); delay_ms(100); } wait_for_button_release(BUTTON_B); delay_ms(1000); for(counter=0;counter<80;counter++) { if(counter < 20 || counter >= 60) set_motors(40,-40); else set_motors(-40,40); calibrate_line_sensors(IR_EMITTERS_ON); delay_ms(20); } set_motors(0,0); while(!button_is_pressed(BUTTON_B)) { unsigned int position = read_line(sensors,IR_EMITTERS_ON); clear(); print_long(position); lcd_goto_xy(0,1); display_readings(sensors); delay_ms(100); } wait_for_button_release(BUTTON_B); clear(); print("Go!"); play_from_program_space(go); while(is_playing()); } int main() { initialize(); maze_solve(); while(1); }
2.359375
2
2024-11-18T22:09:26.816915+00:00
2018-04-10T20:18:18
b1bf27ea1c71a56d0b8e9a932d12931a304e7c3e
{ "blob_id": "b1bf27ea1c71a56d0b8e9a932d12931a304e7c3e", "branch_name": "refs/heads/master", "committer_date": "2018-04-10T20:18:18", "content_id": "4e95c4304cbf73a91c2b68368a77a8f1527ce3fa", "detected_licenses": [ "CC0-1.0" ], "directory_id": "7720da671230f902fe39e900fe78f013f6313fc1", "extension": "h", "filename": "memory.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 128989994, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 631, "license": "CC0-1.0", "license_type": "permissive", "path": "/memory.h", "provenance": "stackv2-0106.json.gz:33606", "repo_name": "Vavassor/PointerMap", "revision_date": "2018-04-10T20:18:18", "revision_id": "90c00e51d0768f8e143d5c3541de43aa31fc21bd", "snapshot_id": "976907285a1bd55b514099f96d62de1ef8623fe4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Vavassor/PointerMap/90c00e51d0768f8e143d5c3541de43aa31fc21bd/memory.h", "visit_date": "2020-03-09T20:38:14.024932" }
stackv2
#ifndef MEMORY_H_ #define MEMORY_H_ #include "sized_types.h" #include <cstdlib> // Note from Andrew Dawson: This is all part of an interface I normally use for // memory. It's not relevant to these tests, so here they're replaced with stubs // that just use calloc and free. struct Heap { int placeholder; }; #define heap_create(heap, bytes) #define heap_destroy(heap) #define HEAP_ALLOCATE(heap, type, count)\ static_cast<type*>(calloc(count, sizeof(type))) #define HEAP_DEALLOCATE(heap, array)\ free(array) #define SAFE_HEAP_DEALLOCATE(heap, array)\ {free(array); (array) = nullptr;} #endif // MEMORY_H_
2.140625
2
2024-11-18T22:09:26.896306+00:00
2022-08-16T07:57:44
06264aab4434e5cdbee7798ec2d3931c90b2cb9a
{ "blob_id": "06264aab4434e5cdbee7798ec2d3931c90b2cb9a", "branch_name": "refs/heads/master", "committer_date": "2022-08-16T07:57:44", "content_id": "3184b66f3c998cfcb785d59477cced6c151c6f9b", "detected_licenses": [ "MIT" ], "directory_id": "c72645b35d51c9ff23daa7d859bf80104c349efb", "extension": "c", "filename": "531_lonely_pixel_i.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 192122974, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1246, "license": "MIT", "license_type": "permissive", "path": "/medium/531_lonely_pixel_i.c", "provenance": "stackv2-0106.json.gz:33734", "repo_name": "Frost-Lee/leet_cc", "revision_date": "2022-08-16T07:57:44", "revision_id": "02b4cac3f9fec36ab8767f3d5237c17cad193b3b", "snapshot_id": "66316ad765e90c07a78d358322e22fc2429c7eab", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/Frost-Lee/leet_cc/02b4cac3f9fec36ab8767f3d5237c17cad193b3b/medium/531_lonely_pixel_i.c", "visit_date": "2022-08-28T04:05:24.750813" }
stackv2
int findLonelyPixel(char** picture, int pictureSize, int* pictureColSize) { int *row_single_cols = (int *)malloc(sizeof(int) * pictureSize); int *col_single_rows = (int *)malloc(sizeof(int) * (*pictureColSize)); for (size_t i = 0; i < pictureSize; i ++) { row_single_cols[i] = -1; } for (size_t i = 0; i < (*pictureColSize); i ++) { col_single_rows[i] = -1; } for (size_t i = 0; i < pictureSize; i ++) { for (size_t j = 0; j < (*pictureColSize); j ++) { if (picture[i][j] == 'B') { if (row_single_cols[i] == -1) { row_single_cols[i] = j; } else { row_single_cols[i] = -2; } if (col_single_rows[j] == -1) { col_single_rows[j] = i; } else { col_single_rows[j] = -2; } } } } int lonely_count = 0; for (size_t i = 0; i < pictureSize; i ++) { if (i < (*pictureColSize) && row_single_cols[i] >= 0 && col_single_rows[row_single_cols[i]] == i) { lonely_count += 1; } } free(row_single_cols); free(col_single_rows); return lonely_count; }
2.65625
3
2024-11-18T22:09:27.031067+00:00
2019-01-03T22:10:42
6ba7b68809c630a00890f8d4086036dac6deae6d
{ "blob_id": "6ba7b68809c630a00890f8d4086036dac6deae6d", "branch_name": "refs/heads/main", "committer_date": "2019-01-03T22:10:42", "content_id": "f3cb9398707c69f162279ca6ee8542b30eeff214", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "1a3d9fda52c764cdb2988f79d13861ae7151ca25", "extension": "h", "filename": "SmartPointerCommonTests.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 142214833, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8123, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/source/Utils/test/include/Memory/SmartPointerCommonTests.h", "provenance": "stackv2-0106.json.gz:33991", "repo_name": "mamaheux/apb", "revision_date": "2019-01-03T22:10:42", "revision_id": "44e3a80c3c67c3516a7a1ac046c666fd7baafb4a", "snapshot_id": "3859ddd57b3fad2569c3cc08e2dc994b3587ec0b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mamaheux/apb/44e3a80c3c67c3516a7a1ac046c666fd7baafb4a/source/Utils/test/include/Memory/SmartPointerCommonTests.h", "visit_date": "2021-06-23T15:11:14.619016" }
stackv2
#ifndef SMART_POINTER_COMMON_TESTS_H #define SMART_POINTER_COMMON_TESTS_H #include <Utils/Containers/FixedArray.h> #include <gtest/gtest.h> #define DECLARE_DEFAULT_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass) \ _DECLARE_DEFAULT_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass, int, element) \ _DECLARE_DEFAULT_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass, int[], array) #define _DECLARE_DEFAULT_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass, type, prefix) \ TEST_F(pointerClass##Tests, prefix##DefaultConstructor_shouldSetThePointerToNullptr) \ { \ pointerClass<type> pointer; \ \ EXPECT_EQ(pointer.get(), nullptr); \ } #define DECLARE_NULLPTR_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass) \ _DECLARE_NULLPTR_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass, int, element) \ _DECLARE_NULLPTR_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass, int[], array) #define _DECLARE_NULLPTR_CONSTRUCTOR_SHOULD_SET_THE_POINTER_TO_NULLPTR(pointerClass, type, prefix) \ TEST_F(pointerClass##Tests, prefix##NullptrConstructor_shouldSetThePointerToNullptr) \ { \ pointerClass<int> pointer(nullptr); \ \ EXPECT_EQ(pointer.get(), nullptr); \ } #define DECLARE_DEREFENCE_SHOULD_RETURN_THE_VALUE(pointerClass) \ TEST_F(pointerClass##Tests, dereference_shouldReturnTheValue) \ { \ int* valuePointer = new int; \ *valuePointer = 10; \ pointerClass<int> pointer(valuePointer); \ \ EXPECT_EQ(*pointer, 10); \ } #define DECLARE_STRUCTURE_DEREFERENCE_SHOULD_RETURN_THE_POINTER(pointerClass) \ TEST_F(pointerClass##Tests, structureDereference_shouldReturnThePointer) \ { \ pointerClass<FixedArray<int, 1>> pointer(new FixedArray<int, 1>); \ \ EXPECT_EQ(pointer->size(), 1); \ } #define DECLARE_OFFSET_ACCESS_OPERATOR_SHOULD_RETURN_THE_VALUE_AT_THE_SPECIFIED_INDEX(pointerClass) \ TEST_F(pointerClass##Tests, offsetAccessOperator_shouldReturnTheValueAtTheSpecifiedIndex) \ { \ int* valuesPointer = new int[2]; \ valuesPointer[0] = 2; \ valuesPointer[1] = 5; \ pointerClass<int[]> pointer(valuesPointer); \ \ EXPECT_EQ(pointer[0], 2); \ EXPECT_EQ(pointer[1], 5); \ } #define DECLARE_BOOL_OPERATOR_SHOULD_CHECK_THE_POINTER_VALIDITY(pointerClass) \ _DECLARE_BOOL_OPERATOR_SHOULD_CHECK_THE_POINTER_VALIDITY(pointerClass, int, new int, element) \ _DECLARE_BOOL_OPERATOR_SHOULD_CHECK_THE_POINTER_VALIDITY(pointerClass, int[], new int[1], ) #define _DECLARE_BOOL_OPERATOR_SHOULD_CHECK_THE_POINTER_VALIDITY(pointerClass, type, typeInstanciation, prefix) \ TEST_F(pointerClass##Tests, prefix##BoolOperator__shouldCheckThePointerValidity) \ { \ pointerClass<type> pointer1; \ pointerClass<type> pointer2(typeInstanciation); \ \ if (pointer1) \ { \ FAIL(); \ } \ else \ { \ SUCCEED(); \ } \ \ if (!pointer2) \ { \ FAIL(); \ } \ else \ { \ SUCCEED(); \ } \ } #define DECLARE_COMPARISON_OPERATORS_SHOULD_RETURN_THE_RIGHT_VALUE(pointerClass) \ TEST_F(pointerClass##Tests, comparisonOperators_shouldReturnTheRigthValues) \ { \ pointerClass<int> pointer1(new int); \ pointerClass<int> pointer2(new int); \ pointerClass<int[]> pointer3(new int[2]); \ pointerClass<int[]> pointer4(new int[2]); \ \ EXPECT_TRUE(pointer1 == pointer1); \ EXPECT_TRUE(pointer1 == pointer1.get()); \ EXPECT_TRUE(pointer1.get() == pointer1); \ EXPECT_FALSE(pointer1 == nullptr); \ \ EXPECT_TRUE(pointer1 != pointer2); \ EXPECT_TRUE(pointer1 != pointer2.get()); \ EXPECT_TRUE(pointer1.get() != pointer2); \ EXPECT_TRUE(pointer1 != nullptr); \ \ EXPECT_TRUE(pointer3 == pointer3); \ EXPECT_TRUE(pointer3 == pointer3.get()); \ EXPECT_TRUE(pointer3.get() == pointer3); \ EXPECT_FALSE(pointer3 == nullptr); \ \ EXPECT_TRUE(pointer3 != pointer4); \ EXPECT_TRUE(pointer3 != pointer4.get()); \ EXPECT_TRUE(pointer3.get() != pointer4); \ EXPECT_TRUE(pointer3 != nullptr); \ \ EXPECT_EQ(pointer1 < pointer2, pointer1.get() < pointer2.get()); \ EXPECT_EQ(pointer1 < pointer2.get(), pointer1.get() < pointer2.get()); \ EXPECT_EQ(pointer1.get() < pointer2, pointer1.get() < pointer2.get()); \ EXPECT_EQ(pointer1 < nullptr, pointer1.get() < nullptr); \ EXPECT_EQ(nullptr < pointer2, nullptr < pointer2.get()); \ \ EXPECT_EQ(pointer3 < pointer4, pointer3.get() < pointer4.get()); \ EXPECT_EQ(pointer3 < pointer4.get(), pointer3.get() < pointer4.get()); \ EXPECT_EQ(pointer3.get() < pointer4, pointer3.get() < pointer4.get()); \ EXPECT_EQ(pointer3 < nullptr, pointer3.get() < nullptr); \ EXPECT_EQ(nullptr < pointer4, nullptr < pointer4.get()); \ \ EXPECT_EQ(pointer1 <= pointer2, pointer1.get() <= pointer2.get()); \ EXPECT_EQ(pointer1 <= pointer2.get(), pointer1.get() <= pointer2.get()); \ EXPECT_EQ(pointer1.get() <= pointer2, pointer1.get() <= pointer2.get()); \ EXPECT_EQ(pointer1 <= nullptr, pointer1.get() <= nullptr); \ EXPECT_EQ(nullptr <= pointer2, nullptr <= pointer2.get()); \ \ EXPECT_EQ(pointer3 <= pointer4, pointer3.get() <= pointer4.get()); \ EXPECT_EQ(pointer3 <= pointer4.get(), pointer3.get() <= pointer4.get()); \ EXPECT_EQ(pointer3.get() <= pointer4, pointer3.get() <= pointer4.get()); \ EXPECT_EQ(pointer3 <= nullptr, pointer3.get() <= nullptr); \ EXPECT_EQ(nullptr <= pointer4, nullptr <= pointer4.get()); \ \ EXPECT_EQ(pointer1 > pointer2, pointer1.get() > pointer2.get()); \ EXPECT_EQ(pointer1 > pointer2.get(), pointer1.get() > pointer2.get()); \ EXPECT_EQ(pointer1.get() > pointer2, pointer1.get() > pointer2.get()); \ EXPECT_EQ(pointer1 > nullptr, pointer1.get() > nullptr); \ EXPECT_EQ(nullptr > pointer2, nullptr > pointer2.get()); \ \ EXPECT_EQ(pointer3 > pointer4, pointer3.get() > pointer4.get()); \ EXPECT_EQ(pointer3 > pointer4.get(), pointer3.get() > pointer4.get()); \ EXPECT_EQ(pointer3.get() > pointer4, pointer3.get() > pointer4.get()); \ EXPECT_EQ(pointer3 > nullptr, pointer3.get() > nullptr); \ EXPECT_EQ(nullptr > pointer4, nullptr > pointer4.get()); \ \ EXPECT_EQ(pointer1 >= pointer2, pointer1.get() >= pointer2.get()); \ EXPECT_EQ(pointer1 >= pointer2.get(), pointer1.get() >= pointer2.get()); \ EXPECT_EQ(pointer1.get() >= pointer2, pointer1.get() >= pointer2.get()); \ EXPECT_EQ(pointer1 >= nullptr, pointer1.get() >= nullptr); \ EXPECT_EQ(nullptr >= pointer2, nullptr >= pointer2.get()); \ \ EXPECT_EQ(pointer3 >= pointer4, pointer3.get() >= pointer4.get()); \ EXPECT_EQ(pointer3 >= pointer4.get(), pointer3.get() >= pointer4.get()); \ EXPECT_EQ(pointer3.get() >= pointer4, pointer3.get() >= pointer4.get()); \ EXPECT_EQ(pointer3 >= nullptr, pointer3.get() >= nullptr); \ EXPECT_EQ(nullptr >= pointer4, nullptr >= pointer4.get()); \ } #define DECLARE_MAKE_SHOULD_CREATE_A_POINTER(pointerClass, method) \ TEST_F(pointerClass##Tests, method##_shouldCreateAPointer) \ { \ pointerClass<int> pointer = method<int>(10); \ \ ASSERT_NE(pointer, nullptr); \ EXPECT_EQ(*pointer, 10); \ } #define DECLARE_MAKE_ARRAY_SHOULD_CREATE_AN_ARRAY(pointerClass, method) \ TEST_F(pointerClass##Tests, method##_shouldCreateAnArray) \ { \ pointerClass<int[]> pointer = method<int>(2); \ pointer[0] = 1; \ pointer[1] = 2; \ \ ASSERT_NE(pointer, nullptr); \ EXPECT_EQ(pointer[0], 1); \ EXPECT_EQ(pointer[1], 2); \ } #endif
2.796875
3
2024-11-18T22:09:27.100247+00:00
2015-03-16T01:59:56
394625b95ba51f13c324ec9791b293bb898b232d
{ "blob_id": "394625b95ba51f13c324ec9791b293bb898b232d", "branch_name": "refs/heads/master", "committer_date": "2015-03-16T01:59:56", "content_id": "469399d1f9f777959804898e56427c8ca5121320", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "468193fe78db697e67cae41a358fcbaa0927090e", "extension": "c", "filename": "latlondist.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 27010110, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3884, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/software/latlondist.c", "provenance": "stackv2-0106.json.gz:34120", "repo_name": "dbtayl/Runner-s-GPS", "revision_date": "2015-03-16T01:59:56", "revision_id": "ad9babdf0279304e4c4305c956ec402b5a841052", "snapshot_id": "ff3dc60b650e580687b3ade5b8edb38ed93ed94a", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/dbtayl/Runner-s-GPS/ad9babdf0279304e4c4305c956ec402b5a841052/software/latlondist.c", "visit_date": "2021-01-01T20:48:07.642139" }
stackv2
/* * Copyright (c) 2015, Daniel Taylor * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Daniel Taylor BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "latlondist.h" //NOTE: Single-precision haversine (regardless of approximations) seems //to over-estimate distance mostly changing in lat, and under-estimate //distance mostly changing in lon, at least for small changes around //where I run. #if DIST_METHOD == DIST_METHOD_HAVERSINE #error You sure you want to use this? //Haversien formula, no sine approximation. Uses floats, so still accumulates //error that way. float distLatLon(float lat0, float lon0, float lat1, float lon1) { lat0 = deg2rad_f(lat0); lon0 = deg2rad_f(lon0); lat1 = deg2rad_f(lat1); lon1 = deg2rad_f(lon1); float dlat = lat1 - lat0; float dlon = lon1 - lon0; double sindlat = sin(dlat/2.0); sindlat *= sindlat; double sindlon = sin(dlon/2.0); sindlon *= sindlon; double a = sindlat + cos(lat0) * cos(lat1) * sindlon; double c = 2 * atan2(sqrt(a), sqrt(1-a)); return WORLD_R * c; } #elif DIST_METHOD == DIST_METHOD_HAVERSINE_APPROX #error You sure you want to use this? //Haversine formula, except approximating sin(x) = x. As this is likely //to only ever deal with small values fed to sine, this works well and //should avoid some excessive calculations float distLatLon(float lat0, float lon0, float lat1, float lon1) { lat0 = deg2rad_f(lat0); lon0 = deg2rad_f(lon0); lat1 = deg2rad_f(lat1); lon1 = deg2rad_f(lon1); float dlat = lat1 - lat0; float dlon = lon1 - lon0; float sindlat = dlat/2.0f; sindlat *= sindlat; float sindlon = dlon/2.0f; sindlon *= sindlon; float a = sindlat + cosf(lat0) * cosf(lat1) * sindlon; float c = 2 * atan2f(sqrtf(a), sqrtf(1-a)); return HAVERSINE_WORLD_R * c; } #elif DIST_METHOD == DIST_METHOD_LINEAR float latf[180]; float lonf[180]; void populateLatLonList() { float lat; int i; for(lat = 0.0f, i=0; lat < 90.0f; lat += 0.5f, i++) { float latmf = LAT_MPD_F(lat * M_PI/180.0f); float lonmf = LON_MPD_F(lat * M_PI/180.0f); latf[i] = latmf; lonf[i] = lonmf; } } //Linear approximation to distance. Works well for small incremental //changes in distance; doesn't use a lot of floating-point calculations float distLatLon(float lat0, float lon0, float lat1, float lon1) { int idx = (int)(abs(lat0) * 2 + 0.5f); float dlat = latf[idx] * (lat1 - lat0); float dlon = lonf[idx] * (lon1 - lon0); return sqrtf(dlat*dlat + dlon*dlon); } #endif
2.21875
2
2024-11-18T22:09:27.335798+00:00
2022-08-10T20:28:43
6f95ea507cd88717abb91b4af359c1e655bc4a2e
{ "blob_id": "6f95ea507cd88717abb91b4af359c1e655bc4a2e", "branch_name": "refs/heads/main", "committer_date": "2022-11-18T03:33:05", "content_id": "98a1d8143b3499f2db0fd5188c27b32950704680", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "c7f3db94cc3d69cd9a2ae24aa3c69cd767b28672", "extension": "c", "filename": "tool.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 523105966, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4848, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/must_rma/src/externals/typeart/demo/tool.c", "provenance": "stackv2-0106.json.gz:34251", "repo_name": "RWTH-HPC/must-rma-correctness22-supplemental", "revision_date": "2022-08-10T20:28:43", "revision_id": "04cb9fe5f0dcb05ea67880209accf19c5e0dda25", "snapshot_id": "10683ff20339098a45a35301dbee6b31d74efaec", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RWTH-HPC/must-rma-correctness22-supplemental/04cb9fe5f0dcb05ea67880209accf19c5e0dda25/must_rma/src/externals/typeart/demo/tool.c", "visit_date": "2023-04-14T20:48:36.684589" }
stackv2
#include <RuntimeInterface.h> #include <mpi.h> #include <stdio.h> int isCompatible(MPI_Datatype mpi_type, typeart_builtin_type recorded_type) { // This comparison is not exhaustive and is only used for this simple demo switch (recorded_type) { case TYPEART_INT8: return mpi_type == MPI_CHAR || mpi_type == MPI_UNSIGNED_CHAR; case TYPEART_INT16: return mpi_type == MPI_SHORT || mpi_type == MPI_UNSIGNED_SHORT; case TYPEART_INT32: return mpi_type == MPI_INT || mpi_type == MPI_UNSIGNED; case TYPEART_INT64: return mpi_type == MPI_LONG || mpi_type == MPI_UNSIGNED_LONG; case TYPEART_FLOAT: return mpi_type == MPI_FLOAT; case TYPEART_DOUBLE: return mpi_type == MPI_DOUBLE; default: break; } return 0; } void analyseBuffer(const void* buf, int count, MPI_Datatype type) { int num_integers, num_addresses, num_datatypes, combiner; PMPI_Type_get_envelope(type, &num_integers, &num_addresses, &num_datatypes, &combiner); // printf("MPI_Type_get_envelope(t,%i,%i,%i,%i)\n", num_integers, num_addresses, num_datatypes, combiner); int array_of_integers[num_integers]; MPI_Aint array_of_addresses[num_addresses]; MPI_Datatype array_of_datatypes[num_datatypes]; if (combiner == MPI_COMBINER_NAMED) { int size; MPI_Type_size(type, &size); char type_name[MPI_MAX_OBJECT_NAME]; int name_len; MPI_Type_get_name(type, type_name, &name_len); printf("Basetype(%s, addr=%p, size=%i , count=%i)\n", type_name, buf, size, count); int type_id; size_t count_check; typeart_status status = typeart_get_type(buf, &type_id, &count_check); if (status == TYPEART_OK) { // If the address corresponds to a struct, fetch the type of the first member while (type_id >= TYPEART_NUM_RESERVED_IDS) { typeart_struct_layout struct_layout; typeart_resolve_type_id(type_id, &struct_layout); type_id = struct_layout.member_types[0]; } // fprintf(stderr, "Type id=%d, name=%s\n", type_info.id, typeart_get_type_name(type_info.id)); if (isCompatible(type, type_id)) { // printf("Types are compatible\n"); } else { const char* recorded_name = typeart_get_type_name(type_id); fprintf(stdout, "[Demo] Error: Incompatible buffer of type %d (%s) - expected %s instead\n", type_id, recorded_name, type_name); } } else { fprintf(stdout, "[Demo] Error: "); if (status == TYPEART_BAD_ALIGNMENT) { fprintf(stdout, "Buffer address does not align with the underlying type at %p\n", buf); } else if (status == TYPEART_UNKNOWN_ADDRESS) { fprintf(stdout, "No buffer allocated at address %p\n", buf); } } return; } MPI_Type_get_contents(type, num_integers, num_addresses, num_datatypes, array_of_integers, array_of_addresses, array_of_datatypes); if (combiner == MPI_COMBINER_RESIZED) { // MPI_TYPE_CREATE_RESIZED int i; MPI_Aint offset; for (i = 0, offset = array_of_addresses[0]; i < count; i++, offset += array_of_addresses[1]) analyseBuffer((void*)((MPI_Aint)buf + offset), 1, array_of_datatypes[0]); return; } if (combiner == MPI_COMBINER_STRUCT) { // MPI_TYPE_CREATE_STRUCT int i, j; MPI_Aint offset, lb, extent; MPI_Type_get_extent(type, &lb, &extent); fprintf(stdout, "Analyzing %d structs:\n", count); for (i = 0, offset = 0; i < count; i++, offset += extent) { for (j = 0; j < array_of_integers[0]; j++) analyseBuffer((void*)((MPI_Aint)buf + offset + array_of_addresses[j]), array_of_integers[j + 1], array_of_datatypes[j]); fprintf(stdout, "\n"); } return; } } int MPI_Sendrecv(const void* sendbuf, int sendcount, MPI_Datatype sendtype, int dest, int sendtag, void* recvbuf, int recvcount, MPI_Datatype recvtype, int source, int recvtag, MPI_Comm comm, MPI_Status* status) { printf("Analyze Send\n"); analyseBuffer(sendbuf, sendcount, sendtype); // analyseBuffer(0, sendcount, sendtype); printf("Analyze Recv\n"); analyseBuffer(recvbuf, recvcount, recvtype); // analyseBuffer(0, recvcount, recvtype); return PMPI_Sendrecv(sendbuf, sendcount, sendtype, dest, sendtag, recvbuf, recvcount, recvtype, source, recvtag, comm, status); } int MPI_Bcast(void* buf, int sendcount, MPI_Datatype sendtype, int root, MPI_Comm comm) { int rank; MPI_Comm_rank(comm, &rank); if (rank == root) { printf("Analyze Send\n"); analyseBuffer(buf, sendcount, sendtype); // analyseBuffer(0, sendcount, sendtype); } else { printf("Analyze Recv\n"); analyseBuffer(buf, sendcount, sendtype); // analyseBuffer(0, recvcount, recvtype); } return PMPI_Bcast(buf, sendcount, sendtype, root, comm); }
2.453125
2
2024-11-18T22:09:27.845151+00:00
2020-03-11T12:08:36
c4977602e87f7f6222941d823f02c893f3c07a23
{ "blob_id": "c4977602e87f7f6222941d823f02c893f3c07a23", "branch_name": "refs/heads/master", "committer_date": "2020-03-11T12:08:36", "content_id": "df6ffcab57c3d0521443a3080744257a493d6a89", "detected_licenses": [ "MIT" ], "directory_id": "10bf15efa69c3dc7be72b93c8edf6444e784388f", "extension": "c", "filename": "handle_errors.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": 558, "license": "MIT", "license_type": "permissive", "path": "/sources/handle_errors.c", "provenance": "stackv2-0106.json.gz:34637", "repo_name": "FaizovR/push_swap", "revision_date": "2020-03-11T12:08:36", "revision_id": "99f33fa29d956094cb4b0d585dd0b3fbab377049", "snapshot_id": "3b0887d05a23ac7dff0cc12ffbbcdc9f2c003e34", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/FaizovR/push_swap/99f33fa29d956094cb4b0d585dd0b3fbab377049/sources/handle_errors.c", "visit_date": "2021-05-24T09:30:09.900014" }
stackv2
#include "../includes/visual.h" #include "../includes/push_swap.h" void ft_handle_error(void) { ft_putstr("Error\n"); exit(0); } void ft_handle_error_lst(t_list *stack_a, t_list *stack_b) { if (stack_a) ft_clear_stack(stack_a); if (stack_b) ft_clear_stack(stack_b); ft_putstr("Error\n"); exit(0); } void del(void *content, size_t content_size) { free(content); content = NULL; content_size = 0; } void stack_init(t_stack *stacks) { stacks->min = 0; stacks->max = 0; stacks->stack_b = NULL; stacks->stack_a = NULL; stacks->v_flag = 0; }
2.25
2
2024-11-18T22:09:27.904265+00:00
2020-12-02T18:56:05
5266375338fd4a93042fd564a3441bd16ef80d21
{ "blob_id": "5266375338fd4a93042fd564a3441bd16ef80d21", "branch_name": "refs/heads/main", "committer_date": "2020-12-02T18:56:05", "content_id": "911003c40c8cd65d4469afaf66544e22148d4f18", "detected_licenses": [ "MIT" ], "directory_id": "be39206892f53feadd34056c3e00cf07ac1f2721", "extension": "c", "filename": "Exercício 5.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 317953030, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 869, "license": "MIT", "license_type": "permissive", "path": "/Atividades em C/Laço de repetição While/Exercício 5.c", "provenance": "stackv2-0106.json.gz:34766", "repo_name": "RodrigoPasini/Programas_C", "revision_date": "2020-12-02T18:56:05", "revision_id": "0e7a64b6e250ac5eed295f647733038953a1d8f7", "snapshot_id": "c26c376c9f0be7c8efcc5ca1b4d4ce79c8541186", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RodrigoPasini/Programas_C/0e7a64b6e250ac5eed295f647733038953a1d8f7/Atividades em C/Laço de repetição While/Exercício 5.c", "visit_date": "2023-01-23T04:49:10.230297" }
stackv2
#include<stdio.h> #include<stdlib.h> int main (void) { int maior, segundo_maior, num, count=3; printf("Digite um numero:"); scanf("%d", &maior); printf("Digite um numero:"); scanf("%d", &num); if(maior > num) segundo_maior = num; else { segundo_maior = maior; maior = num; } while (count <= 10) { printf("Digite um numero:"); scanf("%d", &num); if(num > maior) { segundo_maior = maior; maior = num; } else if(num > segundo_maior) segundo_maior = num; count++; } printf("Maior: %d\n", maior); printf("Segundo maior: %d\n", segundo_maior); system ("pause"); return (0); }
3.1875
3
2024-11-18T22:09:32.315592+00:00
2016-05-02T17:57:11
a3f589877da183d6c6d48dad1ba5afe00493cf10
{ "blob_id": "a3f589877da183d6c6d48dad1ba5afe00493cf10", "branch_name": "refs/heads/master", "committer_date": "2016-05-02T17:57:11", "content_id": "23d65c76a986da909881dbba2b8d638704a7db92", "detected_licenses": [ "Apache-2.0" ], "directory_id": "141ae904ff93303a8153c7f6bb083ea7068cb97e", "extension": "c", "filename": "parser.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": 19877, "license": "Apache-2.0", "license_type": "permissive", "path": "/mess/IFJ-Interpreter/parser.c", "provenance": "stackv2-0106.json.gz:35923", "repo_name": "romanyaremchuk/FIT-VUT", "revision_date": "2016-05-02T17:57:11", "revision_id": "bb6f7f6eb1fea1f13952e0ab463e5aa69a84084c", "snapshot_id": "d76f6774e701138a70e11e49b51b70e2382b11b6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/romanyaremchuk/FIT-VUT/bb6f7f6eb1fea1f13952e0ab463e5aa69a84084c/mess/IFJ-Interpreter/parser.c", "visit_date": "2021-06-08T11:26:20.228412" }
stackv2
/** * Predmet: IFJ / IAL * Projekt: Implementace interpretu jazyka PHP13 * Varianta: a/1/I * Soubor: parser.c * * Popis: * * * Datum: 28.11.2013 * * Autori: Frantisek Kolacek <xkolac12@stud.fit.vutbr.cz> * Stodulka Daniel * Hermann Lukas * Tran Manh Hoang */ #include "parser.h" //Hlavni funkce parseru ERROR parser(SYMBOL_TABLE_PTR st){ ERROR err; if(getToken() != TTYPE_PHP_START) return E_SYNTAX; err = parserFindFunctions(st); if(err != E_OK) return err; init_Token(); if(getToken() != TTYPE_PHP_START) return E_SYNTAX; return parserParse(st); } //Vyhleda definice funkci ERROR parserFindFunctions(SYMBOL_TABLE_PTR st){ fprintf(stderr,"Finding function definitions:\n"); enum_RetVal retval; init_Token(); while((retval = getToken()) != TTYPE_EOF){ //fprintf(stderr,"Token: %s\n", glob_Token.data.data); if(retval == TTYPE_KEYWORD && strCompare(glob_Token.data, "function")){ retval = getToken(); if(retval == TTYPE_FUNCTION){ fprintf(stderr,"- %s\n", glob_Token.data.data); if(stSearchFunction(st, glob_Token.data)) return E_SEMANTIC; stInsertFunction(st, glob_Token.data); st->curr = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; parserParseFunctionParam(st, true); } else if(retval == TTYPE_RESERVED) return E_SEMANTIC; else return E_SYNTAX; } else if(retval == TTYPE_ERROR) return E_SYNTAX; } free_Token(); return E_OK; } //Funkce pro druhe parsovani ERROR parserParse(SYMBOL_TABLE_PTR st){ ERROR err = E_OK; st->curr = &st->start; enum_RetVal retval = getToken(); if(retval == TTYPE_EOF) return err; else if(retval == TTYPE_KEYWORD && strCompare(glob_Token.data, "function")){ err = parserParseFunction(st); if(err != E_OK) return err; return parserParse(st); } else{ err = parserParseCode(st, retval); if(err != E_OK) return err; return parserParse(st); } } //Parsovani definice funkce //function id (<params>){ <code> } ERROR parserParseFunction(SYMBOL_TABLE_PTR st){ fprintf(stderr,"Parsing definition function\n"); ERROR err = E_OK; if(getToken() != TTYPE_FUNCTION) return E_SYNTAX; st->curr = stSearchFunction(st, glob_Token.data); if(!st->curr) return E_COMPILATOR; fprintf(stderr,"Change current function to %s\n", st->curr->id.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseFunctionParam(st, false); if(err != E_OK) return err; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_NOP, NULL, NULL, NULL)); if(getToken() != TTYPE_L_BRACE) return E_SYNTAX; err = parserParseFunctionCode(st); return err; } //Parsovani parametru definice funkce (0-1) // <params> - id <params_n> // <params> - eps ERROR parserParseFunctionParam(SYMBOL_TABLE_PTR st, bool test){ fprintf(stderr,"Parsing function %s definition param\n", st->curr->id.data); enum_RetVal retval = getToken(); if(retval == TTYPE_R_BRACKET) return E_OK; else if(retval == TTYPE_VARIABLE){ //Stejny nazev parametru a funkce - ale nemozne v PHP //if(stSearchFunction(st, glob_Token.data)) // return E_SEMANTIC; if(test) st->curr->argumentsCount++; else{ stInsertSymbol(st->curr, glob_Token.data); listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_POP, stGetLastSymbol(st->curr), NULL, NULL)); } return parserParseFunctionParams(st, test); } else return E_SYNTAX; } //Parsovani parametru definice funkce (2+) // <params_n> - , id <params_n> // <params_n> - eps ERROR parserParseFunctionParams(SYMBOL_TABLE_PTR st, bool test){ fprintf(stderr,"Parsing function definition params\n"); enum_RetVal retval = getToken(); if(retval == TTYPE_R_BRACKET) return E_OK; else if(retval == TTYPE_COMMA){ retval = getToken(); if(retval == TTYPE_VARIABLE){ //Stejny nazev parametru a funkce - ale nemozne v PHP //if(stSearchFunction(st, glob_Token.data)) // return E_SEMANTIC; if(test) st->curr->argumentsCount++; else{ //Stejny nazev dvou parametru if(stSearchSymbol(st->curr, glob_Token.data)) //return E_SEMANTIC; return E_SEMANTIC_OTHER; stInsertSymbol(st->curr, glob_Token.data); listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_POP, stGetLastSymbol(st->curr), NULL, NULL)); st->curr->argumentsCount++; } return parserParseFunctionParams(st, test); } else return E_SYNTAX; } else return E_SYNTAX; } //Parsovani tela definice funkce // <code> - eps // <code> - <command> <code> ERROR parserParseFunctionCode(SYMBOL_TABLE_PTR st){ fprintf(stderr,"Parsing function code\n"); enum_RetVal retval = getToken(); if(retval == TTYPE_R_BRACE) return E_OK; //else if(retval == TTYPE_ELSE) // po ifu musi byt vzdy else // return E_SYNTAX; else{ fprintf(stderr,"Parsing function body\n"); ERROR err = parserParseCode(st, retval); if(err == E_OK) return parserParseFunctionCode(st); else return err; } } //Parsovani prikazu ERROR parserParseCode(SYMBOL_TABLE_PTR st, enum_RetVal retval){ fprintf(stderr,"Parsing code [%d]: %s\n", retval, glob_Token.data.data); ERROR err = E_OK; INSTRUCTION_PTR i1, i2, i3; SYMBOL_PTR symbol; switch(retval){ case TTYPE_VARIABLE: fprintf(stderr,"Found variable: %s\n", glob_Token.data.data); if(!stSearchSymbol(st->curr, glob_Token.data)) stInsertSymbol(st->curr, glob_Token.data); SYMBOL_PTR tmpSymbol = stSearchSymbol(st->curr, glob_Token.data); //Stejny nazev parametru a funkce - ale nemozne v PHP //if(!stSearchFunction(st, glob_Token.data)) // return E_SEMANTIC; retval = getToken(); //Prazdny prikaz if(retval == TTYPE_SEMICOLON) return E_OK; else if(retval != TTYPE_ASSIGN) return E_SYNTAX; else{ //DEBUG FILGY fprintf(stderr,"Found assign and last symbol was: %s\n", tmpSymbol->id); //err = parserControlAssign(st, stGetLastSymbol(st->curr)); err = parserControlAssign(st, tmpSymbol); if(err != E_OK) return err; } break; //FILGY-TODO - samotne volani funkce case TTYPE_FUNCTION: fprintf(stderr,"Found function: %s\n", glob_Token.data.data); fprintf(stderr, "FILGY-TODO: samotne volani funkce\n"); break; case TTYPE_KEYWORD: fprintf(stderr,"Found keyword: %s\n", glob_Token.data.data); //if(<expression>){ <code> }else{ <code> } if(strCompare(glob_Token.data, "if")){ if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; retval = getToken(); //Parsovani podminky err = parserExpression(st, retval, &symbol); if(err != E_OK) return err; // Jump na else listInsertEnd(&st->curr->instructions, (i1 = makeInstruction(INSTRUCTION_IF_JUMP, NULL, symbol, NULL))); if(getToken() != TTYPE_L_BRACE) return E_SYNTAX; // Parsovani tela podminky err = parserParseFunctionCode(st); if(err != E_OK) return err; //Jump na konec else listInsertEnd(&st->curr->instructions, (i2 = makeInstruction(INSTRUCTION_JUMP, NULL, NULL, NULL))); // Navesti pro else listInsertEnd(&st->curr->instructions, (i3 = makeInstruction(INSTRUCTION_LABEL, NULL, NULL, NULL))); i1->destionation = st->curr->instructions.end; if(getToken() != TTYPE_KEYWORD || !strCompare(glob_Token.data, "else")) return E_SYNTAX; fprintf(stderr,"Found else\n"); if(getToken() != TTYPE_L_BRACE) return E_SYNTAX; err = parserParseFunctionCode(st); if(err != E_OK) return err; // Navesti pro konec else listInsertEnd(&st->curr->instructions, (i3 = makeInstruction(INSTRUCTION_LABEL, NULL, NULL, NULL))); i2->destionation = st->curr->instructions.end; fprintf(stderr, "If/else completed\n"); } // //while(<expression>){ <code> } else if(strCompare(glob_Token.data, "while")){ i2 = makeInstruction(INSTRUCTION_JUMP, NULL, NULL, NULL); i3 = makeInstruction(INSTRUCTION_LABEL, NULL, NULL, NULL); listInsertEnd(&st->curr->instructions, i3); i2->destionation = st->curr->instructions.end; if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; retval = getToken(); //Parsovani podminky err = parserExpression(st, retval, &symbol); if(err != E_OK) return err; i1 = makeInstruction(INSTRUCTION_IF_JUMP, NULL, symbol, NULL); listInsertEnd(&st->curr->instructions, i1); if(getToken() != TTYPE_L_BRACE) return E_SYNTAX; //Parsovani tela cyklu err = parserParseFunctionCode(st); if(err != E_OK) return err; listInsertEnd(&st->curr->instructions, i2); i3 = makeInstruction(INSTRUCTION_LABEL, NULL, NULL, NULL); listInsertEnd(&st->curr->instructions, i3); i1->destionation = st->curr->instructions.end; fprintf(stderr, "While completed\n"); } //return expression; else if(strCompare(glob_Token.data, "return")){ retval = getToken(); //EDIT err = parserExpression(st, retval, &symbol); if(err != E_OK) return err; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_PUSH, symbol, NULL, NULL)); listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_RETURN, NULL, NULL, NULL)); //if(getToken() != TTYPE_SEMICOLON) // return E_SYNTAX; } else return E_SYNTAX; break; default: fprintf(stderr,"[debug] SYNTAX ERROR: [%s] %s\n", debugRetval(retval), glob_Token.data.data); return E_SYNTAX; } return err; } // <assign> - expression // <assign> - id(<params>) // <assign> - boolval(<term>) // <assign> - doubleval(<term>) // <assign> - intval(<term>) // <assign> - strval(<term>) // <assign> - get_string() // <assign> - put_string(<term>) // <assign> - strlen(<term>) // <assign> - get_substring(<term>,<num>,<num>) // <assign> - find_string(string, string) // <assign> - sort_string(string) ERROR parserControlAssign(SYMBOL_TABLE_PTR st, SYMBOL_PTR symbol){ fprintf(stderr,"Control assign\n"); ERROR err = E_OK; enum_RetVal retval = getToken(); FUNCTION_PTR f = NULL; SYMBOL_PTR tmp = NULL; switch(retval){ case TTYPE_RESERVED: if(strCompare(glob_Token.data, "boolval")){ fprintf(stderr," - assign lib boolval\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_BOOLVAL, symbol, NULL, NULL)); } else if(strCompare(glob_Token.data, "doubleval")){ fprintf(stderr," - assign lib boolval\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_DOUBLEVAL, symbol, NULL, NULL)); } else if(strCompare(glob_Token.data, "intval")){ fprintf(stderr," - assign lib intval\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_INTVAL, symbol, NULL, NULL)); fprintf(stderr, "DELL intval push symbol: %d\n", symbol); } else if(strCompare(glob_Token.data, "strval")){ fprintf(stderr," - assign lib strval\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_STRVAL, symbol, NULL, NULL)); } else if(strCompare(glob_Token.data, "get_string")){ fprintf(stderr," - assign lib get_string\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_GET_STRING, symbol, NULL, NULL)); fprintf(stderr, "DELL get_string push symbol: %d\n", symbol); } else if(strCompare(glob_Token.data, "put_string")){ fprintf(stderr," - assign lib put_string\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; int* tmpCount = gcMalloc(sizeof(int)); *tmpCount = f->argumentsCalled; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_PUT_STRING, symbol, tmpCount, NULL)); f->argumentsCalled = 0; } else if(strCompare(glob_Token.data, "strlen")){ fprintf(stderr," - assign lib strlen\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_STRLEN, symbol,NULL, NULL)); } else if(strCompare(glob_Token.data, "get_substring")){ fprintf(stderr," - assign lib get_substring\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_GET_SUBSTRING, symbol, NULL, NULL)); } else if(strCompare(glob_Token.data, "find_string")){ fprintf(stderr," - assign lib find_string\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_FIND_STRING, symbol, NULL, NULL)); } else if(strCompare(glob_Token.data, "sort_string")){ fprintf(stderr," - assign lib sort_string\n"); f = stSearchFunction(st, glob_Token.data); if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) //weak return E_SYNTAX; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_SORT_STRING, symbol, NULL, NULL)); } else return E_SYNTAX; break; // variable + 5 case TTYPE_VARIABLE: fprintf(stderr," - assign variable\n"); err = parserExpression(st, retval, &tmp); if(err != E_OK) return err; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_MOV, symbol, tmp, NULL)); //printf("DEBUG: %d\n", tmp->type); //HOTFIX BY FILGY //if(!tmp->filgy) // return E_SEMANTIC_UNDECLARED; fprintf(stderr," - assign variable completed\n"); break; // funkce(x) case TTYPE_FUNCTION: fprintf(stderr," - assign function\n"); if(!(f = stSearchFunction(st, glob_Token.data))) return E_SEMANTIC; if(getToken() != TTYPE_L_BRACKET) return E_SYNTAX; err = parserParseCallParam(st, f); if(err != E_OK) return err; if(getToken() != TTYPE_SEMICOLON) return E_SYNTAX; if(f->argumentsCount != f->argumentsCalled){ fprintf(stderr, " - error call function %s - arguments required %d, passed %d\n", f->id.data, f->argumentsCount, f->argumentsCalled); return E_SEMANTIC_MISS_PARAM; } f->argumentsCalled = 0; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_CALL, f, NULL, NULL)); listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_POP, symbol, NULL, NULL)); fprintf(stderr," - assign function completed\n"); break; //string case TTYPE_STRING: fprintf(stderr," - assign string\n"); err = parserExpression(st, retval, &tmp); if(err != E_OK) return err; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_MOV, symbol, tmp, NULL)); //assert(tmp->id.data && tmp->items); fprintf(stderr," - assign function completed\n"); break; default: fprintf(stderr," - assign default: %s\n", glob_Token.data.data); err = parserExpression(st, retval, &tmp); if(err != E_OK) return err; listInsertEnd(&st->curr->instructions, makeInstruction(INSTRUCTION_MOV, symbol, tmp, NULL)); // //assert(tmp->id.data && tmp->items); fprintf(stderr," - assign default completed\n"); break; } return err; } ERROR parserParseCallParam(SYMBOL_TABLE_PTR st, FUNCTION_PTR f){ enum_RetVal retval = getToken(); SYMBOL_PTR symbol = NULL; //Bez parametru if(retval == TTYPE_R_BRACKET) return E_OK; listEnd(&st->curr->instructions); if(retval == TTYPE_VARIABLE){ if(!stSearchSymbol(st->curr, glob_Token.data)) return E_SEMANTIC_UNDECLARED; symbol = stSearchSymbol(st->curr, glob_Token.data); stInsertStaticValue(st->curr, glob_Token.data, retval, &symbol); fprintf(stderr, "DELL call function with symbol: %d - %s\n", symbol, symbol->id); } else if( retval == TTYPE_NUMBER || retval == TTYPE_DEC_NUMBER || retval == TTYPE_TRUE || retval == TTYPE_FALSE || retval == TTYPE_NULL || retval == TTYPE_STRING ) stInsertStaticValue(st->curr, glob_Token.data, retval, &symbol); else return E_SYNTAX; listInsertPost(&st->curr->instructions, makeInstruction(INSTRUCTION_PUSH, symbol, NULL, NULL)); if(f) f->argumentsCalled++; return parserParseCallParams(st, f); } ERROR parserParseCallParams(SYMBOL_TABLE_PTR st, FUNCTION_PTR f){ enum_RetVal retval = getToken(); SYMBOL_PTR symbol = NULL; listEnd(&st->curr->instructions); //Bez dalsich parametru if(retval == TTYPE_R_BRACKET) return E_OK; //Parametry oddelene carkou if(retval != TTYPE_COMMA) return E_SYNTAX; retval = getToken(); if(retval == TTYPE_VARIABLE){ if(!stSearchSymbol(st->curr, glob_Token.data)) return E_SEMANTIC_UNDECLARED; symbol = stSearchSymbol(st->curr, glob_Token.data); stInsertStaticValue(st->curr, glob_Token.data, retval, &symbol); fprintf(stderr, "DELL call function with symbol: %d - %s\n", symbol, symbol->id); } else if( retval == TTYPE_NUMBER || retval == TTYPE_DEC_NUMBER || retval == TTYPE_TRUE || retval == TTYPE_FALSE || retval == TTYPE_NULL || retval == TTYPE_STRING ) stInsertStaticValue(st->curr, glob_Token.data, retval, &symbol); else return E_SYNTAX; listInsertPost(&st->curr->instructions, makeInstruction(INSTRUCTION_PUSH, symbol, NULL, NULL)); if(f) f->argumentsCalled++; return parserParseCallParams(st, f); }
2.640625
3
2024-11-18T22:09:32.394586+00:00
2018-07-20T10:03:23
dd28f5836a9de2eb7aa33c924fa04b088181b23c
{ "blob_id": "dd28f5836a9de2eb7aa33c924fa04b088181b23c", "branch_name": "refs/heads/master", "committer_date": "2018-07-20T10:03:23", "content_id": "56cb97d7229653004c5b2a1cebaa744a0894858e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "fde5cbb16880e4ba79ce93fe48ab26be6234878b", "extension": "c", "filename": "coils_old.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 46204479, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 27275, "license": "Apache-2.0", "license_type": "permissive", "path": "/coils/coils_old.c", "provenance": "stackv2-0106.json.gz:36051", "repo_name": "orionzhou/rgeneclust", "revision_date": "2018-07-20T10:03:23", "revision_id": "e40e0fe201e509ff8307153cfad18449f511dd86", "snapshot_id": "5275bf6ce2d9441e962094b802d38663782b63c9", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/orionzhou/rgeneclust/e40e0fe201e509ff8307153cfad18449f511dd86/coils/coils_old.c", "visit_date": "2021-01-19T04:24:50.837959" }
stackv2
/* Program COILS version 2.1 */ /* written by J.Lupas, 22 JUN 1993 */ /* edited on 15 JAN 1994 */ /* revised and corrected 4 APR 1994 */ /* incorporates the option to use either the old MTK chart or the new MTIDK chart AND the choice of weighting positions a & d more (2.5 times) */ /* 4 output options: - probabilities for window sizes 14, 21 & 28 in columns, - probabilities for window sizes 14, 21 & 28 in rows, - scores only for a user-input window size, or - the probabilities above a user-input cutoff. Requests input and output files from user. */ /* transferred to c++ by Larry Harvie, harvie@owl.WPI.EDU */ /* adapted to C by Reinhard Schneider, SCHNEIDER@EMBL-Heidelberg.DE */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef FILE *text; typedef double chartstore[21][8]; typedef char residuestore[10001]; typedef double calcstore[4][10001]; typedef int heptadstore[4][10001]; int window; char inputfile[80],outputfile[80]; text protein,pickup; chartstore chartvalue; /* probability values */ residuestore residue; /* stores amino acid sequence */ heptadstore heptnum; /* stores heptad position number */ calcstore calcnumb; /* stores best scores */ int res_total; /* total no. of residues in protein */ char junkline[9000]; /* reads opening protein info. */ char nameprot[9000]; int nomore; /* in case there's junk after last protein */ short windows; double winheight; char option,chartchar,weightchar; double ad_weight; int hept_weight; calcstore tempcalc; heptadstore temphept; char fr14[10001],fr21[10001],fr28[10001]; int pr14[10001],pr21[10001],pr28[10001]; short mod(short x,short y) { double x1=(double) x,y1=(double) y; return (short) floor(fmod(x,y)); } void Init_newchart() /* store the probability values for each of the 20 amino acids to occur in each of the heptad positions */ { chartvalue[1][1]=2.998; chartvalue[1][2]=0.269; chartvalue[1][3]=0.367; chartvalue[1][4]=3.852; chartvalue[1][5]=0.510; chartvalue[1][6]=0.514; chartvalue[1][7]=0.562; chartvalue[2][1]=2.408; chartvalue[2][2]=0.261; chartvalue[2][3]=0.345; chartvalue[2][4]=0.931; chartvalue[2][5]=0.402; chartvalue[2][6]=0.440; chartvalue[2][7]=0.289; chartvalue[3][1]=1.525; chartvalue[3][2]=0.479; chartvalue[3][3]=0.350; chartvalue[3][4]=0.887; chartvalue[3][5]=0.286; chartvalue[3][6]=0.350; chartvalue[3][7]=0.362; chartvalue[4][1]=2.161; chartvalue[4][2]=0.605; chartvalue[4][3]=0.442; chartvalue[4][4]=1.441; chartvalue[4][5]=0.607; chartvalue[4][6]=0.457; chartvalue[4][7]=0.570; chartvalue[5][1]=0.490; chartvalue[5][2]=0.075; chartvalue[5][3]=0.391; chartvalue[5][4]=0.639; chartvalue[5][5]=0.125; chartvalue[5][6]=0.081; chartvalue[5][7]=0.038; chartvalue[6][1]=1.319; chartvalue[6][2]=0.064; chartvalue[6][3]=0.081; chartvalue[6][4]=1.526; chartvalue[6][5]=0.204; chartvalue[6][6]=0.118; chartvalue[6][7]=0.096; chartvalue[7][1]=0.084; chartvalue[7][2]=0.215; chartvalue[7][3]=0.432; chartvalue[7][4]=0.111; chartvalue[7][5]=0.153; chartvalue[7][6]=0.367; chartvalue[7][7]=0.125; chartvalue[8][1]=1.283; chartvalue[8][2]=1.364; chartvalue[8][3]=1.077; chartvalue[8][4]=2.219; chartvalue[8][5]=0.490; chartvalue[8][6]=1.265; chartvalue[8][7]=0.903; chartvalue[9][1]=1.233; chartvalue[9][2]=2.194; chartvalue[9][3]=1.817; chartvalue[9][4]=0.611; chartvalue[9][5]=2.095; chartvalue[9][6]=1.686; chartvalue[9][7]=2.027; chartvalue[10][1]=1.014; chartvalue[10][2]=1.476; chartvalue[10][3]=1.771; chartvalue[10][4]=0.114; chartvalue[10][5]=1.667; chartvalue[10][6]=2.006; chartvalue[10][7]=1.844; chartvalue[11][1]=0.590; chartvalue[11][2]=0.646; chartvalue[11][3]=0.584; chartvalue[11][4]=0.842; chartvalue[11][5]=0.307; chartvalue[11][6]=0.611; chartvalue[11][7]=0.396; chartvalue[12][1]=0.281; chartvalue[12][2]=3.351; chartvalue[12][3]=2.998; chartvalue[12][4]=0.789; chartvalue[12][5]=4.868; chartvalue[12][6]=2.735; chartvalue[12][7]=3.812; chartvalue[13][1]=0.068; chartvalue[13][2]=2.103; chartvalue[13][3]=1.646; chartvalue[13][4]=0.182; chartvalue[13][5]=0.664; chartvalue[13][6]=1.581; chartvalue[13][7]=1.401; chartvalue[14][1]=0.311; chartvalue[14][2]=2.290; chartvalue[14][3]=2.330; chartvalue[14][4]=0.811; chartvalue[14][5]=2.596; chartvalue[14][6]=2.155; chartvalue[14][7]=2.585; chartvalue[15][1]=1.231; chartvalue[15][2]=1.683; chartvalue[15][3]=2.157; chartvalue[15][4]=0.197; chartvalue[15][5]=1.653; chartvalue[15][6]=2.430; chartvalue[15][7]=2.065; chartvalue[16][1]=0.332; chartvalue[16][2]=0.753; chartvalue[16][3]=0.930; chartvalue[16][4]=0.424; chartvalue[16][5]=0.734; chartvalue[16][6]=0.801; chartvalue[16][7]=0.518; chartvalue[17][1]=0.197; chartvalue[17][2]=0.543; chartvalue[17][3]=0.647; chartvalue[17][4]=0.680; chartvalue[17][5]=0.905; chartvalue[17][6]=0.643; chartvalue[17][7]=0.808; chartvalue[18][1]=0.918; chartvalue[18][2]=0.002; chartvalue[18][3]=0.385; chartvalue[18][4]=0.440; chartvalue[18][5]=0.138; chartvalue[18][6]=0.432; chartvalue[18][7]=0.079; chartvalue[19][1]=0.066; chartvalue[19][2]=0.064; chartvalue[19][3]=0.065; chartvalue[19][4]=0.747; chartvalue[19][5]=0.006; chartvalue[19][6]=0.115; chartvalue[19][7]=0.014; chartvalue[20][1]=0.004; chartvalue[20][2]=0.108; chartvalue[20][3]=0.018; chartvalue[20][4]=0.006; chartvalue[20][5]=0.010; chartvalue[20][6]=0.004; chartvalue[20][7]=0.007; } void Init_oldchart() { chartvalue[1][1]=3.167; chartvalue[1][2]=0.297; chartvalue[1][3]=0.398; chartvalue[1][4]=3.902; chartvalue[1][5]=0.585; chartvalue[1][6]=0.501; chartvalue[1][7]=0.483; chartvalue[2][1]=2.597; chartvalue[2][2]=0.098; chartvalue[2][3]=0.345; chartvalue[2][4]=0.894; chartvalue[2][5]=0.514; chartvalue[2][6]=0.471; chartvalue[2][7]=0.431; chartvalue[3][1]=1.665; chartvalue[3][2]=0.403; chartvalue[3][3]=0.386; chartvalue[3][4]=0.949; chartvalue[3][5]=0.211; chartvalue[3][6]=0.342; chartvalue[3][7]=0.360; chartvalue[4][1]=2.240; chartvalue[4][2]=0.37; chartvalue[4][3]=0.480; chartvalue[4][4]=1.409; chartvalue[4][5]=0.541; chartvalue[4][6]=0.772; chartvalue[4][7]=0.663; chartvalue[5][1]=0.531; chartvalue[5][2]=0.076; chartvalue[5][3]=0.403; chartvalue[5][4]=0.662; chartvalue[5][5]=0.189; chartvalue[5][6]=0.106; chartvalue[5][7]=0.013; chartvalue[6][1]=1.417; chartvalue[6][2]=0.090; chartvalue[6][3]=0.122; chartvalue[6][4]=1.659; chartvalue[6][5]=0.19; chartvalue[6][6]=0.13; chartvalue[6][7]=0.1550; chartvalue[7][1]=0.045; chartvalue[7][2]=0.275; chartvalue[7][3]=0.578; chartvalue[7][4]=0.216; chartvalue[7][5]=0.211; chartvalue[7][6]=0.426; chartvalue[7][7]=0.156; chartvalue[8][1]=1.297; chartvalue[8][2]=1.551; chartvalue[8][3]=1.084; chartvalue[8][4]=2.612; chartvalue[8][5]=0.377; chartvalue[8][6]=1.248; chartvalue[8][7]=0.877; chartvalue[9][1]=1.375; chartvalue[9][2]=2.639; chartvalue[9][3]=1.763; chartvalue[9][4]=0.191; chartvalue[9][5]=1.815; chartvalue[9][6]=1.961; chartvalue[9][7]=2.795; chartvalue[10][1]=0.659; chartvalue[10][2]=1.163; chartvalue[10][3]=1.210; chartvalue[10][4]=0.031; chartvalue[10][5]=1.358; chartvalue[10][6]=1.937; chartvalue[10][7]=1.798; chartvalue[11][1]=0.347; chartvalue[11][2]=0.275; chartvalue[11][3]=0.679; chartvalue[11][4]=0.395; chartvalue[11][5]=0.294; chartvalue[11][6]=0.579; chartvalue[11][7]=0.213; chartvalue[12][1]=0.262; chartvalue[12][2]=3.496; chartvalue[12][3]=3.108; chartvalue[12][4]=0.998; chartvalue[12][5]=5.685; chartvalue[12][6]=2.494; chartvalue[12][7]=3.048; chartvalue[13][1]=0.03; chartvalue[13][2]=2.352; chartvalue[13][3]=2.268; chartvalue[13][4]=0.237; chartvalue[13][5]=0.663; chartvalue[13][6]=1.62; chartvalue[13][7]=1.448; chartvalue[14][1]=0.179; chartvalue[14][2]=2.114; chartvalue[14][3]=1.778; chartvalue[14][4]=0.631; chartvalue[14][5]=2.55; chartvalue[14][6]=1.578; chartvalue[14][7]=2.526; chartvalue[15][1]=0.835; chartvalue[15][2]=1.475; chartvalue[15][3]=1.534; chartvalue[15][4]=0.039; chartvalue[15][5]=1.722; chartvalue[15][6]=2.456; chartvalue[15][7]=2.280; chartvalue[16][1]=0.382; chartvalue[16][2]=0.583; chartvalue[16][3]=1.052; chartvalue[16][4]=0.419; chartvalue[16][5]=0.525; chartvalue[16][6]=0.916; chartvalue[16][7]=0.628; chartvalue[17][1]=0.169; chartvalue[17][2]=0.702; chartvalue[17][3]=0.955; chartvalue[17][4]=0.654; chartvalue[17][5]=0.791; chartvalue[17][6]=0.843; chartvalue[17][7]=0.647; chartvalue[18][1]=0.824; chartvalue[18][2]=0.022; chartvalue[18][3]=0.308; chartvalue[18][4]=0.152; chartvalue[18][5]=0.180; chartvalue[18][6]=0.156; chartvalue[18][7]=0.044; chartvalue[19][1]=0.24; chartvalue[19][2]=0; chartvalue[19][3]=0.00; chartvalue[19][4]=0.456; chartvalue[19][5]=0.019; chartvalue[19][6]=0.00; chartvalue[19][7]=0.00; chartvalue[20][1]=0.00; chartvalue[20][2]=0.008; chartvalue[20][3]=0; chartvalue[20][4]=0.013; chartvalue[20][5]=0.0; chartvalue[20][6]=0; chartvalue[20][7]=0; } void Get_info() { char junk; printf("COILS version 2.1\n"); printf("ENTER INPUT FILE: "); fflush(stdout); scanf("%s",inputfile); printf("-->%s\n",inputfile); protein=fopen(inputfile,"r"); /* modify for reading */ if (protein==NULL) { perror("problem"); printf("'%s' can not be found. Try again after verifying the file name.\n",inputfile); exit(0); } /* endif */ printf("ENTER OUTPUT FILE: "); scanf("%s",outputfile); pickup=fopen(outputfile,"w"); if (pickup==NULL) { printf("The system could not open the output file\n"); printf(". Check the free space on disk\n"); exit(0); } /* endif */ printf("Two scoring matrices are available:\n"); printf(" 1 - MTK\n"); printf(" 2 - MTIDK\n"); printf("Which matix? (1|2) <enter>? "); chartchar='\0'; while ((chartchar!='1') && (chartchar!='2') && (chartchar!=(char) 13)) scanf("%c",&chartchar); printf("Do you want a weight of 2.5 for positions a & d? (Y|N) <enter>? "); weightchar='\0'; while ((weightchar!='n') && (weightchar!='y') && (weightchar!='Y') && (weightchar!='N') && (weightchar!=(char) 13)) scanf("%c",&weightchar); fprintf(pickup,"COILS version 2.1\n"); if (chartchar=='2') { fprintf(pickup,"using MTIDK matrix.\n"); Init_newchart(); } else { fprintf(pickup,"using MTK matrix.\n"); Init_oldchart(); } if ((weightchar=='y') || (weightchar=='Y')) { fprintf(pickup,"weights: a,d=2.5 and b,c,e,f,g=1.0\n"); hept_weight=10; ad_weight=2.5; } else { fprintf(pickup,"no weights\n"); hept_weight=7; ad_weight=1.0; } fprintf(pickup,"Input file is %s\n",inputfile); } void Select_option() { printf("OUTPUT OPTIONS:\n"); printf(" p - probabilities in columns\n"); printf(" a - probabilities in rows, abbreviated to the first digit\n"); printf(" b - scores (size of the scanning window defined by the user)\n"); printf(" c - only probabilities above a user-defined cutoff\n"); printf("ENTER OPTION: "); while ((option!='a') && (option!='b') && (option!='c') && (option!='A') && (option!='B') && (option!='C') && (option!='p') && (option!='P')) { scanf("%c",&option); } /* endwhile */ printf("\n"); if ((option=='b') || (option=='B')) { printf("ENTER WINDOW SIZE: "); scanf("%d",&window); } /* end */ else window=14; } int checkforend() { int junklen; char *last4; int checkforend=0; junkline[strlen(junkline)-1]='\0'; junklen=strlen(junkline); if (junklen > 0) { if (junkline[0] == '>') checkforend=1; strcpy(nameprot,junkline); } if (junklen > 3) { last4=(char *) &(junkline[junklen-4]); if (strcmp(last4," ..")==0) { checkforend=1; strcpy(nameprot,junkline); } } return checkforend; } void Skip_opening_info() /* Skip opening lines of protein to get to amino acid sequence */ { int endingfound; endingfound=checkforend(); while (!endingfound) { if (!feof(protein)) { fgets(junkline,9999,protein); endingfound=checkforend(); } else { strcpy(nameprot," "); fclose(protein); protein=fopen(inputfile,"r"); endingfound=1; } /* endif */ } /* endwhile */ } void Store_residues() /* stores only the amino acids of the sequence, skipping numbers, blanks, and carriage returns and ending with '/' || '*' */ { char tempstore; int validaa; res_total=0; tempstore=fgetc(protein); while ((tempstore != '/') && (tempstore != '*') && (!feof(protein))) { switch (tempstore & 95) { case 'L': case 'I': case 'V': case 'M': case 'F': case 'Y': case 'G': case 'A': case 'K': case 'P': case 'R': case 'H': case 'E': case 'D': case 'Q': case 'N': case 'S': case 'T': case 'C': case 'W': validaa=1; break; default: validaa=0; break; } /* endswitch */ if (validaa) { res_total=res_total+1; residue[res_total]=tempstore; } /* endif */ tempstore=fgetc(protein); } /* endwhile */ if (tempstore == '/') fgets(junkline,9999,protein); /* read other '/' at end */ } int Getx(char res) { int X; switch (res & (char) 95) { case 'L': X=1; break; case 'I': X=2; break; case 'V': X=3; break; case 'M': X=4; break; case 'F': X=5; break; case 'Y': X=6; break; case 'G': X=7; break; case 'A': X=8; break; case 'K': X=9; break; case 'R': X=10; break; case 'H': X=11; break; case 'E': X=12; break; case 'D': X=13; break; case 'Q': X=14; break; case 'N': X=15; break; case 'S': X=16; break; case 'T': X=17; break; case 'C': X=18; break; case 'W': X=19; break; case 'P': X=20; break; default: X=-1; break; } /* endswitch */ return X; } void Calculate(int startwindow,int endindex) /* calculates best scores for each window frame */ { int X,x,y,extras,heptad_pos,window_pos,res_pos; double root_inverse,scores,misc; int hept,index,window; double weight; int root; printf("Calculating...\n"); index=1; window=startwindow; while (index<=endindex) { printf("."); fflush(stdout); res_pos=0; root=(window / 7) * hept_weight; do { res_pos=res_pos+1; tempcalc[index][res_pos]=0; for (heptad_pos=0; heptad_pos<=6; heptad_pos++) /* go through each residue in each heptad pos */ { scores=1.0; hept=1; for (window_pos=0;window_pos<=window-1;window_pos++) /* get values at all 21 positions */ { switch (residue[window_pos + res_pos] & 95){ case 'L': x=1; break; case 'I': x=2; break; case 'V': x=3; break; case 'M': x=4; break; case 'F': x=5; break; case 'Y': x=6; break; case 'G': x=7; break; case 'A': x=8; break; case 'K': x=9; break; case 'R': x=10; break; case 'H': x=11; break; case 'E': x=12; break; case 'D': x=13; break; case 'Q': x=14; break; case 'N': x=15; break; case 'S': x=16; break; case 'T': x=17; break; case 'C': x=18; break; case 'W': x=19; break; case 'P': x=20; break; default: x=-1; break; } /* endswitch */ y=(int) fmod((double)(window_pos + res_pos + heptad_pos),7.0); if (y==0) y=7; if (window_pos==0) hept=y; if (y==0) y=7; if ((y==1) || (y==4)) weight=ad_weight; else weight=1.0; root_inverse=1.0/(double) root; misc=pow(chartvalue[x][y],weight); scores=scores*(pow(misc,root_inverse)); } /* end of window_pos loop */ if (scores>tempcalc[index][res_pos]) { tempcalc[index][res_pos]=scores; temphept[index][res_pos]=(int) fmod((double) (hept-1),7.0); } } /* end of heptad_pos loop*/ } while (res_pos+window != res_total+1); for (extras=1; extras<=window-1;extras++) { tempcalc[index][res_pos+extras]=tempcalc[index][res_pos]; temphept[index][res_pos+extras]=(int) fmod((double) (temphept[index][res_pos]+extras),7.0); } window=window+7; index=index+1; } /* for window sizes 14, 21 & 28 */ /*maximize loop*/ index=1; window=startwindow; while (index<=endindex) { res_pos=0; do { res_pos=res_pos+1; calcnumb[index][res_pos]=tempcalc[index][res_pos]; heptnum[index][res_pos]=temphept[index][res_pos]; window_pos=0; do { window_pos=window_pos+1; if (res_pos-window_pos<1) window_pos=window-1; else if (tempcalc[index][res_pos-window_pos]>calcnumb[index][res_pos]) { calcnumb[index][res_pos]=tempcalc[index][res_pos-window_pos]; heptnum[index][res_pos]=(int) fmod((temphept[index][res_pos-window_pos]+window_pos),7.0); } /* endif */ } while (window_pos!=window-1); /* enddo */ } while (res_pos!=res_total); /* enddo */ index=index+1; window=window+7; } printf("\n"); } double Calcprob(double x,double meancc,double stddevcc,double meangl,double stddevgl,double ratio_gl_cc) { double prob1,prob2,prob3,prob4; prob1=(0.5) * pow(((x-meancc) / stddevcc),2.0); prob2=(0.5) * pow(((x-meangl) / stddevgl),2.0); prob3=stddevgl * exp(-prob1); prob4=ratio_gl_cc * stddevcc * exp(-prob2); return (prob3) / (prob3+prob4); } char frame(int heptnum) { switch (heptnum) { case 0: return 'a'; break; case 1: return 'b'; break; case 2: return 'c'; break; case 3: return 'd'; break; case 4: return 'e'; break; case 5: return 'f'; break; case 6: return 'g'; break; } /* endswitch */ return 'x'; } int i_trunc(double n) { return (int) floor(n); } void Column_probs(double peakmin) { int res_pos; char fr14,fr21,fr28; double prob14,prob21,prob28,old14,old21,old28,xx=1,lastxx=1; int prevres,color=8,c14=9,c21=15,c28=12; char t1[]="14",t2[]="21",t3[]="28"; fprintf(pickup,"%s\n",nameprot); fprintf(pickup," Residue Window=14 Window=21 Window=28\n"); fprintf(pickup," Score Probability Score Probability Score Probability\n"); prevres=1; for (res_pos=1;res_pos<=res_total;res_pos++) { fr14=frame(heptnum[1][res_pos]); fr21=frame(heptnum[2][res_pos]); fr28=frame(heptnum[3][res_pos]); if (chartchar=='2') { if ((weightchar=='y') || (weightchar=='Y')) { prob28=Calcprob(calcnumb[3][res_pos],1.74,0.20,0.86,0.18,30); prob21=Calcprob(calcnumb[2][res_pos],1.79,0.24,0.92,0.22,25); prob14=Calcprob(calcnumb[1][res_pos],1.89,0.30,1.04,0.27,20); } else { prob28=Calcprob(calcnumb[3][res_pos],1.69,0.18,0.80,0.18,30); prob21=Calcprob(calcnumb[2][res_pos],1.74,0.23,0.86,0.21,25); prob14=Calcprob(calcnumb[1][res_pos],1.82,0.28,0.95,0.26,20); } /* end */ } /* end */ else { if ((weightchar=='y') || (weightchar=='Y')) { if (calcnumb[3][res_pos] > 0.0) prob28=Calcprob(calcnumb[3][res_pos],1.70,0.24,0.79,0.23,30); else { prob28=0.0; fr28='x'; } /* endif */ if (calcnumb[2][res_pos] > 0.0) prob21=Calcprob(calcnumb[2][res_pos],1.76,0.28,0.86,0.26,25); else { prob21=0.0; fr21='x'; } if (calcnumb[1][res_pos] > 0.0) prob14=Calcprob(calcnumb[1][res_pos],1.88,0.34,1.00,0.33,20); else { prob14=0.0; fr14='x'; } } /* end */ else { if (calcnumb[3][res_pos] > 0.0) prob28=Calcprob(calcnumb[3][res_pos],1.628,0.243,0.770,0.202,30); else { prob28=0.0; fr28='x'; } if (calcnumb[2][res_pos] > 0.0) prob21=Calcprob(calcnumb[2][res_pos],1.683,0.285,0.828,0.236,25); else { prob21=0.0; fr21='x'; } if (calcnumb[1][res_pos] > 0.0) prob14=Calcprob(calcnumb[1][res_pos],1.782,0.328,0.936,0.289,20); else { prob14=0.0; fr14='x'; } } /* end */ } if ((prob14>=peakmin) || (prob21>=peakmin) || (prob28>=peakmin)) { if (res_pos-1!=prevres) fprintf(pickup,"...\n"); prevres=res_pos; fprintf(pickup,"%5d %c",res_pos,residue[res_pos]); fprintf(pickup," %c %5.3lf %5.3lf",fr14,calcnumb[1][res_pos],prob14); fprintf(pickup," %c %5.3lf %5.3lf",fr21,calcnumb[2][res_pos],prob21); fprintf(pickup," %c %5.3lf %5.3lf",fr28,calcnumb[3][res_pos],prob28); fprintf(pickup,"\n"); } } } void Row_probs() { int res_pos,maxline,startpos; fprintf(pickup,"%s\n",nameprot); for (res_pos=1;res_pos<=res_total;res_pos++) { fr14[res_pos]=frame(heptnum[1][res_pos]); fr21[res_pos]=frame(heptnum[2][res_pos]); fr28[res_pos]=frame(heptnum[3][res_pos]); if (chartchar=='2') { if ((weightchar=='y') || (weightchar=='Y')) { pr14[res_pos]=i_trunc(Calcprob(calcnumb[1][res_pos],1.89,0.30,1.04,0.27,20)*10.0); pr21[res_pos]=i_trunc(Calcprob(calcnumb[2][res_pos],1.79,0.24,0.92,0.22,25)*10.0); pr28[res_pos]=i_trunc(Calcprob(calcnumb[3][res_pos],1.74,0.20,0.86,0.18,30)*10.0); } /* end */ else { pr14[res_pos]=i_trunc(Calcprob(calcnumb[1][res_pos],1.82,0.28,0.95,0.26,20)*10.0); pr21[res_pos]=i_trunc(Calcprob(calcnumb[2][res_pos],1.74,0.23,0.86,0.21,25)*10.0); pr28[res_pos]=i_trunc(Calcprob(calcnumb[3][res_pos],1.69,0.18,0.80,0.18,30)*10.0); } /* end */ } /* end */ else { if ((weightchar=='y') || (weightchar=='Y')) { if (calcnumb[3][res_pos] > 0) pr28[res_pos]=i_trunc(Calcprob(calcnumb[3][res_pos],1.70,0.24,0.79,0.23,30)*10.0); else { pr28[res_pos]=0; fr28[res_pos]='x'; } if (calcnumb[2][res_pos] > 0) pr21[res_pos]=i_trunc(Calcprob(calcnumb[2][res_pos],1.76,0.28,0.86,0.26,25)*10.0); else { pr21[res_pos]=0; fr21[res_pos]='x'; } if (calcnumb[1][res_pos] > 0) pr14[res_pos]=i_trunc(Calcprob(calcnumb[1][res_pos],1.88,0.34,1.00,0.33,20)*10.0); else { pr14[res_pos]=0; fr14[res_pos]='x'; } } /* end */ else { if (calcnumb[3][res_pos] > 0) pr28[res_pos]=i_trunc(Calcprob(calcnumb[3][res_pos],1.628,0.243,0.770,0.202,30)*10.0); else { pr28[res_pos]=0; fr28[res_pos]='x'; } if (calcnumb[2][res_pos] > 0) pr21[res_pos]=i_trunc(Calcprob(calcnumb[2][res_pos],1.683,0.285,0.828,0.236,25)*10.0); else { pr21[res_pos]=0; fr21[res_pos]='x'; } if (calcnumb[1][res_pos] > 0) pr14[res_pos]=i_trunc(Calcprob(calcnumb[1][res_pos],1.782,0.328,0.936,0.289,20)*10.0); else { pr14[res_pos]=0; fr14[res_pos]='x'; } } /* end */ } if (pr14[res_pos]>9) pr14[res_pos]=9; if (pr21[res_pos]>9) pr21[res_pos]=9; if (pr28[res_pos]>9) pr28[res_pos]=9; } maxline=60; startpos=1; while (startpos+maxline-1 <= res_total) { fprintf(pickup,"%d\n",startpos); fprintf(pickup," . | . | . | . | . | . |\n"); for (res_pos=startpos;res_pos<=startpos+maxline-1;res_pos++) fprintf(pickup,"%c",residue[res_pos]); fprintf(pickup,"\n\n"); for (res_pos=startpos;res_pos<=startpos+maxline-1;res_pos++) fprintf(pickup,"%d",pr14[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=startpos+maxline-1;res_pos++) fprintf(pickup,"%d",pr21[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=startpos+maxline-1;res_pos++) fprintf(pickup,"%d",pr28[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=startpos+maxline-1;res_pos++) fprintf(pickup,"%c",fr14[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=startpos+maxline-1;res_pos++) fprintf(pickup,"%c",fr21[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=startpos+maxline-1;res_pos++) fprintf(pickup,"%c",fr28[res_pos]); fprintf(pickup,"\n"); fprintf(pickup,"\n"); startpos=startpos+60; } /* finish up! */ if (startpos<=res_total) { fprintf(pickup,"%d\n",startpos); fprintf(pickup," . | . | . | . | . | . |\n"); for (res_pos=startpos;res_pos<=res_total;res_pos++) fprintf(pickup,"%c",residue[res_pos]); fprintf(pickup,"\n"); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=res_total;res_pos++) fprintf(pickup,"%d",pr14[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=res_total;res_pos++) fprintf(pickup,"%d",pr21[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=res_total;res_pos++) fprintf(pickup,"%d",pr28[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=res_total;res_pos++) fprintf(pickup,"%c",fr14[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=res_total;res_pos++) fprintf(pickup,"%c",fr21[res_pos]); fprintf(pickup,"\n"); for (res_pos=startpos;res_pos<=res_total;res_pos++) fprintf(pickup,"%c",fr28[res_pos]); fprintf(pickup,"\n"); fprintf(pickup,"\n"); } } void Scores_only() { int res_pos; char fr; fprintf(pickup,"%s\n",nameprot); fprintf(pickup," Residue Frame Score\n"); for (res_pos=1;res_pos<=res_total;res_pos++) { if (calcnumb[1][res_pos] > 0.0) { fr=frame(heptnum[1][res_pos]); fprintf(pickup," %6d %c %c %2.6lf\n",res_pos,residue[res_pos],fr, calcnumb[1][res_pos]); } else fprintf(pickup," %6d %c x %2.6lf\n",res_pos,residue[res_pos], calcnumb[1][res_pos]); } } void Calc_print() { double peakmin=0.0; int num_wind; if (res_total >= window) { num_wind=3; if ((option=='a') || (option=='A')) { Calculate(window,num_wind); Row_probs(); } else if ((option=='b') || (option=='B')) { num_wind=1; Calculate(window,num_wind); Scores_only(); } /* end */ else { if ((option=='c') || (option=='C')) { printf("ENTER MINIMUM PROBABILITY (as .##): "); scanf("%lf",&peakmin); } Calculate(window,num_wind); Column_probs(peakmin); } } else fprintf(pickup,"Protein too short. Length=%d\n",res_total); } main(int argc, char *argv[], char *envp[]) { /* Main Program */ Get_info(); Select_option(); fgets(junkline,9999,protein); do { Skip_opening_info(); if (!nomore) { Store_residues(); Calc_print(); if (!feof(protein)) fgets(junkline,9999,protein); } } while (!feof(protein)); /* enddo */ fclose(protein); fclose(pickup); }
2.234375
2
2024-11-18T22:09:32.715430+00:00
2017-03-16T08:03:58
ff84dd08bd2a87884a3acac4d5543201f4251f60
{ "blob_id": "ff84dd08bd2a87884a3acac4d5543201f4251f60", "branch_name": "refs/heads/master", "committer_date": "2017-03-16T08:03:58", "content_id": "60735db41fadfe9f417160b9ac88998f572e0ff0", "detected_licenses": [ "MIT" ], "directory_id": "d8518db1927579cccd81e0d24661fe47f41b5b53", "extension": "c", "filename": "116.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 83906508, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 899, "license": "MIT", "license_type": "permissive", "path": "/cprog/ch1/116.c", "provenance": "stackv2-0106.json.gz:36310", "repo_name": "tanwarmohit/swc-prep", "revision_date": "2017-03-16T08:03:58", "revision_id": "67769769bc5845e3840ac8e25356c85fa9ea4e59", "snapshot_id": "2f8be74e571569486780026d99327266ef201390", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/tanwarmohit/swc-prep/67769769bc5845e3840ac8e25356c85fa9ea4e59/cprog/ch1/116.c", "visit_date": "2021-01-20T08:24:27.860380" }
stackv2
#include<stdio.h> #define MAX_LINE 50 int get_line(char *line, int limit); void copy(char *to, char *from); int main(void){ int len, max, prev_len; char s[MAX_LINE], l[MAX_LINE], t[MAX_LINE]; max = prev_len = 0; while((len = get_line(s, MAX_LINE)) > 0){ if(prev_len + len > max){ max = prev_len + len; if(prev_len) copy(l, t); else copy(l, s); } if(s[len - 1] != '\n'){ if(prev_len == 0) copy(t, s); prev_len += len; } else prev_len = 0; } printf("Longest: %d, Line:%s\n", max, l); return 0; } int get_line(char *line, int limit){ int c, i; for(i = 0; i < limit - 1 && (c = getchar()) != EOF && c != '\n'; i++) line[i] = c; if(c == '\n') line[i++] = c; line[i] = '\0'; return i; } void copy(char *to, char *from){ int i = 0; while((to[i] = from[i]) != '\0') i++; }
3.40625
3
2024-11-18T22:09:32.781730+00:00
2019-04-25T01:53:30
0d69072a432665652e34599480c57a4ef6914847
{ "blob_id": "0d69072a432665652e34599480c57a4ef6914847", "branch_name": "refs/heads/master", "committer_date": "2019-04-25T01:53:30", "content_id": "813f0a270c6c56c57c5592fe51706d40aefe8b76", "detected_licenses": [ "Apache-2.0" ], "directory_id": "c5bdcb5bd09f39f7514e202a449a95b1787a9d95", "extension": "c", "filename": "P2 - ATPII - EX 02 - 2017.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 145161369, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2319, "license": "Apache-2.0", "license_type": "permissive", "path": "/Provas/2017/P2/P2 - ATPII - EX 02 - 2017.c", "provenance": "stackv2-0106.json.gz:36438", "repo_name": "murilopereirame/atp2", "revision_date": "2019-04-25T01:53:30", "revision_id": "24c496df2c3afd8fc518f7b305cd04edadf4acd6", "snapshot_id": "54151ec9914a728bb88ca49b638beb09305c5bf4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/murilopereirame/atp2/24c496df2c3afd8fc518f7b305cd04edadf4acd6/Provas/2017/P2/P2 - ATPII - EX 02 - 2017.c", "visit_date": "2020-03-26T17:26:39.609164" }
stackv2
#include <stdio.h> #include <stdlib.h> #define RC 4 typedef enum boleano {true = 1, false = 0} bool; bool matrizMagica(int **A, int N); void main(){ printf("A matriz:\n\n"); //Inicia uma matriz genérica int A[RC][RC] = { {1,1,1,1}, {1,1,1,1}, {1,1,1,1}, {1,1,1,1} }; //Imprime a matriz for(int i = 0; i < RC; i++){ for(int j = 0; j < RC; j++) printf("\t%d ", A[i][j]); printf("\n"); } printf("\n"); //Verifica se é uma matriz mágica if(matrizMagica(A, RC)) printf("E uma matriz magica!\n"); else printf("Nao e uma matriz magica!!\n"); system("pause"); return 0; } bool matrizMagica(int **A, int N){ //Inicia a variavel que irá armazenar a soma, uma auxiliar pra manter a soma e uma para checar se não é a primeira vez que a soma //sera conferida int soma = 0, aux = 0, r1 = 1; //Checar a soma das linhas for(int i = 0; i < N; i++){ soma = 0; for(int j = 0; j < N; j++){ soma += A[i*N + j]; } //Caso a soma não seja igual a soma armazenada, retorna falso (Existe uma verificação de primeiro loop para evitar comparar soma == 0) if(!(aux == soma) && !r1) return false; aux = soma; r1 = 0; } //Checar a soma das colunas for(int j = 0; j < N; j++){ soma = 0; for(int i = 0; i < N; i++){ soma += A[i*N + j]; } if(!(aux == soma)) return false; aux = soma; } //Checar a soma da diagonal principal soma = 0; for(int i = (N - 1), j = 0; i >= 0 && j < N; i--, j++){ soma += A[i*N + j]; } if(!(aux == soma)){ return false; } aux = soma; //Checar a soma da diagonal secundaria soma = 0; for(int i = (N - 1), j = (N - 1); i >= 0 && j >= 0; i--, j--){ soma += A[i*N + j]; } if(!(aux == soma)){ return false; } aux = soma; //Se passou nas verificações anteriores, bingo return true; }
3.65625
4
2024-11-18T22:09:32.846192+00:00
2020-10-01T09:06:09
62933865af59cecb637cd3021db3124f223070ca
{ "blob_id": "62933865af59cecb637cd3021db3124f223070ca", "branch_name": "refs/heads/master", "committer_date": "2020-10-01T09:06:09", "content_id": "527f83776e86428c5e283b76211291445ae7b4f9", "detected_licenses": [ "Apache-2.0", "BSD-3-Clause" ], "directory_id": "1eb656349200f69daed8869ea33991c7680e55e0", "extension": "c", "filename": "ciniparser.c", "fork_events_count": 0, "gha_created_at": "2020-07-22T13:28:11", "gha_event_created_at": "2020-10-01T09:06:10", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 281685094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10289, "license": "Apache-2.0,BSD-3-Clause", "license_type": "permissive", "path": "/ccan/ccan/ciniparser/ciniparser.c", "provenance": "stackv2-0106.json.gz:36566", "repo_name": "iotaledger/access-sdk", "revision_date": "2020-10-01T09:06:09", "revision_id": "17aa7c5491928a5e2d4b6330a22820082d0e2981", "snapshot_id": "3c7482d341331ffeeb8b16cd81e87cbd46268e60", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/iotaledger/access-sdk/17aa7c5491928a5e2d4b6330a22820082d0e2981/ccan/ccan/ciniparser/ciniparser.c", "visit_date": "2023-01-05T18:49:13.265383" }
stackv2
/* Copyright (c) 2000-2007 by Nicolas Devillard. * Copyright (x) 2009 by Tim Post <tinkertim@gmail.com> * MIT License * * 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. */ /** @addtogroup ciniparser * @{ */ /** * @file ciniparser.c * @author N. Devillard * @date Sep 2007 * @version 3.0 * @brief Parser for ini files. */ #include <ctype.h> #include <ccan/ciniparser/ciniparser.h> #define ASCIILINESZ (1024) #define INI_INVALID_KEY ((char*) NULL) /** * This enum stores the status for each parsed line (internal use only). */ typedef enum _line_status_ { LINE_UNPROCESSED, LINE_ERROR, LINE_EMPTY, LINE_COMMENT, LINE_SECTION, LINE_VALUE } line_status; /** * @brief Convert a string to lowercase. * @param s String to convert. * @return ptr to statically allocated string. * * This function returns a pointer to a statically allocated string * containing a lowercased version of the input string. Do not free * or modify the returned string! Since the returned string is statically * allocated, it will be modified at each function call (not re-entrant). */ static char *strlwc(const char *s) { static char l[ASCIILINESZ+1]; int i; if (s == NULL) return NULL; for (i = 0; s[i] && i < ASCIILINESZ; i++) l[i] = tolower(s[i]); l[i] = '\0'; return l; } /** * @brief Remove blanks at the beginning and the end of a string. * @param s String to parse. * @return ptr to statically allocated string. * * This function returns a pointer to a statically allocated string, * which is identical to the input string, except that all blank * characters at the end and the beg. of the string have been removed. * Do not free or modify the returned string! Since the returned string * is statically allocated, it will be modified at each function call * (not re-entrant). */ static char *strstrip(const char *s) { static char l[ASCIILINESZ+1]; unsigned int i, numspc; if (s == NULL) return NULL; while (isspace(*s)) s++; for (i = numspc = 0; s[i] && i < ASCIILINESZ; i++) { l[i] = s[i]; if (isspace(l[i])) numspc++; else numspc = 0; } l[i - numspc] = '\0'; return l; } /** * @brief Load a single line from an INI file * @param input_line Input line, may be concatenated multi-line input * @param section Output space to store section * @param key Output space to store key * @param value Output space to store value * @return line_status value */ static line_status ciniparser_line(char *input_line, char *section, char *key, char *value) { line_status sta; char line[ASCIILINESZ+1]; int len; strcpy(line, strstrip(input_line)); len = (int) strlen(line); if (len < 1) { /* Empty line */ sta = LINE_EMPTY; } else if (line[0] == '#') { /* Comment line */ sta = LINE_COMMENT; } else if (line[0] == '[' && line[len-1] == ']') { /* Section name */ sscanf(line, "[%[^]]", section); strcpy(section, strstrip(section)); strcpy(section, strlwc(section)); sta = LINE_SECTION; } else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2 || sscanf (line, "%[^=] = '%[^\']'", key, value) == 2 || sscanf (line, "%[^=] = %[^;#]", key, value) == 2) { /* Usual key=value, with or without comments */ strcpy(key, strstrip(key)); strcpy(key, strlwc(key)); strcpy(value, strstrip(value)); /* * sscanf cannot handle '' or "" as empty values * this is done here */ if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) { value[0] = 0; } sta = LINE_VALUE; } else if (sscanf(line, "%[^=] = %[;#]", key, value) == 2 || sscanf(line, "%[^=] %[=]", key, value) == 2) { /* * Special cases: * key= * key=; * key=# */ strcpy(key, strstrip(key)); strcpy(key, strlwc(key)); value[0] = 0; sta = LINE_VALUE; } else { /* Generate syntax error */ sta = LINE_ERROR; } return sta; } /* The remaining public functions are documented in ciniparser.h */ int ciniparser_getnsec(dictionary *d) { int i; int nsec; if (d == NULL) return -1; nsec = 0; for (i = 0; i < d->size; i++) { if (d->key[i] == NULL) continue; if (strchr(d->key[i], ':') == NULL) { nsec ++; } } return nsec; } char *ciniparser_getsecname(dictionary *d, int n) { int i; int foundsec; if (d == NULL || n < 0) return NULL; if (n == 0) n ++; foundsec = 0; for (i = 0; i < d->size; i++) { if (d->key[i] == NULL) continue; if (! strchr(d->key[i], ':')) { foundsec++; if (foundsec >= n) break; } } if (foundsec == n) { return d->key[i]; } return (char *) NULL; } void ciniparser_dump(dictionary *d, FILE *f) { int i; if (d == NULL || f == NULL) return; for (i = 0; i < d->size; i++) { if (d->key[i] == NULL) continue; if (d->val[i] != NULL) { fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]); } else { fprintf(f, "[%s]=UNDEF\n", d->key[i]); } } return; } void ciniparser_dump_ini(dictionary *d, FILE *f) { int i, j; char keym[ASCIILINESZ+1]; int nsec; char *secname; int seclen; if (d == NULL || f == NULL) return; memset(keym, 0, ASCIILINESZ + 1); nsec = ciniparser_getnsec(d); if (nsec < 1) { /* No section in file: dump all keys as they are */ for (i = 0; i < d->size; i++) { if (d->key[i] == NULL) continue; fprintf(f, "%s = %s\n", d->key[i], d->val[i]); } return; } for (i = 0; i < nsec; i++) { secname = ciniparser_getsecname(d, i); seclen = (int)strlen(secname); fprintf(f, "\n[%s]\n", secname); snprintf(keym, ASCIILINESZ + 1, "%s:", secname); for (j = 0; j < d->size; j++) { if (d->key[j] == NULL) continue; if (!strncmp(d->key[j], keym, seclen+1)) { fprintf(f, "%-30s = %s\n", d->key[j]+seclen+1, d->val[j] ? d->val[j] : ""); } } } fprintf(f, "\n"); return; } char *ciniparser_getstring(dictionary *d, const char *key, char *def) { char *lc_key; char *sval; if (d == NULL || key == NULL) return def; lc_key = strlwc(key); sval = dictionary_get(d, lc_key, def); return sval; } int ciniparser_getint(dictionary *d, const char *key, int notfound) { char *str; str = ciniparser_getstring(d, key, INI_INVALID_KEY); if (str == INI_INVALID_KEY) return notfound; return (int) strtol(str, NULL, 10); } double ciniparser_getdouble(dictionary *d, const char *key, double notfound) { char *str; str = ciniparser_getstring(d, key, INI_INVALID_KEY); if (str == INI_INVALID_KEY) return notfound; return atof(str); } int ciniparser_getboolean(dictionary *d, const char *key, int notfound) { char *c; int ret; c = ciniparser_getstring(d, key, INI_INVALID_KEY); if (c == INI_INVALID_KEY) return notfound; switch(c[0]) { case 'y': case 'Y': case '1': case 't': case 'T': ret = 1; break; case 'n': case 'N': case '0': case 'f': case 'F': ret = 0; break; default: ret = notfound; break; } return ret; } int ciniparser_find_entry(dictionary *ini, char *entry) { int found = 0; if (ciniparser_getstring(ini, entry, INI_INVALID_KEY) != INI_INVALID_KEY) { found = 1; } return found; } int ciniparser_set(dictionary *d, char *entry, char *val) { return dictionary_set(d, strlwc(entry), val); } void ciniparser_unset(dictionary *ini, char *entry) { dictionary_unset(ini, strlwc(entry)); } dictionary *ciniparser_load(const char *ininame) { FILE *in; char line[ASCIILINESZ+1]; char section[ASCIILINESZ+1]; char key[ASCIILINESZ+1]; char tmp[ASCIILINESZ+1]; char val[ASCIILINESZ+1]; int last = 0, len, lineno = 0, errs = 0; dictionary *dict; if ((in = fopen(ininame, "r")) == NULL) { fprintf(stderr, "ciniparser: cannot open %s\n", ininame); return NULL; } dict = dictionary_new(0); if (!dict) { fclose(in); return NULL; } memset(line, 0, ASCIILINESZ + 1); memset(section, 0, ASCIILINESZ + 1); memset(key, 0, ASCIILINESZ + 1); memset(val, 0, ASCIILINESZ + 1); last = 0; while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) { lineno++; len = (int) strlen(line)-1; /* Safety check against buffer overflows */ if (line[len] != '\n') { fprintf(stderr, "ciniparser: input line too long in %s (%d)\n", ininame, lineno); dictionary_del(dict); fclose(in); return NULL; } /* Get rid of \n and spaces at end of line */ while ((len >= 0) && ((line[len] == '\n') || (isspace(line[len])))) { line[len] = 0; len--; } /* Detect multi-line */ if (len >= 0 && line[len] == '\\') { /* Multi-line value */ last = len; continue; } switch (ciniparser_line(line, section, key, val)) { case LINE_EMPTY: case LINE_COMMENT: break; case LINE_SECTION: errs = dictionary_set(dict, section, NULL); break; case LINE_VALUE: snprintf(tmp, ASCIILINESZ + 1, "%s:%s", section, key); errs = dictionary_set(dict, tmp, val); break; case LINE_ERROR: fprintf(stderr, "ciniparser: syntax error in %s (%d):\n", ininame, lineno); fprintf(stderr, "-> %s\n", line); errs++; break; default: break; } memset(line, 0, ASCIILINESZ); last = 0; if (errs < 0) { fprintf(stderr, "ciniparser: memory allocation failure\n"); break; } } if (errs) { dictionary_del(dict); dict = NULL; } fclose(in); return dict; } void ciniparser_freedict(dictionary *d) { dictionary_del(d); } /** @} */
2.234375
2
2024-11-18T22:09:34.062430+00:00
2017-12-04T17:59:50
609ab6f89fc4eef0973c354292c6df7d0903a3ed
{ "blob_id": "609ab6f89fc4eef0973c354292c6df7d0903a3ed", "branch_name": "refs/heads/master", "committer_date": "2017-12-04T17:59:50", "content_id": "2ea5dff12fa9a9b32d3528b728e206d75fb6c626", "detected_licenses": [ "MIT" ], "directory_id": "f28a6c8e41150b9c4d0c853019fe11dd73fb0e99", "extension": "h", "filename": "help.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 113075124, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3842, "license": "MIT", "license_type": "permissive", "path": "/diccionario/help.h", "provenance": "stackv2-0106.json.gz:37342", "repo_name": "alfreedom/Estructuras-de-Archivos-UASLP", "revision_date": "2017-12-04T17:59:50", "revision_id": "d4a68a8695a7804cfb9b7a391b3dd3f921d15147", "snapshot_id": "2cf15843ab968658fe5ce935fed3d5503d6dbeba", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/alfreedom/Estructuras-de-Archivos-UASLP/d4a68a8695a7804cfb9b7a391b3dd3f921d15147/diccionario/help.h", "visit_date": "2021-08-23T11:27:33.555240" }
stackv2
/* * File: help.h * Author: Alfredo * * Created on 4 de febrero de 2014, 02:02 PM */ #ifndef HELP_H #define HELP_H #include <stdio.h> #define MAX_LINE 80 char line[MAX_LINE]; void GenerateHelp() { FILE *f=fopen("HELP","w"); if(f) { fprintf(f,"********************* AYUDA DEL DICCIONARIO DE DATOS *********************\n\n"); fprintf(f,"NOMBRE:\n"); fprintf(f," dic.exe (windows) dic (linux) Diccionario de Datos\n\n"); fprintf(f,"SINTAXYS:\n"); fprintf(f," dic.exe/dic <opncion1> parametro <opcion2> parametro ...\n\n"); fprintf(f,"DESCRIPCION:\n"); fprintf(f," Crea y manipula archivos que guardaran un diccionario\n"); fprintf(f," de datos, agregando, eliminando, modificando y consultado\n"); fprintf(f," entidades y atributos.\n\n"); fprintf(f," -ae\n"); fprintf(f," (Alta Entidad) <[nombre_de_la_entidad>\n"); fprintf(f," Da de alta una entidad en el diccionario especificado por -d.\n"); fprintf(f," El parametro es el nombre de la entidad.\n\n"); fprintf(f," -be\n"); fprintf(f," (Baja Entidad) <nombre_de_la_entidad>\n"); fprintf(f," Da de baja una entidad en el diccionario especificado por -d.\n"); fprintf(f," El parametro es el nombre de la entidad.\n\n"); fprintf(f," -me [-n]\n"); fprintf(f," (Modifica Entidad) <nombre_de_la_entidad> [-n]\n"); fprintf(f," Renombra una entidad en el diccionario especificado por -d.\n"); fprintf(f," y el nombre especificado por -n.\n"); fprintf(f," El parametro es el nombre de la entidad.\n\n"); fprintf(f," -c\n"); fprintf(f," (Consulta) <nombre_del_diccionario>\n"); fprintf(f," Hace una consulta en el diccionario y muestra todos las\n"); fprintf(f," entidades con sus atributos.\n"); fprintf(f," El parametro es el nombre del diccionario.\n\n"); fprintf(f," -ce\n"); fprintf(f," (Consulta Entidad) <nombre_de_la_entidad>\n"); fprintf(f," Hace una consulta de la entidad en el diccionario especificado\n"); fprintf(f," por -d y muestra todos sus atributos.\n"); fprintf(f," El parametro es el nombre de la entidad.\n\n"); fprintf(f," -d\n"); fprintf(f," (Archivo del diccionarcio) <nombre_del_diccionario>\n"); fprintf(f," Especifica el diccionario a abrir.\n"); fprintf(f," El parametro es el nombre del diccionario.\n"); fprintf(f," -new\n"); fprintf(f," (Nuevo Diccionario) <nombre_del_diccionario>\n"); fprintf(f," Crea un nuevo archivo de diccionario.\n"); fprintf(f," El parametro es el nombre del diccionario.\n\n"); fprintf(f," -h, -help\n"); fprintf(f," (Ayuda)\n"); fprintf(f," Muestra este menu de ayuda.\n\n\n"); fprintf(f,"PROGRAMADO POR:\n\n"); fprintf(f," Alfredo Orozco de la Paz.\n"); fprintf(f," Universidad Autonoma de San Luis Potosi UASLP.\n"); fprintf(f," Area de Computacion e Informatica.\n"); fprintf(f," Materia: Estructuras de Archivos.\n"); fprintf(f," Profesor: Omar Adalid.\n"); fprintf(f," Semestre 2013/2014-II.\n"); fclose(f); } } void ShowHelp() { FILE *f=fopen("HELP","rb"); if(f) { while(fgets(line,MAX_LINE,f)) printf("%s",line); fclose(f); } else { GenerateHelp(); ShowHelp(); } } #endif /* HELP_H */
2.265625
2
2024-11-18T22:09:34.124687+00:00
2020-12-20T20:16:09
71ebf7b8de08a27e048c19551fa1dd59d2dfa4b4
{ "blob_id": "71ebf7b8de08a27e048c19551fa1dd59d2dfa4b4", "branch_name": "refs/heads/master", "committer_date": "2020-12-20T20:16:09", "content_id": "29330f5df07970b27648f8af126571d4b7442bd2", "detected_licenses": [ "MIT" ], "directory_id": "f7be76d576b043ddcc08d693de01dfddb390348a", "extension": "c", "filename": "test-t2.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 298435214, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4798, "license": "MIT", "license_type": "permissive", "path": "/T2/test-t2.c", "provenance": "stackv2-0106.json.gz:37471", "repo_name": "matiasvergaras/CC3301-PSS", "revision_date": "2020-12-20T20:16:09", "revision_id": "9514c6da330310284bbc267a285c90d3d58ed957", "snapshot_id": "dfd92497f32bc552baead5fa4e9c64a9188f7584", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matiasvergaras/CC3301-PSS/9514c6da330310284bbc267a285c90d3d58ed957/T2/test-t2.c", "visit_date": "2023-02-06T03:47:47.392261" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include "t2.h" #ifdef VALGRIND #define NITER 1 #else #define NITER 5000000 #endif // ---------------------------------------------------- // Funcion que entrega el tiempo transcurrido desde el lanzamiento del // programa en milisegundos static int time0= 0; static int getTime0() { struct timeval Timeval; gettimeofday(&Timeval, NULL); return Timeval.tv_sec*1000+Timeval.tv_usec/1000; } static void resetTime() { time0= getTime0(); } static int getTime() { return getTime0()-time0; } // ---------------------------------------------------- // Revisar: verifica que un string es un valor especifico void revisar(char *s, char *valor) { if (strcmp(s, valor)!=0) { fprintf(stderr, "El string debio ser \"%s\", no \"%s\"\n", valor, s); exit(1); } } void revisar_reducir(char *s, char *res) { int len= strlen(s); char a[len+1000+1]; for (int i= 0; i<500; i++) a[i]= ~((i+34)%256); strcpy(&a[500], s); for (int i= 0; i<500; i++) a[500+i+len+1]= ~((i+34)%256); reducir(&a[500]); revisar(&a[500], res); for (int i= 0; i<500; i++) { if (a[i]!= (char)~((i+34)%256)) { fprintf(stderr, "reducir escribio fuera del string\n"); exit(1); } } for (int i= 0; i<500; i++) { if (a[500+i+len+1]!= (char)~((i+34)%256)) { fprintf(stderr, "reducir escribio fuera del string\n"); exit(1); } } } void revisar_reduccion(char *s, char *res) { char *red= reduccion(s); revisar(red, res); free(red); } void revisar_serie(void (*fun)(char *s, char *res)) { (*fun)("", ""); (*fun)(" ", " "); (*fun)(" ", " "); (*fun)(" ", " "); (*fun)("a", "a"); (*fun)("palabra", "palabra"); (*fun)(" palabra ", " palabra "); (*fun)("palabra ", "palabra "); (*fun)(" palabra", " palabra"); (*fun)("hola que tal", "hola que tal"); (*fun)(" hola que tal ", " hola que tal "); } void bench_reducir(char *s) { char a[strlen(s)+1]; strcpy(a, s); reducir(a); } void bench_reduccion(char *s) { char a[strlen(s)+1]; strcpy(a, s); char *res= reduccion(a); free(res); } char *reduccion_trivial(char *s) { char a[strlen(s)+1]; strcpy(a, s); reducir(a); char *res= malloc(strlen(a)+1); strcpy(res, a); return res; } void bench_reduccion_trivial(char *s) { char a[strlen(s)+1]; strcpy(a, s); char *res= reduccion_trivial(a); free(res); } void bench_serie(void (*fun)(char *s)) { (*fun)(""); (*fun)(" "); (*fun)(" "); (*fun)(" "); (*fun)("a"); (*fun)("palabra"); (*fun)(" palabra "); (*fun)("palabra "); (*fun)(" palabra"); (*fun)("hola que tal"); (*fun)(" hola que tal "); } int main() { printf("Prueba de la parte a\n"); { printf("Test 1: string vacio\n"); char s[]= ""; reducir(s); revisar(s, ""); printf("Aprobado\n"); } { printf("Test del enunciado\n"); char s[]= "hola que tal"; reducir(s); // elimina espacios de "hola que tal" revisar(s, "hola que tal"); // No debe tocar "123" printf("Aprobado\n"); } { printf("Test de una variacion del enunciado\n"); char s[]= " hola que tal "; reducir(s); // elimina espacios de "hola que tal" revisar(s, " hola que tal "); // No debe tocar "123" printf("Aprobado\n"); } { printf("Tests adicionales\n"); revisar_serie(revisar_reducir); printf("Aprobado\n"); } printf("Prueba de la parte b\n"); revisar_serie(revisar_reduccion); printf("Aprobado\n"); printf("Benchmark de la parte a\n"); resetTime(); for (int k=0; k<NITER; k++) bench_serie(bench_reducir); int time_reducir= getTime(); printf("Tiempo para reducir: %d\n", time_reducir); printf("Benchmark de la parte b\n"); resetTime(); for (int k=0; k<NITER; k++) bench_serie(bench_reduccion); int time_reduccion= getTime(); printf("Tiempo para reduccion: %d\n", time_reduccion); #ifndef VALGRIND if (time_reduccion*90/100<time_reducir) { fprintf(stderr, "%s\n", "El tiempo de deducir no es el 90% del tiempo de reduccion"); exit(1); } #endif printf("Benchmark de la parte b implementada a partir de la parte a\n"); resetTime(); for (int k=0; k<NITER; k++) bench_serie(bench_reduccion_trivial); int time_reduccion_trivial= getTime(); printf("Tiempo para reduccion: %d\n", time_reduccion_trivial); #ifndef VALGRIND if (time_reduccion_trivial*90/100<time_reduccion) { fprintf(stderr, "%s\n", "El tiempo de reduccion no es el 90% del tiempo de reduccion trivial"); exit(1); } #endif printf("Felicitaciones: Aprobo todos los tests\n"); return 0; }
2.8125
3
2024-11-18T22:09:34.565895+00:00
2021-09-17T12:18:45
7e7d331603eceb19b4b9d3bdfa207e8e31e47f05
{ "blob_id": "7e7d331603eceb19b4b9d3bdfa207e8e31e47f05", "branch_name": "refs/heads/main", "committer_date": "2021-09-17T12:18:45", "content_id": "9e72a4b259390c6ba16be9926f46f8f5d9910d45", "detected_licenses": [ "MIT" ], "directory_id": "e9247e5482342e6fdfb581bc2ea4a87516d89373", "extension": "h", "filename": "categorias.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": 996, "license": "MIT", "license_type": "permissive", "path": "/src/categorias.h", "provenance": "stackv2-0106.json.gz:37600", "repo_name": "maybenmargart/cyshell", "revision_date": "2021-09-17T12:18:45", "revision_id": "e8597dcfcb4ecf174037d82c950387299a8b5ccd", "snapshot_id": "c39de3dd73455107327d6808c8e4c710ca748c27", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/maybenmargart/cyshell/e8597dcfcb4ecf174037d82c950387299a8b5ccd/src/categorias.h", "visit_date": "2023-08-14T10:30:27.239326" }
stackv2
#ifndef EP2_CATEGORIAS_H #define EP2_CATEGORIAS_H #define MAX_OPERADORES 7 #define MAX_CATEGORIAS 14 typedef enum listaCategorias { /* 7 operadores aritmeticos */ OPER_EXPONENCIACAO /* "^", 0 */ ,OPER_RESTO_DIVISAO /* "%", 1 */ ,OPER_MULTIPLICACAO /* "*", 2 */ ,OPER_DIVISAO /* "/", 3 */ ,OPER_ADICAO /* "+", 4 */ ,OPER_SUBTRACAO /* "-", 5 */ ,OPER_MENOS_UNARIO /* "_", 6 */ /* parenteses para expressoes infixas */ ,ABRE_PARENTESES /* "(" , 7 */ ,FECHA_PARENTESES /* ")" , 8 */ /* categorias dos valores numéricos no formato de string */ ,FLOAT_STR /* 9 */ ,INT_STR /* 10 */ /* categorias dos valores numéricos */ ,FLOAT /* 11 */ ,INT /* 12 */ /* categoria indefinida */ ,INDEFINIDA /* 13 */ } Categoria; void imprimeNomeCategoria(int ); char *getNomeCategoria(int); #endif /* _CATEGORIAS_H */
2
2
2024-11-18T22:09:35.488472+00:00
2017-09-29T18:11:47
a20ac49a6beeab9ab5b381a40da9a5123d4f88f8
{ "blob_id": "a20ac49a6beeab9ab5b381a40da9a5123d4f88f8", "branch_name": "refs/heads/master", "committer_date": "2017-09-29T18:11:47", "content_id": "6f668ba31a8b5f37d23a50607a1d9518fcb6ebbf", "detected_licenses": [ "MIT" ], "directory_id": "c8680091ab8376b149ab2d86bf3eb8641726bd36", "extension": "c", "filename": "examplesBitwiseOperators.c", "fork_events_count": 0, "gha_created_at": "2017-09-12T05:51:54", "gha_event_created_at": "2017-09-18T16:31:06", "gha_language": "C", "gha_license_id": null, "github_id": 103227946, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1227, "license": "MIT", "license_type": "permissive", "path": "/examplesBitwiseOperators.c", "provenance": "stackv2-0106.json.gz:37728", "repo_name": "gcsadovy/theCProgrammingLanguage", "revision_date": "2017-09-29T18:11:47", "revision_id": "70867c481b8af41042744fb104a43fcd55474739", "snapshot_id": "5adeba9c4477c1c89043ec1c764efcc6eb3e1373", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gcsadovy/theCProgrammingLanguage/70867c481b8af41042744fb104a43fcd55474739/examplesBitwiseOperators.c", "visit_date": "2021-07-06T05:42:03.368819" }
stackv2
/* bitwise operators */ /* c has six operators that are special to bitwise operations that can only be used with integers (char, long, short, int; unsigned or signed) & == bitwise AND; | == bitwise inclusive OR; ^ == bitwise exclusive OR; << == left shift >> == right shift ~ == one's complement (unary) */ /* & can be used to mask off bits whereas | can be used to turn bits on; */ /* the OR operator ^ sets a one in each bit position where its operands have different bits and a zero where they are the same. */ /* need to distinguish from && and ||; int x=1, y=2; x & y == 0 x && y == 1 */ /* << and >> perform left and right shifts of their left operand by the number of bit positions given by the right operand; must be non-neg; thus, x << 2 shifts the value of x by two positions, filling vacated positions with zero; this is equivalent to multiplication by 4; */ /* the unary ~ yields the one's complement of an int; it converts each 1 bit into a 0 bit and vice versa */ x = x & ~077 /* sets the last 6 bits of x to 0 */ /* getbits: get n bits from position p */ unsigned getbits(unsigned x, int p, int n) { return (x >> (p + 1 - n)) & ~(~0 << n); /* need to figure out what the hell this is doing */ }
3.359375
3
2024-11-18T22:09:35.573525+00:00
2020-04-24T23:20:40
0522838d3b892f479be78547f00e6950cf09a309
{ "blob_id": "0522838d3b892f479be78547f00e6950cf09a309", "branch_name": "refs/heads/master", "committer_date": "2020-04-24T23:20:40", "content_id": "8c89df698ad56c60f744f3af24daaeea0bf11e33", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "48c2d779adc3ec016b996d1bb03c5f9b2605bb3f", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": "2020-04-29T11:44:55", "gha_event_created_at": "2020-04-29T11:44:56", "gha_language": null, "gha_license_id": null, "github_id": 259910011, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 455, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/cryptarm/simeck/test.c", "provenance": "stackv2-0106.json.gz:37856", "repo_name": "wqweto/tinycrypt", "revision_date": "2020-04-24T23:20:40", "revision_id": "b6100cf07b7355643085dda326c13dcfcc804077", "snapshot_id": "6aa72dab0fc553de87f7d925dd075fbc4347211b", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/wqweto/tinycrypt/b6100cf07b7355643085dda326c13dcfcc804077/cryptarm/simeck/test.c", "visit_date": "2022-04-24T00:13:25.536111" }
stackv2
#include <stdio.h> #include <string.h> #include "simeck.h" int main(void){ uint32_t key[]={0x03020100,0x0b0a0908,0x13121110,0x1b1a1918}; uint32_t txt[]={0x20646e75,0x656b696c}; uint32_t res[]={0x5f7ab7ed,0x45ce6902}; int equ; simeck(key,txt); printf("Simeck64/128 %08x %08x\n", txt[1], txt[0]); equ=(memcmp(res,txt,8)==0); printf("SIMECK Test %s\n", equ ? "OK" : "FAILED"); return 0; }
2.484375
2
2024-11-18T22:09:35.701926+00:00
2018-05-28T01:40:09
81635b81a52159db798512c294444d94a9646942
{ "blob_id": "81635b81a52159db798512c294444d94a9646942", "branch_name": "refs/heads/master", "committer_date": "2018-05-28T01:40:09", "content_id": "38ffbe8c11a229f532932d9748304329a1fd2dfa", "detected_licenses": [ "MIT" ], "directory_id": "8b2fbd4b6e80745e8c69bc38eae1f068ced7990c", "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": 132971004, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4111, "license": "MIT", "license_type": "permissive", "path": "/rrpio/main.c", "provenance": "stackv2-0106.json.gz:37984", "repo_name": "bmarcosps/round-robin-priorities", "revision_date": "2018-05-28T01:40:09", "revision_id": "2fa6360643d32b9fb9c8465f8d91371442810873", "snapshot_id": "2e02e365047e71c27c43a6e29988fa74b2587919", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bmarcosps/round-robin-priorities/2fa6360643d32b9fb9c8465f8d91371442810873/rrpio/main.c", "visit_date": "2020-03-16T20:45:00.201110" }
stackv2
/* * main.c - Simulacao de carga de trabalho para escalonamento de processos * * Autor: Marcelo Moreno * Projeto: Trabalho Pratico I - Sistemas Operacionais * Organizacao: Universidade Federal de Juiz de Fora * Departamento: Dep. Ciencia da Computacao * * => NAO MODIFIQUE ESTE ARQUIVO <= * */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "process.h" #include "sched.h" #include "rrprio.h" #define SCHED_ITERATIONS 100 #define PROCESS_CREATION_PROBABILITY 0.3 #define PROCESS_DESTROY_PROBABILITY 0.05 #define PROCESS_BLOCK_PROBABILITY 0.6 #define PROCESS_UNBLOCK_PROBABILITY 0.4 #define PROCESS_SETPRIO_PROBABILITY 0.1 void _dumpSchedParams(Process *p) { RRPrioParams *rrp = processGetSchedParams(p); printf("Prio: %d; ",rrp->prio); } Process* _createProcess(Process *plist, int ppid, int prio) { RRPrioParams *rrp; printf("Criando processo... "); plist = processCreate(plist); rrp = malloc(sizeof (RRPrioParams)); rrp->prio = prio; rrpInitSchedParams(plist, rrp); processSetStatus(plist, PROC_READY); processSetParentPid(plist, ppid); printf(" Criado PID %d!\n", processGetPid(plist)); return plist; } Process* _destroyProcess(Process *plist, int pid) { printf("Destruindo processo... "); plist = processDestroy(plist, pid); printf(" Destruido PID %d!\n", pid); return plist; } int _countReady(Process *plist) { Process *p, *next; int count = 0; for (p=plist; p!=NULL; p=next) { next = processGetNext(p); if (processGetStatus(p)==PROC_READY) count++; } return count; } Process* _getNthReady(Process *plist, int n) { Process *p=NULL, *next; int count = 0; for (p=plist; p!=NULL; p=next) { next = processGetNext(p); if (processGetStatus(p)==PROC_READY) count++; if (count==n) return p; } return NULL; } Process* _doRandomThings(Process *plist) { Process *p, *next, *dst; int pid, n, newprio, oldprio; int ready; double r = rand() / (double)RAND_MAX; printf("===Acoes Aleatorias===\n"); if (r < PROCESS_CREATION_PROBABILITY) plist = _createProcess(plist,1,rand()%8); for (p=plist;p!=NULL;p=next) { next = processGetNext(p); pid = processGetPid(p); if (pid==1) continue; r = rand() / (double)RAND_MAX; if (processGetStatus(p)==PROC_READY && r < PROCESS_DESTROY_PROBABILITY) { plist = _destroyProcess(plist,processGetPid(p)); continue; } r = rand() / (double)RAND_MAX; if (processGetStatus(p)==PROC_RUNNING && r < PROCESS_BLOCK_PROBABILITY) { processSetStatus(p,PROC_WAITING); r = rand() / (double)RAND_MAX; if (r < PROCESS_SETPRIO_PROBABILITY) { ready = _countReady(plist) - 1; if (ready > 0) { n = rand() % ready + 1; newprio = rand()%8; oldprio = rrpSetPrio(p,newprio); printf("Processo %d, passa a ter prioridade %d, que anteriormente era %d\n", pid,newprio,oldprio); } } printf("Bloqueado processo %d\n",pid); } else if (processGetStatus(p)==PROC_WAITING && r < PROCESS_UNBLOCK_PROBABILITY) { processSetStatus(p,PROC_READY); printf("Desbloqueado processo %d\n",pid); } } printf("======================\n"); return plist; } int main(void) { int i = 0, step = 0; char c = ' '; Process* plist = NULL, *p1 = NULL; srand(time(NULL)); //Inicializar escalonadores de processos schedInitSchedInfo(); rrpInitSchedInfo(); //Criando primeiro processo... plist = _createProcess(plist, 1, 0); printf("\n"); while (c != 'n') { switch (i) { case 0: printf("(Passo:%d)\n", step, i); plist = _doRandomThings(plist); processDump(plist,_dumpSchedParams); printf("\n"); i++; break; case SCHED_ITERATIONS+1: printf("(Passo:%d/Iteracoes:%d)\n", step, i-1); processDump(plist,_dumpSchedParams); step++; i = 0; printf("\nContinuar (s/n)? "); fflush(stdout); c = getchar(); printf("\n"); break; default: p1 = schedSchedule(plist); // printf("(Passo:%d/Iteracao:%d) Processo escalonado PID %d.\n", step, i, processGetPid(p1)); // processDump(plist,_dumpSchedParams); // printf("\n"); i++; } } return 0; }
2.890625
3
2024-11-18T22:09:35.810245+00:00
2020-10-01T09:06:09
5b617fe84ed1bb2a69cb3e3f2237a982c2a877f4
{ "blob_id": "5b617fe84ed1bb2a69cb3e3f2237a982c2a877f4", "branch_name": "refs/heads/master", "committer_date": "2020-10-01T09:06:09", "content_id": "46df3653aa6f5003a9e257d3a58297b49b0cd8d4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1eb656349200f69daed8869ea33991c7680e55e0", "extension": "c", "filename": "timer.c", "fork_events_count": 0, "gha_created_at": "2020-07-22T13:28:11", "gha_event_created_at": "2020-10-01T09:06:10", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 281685094, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5659, "license": "Apache-2.0", "license_type": "permissive", "path": "/utils/misc/timer.c", "provenance": "stackv2-0106.json.gz:38112", "repo_name": "iotaledger/access-sdk", "revision_date": "2020-10-01T09:06:09", "revision_id": "17aa7c5491928a5e2d4b6330a22820082d0e2981", "snapshot_id": "3c7482d341331ffeeb8b16cd81e87cbd46268e60", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/iotaledger/access-sdk/17aa7c5491928a5e2d4b6330a22820082d0e2981/utils/misc/timer.c", "visit_date": "2023-01-05T18:49:13.265383" }
stackv2
/* * This file is part of the DAC distribution (https://github.com/xainag/frost) * Copyright (c) 2020 IOTA Stiftung * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /**************************************************************************** * \project IOTA Access * \file timer.c * \brief * Timer module * * @Author Strahinja Golic * * \notes * * \history * 05.03.2020. Initial version. ****************************************************************************/ #include <poll.h> #include <pthread.h> #include <stdint.h> #include <string.h> #include <sys/timerfd.h> #include <unistd.h> #include "dlog.h" #include "timer.h" #define MAX_TIMER_COUNT 1000 #define POLL_TIMEOUT 100 #define SEC_PRESCALER 1000 #define NSEC_PRESCALER 1000000 typedef struct timer_node { int id; int fd; time_handler callback; void *user_data; unsigned int interval; timer_mode_t type; struct timer_node *next; } timer_node_t; typedef struct itimerspec itimerspec_t; typedef struct pollfd pollfd_t; static void *timer_thread(void *data); static bool thread_is_running = FALSE; static int timer_list_size = 0; static pthread_t thread_id; static timer_node_t *head = NULL; int timer_init(void) { thread_is_running = TRUE; if (pthread_create(&thread_id, NULL, timer_thread, NULL)) { dlog_printf("\n\nERROR[%s]: Thread creation failed\n\n", __FUNCTION__); thread_is_running = FALSE; return -1; } return 1; } void timer_deinit() { while (head) { timer_stop(head->id); } thread_is_running = FALSE; pthread_cancel(thread_id); pthread_join(thread_id, NULL); } int timer_start(unsigned int interval, time_handler handler, timer_mode_t type, void *user_data) { int i = 0; timer_node_t *new_node = NULL; timer_node_t *temp = NULL; itimerspec_t new_value; new_node = (timer_node_t *)malloc(sizeof(timer_node_t)); if (new_node == NULL) { dlog_printf("\n\nERROR[%s]: Failed to allocate new node\n\n", __FUNCTION__); return -1; } new_node->callback = handler; new_node->user_data = user_data; new_node->interval = interval; new_node->type = type; new_node->fd = timerfd_create(CLOCK_REALTIME, 0); if (new_node->fd == -1) { dlog_printf("\n\nERROR[%s]: Failed to create timerfd\n\n", __FUNCTION__); free(new_node); return -1; } new_value.it_value.tv_sec = interval / SEC_PRESCALER; new_value.it_value.tv_nsec = (interval % SEC_PRESCALER) * NSEC_PRESCALER; if (type == TIMER_PERIODIC) { new_value.it_interval.tv_sec = interval / SEC_PRESCALER; new_value.it_interval.tv_nsec = (interval % SEC_PRESCALER) * NSEC_PRESCALER; } else { new_value.it_interval.tv_sec = 0; new_value.it_interval.tv_nsec = 0; } timerfd_settime(new_node->fd, 0, &new_value, NULL); // find first available ID for (i = 0; i <= timer_list_size; i++) { bool found = FALSE; temp = head; while (temp != NULL) { if (temp->id == i) { found = TRUE; break; } temp = temp->next; } if (!found) { break; } } new_node->id = i; /*Inserting the timer node into the list*/ new_node->next = head; head = new_node; timer_list_size++; return new_node->id; } void timer_stop(int timer_id) { timer_node_t *tmp = NULL; timer_node_t *node = head; while (node) { if (node->id == timer_id) { break; } else { node = node->next; } } if (node == NULL) { dlog_printf("\n\nERROR[%s]: Timer %d is not started\n\n", __FUNCTION__, timer_id); return; } close(node->fd); if (node == head) { head = head->next; } else { tmp = head; while (tmp && tmp->next != node) { tmp = tmp->next; } if (tmp) { // tmp->next can not be NULL here tmp->next = tmp->next->next; } } if (node) { free(node); timer_list_size--; } } timer_node_t *get_timer_from_fd(int fd) { timer_node_t *tmp = head; while (tmp) { if (tmp->fd == fd) { return tmp; } tmp = tmp->next; } return NULL; } void *timer_thread(void *data) { int iMaxCount = 0; int read_fds = 0; int i; int s; uint64_t exp; pollfd_t ufds[MAX_TIMER_COUNT] = {{0}}; timer_node_t *tmp = NULL; while (thread_is_running) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_testcancel(); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); iMaxCount = 0; tmp = head; memset(ufds, 0, sizeof(pollfd_t) * MAX_TIMER_COUNT); while (tmp) { ufds[iMaxCount].fd = tmp->fd; ufds[iMaxCount].events = POLLIN; iMaxCount++; tmp = tmp->next; } read_fds = poll(ufds, iMaxCount, POLL_TIMEOUT); if (read_fds <= 0) { continue; } for (i = 0; i < iMaxCount; i++) { if (ufds[i].revents & POLLIN) { s = read(ufds[i].fd, &exp, sizeof(uint64_t)); if (s != sizeof(uint64_t)) { continue; } tmp = get_timer_from_fd(ufds[i].fd); if (tmp && tmp->callback) { tmp->callback((size_t)tmp, tmp->user_data); } } } } return NULL; }
2.421875
2
2024-11-18T22:09:35.963235+00:00
2014-09-15T21:34:19
7eb0822db50b79a5c7d8f18da5461fc348ee9242
{ "blob_id": "7eb0822db50b79a5c7d8f18da5461fc348ee9242", "branch_name": "refs/heads/master", "committer_date": "2014-09-15T21:34:19", "content_id": "4c20798841b20a28c0e560d7779c0de0c01d114e", "detected_licenses": [ "MIT" ], "directory_id": "4f6cff849b557ae5e42415101b5007a415fb408a", "extension": "c", "filename": "colors.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": 3308, "license": "MIT", "license_type": "permissive", "path": "/colors.c", "provenance": "stackv2-0106.json.gz:38375", "repo_name": "xneby/colors", "revision_date": "2014-09-15T21:34:19", "revision_id": "8ef2cf91635deb2e949ab6ac2bee13223159cfee", "snapshot_id": "cf9ad69dc1adba04f8e68d270a2752c899298bc3", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/xneby/colors/8ef2cf91635deb2e949ab6ac2bee13223159cfee/colors.c", "visit_date": "2020-05-07T20:26:43.235098" }
stackv2
/* The MIT License (MIT) Copyright (c) 2014 Karol Farbiś Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #define STRING "Quick brown fox jumps over the lazy dog" static struct termios original; int max(int a, int b) { if(a > b) return a; return b; } bool isvalidansi(char c) { if('0' <= c && c <= '9') return true; return c ==';'; } void initialize_terminal(void) { struct termios term; tcgetattr(STDIN_FILENO, &term); original = term; term.c_lflag &= ~ECHO; term.c_lflag &= ~ICANON; tcsetattr(STDIN_FILENO, TCSANOW, &term); } void finalize_terminal(void) { tcsetattr(STDIN_FILENO, TCSANOW, &original); } static char* buffer; static size_t buffer_size; static size_t buffer_length; void clear_buffer() { free(buffer); buffer = NULL; buffer_size = buffer_length = 0; } void resize_buffer(size_t new_size) { buffer = realloc(buffer, new_size * sizeof(char)); if(new_size == 0) buffer = NULL; buffer_size = new_size; } void delete_last_character() { if(buffer_length == 0) return; buffer[--buffer_length] = 0; if(buffer_length * 4 < buffer_size) { resize_buffer(buffer_size / 4); } } void add_character(char c) { if(buffer_length + 1 >= buffer_size) { resize_buffer(max(6, buffer_size) * 2); } buffer[buffer_length++] = c; buffer[buffer_length] = 0; } void write_back() { printf("\r\033[K\n\033[K\033[A"); if(buffer != NULL) { char* copy_buffer = malloc(buffer_length * sizeof(char) + 1); strcpy(copy_buffer, buffer); if(buffer_length > 0 && copy_buffer[buffer_length-1] == ';') copy_buffer[buffer_length-1] = 0; printf("\033[%sm%s\n", copy_buffer, buffer); free(copy_buffer); } else printf("\n"); printf("%s\r\033[0m\033[A\033[%zuC\033[D", STRING, buffer_length+1); } bool read_and_parse_character() { char c; if(scanf("%c", &c) == EOF) return false; switch(c) { case 4: return false; case 10: clear_buffer(); break; case 127: delete_last_character(); break; default: if(isvalidansi(c)) add_character(c); } write_back(); return true; } int main(void) { initialize_terminal(); printf("\n%s\r\033[A", STRING); while(read_and_parse_character()); free(buffer); finalize_terminal(); return 0; }
2.75
3
2024-11-18T22:09:36.052019+00:00
2020-07-12T17:50:17
2d999339ef4f048af5685e3d548711b1284dd793
{ "blob_id": "2d999339ef4f048af5685e3d548711b1284dd793", "branch_name": "refs/heads/master", "committer_date": "2020-07-12T17:50:17", "content_id": "b0aeca9f3eed63c19db9635a133c5bc80a7f7fe9", "detected_licenses": [ "MIT" ], "directory_id": "565e30acd3576ba1b61790cfe6f7b6eb957fc72f", "extension": "c", "filename": "tss.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": 598, "license": "MIT", "license_type": "permissive", "path": "/src/arch/x86/core/tss.c", "provenance": "stackv2-0106.json.gz:38504", "repo_name": "zzcontinent/xbook2", "revision_date": "2020-07-12T17:50:17", "revision_id": "696bc751d23c812007d49983584efe36c8bf6748", "snapshot_id": "710e81a1f51b3165b6ee988a85c33c195785f890", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/zzcontinent/xbook2/696bc751d23c812007d49983584efe36c8bf6748/src/arch/x86/core/tss.c", "visit_date": "2022-11-17T18:58:54.562343" }
stackv2
#include "tss.h" #include "segment.h" #include "registers.h" #include <string.h> #include <xbook/task.h> /* tss对象 */ tss_t tss; tss_t *get_tss() { return &tss; } void update_tss_info(unsigned long task_addr) { // 更新tss.esp0的值为任务的内核栈顶 tss.esp0 = (unsigned long)(task_addr + TASK_KSTACK_SIZE); } void init_tss() { memset(&tss, 0, sizeof(tss)); // 内核的内核栈 tss.esp0 = KERNEL_STATCK_TOP; // 内核栈选择子 tss.ss0 = KERNEL_DATA_SEL; tss.iobase = sizeof(tss); // 加载tss register load_tr(KERNEL_TSS_SEL); }
2.125
2
2024-11-18T22:09:36.562699+00:00
2020-03-04T12:58:18
a33613c8767123f7e828901cdf20068f71727d78
{ "blob_id": "a33613c8767123f7e828901cdf20068f71727d78", "branch_name": "refs/heads/master", "committer_date": "2020-03-04T12:58:18", "content_id": "0a11e2a1961a39356b86103976c3cd9bf30b82c0", "detected_licenses": [ "MIT" ], "directory_id": "5e55d7b3a1b9d8ac5e91baaaec844a31b5f79573", "extension": "c", "filename": "ejercicio15.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 236490347, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 579, "license": "MIT", "license_type": "permissive", "path": "/Lenguajes/C/ejercicio15.c", "provenance": "stackv2-0106.json.gz:39147", "repo_name": "AlbertoCurso/Ejercicios", "revision_date": "2020-03-04T12:58:18", "revision_id": "650f7781f084b323e3e06006486baddf9c3a0d76", "snapshot_id": "d085749794a319c41c608f269c3bdb4127b79082", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AlbertoCurso/Ejercicios/650f7781f084b323e3e06006486baddf9c3a0d76/Lenguajes/C/ejercicio15.c", "visit_date": "2020-12-21T16:32:59.200397" }
stackv2
//JUEGO DE LAS TRES EN RAYA #include "stdio.h" void funcion1(int a); void funcion2(int *a); void saltoLinea(); void display(int x); int main(int argc, char const *argv[]) { int a1 = 0; int a2 = 0; float salto = '\n'; funcion1(a1); funcion2(&a2); display(a1); saltoLinea(); display(a2); return 0; } //Paso de parámetros por valor. void funcion1(int a) { a = 8; } //Paso de parámetros por referencia. void funcion2(int *a) { *a = 8; } void display(int x) { printf("%d", x); } void saltoLinea() { printf("\n"); }
3.5
4
2024-11-18T22:09:38.075179+00:00
2021-12-06T11:37:59
e708e66d88fa37bc53f9b3a7f2e21f5dd50a7cd5
{ "blob_id": "e708e66d88fa37bc53f9b3a7f2e21f5dd50a7cd5", "branch_name": "refs/heads/master", "committer_date": "2021-12-06T11:37:59", "content_id": "0081781b9b24451fb1763bd882aa0066a4dd68d2", "detected_licenses": [ "MIT" ], "directory_id": "55368cb4c9d5fec97deaec8db38e9956c9e98435", "extension": "c", "filename": "ft_ldtoa_base.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 185663154, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2256, "license": "MIT", "license_type": "permissive", "path": "/Stdlib/ft_ldtoa_base.c", "provenance": "stackv2-0106.json.gz:39275", "repo_name": "akharrou/42-Project-Libft", "revision_date": "2021-12-06T11:37:59", "revision_id": "14a50e8706c8816d470625db4e7b027c956d89dd", "snapshot_id": "4714abc378f891f6ff9c2c554f0417ca25b4e67c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/akharrou/42-Project-Libft/14a50e8706c8816d470625db4e7b027c956d89dd/Stdlib/ft_ldtoa_base.c", "visit_date": "2021-12-14T17:18:39.662735" }
stackv2
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ldtoa_base.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akharrou <akharrou@student.42.us.org> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/28 09:48:40 by akharrou #+# #+# */ /* Updated: 2019/05/07 10:56:59 by akharrou ### ########.fr */ /* */ /* ************************************************************************** */ #include "../Includes/stdlib_42.h" #include "../Includes/string_42.h" #include "../Includes/stdint_42.h" #include "../Includes/macros_42.h" #include "../Includes/bigint.h" #define BIAS 16383 #define MANT_SIZE 63 #define _15BITS 32767 #define MAX_EXPONENT (32767 - BIAS - MANT_SIZE) #define EMPTY 9223372036854775808u #define INF (num.exponent == MAX_EXPONENT && num.mantissa == EMPTY) #define NAN_ (num.exponent == MAX_EXPONENT && num.mantissa != EMPTY) char *ft_ldtoa_base(long double n, char *base, int width, int precision) { t_long_double num; t_bigint res; num.ldbl_.val = n; num.sign = num.ldbl_.body[9] >> 7 != 0; num.exponent = (*(short *)&num.ldbl_.body[8] & _15BITS) - BIAS - MANT_SIZE; num.mantissa = *(intmax_t *)num.ldbl_.body; if (INF) return ((num.sign) ? ft_strdup("-inf") : ft_strdup("inf")); if (NAN_) return (ft_strdup("nan")); res = ft_utoa_base(num.mantissa, DECIMAL_BASE, 0); if (num.exponent > 0) while (num.exponent-- > 0) res = bigint_mulfre(res, 2, base, 1); else while (num.exponent++ < 0) res = bigint_divfre(res, 2, base, 1); precision = (precision >= 0) ? precision : 6; res = bigint_roundfre(res, base, precision, 1); res = ft_strprepend(res, ft_padding(width - ft_strlen(res), '0'), 1, 1); return ((num.sign) ? ft_strprepend(res, "-", 1, 0) : res); }
2.625
3
2024-11-18T22:09:38.753767+00:00
2018-09-10T01:26:10
c4b4f3223d2938e0e75cfc5a7979a3f0134ee189
{ "blob_id": "c4b4f3223d2938e0e75cfc5a7979a3f0134ee189", "branch_name": "refs/heads/master", "committer_date": "2018-09-10T01:26:10", "content_id": "1b844d1f5efc331a90701c77383e06db8875eee2", "detected_licenses": [ "MIT" ], "directory_id": "2b3944f69b98e430eb7bbe3c9dbac82d5b3bb3b1", "extension": "c", "filename": "udp_receive.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 101362035, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1403, "license": "MIT", "license_type": "permissive", "path": "/Linux_system_programming/Network_programming/udp_receive.c", "provenance": "stackv2-0106.json.gz:40054", "repo_name": "EmrysChe/C_and_CPP_practice", "revision_date": "2018-09-10T01:26:10", "revision_id": "25ee425f9235d44eda910d8d62e789ad5e164aee", "snapshot_id": "6c2aeea4c96ad8c1665ae51146d89d868156a9c3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/EmrysChe/C_and_CPP_practice/25ee425f9235d44eda910d8d62e789ad5e164aee/Linux_system_programming/Network_programming/udp_receive.c", "visit_date": "2021-01-20T03:25:44.769579" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> int main(int argc ,char *argv[]) { unsigned int short port = 8080; if(argc > 1) { port = atoi(argv[1]); } int sockfd; sockfd = socket(AF_INET,SOCK_DGRAM,0); if(sockfd < 0) { perror("socket"); exit(-1); } struct sockaddr_in my_addr; bzero(&my_addr,sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(port); my_addr.sin_addr.s_addr = htonl(INADDR_ANY); printf("Bind serber to port %d\n",port); int err_log; err_log = bind(sockfd,(struct sockaddr*)&my_addr,sizeof(my_addr)); if(err_log != 0) { perror("bind"); close(sockfd); exit(-1); } while(1) { int recv_len; char recv_buf[512] = ""; struct sockaddr_in client_addr; char cli_ip[INET_ADDRSTRLEN] = ""; socklen_t cliaddr_len = sizeof(client_addr); recv_len = recvfrom(sockfd,recv_buf,sizeof(recv_buf),0,(struct sockaddr*)&client_addr,&cliaddr_len); inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,cli_ip,INET_ADDRSTRLEN); printf("\nip:%s , port:%d \n",cli_ip,ntohs(client_addr.sin_port)); printf("data(%d):%s\n",recv_len,recv_buf); } close(sockfd); return 0; }
2.765625
3
2024-11-18T22:09:38.846965+00:00
2022-01-07T17:31:19
1fec89e542e70873eaf2b8c58a59c5759a4268ec
{ "blob_id": "1fec89e542e70873eaf2b8c58a59c5759a4268ec", "branch_name": "refs/heads/master", "committer_date": "2022-01-07T17:31:19", "content_id": "6710392a7652407c71338745631fd1728e176080", "detected_licenses": [ "MIT" ], "directory_id": "186cc5875110c58b51100e16ef59c5389822ada0", "extension": "c", "filename": "VariableRanges.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 163568367, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 516, "license": "MIT", "license_type": "permissive", "path": "/Udemy_C/Chapter2_Variables/VariableRanges.c", "provenance": "stackv2-0106.json.gz:40182", "repo_name": "kiam75/C", "revision_date": "2022-01-07T17:31:19", "revision_id": "e917862fff2f07c9d92f7c29c938eae491bc3ee8", "snapshot_id": "9965143ebb0fa4c9716a77fa3eeb9edb98d8a96a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kiam75/C/e917862fff2f07c9d92f7c29c938eae491bc3ee8/Udemy_C/Chapter2_Variables/VariableRanges.c", "visit_date": "2022-01-15T00:22:53.447275" }
stackv2
#include <float.h> #include <limits.h> #include <stdio.h> int main() { int a = 1; unsigned int b = 1u; float c = 1.0f; double d = 1.0; char e = 42; printf("Variable a: %lu\n", sizeof(a)); printf("Variable b: %lu\n", sizeof(b)); printf("Variable c: %lu\n", sizeof(c)); printf("Variable d: %lu\n", sizeof(d)); printf("Variable e: %lu\n", sizeof(e)); printf("Int range: %d, %d\n", INT_MIN, INT_MAX); printf("Float range: %E, %E\n", FLT_MIN, FLT_MAX); return 0; }
2.921875
3
2024-11-18T22:09:39.572368+00:00
2021-05-25T17:40:13
34c92f958bc19cbfd3e5125e0a56645a4e93f53e
{ "blob_id": "34c92f958bc19cbfd3e5125e0a56645a4e93f53e", "branch_name": "refs/heads/master", "committer_date": "2021-05-25T17:40:13", "content_id": "323780e8b58f6e52f59d0c2235f383321c9c5e7a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "9dd63737483cae14ff0b90fde23652b4a8d98c7c", "extension": "c", "filename": "Source.c", "fork_events_count": 0, "gha_created_at": "2020-09-22T11:41:37", "gha_event_created_at": "2021-05-28T08:42:14", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 297630430, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1989, "license": "Apache-2.0", "license_type": "permissive", "path": "/Homework8/AVLTree/Source.c", "provenance": "stackv2-0106.json.gz:40311", "repo_name": "ValentinaShvetsova/Homework", "revision_date": "2021-05-25T17:40:13", "revision_id": "8e54ee10169c0be0a7ba023a69ae9aca328d0782", "snapshot_id": "cd93587bcceb2e271f16a4cbb9e9037645dba669", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ValentinaShvetsova/Homework/8e54ee10169c0be0a7ba023a69ae9aca328d0782/Homework8/AVLTree/Source.c", "visit_date": "2023-05-08T22:52:04.675633" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "AVLTree.h" bool functionsWorking() { struct Tree* tree = createTree(); addValue(tree, "11", "right"); addValue(tree, "12", "root"); addValue(tree, "13", "left"); if (strcmp(getValue(tree, "12"), "root") != 0) { deleteTree(tree); return false; } if (!contains(tree, "13") || !contains(tree, "12") || !contains(tree, "11")) { deleteTree(tree); return false; } if (strcmp(getRootValue(tree), "12") != 0) { deleteTree(tree); return false; } deleteValue(tree, "13"); if (contains(tree, "13")) { deleteTree(tree); return false; } deleteTree(tree); return true; } int main() { if (!functionsWorking()) { return 1; } int command = 0; bool shouldGoOut = false; struct Tree* tree = createTree(); while (!shouldGoOut) { printf("Choose the command:\n0) Exit\n1)Add value by key\n2)Get value by key\n"); printf("3)Check whether the key is in the dictionary or not\n4)Delete key and value\n"); scanf("%d", &command); char key[50] = { 0 }; switch (command) { case 0: shouldGoOut = true; break; case 1: { char value[100] = { 0 }; printf("Enter the key: "); scanf("%s", &key); printf("Enter value: "); scanf("%s", &value); addValue(tree, key, value); break; } case 2: { printf("Enter the key: "); scanf("%s", &key); char* result = getValue(tree, key); if (result == NULL) { printf("Value for this key wasn't found\n"); } else { printf("%s", result); } break; } case 3: { printf("Enter the key: "); scanf("%s", &key); if (contains(tree, key)) { printf("The key is in the dictionary"); } else { printf("The key is not in the dictionary"); } break; } case 4: { printf("Enter the key: "); scanf("%s", &key); deleteValue(tree, key); break; } default: printf("Invalid input, try again\n"); break; } } deleteTree(tree); return 0; }
3.390625
3
2024-11-18T22:09:41.669053+00:00
2021-05-26T01:20:57
26a59a369d72bf06615dbf3283703cf2d6ebf611
{ "blob_id": "26a59a369d72bf06615dbf3283703cf2d6ebf611", "branch_name": "refs/heads/main", "committer_date": "2021-05-26T01:20:57", "content_id": "b65111bbc328a46796ad6fa703ca09531669e6ee", "detected_licenses": [ "MIT" ], "directory_id": "8c208dae8ecffd1d52c53d246cef8471f441e88e", "extension": "c", "filename": "Exercicio_10.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 344955265, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 310, "license": "MIT", "license_type": "permissive", "path": "/Exercicios04/Exercicio_10.c", "provenance": "stackv2-0106.json.gz:40698", "repo_name": "PaixaoThales/PE_Programacao_Estruturada_UFABC_2021_1", "revision_date": "2021-05-26T01:20:57", "revision_id": "07e49aca29e578101231ce627733b60038396fc4", "snapshot_id": "2aae311a5ddcf01e574025fee0de665e2231b37f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PaixaoThales/PE_Programacao_Estruturada_UFABC_2021_1/07e49aca29e578101231ce627733b60038396fc4/Exercicios04/Exercicio_10.c", "visit_date": "2023-04-26T06:29:29.525915" }
stackv2
#include <stdio.h> #include <stdlib.h> int somaCubos(int num); int somaCubos(int num){ if(num == 1){ return 1; }else{ return (num * num * num) + somaCubos(num - 1); } } int main(int argc, char *argv[]){ int n; scanf("%d", &n); printf("%d", somaCubos(n)); return 0; }
3.125
3
2024-11-18T22:09:42.348854+00:00
2016-06-02T00:11:27
b903c4a59951e01c4228c5aa7672369501cba882
{ "blob_id": "b903c4a59951e01c4228c5aa7672369501cba882", "branch_name": "refs/heads/master", "committer_date": "2016-06-02T00:11:27", "content_id": "a59a8f94ba921b5118946bf27fb51f9c418e5c85", "detected_licenses": [ "MIT" ], "directory_id": "5a8fd1519755593a750165935936e858a77a8579", "extension": "c", "filename": "basic.c", "fork_events_count": 0, "gha_created_at": "2016-07-13T09:26:32", "gha_event_created_at": "2016-07-13T09:26:33", "gha_language": null, "gha_license_id": null, "github_id": 63233038, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1106, "license": "MIT", "license_type": "permissive", "path": "/examples/basic.c", "provenance": "stackv2-0106.json.gz:40828", "repo_name": "gasparfm/libstr", "revision_date": "2016-06-02T00:11:27", "revision_id": "779f3cb64126a070570086972793869ad6a8442e", "snapshot_id": "be127aa043c949cae9f6988b6cc1c7a1927c79f6", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/gasparfm/libstr/779f3cb64126a070570086972793869ad6a8442e/examples/basic.c", "visit_date": "2020-12-26T09:26:07.802514" }
stackv2
#include "../libstr.h" #include <stdio.h> int main(int argc, char const *argv[]) { char str[] = "Hello World"; int W = indexOf('W',str); if(W > 0){ const char* substring = substr(str, W, strlen(str) -1 ); /* => World */ printf("%s\n",substring); } char* str1 = (char*)"Hello World"; char* sliced = strslice(str1, 6); char* reverse = strreverse(str1); char o = charAt(str1, 4); char* replaced = strreplace('e', '3', str1); replaced = strreplace('o','0', replaced); printf("\nCharAt(4): '%c'\n", o); /* => 'o' */ printf("Slice: %s\n", sliced); /* => World */ printf("Reverse: %s\n", reverse); /* => dlroW olleH */ printf("Replace: %s\n", replaced); /* H3ll0 W0rld */ char str11[] = "Lorem ipsum dolor sit amet"; char** splited = strsplit(' ', str11); /* => { "Lorem", "ipsum", "dolor", "sit", "amet" } */ printf("Splited: "); int i; for(i = 0 ; i < 5 ; i++){ printf("[\"%s\"]", splited[i]); } printf("\n"); freeStr(sliced); freeStr(reverse); freeStr(replaced); return 0; }
3.140625
3
2024-11-18T22:09:43.239533+00:00
2013-08-19T23:18:03
48817bed567a28532708c68004866cadaba4e0a8
{ "blob_id": "48817bed567a28532708c68004866cadaba4e0a8", "branch_name": "refs/heads/master", "committer_date": "2013-08-19T23:18:03", "content_id": "54eaed4892857471167b71687b8f7f51d608cdeb", "detected_licenses": [ "MIT" ], "directory_id": "88b897880bc84381d41c635b754a73964c891b96", "extension": "c", "filename": "code.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": 19273, "license": "MIT", "license_type": "permissive", "path": "/code.c", "provenance": "stackv2-0106.json.gz:41476", "repo_name": "matthiaskrgr/gmqcc", "revision_date": "2013-08-19T23:18:03", "revision_id": "a7fdbbe35beb9c12a2f4822b716c7c487a7273e1", "snapshot_id": "e37c969b65caf48c5adf2ba7e5cc219043340375", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matthiaskrgr/gmqcc/a7fdbbe35beb9c12a2f4822b716c7c487a7273e1/code.c", "visit_date": "2020-04-04T21:52:50.330147" }
stackv2
/* * Copyright (C) 2012, 2013 * Dale Weiler * Wolfgang Bumiller * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <string.h> #include "gmqcc.h" /* * We could use the old method of casting to uintptr_t then to void* * or qcint_t; however, it's incredibly unsafe for two reasons. * 1) The compilers aliasing optimization can legally make it unstable * (it's undefined behaviour). * * 2) The cast itself depends on fresh storage (newly allocated in which * ever function is using the cast macros), the contents of which are * transferred in a way that the obligation to release storage is not * propagated. */ typedef union { void *enter; qcint_t leave; } code_hash_entry_t; /* Some sanity macros */ #define CODE_HASH_ENTER(ENTRY) ((ENTRY).enter) #define CODE_HASH_LEAVE(ENTRY) ((ENTRY).leave) void code_push_statement(code_t *code, prog_section_statement_t *stmt, int linenum) { vec_push(code->statements, *stmt); vec_push(code->linenums, linenum); } void code_pop_statement(code_t *code) { vec_pop(code->statements); vec_pop(code->linenums); } code_t *code_init() { static prog_section_function_t empty_function = {0,0,0,0,0,0,0,{0,0,0,0,0,0,0,0}}; static prog_section_statement_t empty_statement = {0,{0},{0},{0}}; static prog_section_def_t empty_def = {0, 0, 0}; code_t *code = (code_t*)mem_a(sizeof(code_t)); int i = 0; memset(code, 0, sizeof(code_t)); code->entfields = 0; code->string_cache = util_htnew(OPTS_OPTIMIZATION(OPTIM_OVERLAP_STRINGS) ? 0x100 : 1024); /* * The way progs.dat is suppose to work is odd, there needs to be * some null (empty) statements, functions, and 28 globals */ for(; i < 28; i++) vec_push(code->globals, 0); vec_push(code->chars, '\0'); vec_push(code->functions, empty_function); code_push_statement(code, &empty_statement, 0); vec_push(code->defs, empty_def); vec_push(code->fields, empty_def); return code; } void *code_util_str_htgeth(hash_table_t *ht, const char *key, size_t bin); uint32_t code_genstring(code_t *code, const char *str) { size_t hash; code_hash_entry_t existing; if (!str) return 0; if (!*str) { if (!code->string_cached_empty) { code->string_cached_empty = vec_size(code->chars); vec_push(code->chars, 0); } return code->string_cached_empty; } if (OPTS_OPTIMIZATION(OPTIM_OVERLAP_STRINGS)) { hash = ((unsigned char*)str)[strlen(str)-1]; CODE_HASH_ENTER(existing) = code_util_str_htgeth(code->string_cache, str, hash); } else { hash = util_hthash(code->string_cache, str); CODE_HASH_ENTER(existing) = util_htgeth(code->string_cache, str, hash); } if (CODE_HASH_ENTER(existing)) return CODE_HASH_LEAVE(existing); CODE_HASH_LEAVE(existing) = vec_size(code->chars); vec_append(code->chars, strlen(str)+1, str); util_htseth(code->string_cache, str, hash, CODE_HASH_ENTER(existing)); return CODE_HASH_LEAVE(existing); } qcint_t code_alloc_field (code_t *code, size_t qcsize) { qcint_t pos = (qcint_t)code->entfields; code->entfields += qcsize; return pos; } static size_t code_size_generic(code_t *code, prog_header_t *code_header, bool lno) { size_t size = 0; if (lno) { size += 4; /* LNOF */ size += sizeof(uint32_t); /* version */ size += sizeof(code_header->defs.length); size += sizeof(code_header->globals.length); size += sizeof(code_header->fields.length); size += sizeof(code_header->statements.length); size += sizeof(code->linenums[0]) * vec_size(code->linenums); } else { size += sizeof(prog_header_t); size += sizeof(prog_section_statement_t) * vec_size(code->statements); size += sizeof(prog_section_def_t) * vec_size(code->defs); size += sizeof(prog_section_field_t) * vec_size(code->fields); size += sizeof(prog_section_function_t) * vec_size(code->functions); size += sizeof(int32_t) * vec_size(code->globals); size += 1 * vec_size(code->chars); } return size; } #define code_size_binary(C, H) code_size_generic((C), (H), false) #define code_size_debug(C, H) code_size_generic((C), (H), true) static void code_create_header(code_t *code, prog_header_t *code_header, const char *filename, const char *lnofile) { size_t i; code_header->statements.offset = sizeof(prog_header_t); code_header->statements.length = vec_size(code->statements); code_header->defs.offset = code_header->statements.offset + (sizeof(prog_section_statement_t) * vec_size(code->statements)); code_header->defs.length = vec_size(code->defs); code_header->fields.offset = code_header->defs.offset + (sizeof(prog_section_def_t) * vec_size(code->defs)); code_header->fields.length = vec_size(code->fields); code_header->functions.offset = code_header->fields.offset + (sizeof(prog_section_field_t) * vec_size(code->fields)); code_header->functions.length = vec_size(code->functions); code_header->globals.offset = code_header->functions.offset + (sizeof(prog_section_function_t) * vec_size(code->functions)); code_header->globals.length = vec_size(code->globals); code_header->strings.offset = code_header->globals.offset + (sizeof(int32_t) * vec_size(code->globals)); code_header->strings.length = vec_size(code->chars); code_header->version = 6; code_header->skip = 0; if (OPTS_OPTION_BOOL(OPTION_FORCECRC)) code_header->crc16 = OPTS_OPTION_U16(OPTION_FORCED_CRC); else code_header->crc16 = code->crc; code_header->entfield = code->entfields; if (OPTS_FLAG(DARKPLACES_STRING_TABLE_BUG)) { util_debug("GEN", "Patching stringtable for -fdarkplaces-stringtablebug\n"); /* >= + P */ vec_push(code->chars, '\0'); /* > */ vec_push(code->chars, '\0'); /* = */ vec_push(code->chars, '\0'); /* P */ } /* ensure all data is in LE format */ util_endianswap(&code_header->version, 1, sizeof(code_header->version)); util_endianswap(&code_header->crc16, 1, sizeof(code_header->crc16)); util_endianswap(&code_header->statements, 2, sizeof(code_header->statements.offset)); util_endianswap(&code_header->defs, 2, sizeof(code_header->statements.offset)); util_endianswap(&code_header->fields, 2, sizeof(code_header->statements.offset)); util_endianswap(&code_header->functions, 2, sizeof(code_header->statements.offset)); util_endianswap(&code_header->strings, 2, sizeof(code_header->statements.offset)); util_endianswap(&code_header->globals, 2, sizeof(code_header->statements.offset)); util_endianswap(&code_header->entfield, 1, sizeof(code_header->entfield)); /* * These are not part of the header but we ensure LE format here to save on duplicated * code. */ util_endianswap(code->statements, vec_size(code->statements), sizeof(prog_section_statement_t)); util_endianswap(code->defs, vec_size(code->defs), sizeof(prog_section_def_t)); util_endianswap(code->fields, vec_size(code->fields), sizeof(prog_section_field_t)); util_endianswap(code->functions, vec_size(code->functions), sizeof(prog_section_function_t)); util_endianswap(code->globals, vec_size(code->globals), sizeof(int32_t)); if (!OPTS_OPTION_BOOL(OPTION_QUIET)) { if (lnofile) con_out("writing '%s' and '%s'...\n", filename, lnofile); else con_out("writing '%s'\n", filename); } if (!OPTS_OPTION_BOOL(OPTION_QUIET) && !OPTS_OPTION_BOOL(OPTION_PP_ONLY)) { char buffer[1024]; con_out("\nOptimizations:\n"); for (i = 0; i < COUNT_OPTIMIZATIONS; ++i) { if (opts_optimizationcount[i]) { util_optimizationtostr(opts_opt_list[i].name, buffer, sizeof(buffer)); con_out( " %s: %u\n", buffer, (unsigned int)opts_optimizationcount[i] ); } } } } static void code_stats(const char *filename, const char *lnofile, code_t *code, prog_header_t *code_header) { if (OPTS_OPTION_BOOL(OPTION_QUIET) || OPTS_OPTION_BOOL(OPTION_PP_ONLY)) return; con_out("\nFile statistics:\n"); con_out(" dat:\n"); con_out(" name: %s\n", filename); con_out(" size: %u (bytes)\n", code_size_binary(code, code_header)); con_out(" crc: 0x%04X\n", code->crc); if (lnofile) { con_out(" lno:\n"); con_out(" name: %s\n", lnofile); con_out(" size: %u (bytes)\n", code_size_debug(code, code_header)); } con_out("\n"); } /* * Same principle except this one allocates memory and writes the lno(optional) and the dat file * directly out to allocated memory. Which is actually very useful for the future library support * we're going to add. */ #if 0 static bool code_write_memory(code_t *code, uint8_t **datmem, size_t *sizedat, uint8_t **lnomem, size_t *sizelno) GMQCC_UNUSED { prog_header_t code_header; uint32_t offset = 0; if (!datmem) return false; code_create_header(code, &code_header, "<<memory>>", "<<memory>>"); #define WRITE_CHUNK(C,X,S) \ do { \ memcpy((void*)(&(*C)[offset]), (const void*)(X), (S)); \ offset += (S); \ } while (0) /* Calculate size required to store entire file out to memory */ if (lnomem) { uint32_t version = 1; *sizelno = code_size_debug(code, &code_header); *lnomem = (uint8_t*)mem_a(*sizelno); WRITE_CHUNK(lnomem, "LNOF", 4); WRITE_CHUNK(lnomem, &version, sizeof(version)); WRITE_CHUNK(lnomem, &code_header.defs.length, sizeof(code_header.defs.length)); WRITE_CHUNK(lnomem, &code_header.globals.length, sizeof(code_header.globals.length)); WRITE_CHUNK(lnomem, &code_header.fields.length, sizeof(code_header.fields.length)); WRITE_CHUNK(lnomem, &code_header.statements.length, sizeof(code_header.statements.length)); /* something went terribly wrong */ if (offset != *sizelno) { mem_d(*lnomem); *sizelno = 0; return false; } offset = 0; } /* Write out the dat */ *sizedat = code_size_binary(code, &code_header); *datmem = (uint8_t*)mem_a(*sizedat); WRITE_CHUNK(datmem, &code_header, sizeof(prog_header_t)); WRITE_CHUNK(datmem, code->statements, sizeof(prog_section_statement_t) * vec_size(code->statements)); WRITE_CHUNK(datmem, code->defs, sizeof(prog_section_def_t) * vec_size(code->defs)); WRITE_CHUNK(datmem, code->fields, sizeof(prog_section_field_t) * vec_size(code->fields)); WRITE_CHUNK(datmem, code->functions, sizeof(prog_section_function_t) * vec_size(code->functions)); WRITE_CHUNK(datmem, code->globals, sizeof(int32_t) * vec_size(code->globals)); WRITE_CHUNK(datmem, code->chars, 1 * vec_size(code->chars)); vec_free(code->statements); vec_free(code->linenums); vec_free(code->defs); vec_free(code->fields); vec_free(code->functions); vec_free(code->globals); vec_free(code->chars); util_htdel(code->string_cache); mem_d(code); code_stats("<<memory>>", (lnomem) ? "<<memory>>" : NULL, code, &code_header); return true; } #endif /*!#if 0 reenable when ready to be used */ #undef WRITE_CHUNK bool code_write(code_t *code, const char *filename, const char *lnofile) { prog_header_t code_header; FILE *fp = NULL; size_t it = 2; code_create_header(code, &code_header, filename, lnofile); if (lnofile) { uint32_t version = 1; fp = fs_file_open(lnofile, "wb"); if (!fp) return false; util_endianswap(&version, 1, sizeof(version)); util_endianswap(code->linenums, vec_size(code->linenums), sizeof(code->linenums[0])); if (fs_file_write("LNOF", 4, 1, fp) != 1 || fs_file_write(&version, sizeof(version), 1, fp) != 1 || fs_file_write(&code_header.defs.length, sizeof(code_header.defs.length), 1, fp) != 1 || fs_file_write(&code_header.globals.length, sizeof(code_header.globals.length), 1, fp) != 1 || fs_file_write(&code_header.fields.length, sizeof(code_header.fields.length), 1, fp) != 1 || fs_file_write(&code_header.statements.length, sizeof(code_header.statements.length), 1, fp) != 1 || fs_file_write(code->linenums, sizeof(code->linenums[0]), vec_size(code->linenums), fp) != vec_size(code->linenums)) { con_err("failed to write lno file\n"); } fs_file_close(fp); fp = NULL; } fp = fs_file_open(filename, "wb"); if (!fp) return false; if (1 != fs_file_write(&code_header, sizeof(prog_header_t) , 1 , fp) || vec_size(code->statements) != fs_file_write(code->statements, sizeof(prog_section_statement_t), vec_size(code->statements), fp) || vec_size(code->defs) != fs_file_write(code->defs, sizeof(prog_section_def_t) , vec_size(code->defs) , fp) || vec_size(code->fields) != fs_file_write(code->fields, sizeof(prog_section_field_t) , vec_size(code->fields) , fp) || vec_size(code->functions) != fs_file_write(code->functions, sizeof(prog_section_function_t) , vec_size(code->functions) , fp) || vec_size(code->globals) != fs_file_write(code->globals, sizeof(int32_t) , vec_size(code->globals) , fp) || vec_size(code->chars) != fs_file_write(code->chars, 1 , vec_size(code->chars) , fp)) { fs_file_close(fp); return false; } util_debug("GEN","HEADER:\n"); util_debug("GEN"," version: = %d\n", code_header.version ); util_debug("GEN"," crc16: = %d\n", code_header.crc16 ); util_debug("GEN"," entfield: = %d\n", code_header.entfield); util_debug("GEN"," statements = {.offset = % 8d, .length = % 8d}\n", code_header.statements.offset, code_header.statements.length); util_debug("GEN"," defs = {.offset = % 8d, .length = % 8d}\n", code_header.defs .offset, code_header.defs .length); util_debug("GEN"," fields = {.offset = % 8d, .length = % 8d}\n", code_header.fields .offset, code_header.fields .length); util_debug("GEN"," functions = {.offset = % 8d, .length = % 8d}\n", code_header.functions .offset, code_header.functions .length); util_debug("GEN"," globals = {.offset = % 8d, .length = % 8d}\n", code_header.globals .offset, code_header.globals .length); util_debug("GEN"," strings = {.offset = % 8d, .length = % 8d}\n", code_header.strings .offset, code_header.strings .length); /* FUNCTIONS */ util_debug("GEN", "FUNCTIONS:\n"); for (; it < vec_size(code->functions); it++) { size_t j = code->functions[it].entry; util_debug("GEN", " {.entry =% 5d, .firstlocal =% 5d, .locals =% 5d, .profile =% 5d, .name =% 5d, .file =% 5d, .nargs =% 5d, .argsize ={%d,%d,%d,%d,%d,%d,%d,%d} }\n", code->functions[it].entry, code->functions[it].firstlocal, code->functions[it].locals, code->functions[it].profile, code->functions[it].name, code->functions[it].file, code->functions[it].nargs, code->functions[it].argsize[0], code->functions[it].argsize[1], code->functions[it].argsize[2], code->functions[it].argsize[3], code->functions[it].argsize[4], code->functions[it].argsize[5], code->functions[it].argsize[6], code->functions[it].argsize[7] ); util_debug("GEN", " NAME: %s\n", &code->chars[code->functions[it].name]); /* Internal functions have no code */ if (code->functions[it].entry >= 0) { util_debug("GEN", " CODE:\n"); for (;;) { if (code->statements[j].opcode != INSTR_DONE) util_debug("GEN", " %-12s {% 5i,% 5i,% 5i}\n", util_instr_str[code->statements[j].opcode], code->statements[j].o1.s1, code->statements[j].o2.s1, code->statements[j].o3.s1 ); else { util_debug("GEN", " DONE {0x00000,0x00000,0x00000}\n"); break; } j++; } } } fs_file_close(fp); code_stats(filename, lnofile, code, &code_header); return true; } void code_cleanup(code_t *code) { vec_free(code->statements); vec_free(code->linenums); vec_free(code->defs); vec_free(code->fields); vec_free(code->functions); vec_free(code->globals); vec_free(code->chars); util_htdel(code->string_cache); mem_d(code); }
2.140625
2
2024-11-18T22:09:43.791947+00:00
2019-08-12T19:53:50
db7c976b060f3a8754ef3fa2b532b9f000e4927e
{ "blob_id": "db7c976b060f3a8754ef3fa2b532b9f000e4927e", "branch_name": "refs/heads/master", "committer_date": "2019-08-12T19:53:50", "content_id": "d30b8d0d10963cac98c99f7a6b416d73bbbddd31", "detected_licenses": [ "Apache-2.0" ], "directory_id": "b6fe81dfe1fc44f31618c448b37c4001503ce7d1", "extension": "c", "filename": "filee.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 177277398, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 489, "license": "Apache-2.0", "license_type": "permissive", "path": "/filee.c", "provenance": "stackv2-0106.json.gz:41604", "repo_name": "tonystark665/my_codes", "revision_date": "2019-08-12T19:53:50", "revision_id": "32620a61063be984468cc5d1fedbe519cca32951", "snapshot_id": "d987298c3b5f8f956fc4514ffefda603f6952f1d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tonystark665/my_codes/32620a61063be984468cc5d1fedbe519cca32951/filee.c", "visit_date": "2020-05-01T04:32:11.699584" }
stackv2
#include<stdio.h> #include<stdlib.h> int main() { int n,i; scanf("%d",&n); char *string=(char*)malloc(n*sizeof(char)); scanf("%s",string); int q; scanf("%d",&q); int *queries=(int*)malloc(q*sizeof(int)); for(i=0;i<q;i++) { scanf("%d",&queries[i]); } int count=0; int querynumber; char alphabet; int a; for(a=0;a<q;a++) { count=0; querynumber=queries[a]; alphabet=string[querynumber-1]; for(i=0;i<querynumber-1;i++) { if(string[i]==alphabet) count++; } printf("%d\n",count); } return 0; }
2.578125
3
2024-11-18T22:09:43.955066+00:00
2023-08-23T03:45:56
e9438b5b4e805f848a40f4272c579427b451e2a8
{ "blob_id": "e9438b5b4e805f848a40f4272c579427b451e2a8", "branch_name": "refs/heads/master", "committer_date": "2023-08-23T03:45:56", "content_id": "7f55a8b01e861825f8215fa0c30bffcd1cd3ed62", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d9322e797c881a28c8f517178880b5c008994f6c", "extension": "c", "filename": "pal_smmu.c", "fork_events_count": 146, "gha_created_at": "2016-11-23T15:06:17", "gha_event_created_at": "2023-09-11T06:09:32", "gha_language": "C", "gha_license_id": "Apache-2.0", "github_id": 74587546, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1735, "license": "Apache-2.0", "license_type": "permissive", "path": "/platform/pal_uefi/src/pal_smmu.c", "provenance": "stackv2-0106.json.gz:41732", "repo_name": "ARM-software/sbsa-acs", "revision_date": "2023-08-23T03:45:56", "revision_id": "3b6e10a812da5e311f3ef8541233088691d3d3a7", "snapshot_id": "023b314ac29c2ab4bb174d87ce37c32bdeb33981", "src_encoding": "UTF-8", "star_events_count": 86, "url": "https://raw.githubusercontent.com/ARM-software/sbsa-acs/3b6e10a812da5e311f3ef8541233088691d3d3a7/platform/pal_uefi/src/pal_smmu.c", "visit_date": "2023-09-04T07:05:46.879989" }
stackv2
/** @file * Copyright (c) 2019, Arm Limited or its affiliates. All rights reserved. * SPDX-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. **/ /* This is a place-holder file. Need to be implemented if needed in later releases */ /** @brief This API prepares the smmu page tables to support input PasId @param SmmuBase - Physical addr of the SMMU for which PasId support is needed @param PasId - Process Address Space identifier @return zero for success, one for failure **/ UINT32 pal_smmu_create_pasid_entry ( UINT64 SmmuBase, UINT32 PasId ) { return 1; } /** @brief This API globally disables the SMMU based on input base address @param SmmuBase - Physical addr of the SMMU that needs to be globally disabled @return zero for success, one for failure **/ UINT32 pal_smmu_disable ( UINT64 SmmuBase ) { return 0; } /** @brief This API converts physical address to IO virtual address @param SmmuBase - Physical addr of the SMMU for pa to iova conversion @param Pa - Physical address to use in conversion @return zero for success, one for failure */ UINT64 pal_smmu_pa2iova ( UINT64 SmmuBase, UINT64 Pa ) { return 0; }
2.03125
2
2024-11-18T22:09:44.233373+00:00
2018-09-19T17:40:29
324ab62681c8c0adba98aa074de11f2d65cacc24
{ "blob_id": "324ab62681c8c0adba98aa074de11f2d65cacc24", "branch_name": "refs/heads/master", "committer_date": "2018-09-19T17:40:29", "content_id": "32a2b63aa3dc34c7c0356985106e8d5dc253f64b", "detected_licenses": [ "MIT" ], "directory_id": "17ce54614b589161e397cb399696630704c9286c", "extension": "c", "filename": "simple_loop_computer.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 92426527, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6626, "license": "MIT", "license_type": "permissive", "path": "/CUtils/src/main/c/simple_loop_computer.c", "provenance": "stackv2-0106.json.gz:41861", "repo_name": "Koldar/crashc", "revision_date": "2018-09-19T17:40:29", "revision_id": "e2d7b5808380f67c5434ba8aa419476f18963295", "snapshot_id": "61040b6fa1a267074027891df8f2241b397ee0fc", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Koldar/crashc/e2d7b5808380f67c5434ba8aa419476f18963295/CUtils/src/main/c/simple_loop_computer.c", "visit_date": "2021-01-22T04:04:53.569124" }
stackv2
/* * simple_loop_computer.c * * Created on: Jul 25, 2017 * Author: koldar */ #include "simple_loops_computer.h" #include <stdbool.h> #include "scc.h" #include "heap.h" #include "stack.h" #include "dynamic_array.h" #include "log.h" typedef HT node_list_ht; typedef dynamic_1D_array bool_array; typedef Stack node_stack; typedef struct johnson_support { /** * array of booleans. * * A cell is true iff the node is inside the building loop. * False otherwise */ bool_array* blocked; /** * An hashtable representing B * * In B where each key is an id of a node in ::johnson_support::graph while * the value is a list of nodes in ::johnson_support::graph. */ node_list_ht* B; /** * A stack where to put the vertex on ::circuit */ node_stack* stack; /** * The function used to check if an edge can be traversed or not */ edge_traverser t; /** * an hashtable where containing each node that we need to consider inside the SCC algorithm computation. * * If we need to consider a node, we need to have an entry in this field indexed by the **node id**. */ bool_ht* included; } johnson_support; static void unblock(bool_array* blocked, node_list_ht* b, NodeId u); static bool circuit(const PredSuccGraph* graph, const scc_graph* sccGraph, const scc* sccOfRoot, node_stack* stack, bool_array* blocked, node_list_ht* b, NodeId rootId, NodeId vId, loop_list* retVal); static void cricuit_finding_algorithm(johnson_support* support, const PredSuccGraph* graph, loop_list* retVal); johnson_support* initJohnsonSupport() { johnson_support* retVal = malloc(sizeof (johnson_support)); if (retVal == NULL) { ERROR_MALLOC(); } retVal->B = initHT(); retVal->blocked = NULL; retVal->stack = NULL; retVal->t = NULL; retVal->included = initHT(); return retVal; } void destroyJohnsonSupport(johnson_support* support) { destroyDynamicArray(support->blocked); destroyHTWithElements(&support->B, destroyList); destroyStack(support->stack); destroyHT(&support->included); } loop_list* computeSimpleLoopsInGraph(johnson_support* support, const PredSuccGraph* g, edge_traverser t) { loop_list* retVal = initList(); // ***************** SETUP SUPPORT ******************** if (support->blocked != NULL && getSizeOfDynamicArray(support->blocked) < getSizeOfGraph(g)) { destroyDynamicArray(support->blocked); } support->blocked = initDynamicArray(bool, getSizeOfGraph(g)); if (support->stack != NULL && getStackMaxSize(support->stack) < getSizeOfGraph(g)) { destroyStack(support->stack); } support->stack = initStack(getSizeOfGraph(g)); support->t = t; clearHT(&support->included); clearStack(support->stack); clearDynamicArrayTo(support->blocked, bool, true); ITERATE_ON_HT(&support->B, el) { destroyList((node_list*)el->data); free(el); } // ****************** EXECUTE ALGORITHM ******************* cricuit_finding_algorithm(support, g, retVal); return retVal; } static void cricuit_finding_algorithm(johnson_support* support, const PredSuccGraph* graph, loop_list* retVal) { scc_graph* sccGraph = NULL; scc* sccAnalyzed; for (NodeId id=0; id<getSizeOfGraph(graph); id++) { addItemInHTWithKey(&support->included, id, true); } //loop over the nodes for (NodeId s=0; s<getSizeOfGraph(graph); s++) { sccGraph = initStronglyConnectedComponentsGraph(graph, support->t, false, support->included); //scc containing s sccAnalyzed = getStrongConnectedComponentOfNodeById(sccGraph, s); if (sccAnalyzed == NULL) { break; } Node* root = getNodeWithMinimumIdInStrongConnectedComponent(sccAnalyzed); ITERATE_THROUGH_HEAP(getNodesInsideStrongConnectedComponent(sccAnalyzed), node, Node*) { setDynamicArrayCellTo(support->blocked, node->id, bool, false); NodeList* b_node = getItemInHT(&support->B, node->id); if (b_node == NULL) { addItemInHTWithKey(&support->B, node->id, initList()); } else { clearList(b_node); } } circuit(graph, sccGraph, sccAnalyzed, support->stack, support->blocked, support->B, root->id, root->id, retVal); //we now remove the node "s" from the graph, since we have computed all the loop involving it if (sccGraph != NULL) { destroyStronglyConnectedComponentsGraph(sccGraph); } deleteItemInHT(&support->included, s); } } static void unblock(bool_array* blocked, node_list_ht* b, NodeId u) { //put the node outside the building loop setDynamicArrayCellTo(blocked, u, bool, false); NodeList* bu = getItemInHT(&b, u); VARIABLE_ITERATE_ON_LIST(bu, prevCell, cell, w, Node) { removeElementInListCell(bu, &prevCell, cell); if (getDynamicArrayCellValue(blocked, w->id, bool)) { unblock(blocked, b, w->id); } } } static bool circuit(const PredSuccGraph* graph, const scc_graph* sccGraph, const scc* sccOfRoot, node_stack* stack, bool_array* blocked, node_list_ht* b, NodeId rootId, NodeId vId, loop_list* retVal) { bool f; Node* v; Node* w; f = false; v = getNodeInGraph(graph, vId); pushToStack(stack, v); setDynamicArrayCellTo(blocked, vId, bool, true); // ******************** L1 *************************** ITERATE_VALUES_ON_HT(&v->successors, e, Edge) { w = e->sink; if (!isNodeInsideStrongConnectedComponentById(sccGraph, w->id, sccOfRoot->id)) { //the successor is in another scc. We ignore it since it can't lead to cycles continue; } if (w->id == rootId) { //output circuit composed of stack followed by s loop* l = initList(); ITERATE_THROUGH_STACK(stack, n, Node*) { addTailInList(l, n); } addTailInList(retVal, l); f = true; } else if (!getDynamicArrayCellValue(blocked, w->id, bool)) { if (circuit(graph, sccGraph, sccOfRoot, stack, blocked, b, rootId, w->id, retVal)) { f = true; } } } // ******************** L2 ************************ if (f) { unblock(blocked, b, vId); } else { bool found; ITERATE_VALUES_ON_HT(&v->successors, e, Edge) { w = e->sink; NodeId wId = w->id; if (!isNodeInsideStrongConnectedComponentById(sccGraph, w->id, sccOfRoot->id)) { //the successor is in another scc. We ignore it since it can't lead to cycles continue; } NodeList* bw = getItemInHT(&b, wId); if (bw == NULL) { bw = initList(); addItemInHTWithKey(&b, wId, bw); } //search in bw for v found = false; ITERATE_ON_LIST(bw, cell, n, Node) { if (n->id == vId) { found = true; break; } } if (!found) { addTailInList(bw, v); } } } Node* expectedV = popFromStack(stack); #ifdef DEBUG if (expectedV->id != v->id) { ERROR_UNHANDLED_CASE("popped from stack", expectedV->id); } #endif return f; }
2.53125
3
2024-11-18T22:09:51.442425+00:00
2018-12-12T19:34:58
485f3fcbeff757efa0271edb7ce2963be50a9b13
{ "blob_id": "485f3fcbeff757efa0271edb7ce2963be50a9b13", "branch_name": "refs/heads/master", "committer_date": "2018-12-12T19:34:58", "content_id": "6dbe478f118097e2da7f78da14da967c7fb9a3a7", "detected_licenses": [ "MIT" ], "directory_id": "205798618411cd76c20bb2af66a6b9a5208f111c", "extension": "h", "filename": "TP2_Ej3Required.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 136393725, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2028, "license": "MIT", "license_type": "permissive", "path": "/TP2/tp2_ejercicio3/fsm/TP2_Ej3Required.h", "provenance": "stackv2-0106.json.gz:41989", "repo_name": "sebastianmuratore/td2-2018r4051-grupo1", "revision_date": "2018-12-12T19:34:58", "revision_id": "f522fc7e63c4bcf94545314f5cf6517055da9eba", "snapshot_id": "a1801c98531085feb2f27cf1e21a97062d6df987", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/sebastianmuratore/td2-2018r4051-grupo1/f522fc7e63c4bcf94545314f5cf6517055da9eba/TP2/tp2_ejercicio3/fsm/TP2_Ej3Required.h", "visit_date": "2020-03-19T10:41:57.341830" }
stackv2
#ifndef TP2_EJ3REQUIRED_H_ #define TP2_EJ3REQUIRED_H_ #include "sc_types.h" #include "TP2_Ej3.h" #ifdef __cplusplus extern "C" { #endif /*! \file This header defines prototypes for all functions that are required by the state machine implementation. This is a state machine uses time events which require access to a timing service. Thus the function prototypes: - tP2_Ej3_setTimer and - tP2_Ej3_unsetTimer are defined. This state machine makes use of operations declared in the state machines interface or internal scopes. Thus the function prototypes: - tP2_Ej3Iface_opLed are defined. These functions will be called during a 'run to completion step' (runCycle) of the statechart. There are some constraints that have to be considered for the implementation of these functions: - never call the statechart API functions from within these functions. - make sure that the execution time is as short as possible. */ extern void tP2_Ej3Iface_opLed(const TP2_Ej3* handle, const sc_integer Led, const sc_boolean State); /*! * This is a timed state machine that requires timer services */ /*! This function has to set up timers for the time events that are required by the state machine. */ /*! This function will be called for each time event that is relevant for a state when a state will be entered. \param evid An unique identifier of the event. \time_ms The time in milli seconds \periodic Indicates the the time event must be raised periodically until the timer is unset */ extern void tP2_Ej3_setTimer(TP2_Ej3* handle, const sc_eventid evid, const sc_integer time_ms, const sc_boolean periodic); /*! This function has to unset timers for the time events that are required by the state machine. */ /*! This function will be called for each time event taht is relevant for a state when a state will be left. \param evid An unique identifier of the event. */ extern void tP2_Ej3_unsetTimer(TP2_Ej3* handle, const sc_eventid evid); #ifdef __cplusplus } #endif #endif /* TP2_EJ3REQUIRED_H_ */
2.3125
2
2024-11-18T22:09:51.641415+00:00
2020-02-01T15:18:36
b31b2106d59b03ded9ed06a0dfba731f81d75d54
{ "blob_id": "b31b2106d59b03ded9ed06a0dfba731f81d75d54", "branch_name": "refs/heads/master", "committer_date": "2020-02-01T15:18:36", "content_id": "20df31068de87b065fd0449fa896da4e6de2a8b0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "dc875bef0f5dc634973d60df30e243cf46ef89d2", "extension": "c", "filename": "watchdog.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 237459442, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4298, "license": "Apache-2.0", "license_type": "permissive", "path": "/watchdog/watchdog.c", "provenance": "stackv2-0106.json.gz:42246", "repo_name": "mhz2010/iot_daemon", "revision_date": "2020-02-01T15:18:36", "revision_id": "75367a7e207faa695ba66eaefdfefefcd5db66d0", "snapshot_id": "227d470df10273fbeeb65a7ccd11f9af62869f3e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mhz2010/iot_daemon/75367a7e207faa695ba66eaefdfefefcd5db66d0/watchdog/watchdog.c", "visit_date": "2020-12-26T09:08:49.377222" }
stackv2
#include <linux/watchdog.h> #include "watchdog.h" int __watchdog_fd = -1; /*********************************************************************/ /* * ini_watchdog * 使能看门狗 * * @param * unsigned int time 喂狗超时时间 * * @return unsigned int * 成功: IOT_SUCCEESE * 失败: IOT_FAILED * * @note * **********************************************************************/ unsigned int ini_watchdog(unsigned int time) { #ifndef WDT_ENABLE return IOT_SUCCEESE; #endif /*open watchdog file*/ __watchdog_fd = open("/dev/watchdog",O_RDWR); if(__watchdog_fd < 0){ IOT_WARN("%s : open /dev/watchdog FILED.\n",__FUNCTION__); return IOT_FAILED; } else{ IOT_INFO("%s : open /dev/watchdog OK.\n",__FUNCTION__); } /*set time*/ if(ioctl(__watchdog_fd,WDIOC_SETTIMEOUT,&time) < 0){ IOT_WARN("%s : watchdog set timeout failed.\n",__FUNCTION__); return IOT_FAILED; } else{ IOT_INFO("%s : watchdog set timeout %d.\n",__FUNCTION__, time); } return IOT_SUCCEESE; } /*********************************************************************/ /* * release_watchdog * 关闭看门狗 * * @param * * @return unsigned int * 成功: IOT_SUCCEESE * 失败: IOT_FAILED * * @note * **********************************************************************/ unsigned int release_watchdog() { #ifndef WDT_ENABLE return IOT_SUCCEESE; #endif unsigned int ret = IOT_SUCCEESE; if(__watchdog_fd < 0) { IOT_WARN("%s : watchdog not opened.\n",__FUNCTION__); __watchdog_fd = -1; return IOT_SUCCEESE; } else{ } /*disable watchdog*/ if(1 != write(__watchdog_fd,"V",1)) { /*Magic Close feature*/ IOT_WARN("%s : watchdog disable failed.\n",__FUNCTION__); ret = IOT_FAILED; } else{ IOT_INFO("%s : watchdog disable OK.\n",__FUNCTION__); } /*close watchdog*/ if( 0 > close(__watchdog_fd)) { IOT_WARN("%s : watchdog close failed.\n",__FUNCTION__); ret = IOT_FAILED; } else{ IOT_INFO("%s : watchdog close OK.\n",__FUNCTION__); } __watchdog_fd = -1; return ret; } /*********************************************************************/ /* * set_keeptime_watchdog * 设置喂狗超时时间 * * @param * unsigned int time 喂狗超时时间 * * @return unsigned int * 成功: IOT_SUCCEESE * 失败: IOT_FAILED * * @note * **********************************************************************/ unsigned int set_keeptime_watchdog(unsigned int time) { #ifndef WDT_ENABLE return IOT_SUCCEESE; #endif /*set time*/ if(ioctl(__watchdog_fd,WDIOC_SETTIMEOUT,&time) < 0){ IOT_WARN("%s : watchdog set timeout failed.\n",__FUNCTION__); return IOT_FAILED; } else{ IOT_INFO("%s : watchdog set timeout %d.\n",__FUNCTION__, time); return IOT_SUCCEESE; } } /*********************************************************************/ /* * feed_watchdog * 喂狗 * * @param * * * @return unsigned int * 成功: IOT_SUCCEESE * 失败: IOT_FAILED * * @note * **********************************************************************/ unsigned int feed_watchdog(){ #ifndef WDT_ENABLE return IOT_SUCCEESE; #endif static unsigned int cnt = 0; /*防止喂狗错误输出过于频繁*/ if(__watchdog_fd < 0) { if( (cnt%100) == 0) { IOT_WARN("%s : watchdog not opened.\n",__FUNCTION__); } else{ cnt ++; } return IOT_FAILED; } else{ } if(ioctl(__watchdog_fd,WDIOC_KEEPALIVE) < 0){ if( (cnt%300) == 0 ) { IOT_WARN("%s : feed watchdog failed.\n",__FUNCTION__); } else{ cnt ++; } return IOT_FAILED; } else{ return IOT_SUCCEESE; } }
2.5
2
2024-11-18T22:09:51.790290+00:00
2017-01-30T23:56:51
9e88742e3f501e3eefc45b80436e2cd99c3f355d
{ "blob_id": "9e88742e3f501e3eefc45b80436e2cd99c3f355d", "branch_name": "refs/heads/master", "committer_date": "2017-01-30T23:56:51", "content_id": "320a7a3ae61eba94b11a43a755a95ce844b7bb01", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f8ce0493db3f2bde39e27afb0c5db5995e16e19f", "extension": "c", "filename": "FileMerge.c", "fork_events_count": 0, "gha_created_at": "2018-02-20T20:34:26", "gha_event_created_at": "2018-02-20T20:34:26", "gha_language": null, "gha_license_id": null, "github_id": 122252793, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2561, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Sinalgo/data/sensor_readings/FileMerge.c", "provenance": "stackv2-0106.json.gz:42503", "repo_name": "kelsonribeiro/Cluster_WSN", "revision_date": "2017-01-30T23:56:51", "revision_id": "d2fe398726dd494a0a693e557170ad10cc79d33b", "snapshot_id": "e1143e016eec7b955704950f61f056776997407e", "src_encoding": "ISO-8859-1", "star_events_count": 2, "url": "https://raw.githubusercontent.com/kelsonribeiro/Cluster_WSN/d2fe398726dd494a0a693e557170ad10cc79d33b/Sinalgo/data/sensor_readings/FileMerge.c", "visit_date": "2021-04-28T08:33:47.221286" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> int main(){ setlocale(LC_ALL,"ptb"); FILE *arq1,*arq2,*arqConcat; char nome1[50],nome2[50],c; printf("Programa para concatenar o conteúdo de 2 Arquivos-Textos dados em um novo arquivo, com nome dado pelo usuário\n"); printf("Digite o nome do 1º arquivo texto a ser concatenado: "); gets(nome1); printf("Digite o nome do 2º arquivo texto a ser concatenado: "); gets(nome2); printf("Os nomes dos arquivos-texto digitados foram: %s e %s\n",nome1,nome2); system("pause"); arq1 = fopen(nome1,"r"); if(arq1 == NULL){ printf("Erro na abertura do arquivo %s!\n",nome1); //system("pause"); exit(1); } else{ printf("Abertura do arquivo %s realizada com sucesso!\n",nome1); } arq2 = fopen(nome2,"r"); if(arq2 == NULL){ printf("Erro na abertura do arquivo %s!\n",nome2); //system("pause"); exit(1); } else{ printf("Abertura do arquivo %s realizada com sucesso!\n",nome2); } int num = 1; char nome[50]; printf("Digite o nome do novo arquivo texto a ser gerado: "); gets(nome); arqConcat = fopen(nome,"w+"); if(arqConcat == NULL){ printf("Erro na abertura do arquivo: %s!\n",nome); //system("pause"); exit(1); } else{ printf("Criação do arquivo %s realizada com sucesso!\n",nome); } system("pause"); //nome = "NovoArquivo"+num+".txt"; /* sprintf(nome, "%s%i.txt","NovoArquivo",num); arqConcat = fopen(nome,"w+"); while(arqConcat == NULL){ num++; sprintf(nome,"%s%i.txt","NovoArquivo",num); arqConcat = fopen(nome,"w+"); //printf("Erro na criação do arquivo %s!\n",nomeNovo); //system("pause"); //exit(1); } printf("Criação do arquivo %s realizada com sucesso!\n",nome); */ //int i,num_linhas = 1; //Concatenando caracteres do arq1 while((c = fgetc(arq1)) != EOF) { // printf("%c",c); fputc(c,arqConcat); } //Concatenando caracteres do arq2 while((c = fgetc(arq2)) != EOF) { // printf("%c",c); fputc(c,arqConcat); } //Fechando os arquivos abertos fclose(arq1); fclose(arq2); //Voltando ao início de "arqConcat" //rewind(arqConcat); //Impressão de todo o conteúdo do arquivo /* while((c = fgetc(arqConcat)) != EOF) { printf("%c",c); } */ // printf("\nO número de linhas do arquivo %s é %d\n",nome,num_linhas); fclose(arqConcat); //system("pause"); return 0; }
3.265625
3
2024-11-18T22:09:52.321657+00:00
2023-08-18T10:48:30
9727faafe3827a6e01af7dd1bb368c22e3db71e8
{ "blob_id": "9727faafe3827a6e01af7dd1bb368c22e3db71e8", "branch_name": "refs/heads/master", "committer_date": "2023-08-18T10:48:30", "content_id": "0a07f17710ddb85558e42331d410cba9a557a4e4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e8b04bef9aa1ac8e2c109dd315f133c8f4d28ae6", "extension": "c", "filename": "spring_damping_force_plugin.c", "fork_events_count": 1525, "gha_created_at": "2018-11-05T14:09:10", "gha_event_created_at": "2023-08-28T16:30:33", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 156228018, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 885, "license": "Apache-2.0", "license_type": "permissive", "path": "/tests/physics/plugins/physics/spring_damping_force_plugin/spring_damping_force_plugin.c", "provenance": "stackv2-0106.json.gz:42634", "repo_name": "cyberbotics/webots", "revision_date": "2023-08-18T10:48:30", "revision_id": "8aba6eaae76989facf3442305c8089d3cc366bcf", "snapshot_id": "f075dacf4067e8dcebbfd89e8690df8525f6d745", "src_encoding": "UTF-8", "star_events_count": 2495, "url": "https://raw.githubusercontent.com/cyberbotics/webots/8aba6eaae76989facf3442305c8089d3cc366bcf/tests/physics/plugins/physics/spring_damping_force_plugin/spring_damping_force_plugin.c", "visit_date": "2023-08-31T09:41:13.205940" }
stackv2
#include <ode/ode.h> #include <plugins/physics.h> static int BODIES_COUNT = 6; static dBodyID *bodies = NULL; void webots_physics_init() { int i = 0; bodies = malloc(BODIES_COUNT * sizeof(dBodyID)); char name[32]; for (i = 0; i < BODIES_COUNT; ++i) { sprintf(name, "END_POINT_SOLID_%d", i + 1); bodies[i] = dWebotsGetBodyFromDEF(name); if (bodies[i] == NULL) dWebotsConsolePrintf("Invalid body %s\n", name); } } void webots_physics_step() { static int step_count = 0; if (step_count >= 20) return; dBodyAddRelForce(bodies[0], 0.2, 0.0, 0.0); dBodyAddRelForce(bodies[1], 0.2, 0.0, 0.0); dBodyAddRelForce(bodies[2], 0.0, 5.0, 0.0); dBodyAddRelForce(bodies[3], 0.0, 0.0, -5.0); dBodyAddRelForce(bodies[4], 1.0, 0.0, 0.5); dBodyAddRelForce(bodies[5], 1.0, 0.0, 0.5); step_count++; } void webots_physics_cleanup() { free(bodies); }
2.421875
2
2024-11-18T22:09:52.451145+00:00
2019-06-19T10:36:44
a93f4ef64bb3ef073b6774a40fe13482b7c067ab
{ "blob_id": "a93f4ef64bb3ef073b6774a40fe13482b7c067ab", "branch_name": "refs/heads/master", "committer_date": "2019-06-19T10:36:44", "content_id": "69d53746f52b26a57ef10b6d0ba6576743f641e4", "detected_licenses": [ "Apache-2.0" ], "directory_id": "594b35b05fc3825ba52f0bc86a7073bdeb355684", "extension": "c", "filename": "nv_list.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 192347821, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7596, "license": "Apache-2.0", "license_type": "permissive", "path": "/Middlewares/private/nv_list/nv_list.c", "provenance": "stackv2-0106.json.gz:42763", "repo_name": "KarmaStone/stm32_project", "revision_date": "2019-06-19T10:36:44", "revision_id": "55fd8a625486cdd55a2178047e9f3503545a3fa7", "snapshot_id": "3a77b1c9e9d500bf40b7dc58fc3576e989d027d4", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/KarmaStone/stm32_project/55fd8a625486cdd55a2178047e9f3503545a3fa7/Middlewares/private/nv_list/nv_list.c", "visit_date": "2020-06-05T06:48:29.384029" }
stackv2
#include "nv_list.h" #include "crc32.h" #include "stdlib.h" uint8_t nv_buf[4096]; /* ** */ void nvlist_clear(nv_list *list) { uint32_t addr = 0; uint32_t page = list->max * list->index_size / list->page_size; if ((list->max * list->index_size) % list->page_size != 0) { page = list->max * list->index_size / list->page_size + 1; } else { page = list->max * list->index_size / list->page_size; } nv_flash_getlock(); for (uint8_t i = 0; i < page; i++) { addr = list->index_addr + i * list->page_size; nv_flash_earse(addr); } nv_flash_reslock(); } /* ** */ uint32_t nvlist_read_id( nv_list *list , uint32_t index) { uint32_t tempID = 0; nv_flash_read(list->index_addr + index * list->index_size, (uint8_t *)&tempID, list->index_size); return tempID; } /* ** */ void nvlist_read_data(nv_list *list , uint32_t index) { nv_flash_read(list->data_addr + index * list->data_size, list->data, list->data_size); } void nvlist_del_index( nv_list *list , uint32_t index) { uint32_t addr = 0, page = 0; addr = list->index_addr + index * list->index_size; page = addr / list->page_size; nv_flash_getlock(); nv_flash_read(page * list->page_size, nv_buf, list->page_size); *(uint32_t *)(nv_buf + (index * list->index_size) % list->page_size) = EMPTY_ID; nv_flash_earse(page * list->page_size); nv_flash_write(page * list->page_size, nv_buf, list->page_size); nv_flash_reslock(); } void nvlist_del_index_no_lock( nv_list *list , uint32_t index) { uint32_t addr = 0, page = 0; addr = list->index_addr + index * list->index_size; page = addr / list->page_size; nv_flash_read(page * list->page_size, nv_buf, list->page_size); *(uint32_t *)(nv_buf + (index * list->index_size) % list->page_size) = EMPTY_ID; nv_flash_earse(page * list->page_size); nv_flash_write(page * list->page_size, nv_buf, list->page_size); } void nvlist_add_index(nv_list *list , uint32_t index) { uint32_t addr = 0, page = 0, ID = 0; addr = list->index_addr + index * list->index_size; page = addr / list->page_size; ID = crc32(list->index_data, list->index_cnt); nv_flash_getlock(); nv_flash_read(page * list->page_size, nv_buf, list->page_size); *(uint32_t *)(nv_buf + (index * list->index_size) % list->page_size) = ID; nv_flash_earse(page * list->page_size); nv_flash_write(page * list->page_size, nv_buf, list->page_size); nv_flash_reslock(); } int32_t nvlist_find_index(nv_list *list , uint32_t ID) { uint32_t tempID; nv_flash_getlock(); for (uint32_t i = 0; i < list->max; i++) { nv_flash_read(list->index_addr + i * list->index_size, (uint8_t *)&tempID, 4); if (tempID == ID) { nv_flash_reslock(); return i; } } nv_flash_reslock(); return FIND_NULL_ID; } void nvlist_add_data( nv_list *list , uint32_t index) { uint32_t addr = 0, page = 0; addr = list->data_addr + index * list->data_size; page = addr / list->page_size; nv_flash_getlock(); nv_flash_read(page * list->page_size, nv_buf, list->page_size); memcpy(nv_buf + (index * list->data_size) % list->page_size, list->data, list->data_size); nv_flash_earse(page * list->page_size); nv_flash_write(page * list->page_size, nv_buf, list->page_size); nv_flash_reslock(); } int32_t find_index(nv_list *list) { uint32_t tem = 0; uint32_t pos = 0; uint32_t ID = 0; ID = crc32(list->index_data, list->index_cnt); nv_flash_getlock(); for (uint32_t addr = list->index_addr; addr < list->index_addr + list->max * list->index_size; addr += 4096) { nv_flash_read(addr, nv_buf, 4096); for (uint16_t i = 0; i < 4096 / list->index_size; i++) { tem = 0; memcpy(&tem, nv_buf + i * list->index_size, list->index_size); if (tem == ID) { pos = ((addr + i * list->index_size) - list->index_addr) / list->index_size; nvlist_read_data( list , pos ); nv_flash_reslock(); return (pos); } } } nv_flash_reslock(); return FIND_NULL_ID; } int32_t nvlist_find(nv_list *list) { uint32_t pos = 0; uint32_t tick = HAL_GetTick(); if ((pos = find_index(list)) != FIND_NULL_ID) { log(DEBUG, "在 %d 位置查询到数据 , 查询时间:%d\n", pos, HAL_GetTick() - tick); return pos; } log(DEBUG, "该卡号不在黑白名单中, 查询时间:%d\n", HAL_GetTick() - tick); return FIND_NULL_ID; } int32_t nvlist_add(nv_list *list) { uint32_t index = 0; nv_list temp_list; memcpy(&temp_list , list , sizeof(nv_list)); temp_list.data = malloc(temp_list.data_size); memset(temp_list.data , 0x00 , temp_list.data_size); if ((index = nvlist_find(&temp_list)) == FIND_NULL_ID) { log(DEBUG, "当前黑白名单列表没有找到对应卡号,新增名单\n"); if ((index = nvlist_find_index(&temp_list , EMPTY_ID)) == FIND_NULL_ID) { log(WARN, "黑白名单数据已经满了。\n"); return LIST_FULL; } log(DEBUG, "找到一个空闲位置,位置:%d\n", index); nvlist_add_index(&temp_list , index); } else { log(DEBUG, "当前列表中存在改卡号,位置:%d \n", index); } if (memcmp(temp_list.data,list->data, list->data_size) == TRUE) { log(DEBUG, "写入的数据和存储的数据一样,不用重新写入\n"); } else { log(DEBUG, "数据将写入到 %d 位置中。\n", index); nvlist_add_data( list , index ); } return LIST_SUCCESS; } int32_t nvlist_del(nv_list *list) { uint32_t index = 0; if ((index = nvlist_find(list)) == FIND_NULL_ID) { log(DEBUG, "列表中没有改名单,删除失败\n"); } else { log(DEBUG, " 在%d 位置删除\n", index); nvlist_del_index(list , index); } return LIST_SUCCESS; } void nvlist_show(nv_list *list) { uint32_t cnt = 0; nv_flash_getlock(); for (uint32_t i = 0; i < list->max; i++) { if (nvlist_read_id(list , i) != EMPTY_ID) { cnt++; } } nv_flash_reslock(); log(DEBUG, "当前设备黑白名单条数:%d\n", cnt); } /* void permiList_clear_overdue(void) { permiListType list; uint32_t deviceTime; if (config.read(CFG_SYS_UPDATA_TIME, NULL) == TRUE) { deviceTime = rtc.read_stamp(); log(DEBUG, "当前设备时间戳:%d\n", deviceTime); nv_flash_getlock(); for (uint32_t i = 0; i < 8000; i++) { if (nvlist_read_id(i) != EMPTY_ID) { nvlist_read_data(i, &list); if (list.time < deviceTime) { log(DEBUG, "删除过期黑白名单,POS=%d , ID=%llx , TIME:%u\n", i, list.ID, list.time); nvlist_del_index_no_lock(i); } if ((list.status != LIST_BLACK) && (list.status != LIST_WRITE)) { log(INFO, "黑白名单状态错误,status=%d , 删除POS=%d\n", list.status, i); nvlist_del_index_no_lock(i); } } HAL_IWDG_Refresh(&hiwdg); } nv_flash_reslock(); } else { log(INFO, "设备还没有同步时间\n"); } } */
2.671875
3
2024-11-18T22:09:52.701419+00:00
2018-12-11T21:58:55
2c93f3bc2f94dc9cadabcc68fe4f05b73b93410c
{ "blob_id": "2c93f3bc2f94dc9cadabcc68fe4f05b73b93410c", "branch_name": "refs/heads/master", "committer_date": "2018-12-11T21:58:55", "content_id": "9cd75bccc618c83ff70b99d038a7bff001c1a692", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "db3195bbe3a52fd2688f6c8b62342a60167613dc", "extension": "c", "filename": "struct.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 161398954, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3381, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/testing/structure-shape/struct.c", "provenance": "stackv2-0106.json.gz:43019", "repo_name": "devnull-cz/adv-unix-linux-prog-in-c-src", "revision_date": "2018-12-11T21:58:55", "revision_id": "f624883bf59a9864dce9d665cff3bc9b1f5f2562", "snapshot_id": "abf36fcb52d14ca13514ababeeb2e04e287f7897", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/devnull-cz/adv-unix-linux-prog-in-c-src/f624883bf59a9864dce9d665cff3bc9b1f5f2562/testing/structure-shape/struct.c", "visit_date": "2020-04-11T00:51:51.006988" }
stackv2
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright 2009 Jan Pechanec, Vladimir Kotal. All rights reserved. * Use is subject to license terms. */ /* * Example for testing. How many bugs are in the code ? How to construct * test cases to capture them all ? Adapt the code so that it can be tested * by automated program and write a simple fuzzer and run it - how many * problematic cases it discovered ? What about smart fuzzing ? */ #include <stdio.h> #include <err.h> /* minimum difference (in seconds) */ #define MINDIFF 60 /* assume 1 MB/s */ #define SECS2KBYTES(x) ((x) << 20) /* defaults */ #define DEFAULT_HARD 28800 /* 8 hours */ #define DEFAULT_SOFT 25200 /* 7 hours */ /* * Rules: * * soft_sec < hard_sec * soft_kb < hard_kb * diff(soft_*, hard_*) >= MINDIFF * */ typedef struct entry_s { unsigned timer_hard_sec; unsigned timer_soft_sec; unsigned timer_hard_kb; unsigned timer_soft_kb; } entry_t; /* Shape up the structure from the input data according to the rules above. */ int main(int argc, char *argv[]) { entry_t e; if (argc != 5) errx(1, "usage: %s <hard_sec> <soft_sec> <hard_kb> <soft_kb>\n" "\tdefault value: 0", argv[0]); if (atoi(argv[1]) == 0) e.timer_hard_sec = DEFAULT_HARD; else e.timer_hard_sec = atoi(argv[1]); if (atoi(argv[2]) == 0) e.timer_soft_sec = DEFAULT_SOFT; else e.timer_soft_sec = atoi(argv[2]); if (atoi(argv[3]) == 0) e.timer_hard_kb = SECS2KBYTES(e.timer_hard_sec); else e.timer_hard_kb = atoi(argv[3]); if (atoi(argv[4]) == 0) e.timer_soft_kb = SECS2KBYTES(e.timer_hard_sec); else e.timer_soft_kb = atoi(argv[4]); if (e.timer_hard_sec - e.timer_soft_sec < MINDIFF) e.timer_soft_sec -= MINDIFF; if (e.timer_hard_kb - e.timer_soft_kb < MINDIFF) e.timer_soft_kb -= MINDIFF; printf("Resulting structure:\n" "hard_sec = %u\n" "soft_sec = %u\n" "hard_kb = %u\n" "soft_kb = %u\n", e.timer_hard_sec, e.timer_soft_sec, e.timer_hard_kb, e.timer_soft_kb); return (0); }
2.359375
2
2024-11-18T22:09:52.925440+00:00
2017-04-30T02:29:17
4588985a77b99a6cfa3e53daea22e22c5166978a
{ "blob_id": "4588985a77b99a6cfa3e53daea22e22c5166978a", "branch_name": "refs/heads/master", "committer_date": "2017-04-30T02:29:17", "content_id": "ab4f5b4a2f15955558d73a72082127131f93a4bf", "detected_licenses": [ "MIT" ], "directory_id": "38ce2ded8af2a4f3fb43afd18f45d235d026850d", "extension": "c", "filename": "mstran.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 62423882, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9999, "license": "MIT", "license_type": "permissive", "path": "/msp/src/mstran.c", "provenance": "stackv2-0106.json.gz:43408", "repo_name": "mlconnolly1951/biohedron", "revision_date": "2017-04-30T02:29:17", "revision_id": "5ee538068dab114d965e07204f6634cca000b0b8", "snapshot_id": "9845b9ed2b09f96744c4b463421f163d5adbcf83", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mlconnolly1951/biohedron/5ee538068dab114d965e07204f6634cca000b0b8/msp/src/mstran.c", "visit_date": "2021-01-16T21:46:14.395337" }
stackv2
/* MSTran MS Translate to other formats Copyright 1995 by Michael L. Connolly All Rights Reserved December 20, 2001 */ #include "ms.h" #include "msenum.h" #include "mslimit.h" #include "msdefault.h" #include "msstruct.h" #include "msglobal.h" #include "msfunction.h" int mstran (struct msscene *ms, FILE *fpt, FILE *fpd, FILE *fpm, FILE *fpg, FILE *fpo, int fn, int which_value, double minval, double maxval, struct color_ramp *ramp, double ctrlev, int uniform_hue) { int result; long norg; double tolerance = 0.3; char message[MAX_STRING]; struct surface *phn, *tan, *btn, *orgphn; struct surface *den; struct oringe *org, *head, *tail; struct molecule *mol; if (fpo == NULL) return(0); if (fpt != NULL) { phn = read_polyhedron (fpt); fclose(fpt); if (phn == NULL) return (0); if (which_value < 0 || minval == maxval) phn -> scheme = define_scheme (UNIFORM_COLORING, uniform_hue, which_value, minval, maxval); else phn -> scheme = define_scheme (VERTEX_COLORING, 0, which_value, minval, maxval); if (error()) return (0); if (phn -> scheme == NULL) { set_error2 ("mstran: define_scheme returns null"); return (0); } if (fn == INVENTOR) { write_header_iv (ms, fpo); if (error()) return (0); write_tri_iv (ms, phn, fpo, ramp); } else if (fn == WHATIF) write_whatif (phn, fpo); else if (fn == O) write_Os (phn, fpo, "dot"); if (error()) return (0); } if (fpd != NULL) { den = read_density (fpd); fclose (fpd); if (den == NULL) return(0); result = polygonize_density (den, ctrlev); if (result == 0) return (0); den -> scheme = define_scheme (UNIFORM_COLORING, uniform_hue, 0, 0.0, 1.0); if (den -> scheme == NULL) return (0); write_header_iv (ms, fpo); if (error()) return (0); write_den_iv (ms, den, ctrlev, fpo); if (error()) return (0); /* close output file */ fclose (fpo); } if (fpg != NULL) { norg = 0; head = NULL; tail = NULL; for (;;) { org = read_oringe (fpg); if (error ()) break; if (org == NULL) break; /* End of File */ norg++; if (head == NULL) head = org; else tail -> next = org; tail = org; } fclose (fpg); if (error ()) return (0); sprintf (message, "%ld oringe records read", norg); inform (message); orgphn = polyhedron_oringes (head, 0.2, ORG_SURFACE); if (error()) return (0); orgphn -> scheme = define_scheme (UNIFORM_COLORING, 2, -1, 0.0, 0.0); if (error()) return (0); if (orgphn -> scheme == NULL) { set_error2 ("mstran: define_scheme returns null"); return (0); } write_header_iv (ms, fpo); if (error()) return (0); write_edg_iv (ms, orgphn, fpo); if (error()) return (0); } if (fpm != NULL) { mol = read_molecule (ms, "", "", DEFAULT_ALPHA, fpm, NULL, NULL, NULL); fclose(fpm); if (mol == NULL) return (0); if (error()) return (0); connect_command ("atoms", tolerance); write_header_iv (ms, fpo); if (error()) return (0); write_mol_iv (ms, mol, fpo); } fclose (fpo); return(1); } void tran_mem () { unsigned long size; int type; char type_name[32]; init_mem ((unsigned long) N_OBJECTS); if (error()) return; type = MSSCENE; size = sizeof (struct msscene); strcpy (type_name, "msscene"); define_type (type, size, type_name); if (error()) return; type = SPHERE; size = sizeof (struct sphere); strcpy (type_name, "sphere"); define_type (type, size, type_name); if (error()) return; type = TORUS; size = sizeof (struct torus); strcpy (type_name, "torus"); define_type (type, size, type_name); if (error()) return; type = PROBE; size = sizeof (struct probe); strcpy (type_name, "probe"); define_type (type, size, type_name); if (error()) return; type = VERTEX; size = sizeof (struct vertex); strcpy (type_name, "vertex"); define_type (type, size, type_name); if (error()) return; type = CIRCLE; size = sizeof (struct circle); strcpy (type_name, "circle"); define_type (type, size, type_name); if (error()) return; type = ARC; size = sizeof (struct arc); strcpy (type_name, "arc"); define_type (type, size, type_name); if (error()) return; type = FACE; size = sizeof (struct face); strcpy (type_name, "face"); define_type (type, size, type_name); if (error()) return; type = CYCLE; size = sizeof (struct cycle); strcpy (type_name, "cycle"); define_type (type, size, type_name); if (error()) return; type = EDGE; size = sizeof (struct edge); strcpy (type_name, "edge"); define_type (type, size, type_name); if (error()) return; type = COMPONENT; size = sizeof (struct component); strcpy (type_name, "component"); define_type (type, size, type_name); if (error()) return; type = SURFACE; size = sizeof (struct surface); strcpy (type_name, "surface"); define_type (type, size, type_name); if (error()) return; type = VARIETY; size = sizeof (struct variety); strcpy (type_name, "variety"); define_type (type, size, type_name); if (error()) return; type = PHNVTX; size = phnvtx_size (); strcpy (type_name, "phnvtx"); define_type (type, size, type_name); type = PHNEDG; size = phnedg_size (); strcpy (type_name, "phnedg"); define_type (type, size, type_name); type = PHNTRI; size = phntri_size (); strcpy (type_name, "phntri"); define_type (type, size, type_name); type = POLYGON; size = sizeof (struct polygon); strcpy (type_name, "polygon"); define_type (type, size, type_name); type = HEDVTX; size = sizeof (struct hedvtx); strcpy (type_name, "hedvtx"); define_type (type, size, type_name); if (error()) return; type = HEDEDG; size = sizeof (struct hededg); strcpy (type_name, "hededg"); define_type (type, size, type_name); if (error()) return; type = HEDTRI; size = sizeof (struct hedtri); strcpy (type_name, "hedtri"); define_type (type, size, type_name); if (error()) return; type = VTXGRP; size = sizeof (struct vtxgrp); strcpy (type_name, "vtxgrp"); define_type (type, size, type_name); if (error()) return; type = HEDRON; size = sizeof (struct hedron); strcpy (type_name, "hedron"); define_type (type, size, type_name); if (error()) return; type = MOLECULE; size = sizeof (struct molecule); strcpy (type_name, "molecule"); define_type (type, size, type_name); type = OBJECT_SCHEME; size = sizeof (struct object_scheme); strcpy (type_name, "object_scheme"); define_type (type, size, type_name); if (error()) return; type = COLOR_RAMP; size = sizeof (struct color_ramp); strcpy (type_name, "color_ramp"); define_type (type, size, type_name); if (error()) return; type = ORINGE; size = sizeof (struct oringe); strcpy (type_name, "oringe"); define_type (type, size, type_name); if (error()) return; type = RECORD; size = sizeof (struct record); strcpy (type_name, "record"); define_type (type, size, type_name); if (error()) return; type = TOKEN; size = sizeof (struct token); strcpy (type_name, "token"); define_type (type, size, type_name); if (error()) return; type = EDGER; size = sizeof (struct edger); strcpy (type_name, "edger"); define_type (type, size, type_name); if (error()) return; type = MATERIAL_TABLE; size = sizeof (struct material_table); strcpy (type_name, "material_table"); define_type (type, size, type_name); if (error()) return; type = PATTERNRECORD; size = sizeof (struct patternRecord); strcpy (type_name, "patternRecord"); define_type (type, size, type_name); if (error()) return; type = RADIUSRECORD; size = sizeof (struct radiusRecord); strcpy (type_name, "radiusRecord"); define_type (type, size, type_name); if (error()) return; type = RESIDUEINDEX; size = sizeof (struct residueIndex); strcpy (type_name, "residueIndex"); define_type (type, size, type_name); if (error()) return; type = ARRAY; size = sizeof (struct array); strcpy (type_name, "array"); define_type (type, size, type_name); if (error()) return; type = ATOM; size = sizeof (struct atom); strcpy (type_name, "atom"); define_type (type, size, type_name); if (error()) return; type = BOND; size = sizeof (struct bond); strcpy (type_name, "bond"); define_type (type, size, type_name); if (error()) return; type = OBJECT_HEADER; size = sizeof (struct object_header); strcpy (type_name, "object_header"); define_type (type, size, type_name); if (error()) return; type = OBJECT_BLOCK; size = sizeof (struct object_block); strcpy (type_name, "object_block"); define_type (type, size, type_name); if (error()) return; type = ELEMENT; size = sizeof (struct element); strcpy (type_name, "element"); define_type (type, size, type_name); if (error()) return; type = ELEMENT_BLOCK; size = sizeof (struct element_block); strcpy (type_name, "element_block"); define_type (type, size, type_name); if (error()) return; type = SET; size = sizeof (struct set); strcpy (type_name, "set"); define_type (type, size, type_name); if (error()) return; type = SYMBOL; size = sizeof (struct symbol); strcpy (type_name, "symbol"); define_type (type, size, type_name); if (error()) return; type = BOOLEAN; size = sizeof (struct boolean); strcpy (type_name, "boolean"); define_type (type, size, type_name); if (error()) return; type = INTEGER; size = sizeof (struct integer); strcpy (type_name, "integer"); define_type (type, size, type_name); if (error()) return; type = REAL; size = sizeof (struct real); strcpy (type_name, "real"); define_type (type, size, type_name); if (error()) return; type = STRING; size = sizeof (struct string); strcpy (type_name, "string"); define_type (type, size, type_name); if (error()) return; type = REGION; size = sizeof (struct region); strcpy (type_name, "region"); define_type (type, size, type_name); if (error()) return; type = CEPT; size = sizeof (struct cept); strcpy (type_name, "cept"); define_type (type, size, type_name); if (error()) return; } /* mstran Copyright 1998 by Michael L. Connolly All Rights Reserved */
2.15625
2
2024-11-18T22:09:53.547847+00:00
2014-12-02T13:27:08
5e3af8a80742b29eff9d49b62918cdcaeb8c2576
{ "blob_id": "5e3af8a80742b29eff9d49b62918cdcaeb8c2576", "branch_name": "refs/heads/master", "committer_date": "2014-12-02T13:27:08", "content_id": "0481901746b15efbb2897d6c02f05ac88f3b3a19", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e67dd9c8292725e024bf66073b285d36c81bfb8e", "extension": "h", "filename": "stack.h", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 27294726, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 492, "license": "Apache-2.0", "license_type": "permissive", "path": "/stack.h", "provenance": "stackv2-0106.json.gz:43794", "repo_name": "yadavvi91/MinimumSpanningTree", "revision_date": "2014-12-02T13:27:08", "revision_id": "f0b7e0addcc2ef603756f70b539884f23415e34b", "snapshot_id": "8941865d3fe7d699a8e08a73c4aedc37fe7376ab", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/yadavvi91/MinimumSpanningTree/f0b7e0addcc2ef603756f70b539884f23415e34b/stack.h", "visit_date": "2021-01-01T18:41:54.843434" }
stackv2
#ifndef STACK_H_INCLUDED #define STACK_H_INCLUDED typedef struct stack_node { int value; struct stack_node *prev; } stack_node; typedef struct stack { int size; stack_node *top; } stack; typedef int boolean; #define TRUE 1 #define FALSE 0 #define NMAX 1000 stack* stack_create(); void stack_push(stack *stack_inst, int value); int stack_pop(stack *stack_inst); boolean stack_is_empty(stack *stack_inst); void stack_destroy(stack *stack_inst); #endif // STACK_H_INCLUDED
2.171875
2
2024-11-18T22:09:55.045228+00:00
2020-08-07T01:51:16
e35300df6c3307ca6f41191324b38b3d37c18c81
{ "blob_id": "e35300df6c3307ca6f41191324b38b3d37c18c81", "branch_name": "refs/heads/master", "committer_date": "2020-08-07T01:51:16", "content_id": "36d2aa1310b2336db2e7c36c99812d9aeb5a09fb", "detected_licenses": [ "MIT" ], "directory_id": "feb08986f99162d579f3350bd1d2663b188d1496", "extension": "c", "filename": "exercicio05.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 258096389, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 770, "license": "MIT", "license_type": "permissive", "path": "/C/Listas/Lista 2/exercicio05.c", "provenance": "stackv2-0106.json.gz:44053", "repo_name": "Lucas-Angelo/AED1", "revision_date": "2020-08-07T01:51:16", "revision_id": "e45d79340457463b0bde77d7e96b704e910d9713", "snapshot_id": "80acbc1b28fb9d089577efcfeb0ef2f9c965baf9", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Lucas-Angelo/AED1/e45d79340457463b0bde77d7e96b704e910d9713/C/Listas/Lista 2/exercicio05.c", "visit_date": "2022-11-25T11:56:56.742254" }
stackv2
#include <stdio.h> #include <stdlib.h> int main() { float custoF, custoC; printf("Qual o custo de fabrica do seu novo carro? "); scanf("%f", &custoF); if(custoF <= 28000) { custoC = custoF + (custoF*0.05); printf("O custo do consumidor com a aplicacao de impostos no seu carro e de: R$%.2f\n\n", custoC); } else if(custoF > 28000 && custoF < 45000) { custoC = custoF + (custoF*0.10) + (custoF*0.15); printf("O custo do consumidor com a aplicacao de impostos no seu carro e de: R$%.2f\n\n", custoC); } else { custoC = custoF + (custoF*0.15) + (custoF*0.20); printf("O custo do consumidor com a aplicacao de impostos no seu carro e de: R$%.2f\n\n", custoC); } return 0; }
3.0625
3
2024-11-18T22:09:55.166209+00:00
2020-06-22T03:38:25
32de4040dc9311eddfb65ceb3cd3c6fd852f17b8
{ "blob_id": "32de4040dc9311eddfb65ceb3cd3c6fd852f17b8", "branch_name": "refs/heads/master", "committer_date": "2020-06-22T03:38:25", "content_id": "2ffea1491da22886a70dcc5bd1e1dbdec1eba98d", "detected_licenses": [ "MIT" ], "directory_id": "5c6b88c3954b4dde11e70f7abe644414cd81f0b1", "extension": "c", "filename": "batch.c", "fork_events_count": 0, "gha_created_at": "2019-10-29T18:31:13", "gha_event_created_at": "2020-06-22T03:38:26", "gha_language": "C", "gha_license_id": "MIT", "github_id": 218356374, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6997, "license": "MIT", "license_type": "permissive", "path": "/source/push[exe]/batch.c", "provenance": "stackv2-0106.json.gz:44311", "repo_name": "fengjixuchui/Push", "revision_date": "2020-06-22T03:38:25", "revision_id": "662cfb8684af63b8c8afbd742aeabdfa195441fb", "snapshot_id": "7787df9c87856170df7fefa248c468b76d202331", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fengjixuchui/Push/662cfb8684af63b8c8afbd742aeabdfa195441fb/source/push[exe]/batch.c", "visit_date": "2020-08-30T10:49:43.703793" }
stackv2
#include <sl.h> #include "push.h" #include "file.h" #include "batch.h" WCHAR* BatchFileName; VOID GetBatchFile( PUSH_GAME* Game, WCHAR* Buffer ) { WCHAR *dot; WCHAR batchFile[260]; String_Copy(batchFile, L"cache\\"); String_Concatenate(batchFile, Game->Name); dot = String_FindLastChar(batchFile, '.'); if (dot) String_Copy(dot, L".txt"); else String_Concatenate(batchFile, L".txt"); String_Copy(Buffer, batchFile); } VOID BatchFile_Initialize( PUSH_GAME* Game ) { UINT64 fileSize; VOID *buffer = NULL, *bufferOffset; WCHAR *lineStart, *nextLine, *end; FILE_LIST_ENTRY fileEntry; WCHAR line[260]; UINT16 lineLength; WCHAR batchFile[260]; FileList = NULL; // Get the batchfile name and path GetBatchFile(Game, batchFile); // Allocate some memory for the batchfile name BatchFileName = (WCHAR*) Memory_Allocate( (String_GetLength(batchFile) + 1) * sizeof(WCHAR) ); // Save new batchfile name String_Copy(BatchFileName, batchFile); // Open the batchfile and read the entire file into memory buffer = File_Load(batchFile, &fileSize); if (!buffer) return; // Start our reads after the UTF16-LE character marker bufferOffset = (WCHAR*) buffer + 1; // Update fileSize to reflect. It is now invalid for use as the // actual file size. fileSize -= sizeof(WCHAR); // Get the end of the buffer end = (WCHAR *)((UINT_B)bufferOffset + fileSize); // Let's start the day off nicely nextLine = (WCHAR*) bufferOffset; fileSize = 0; // Get all file names and queue them for caching while (nextLine < end) { lineStart = nextLine; // Try to find new line character nextLine = Memory_FindFirstChar(lineStart, '\n', end - lineStart); if (!nextLine) // Didn't find it? How about return? nextLine = Memory_FindFirstChar(lineStart, '\r', end - lineStart); if (!nextLine) // Still didn't find any? Must not be one. nextLine = end + 1; lineLength = (nextLine - 1) - lineStart; // Copy line into a buffer String_CopyN(line, lineStart, lineLength); // Terminate the buffer; line[lineLength] = L'\0'; nextLine++; // Add to file list fileEntry.Name = line; fileEntry.Bytes = File_GetSize(line); PushAddToFileList(&FileList, &fileEntry); // Increment total batch size counter fileSize += fileEntry.Bytes; } // Be a nice guy and give back what was given to you Memory_Free(buffer); // Update batch size; BatchSize = fileSize; } /** * Checks whether a file is included in a batchfile. * * \param BatchFile The batchfile. * \param File A pointer to a FILE_LIST_ENTRY * structure representing the file. */ BOOLEAN BatchFile_IsBatchedFile( FILE_LIST_ENTRY* File ) { FILE_LIST_ENTRY *file; file = (FILE_LIST_ENTRY*) FileList; while (file != NULL) { if (File->Bytes == file->Bytes && String_Compare(File->Name, file->Name) == 0) return TRUE; file = file->NextEntry; } return FALSE; } /** * Gets the size (in bytes) of * a batchfile. * * \param BatchFile The batchfile. */ UINT64 BatchFile_GetBatchSize() { return BatchSize; } /** * Saves the batchfile to disk. * * \param BatchFile The batchfile. */ VOID BatchFile_SaveBatchFile( PUSH_GAME* Game ) { HANDLE fileHandle = NULL; IO_STATUS_BLOCK isb; FILE_LIST_ENTRY *file; WCHAR marker = 0xFEFF; WCHAR end[] = L"\r\n"; NTSTATUS status; status = File_Create( &fileHandle, BatchFileName, SYNCHRONIZE | FILE_READ_ATTRIBUTES | GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL ); // Check if \cache folder has not been created yet. if (status == STATUS_OBJECT_PATH_NOT_FOUND) { HANDLE directoryHandle; File_Create( &directoryHandle, L"cache", FILE_LIST_DIRECTORY | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_CREATE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT, NULL ); File_Close(directoryHandle); //try again. File_Create( &fileHandle, BatchFileName, SYNCHRONIZE | FILE_READ_ATTRIBUTES | GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL ); } file = (FILE_LIST_ENTRY*) FileList; if (file) { Game_SetFlags(Game, GAME_RAMDISK); } // Write character marker NtWriteFile( fileHandle, NULL, NULL, NULL, &isb, &marker, sizeof(marker), NULL, NULL ); // Write all batch items to file while (file != 0) { // Write a single item to batch file NtWriteFile( fileHandle, NULL, NULL, NULL, &isb, file->Name, String_GetLength(file->Name) * sizeof(WCHAR), NULL, NULL ); // Write new line NtWriteFile( fileHandle, NULL, NULL, NULL, &isb, &end, 4, NULL, NULL ); file = file->NextEntry; } if (fileHandle) { File_Close(fileHandle); } } /** * Adds an item to a * batchfile. * * \param BatchFile The * batchfile. * \param File Pointer to a * FILE_LIST_ENTRY structure * with details of the file. */ VOID BatchFile_AddItem( FILE_LIST_ENTRY* File ) { FILE_LIST_ENTRY file; file.Name = File->Name; file.Bytes = File->Bytes; PushAddToFileList( &FileList, &file ); } /** * Removes an item from a batchfile. * * \param File Pointer to a FILE_LIST_ENTRY structure with * details of the file. */ VOID BatchFile_RemoveItem( FILE_LIST_ENTRY* File ) { FILE_LIST_ENTRY *file, *previousEntry; file = FileList; while (file != 0) { if (file->Bytes == File->Bytes && String_Compare(file->Name, File->Name) == 0) { if (file == FileList) FileList = file->NextEntry; else previousEntry->NextEntry = file->NextEntry; break; } previousEntry = file; file = file->NextEntry; } } /** * Gets a pointer to * the batchfile list * used by the * BatchFile class. */ FILE_LIST BatchFile_GetBatchList() { return FileList; }
2.25
2
2024-11-18T22:09:55.662309+00:00
2023-07-07T18:18:01
2ecd48082c0116ed37e31561ea6f035b26b81f09
{ "blob_id": "2ecd48082c0116ed37e31561ea6f035b26b81f09", "branch_name": "refs/heads/master", "committer_date": "2023-07-07T18:20:16", "content_id": "903741f9f026774a0bca35030ecef4a3f7a9dd01", "detected_licenses": [ "Zlib" ], "directory_id": "9c4ec01e04f7b0a1d213e1060c6b0a008dde7cbd", "extension": "c", "filename": "main.c", "fork_events_count": 212, "gha_created_at": "2018-01-09T20:13:39", "gha_event_created_at": "2021-06-17T20:12:04", "gha_language": "C", "gha_license_id": "NOASSERTION", "github_id": 116865771, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12272, "license": "Zlib", "license_type": "permissive", "path": "/series2/pcnt/pcnt_oversampling_quadrature/src/main.c", "provenance": "stackv2-0106.json.gz:44569", "repo_name": "SiliconLabs/peripheral_examples", "revision_date": "2023-07-07T18:18:01", "revision_id": "87b252e5a1bf5b36a548c121e8ffda085d3bcbc4", "snapshot_id": "edf5ee87cd0bcb2e7ad5066e278fa1ad3b92bd35", "src_encoding": "UTF-8", "star_events_count": 326, "url": "https://raw.githubusercontent.com/SiliconLabs/peripheral_examples/87b252e5a1bf5b36a548c121e8ffda085d3bcbc4/series2/pcnt/pcnt_oversampling_quadrature/src/main.c", "visit_date": "2023-07-26T22:20:57.916375" }
stackv2
/***************************************************************************//** * @file main.c * @brief This project demonstrates the oversampling quadrature decoder mode of * the pulse counter peripheral. The program will request an interrupt whenever * the quadrature decoder detects a change in direction or a counter overflow or * counter underflow. The example utilizes OVSQUAD 4X mode, such that counter * value changes with each state transition of S1IN/S0IN (see PCNT State * Transitions in Reference Manual). LED0 toggles on detected direction changes, * and LED1 toggles on counter overflow/underflow events. Optional pulse width * filter and flutter removal are both enabled. ******************************************************************************* * # License * <b>Copyright 2021 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * SPDX-License-Identifier: Zlib * * The licensor of this software is Silicon Laboratories Inc. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * ******************************************************************************* * # Evaluation Quality * This code has been minimally tested to ensure that it builds and is suitable * as a demonstration for evaluation purposes only. This code will be maintained * at the sole discretion of Silicon Labs. ******************************************************************************/ #include "em_chip.h" #include "em_cmu.h" #include "em_device.h" #include "em_emu.h" #include "em_gpio.h" #include "em_pcnt.h" #include "em_prs.h" #include "mx25flash_spi.h" #include "bsp.h" // PRS channels to use for GPIO/PCNT #define PCNT_PRS_Ch0 0 #define PCNT_PRS_Ch1 1 // PCNT Top value with hysteresis #define PCNTTopValue 10 // Interrupt every 6 S1IN/S0IN state transitions in // the same direction // Push-buttons are active-low #define PB_PRESSED 0 /* * This example enters EM2 in the infinite while loop; Setting this define to 1 * enables debug connectivity in the EMU_CTRL register, which will consume about * 0.5uA additional supply current; comment this line of code to disable */ #define EM2DEBUG 1 /******************************************************************************* ************************** GLOBAL VARIABLES ******************************* ******************************************************************************/ int32_t absCnt = 0; // Counter value valid upon interrupt completion uint32_t UFCnt = 0; uint32_t OFCnt = 0; /***************************************************************************//** * @brief escapeHatch() * When developing or debugging code that enters EM2 or * lower, it's a good idea to have an "escape hatch" type * mechanism, e.g. a way to pause the device so that a debugger can * connect in order to erase flash, among other things. * * Before proceeding with this example, make sure PB0 is not pressed. * If the PB0 pin is low, turn on LED0 and execute the breakpoint * instruction to stop the processor in EM0 and allow a debug * connection to be made. ******************************************************************************/ void escapeHatch(void) { CMU_ClockEnable(cmuClock_GPIO, true); GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeInputPullFilter, 1); if (GPIO_PinInGet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN) == 0) { GPIO_PinModeSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN, gpioModePushPull, 1); __BKPT(0); } // Pin not asserted, so disable input else { GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeDisabled, 0); CMU_ClockEnable(cmuClock_GPIO, false); } } /***************************************************************************//** * @brief PCNT0 interrupt handler * This function acknowledges the interrupt and toggles LED0/LED1 ******************************************************************************/ void PCNT0_IRQHandler(void) { uint32_t flags = PCNT_IntGet(PCNT0); PCNT_IntClear(PCNT0, (PCNT_IF_DIRCNG | PCNT_IF_OF | PCNT_IF_UF)); if(PCNT0->STATUS & PCNT_STATUS_DIR) { // check direction; indicate with LED0 GPIO_PinOutSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN); // set LED0 if down } else { GPIO_PinOutClear(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN); // clear LED0 if up } if(flags & PCNT_IF_OF) { // check for overflow GPIO_PinOutToggle(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN); // toggle led 1 OFCnt += 1; } else if(flags & PCNT_IF_UF) { // check for underflow GPIO_PinOutToggle(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN); // toggle led 1 UFCnt += 1; } /* * absCnt value with hysteresis * Only valid on interrupt; CNT can/will change between interrupts * and not be captured in absCnt value until next direction change or * overflow/underflow event */ absCnt = PCNT0->CNT - UFCnt * (PCNTTopValue/2 + 1) + OFCnt * (PCNTTopValue/2 + 1); } /***************************************************************************//** * @brief Initialize PCNT0 * This function sets up PCNT0 with oversampling quadrature mode * S0 PRS linked to PRSCH0 * S1 PRS linked to PRSCH1 ******************************************************************************/ static void initPcnt(void) { PCNT_Init_TypeDef pcntInit = PCNT_INIT_DEFAULT; PCNT_Filter_TypeDef pcntFilterInit = PCNT_FILTER_DEFAULT; CMU_ClockEnable(cmuClock_PCNT0, true); pcntInit.mode = pcntModeOvsQuad4; // OVS quadrature mode pcntInit.top = PCNTTopValue; pcntInit.s1CntDir = false; // S1 does not affect counter direction, // using default init setting; count up pcntInit.s0PRS = PCNT_PRS_Ch0; pcntInit.s1PRS = PCNT_PRS_Ch1; pcntInit.filter = true; pcntInit.cntEvent = pcntCntEventBoth; // count up and down pcntInit.hyst = true; // Use max filter len for GPIO push button pcntFilterInit.filtLen = _PCNT_OVSCTRL_FILTLEN_MASK; pcntFilterInit.flutterrm = true; /* * With flutter removal enabled, counter is only updated if the current and * previous state transition of the rotation are in the same direction. */ // Enable PRS0 input PCNT_PRSInputEnable(PCNT0, pcntPRSInputS0, true); // Enable PRS1 input PCNT_PRSInputEnable(PCNT0, pcntPRSInputS1, true); // Filter configuration PCNT_FilterConfiguration(PCNT0, &pcntFilterInit, true); // PCNT0 Init PCNT_Init(PCNT0, &pcntInit); /* * On-board push button is active low on WSTK and PCNT is configured to count * on rising edge. Upon enabling PCNT module, initial state of push button * will cause the counter to increment without a button press. * * Wait here until this count propagates through counter-clock domain. */ while(PCNT0->CNT == 0); /* * Reset the count back to zero. * * Alternatively, modifying the PCNT initialization configuration to count on * falling edge (add "pcntInit.negEdge = true;" before PCNT_Init() function * call) would also alleviate additional count on PCNT module start-up, or the * PRS logic could be modified to negate the discrete on-board logic (select * NOT A function logic in PRS channel's FNSEL field). For this example, the * desire is to increment counter on push button release. Note that negating * both (negEdge and PRS logic) results in the same problem and would require * the counter clear that has been implemented for accurate count of the first * overflow event. */ PCNT0->CMD_SET = PCNT_CMD_CNTRST; // Enable PCNT0 interrupt PCNT_IntEnable(PCNT0, (PCNT_IEN_OF | PCNT_IEN_UF | PCNT_IEN_DIRCNG)); // Clear PCNT0 pending interrupt NVIC_ClearPendingIRQ(PCNT0_IRQn); // Enable PCNT0 interrupt in the interrupt controller NVIC_EnableIRQ(PCNT0_IRQn); } /***************************************************************************//** * @brief Initialize PRS * This function sets up GPIO PRS which links BTN0 and BTN1 to PRS0 and * PRS1, respectively ******************************************************************************/ static void initPrs(void) { CMU_ClockEnable(cmuClock_PRS, true); // Set up GPIO PRS PRS_SourceAsyncSignalSet(PCNT_PRS_Ch0, PRS_ASYNC_CH_CTRL_SOURCESEL_GPIO, BSP_GPIO_PB0_PIN); // Set up GPIO PRS PRS_SourceAsyncSignalSet(PCNT_PRS_Ch1, PRS_ASYNC_CH_CTRL_SOURCESEL_GPIO, BSP_GPIO_PB1_PIN); } /***************************************************************************//** * @brief Initialize GPIO setup * This function configures BTN0 and BTN1 as input and enables * external interrupts for BTN0 and BTN1 ******************************************************************************/ static void initGpio(void) { CMU_ClockEnable(cmuClock_GPIO, true); // Initialize LED driver GPIO_PinModeSet(BSP_GPIO_LED0_PORT, BSP_GPIO_LED0_PIN, gpioModePushPull, 0); GPIO_PinModeSet(BSP_GPIO_LED1_PORT, BSP_GPIO_LED1_PIN, gpioModePushPull, 0); // Configure pin I/O - BTN0 GPIO_PinModeSet(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, gpioModeInputPullFilter, 1); // Configure pin I/O - BTN1 GPIO_PinModeSet(BSP_GPIO_PB1_PORT, BSP_GPIO_PB1_PIN, gpioModeInputPullFilter, 1); // Configure BTN0 for external interrupt GPIO_ExtIntConfig(BSP_GPIO_PB0_PORT, BSP_GPIO_PB0_PIN, BSP_GPIO_PB0_PIN, false, false, false); // Configure BTN1 for external interrupt GPIO_ExtIntConfig(BSP_GPIO_PB1_PORT, BSP_GPIO_PB1_PIN, BSP_GPIO_PB1_PIN, false, false, false); } /***************************************************************************//** * @brief Main function ******************************************************************************/ int main(void) { FlashStatus status; CHIP_Init(); // Recommended recovery procedure for code in development escapeHatch(); // Select FSRCO for SYSCLK; FSRCO is default out of reset CMU_ClockSelectSet(cmuClock_SYSCLK, cmuSelect_FSRCO); // Turn on DCDC regulator EMU_DCDCInit_TypeDef dcdcInit = EMU_DCDCINIT_WSTK_DEFAULT; EMU_DCDCInit(&dcdcInit); // Enable voltage downscaling in EM2/3 (VSCALE0) EMU_EM23Init_TypeDef em23Init = EMU_EM23INIT_DEFAULT; em23Init.vScaleEM23Voltage = emuVScaleEM23_LowPower; // Initialize EM mode 2/3 EMU_EM23Init(&em23Init); // Use LFRCO as clock for EM23GRPACLK and PCNT CMU_ClockSelectSet(cmuClock_EM23GRPACLK, cmuSelect_LFRCO); #ifdef EM2DEBUG // Enable debug connectivity in EM2 EMU->CTRL_SET = EMU_CTRL_EM2DBGEN; #endif // Initialize GPIO initGpio(); // Initialize and power-down MX25 SPI flash MX25_init(); MX25_RSTEN(); MX25_RST(&status); MX25_DP(); MX25_deinit(); // PRS Initialization initPrs(); // PCNT Initialization initPcnt(); /* * Enter EM2 forever; PCNT/EM23GRACLK sourced from LFRCO - only available down * to EM2. EM23GRACLK can be sourced by the slower ULFRCO to run in EM3, * however, maximum input toggle frequency should be 2 times slower, and is * further limited by the (optional; enabled in this example) pulse width * filter. */ while (true) { EMU_EnterEM2(false); } }
2.109375
2
2024-11-18T22:09:55.799103+00:00
2018-03-30T20:09:32
b4f8f2d6edd22ff33bf8491807ab4508e297082d
{ "blob_id": "b4f8f2d6edd22ff33bf8491807ab4508e297082d", "branch_name": "refs/heads/master", "committer_date": "2018-03-30T20:09:32", "content_id": "d1ae22bd43053fa0f2e58c9d742755ba991b18f7", "detected_licenses": [ "MIT" ], "directory_id": "973de2d119ff849844deeb55f99fc8d8f6796573", "extension": "c", "filename": "dio.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 124124899, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3243, "license": "MIT", "license_type": "permissive", "path": "/dio.c", "provenance": "stackv2-0106.json.gz:44699", "repo_name": "Mithreindeir/DISH", "revision_date": "2018-03-30T20:09:32", "revision_id": "12b2eed6b924068c46ec311aa70f16fe0e1c8140", "snapshot_id": "26096ba48001b9aef42e4df7cbbcb07ed6cd409c", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Mithreindeir/DISH/12b2eed6b924068c46ec311aa70f16fe0e1c8140/dio.c", "visit_date": "2021-04-26T22:38:33.053537" }
stackv2
#include "dio.h" char * dish_readline(char ** history, int num_history, struct termios saved) { char buf[256]; memset(buf, 0, 256); int iter=0, miter=0, x=0, y=0; get_cursor(&x, &y); int arrow_key = 0; int hiter = num_history; char c = 1; while (c && c != EOF && c != '\n' && c != '\r') { if (iscntrl(c)) { if (c==3) { set_term(saved); exit(1); } else if (c==26) { struct termios tmp = get_term(); set_term(saved); kill(getpid(),SIGTSTP); get_cursor(&x, &y); set_term(tmp); } } c = key_process(&arrow_key); if (arrow_key && c=='C') iter < miter ? ++iter : iter; if (arrow_key && c=='D') iter > 0 ? --iter : iter; if (arrow_key && c=='A' && num_history > 0) { hiter > 0 ? --hiter : hiter; memset(buf, 0, 256); int len = strlen(history[hiter]); memcpy(buf, history[hiter], len); miter = len, iter = len; } if (arrow_key && c=='B' && num_history > 0) { hiter=hiter < num_history-1 ? ++hiter : num_history-1; memset(buf, 0, 256); int len = strlen(history[hiter]); memcpy(buf, history[hiter], len); miter = len, iter = len; } if (!arrow_key) { if (miter >= 255 || iter >= 255) break; if (c>=0x20&&c<0x7f) { if (miter == iter) { buf[miter++, iter++] = c; } else { memmove(buf+iter+1, buf+iter, miter-iter); buf[miter++, iter++] = c; } } else if (c==0x7f&&iter>0) { if (miter==iter) { buf[--miter, --iter] = 0; } else { memmove(buf+iter-1, buf+iter, miter-iter); miter--, iter--; } } } arrow_key = 0; set_cursor(x, y); write_str("\x1b[K"); write_buffer(buf, miter); set_cursor(x+iter, y); } char * str = malloc(miter+1); strncpy(str, buf, miter); str[miter] = 0; return str; } int key_process(int * arrowkey) { char c = read_char(); if (c!=0x1b) return c; c = read_char(); if (c=='[') { *arrowkey = 1; return read_char(); } return c; } char ** dish_splitline(const char * input, int *num_param) { char ** args = NULL; int num_arg = 0; char * arg = dish_split(input); while (arg) { num_arg++; if (!args) { args = malloc(sizeof(char*)); } else { args = realloc(args, sizeof(char*)*num_arg); } args[num_arg-1] = arg; arg = dish_split(NULL); } *num_param = num_arg; return args; } char * dish_split(const char * line) { static const char * str = NULL; if (line) str = line; int squote = 0, dquote = 0, rstr = 0; int len = strlen(str); int doff = 0; int real_char = 0; int str_start = -1; for (int i = 0; i < len; i++) { if (!real_char&&(str[i]==' '||str[i]=='\t'||str[i]=='\n'))continue; real_char = 1; str_start = str_start==-1 ? i : str_start; if (str[i]=='\'') { squote = !squote; str_start = squote ? i+1 : str_start; rstr = !squote; doff = 1; } if (str[i]=='\"') { dquote = !dquote; str_start = dquote ? i+1 : str_start; rstr = !dquote; doff = 1; } if (!squote&&!dquote&&(str[i]==' '||str[i]=='\n'||str[i]=='\t')) rstr = 1; if ((i+1)==len) rstr = !rstr ? (i++, 1) : rstr; if (rstr) { int slen = i - str_start; char * str2 = malloc(slen+1); memcpy(str2, str+str_start, slen); str2[slen] = 0; str+=i+doff; return str2; } } return NULL; }
2.703125
3
2024-11-18T22:09:55.921811+00:00
2021-10-06T12:49:28
a04ee1442e8682962cd71474ecb8a0006027887d
{ "blob_id": "a04ee1442e8682962cd71474ecb8a0006027887d", "branch_name": "refs/heads/main", "committer_date": "2021-10-06T12:49:28", "content_id": "25f865fc2e19592bf468cf8c42f14829a80aa631", "detected_licenses": [ "CC0-1.0" ], "directory_id": "9a1db4ea1fc49606ea95b924f46ebf1436d94c38", "extension": "c", "filename": "connect.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": 2102, "license": "CC0-1.0", "license_type": "permissive", "path": "/4-CO-RE/connect.c", "provenance": "stackv2-0106.json.gz:44956", "repo_name": "yonggeshidai/Linux-eBPF-Learning", "revision_date": "2021-10-06T12:49:28", "revision_id": "0568cd60b352af6cda7c8e2bb85d4733aec6fb6c", "snapshot_id": "1ac9551b3a626804ffd33df04807a7f0e19b29ae", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/yonggeshidai/Linux-eBPF-Learning/0568cd60b352af6cda7c8e2bb85d4733aec6fb6c/4-CO-RE/connect.c", "visit_date": "2023-08-16T20:40:34.182974" }
stackv2
// The tracepoint requires kernel CONFIG_FTRACE_SYSCALLS to be set. #include <stdio.h> #include <string.h> #include <signal.h> #include <errno.h> #include <sys/resource.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "connect_kern.skel.h" #define MAX_LENGTH 16 struct bpf_msg { char comm[MAX_LENGTH]; struct sockaddr uservaddr; }; static struct connect_kern *skel; static struct ring_buffer *rb; static bool stop; static void sigint_handler(int sig) { stop = true; } static int print_bpf_output(void *ctx, void *data, size_t size) { struct bpf_msg *val = data; struct sockaddr_in *dest = (struct sockaddr_in *)&val->uservaddr; fprintf(stdout, ">> [%s]: connect '%s:%d'\n", val->comm, inet_ntoa(dest->sin_addr), dest->sin_port); return 0; } /* Prevent: * libbpf: load bpf program failed: Operation not permitted * libbpf: permission error while running as root; try raising 'ulimit -l'? * current value: 64.0 KiB * libbpf: failed to load program 'tracepoint/syscalls/sys_enter_openat' */ void setlimit(void) { struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY}; setrlimit(RLIMIT_MEMLOCK, &r); } int main(int argc, char *argv[]) { struct ring_buffer_opts rb_opts = {}; int retval = 0; int map_fd; setlimit(); skel = connect_kern__open_and_load(); if (!skel) goto cleanup; map_fd = bpf_object__find_map_fd_by_name(skel->obj, "ringbuf"); if (map_fd < 0) { fprintf(stderr, "ERROR: finding a map in obj file failed!\n"); goto cleanup; } retval = connect_kern__attach(skel); if (retval) goto cleanup; if (signal(SIGINT, sigint_handler) == SIG_ERR) { fprintf(stderr, "ERROR: %s\n", strerror(errno)); goto cleanup; } rb = ring_buffer__new(map_fd, print_bpf_output, NULL, NULL); if (rb == NULL) { fprintf(stderr, "ERROR: failed to setup bpf ring_buffer!\n"); goto cleanup; } while (true) { ring_buffer__poll(rb, 1000); if (stop) break; } connect_kern__detach(skel); ring_buffer__free(rb); bpf_link__destroy(skel->links.hello); cleanup: connect_kern__destroy(skel); return 0; }
2.359375
2
2024-11-18T22:09:56.643325+00:00
2021-10-11T08:36:10
5459874d06197c8b7a29c009080f6dcc1e50291d
{ "blob_id": "5459874d06197c8b7a29c009080f6dcc1e50291d", "branch_name": "refs/heads/main", "committer_date": "2021-10-11T08:36:10", "content_id": "352a9b059f84f57ac2c429d74ac42cbb93f693fb", "detected_licenses": [ "MIT" ], "directory_id": "2a21910f94ab2272d5dbfd58d7f8992ae4bb25ea", "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": 415841255, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2453, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0106.json.gz:45730", "repo_name": "ImtiazKabir/Expanding-determinant-with-permutation", "revision_date": "2021-10-11T08:36:10", "revision_id": "28a0df4b27aab79418127ec391e9ffdd8e2e2835", "snapshot_id": "ab270fe169391ec4a6006c7eaabc46f62c4a3884", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ImtiazKabir/Expanding-determinant-with-permutation/28a0df4b27aab79418127ec391e9ffdd8e2e2835/main.c", "visit_date": "2023-08-24T09:41:12.763528" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define STB_DS_IMPLEMENTATION #include "stb_ds.h" #define DELIM "," double determinant( double const * const * const matrix, int const dim ); void setup( FILE * * const file_p, char const * const path, int * const dim_p, double * * * const matrix ); void clean_up( FILE * file, int const dim, double * * matrix ); void check_square_err( int const dim, double * * matrix ); void parse_matrix( FILE * file, double * * * const matrix_p ); int main( int const argc, char const * const * const argv ) { // example usage if (argc != 2) { fprintf(stderr, "Example usage: %s matrix.txt\n", argv[0]); exit(EXIT_FAILURE); } FILE * file; double * * matrix; int dim; setup(&file, argv[1], &dim, &matrix); // calculating the determinant double const det = determinant( (double const * const * const) matrix, dim ); printf("%f\n", det); clean_up(file, dim, matrix); return EXIT_SUCCESS; } void setup( FILE * * const file_p, char const * const path, int * const dim_p, double * * * const matrix_p ) { // opening the file *file_p = fopen(path, "r"); if (*file_p == NULL) { perror(NULL); fprintf(stderr, "Could not find %s\n", path); exit(EXIT_FAILURE); } // parsing the matrix parse_matrix(*file_p, matrix_p); // checking if it is square int const dim = arrlen(*matrix_p); *dim_p = dim; check_square_err(dim, *matrix_p); } void clean_up( FILE * file, int const dim, double * * matrix ) { for (int i = 0; i < dim; ++i) { arrfree(matrix[i]); } arrfree(matrix); fclose(file); } void check_square_err( int const dim, double * * matrix ) { for (int i = 0; i < dim; ++i) { if (arrlen(matrix[i]) != dim) { fprintf(stderr, "Try with a square matrix (comma separated)\n" "For example:\n" "1.01 , -0.02, 0\n" " 4 , -5 , 5.05\n" " 0 , -3 , 1\n" ); exit(EXIT_FAILURE); } } } void parse_matrix( FILE * file, double * * * const matrix_p ) { char line[20]; *matrix_p = NULL; while (fgets(line, 20, file)) { char *token = strtok(line, DELIM); double *row = NULL; while (token != NULL) { double number = atof(token); arrput(row, number); token = strtok(NULL, DELIM); } arrput(*matrix_p, row); printf("\n"); } }
2.890625
3
2024-11-18T22:09:56.810042+00:00
2023-08-13T10:00:00
915dba0789412bef306a8e1d7e82b323c4473638
{ "blob_id": "915dba0789412bef306a8e1d7e82b323c4473638", "branch_name": "refs/heads/master", "committer_date": "2023-08-13T10:00:00", "content_id": "44dc0b6bff6c713fa88362420febd6e4bed60f46", "detected_licenses": [ "MIT" ], "directory_id": "0cc343d927d5db6693006018986715c43acab961", "extension": "c", "filename": "debug.c", "fork_events_count": 64, "gha_created_at": "2013-11-19T08:57:02", "gha_event_created_at": "2023-08-10T21:16:08", "gha_language": "OCaml", "gha_license_id": "NOASSERTION", "github_id": 14519163, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 987, "license": "MIT", "license_type": "permissive", "path": "/examples/crypto_ccs/symbolic_model/src/debug.c", "provenance": "stackv2-0106.json.gz:45859", "repo_name": "verifast/verifast", "revision_date": "2023-08-13T10:00:00", "revision_id": "d152da790c7ebf72ce616533a6c83082629adbdb", "snapshot_id": "ec0101fc4a69bd33c5f66be4444169c4e060ead8", "src_encoding": "UTF-8", "star_events_count": 325, "url": "https://raw.githubusercontent.com/verifast/verifast/d152da790c7ebf72ce616533a6c83082629adbdb/examples/crypto_ccs/symbolic_model/src/debug.c", "visit_date": "2023-08-25T00:13:51.464802" }
stackv2
#include "debug.h" #include "general.h" #include "item.h" void debug_print(const char *message) //@ requires [?f]string(message, ?cs); //@ ensures [f]string(message, cs); { #ifdef DEBUG printf("<DEBUG>%s\n", message); #endif } void print_buffer(const char *buffer, int size) //@ requires [?f]crypto_chars(?kind, buffer, size, ?ccs); //@ ensures [f]crypto_chars(kind, buffer, size, ccs); { #ifdef DEBUG int i = 0; while (i < size) { if (i % 32 == 0) printf("\n"); printf("%x", (unsigned char) buffer[i]); i++; } printf("\n"); #endif } void print_item(const struct item* item) //@ requires [?f]item(item, ?i, ?pub); //@ ensures [f]item(item, i, pub); { #ifdef DEBUG printf("---------------------\n"); printf("Item: %p\n", item); printf("\tsize %i\n", item->size); printf("\ttag: %c\n", *(item->content)); printf("\tcontent:"); print_buffer(item->content + 1, item->size - 1); printf("---------------------\n"); #else #endif }
2.609375
3
2024-11-18T22:09:58.282955+00:00
2021-09-27T12:59:47
36d0c743eaf34cbf6cad765bc7d13fa607425909
{ "blob_id": "36d0c743eaf34cbf6cad765bc7d13fa607425909", "branch_name": "refs/heads/master", "committer_date": "2021-09-28T08:42:54", "content_id": "ce8528163b0b85b0a4f1c60cda68c1a5bcd320e5", "detected_licenses": [ "MIT" ], "directory_id": "f05c7fad226f0c657fa2a39328eeb93a58151b53", "extension": "c", "filename": "ut_redis.c", "fork_events_count": 17, "gha_created_at": "2017-11-16T12:28:03", "gha_event_created_at": "2021-09-28T08:42:55", "gha_language": "C", "gha_license_id": "MIT", "github_id": 110968815, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9443, "license": "MIT", "license_type": "permissive", "path": "/utils/ut_redis.c", "provenance": "stackv2-0106.json.gz:46373", "repo_name": "bitlum/viabtc_exchange_server", "revision_date": "2021-09-27T12:59:47", "revision_id": "2bddb956e7bf97981e2cd6b67a9a6e132a59de34", "snapshot_id": "463a585905fd11db6a50623d10ebb66a7111245c", "src_encoding": "UTF-8", "star_events_count": 28, "url": "https://raw.githubusercontent.com/bitlum/viabtc_exchange_server/2bddb956e7bf97981e2cd6b67a9a6e132a59de34/utils/ut_redis.c", "visit_date": "2021-12-21T07:33:51.347428" }
stackv2
/* * Description: * History: yang@haipo.me, 2016/03/27, create */ # include <stdlib.h> # include <string.h> # include <stdarg.h> # include <errno.h> # include "ut_log.h" # include "ut_redis.h" static void append_node(redis_sentinel_t *context, redis_sentinel_node *node) { if (context->list == NULL) { context->list = node; return; } redis_sentinel_node *curr = context->list; while (curr->next != NULL) { curr = curr->next; } curr->next = node; node->prev = curr; } static void move_to_front(redis_sentinel_t *context, redis_sentinel_node *node) { if (node == context->list) return; node->prev->next = node->next; if (node->next) { node->next->prev = node->prev; } node->next = context->list; node->prev = NULL; context->list->prev = node; context->list = node; } redis_sentinel_t *redis_sentinel_create(redis_sentinel_cfg *cfg) { redis_sentinel_t *context = malloc(sizeof(redis_sentinel_t)); if (context == NULL) return NULL; memset(context, 0, sizeof(redis_sentinel_t)); context->db = cfg->db; context->name = strdup(cfg->name); if (context->name == NULL) { free(context); return NULL; } for (uint32_t i = 0; i < cfg->addr_count; ++i) { redis_sentinel_node *node = malloc(sizeof(redis_sentinel_node)); if (node == NULL) { redis_sentinel_release(context); return NULL; } memset(node, 0, sizeof(redis_sentinel_node)); node->addr.host = strdup(cfg->addr_arr[i].host); node->addr.port = cfg->addr_arr[i].port; if (node->addr.host == NULL) { free(node); redis_sentinel_release(context); return NULL; } append_node(context, node); } return context; } void redis_sentinel_release(redis_sentinel_t *context) { redis_sentinel_node *curr = context->list; redis_sentinel_node *next; while (curr) { next = curr->next; free(curr->addr.host); free(curr); curr = next; } free(context); } int redis_sentinel_get_master_addr(redis_sentinel_t *context, redis_addr *addr) { redis_sentinel_node *curr = context->list; while (curr) { struct timeval timeout = { 3, 0 }; redisContext *redis = redisConnectWithTimeout(curr->addr.host, curr->addr.port, timeout); if (redis == NULL || redis->err) { if (redis) { redisFree(redis); } curr = curr->next; continue; } redisReply *reply = redisCommand(redis, "SENTINEL get-master-addr-by-name %s", context->name); if (reply == NULL || reply->type != REDIS_REPLY_ARRAY || reply->elements != 2) { if (reply) { freeReplyObject(reply); redisFree(redis); } curr = curr->next; continue; } move_to_front(context, curr); addr->host = strdup(reply->element[0]->str); addr->port = atoi(reply->element[1]->str); freeReplyObject(reply); redisFree(redis); return 0; } return -1; } static char *get_slave_info(size_t elements, redisReply **element, char *key) { for (size_t i = 0; i < elements; i += 2){ if (strcmp(element[i]->str, key) == 0) { return element[i + 1]->str; } } return NULL; } int redis_sentinel_get_slave_addr(redis_sentinel_t *context, redis_addr *addr) { redis_sentinel_node *curr = context->list; while (curr) { struct timeval timeout = { 3, 0 }; redisContext *redis = redisConnectWithTimeout(curr->addr.host, curr->addr.port, timeout); if (redis == NULL || redis->err) { if (redis) { redisFree(redis); } curr = curr->next; continue; } redisReply *reply = redisCommand(redis, "SENTINEL slaves %s", context->name); if (reply == NULL || reply->type != REDIS_REPLY_ARRAY) { if (reply) { freeReplyObject(reply); redisFree(redis); } curr = curr->next; continue; } for (size_t i = 0; i < reply->elements; ++i) { const char *flags = get_slave_info(reply->element[i]->elements, reply->element[i]->element, "flags"); if (flags == NULL || strstr(flags, "disconnected")) { continue; } const char *host = get_slave_info(reply->element[i]->elements, reply->element[i]->element, "ip"); if (host == NULL) { continue; } const char *port = get_slave_info(reply->element[i]->elements, reply->element[i]->element, "port"); if (port == NULL) { continue; } move_to_front(context, curr); addr->host = strdup(host); addr->port = atoi(port); freeReplyObject(reply); redisFree(redis); return 0; } curr = curr->next; } return -1; } redisContext *redis_sentinel_connect_master(redis_sentinel_t *context) { for (int i = 0; i < 3; ++i) { redis_addr addr; if (redis_sentinel_get_master_addr(context, &addr) < 0) return NULL; struct timeval timeout = { 3, 0 }; redisContext *redis = redisConnectWithTimeout(addr.host, addr.port, timeout); if (redis == NULL || redis->err) { if (redis) { redisFree(redis); } free(addr.host); return NULL; } free(addr.host); redisSetTimeout(redis, timeout); redisReply *reply = redisCommand(redis, "ROLE"); if (reply == NULL || reply->type != REDIS_REPLY_ARRAY) { if (reply) { freeReplyObject(reply); } redisFree(redis); return NULL; } if (strcmp(reply->element[0]->str, "master") != 0) { freeReplyObject(reply); redisFree(redis); continue; } freeReplyObject(reply); if (context->db > 0) { reply = redisCommand(redis, "SELECT %d", context->db); if (redis == NULL || reply->type == REDIS_REPLY_ERROR) { if (reply) { freeReplyObject(reply); } redisFree(redis); return NULL; } freeReplyObject(reply); } return redis; } return NULL; } redisContext *redis_sentinel_connect_slave(redis_sentinel_t *context) { for (int i = 0; i < 3; ++i) { redis_addr addr; if (redis_sentinel_get_slave_addr(context, &addr) < 0) return NULL; struct timeval timeout = { 3, 0 }; redisContext *redis = redisConnectWithTimeout(addr.host, addr.port, timeout); if (redis == NULL || redis->err) { if (redis) { redisFree(redis); } free(addr.host); return NULL; } free(addr.host); redisSetTimeout(redis, timeout); redisReply *reply = redisCommand(redis, "ROLE"); if (reply == NULL || reply->type != REDIS_REPLY_ARRAY) { if (reply) { freeReplyObject(reply); } redisFree(redis); return NULL; } if (strcmp(reply->element[0]->str, "slave") != 0) { freeReplyObject(reply); redisFree(redis); continue; } freeReplyObject(reply); if (context->db > 0) { reply = redisCommand(redis, "SELECT %d", context->db); if (redis == NULL || reply->type == REDIS_REPLY_ERROR) { if (reply) { freeReplyObject(reply); } redisFree(redis); return NULL; } freeReplyObject(reply); } return redis; } return NULL; } int redis_addr_cfg_parse(const char *cfg, redis_addr *addr) { char *sep = strchr(cfg, ':'); if (sep == NULL) return -1; addr->port = atoi(sep + 1); if (addr->port <= 0) return -1; addr->host = malloc(sep - cfg + 1); if (addr->host == NULL) return -1; memcpy(addr->host, cfg, sep - cfg); addr->host[sep - cfg] = '\0'; return 0; } void *redisCmd(redisContext *c, const char *format, ...) { va_list ap; va_start(ap, format); redisReply *reply = redisvCommand(c, format, ap); va_end(ap); if (reply == NULL) { log_error("redisCommand fail: %d: %s", c->err, strerror(errno)); return NULL; } if (reply->type == REDIS_REPLY_ERROR) { log_error("redisCommand error: %s", reply->str); freeReplyObject(reply); return NULL; } return reply; } void *redisRawCmd(redisContext *c, const char *cmd) { redisReply *reply = redisCommand(c, cmd); if (reply == NULL) { log_error("redisCommand: %s fail: %d: %s", cmd, c->err, strerror(errno)); return NULL; } if (reply->type == REDIS_REPLY_ERROR) { log_error("redisCommand: %s error: %s", cmd, reply->str); freeReplyObject(reply); return NULL; } return reply; }
2.703125
3
2024-11-18T22:09:58.613742+00:00
2018-11-10T21:54:07
78f33ba8efa8ece041a5c9b32b2e996b7a58ae0a
{ "blob_id": "78f33ba8efa8ece041a5c9b32b2e996b7a58ae0a", "branch_name": "refs/heads/master", "committer_date": "2018-11-10T21:54:07", "content_id": "3a14dd68e4027010426636ce7e80d192ccc598b9", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "151b24446ff8ce967b1a02d117d77419709e7d68", "extension": "c", "filename": "hexarg.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 157024986, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1871, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/libburte/hexarg.c", "provenance": "stackv2-0106.json.gz:46888", "repo_name": "robodan/burte", "revision_date": "2018-11-10T21:54:07", "revision_id": "e0ab58374d26957aeea852853232d25fe85bbde9", "snapshot_id": "24c79ca9097ddd92c44ffcce5352bc215fc2eabe", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/robodan/burte/e0ab58374d26957aeea852853232d25fe85bbde9/src/libburte/hexarg.c", "visit_date": "2020-04-05T16:42:11.501576" }
stackv2
/* hexarg -- parse hexadecimal integer argument * * Usage: i = hexarg (ptr,brk,prompt,min,max,default) * unsigned int i,min,max,default; * char **ptr,*brk,*prompt; * * Will attempt to parse an argument from the string pointed to * by "ptr", incrementing ptr to point to the next arg. If * an arg is found, it is converted into an hexadecimal integer. If there is * no arg or the value of the arg is not within the range * [min..max], then "gethex" is called to ask the user for an * hexadecimal integer value. * "Brk" is the list of characters which may terminate an argument; * if 0, then " " is used. * * HISTORY * 18-Apr-83 Rafael Bracho (rxb) at Carnegie-Mellon University * Changed so it beeps at the user instead of cluttering the screen. * * 17-Feb-83 John Schlag (jfs) at Carnegie-Mellon University * Ported to the 68000 for the Popeye system. * * 20-Nov-79 Steven Shafer (sas) at Carnegie-Mellon University * Created for VAX. */ #include <stdio.h> char *nxtarg (); unsigned int atox (); int hexarg (ptr, brk, prompt, min, max, defalt) char **ptr; char *brk, *prompt; unsigned int min, max, defalt; { register unsigned int i; register char *arg, *p; arg = nxtarg (ptr, brk); if (*arg != '\0') /* if there was an arg */ { if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) strcpy (arg, arg + 2); for (p = arg; *p && ((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F')); p++); if (*p) { if (strcmp (arg, "?") != 0) putchar (CTRL ('G')); } else { i = atox (arg); if (i < min || i > max) putchar (CTRL ('G')); } } if (*arg == '\0' || *p != '\0' || i < min || i > max) i = gethex (prompt, min, max, defalt); return (i); }
2.96875
3
2024-11-18T22:09:58.944804+00:00
2016-02-16T18:18:26
44589260cae901ebeda04f250f8db990acbea79f
{ "blob_id": "44589260cae901ebeda04f250f8db990acbea79f", "branch_name": "refs/heads/master", "committer_date": "2016-02-16T18:18:26", "content_id": "7fcfb4148e9842e0e053f6c43d37ab34404cf039", "detected_licenses": [ "MIT" ], "directory_id": "e02adcda7a1d00dd303b21b4a8e18e6c86b0c639", "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": 51855837, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 391, "license": "MIT", "license_type": "permissive", "path": "/test/main.c", "provenance": "stackv2-0106.json.gz:47405", "repo_name": "nathanfaucett/c-string_to_float", "revision_date": "2016-02-16T18:18:26", "revision_id": "ffb3f05ffa33d0cb5884ccb0c0186a151ce1cfa7", "snapshot_id": "da85837e800579f088d04655d26ead9d41cbde35", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/nathanfaucett/c-string_to_float/ffb3f05ffa33d0cb5884ccb0c0186a151ce1cfa7/test/main.c", "visit_date": "2021-01-10T07:00:36.091779" }
stackv2
#include <stdio.h> #include <stdlib.h> #include "../lib.h" int main(void) { float32 x0 = string_to_float32("-32"); float32 x1 = string_to_float32("-0"); float32 x2 = string_to_float32("0"); float32 x3 = string_to_float32("32"); printf("%f\n", (float) x0); printf("%f\n", (float) x1); printf("%f\n", (float) x2); printf("%f\n", (float) x3); return 0; }
2.21875
2
2024-11-18T22:09:59.139172+00:00
2023-08-19T04:53:58
c53b2edb699a2a28bae9adbac22b99605fec4fab
{ "blob_id": "c53b2edb699a2a28bae9adbac22b99605fec4fab", "branch_name": "refs/heads/master", "committer_date": "2023-08-19T04:53:58", "content_id": "4c72c15f92370ad603bd9b565a5b38393cb93fa2", "detected_licenses": [ "MIT" ], "directory_id": "f8fe6eec5dc1200a112a13dcd2102af4fccf2417", "extension": "c", "filename": "MonolithHydraulicDiameter.C", "fork_events_count": 4, "gha_created_at": "2020-03-06T15:33:35", "gha_event_created_at": "2023-09-03T16:22:27", "gha_language": "Assembly", "gha_license_id": "MIT", "github_id": 245455360, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1860, "license": "MIT", "license_type": "permissive", "path": "/src/auxkernels/MonolithHydraulicDiameter.C", "provenance": "stackv2-0106.json.gz:47794", "repo_name": "aladshaw3/cats", "revision_date": "2023-08-19T04:53:58", "revision_id": "289fdc0712cbb1c000dd42a84f5a7eb57e848cdc", "snapshot_id": "c507b01c97a0aebf69aae1d6a12a3df20805527a", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/aladshaw3/cats/289fdc0712cbb1c000dd42a84f5a7eb57e848cdc/src/auxkernels/MonolithHydraulicDiameter.C", "visit_date": "2023-08-31T06:33:07.571570" }
stackv2
/*! * \file MonolithHydraulicDiameter.h * \brief Auxillary kernel to calculate the hydraulic diameter for the monolith * \details This file is responsible for calculating the hydraulic diameter for * the monolith. This value may not be used on its own, but will likely * be used in conjunction with other properties (such as film mass transfer * or diffusion rates). * * \author Austin Ladshaw * \date 09/14/2021 * \copyright This kernel was designed and built at Oak Ridge National * Laboratory by Austin Ladshaw for research in catalyst * performance for new vehicle technologies. * * Austin Ladshaw does not claim any ownership or copyright to the * MOOSE framework in which these kernels are constructed, only * the kernels themselves. The MOOSE framework copyright is held * by the Battelle Energy Alliance, LLC (c) 2010, all rights reserved. */ #include "MonolithHydraulicDiameter.h" registerMooseObject("catsApp", MonolithHydraulicDiameter); InputParameters MonolithHydraulicDiameter::validParams() { InputParameters params = AuxKernel::validParams(); params.addParam<Real>("cell_density",50,"Cell density of the monolith (# of cells per face area)"); params.addRequiredCoupledVar("channel_vol_ratio","Ratio of channel volume to total volume "); return params; } MonolithHydraulicDiameter::MonolithHydraulicDiameter(const InputParameters & parameters) : AuxKernel(parameters), _cell_density(getParam<Real>("cell_density")), _bulk_porosity(coupledValue("channel_vol_ratio")) { } Real MonolithHydraulicDiameter::computeValue() { Real Ac = _bulk_porosity[_qp]/_cell_density; Real dc = 2.0*sqrt((Ac/3.14159)); Real ds = sqrt(Ac); Real dh = 0.5*(dc+ds); return dh; }
2.28125
2
2024-11-18T22:09:59.425759+00:00
2018-07-01T20:42:58
dd6460bcce1e7e408b531451d0ef8bd182169582
{ "blob_id": "dd6460bcce1e7e408b531451d0ef8bd182169582", "branch_name": "refs/heads/master", "committer_date": "2018-07-01T20:42:58", "content_id": "9cf7b326573d18aaae8250578c51944a349127c5", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6a8079bf90e0d73f375e75ec2eb1da24170b1122", "extension": "c", "filename": "mystruct.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 116976655, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5124, "license": "Apache-2.0", "license_type": "permissive", "path": "/assignment3/structs/mystruct.c", "provenance": "stackv2-0106.json.gz:48180", "repo_name": "matticoli/CS2303", "revision_date": "2018-07-01T20:42:58", "revision_id": "5399fa2c8bdfcd0620793356dba108ba92f36da3", "snapshot_id": "bb804b580e036c0a153e15e55f34002b95a883ce", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matticoli/CS2303/5399fa2c8bdfcd0620793356dba108ba92f36da3/assignment3/structs/mystruct.c", "visit_date": "2021-09-17T11:38:52.051453" }
stackv2
/** mystruct.c * @author Mike Ciaraldi */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "mystruct.h" #define THIS_YR 2018 // Macro for current year (max value for random years) // Helper function prototypes int randInt(int max); char *randStr(int length); char randChar(); /** Allocates an Employee struct and fills in its fields * @param birth Year the emploee was born. * @param start Year the employee started with the company. * @param name String containing employee's name * @return Pointer to Employee struct, newly allocated from the heap. */ struct Employee* makeEmployee(int birth, int start, const char *name) { // Alloc memory for new employee struct Employee *e = malloc(sizeof(struct Employee)); // Set props from parameters e -> birth_year = birth; e -> start_year = start; strcpy(e -> name, name); return e; // Return pointer to new employee } /** Prints out information on a given Employee * @param e Pointer to employee to be printed */ void printEmployee(struct Employee *e) { // Print location and fields for employee in one line printf("%p\t%s\tBorn: %d\tStarted: %d\n", e, e -> name, e -> birth_year, e -> start_year); } /** Generates random Employee * @return pointer to new employee */ struct Employee* randEmployee() { // Calls helper functions and passes random data into makeEmployee return makeEmployee(randInt(THIS_YR), randInt(THIS_YR), randStr(10)); } /** Generates array of random employees of given length * @param count Length of random Employee array * @return array of random Employees */ struct Employee** randCompany(int count) { // Allocate new array of employees struct Employee** arr = malloc(sizeof(struct Employee) * count); // If unable to allocate memory, return null ptr if(arr == NULL) return NULL; // Iterate through each employee in array, and set the employee pointer // to the location returned by randEmployee call for(int i = 0; i < count; i++) { arr[i] = randEmployee(); } // return the array return arr; } /** Prints out an array of Employees * @param company Employee array to print * @param count length of Employee array */ void printCompany(struct Employee **company, int count) { // Print out location of company array printf("Company %p\n", company); // Iterate through each employee in company array and print for(int i = 0; i < count; i++) { printEmployee(company[i]); } } /** Shallow copies an array of Employees * @param company Employee array to print * @param count length of Employee array * @return shallow copy of company array */ struct Employee **shallowCopyCompany(struct Employee **company, int count) { // Allocate memory for an array of pointers // NOTE: This does not leave empty space for the full struct at each index! struct Employee **dupe = malloc(sizeof(struct Employee *) * count); // Copy each pointer over for(int i = 0; i < count; i++) { dupe[i] = company[i]; } // Return the new array return dupe; } /** Deep copies an array of Employees * @param company Employee array to print * @param count length of Employee array * @return deep copy of company array */ struct Employee **deepCopyCompany(struct Employee **company, int count) { // Allocate memory for an array of Employees // NOTE: This MUST leave empty space for the full struct at each index! struct Employee **dupe = malloc(sizeof(struct Employee *) * count); // For each Employee for(int i = 0; i < count; i++) { // Make a new employee with data from old one and put it in the dupe array struct Employee *e = company[i]; dupe[i] = makeEmployee(e->birth_year, e->start_year, e->name); } // Return new array return dupe; } /** Frees memory from Employee array * @param company Employee array to print * @param count length of Employee array */ void fireEveryone(struct Employee **company, int count) { // For each employee in the company array for(int i = 0; i < count; i++) { // Free the memory held by the struct free(company[i]); } // Free the memory held by the array of pointers to structs free(company); } /** Returns a random int between 0 and max (inclusive) * @param max The max value of the random int (inclusive) * @return Random int between 0 and max */ int randInt(int max) { // Generates rand int bt 0 and max (inclusive) return rand() % (max + 1); } /** Returns a random string of given length * @param length length of random string to generate * @return Random string of length length */ char *randStr(int length) { // Create string buffer for random string char *s = malloc(sizeof(char) * (length + 1)); // If malloc fails, return null ptr if(s == NULL) return NULL; // Add (length) random characters to string buffer for(char *c = s; c - s < length; c++) { *c = randChar(); } // Append null terminator *(s + length) = '\0'; return s; } /** Returns a random char between a and z (lowercase, inclusive) * @return Random character between a and z (lowercase, inclusive) */ char randChar() { // Generates random ascii value corresponding to a-z and casts to char return (char)(rand() % ('z' - 'a') + 'a'); }
3.765625
4
2024-11-18T22:09:59.586095+00:00
2021-07-27T08:53:05
30fbc3e9d0fda28f24cafc2b656caf9f7dea2c77
{ "blob_id": "30fbc3e9d0fda28f24cafc2b656caf9f7dea2c77", "branch_name": "refs/heads/master", "committer_date": "2021-07-27T08:53:05", "content_id": "e836d0e2a14a42067132a9fabc26227abc0e6cad", "detected_licenses": [ "MIT" ], "directory_id": "1afb46aea37d8473e68148cffb918b902ad94cf6", "extension": "h", "filename": "stack.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 371817618, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1067, "license": "MIT", "license_type": "permissive", "path": "/src/stack.h", "provenance": "stackv2-0106.json.gz:48437", "repo_name": "dominicprice/tinylisp", "revision_date": "2021-07-27T08:53:05", "revision_id": "f93146049f95e51863fa4b9bb874d850f45d2bb4", "snapshot_id": "67cfa7b3295b6632b9ee93228e5b25a62ff5b413", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/dominicprice/tinylisp/f93146049f95e51863fa4b9bb874d850f45d2bb4/src/stack.h", "visit_date": "2023-07-06T03:11:01.142721" }
stackv2
#ifndef TINYLISP_STACK_H #define TINYLISP_STACK_H #include "object.h" #define LISP_MAX_STACK_SIZE 128 typedef struct LispStackFrame_ *LispStackFrame; typedef struct LispStack_ *LispStack; struct LispStackFrame_ { int size, capacity; char** keys; LispObject* vals; }; LispStackFrame lisp_stackframe_new(); void lisp_stackframe_free(LispStackFrame frame); LispObject lisp_stackframe_find(LispStackFrame frame, char* key); error_t lisp_stackframe_set(LispStackFrame frame, char* key, LispObject val); void lisp_stackframe_print(LispStackFrame frame); struct LispStack_ { LispStackFrame frames[LISP_MAX_STACK_SIZE]; int nframes; }; LispStack lisp_stack_new(); void lisp_stack_free(LispStack stack); LispObject lisp_stack_find(LispStack stack, char* key); error_t lisp_stack_setlocal(LispStack stack, char* key, LispObject val); error_t lisp_stack_setglobal(LispStack stack, char* key, LispObject val); error_t lisp_stack_push(LispStack stack, LispStackFrame frame); error_t lisp_stack_push_empty(LispStack stack); void lisp_stack_pop(LispStack stack); #endif
2.203125
2
2024-11-18T22:10:00.593777+00:00
2022-10-11T06:03:30
04b9c0813337d46b449a6291891db4909b094796
{ "blob_id": "04b9c0813337d46b449a6291891db4909b094796", "branch_name": "refs/heads/master", "committer_date": "2022-10-11T06:03:30", "content_id": "00b3c8ecb8ba02a769fe00911e0ee7292b46cedf", "detected_licenses": [ "MIT" ], "directory_id": "a3fa9abd8fdac2fa62dc8fbfd27dd371f81ec922", "extension": "h", "filename": "qdma_list.h", "fork_events_count": 0, "gha_created_at": "2019-10-10T22:15:15", "gha_event_created_at": "2022-12-08T03:09:42", "gha_language": "C", "gha_license_id": "MIT", "github_id": 214295118, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4826, "license": "MIT", "license_type": "permissive", "path": "/dma/QDMA/DPDK/drivers/net/qdma/qdma_access/qdma_list.h", "provenance": "stackv2-0106.json.gz:48824", "repo_name": "IxiaLabs/kiflash", "revision_date": "2022-10-11T06:03:30", "revision_id": "8d37c8214c939130a9442b64407fcaa085756ab7", "snapshot_id": "bf5604d753e9b207fc3bc55f1355a31df6f44af1", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/IxiaLabs/kiflash/8d37c8214c939130a9442b64407fcaa085756ab7/dma/QDMA/DPDK/drivers/net/qdma/qdma_access/qdma_list.h", "visit_date": "2022-12-14T13:14:20.569292" }
stackv2
/* * Copyright(c) 2019 Xilinx, Inc. All rights reserved. * * BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef QDMA_LIST_H_ #define QDMA_LIST_H_ /** * DOC: QDMA common library provided list implementation definitions * * Header file *qdma_list.h* defines APIs for creating and managing list. */ /** * struct qdma_list_head - data type for creating a list node */ struct qdma_list_head { struct qdma_list_head *prev; struct qdma_list_head *next; void *priv; }; #define QDMA_LIST_HEAD_INIT(name) { &(name), &(name), NULL } #define QDMA_LIST_HEAD(name) \ struct qdma_list_head name = QDMA_LIST_HEAD_INIT(name) #define QDMA_LIST_GET_DATA(node) (node->priv) #define QDMA_LIST_SET_DATA(node, data) ((node)->priv = data) #define qdma_list_for_each_safe(pos, n, head) \ for (pos = (head)->next, n = pos->next; pos != (head); \ pos = n, n = pos->next) #define qdma_list_is_last_entry(entry, head) ((entry)->next == (head)) #define qdma_list_is_empty(head) ((head)->next == (head)) /*****************************************************************************/ /** * qdma_list_init_head(): Init the list head * * @head: head of the list * * Return: None *****************************************************************************/ void qdma_list_init_head(struct qdma_list_head *head); /*****************************************************************************/ /** * qdma_list_add_tail(): add the given @node at the end of the list with @head * * @node: new entry which has to be added at the end of the list with @head * @head: head of the list * * This API needs to be called with holding the lock to the list * * Return: None *****************************************************************************/ void qdma_list_add_tail(struct qdma_list_head *node, struct qdma_list_head *head); /*****************************************************************************/ /** * qdma_list_insert_before(): add the given @node at the before a @node * * @new_node: new entry which has to be added before @node * @node: reference node in the list * * This API needs to be called with holding the lock to the list * * Return: None *****************************************************************************/ void qdma_list_insert_before(struct qdma_list_head *new_node, struct qdma_list_head *node); /*****************************************************************************/ /** * qdma_list_insert_after(): add the given @node at the after a @node * * @new_node: new entry which has to be added after @node * @node: reference node in the list * * This API needs to be called with holding the lock to the list * * Return: None *****************************************************************************/ void qdma_list_insert_after(struct qdma_list_head *new_node, struct qdma_list_head *node); /*****************************************************************************/ /** * qdma_list_del(): delete an node from the list * * @node: node in a list * * This API needs to be called with holding the lock to the list * * Return: None *****************************************************************************/ void qdma_list_del(struct qdma_list_head *node); #endif /* QDMA_LIST_H_ */
2.0625
2
2024-11-18T22:10:05.139543+00:00
2018-02-16T05:16:05
ad3bd3c99d8d92d60e3a0f8abd3703c63849dc0e
{ "blob_id": "ad3bd3c99d8d92d60e3a0f8abd3703c63849dc0e", "branch_name": "refs/heads/master", "committer_date": "2018-02-16T05:16:05", "content_id": "debe845a138a6f178ca9a9c2fc835c016dd5c359", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1768527a8b033a4fd9d1ea7b155cdc5910d5f9de", "extension": "c", "filename": "tbsr.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 121590803, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 599, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/tbsr.c", "provenance": "stackv2-0106.json.gz:49081", "repo_name": "samuel-crypto/tbsr-cryptosystem", "revision_date": "2018-02-16T05:16:05", "revision_id": "ce146b1eb856bf3688b0ae24f8ce4f399bdedb3d", "snapshot_id": "31006f1a2dedd8e2535563f7740670bf0b58346b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/samuel-crypto/tbsr-cryptosystem/ce146b1eb856bf3688b0ae24f8ce4f399bdedb3d/src/tbsr.c", "visit_date": "2021-04-29T20:04:09.222755" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "tbsr.h" char *tbsr_encrypt (char *word, char *key) { char *result = (char *)malloc(sizeof(char) * 100); if(result == NULL) { fprintf(stderr, "Error allocating string!\n"); return NULL; } else { strcpy(result, word); } return result; } char *tbsr_decrypt (char *word, char *key) { char *result = (char *)malloc(sizeof(char) * 100); if(result == NULL) { fprintf(stderr, "Error allocating string!\n"); return NULL; } else { strcpy(result, word); } return result; } int tbsr_init_dicts() { return 1; }
2.359375
2
2024-11-18T22:10:05.250395+00:00
2019-02-26T14:47:02
e97e53d07055c54b4f370265508566ca42d8b839
{ "blob_id": "e97e53d07055c54b4f370265508566ca42d8b839", "branch_name": "refs/heads/master", "committer_date": "2019-02-26T14:47:02", "content_id": "70582a574b6f120a4a3293fdb809834c2e6c9561", "detected_licenses": [ "MIT" ], "directory_id": "a0d0e16e6b8af86d04e05ead726e996d39dde823", "extension": "c", "filename": "testmodule.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 172636327, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2250, "license": "MIT", "license_type": "permissive", "path": "/SCIAN_Soft/_dll/src/testmodule.c", "provenance": "stackv2-0106.json.gz:49210", "repo_name": "scianlab/sciansoft", "revision_date": "2019-02-26T14:47:02", "revision_id": "379e2cea6e0f36f3c9d043e8b1b6cfb66b95440c", "snapshot_id": "60a58680764e95f40d83e6a3cafb830575759617", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/scianlab/sciansoft/379e2cea6e0f36f3c9d043e8b1b6cfb66b95440c/SCIAN_Soft/_dll/src/testmodule.c", "visit_date": "2020-04-25T08:08:01.777478" }
stackv2
#include <stdio.h> #include "idl_export.h" /* prototype for IDL_Load */ int IDL_Load( void ); /* * Define message codes and their corresponding printf(3) format * strings. Note that message codes start at zero and each one is * one less that the previous one. Codes must be monotonic and * contiguous. */ static IDL_MSG_DEF msg_arr[] = { #define M_TM_INPRO 0 { "M_TM_INPRO", "%NThis is from a loadable module procedure." }, #define M_TM_INFUN -1 { "M_TM_INFUN", "%NThis is from a loadable module function." }, }; /* * The load function fills in this message block handle with the * opaque handle to the message block used for this module. The other * routines can then use it to throw errors from this block. */ static IDL_MSG_BLOCK msg_block; /* Implementation of the TESTPRO IDL procedure */ void testpro(int argc, IDL_VPTR *argv) { IDL_MessageFromBlock(msg_block, M_TM_INPRO, IDL_MSG_RET); } /* Implementation of the TESTFUN IDL function */ IDL_VPTR testfun(int argc, IDL_VPTR *argv) { IDL_MessageFromBlock(msg_block, M_TM_INFUN, IDL_MSG_RET); return IDL_StrToSTRING("TESTFUN asdfsda"); } int IDL_Load(void) { /* * These tables contain information on the functions and procedures * that make up the TESTMODULE DLM. The information contained in these * tables must be identical to that contained in testmodule.dlm. */ static IDL_SYSFUN_DEF2 function_addr[] = { { testfun, "TESTFUN", 0, IDL_MAXPARAMS, 0, 0}, }; static IDL_SYSFUN_DEF2 procedure_addr[] = { { (IDL_FUN_RET) testpro, "TESTPRO", 0, IDL_MAX_ARRAY_DIM, 0, 0}, }; /* * Create a message block to hold our messages. Save its handle where * the other routines can access it. */ if (!(msg_block = IDL_MessageDefineBlock("Testmodule", IDL_CARRAY_ELTS(msg_arr), msg_arr))) return IDL_FALSE; /* * Register our routine. The routines must be specified exactly the same * as in testmodule.dlm. */ return IDL_SysRtnAdd(function_addr, TRUE, IDL_CARRAY_ELTS(function_addr)) && IDL_SysRtnAdd(procedure_addr, FALSE, IDL_CARRAY_ELTS(procedure_addr)); }
2.453125
2
2024-11-18T22:10:05.517924+00:00
2017-05-04T19:21:43
584086f8988c1fc613987fd5cb1d9c2fe4491f88
{ "blob_id": "584086f8988c1fc613987fd5cb1d9c2fe4491f88", "branch_name": "refs/heads/master", "committer_date": "2017-05-04T19:21:43", "content_id": "a56432c4600166586af2da5809a3ccd824db53cc", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d68dade96a08a1c29d277b7cf9ee5268a99e90ac", "extension": "c", "filename": "test.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 90210347, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 509, "license": "Apache-2.0", "license_type": "permissive", "path": "/test.c", "provenance": "stackv2-0106.json.gz:49599", "repo_name": "veluca93/asd1617-project", "revision_date": "2017-05-04T19:21:43", "revision_id": "defb0625f7a03aab9379a7c94c1dc7ed08bc983f", "snapshot_id": "350e3793de4d48d5f8c1817e139ea27b21d54630", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/veluca93/asd1617-project/defb0625f7a03aab9379a7c94c1dc7ed08bc983f/test.c", "visit_date": "2021-01-20T09:00:20.365634" }
stackv2
#include "parse_osm.h" int main() { osm_map_t* map = osm_parse(stdin); unsigned i; for (i=0; i<dyn_size(map->nodes); i++) { osm_node_t* node = dyn_get(map->nodes, i); printf("%lu (%lf, %lf)", node->id, node->lat, node->lon); unsigned j=0; for (j=0; j<dyn_size(node->tags); j++) { osm_tag_t* tag = dyn_get(node->tags, j); printf(" %s='%s'", tag->key, tag->value); } printf("\n"); } osm_free_map(map); return 0; }
2.59375
3
2024-11-18T22:10:06.363427+00:00
2018-04-16T19:37:10
f8b4c0abc0a6848739a71f2079cad7be1e27800a
{ "blob_id": "f8b4c0abc0a6848739a71f2079cad7be1e27800a", "branch_name": "refs/heads/master", "committer_date": "2018-04-16T19:37:10", "content_id": "253b3ab785aed9cbc5b6b0cd3e35f03a85d589ac", "detected_licenses": [ "MIT" ], "directory_id": "dca4fcbaf2c1e6d06da68ad76008c888744d10f4", "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": 129795062, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11512, "license": "MIT", "license_type": "permissive", "path": "/ARM_STM32/Serial-CAN/main.c", "provenance": "stackv2-0106.json.gz:50632", "repo_name": "fuszenecker/ARM", "revision_date": "2018-04-16T19:37:10", "revision_id": "ef5f58eb0b907ddd4aa807bba43c61b9afb63f21", "snapshot_id": "874dd1f5855eda616059472117b40318d794a821", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/fuszenecker/ARM/ef5f58eb0b907ddd4aa807bba43c61b9afb63f21/ARM_STM32/Serial-CAN/main.c", "visit_date": "2020-03-11T05:10:53.799427" }
stackv2
// --------------------------------------------------------------------------- // This file contains the "main()" function of the microcontroller. // --------------------------------------------------------------------------- #include <config.h> #include <sysinit.h> #include <queue.h> #include <num_conv.h> #include <irq.h> #include <gpio.h> #include <usart.h> #include <clock.h> #include <can.h> #include <can_cmd.h> // --------------------------------------------------------------------------- // Global variables: queues to the CAN and USART routines. // --------------------------------------------------------------------------- volatile t_queue usart2can; volatile t_queue can2usart; // --------------------------------------------------------------------------- // These variables contain the CAN baudrate and the filter/mask settings. // --------------------------------------------------------------------------- volatile unsigned int can_baudrate; volatile unsigned int usart_baudrate = USART_BAUDRATE; extern const unsigned int f_cpu; // Frequency of CPU clock volatile unsigned int can_filter[14], can_id[14]; // --------------------------------------------------------------------------- // The get_free_mem() function determines the free memory (RAM). // --------------------------------------------------------------------------- unsigned int get_free_mem(); // --------------------------------------------------------------------------- // The "main()" function is started by the "sysinit()" routine. // The "sysinit()" is the function that is started when the MCU starts. // --------------------------------------------------------------------------- int main() { // A string to store text message to the "upper" CPU or user char str[MAX_STR_LEN]; // The amount of the free RAM unsigned int free_mem = 1; // Pointer to a message in the message queue t_message *pmsg; // Predefine the value of the CAN baud rate can_baudrate = CAN_BAUDRATE; // Until I realize nirvana... while (1) { // Is there a new message in the USART->CAN queue? // The message arrives from the USART ISR. if (queue_get_non_blocking((t_queue *) &usart2can, &pmsg) == QUEUE_OK) { switch (pmsg->command & 0xffff) { case USART_SET_BAUD: // Predefined baud rate shall be changed usart_baudrate = pmsg->param1; // Set the BAUD rate usart_init(usart_baudrate); // Human-readable string... usart_send_str("+ USART Baud rate: 0x"); // + the numeric of baud rate converted to hexadecimal format num2hex(usart_baudrate, str, 8); // Send hexadecinal "string" usart_send_str(str); usart_send_str("."); break; case CAN_VERSION: // Get version information: // A text message will be sent: // constant text + VERSION string // (which can be seen in "config.h") usart_send_str("+ SER_CAN: "); usart_send_str(DEV_VERSION); break; case GET_FREE_MEM: // Get free memory usart_send_str("+ Free memory: 0x"); // Convert the number to hexadecimal format free_mem = get_free_mem(); num2hex(free_mem, str, 8); // Print the amount of free memory usart_send_str(str); // Memory in use usart_send_str(" bytes, memory in use: 0x"); // Convert the number to hexadecimal format num2hex(RAM_SIZE - free_mem, str, 8); // Print the amount of used memory usart_send_str(str); usart_send_str(" bytes."); break; case CAN_SET_BAUD: // Predefined baud rate shall be changed can_baudrate = pmsg->param1; // See equation above CAN_set_prescaler(f_cpu / 32 / can_baudrate - 1); // Human-readable string... usart_send_str("+ CAN Baud rate: 0x"); // + the numeric of baud rate converted to hexadecimal format num2hex(can_baudrate, str, 8); // Send hexadecinal "string" usart_send_str(str); usart_send_str(", divisor: 0x"); num2hex(f_cpu / 32 / can_baudrate - 1, str, 8); usart_send_str(str); usart_send_str("."); break; case CAN_SET_FILTER: // Set filter mask value: // The filter identifier must be less than 14! if ((pmsg->param1 < 14) && (pmsg->param1 >= 0)) { // Save mask value to the array defined above can_filter[pmsg->param1] = pmsg->param2 & 0x9fffffff; // Set filter according to the saved value CAN_set_filter(pmsg->param1, can_filter[pmsg->param1], can_id[pmsg->param1]); // A little string to the user: // The values will be sent back usart_send_str("+ Filter 0x"); num2hex(pmsg->param1, str, 1); usart_send_str(str); usart_send_str(": Mask: 0x"); num2hex(can_filter[pmsg->param1], str, 8); usart_send_str(str); usart_send_str(", Id: 0x"); num2hex(can_id[pmsg->param1], str, 8); usart_send_str(str); if (can_filter[pmsg->param1] & 0x80000000) usart_send_str(", RTR"); usart_send_str("."); } else { // if the filter ID >= 14 or ID < 0, then an // error message should be sent usart_send_str("- Invalid filter number."); } break; case CAN_SET_ID: // Set ID value: // The filter identifier must be less than 14! if ((pmsg->param1 < 14) && (pmsg->param1 >= 0)) { // Save filter ID value to the array defined above can_id[pmsg->param1] = pmsg->param2 & 0x9fffffff; // Set filter according to the saved value CAN_set_filter(0, can_filter[pmsg->param1], can_id[pmsg->param1]); // A little string to the user: // The values will be sent back usart_send_str("+ Filter 0x"); num2hex(pmsg->param1, str, 1); usart_send_str(str); usart_send_str(": Mask: 0x"); num2hex(can_filter[pmsg->param1], str, 8); usart_send_str(str); usart_send_str(", Id: 0x"); num2hex(can_id[pmsg->param1], str, 8); usart_send_str(str); if (can_filter[pmsg->param1] & 0x80000000) usart_send_str(", RTR"); usart_send_str("."); } else { // if the filter ID >= 14 or ID < 0, then an // error message should be sent usart_send_str("- Invalid filter number."); } break; case CAN_SEND: // Send message through CAN bus: // Try to send the message, on success... if (CAN_send(pmsg->param1 & 0x1fffffff, pmsg->command >> 16, pmsg->param2, pmsg->param3, pmsg->param1 & 0x80000000) == CANTXOK) { // ... a positive acknowledge is sent ... usart_send_str("+ Message successfully sent."); } else { // ... else a warning will be received on USART usart_send_str("- Unable to send message."); } break; case CAN_UNKNOWN: // When an unknown CAN message arrives, a warning should appear usart_send_str("- Invalid command."); break; default: break; } // After sending the message(s), a newline should be sent, as well. // But what kind of newline? CR+LF or LF only? // It depends on the "upper" device or on the user. if (cr_needed) usart_send_str("\r\n"); else usart_send_str("\n"); // The received and processed message should be removed from // the queue, so that some space appaers in the queue. queue_remove((t_queue *) &usart2can); } // If there is a message in the CAN queue arrived from the CAN ISR... if (queue_get_non_blocking((t_queue *)&can2usart, &pmsg) == QUEUE_OK) { // Provide a string that contains the ID, ... usart_send_str("# id: 0x"); num2hex(pmsg->param1 & 0x1fffffff, str, 8); usart_send_str(str); // ... length ... usart_send_str(", length: "); num2hex(pmsg->command & 0xffff, str, 1); usart_send_str(str); // ... and data field. usart_send_str(", data: 0x"); num2hex(pmsg->param2, str, 8); usart_send_str(str); num2hex(pmsg->param3, str, 8); usart_send_str(str); // Remote frame? if (pmsg->command >> 16) usart_send_str(", RTR"); usart_send_str("."); // The string will be terminated as described above. if (cr_needed) usart_send_str("\r\n"); else usart_send_str("\n"); // The received and processed message should be removed from // the queue, so that some space appaers in the queue. queue_remove((t_queue *) &can2usart); } } /* while (1) ... */ } // --------------------------------------------------------------------------- // The get_free_mem() function determines the free memory (RAM). // --------------------------------------------------------------------------- unsigned int get_free_mem() { unsigned char *p = (unsigned char *) RAM_BASE; unsigned int i, flag, free = 0; for (; p < ((unsigned char *) RAM_BASE + RAM_SIZE); p += PAGE_SIZE) { for (flag = 1, i = 0; i < PAGE_SIZE; i++) if (p[i] != 0) flag = 0; if (flag) free++; } return free * PAGE_SIZE; }
2.53125
3
2024-11-18T22:36:55.318732+00:00
2017-02-10T10:40:36
702e60b4646915d9d1da3ff2c5ef4d88bc11ead4
{ "blob_id": "702e60b4646915d9d1da3ff2c5ef4d88bc11ead4", "branch_name": "refs/heads/master", "committer_date": "2017-02-10T10:40:36", "content_id": "9900ee5acb4e43cfb02ca84ab8fedac726f9379b", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "0b582aaa5f49717b9b71d3a0b1c0e3186b910673", "extension": "c", "filename": "2440lib.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 30102006, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17124, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/bootloader/TQloader/src/2440lib.c", "provenance": "stackv2-0107.json.gz:82516", "repo_name": "EleVenPerfect/S3C2440", "revision_date": "2017-02-10T10:40:36", "revision_id": "e85300e53770d384ca4537f3e7bf702ece3d1d6d", "snapshot_id": "14462758fdc40ddd147059ac62ca373cae93bd35", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/EleVenPerfect/S3C2440/e85300e53770d384ca4537f3e7bf702ece3d1d6d/bootloader/TQloader/src/2440lib.c", "visit_date": "2021-01-18T21:08:06.667251" }
stackv2
//=================================================================== // File Name : 2440lib.c // Function : TQ2410 PLL,Uart, LED, Port Init // Version : 1.0 //=================================================================== #include "def.h" #include "option.h" #include "2440addr.h" #include "2440lib.h" #include "2440slib.h" #include <stdarg.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> extern char Image$$RW$$Limit[]; void *mallocPt=Image$$RW$$Limit; //***************************[ SYSTEM ]*************************************************** void Delay(int time) { U32 val = (PCLK>>3)/1000-1; rTCFG0 &= ~(0xff<<8); rTCFG0 |= 3<<8; //prescaler = 3+1 rTCFG1 &= ~(0xf<<12); rTCFG1 |= 0<<12; //mux = 1/2 rTCNTB3 = val; rTCMPB3 = val>>1; // 50% rTCON &= ~(0xf<<16); rTCON |= 0xb<<16; //interval, inv-off, update TCNTB3&TCMPB3, start timer 3 rTCON &= ~(2<<16); //clear manual update bit while(time--) { while(rTCNTO3>=val>>1); while(rTCNTO3<val>>1); }; } //***************************[ PORTS ]**************************************************** void Port_Init(void) { //CAUTION:Follow the configuration order for setting the ports. // 1) setting value(GPnDAT) // 2) setting control register (GPnCON) // 3) configure pull-up resistor(GPnUP) //32bit data bus configuration //*** PORT A GROUP //Ports : GPA22 GPA21 GPA20 GPA19 GPA18 GPA17 GPA16 GPA15 GPA14 GPA13 GPA12 //Signal : nFCE nRSTOUT nFRE nFWE ALE CLE nGCS5 nGCS4 nGCS3 nGCS2 nGCS1 //Binary : 1 1 1 , 1 1 1 1 , 1 1 1 1 //Ports : GPA11 GPA10 GPA9 GPA8 GPA7 GPA6 GPA5 GPA4 GPA3 GPA2 GPA1 GPA0 //Signal : ADDR26 ADDR25 ADDR24 ADDR23 ADDR22 ADDR21 ADDR20 ADDR19 ADDR18 ADDR17 ADDR16 ADDR0 //Binary : 1 1 1 1 , 1 1 1 1 , 1 1 1 1 rGPACON = 0x7fffff; //**** PORT B GROUP //Ports : GPB10 GPB9 GPB8 GPB7 GPB6 GPB5 GPB4 GPB3 GPB2 GPB1 GPB0 //Signal : nXDREQ0 nXDACK0 nXDREQ1 nXDACK1 nSS_KBD nDIS_OFF L3CLOCK L3DATA L3MODE nIrDATXDEN Keyboard //Setting: INPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT //Binary : 00 , 01 01 , 01 01 , 01 01 , 01 01 , 01 01 rGPBCON = 0x055555; rGPBUP = 0x6Bf; // The pull up function is disabled GPB[10:0] //*** PORT C GROUP //Ports : GPC15 GPC14 GPC13 GPC12 GPC11 GPC10 GPC9 GPC8 GPC7 GPC6 GPC5 GPC4 GPC3 GPC2 GPC1 GPC0 //Signal : VD7 VD6 VD5 VD4 VD3 VD2 VD1 VD0 LCDVF2 LCDVF1 LCDVF0 VM VFRAME VLINE VCLK LEND //Binary : 10 10 , 10 10 , 10 10 , 10 10 , 10 10 , 10 10 , 10 10 , 10 10 rGPCCON = 0xaaaaaaaa; rGPCUP = 0xffff; // The pull up function is disabled GPC[15:0] //*** PORT D GROUP //Ports : GPD15 GPD14 GPD13 GPD12 GPD11 GPD10 GPD9 GPD8 GPD7 GPD6 GPD5 GPD4 GPD3 GPD2 GPD1 GPD0 //Signal : VD23 VD22 VD21 VD20 VD19 VD18 VD17 VD16 VD15 VD14 VD13 VD12 VD11 VD10 VD9 VD8 //Binary : 10 10 , 10 10 , 10 10 , 10 10 , 10 10 , 10 10 , 10 10 ,10 10 rGPDCON = 0xaaaaaaaa; rGPDUP = 0xffff; // The pull up function is disabled GPD[15:0] //*** PORT E GROUP //Ports : GPE15 GPE14 GPE13 GPE12 GPE11 GPE10 GPE9 GPE8 GPE7 GPE6 GPE5 GPE4 //Signal : IICSDA IICSCL SPICLK SPIMOSI SPIMISO SDDATA3 SDDATA2 SDDATA1 SDDATA0 SDCMD SDCLK IN //Binary : 10 10 , 10 10 , 10 10 , 10 10 , 10 10 , 10 00 , //------------------------------------------------------------------------------------------------------- //Ports : GPE3 GPE2 GPE1 GPE0 //Signal : IN IN IN IN //Binary : 00 00 , 00 00 //rGPECON = 0xaaaaaaaa; //rGPEUP = 0xffff; // The pull up function is disabled GPE[15:0] rGPECON = 0xa02aa800; // For added AC97 setting rGPEUP = 0xffff; //*** PORT F GROUP //Ports : GPF7 GPF6 GPF5 GPF4 GPF3 GPF2 GPF1 GPF0 //Signal : nLED_8 nLED_4 nLED_2 nLED_1 nIRQ_PCMCIA EINT2 KBDINT EINT0 //Setting: Output Output Output Output EINT3 EINT2 EINT1 EINT0 //Binary : 01 01 , 01 01 , 10 10 , 10 10 rGPFCON = 0x55aa; rGPFUP = 0xff; // The pull up function is disabled GPF[7:0] //*** PORT G GROUP //Ports : GPG15 GPG14 GPG13 GPG12 GPG11 GPG10 GPG9 GPG8 GPG7 GPG6 //Signal : nYPON YMON nXPON XMON EINT19 DMAMODE1 DMAMODE0 DMASTART KBDSPICLK KBDSPIMOSI //Setting: nYPON YMON nXPON XMON EINT19 Output Output Output SPICLK1 SPIMOSI1 //Binary : 11 11 , 11 11 , 10 01 , 01 01 , 11 11 //----------------------------------------------------------------------------------------- //Ports : GPG5 GPG4 GPG3 GPG2 GPG1 GPG0 //Signal : KBDSPIMISO LCD_PWREN EINT11 nSS_SPI IRQ_LAN IRQ_PCMCIA //Setting: SPIMISO1 LCD_PWRDN EINT11 nSS0 EINT9 EINT8 //Binary : 11 11 , 10 11 , 10 10 rGPGCON = 0x00a2aaaa;// GPG9 input without pull-up rGPGUP = 0xffff; // The pull up function is disabled GPG[15:0] //*** PORT H GROUP //Ports : GPH10 GPH9 GPH8 GPH7 GPH6 GPH5 GPH4 GPH3 GPH2 GPH1 GPH0 //Signal : CLKOUT1 CLKOUT0 UCLK nCTS1 nRTS1 RXD1 TXD1 RXD0 TXD0 nRTS0 nCTS0 //Binary : 10 , 10 10 , 11 11 , 10 10 , 10 10 , 10 10 rGPHCON = 0x00faaa; rGPHUP = 0x7ff; // The pull up function is disabled GPH[10:0] // Added for S3C2440X, DonGo //*** PORT J GROUP //Ports : GPJ12 GPJ11 GPJ10 GPJ9 GPJ8 GPJ7 GPJ6 GPJ5 GPJ4 GPJ3 GPJ2 GPJ1 GPJ0 //Signal : CAMRESET CAMPCLKOUT CAMHREF CAMVSYNC CAMPCLKIN CAMDAT[7] CAMDAT[6] CAMDAT[5] CAMDAT[4] CAMDAT[3] CAMDAT[2] CAMDAT[1] CAMDAT[0] //Binary : 10 10 10 10 10 10 10 10 10 10 10 10 10 rGPJCON = 0x02aaaaaa; rGPJUP = 0x1fff; // The pull up function is disabled GPH[10:0] //External interrupt will be falling edge triggered. rEXTINT0 = 0x22222222; // EINT[7:0] rEXTINT1 = 0x22222222; // EINT[15:8] rEXTINT2 = 0x22222222; // EINT[23:16] } //***************************[ UART ]****************************** static int whichUart=0; void Uart_Init(int pclk,int baud) { int i; if(pclk == 0) pclk = PCLK; rUFCON0 = 0x0; //UART channel 0 FIFO control register, FIFO disable rUFCON1 = 0x0; //UART channel 1 FIFO control register, FIFO disable rUFCON2 = 0x0; //UART channel 2 FIFO control register, FIFO disable rUMCON0 = 0x0; //UART chaneel 0 MODEM control register, AFC disable rUMCON1 = 0x0; //UART chaneel 1 MODEM control register, AFC disable //UART0 rULCON0 = 0x3; //Line control register : Normal,No parity,1 stop,8 bits // [10] [9] [8] [7] [6] [5] [4] [3:2] [1:0] // Clock Sel, Tx Int, Rx Int, Rx Time Out, Rx err, Loop-back, Send break, Transmit Mode, Receive Mode // 0 1 0 , 0 1 0 0 , 01 01 // PCLK Level Pulse Disable Generate Normal Normal Interrupt or Polling rUCON0 = 0x245; // Control register rUBRDIV0=( (int)(pclk/16./baud+0.5) -1 ); //Baud rate divisior register 0 //UART1 rULCON1 = 0x3; rUCON1 = 0x245; rUBRDIV1=( (int)(pclk/16./baud+0.5) -1 ); //UART2 rULCON2 = 0x3; rUCON2 = 0x245; rUBRDIV2=( (int)(pclk/16./baud+0.5) -1 ); for(i=0;i<100;i++); } //=================================================================== void Uart_Select(int ch) { if(ch>=0&&ch<=2) whichUart = ch; } //=================================================================== void Uart_TxEmpty(int ch) { if(ch==0) while(!(rUTRSTAT0 & 0x4)); //Wait until tx shifter is empty. else if(ch==1) while(!(rUTRSTAT1 & 0x4)); //Wait until tx shifter is empty. else if(ch==2) while(!(rUTRSTAT2 & 0x4)); //Wait until tx shifter is empty. } //===================================================================== char Uart_Getch(void) { if(whichUart==0) { while(!(rUTRSTAT0 & 0x1)); //Receive data ready return RdURXH0(); } else if(whichUart==1) { while(!(rUTRSTAT1 & 0x1)); //Receive data ready return RdURXH1(); } else if(whichUart==2) { while(!(rUTRSTAT2 & 0x1)); //Receive data ready return RdURXH2(); } return 0 ; } //==================================================================== char Uart_GetKey(void) { if(whichUart==0) { if(rUTRSTAT0 & 0x1) //Receive data ready return RdURXH0(); else return 0; } else if(whichUart==1) { if(rUTRSTAT1 & 0x1) //Receive data ready return RdURXH1(); else return 0; } else if(whichUart==2) { if(rUTRSTAT2 & 0x1) //Receive data ready return RdURXH2(); else return 0; } return 0 ; } //==================================================================== void Uart_GetString(char *string) { char *string2 = string; char c; while((c = Uart_Getch())!='\r') { if(c=='\b') { if( (int)string2 < (int)string ) { Uart_Printf("\b \b"); string--; } } else { *string++ = c; Uart_SendByte(c); } } *string='\0'; Uart_SendByte('\n'); } //===================================================================== int Uart_GetIntNum(void) { char str[30]; char *string = str; int base = 10; int minus = 0; int result = 0; int lastIndex; int i; Uart_GetString(string); if(string[0]=='-') { minus = 1; string++; } if(string[0]=='0' && (string[1]=='x' || string[1]=='X')) { base = 16; string += 2; } lastIndex = strlen(string) - 1; if(lastIndex<0) return -1; if(string[lastIndex]=='h' || string[lastIndex]=='H' ) { base = 16; string[lastIndex] = 0; lastIndex--; } if(base==10) { result = atoi(string); result = minus ? (-1*result):result; } else { for(i=0;i<=lastIndex;i++) { if(isalpha(string[i])) { if(isupper(string[i])) result = (result<<4) + string[i] - 'A' + 10; else result = (result<<4) + string[i] - 'a' + 10; } else result = (result<<4) + string[i] - '0'; } result = minus ? (-1*result):result; } return result; } //***************************************************************************** //get a number for the uart //***************************************************************************** int Uart_GetIntNum_GJ(void) { char string[16] ; char *p_string = string ; char c; int i = 0 ; int data = 0 ; while( ( c = Uart_Getch()) != '\r' ) { if(c=='\b') p_string--; else *p_string++=c; Uart_SendByte( c ) ; } *p_string = '\0'; i = 0 ; while( string[i] != '\0' ) { data = data * 10 ; if( string[i]<'0'||string[i]>'9' ) return -1 ; data = data + ( string[i]-'0' ) ; i++ ; } return data ; } //***************************************************************************** //===================================================================== void Uart_SendByte(int data) { if(whichUart==0) { if(data=='\n') { while(!(rUTRSTAT0 & 0x2)); // Delay(1); //because the slow response of hyper_terminal WrUTXH0('\r'); } while(!(rUTRSTAT0 & 0x2)); //Wait until THR is empty. // Delay(1); WrUTXH0(data); } else if(whichUart==1) { if(data=='\n') { while(!(rUTRSTAT1 & 0x2)); //Delay(1); //because the slow response of hyper_terminal rUTXH1 = '\r'; } while(!(rUTRSTAT1 & 0x2)); //Wait until THR is empty. //Delay(1); rUTXH1 = data; } else if(whichUart==2) { if(data=='\n') { while(!(rUTRSTAT2 & 0x2)); //Delay(1); //because the slow response of hyper_terminal rUTXH2 = '\r'; } while(!(rUTRSTAT2 & 0x2)); //Wait until THR is empty. //Delay(1); rUTXH2 = data; } } //==================================================================== void Uart_SendString(char *pt) { while(*pt) Uart_SendByte(*pt++); } //==================================================================== char *hex2char(unsigned int val) { static char str[2]; str[1]='\0'; if(val<=9) str[0]='0'+val; else str[0]=('a'+val-10); return str; } //==================================================================== void Uart_SendDWORD(DWORD d, BOOL cr) { Uart_SendString("0x"); Uart_SendString(hex2char((d & 0xf0000000) >> 28)); Uart_SendString(hex2char((d & 0x0f000000) >> 24)); Uart_SendString(hex2char((d & 0x00f00000) >> 20)); Uart_SendString(hex2char((d & 0x000f0000) >> 16)); Uart_SendString(hex2char((d & 0x0000f000) >> 12)); Uart_SendString(hex2char((d & 0x00000f00) >> 8)); Uart_SendString(hex2char((d & 0x000000f0) >> 4)); Uart_SendString(hex2char((d & 0x0000000f) >> 0)); if (cr) Uart_SendString("\n"); } //===================================================================== //If you don't use vsprintf(), the code size is reduced very much. void Uart_Printf(char *fmt,...) { va_list ap; char string[256]; va_start(ap,fmt); vsprintf(string,fmt,ap); Uart_SendString(string); va_end(ap); } //**************************[ BOARD LED ]********************************* void LED_Display(int data) { rGPBDAT = (rGPBDAT & ~(0x5<<5)) | ((~data & 0x5)<<5); } //***************************[ BOARD BEEP ]******************************* void Buzzer_Freq_Set( U32 freq ) { rGPBCON &= ~3; //set GPB0 as tout0, pwm output rGPBCON |= 2; rTCFG0 &= ~0xff; rTCFG0 |= 15; //prescaler = 15+1 rTCFG1 &= ~0xf; rTCFG1 |= 2; //mux = 1/8 rTCNTB0 = (PCLK>>7)/freq; rTCMPB0 = rTCNTB0>>1; // 50% rTCON &= ~0x1f; rTCON |= 0xb; //disable deadzone, auto-reload, inv-off, update TCNTB0&TCMPB0, start timer 0 rTCON &= ~2; //clear manual update bit } void Buzzer_Stop( void ) { rGPBCON &= ~3; //set GPB0 as output rGPBCON |= 1; rGPBDAT &= ~1; } //***************************[ BOARD BEEP ]******************************* void Beep(U32 freq, U32 ms) { Buzzer_Freq_Set( freq ) ; Delay( ms ) ; Buzzer_Stop() ; } //*************************[ Timer ]******************************** void Timer_Start(int divider) //0:16us,1:32us 2:64us 3:128us { rWTCON = ((PCLK/1000000-1)<<8)|(divider<<3); //Watch-dog timer control register rWTDAT = 0xffff; //Watch-dog timer data register rWTCNT = 0xffff; //Watch-dog count register // Watch-dog timer enable & interrupt disable rWTCON = (rWTCON & ~(1<<5) & ~(1<<2)) |(1<<5); } //================================================================= int Timer_Stop(void) { rWTCON = ((PCLK/1000000-1)<<8); return (0xffff - rWTCNT); } //*************************[ MPLL ]******************************* void ChangeMPllValue(int mdiv,int pdiv,int sdiv) { rMPLLCON = (mdiv<<12) | (pdiv<<4) | sdiv; } //************************[ HCLK, PCLK ]*************************** void ChangeClockDivider() { int hdivn=2, pdivn=1; // hdivn_val (FCLK:HCLK)ratio hdivn // 11 1:1 (0) // 12 1:2 (1) // 13 1:3 (3) // 14 1:4 (2) // pdivn_val (HCLK:PCLK)ratio pdivn // 11 1:1 (0) // 12 1:2 (1) //Uart_Printf("Clock division change [hdiv:%x, pdiv:%x]\n", hdivn, pdivn); rCLKDIVN = (hdivn<<1) | pdivn; if(hdivn!=0) MMU_SetAsyncBusMode(); else MMU_SetFastBusMode(); } //**************************[ UPLL ]******************************* void ChangeUPllValue(int mdiv,int pdiv,int sdiv) { rUPLLCON = (mdiv<<12) | (pdiv<<4) | sdiv; } //*************************[ General Library ]********************** void * malloc(unsigned nbyte) //Very simple; Use malloc() & free() like Stack //void *mallocPt=Image$$RW$$Limit; { void *returnPt = mallocPt; mallocPt = (int *)mallocPt+nbyte/4+((nbyte%4)>0); //To align 4byte if( (int)mallocPt > HEAPEND ) { mallocPt = returnPt; return NULL; } return returnPt; } //------------------------------------------------------------------- void free(void *pt) { mallocPt = pt; }
2.171875
2
2024-11-18T22:36:55.378980+00:00
2019-10-02T21:30:25
5bad3dcfe2c5901c13c20d4b911fc148af750adb
{ "blob_id": "5bad3dcfe2c5901c13c20d4b911fc148af750adb", "branch_name": "refs/heads/master", "committer_date": "2019-10-02T21:30:25", "content_id": "a7d07135ec02c1483d584781a02f051251b5e436", "detected_licenses": [ "MIT" ], "directory_id": "e7835fd7ea78cb6edf590c60a0b24fc5b343e00b", "extension": "h", "filename": "ModbusEnum.h", "fork_events_count": 0, "gha_created_at": "2019-12-04T01:14:42", "gha_event_created_at": "2019-12-04T01:14:43", "gha_language": null, "gha_license_id": "NOASSERTION", "github_id": 225749953, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 639, "license": "MIT", "license_type": "permissive", "path": "/pnpbridge/src/adapters/src/modbus_pnp/ModbusEnum.h", "provenance": "stackv2-0107.json.gz:82644", "repo_name": "matsujirushi/AzurePnPBridgePreview", "revision_date": "2019-10-02T21:30:25", "revision_id": "cef6def7f14965fba65948a9eeae97a029d49f1b", "snapshot_id": "e1cc9d9b74160bdac4c66168757e7e380f25bc0d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matsujirushi/AzurePnPBridgePreview/cef6def7f14965fba65948a9eeae97a029d49f1b/pnpbridge/src/adapters/src/modbus_pnp/ModbusEnum.h", "visit_date": "2020-09-24T11:26:55.740814" }
stackv2
#pragma once #ifdef __cplusplus extern "C" { #endif typedef enum ModbusDataType { NUMERIC, FLAG, STRING, HEXSTRING, INVALID } ModbusDataType; typedef enum EntityType { CoilStatus = 0, InputStatus = 1, InputRegister = 3, HoldingRegister = 4 } EntityType; typedef enum FunctionCodeType { ReadCoils = 1, ReadInputs = 2, ReadHoldingRegisters = 3, ReadInputRegisters = 4, WriteCoil = 5, WriteHoldingRegister = 6 } FunctionCodeType; typedef enum CapabilityType { Telemetry, Property, Command } CapabilityType; typedef enum MODBUS_CONNECTION_TYPE { UNKOWN, RTU, TCP, }MODBUS_CONNECTION_TYPE; #ifdef __cplusplus } #endif
2
2
2024-11-18T22:36:55.457828+00:00
2021-09-08T05:57:32
dfccb90423092c0f4830be66dc4e190545d20ac4
{ "blob_id": "dfccb90423092c0f4830be66dc4e190545d20ac4", "branch_name": "refs/heads/master", "committer_date": "2021-09-08T05:57:32", "content_id": "e962266a992ef2cd5462a9aea8ff8e87f805e662", "detected_licenses": [ "MIT" ], "directory_id": "05dcfa3fbf8cd95f94f1af14a068d28e1129e1d5", "extension": "c", "filename": "encryption.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": 3092, "license": "MIT", "license_type": "permissive", "path": "/src/encryption.c", "provenance": "stackv2-0107.json.gz:82773", "repo_name": "nihilistdev/PassMann", "revision_date": "2021-09-08T05:57:32", "revision_id": "2e79222970fcfec0b4c92336e7ed4f0b0c009ecc", "snapshot_id": "e5fb7bc852dad8eb83fed60a8c09cb12bfb8e9e8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/nihilistdev/PassMann/2e79222970fcfec0b4c92336e7ed4f0b0c009ecc/src/encryption.c", "visit_date": "2023-07-27T10:05:47.445678" }
stackv2
#include "encryption.h" /** * Encrypts file using crypto secret box from libsodium */ int encrypt(const char *target_file, const char *source_file, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) { unsigned char buf_in[CHUNK_SIZE]; unsigned char buf_out[CHUNK_SIZE + crypto_secretstream_xchacha20poly1305_ABYTES]; unsigned char header[crypto_secretstream_xchacha20poly1305_HEADERBYTES]; crypto_secretstream_xchacha20poly1305_state st; FILE *fp_t, *fp_s; unsigned long long out_len; size_t rlen; int eof; unsigned char tag; fp_s = fopen(source_file, "rb"); fp_t = fopen(target_file, "wb"); crypto_secretstream_xchacha20poly1305_init_push(&st, header, key); fwrite(header, 1, sizeof header, fp_t); do { rlen = fread(buf_in, 1, sizeof buf_in, fp_s); eof = feof(fp_s); tag = eof ? crypto_secretstream_xchacha20poly1305_TAG_FINAL : 0; crypto_secretstream_xchacha20poly1305_push(&st, buf_out, &out_len, buf_in, rlen, NULL, 0, tag); fwrite(buf_out, 1, (size_t)out_len, fp_t); } while (!eof); fclose(fp_t); fclose(fp_s); return 0; } /** * Decrypts the file */ int decrypt(const char *target_file, const char *source_file, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]) { unsigned char buf_in[CHUNK_SIZE + crypto_secretstream_xchacha20poly1305_ABYTES]; unsigned char buf_out[CHUNK_SIZE]; unsigned char header[crypto_secretstream_xchacha20poly1305_HEADERBYTES]; crypto_secretstream_xchacha20poly1305_state st; FILE *fp_t, *fp_s; unsigned long long out_len; size_t rlen; int eof; int ret = -1; unsigned char tag; fp_s = fopen(source_file, "rb"); fp_t = fopen(target_file, "wb"); fread(header, 1, sizeof header, fp_s); if (crypto_secretstream_xchacha20poly1305_init_pull(&st, header, key) != 0) { append_log(time_now(), "Incomplete header"); goto ret; /* incomplete header */ } do { rlen = fread(buf_in, 1, sizeof buf_in, fp_s); eof = feof(fp_s); if (crypto_secretstream_xchacha20poly1305_pull(&st, buf_out, &out_len, &tag, buf_in, rlen, NULL, 0) != 0) { append_log(time_now(), "Corrupted chunk"); goto ret; /* corrupted chunk */ } if (tag == crypto_secretstream_xchacha20poly1305_TAG_FINAL && !eof) { append_log(time_now(), "Premature end (end of file reached before the end of the stream)"); goto ret; /* premature end (end of file reached before the end of the stream) */ } fwrite(buf_out, 1, (size_t)out_len, fp_t); } while (!eof); ret = 0; ret: fclose(fp_t); fclose(fp_s); return ret; } int check_db_file(char *filename) { FILE *fptr; fptr = fopen(filename, "rb"); if (fptr == NULL) { return -1; } fclose(fptr); return 0; }
2.25
2
2024-11-18T22:36:55.734472+00:00
2019-08-24T19:03:48
b6f9e9a52c205187357152bbad087227553dadb2
{ "blob_id": "b6f9e9a52c205187357152bbad087227553dadb2", "branch_name": "refs/heads/master", "committer_date": "2019-08-24T19:03:48", "content_id": "55685f7780d12609be17335bdf0f36413bf7ad84", "detected_licenses": [ "MIT" ], "directory_id": "278fe7b839774d07ba74604fc2c907ec7148a424", "extension": "c", "filename": "patch.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 204199164, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 202, "license": "MIT", "license_type": "permissive", "path": "/x86/patch.c", "provenance": "stackv2-0107.json.gz:83159", "repo_name": "rockstar177/Patch", "revision_date": "2019-08-24T19:03:48", "revision_id": "1883eeb688466940e23ac4c9b062911b311060ca", "snapshot_id": "7e5e3c58806afdb4582bb2e4515b9c8515cc2522", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rockstar177/Patch/1883eeb688466940e23ac4c9b062911b311060ca/x86/patch.c", "visit_date": "2020-07-10T06:59:31.600357" }
stackv2
#include <stdio.h> int main(void) { FILE * file = fopen("binary","r+b"); unsigned char opcode = 0x74; fseek(file,0x6a1,SEEK_SET); fwrite(&opcode,sizeof(opcode),1,file); fclose(file); return 0; }
2.0625
2
2024-11-18T22:36:55.805360+00:00
2021-01-11T04:01:03
e120bc493fe2a84217ed4ac690632d1ea44e9784
{ "blob_id": "e120bc493fe2a84217ed4ac690632d1ea44e9784", "branch_name": "refs/heads/master", "committer_date": "2021-01-11T04:01:03", "content_id": "4d312ecf7e74cd23d71c552693b6da1dadc74469", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f4109a281e5171675a65711e7edcf4873bc7fbac", "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": 174640917, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12438, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0107.json.gz:83288", "repo_name": "mnakao/APSP", "revision_date": "2021-01-11T04:01:03", "revision_id": "afc07bb4aa8ab3278bbc9e1e38f05eea8b4c3c22", "snapshot_id": "3125feeefab9baebbb9e8a4fbfbb41bbbae4d541", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mnakao/APSP/afc07bb4aa8ab3278bbc9e1e38f05eea8b4c3c22/main.c", "visit_date": "2021-06-22T15:21:25.912103" }
stackv2
#include "common.h" double elapsed[NUM_TIMERS], start[NUM_TIMERS]; #ifdef __C2CUDA__ extern void init_matrix_dev(const int nodes, const int degree, const int* num_degrees, const int algo); extern void finalize_matrix_dev(); extern void matrix_op(const int nodes, const int degree, const int* restrict adjacency, const int* restrict num_degrees, const int groups, int *diameter, double *ASPL, double *sum); extern void matrix_op_memory_saving(const int nodes, const int degree, const int* restrict adjacency, const int* restrict num_degrees, const int groups, int *diameter, double *ASPL, double *sum); #endif static void print_help(char *argv) { PRINT_R0("%s -f <edge_file> [-g <groups>] [-n <iterations>] [-d degree] [-B] [-S] [-P] [-h]\n", argv); EXIT(0); } static void set_args(const int argc, char **argv, char *infname, int *groups, int *num, int *degree, bool *enable_bfs, bool *enable_memory_saving, bool *enable_profile) { if(argc == 1 || argc == 2) print_help(argv[0]); int result; while((result = getopt(argc,argv,"f:g:n:d:hlBSP"))!=-1){ switch(result){ case 'f': if(strlen(optarg) > MAX_FILENAME_LENGTH){ PRINT_R0("Input filename is long (%s). Please change MAX_FILENAME_LENGTH.\n", optarg); EXIT(1); } strcpy(infname, optarg); break; case 'g': *groups = atoi(optarg); break; case 'n': *num = atoi(optarg); break; case 'd': *degree = atoi(optarg); break; case 'l': // This option remains for compatibility with the past version break; case 'B': *enable_bfs = true; break; case 'S': *enable_memory_saving = true; break; case 'P': *enable_profile = true; break; default: print_help(argv[0]); } } } #ifdef _OPENMP static int top_down_step(const int level, const int nodes, const int num_frontier, const int degree, const int* restrict adjacency, int* restrict num_degrees, int* restrict frontier, int* restrict next, int* restrict distance, char* restrict bitmap) { int count = 0; int local_frontier[nodes]; #pragma omp parallel private(local_frontier) { int local_count = 0; #pragma omp for nowait for(int i=0;i<num_frontier;i++){ int v = frontier[i]; for(int j=0;j<num_degrees[v];j++){ int n = *(adjacency + v * degree + j); // adjacency[v][j]; if(bitmap[n] == NOT_VISITED){ bitmap[n] = VISITED; distance[n] = level; local_frontier[local_count++] = n; } } } // end for i #pragma omp critical { memcpy(&next[count], local_frontier, local_count*sizeof(int)); count += local_count; } } return count; } #else static int top_down_step(const int level, const int nodes, const int num_frontier, const int degree, const int* restrict adjacency, const int* restrict num_degrees, int* restrict frontier, int* restrict next, int* restrict distance, char* restrict bitmap) { int count = 0; for(int i=0;i<num_frontier;i++){ int v = frontier[i]; for(int j=0;j<num_degrees[v];j++){ int n = *(adjacency + v * degree + j); // int n = adjacency[v][j]; if(bitmap[n] == NOT_VISITED){ bitmap[n] = VISITED; distance[n] = level; next[count++] = n; } } } return count; } #endif #ifndef __C2CUDA__ static void matrix_op_memory_saving(const int nodes, const int degree, const int* restrict adjacency, const int* restrict num_degrees, const int groups, int *diameter, double *ASPL, double *sum) { unsigned int elements = (nodes/groups+(UINT64_BITS-1))/UINT64_BITS; size_t s = nodes * CHUNK * sizeof(uint64_t); uint64_t* A = malloc(s); // uint64_t A[nodes][CHUNK]; uint64_t* B = malloc(s); // uint64_t B[nodes][CHUNK]; int parsize = (elements + CHUNK - 1)/CHUNK; *sum = (double)nodes * (nodes - 1); *diameter = 1; for(int t=0;t<parsize;t++){ unsigned int kk, l; clear_buffers(A, B, nodes * CHUNK); for(l=0; l<UINT64_BITS*CHUNK && UINT64_BITS*t*CHUNK+l<nodes/groups; l++){ unsigned int offset = (UINT64_BITS*t*CHUNK+l)*CHUNK+l/UINT64_BITS; A[offset] = B[offset] = (0x1ULL<<(l%UINT64_BITS)); } for(kk=0;kk<nodes;kk++){ #pragma omp parallel for for(int i=0;i<nodes;i++) for(int j=0;j<num_degrees[i];j++){ int n = *(adjacency + i * degree + j); // int n = adjacency[i][j]; for(int k=0;k<CHUNK;k++) B[i*CHUNK+k] |= A[n*CHUNK+k]; } uint64_t num = 0; #pragma omp parallel for reduction(+:num) for(int i=0;i<CHUNK*nodes;i++) num += POPCNT(B[i]); if(num == (uint64_t)nodes*l) break; // swap A <-> B uint64_t* tmp = A; A = B; B = tmp; *sum += ((double)nodes * l - num) * groups; } *diameter = MAX(*diameter, kk+1); } if(*diameter > nodes){ PRINT_R0("This graph is not connected graph.\n"); EXIT(1); } *ASPL = *sum / (((double)nodes-1)*nodes); *sum /= 2.0; free(A); free(B); } static void matrix_op(const int nodes, const int degree, const int* restrict adjacency, const int* restrict num_degrees, const int groups, int *diameter, double *ASPL, double *sum) { unsigned int elements = (nodes/groups+(UINT64_BITS-1))/UINT64_BITS; size_t s = nodes * elements * sizeof(uint64_t); uint64_t* A = malloc(s); // uint64_t A[nodes][elements]; uint64_t* B = malloc(s); // uint64_t B[nodes][elements]; clear_buffers(A, B, nodes * elements); #pragma omp parallel for for(int i=0;i<nodes/groups;i++){ unsigned int offset = i*elements+i/UINT64_BITS; A[offset] = B[offset] = (0x1ULL << (i%UINT64_BITS)); } *sum = (double)nodes * (nodes - 1); *diameter = 1; for(int kk=0;kk<nodes;kk++){ #pragma omp parallel for for(int i=0;i<nodes;i++) for(int j=0;j<num_degrees[i];j++){ int n = *(adjacency + i * degree + j); // int n = adjacency[i][j]; for(int k=0;k<elements;k++) B[i*elements+k] |= A[n*elements+k]; } uint64_t num = 0; #pragma omp parallel for reduction(+:num) for(int i=0;i<elements*nodes;i++) num += POPCNT(B[i]); num *= groups; if(num == (uint64_t)nodes*nodes) break; // swap A <-> B uint64_t* tmp = A; A = B; B = tmp; *sum += (double)nodes * nodes - num; (*diameter) += 1; } if(*diameter > nodes){ PRINT_R0("This graph is not connected graph.\n"); EXIT(1); } *ASPL = *sum / (((double)nodes-1)*nodes); *sum /= 2.0; free(A); free(B); } #endif static void bfs(const int nodes, const int lines, const int degree, int* restrict adjacency, int* restrict num_degrees, const int groups, int *diameter, double *ASPL, double *sum) { int *frontier = malloc(sizeof(int) * nodes); int *distance = malloc(sizeof(int) * nodes); char *bitmap = malloc(sizeof(char) * nodes); int *next = malloc(sizeof(int) * nodes); bool all_visited = true; *sum = 0; for(int s=0;s<nodes/groups;s++){ int num_frontier = 0, level = 0; for(int i=0;i<nodes;i++) bitmap[i] = NOT_VISITED; frontier[0] = s; num_frontier = 1; distance[s] = level; bitmap[s] = VISITED; while(1){ num_frontier = top_down_step(level++, nodes, num_frontier, degree, (int *)adjacency, num_degrees, frontier, next, distance, bitmap); if(num_frontier == 0) break; // Swap frontier <-> next int *tmp = frontier; frontier = next; next = tmp; } *diameter = MAX(*diameter, level-1); for(int i=s+1;i<nodes;i++){ if(bitmap[i] == NOT_VISITED) all_visited = false; if(groups == 1) *sum += (distance[i] + 1); else *sum += (distance[i] + 1) * (groups - i/(nodes/groups)); } } if(all_visited == false){ PRINT_R0("This graph is not connected graph.\n"); EXIT(1); } *ASPL = *sum / ((((double)nodes-1)*nodes)/2); free(frontier); free(distance); free(bitmap); free(next); } static void evaluation(const int nodes, const int lines, const int degree, int* restrict adjacency, int* restrict num_degrees, const int groups, const bool enable_bfs, int *diameter, double *ASPL, double *sum, const int algo) { if(algo == BFS) bfs(nodes, lines, degree, adjacency, num_degrees, groups, diameter, ASPL, sum); else if(algo == MATRIX_OP) matrix_op(nodes, degree, adjacency, num_degrees, groups, diameter, ASPL, sum); else if(algo == MATRIX_OP_MEMORY_SAVING) matrix_op_memory_saving(nodes, degree, adjacency, num_degrees, groups, diameter, ASPL, sum); } int main(int argc, char *argv[]) { char infname[MAX_FILENAME_LENGTH]; int diameter = -1, low_diam = -1, groups = 1, num = 1, algo; double ASPL = -1.0, sum = 0.0, low_ASPL = -1.0; int width = 0, height = 0, degree = NOT_DEFINED; bool enable_bfs = false, enable_memory_saving = false, enable_profile = false; set_args(argc, argv, infname, &groups, &num, &degree, &enable_bfs, &enable_memory_saving, &enable_profile); bool is_general = check_general(infname); if(!is_general && groups != 1) ERROR("Not Implement yet using -g for grid graph.\n"); else if(enable_bfs && enable_memory_saving) ERROR("(-B && -L) must not be used.\n"); #ifdef __C2CUDA__ else if(enable_bfs) ERROR("BFS is not implemented in CUDA version.\n"); else if(groups != 1) ERROR("-g must be 1 in CUDA version.\n"); #endif int lines = count_lines(infname); int (*edge)[2] = malloc(sizeof(int)*lines*2); // int edge[lines][2]; if(is_general) read_file_general(edge, infname); else read_file_grid(edge, &width, &height, infname); int nodes = max_node_num(lines, (int *)edge) + 1; if(nodes%groups != 0) ERROR("Number of nodes must be divisible by g.\n"); if(enable_bfs) algo = BFS; else if(enable_memory_saving) algo = MATRIX_OP_MEMORY_SAVING; else{ unsigned int elements = (nodes+(UINT64_BITS-1))/UINT64_BITS; double s = (double)nodes/groups * elements * sizeof(uint64_t); algo = (s <= (double)MATRIX_OP_THRESHOLD)? MATRIX_OP : MATRIX_OP_MEMORY_SAVING; } calc_degree(nodes, lines, edge, &degree); int (*adjacency)[degree] = malloc(sizeof(int) * nodes * degree); // int adjacency[nodes][degree]; if(is_general){ lower_bound_of_diam_aspl_general(&low_diam, &low_ASPL, nodes, degree); PRINT_R0("Nodes = %d, Degree = %d\n", nodes, degree); } else{ int length = calc_length(lines, edge, height); lower_bound_of_diam_aspl_grid(&low_diam, &low_ASPL, width, height, degree, length); PRINT_R0("Width = %d, Height = %d, Degree = %d, Length = %d\n", width, height, degree, length); } int *num_degrees = malloc(sizeof(int) * nodes); clear_buffer(num_degrees, nodes); create_adjacency(nodes, lines, degree, edge, adjacency, num_degrees); #ifdef __C2CUDA__ init_matrix_dev(nodes, degree, num_degrees, algo); #endif timer_clear_all(); timer_start(TIMER_BFS); for(int i=0;i<num;i++) evaluation(nodes, lines, degree, (int *)adjacency, (int *)num_degrees, groups, enable_bfs, &diameter, &ASPL, &sum, algo); timer_stop(TIMER_BFS); PRINT_R0("Diameter = %d\n", diameter); PRINT_R0("Diameter Gap = %d (%d - %d)\n", diameter-low_diam, diameter, low_diam); PRINT_R0("ASPL = %.10f (%.0f/%.0f)\n", ASPL, sum, (double)nodes*(nodes-1)/2); PRINT_R0("ASPL Gap = %.10f (%.10f - %.10f)\n", ASPL - low_ASPL, ASPL, low_ASPL); double time_bfs = timer_read(TIMER_BFS); if(enable_profile){ PRINT_R0("---\n"); if(num != 1) PRINT_R0("Number of iterations = %d\n", num); #ifdef _OPENMP PRINT_R0("Number of threads = %d\n", omp_get_max_threads()); #endif if(groups != 1) PRINT_R0("Number of groups = %d\n", groups); if(algo == BFS) PRINT_R0("Algothrim = BFS\n"); else if(algo == MATRIX_OP) PRINT_R0("Algothrim = MATRIX Opetation\n"); else PRINT_R0("Algothrim = MATRIX Operation (MEMORY SAVING)\n"); PRINT_R0("Elapsed Time = %f sec.\n", time_bfs); double traversed_edges = (double)nodes*lines/groups; PRINT_R0("Performance = %f MTEPS\n", traversed_edges/time_bfs/1000/1000*num); verify(lines, edge, is_general, height); } #ifdef __C2CUDA__ finalize_matrix_dev(); #endif return 0; }
2.296875
2
2024-11-18T22:36:56.222203+00:00
2019-07-05T20:40:56
38108ca2cf6987f3e3201bb753d2633758bc84cb
{ "blob_id": "38108ca2cf6987f3e3201bb753d2633758bc84cb", "branch_name": "refs/heads/master", "committer_date": "2019-07-05T20:40:56", "content_id": "f6b8a29bdbb00dc4cb3637726ee409d95516276c", "detected_licenses": [ "MIT" ], "directory_id": "228e8e60648165e03e53f28d4b3f2545763edc0e", "extension": "h", "filename": "ExtremeC_examples_chapter4_3.h", "fork_events_count": 0, "gha_created_at": "2019-07-06T00:20:59", "gha_event_created_at": "2019-07-06T00:21:00", "gha_language": null, "gha_license_id": null, "github_id": 195480165, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 813, "license": "MIT", "license_type": "permissive", "path": "/ch04/ExtremeC_examples_chapter4_3.h", "provenance": "stackv2-0107.json.gz:83417", "repo_name": "urantialife/Extreme-C", "revision_date": "2019-07-05T20:40:56", "revision_id": "9608c6869d39408aa712b1fa872db1f637c47642", "snapshot_id": "b992c2325a758157bc644db16dcac5939734ecd8", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/urantialife/Extreme-C/9608c6869d39408aa712b1fa872db1f637c47642/ch04/ExtremeC_examples_chapter4_3.h", "visit_date": "2020-06-16T04:29:45.486556" }
stackv2
// File name: ExtremeC_examples_chapter4_3.h // Description: The header file which exposes public attributes and behavior functions // related to a list object. As you see, the attribute structure does not // disclose any of its members. #ifndef EXTREME_C_EXAMPLES_CHAPTER_4_3_H #define EXTREME_C_EXAMPLES_CHAPTER_4_3_H #include <unistd.h> // The attribute structure with no disclosed attribute struct list_t; // Allocation function struct list_t* list_malloc(); // Constructor and destructor functions void list_init(struct list_t*); void list_destroy(struct list_t*); // Public behavior functions int list_add(struct list_t*, int); int list_get(struct list_t*, int, int*); void list_clear(struct list_t*); size_t list_size(struct list_t*); void list_print(struct list_t*); #endif
2.1875
2
2024-11-18T22:36:56.461462+00:00
2021-06-02T18:57:18
b987a2f9e6ab3b020387488cd7fb0b87f19a2294
{ "blob_id": "b987a2f9e6ab3b020387488cd7fb0b87f19a2294", "branch_name": "refs/heads/main", "committer_date": "2021-06-02T18:57:18", "content_id": "33dbe76c86a41db89c902a5438679db5060cd268", "detected_licenses": [ "Unlicense" ], "directory_id": "d023d5d3f7204443fd5583be4d57562262c7bff1", "extension": "h", "filename": "irc_array.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": 796, "license": "Unlicense", "license_type": "permissive", "path": "/Unnamed-Project/irc_base/irc_array.h", "provenance": "stackv2-0107.json.gz:83807", "repo_name": "duplicatalittera/Miscellaneous", "revision_date": "2021-06-02T18:57:18", "revision_id": "280c8940de8c0cf59947058bebe10bfc52cdd4e0", "snapshot_id": "9479eda2c4cd6106a3796666d326fd889546adf9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/duplicatalittera/Miscellaneous/280c8940de8c0cf59947058bebe10bfc52cdd4e0/Unnamed-Project/irc_base/irc_array.h", "visit_date": "2023-05-25T18:24:16.774132" }
stackv2
#ifndef __IRC_ARRAY_H #define __IRC_ARRAY_H #include "irc_base.h" #include <malloc.h> #include <string.h> #include <stdarg.h> typedef struct { void **data; ul_t size; } Array; Array array(ul_t size, ...) { void **arr = malloc(sizeof(void *) * size); va_list vlist; va_start(vlist, size); for (ul_t i = 0; i < size; i++) { void *arg = va_arg(vlist, void *); arr[i] = arg; } va_end(vlist); return (Array) { arr, size }; } void append(Array *arr, void *data) { ul_t size = arr->size; void **tmp = realloc(arr->data, sizeof(void *) * size + 1ull); tmp[size] = data; arr->data = tmp; arr->size++; } void set(Array *arr, ul_t index, void *data) { if (arr->size <= index) return; arr->data[index] = data; } #endif
2.515625
3
2024-11-18T22:36:56.787805+00:00
2022-11-05T17:46:59
4cc0522751eff1c749a2f58c9a1a355d17e413e2
{ "blob_id": "4cc0522751eff1c749a2f58c9a1a355d17e413e2", "branch_name": "refs/heads/master", "committer_date": "2022-11-05T17:46:59", "content_id": "b81848aa45c33aa206f55ca33578940949df24b7", "detected_licenses": [ "MIT" ], "directory_id": "c07d5913ecf3a23e5ba5b7fb1ed5f39550a86e96", "extension": "c", "filename": "runsub.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 37094911, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3383, "license": "MIT", "license_type": "permissive", "path": "/DevTools/runsub.c", "provenance": "stackv2-0107.json.gz:84064", "repo_name": "stackprobe/Factory", "revision_date": "2022-11-05T17:46:59", "revision_id": "0aef20aefba7a080f12652230790a18ce17c2795", "snapshot_id": "41777490800b30a02ba80286b536c1e9a80f2b4f", "src_encoding": "SHIFT_JIS", "star_events_count": 2, "url": "https://raw.githubusercontent.com/stackprobe/Factory/0aef20aefba7a080f12652230790a18ce17c2795/DevTools/runsub.c", "visit_date": "2022-11-24T15:50:59.412175" }
stackv2
/* > runsub.exe [/-B] [/-S | /-R] [/-O] [/R ROOT-DIR] [/T TIMEWAIT-SEC] [/TM TIMEWAIT-MILLIS] TARGET /-B ... 実行するプログラムの終了を待たずに次へ進む。 /-S ... サブディレクトリを無視する。 /-R ... 検索のルートディレクトリを無視する。 /-O ... Ignore obj Debug ROOT-DIR ... 検索のルートディレクトリを指定する。デフォ = 実行時のカレント TIMEWAIT-SEC ... プログラムを実行する度に待つ秒数。 TIMEWAIT-MILLIS ... プログラムを実行する度に待つミリ秒数。 TARGET ... 実行するプログラムのノード名 全てのプログラムを実行する場合は * を指定する。 *PTN とすると部分一致になる。 - - - 実行するプログラムと同じディレクトリへ移動してから実行する。 */ #include "C:\Factory\Common\all.h" #include "C:\Factory\SubTools\BlueFish\libs\Lock.h" static uint NonBlockingMode; static uint TimeWaitMillis; static void Run(char *file) { char *absPath = c_makeFullPath(file); cout("runsub: %s\n", absPath); cmdTitle_x(xcout("runsub - %s", absPath)); BlueFish_Lock(); { if(NonBlockingMode) execute_x(xcout("START CMD /C \"%s\"", file)); else execute(file); } BlueFish_Unlock(); cmdTitle("runsub"); cout("runsub: %s done\n", absPath); if(TimeWaitMillis) coSleep(TimeWaitMillis); } int main(int argc, char **argv) { int intoSubDirMode = 1; int skipRootDir = 0; int ignoreObjDebug = 0; char *rootDir = "."; char *target; char *batch; char *execu; autoList_t *dirs; char *dir; uint index; readArgs: if(argIs("/-B")) { NonBlockingMode = 1; goto readArgs; } if(argIs("/-S")) { intoSubDirMode = 0; goto readArgs; } if(argIs("/-R")) { skipRootDir = 1; goto readArgs; } if(argIs("/-O")) { ignoreObjDebug = 1; goto readArgs; } if(argIs("/R")) { rootDir = nextArg(); goto readArgs; } if(argIs("/T")) { TimeWaitMillis = toValue(nextArg()) * 1000; goto readArgs; } if(argIs("/TM")) { TimeWaitMillis = toValue(nextArg()); goto readArgs; } target = nextArg(); batch = addExt(strx(target), "bat"); execu = addExt(strx(target), "exe"); if(intoSubDirMode) { dirs = lssDirs(rootDir); sortJLinesICase(dirs); if(!skipRootDir) insertElement(dirs, 0, (uint)strx(rootDir)); } else dirs = createOneElement((uint)strx(rootDir)); foreach(dirs, dir, index) { if(!existDir(dir)) // これまでの Run() によって削除されることもある。 continue; if(ignoreObjDebug && (mbs_stristr(dir, "\\obj\\") || mbs_stristr(dir, "\\Debug\\"))) continue; addCwd(dir); if(target[0] == '*') { autoList_t *files = lsFiles("."); char *file; uint file_index; eraseParents(files); sortJLinesICase(files); foreach(files, file, file_index) { if( !_stricmp("bat", getExt(file)) || !_stricmp("exe", getExt(file)) ) { if(target[1] == '\0' || mbs_strstrCase(file, target + 1, 1)) { Run(file); } } } releaseDim(files, 1); } else { if(existFile(batch)) { Run(batch); } if(existFile(execu)) { Run(execu); } } unaddCwd(); } releaseDim(dirs, 1); memFree(batch); memFree(execu); }
2.5625
3
2024-11-18T22:36:57.266371+00:00
2021-02-24T18:27:44
6c01cebac26a7ea7cc60babad14666e464961c0b
{ "blob_id": "6c01cebac26a7ea7cc60babad14666e464961c0b", "branch_name": "refs/heads/master", "committer_date": "2021-02-24T18:27:44", "content_id": "780f45aa33f53e5bf46c236686be2d3dee691521", "detected_licenses": [ "MIT" ], "directory_id": "36eb942ec11fe9ab1d7a868badaa27e96f464e53", "extension": "c", "filename": "prime number.c", "fork_events_count": 0, "gha_created_at": "2020-09-05T18:19:13", "gha_event_created_at": "2020-10-02T09:12:00", "gha_language": "Java", "gha_license_id": null, "github_id": 293131138, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 811, "license": "MIT", "license_type": "permissive", "path": "/prime number.c", "provenance": "stackv2-0107.json.gz:84707", "repo_name": "chauhan0707/Coding", "revision_date": "2021-02-24T18:27:44", "revision_id": "760aea49bb468e191ec8f5aa3e3bda1e70018908", "snapshot_id": "82ba0cf78cfbf058654d882c514b5035da24e5f3", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/chauhan0707/Coding/760aea49bb468e191ec8f5aa3e3bda1e70018908/prime number.c", "visit_date": "2023-03-08T00:39:57.013349" }
stackv2
#include<stdio.h> // declaring the recursive function int isPrime(int, int); int main() { printf("\n\n\t\tStudytonight - Best place to learn\n\n\n"); int num, prime; printf("Enter a positive number to check if Prime: "); scanf("%d", &num); prime = isPrime(num, num/2); if(prime == 1) { printf("\n\n%d is a prime number\n\n", num); } else { printf("\n\n%d is a Composite number\n\n", num); } printf("\n\n\t\t\tCoding is Fun !\n\n\n"); return 0; } // function definition int isPrime(int n, int i) { if(i == 1) return 1; // return statement terminates the recursive funtion else { if(n%i == 0) return 0; else isPrime(n, i-1); // recursive call not using return statement } }
3.734375
4
2024-11-18T22:36:57.393240+00:00
2023-08-22T17:23:00
44fd3cee484212d8d4ad586dea8924399b672b2c
{ "blob_id": "44fd3cee484212d8d4ad586dea8924399b672b2c", "branch_name": "refs/heads/master", "committer_date": "2023-08-22T17:23:46", "content_id": "7b0cefadbc7512ec0199b543f6b2cc61fe32b949", "detected_licenses": [ "MIT" ], "directory_id": "3a4f120f3211a1482b8ba826f4922fa741c5586e", "extension": "c", "filename": "PmodGPS.c", "fork_events_count": 327, "gha_created_at": "2015-11-13T18:23:02", "gha_event_created_at": "2023-08-22T17:23:47", "gha_language": "C", "gha_license_id": "MIT", "github_id": 46139497, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 47436, "license": "MIT", "license_type": "permissive", "path": "/ip/Pmods/PmodGPS_v1_1/drivers/PmodGPS_v1_1/src/PmodGPS.c", "provenance": "stackv2-0107.json.gz:84837", "repo_name": "Digilent/vivado-library", "revision_date": "2023-08-22T17:23:00", "revision_id": "cbfde215a27053004cb41d85535c4a1bd1673e14", "snapshot_id": "7135129c7e4fec84d17e1fe037598bd2124085eb", "src_encoding": "WINDOWS-1252", "star_events_count": 512, "url": "https://raw.githubusercontent.com/Digilent/vivado-library/cbfde215a27053004cb41d85535c4a1bd1673e14/ip/Pmods/PmodGPS_v1_1/drivers/PmodGPS_v1_1/src/PmodGPS.c", "visit_date": "2023-09-05T22:04:31.189589" }
stackv2
/******************************************************************************/ /* */ /* PmodGPS.c -- Driver definitions for the PmodGPS */ /* */ /******************************************************************************/ /* Author: Thomas Kappenman */ /* */ /******************************************************************************/ /* File Description: */ /* */ /* This file contains the drivers for the PmodGPS IP from Digilent */ /* */ /******************************************************************************/ /* Revision History: */ /* */ /* 04/17/2016(tom21091): Created */ /* 10/13/2017(atangzwj): Validated for Vivado 2015.4 */ /* 11/04/2017(atangzwj): Validated for Vivado 2016.4 */ /* 01/29/2018(atangzwj): Validated for Vivado 2017.4 */ /* */ /******************************************************************************/ /***************************** Include Files *******************************/ #include <stdio.h> #include <stdlib.h> #include "PmodGPS.h" /************************** Function Definitions ***************************/ XUartNs550_Config GPS_Config = { 0, 0, 0, 9600 // Default Baud rate }; /* ------------------------------------------------------------ */ /* GPS_begin(PmodGPS *InstancePtr, u32 GPIO_Address, u32 UART_Address) ** ** Parameters: ** InstancePtr: A PmodGPS object to start ** GPIO_Address: The Base address of the PmodGPS GPIO ** UART_Address: The Base address of the PmodGPS UART ** Peripheral_Clk: Frequency (Hz) of the PmodGPS IP's clock ** ** Return Value: ** none ** ** Errors: ** none ** ** Description: ** Initialize the PmodGPS. */ void GPS_begin(PmodGPS *InstancePtr, u32 GPIO_Address, u32 UART_Address, u32 Peripheral_Clk) { InstancePtr->periph_clk = Peripheral_Clk; InstancePtr->GPIO_addr = GPIO_Address; GPS_Config.BaseAddress = UART_Address; GPS_Config.InputClockHz = Peripheral_Clk; Xil_Out32(InstancePtr->GPIO_addr + 4, 0x3); // Set 3DF and PPS to inputs GPS_UARTInit(&InstancePtr->GPSUart); GPS_changeBaud(InstancePtr, 115200); // Set baud rate to 115200 GPS_setModes(InstancePtr, 1, 1, 1, 1, 1, 1); } /* ------------------------------------------------------------ */ /* GPS_changeBaud() ** ** Parameters: ** InstancePtr: PmodGPS object to configure ** baud: Desired baud rate to set the PmodGPS to ** ** Return Value: ** 1 if successful, 0 if invalid baud ** ** Errors: ** none ** ** Description: ** Changes the baud rate of the PmodGPS, then the XUartNs550 ** controller */ int GPS_changeBaud(PmodGPS *InstancePtr, int baud) { char *message; u32 i = 0; switch (baud) { case 4800: message = "$PMTK251,4800*14\r\n"; break; case 9600: message = "$PMTK251,9600*17\r\n"; break; case 14400: message = "$PMTK251,14400*29\r\n"; break; case 19200: message = "$PMTK251,19200*22\r\n"; break; case 38400: message = "$PMTK251,38400*27\r\n"; break; case 57600: message = "$PMTK251,57600*2C\r\n"; break; case 115200: message = "$PMTK251,115200*1F\r\n"; break; default: return XST_FAILURE; break; } while (i < strlen(message)) { i += XUartNs550_Send(&InstancePtr->GPSUart, (u8*) message + i, strlen(message) - i); while (XUartNs550_IsSending(&InstancePtr->GPSUart)); } XUartNs550_SetBaud(InstancePtr->GPSUart.BaseAddress, InstancePtr->periph_clk, baud); return XST_SUCCESS; } /* ------------------------------------------------------------ */ /* GPS_setUpdateRate() ** ** Parameters: ** InstancePtr: PmodGPS object to configure ** milli_interval: Desired millisecond interval to receive messages ** ** Return Value: ** 1 ** ** Errors: ** none ** ** Description: ** Sets the frequency that the PmodGPS sends sentences. ** 100ms - 10seconds */ int GPS_setUpdateRate(PmodGPS *InstancePtr, int milli_interval) { char message[20] = {0}; u32 i = 0; u8 checksum; if (milli_interval > 10000 || milli_interval < 100) return XST_FAILURE; sprintf(message, "$PMTK220,%d*", milli_interval); checksum = GPS_getChecksum(message); sprintf(message, "$PMTK220,%d*%X\r\n", milli_interval, checksum); while (i < strlen(message)) { i += XUartNs550_Send(&InstancePtr->GPSUart, (u8*) message + i, strlen(message) - i); while (XUartNs550_IsSending(&InstancePtr->GPSUart)); } return XST_SUCCESS; } /* ------------------------------------------------------------ */ /* GPS_setModes() ** ** Parameters: ** InstancePtr: PmodGPS object to configure ** GLL: GPS pings per GLL message ** RMC: GPS pings per RMC message ** VTG: GPS pings per VTG message ** GGA: GPS pings per GGA message ** GSA: GPS pings per GSA message ** GSV: GPS pings per GSV message ** ** Return Value: ** 1 ** ** Errors: ** none ** ** Description: ** Configures which messages are sent by the GPS: ** 1 = Every ping ** 2 = Every two pings, up to 5 */ int GPS_setModes(PmodGPS *InstancePtr, u8 GGA, u8 GLL, u8 GSA, u8 GSV, u8 RMC, u8 VTG) { char message[52] = {0}; u32 i = 0; u8 checksum; sprintf(message, "$PMTK314,%d,%d,%d,%d,%d,%d,0,0,0,0,0,0,0,0,0,0,0,0,0*", GLL, RMC, VTG, GGA, GSA, GSV); checksum = GPS_getChecksum(message); sprintf(message, "$PMTK314,%d,%d,%d,%d,%d,%d,0,0,0,0,0,0,0,0,0,0,0,0,0*%X\r\n", GLL, RMC, VTG, GGA, GSA, GSV, checksum); if (*message) { while (i < strlen(message)) { i += XUartNs550_Send(&InstancePtr->GPSUart, (u8*) message + i, strlen(message) - i); while (XUartNs550_IsSending(&InstancePtr->GPSUart)); } } if (VTG) InstancePtr->last_Sentence = 6; else if (RMC) InstancePtr->last_Sentence = 5; else if (GSA) InstancePtr->last_Sentence = 3; else if (GLL) InstancePtr->last_Sentence = 2; else if (GGA) InstancePtr->last_Sentence = 1; return 1; } /* ------------------------------------------------------------ */ /* GPS_getChecksum() ** ** Parameters: ** message: The NMEA sentence to calculate the checksum from ** ** Return Value: ** checksum of the message ** ** Errors: ** none ** ** Description: ** Calculates the checksum for the input sentence */ u8 GPS_getChecksum(char *message) { char *temp = message + 1; // Skip the $ u8 checksum = 0; while (*temp != '*') { checksum ^= *temp; temp++; } return checksum; } /* ------------------------------------------------------------ */ /* GPS_UARTInit ** ** Parameters: ** UartInstancePtr: The XUartNs550 object to initialize ** ** Return Value: ** 0 if success, 1 if failure ** ** Errors: ** none ** ** Description: ** Initializes the PmodGPS UART. */ int GPS_UARTInit(XUartNs550 *UartInstancePtr) { int Status; u16 Options; Status = XUartNs550_CfgInitialize(UartInstancePtr, &GPS_Config, GPS_Config.BaseAddress); if (Status != XST_SUCCESS) { return XST_FAILURE; } Options = XUN_OPTION_FIFOS_ENABLE; XUartNs550_SetOptions(UartInstancePtr, Options); return XST_SUCCESS; } /* ------------------------------------------------------------ */ /* GPS_readPPSpin() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** PPS input - Ping per second ** ** Errors: ** none ** ** Description: ** Reads the 3DF pin */ int GPS_readPPSpin(PmodGPS *InstancePtr) { return Xil_In32(InstancePtr->GPIO_addr) & 0x2; } /* ------------------------------------------------------------ */ /* GPS_read3DFpin() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** 3DF input ** ** Errors: ** none ** ** Description: ** Reads the 3DF pin */ int GPS_read3DFpin(PmodGPS *InstancePtr) { return Xil_In32(InstancePtr->GPIO_addr) & 0x1; } /* ------------------------------------------------------------ */ /* GPS_getData() ** ** Parameters: ** InstancePtr: PmodGPS object to get data from ** ** Return Value: ** 1 if data was received successfully, 0 if not ** ** Errors: ** none ** ** Description: ** For use in POLLED MODE ONLY ** Does a read of data. finishes when a value of decimal 10 (ASCII <LF>) ** is detected. Checks to see if it is the last sentence and returns if ** yes. */ GPS_bool GPS_getData(PmodGPS *InstancePtr) { int count = 0; GPS_NMEA mode = GPS_INVALID; unsigned int ReceivedCount = 0; u16 options = XUartNs550_GetOptions(&InstancePtr->GPSUart); if (options & XUN_OPTION_DATA_INTR) return 0; // If in interrupt mode, return 0 if (ReceivedCount += XUartNs550_Recv(&InstancePtr->GPSUart, (u8*) InstancePtr->recv + ReceivedCount, GPS_MAX_SIZE)) { // If there is a sentence while (1) { while ((InstancePtr->recv[ReceivedCount - 1] != '\n')) { ReceivedCount += XUartNs550_Recv(&InstancePtr->GPSUart, (u8*) InstancePtr->recv + ReceivedCount, GPS_MAX_SIZE); } InstancePtr->recv[ReceivedCount] = '\0'; mode = GPS_chooseMode(InstancePtr->recv + count); if (mode == InstancePtr->last_Sentence) { break; } count = ReceivedCount; ReceivedCount += XUartNs550_Recv(&InstancePtr->GPSUart, (u8*) InstancePtr->recv + ReceivedCount, GPS_MAX_SIZE); } } else { return 0; } InstancePtr->ping = TRUE; return 1; } /* ------------------------------------------------------------ */ /* GPS_getSentence() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** output: A pointer to where the string will be stored ** ** Return Value: ** True if sentence received, false if not ** ** Errors: ** none ** ** Description: ** Attempts to read a single sentence through UART */ GPS_bool GPS_getSentence(PmodGPS *InstancePtr, char *output) { int ReceivedCount = 0; if (ReceivedCount += XUartNs550_Recv(&InstancePtr->GPSUart, (u8*) output + ReceivedCount, 1)) { // If there is a sentence while (output[ReceivedCount - 1] != '\n') { ReceivedCount += XUartNs550_Recv(&InstancePtr->GPSUart, (u8*) output + ReceivedCount, 1); } return 1; } else return 0; } /* ------------------------------------------------------------ */ /* GPS_formatSentence() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** bool ** ** Errors: ** none ** ** Description: ** Parses the GPS NMEA sentence stored in InstancePtr->recv */ GPS_bool GPS_formatSentence(PmodGPS *InstancePtr) { int i = 0; GPS_NMEA mode = GPS_INVALID; // Reset ping now that we are about to parse the last sentence InstancePtr->ping = 0; while (1) { mode = GPS_chooseMode(InstancePtr->recv + i); switch (mode) { case (GPS_GGA): i += GPS_formatGGA(InstancePtr, InstancePtr->recv + i); if (InstancePtr->last_Sentence == GPS_GGA) return 1; break; case (GPS_GLL): i += GPS_formatGLL(InstancePtr, InstancePtr->recv + i); if (InstancePtr->last_Sentence == GPS_GLL) return 1; break; case (GPS_GSA): i += GPS_formatGSA(InstancePtr, InstancePtr->recv + i); if (InstancePtr->last_Sentence == GPS_GSA) return 1; break; case (GPS_GSV): i += GPS_formatGSV(InstancePtr, InstancePtr->recv + i); if (InstancePtr->last_Sentence == GPS_GSV) return 1; break; case (GPS_RMC): i += GPS_formatRMC(InstancePtr, InstancePtr->recv + i); if (InstancePtr->last_Sentence == GPS_RMC) return 1; break; case (GPS_VTG): i += GPS_formatVTG(InstancePtr, InstancePtr->recv + i); if (InstancePtr->last_Sentence == GPS_VTG) return 1; break; case (GPS_INVALID): return 0; break; } } return 1; } /* ------------------------------------------------------------ */ /* GPS_isFixed() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** bool PFI ** ** Errors: ** none ** ** Description: ** Returns a true if PFI is 1, else 0 */ GPS_bool GPS_isFixed(PmodGPS *InstancePtr) { return (GPS_bool) ((int) (InstancePtr->GGAdata.PFI - '0') == 1 || (int) (InstancePtr->GGAdata.PFI - '0') == 2); } /* ------------------------------------------------------------ */ /* getLatitude(), getLongitude() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** A string containing the data requested ** ** Errors: ** none ** ** Description: ** Get functions for several data members in string form */ char *GPS_getLatitude(PmodGPS *InstancePtr) { return InstancePtr->GGAdata.LAT; } char *GPS_getLongitude(PmodGPS *InstancePtr) { return InstancePtr->GGAdata.LONG; } /* ------------------------------------------------------------ */ /* getAltitudeString() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** A string containing the altitude with appended units ** ** Errors: ** none ** ** Description: ** Gets altitude and returns its value with units in string form */ char *GPS_getAltitudeString(PmodGPS *InstancePtr) { static char temp[12]; sprintf(temp, "%s %c", InstancePtr->GGAdata.ALT, InstancePtr->GGAdata.AUNIT); return temp; } /* ------------------------------------------------------------ */ /* getDate() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** A string containing the date in correct format ** ** Errors: ** none ** ** Description: ** Formats the date and returns it as a char string */ char *GPS_getDate(PmodGPS *InstancePtr) { static char date[8]; date[0] = InstancePtr->RMCdata.DATE[2]; date[1] = InstancePtr->RMCdata.DATE[3]; date[2] = '/'; date[3] = InstancePtr->RMCdata.DATE[0]; date[4] = InstancePtr->RMCdata.DATE[1]; date[5] = '/'; date[6] = InstancePtr->RMCdata.DATE[4]; date[7] = InstancePtr->RMCdata.DATE[5]; strcat(date, "\0"); return date; } /* ------------------------------------------------------------ */ /* getTime(), getNumSats(), getPDOP(), getAltitude(), getSpeedKnots(), ** getSpeedKM(), getHeading() ** ** Parameters: ** none ** ** Return Value: ** The data in the structs in either integer or double form ** ** Errors: ** none ** ** Description: ** Get functions for several items in the PmodGPS structs. These values ** are converted to integers or doubles before being returned. */ double GPS_getTime(PmodGPS *InstancePtr) { return atof(InstancePtr->GGAdata.UTC); } int GPS_getNumSats(PmodGPS *InstancePtr) { return atoi(InstancePtr->GGAdata.NUMSAT); } double GPS_getPDOP(PmodGPS *InstancePtr) { return atof(InstancePtr->GSAdata.PDOP); } double GPS_getAltitude(PmodGPS *InstancePtr) { return atof(InstancePtr->GGAdata.ALT); } double GPS_getSpeedKnots(PmodGPS *InstancePtr) { return atof(InstancePtr->VTGdata.SPD_N); } double GPS_getSpeedKM(PmodGPS *InstancePtr) { return atof(InstancePtr->VTGdata.SPD_KM); } double GPS_getHeading(PmodGPS *InstancePtr) { return atof(InstancePtr->VTGdata.COURSE_T); } /* ------------------------------------------------------------ */ /* chooseMode() ** ** Parameters: ** char recv[GPS_MAX_SIZE] ** ** Return Value: ** NMEA mode: The format of the sentence, for use in deciding ** which struct to format into ** ** Errors: ** none ** ** Description: ** Reads the third, fourth, and fifth character in the sentence, and ** outputs an NMEA mode. */ GPS_NMEA GPS_chooseMode(char recv[]) { GPS_NMEA mode = GPS_INVALID; while (recv[0] != '$' && recv[0] != '\0') recv--; //If not at beginning of sentence, go back if (((recv[0]) != '$') || ((recv[1]) != 'G') || ((recv[2]) != 'P')) return GPS_INVALID; if (((recv[3]) == 'G') && ((recv[4]) == 'G') && (recv[5] == 'A')) { mode = GPS_GGA; } else if (((recv[3]) == 'G') && ((recv[4]) == 'L') && (recv[5] == 'L')) { mode = GPS_GLL; } else if (((recv[3]) == 'G') && ((recv[4]) == 'S') && (recv[5] == 'A')) { mode = GPS_GSA; } else if (((recv[3]) == 'G') && ((recv[4]) == 'S') && (recv[5] == 'V')) { mode = GPS_GSV; } else if (((recv[3]) == 'R') && ((recv[4]) == 'M') && (recv[5] == 'C')) { mode = GPS_RMC; } else if (((recv[3]) == 'V') && ((recv[4]) == 'T') && (recv[5] == 'G')) { mode = GPS_VTG; } return mode; } /* ------------------------------------------------------------ */ /* getSatelliteInfo() ** ** Parameters: ** InstancePtr: PmodGPS object to read from ** ** Return Value: ** The array of SATELLITE structs in GSVdata ** ** Errors: ** none ** ** Description: ** A get function for the SATELLITE structs containing satellite info. */ GPS_SATELLITE *GPS_getSatelliteInfo(PmodGPS *InstancePtr) { if (InstancePtr->GSVdata.SAT) return InstancePtr->GSVdata.SAT; else return 0; } /* ------------------------------------------------------------ */ /* formatGGA() ** ** Parameters: ** InstancePtr: PmodGPS object to store data into ** data_array: an array to the data to be formatted ** ** Return Value: ** The offset from the beginning of data_array ** ** Errors: ** none ** ** Description: ** Formats a mode's data into elements in a struct. ** NOTE: ',' will separate all values */ int GPS_formatGGA(PmodGPS *InstancePtr, char *data_array) { enum cases { UTC, LAT, NS, LONG, EW, PFI, NUMSAT, HDOP, ALT, AUNIT, GSEP, GUNIT, AODC }; enum cases datamember = UTC; char *start_ptr; char *end_ptr = data_array + 7; // Set end_ptr after message ID ("$GPGGA,") GPS_bool flag = 1; char COORDbuf[14] = {0}; char checksum[3] = {0}; while (flag) { start_ptr = end_ptr; while (*end_ptr != ',' && (*(end_ptr + 1) != 10) && *end_ptr != '*' && *end_ptr != '$') end_ptr++; // Increment ptr until a comma is found if (*end_ptr == '$') { return end_ptr - data_array; } if (*end_ptr == 10 || *(end_ptr + 1) == 10 || (*end_ptr == '*' && *(end_ptr - 1) == ',')) { // End reached flag = 0; break; } switch (datamember) { case UTC: memcpy(InstancePtr->GGAdata.UTC, start_ptr, (end_ptr - start_ptr)); InstancePtr->GGAdata.UTC[end_ptr - start_ptr] = '\0'; // End null char datamember = LAT; break; case LAT: memcpy(COORDbuf, start_ptr, (end_ptr - start_ptr)); if (*COORDbuf) { GPS_formatCOORDS(COORDbuf); strcpy(InstancePtr->GGAdata.LAT, COORDbuf); memset(COORDbuf, 0, sizeof(COORDbuf)); } datamember = NS; break; case NS: if (*start_ptr != ',') { InstancePtr->GGAdata.NS = *start_ptr; strncat(InstancePtr->GGAdata.LAT, start_ptr, 1); } datamember = LONG; break; case LONG: memcpy(COORDbuf, start_ptr, (end_ptr - start_ptr)); if (*COORDbuf) { GPS_formatCOORDS(COORDbuf); strcpy(InstancePtr->GGAdata.LONG, COORDbuf);\ memset(COORDbuf, 0, sizeof(COORDbuf)); } datamember = EW; break; case EW: if (*start_ptr != ',') { InstancePtr->GGAdata.EW = *start_ptr; strncat(InstancePtr->GGAdata.LONG, start_ptr, 1); } datamember = PFI; break; case PFI: if (*start_ptr != ',') InstancePtr->GGAdata.PFI = *start_ptr; datamember = NUMSAT; break; case NUMSAT: memcpy(InstancePtr->GGAdata.NUMSAT, start_ptr, (end_ptr - start_ptr)); InstancePtr->GGAdata.NUMSAT[end_ptr - start_ptr] = '\0'; datamember = HDOP; break; case HDOP: memcpy(InstancePtr->GGAdata.HDOP, start_ptr, (end_ptr - start_ptr)); InstancePtr->GGAdata.HDOP[end_ptr - start_ptr] = '\0'; datamember = ALT; break; case ALT: memcpy(InstancePtr->GGAdata.ALT, start_ptr, (end_ptr - start_ptr)); InstancePtr->GGAdata.ALT[end_ptr - start_ptr] = '\0'; datamember = AUNIT; break; case AUNIT: if (*start_ptr != ',') InstancePtr->GGAdata.AUNIT = *start_ptr; datamember = GSEP; break; case GSEP: memcpy(InstancePtr->GGAdata.GSEP, start_ptr, (end_ptr - start_ptr)); InstancePtr->GGAdata.GSEP[end_ptr - start_ptr] = '\0'; datamember = GUNIT; break; case GUNIT: if (*start_ptr != ',') InstancePtr->GGAdata.GUNIT = *start_ptr; datamember = AODC; break; case AODC: memcpy(InstancePtr->GGAdata.AODC, start_ptr, (end_ptr - start_ptr)); InstancePtr->GGAdata.AODC[end_ptr - start_ptr] = '\0'; flag = 0; break; } end_ptr++; // Increment past the last comma } // Get checksum while (*(end_ptr) != 10) end_ptr++; checksum[0] = *(end_ptr - 3); checksum[1] = *(end_ptr - 2); checksum[2] = 0; memcpy(InstancePtr->GGAdata.CHECKSUM, checksum, 3); return end_ptr - data_array + 1; } /* ------------------------------------------------------------ */ /* GPS_formatGLL() ** ** Parameters: ** InstancePtr: PmodGPS object to store data into ** data_array: an array to the data to be formatted ** ** Return Value: ** The offset from the beginning of data_array ** ** Errors: ** none ** ** Description: ** Formats a mode's data into elements in a struct. ** NOTE: ',' will separate all values */ int GPS_formatGLL(PmodGPS *InstancePtr, char *data_array) { enum cases { LAT, NS, LONG, EW, TIME, ACTIVE, MODE }; enum cases datamember = LAT; char *start_ptr; char *end_ptr = data_array + 7; // Set end_ptr after message ID ("$GPGGA,") GPS_bool flag = 1; char COORDbuf[14] = {0}; char checksum[3] = {0}; while (flag) { start_ptr = end_ptr; while (*end_ptr != ',' && (*(end_ptr + 1) != 10) && *end_ptr != '*' && *end_ptr != '$') end_ptr++; // Increment ptr until a comma is found if (*end_ptr == '$') { return end_ptr - data_array; } if (*end_ptr == 10 || *(end_ptr + 1) == 10 || (*end_ptr == '*' && *(end_ptr - 1) == ',')) { // End reached flag = 0; break; } switch (datamember) { case LAT: memcpy(COORDbuf, start_ptr, (end_ptr - start_ptr)); if (*COORDbuf) { GPS_formatCOORDS(COORDbuf); strcpy(InstancePtr->GLLdata.LAT, COORDbuf); memset(COORDbuf, 0, sizeof(COORDbuf)); } datamember = NS; break; case NS: if (*start_ptr != ',') { InstancePtr->GLLdata.NS = *start_ptr; strncat(InstancePtr->GLLdata.LAT, start_ptr, 1); } datamember = LONG; break; case LONG: memcpy(COORDbuf, start_ptr, (end_ptr - start_ptr)); if (*COORDbuf) { GPS_formatCOORDS(COORDbuf); strcpy(InstancePtr->GLLdata.LONG, COORDbuf);\ memset(COORDbuf, 0, sizeof(COORDbuf)); } datamember = EW; break; case EW: if (*start_ptr != ',') { InstancePtr->GLLdata.EW = *start_ptr; strncat(InstancePtr->GLLdata.LONG, start_ptr, 1); } datamember = TIME; break; case TIME: memcpy(InstancePtr->GLLdata.UTC, start_ptr, (end_ptr - start_ptr)); InstancePtr->GLLdata.UTC[end_ptr - start_ptr] = '\0'; // End null char datamember = ACTIVE; break; case ACTIVE: if (*start_ptr != ',') InstancePtr->GLLdata.ACTIVE = *start_ptr; datamember = MODE; break; case MODE: if (*start_ptr != ',') InstancePtr->GLLdata.MODE = *start_ptr; flag = 0; break; } end_ptr++; // Increment past the last comma } // Get checksum while (*(end_ptr) != 10) end_ptr++; checksum[0] = *(end_ptr - 3); checksum[1] = *(end_ptr - 2); checksum[2] = 0; memcpy(InstancePtr->GLLdata.CHECKSUM, checksum, 3); return end_ptr - data_array + 1; } /* ------------------------------------------------------------ */ /* GPS_formatGSA() ** ** Parameters: ** InstancePtr: PmodGPS object to store data into ** data_array: an array to the data to be formatted ** ** Return Value: ** The offset from the beginning of data_array ** ** Errors: ** none ** ** Description: ** Formats a mode's data into elements in a struct. */ int GPS_formatGSA(PmodGPS *InstancePtr, char *data_array) { enum cases { MODE1, MODE2, SAT1, SAT2, SAT3, SAT4, SAT5, SAT6, SAT7, SAT8, SAT9, SAT10, SAT11, SAT12, PDOP, HDOP, VDOP }; enum cases datamember = MODE1; char *start_ptr; char *end_ptr = data_array + 7; // Set end_ptr after message ID ("$GPGGA,") GPS_bool flag = 1; char checksum[3] = {0}; while (flag) { start_ptr = end_ptr; while (*end_ptr != ',' && (*(end_ptr + 1) != 10) && *end_ptr != '*' && *end_ptr != '$') end_ptr++; // Increment ptr until a comma is found if (*end_ptr == '$') { return end_ptr - data_array; } if (*end_ptr == 10 || *(end_ptr + 1) == 10 || (*end_ptr == '*' && *(end_ptr - 1) == ',')) { // End reached flag = 0; break; } switch (datamember) { case MODE1: if (*start_ptr != ',') InstancePtr->GSAdata.MODE1 = *start_ptr; datamember = MODE2; break; case MODE2: if (*start_ptr != ',') InstancePtr->GSAdata.MODE2 = *start_ptr; datamember = SAT1; break; case SAT1: memcpy(InstancePtr->GSAdata.SAT1, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT1[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT2; break; case SAT2: memcpy(InstancePtr->GSAdata.SAT2, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT2[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT3; break; case SAT3: memcpy(InstancePtr->GSAdata.SAT3, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT3[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT4; break; case SAT4: memcpy(InstancePtr->GSAdata.SAT4, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT4[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT5; break; case SAT5: memcpy(InstancePtr->GSAdata.SAT5, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT5[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT6; break; case SAT6: memcpy(InstancePtr->GSAdata.SAT6, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT6[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT7; break; case SAT7: memcpy(InstancePtr->GSAdata.SAT7, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT7[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT8; break; case SAT8: memcpy(InstancePtr->GSAdata.SAT8, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT8[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT9; break; case SAT9: memcpy(InstancePtr->GSAdata.SAT9, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT9[end_ptr - start_ptr] = '\0'; // End null char datamember = SAT10; break; case SAT10: memcpy(InstancePtr->GSAdata.SAT10, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT10[end_ptr - start_ptr] = '\0'; datamember = SAT11; break; case SAT11: memcpy(InstancePtr->GSAdata.SAT11, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT11[end_ptr - start_ptr] = '\0'; datamember = SAT12; break; case SAT12: memcpy(InstancePtr->GSAdata.SAT12, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.SAT12[end_ptr - start_ptr] = '\0'; datamember = PDOP; break; case PDOP: memcpy(InstancePtr->GSAdata.PDOP, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.PDOP[end_ptr - start_ptr] = '\0'; datamember = HDOP; break; case HDOP: memcpy(InstancePtr->GSAdata.HDOP, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.HDOP[end_ptr - start_ptr] = '\0'; datamember = VDOP; break; case VDOP: memcpy(InstancePtr->GSAdata.VDOP, start_ptr, (end_ptr - start_ptr)); InstancePtr->GSAdata.VDOP[end_ptr - start_ptr] = '\0'; flag = 0; break; } end_ptr++; //Increment past the last comma } // end of while // Get checksum while (*(end_ptr) != 10) end_ptr++; checksum[0] = *(end_ptr - 3); checksum[1] = *(end_ptr - 2); checksum[2] = 0; memcpy(InstancePtr->GSAdata.CHECKSUM, checksum, 3); return end_ptr - data_array + 1; } /* ------------------------------------------------------------ */ /* GPS_formatGSV() ** ** Parameters: ** InstancePtr: PmodGPS object to store data into ** data_array: an array to the data to be formatted ** ** Return Value: ** The offset from the beginning of data_array ** ** Errors: ** none ** ** Description: ** Formats GSV messages into their corresponding structs. */ int GPS_formatGSV(PmodGPS *InstancePtr, char *data_array) { enum cases { NUMM, MESNUM, SATVIEW, SATID1, ELV1, AZM1, SNR1, SATID2, ELV2, AZM2, SNR2, SATID3, ELV3, AZM3, SNR3, SATID4, ELV4, AZM4, SNR4 }; enum cases datamember = NUMM; char *start_ptr; char *end_ptr = data_array + 7; // Set end_ptr after message ID ("$GPGGA,") GPS_bool flag = 1; char checksum[3] = {0}; int mesnum = 0; char buffer[4]; while (flag) { start_ptr = end_ptr; while (*end_ptr != ',' && (*(end_ptr + 1) != 10) && *end_ptr != '*' && *end_ptr != '$') end_ptr++; // Increment ptr until a comma is found if (*end_ptr == '$') { return end_ptr - data_array; } if (*end_ptr == 10 || *(end_ptr + 1) == 10 || (*end_ptr == '*' && *(end_ptr - 1) == ',')) { // End reached flag = 0; break; } switch (datamember) { case NUMM: if (*start_ptr != ',') InstancePtr->GSVdata.NUMM = (int) (*start_ptr - '0'); datamember = MESNUM; break; case MESNUM: if (*start_ptr != ',') { InstancePtr->GSVdata.MESNUM = (int) (*start_ptr - '0'); mesnum = InstancePtr->GSVdata.MESNUM; } datamember = SATVIEW; break; case SATVIEW: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SATVIEW = atoi(buffer); datamember = SATID1; break; case SATID1: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4].ID = atoi(buffer); datamember = ELV1; break; case ELV1: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4].ELV = atoi(buffer); datamember = AZM1; break; case AZM1: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4].AZM = atoi(buffer); datamember = SNR1; break; case SNR1: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4].SNR = atoi(buffer); datamember = SATID2; break; case SATID2: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 1].ID = atoi(buffer); datamember = ELV2; break; case ELV2: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 1].ELV = atoi(buffer); datamember = AZM2; break; case AZM2: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 1].AZM = atoi(buffer); datamember = SNR2; break; case SNR2: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 1].SNR = atoi(buffer); datamember = SATID3; break; case SATID3: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 2].ID = atoi(buffer); datamember = ELV3; break; case ELV3: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 2].ELV = atoi(buffer); datamember = AZM3; break; case AZM3: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 2].AZM = atoi(buffer); datamember = SNR3; break; case SNR3: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 2].SNR = atoi(buffer); datamember = SATID4; break; case SATID4: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 3].ID = atoi(buffer); datamember = ELV4; break; case ELV4: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 3].ELV = atoi(buffer); datamember = AZM4; break; case AZM4: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 3].AZM = atoi(buffer); datamember = SNR4; break; case SNR4: memcpy(buffer, start_ptr, (end_ptr - start_ptr)); buffer[end_ptr - start_ptr] = '\0'; // End null char InstancePtr->GSVdata.SAT[(mesnum - 1) * 4 + 3].SNR = atoi(buffer); flag = 0; break; } end_ptr++; } // end of while //Get checksum while (*(end_ptr) != 10) end_ptr++; checksum[0] = *(end_ptr - 3); checksum[1] = *(end_ptr - 2); checksum[2] = 0; memcpy(InstancePtr->GSVdata.CHECKSUM, checksum, 3); return end_ptr - data_array + 1; } /* ------------------------------------------------------------ */ /* GPS_formatRMC() ** ** Parameters: ** InstancePtr: PmodGPS object to store data into ** data_array: an array to the data to be formatted ** ** Return Value: ** The offset from the beginning of data_array ** ** Errors: ** none ** ** Description: ** Formats a mode's data into elements in a struct. */ int GPS_formatRMC(PmodGPS *InstancePtr, char *data_array) { enum cases { UTC, STAT, LAT, NS, LONG, EW, SOG, COG, DATE, MVAR, MVARDIR, MODE }; enum cases datamember = UTC; char *start_ptr; char *end_ptr = data_array + 7; // Set end_ptr after message ID ("$GPGGA,") GPS_bool flag = 1; char checksum[3] = { 0 }; while (flag) { start_ptr = end_ptr; while (*end_ptr != ',' && (*(end_ptr + 1) != 10) && *end_ptr != '*' && *end_ptr != '$') end_ptr++; // Increment ptr until a comma is found if (*end_ptr == '$') { return end_ptr - data_array; } if (*end_ptr == 10 || *(end_ptr + 1) == 10 || (*end_ptr == '*' && *(end_ptr - 1) == ',')) { // End reached flag = 0; break; } switch (datamember) { case UTC: memcpy(InstancePtr->RMCdata.UTC, start_ptr, (end_ptr - start_ptr)); InstancePtr->RMCdata.UTC[end_ptr - start_ptr] = '\0'; // End null char datamember = STAT; break; case STAT: if (*start_ptr != ',') InstancePtr->RMCdata.STAT = *start_ptr; datamember = LAT; break; case LAT: memcpy(InstancePtr->RMCdata.LAT, start_ptr, (end_ptr - start_ptr)); InstancePtr->RMCdata.LAT[end_ptr - start_ptr] = '\0'; // End null char datamember = NS; break; case NS: if (*start_ptr != ',') InstancePtr->RMCdata.NS = *start_ptr; datamember = LONG; break; case LONG: memcpy(InstancePtr->RMCdata.LONG, start_ptr, (end_ptr - start_ptr)); InstancePtr->RMCdata.LONG[end_ptr - start_ptr] = '\0'; // End null char datamember = EW; break; case EW: if (*start_ptr != ',') InstancePtr->RMCdata.EW = *start_ptr; datamember = SOG; break; case SOG: memcpy(InstancePtr->RMCdata.SOG, start_ptr, (end_ptr - start_ptr)); InstancePtr->RMCdata.SOG[end_ptr - start_ptr] = '\0'; // End null char datamember = COG; break; case COG: memcpy(InstancePtr->RMCdata.COG, start_ptr, (end_ptr - start_ptr)); InstancePtr->RMCdata.COG[end_ptr - start_ptr] = '\0'; // End null char datamember = DATE; break; case DATE: memcpy(InstancePtr->RMCdata.DATE, start_ptr, (end_ptr - start_ptr)); InstancePtr->RMCdata.DATE[end_ptr - start_ptr] = '\0'; // End null char datamember = MVAR; break; case MVAR: memcpy(InstancePtr->RMCdata.MVAR, start_ptr, (end_ptr - start_ptr)); InstancePtr->RMCdata.MVAR[end_ptr - start_ptr] = '\0'; // End null char datamember = MVARDIR; break; case MVARDIR: if (*start_ptr != ',') InstancePtr->RMCdata.MVARDIR = *start_ptr; datamember = MODE; break; case MODE: if (*start_ptr != ',') InstancePtr->RMCdata.MODE = *start_ptr; flag = 0; break; } end_ptr++; } // end of while // Get checksum while (*(end_ptr) != 10) end_ptr++; checksum[0] = *(end_ptr - 3); checksum[1] = *(end_ptr - 2); checksum[2] = 0; memcpy(InstancePtr->RMCdata.CHECKSUM, checksum, 3); return end_ptr - data_array + 1; } /* ------------------------------------------------------------ */ /* GPS_formatVTG() ** ** Parameters: ** InstancePtr: PmodGPS object to store data into ** data_array: an array to the data to be formatted ** ** Return Value: ** The offset from the beginning of data_array ** ** Errors: ** none ** ** Description: ** Formats a mode's data into elements in a struct. */ int GPS_formatVTG(PmodGPS *InstancePtr, char *data_array) { enum cases { COURSE_T, REF_T, COURSE_M, REF_M, SPD_N, UNIT_N, SPD_KM, UNIT_KM, MODE, CHECKSUM }; enum cases datamember = COURSE_T; char *start_ptr; char *end_ptr = data_array + 7; // Set end_ptr after message ID ("$GPGGA,") GPS_bool flag = 1; char checksum[3] = { 0 }; while (flag) { start_ptr = end_ptr; while (*end_ptr != ',' && (*(end_ptr + 1) != 10) && *end_ptr != '*' && *end_ptr != '$') end_ptr++; // Increment ptr until a comma is found if (*end_ptr == '$') { return end_ptr - data_array; } if (*end_ptr == 10 || *(end_ptr + 1) == 10 || (*end_ptr == '*' && *(end_ptr - 1) == ',')) { // End reached flag = 0; break; } // Choose where to put this data switch (datamember) { case COURSE_T: memcpy(InstancePtr->VTGdata.COURSE_T, start_ptr, (end_ptr - start_ptr)); InstancePtr->VTGdata.COURSE_T[end_ptr - start_ptr] = '\0'; // Null char datamember = REF_T; break; case REF_T: if (*start_ptr != ',') InstancePtr->VTGdata.REF_T = *start_ptr; datamember = COURSE_M; break; case COURSE_M: memcpy(InstancePtr->VTGdata.COURSE_M, start_ptr, (end_ptr - start_ptr)); InstancePtr->VTGdata.COURSE_M[end_ptr - start_ptr] = '\0'; datamember = REF_M; break; case REF_M: if (*start_ptr != ',') InstancePtr->VTGdata.REF_M = *start_ptr; datamember = SPD_N; break; case SPD_N: memcpy(InstancePtr->VTGdata.SPD_N, start_ptr, (end_ptr - start_ptr)); InstancePtr->VTGdata.SPD_N[end_ptr - start_ptr] = '\0'; datamember = UNIT_N; break; case UNIT_N: if (*start_ptr != ',') InstancePtr->VTGdata.UNIT_N = *start_ptr; datamember = SPD_KM; break; case SPD_KM: memcpy(InstancePtr->VTGdata.SPD_KM, start_ptr, (end_ptr - start_ptr)); InstancePtr->VTGdata.SPD_KM[end_ptr - start_ptr] = '\0'; datamember = UNIT_KM; break; case UNIT_KM: if (*start_ptr != ',') InstancePtr->VTGdata.UNIT_KM = *start_ptr; datamember = MODE; break; case MODE: if (*start_ptr != ',') InstancePtr->VTGdata.MODE = *start_ptr; datamember = CHECKSUM; flag = 0; break; case CHECKSUM: while (*(end_ptr) != 10) end_ptr++; checksum[0] = *(end_ptr - 3); checksum[1] = *(end_ptr - 2); checksum[2] = 0; memcpy(InstancePtr->VTGdata.CHECKSUM, checksum, 3); return end_ptr - data_array + 1; break; } end_ptr++; } // end of while return 0; } /* ------------------------------------------------------------ */ /* char *GPS_formatCOORDS() ** ** Parameters: ** coords: the un-formatted decimal representation of latitude or ** longitude ** ** Return Value: ** Correctly formatted coordinates in degrees, minutes, and seconds ** ** Errors: ** none ** ** Description: ** Formats a set of coordinates of the form XXXX.XXXX or XXXXX.XXXX ** into XX[X]°XX'XX.XX" */ void GPS_formatCOORDS(char *coords) { if (!*coords) return; char *coordsstart = coords; int degmin = atol(strtok(coords, ".")); int deg = degmin / 100; degmin %= 100; float sec = atol(strtok(NULL, " \0")); sec = sec * 6 / 1000; sprintf(coordsstart, "%d°%d'%.1f\"", deg, degmin, sec); return; } /* ------------------------------------------------------------ */ /* GPS_intHandler() ** ** Parameters: ** InstancePtr: PmodGPS object to get data from ** Event: Describes the UART interrupt type ** EventData: Describes how many bytes were sent/received ** ** Return Value: ** none ** ** Errors: ** none ** ** Description: ** XUartNs550 Interrupt that receives sentences until the last one ** is received */ void GPS_intHandler(PmodGPS *InstancePtr, u32 Event, unsigned int EventData) { if (Event == XUN_EVENT_RECV_DATA) { // Start receiving new sentence XUartNs550_Recv(&InstancePtr->GPSUart, (u8*) InstancePtr->recv, 600); } if (Event == XUN_EVENT_RECV_TIMEOUT) { // Triggers every 8 bytes if (InstancePtr->recv[EventData - 1] == '\n') { // If end of sentence if (GPS_chooseMode(&InstancePtr->recv[EventData - 1]) == InstancePtr->last_Sentence) { // Check if it is last sentence InstancePtr->recv[EventData] = '\0'; // Terminate string XUartNs550_Recv(&InstancePtr->GPSUart, (u8*) InstancePtr->recv, 600); // Request a new sentence (resets it) // Set ping variable for use outside of the interrupt InstancePtr->ping = TRUE; } } } if (Event == XUN_EVENT_RECV_ERROR) { xil_printf("%d error\r\n", EventData); } }
2.125
2
2024-11-18T22:36:57.467416+00:00
2017-05-26T07:02:23
0748d78dca5306fbb715fc4919400e4110374775
{ "blob_id": "0748d78dca5306fbb715fc4919400e4110374775", "branch_name": "refs/heads/master", "committer_date": "2017-05-26T07:02:23", "content_id": "06b9be7e66fccb6a82248d443761e7b6c7f6d342", "detected_licenses": [ "MIT-Modern-Variant" ], "directory_id": "765ae811f637a81bc040b34ceb14d9ac72763479", "extension": "c", "filename": "halt_child.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": 596, "license": "MIT-Modern-Variant", "license_type": "permissive", "path": "/test/halt_child.c", "provenance": "stackv2-0107.json.gz:84966", "repo_name": "DLZSY/nachos", "revision_date": "2017-05-26T07:02:23", "revision_id": "3c99ccefe265c33badfcd2d5867c1e64b7d281ff", "snapshot_id": "5b0dd815eea0b48cab76a5aef069700e760d9624", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/DLZSY/nachos/3c99ccefe265c33badfcd2d5867c1e64b7d281ff/test/halt_child.c", "visit_date": "2021-06-17T06:20:31.727447" }
stackv2
/* halt_child.c * Simple program to test that child processes can't halt the machine. * * NOTE: for some reason, user programs with global data structures * sometimes haven't worked in the Nachos environment. So be careful * out there! One option is to allocate data structures as * automatics within a procedure, but if you do this, you have to * be careful to allocate a big enough stack to hold the automatics! */ #include "syscall.h" int main() { char *prog = "halt.coff"; printf("Child exit1.coff ...\n"); exec(prog, 0, 0); printf("This is the parent\n"); }
2.59375
3
2024-11-18T22:36:57.741196+00:00
2020-07-21T23:49:55
824ef03d5804bd8da8e69b3ce80e0dc000253616
{ "blob_id": "824ef03d5804bd8da8e69b3ce80e0dc000253616", "branch_name": "refs/heads/master", "committer_date": "2020-07-21T23:49:55", "content_id": "333fb6e8d8ad3e44964b593e51b53e04ed688de5", "detected_licenses": [ "MIT" ], "directory_id": "548a2372a1387ec91f62c1b02f09942cf08bf3ef", "extension": "c", "filename": "main.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3356, "license": "MIT", "license_type": "permissive", "path": "/main.c", "provenance": "stackv2-0107.json.gz:85095", "repo_name": "matthilde/42", "revision_date": "2020-07-21T23:49:55", "revision_id": "5a4350b41311c873944aee69958863c94488c2a0", "snapshot_id": "267c239ba0452b5bb5cc705ac1723562f121a50a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/matthilde/42/5a4350b41311c873944aee69958863c94488c2a0/main.c", "visit_date": "2022-11-22T22:41:27.441657" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <getopt.h> #include "lib42.h" #define HELP "Usage: 42 [OPTION]...\n" \ "Returns the answer to the ultimate question of life.\n\n" \ " -s, --stdout Prints the answer to stdout.\n" \ " -e, --stderr Prints the answer to stderr.\n" \ " -n, --no-return Returns 0 instead of the answer.\n" \ " -c, --custom Custom return number.\n" \ " -v, --verbose Verbose.\n" \ " -h, --help Display this help and exit.\n" \ " -V, --version Output version information and exit.\n\n" \ "Examples: \n" \ " 42 Returns the answer to the ultimate question of life.\n" \ " 42 -n Returns 0.\n\n" \ "42 online help: <https://h3liu.ml/w/42.html>\n" \ "or available locally via: man 42\n\n" \ "Report bugs to <no@example.org>\n\n" #define VERSION "42 Computation Program 4.2\n" \ "Copyright (C) 2020 h34ting4ppliance.\n" \ "Licensed under the MIT License <https://mit-license.org/>.\n" \ "This is free software; you are free to change and redistribute it.\n" \ "There is NO WARRANTY, to the extent permitted by law.\n\n" \ "Written by h34ting4ppliance.\n" static struct option long_options[] = { {"stdout", no_argument, NULL, 's'}, {"stderr", no_argument, NULL, 'e'}, {"no-return", no_argument, NULL, 'n'}, {"custom", required_argument, NULL, 'c'}, {"verbose", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'V'} }; bool verbose_logs = false; void print_usage(); void print_version(); void generate_struct(struct42* a_struct, const int argc, char** argv) { char c; a_struct->to_stdout = false; a_struct->to_stderr = false; a_struct->no_return = false; a_struct->custom_ret = false; while ((c = getopt_long(argc, argv, "senc:vhV", long_options, NULL)) != -1) switch (c) { case 's': a_struct->to_stdout = true; break; case 'e': a_struct->to_stderr = true; break; case 'n': a_struct->no_return = true; break; case 'c': a_struct->custom_ret = true; a_struct->return_num = atoi(optarg); break; case 'v': printf("You won't believe it but I was too lazy to implement verbosity.\n"); break; case 'h': print_usage(); exit(0); break; case 'V': print_version(); exit(0); break; default: case '?': print_usage(); exit(1); break; } } void print_usage() { printf(HELP); } void print_version() { printf(VERSION); } int main(int argc, char** argv) { struct42 config; generate_struct(&config, argc, argv); int answer = api42(&config); return answer; }
2.609375
3
2024-11-18T22:36:57.908143+00:00
2022-11-05T17:46:59
72aaae5dfb0db98d5c877082a178611bd9bce564
{ "blob_id": "72aaae5dfb0db98d5c877082a178611bd9bce564", "branch_name": "refs/heads/master", "committer_date": "2022-11-05T17:46:59", "content_id": "6815037f0b0ae96bd64b882ca3bccd8befa5354c", "detected_licenses": [ "MIT" ], "directory_id": "c07d5913ecf3a23e5ba5b7fb1ed5f39550a86e96", "extension": "c", "filename": "rept.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 37094911, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1527, "license": "MIT", "license_type": "permissive", "path": "/SubTools/rept.c", "provenance": "stackv2-0107.json.gz:85353", "repo_name": "stackprobe/Factory", "revision_date": "2022-11-05T17:46:59", "revision_id": "0aef20aefba7a080f12652230790a18ce17c2795", "snapshot_id": "41777490800b30a02ba80286b536c1e9a80f2b4f", "src_encoding": "SHIFT_JIS", "star_events_count": 2, "url": "https://raw.githubusercontent.com/stackprobe/Factory/0aef20aefba7a080f12652230790a18ce17c2795/SubTools/rept.c", "visit_date": "2022-11-24T15:50:59.412175" }
stackv2
/* rept.exe [/F] [/I] [/P 置き換え前パターン 置き換え後パターン]... 入力ファイル 出力ファイル */ #include "C:\Factory\Common\all.h" static autoList_t *FindPtns; static autoList_t *DestPtns; static int ForceMode; static int IgnoreCaseFlag; static void RepText_Main(char *rFile, char *wFile) { char *text = readText_b(rFile); char *findPtn; uint index; foreach(FindPtns, findPtn, index) { char *destPtn = getLine(DestPtns, index); text = replaceLine(text, findPtn, destPtn, IgnoreCaseFlag); } writeOneLineNoRet_b(wFile, text); memFree(text); } static void RepText(char *rFile, char *wFile) { if(ForceMode || !existFile(wFile)) { RepText_Main(rFile, wFile); } else { char *midFile = makeTempPath(NULL); RepText_Main(rFile, midFile); if(isSameFile(midFile, wFile)) // ? 同じ -> 適用不要 { cout("SKIP!\n"); removeFile(midFile); } else { removeFile(wFile); moveFile(midFile, wFile); } memFree(midFile); } } int main(int argc, char **argv) { FindPtns = newList(); DestPtns = newList(); readArgs: if(argIs("/F")) // Force mode { ForceMode = 1; goto readArgs; } if(argIs("/I")) // Ignore case { IgnoreCaseFlag = 1; goto readArgs; } if(argIs("/P")) // Pair { addElement(FindPtns, (uint)nextArg()); addElement(DestPtns, (uint)nextArg()); goto readArgs; } { char *rFile; char *wFile; rFile = nextArg(); wFile = nextArg(); errorCase(hasArgs(1)); // 不明なオプション RepText(rFile, wFile); } }
2.734375
3
2024-11-18T22:36:58.030004+00:00
2023-09-01T08:20:15
ba0eaa5646998370bbc9755e405b65655a6a5868
{ "blob_id": "ba0eaa5646998370bbc9755e405b65655a6a5868", "branch_name": "refs/heads/master", "committer_date": "2023-09-01T08:21:05", "content_id": "ac3f804717945aea4189979158d4b7c8f2aa594d", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "820b6af9fd43b270749224bb278e5f714f655ac9", "extension": "c", "filename": "ex_get_set_param.c", "fork_events_count": 1243, "gha_created_at": "2010-04-27T15:12:58", "gha_event_created_at": "2023-09-14T07:53:03", "gha_language": "C++", "gha_license_id": "NOASSERTION", "github_id": 631615, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6392, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/ThirdParty/exodusII/vtkexodusII/src/ex_get_set_param.c", "provenance": "stackv2-0107.json.gz:85481", "repo_name": "Kitware/VTK", "revision_date": "2023-09-01T08:20:15", "revision_id": "dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271", "snapshot_id": "49dee7d4f83401efce8826f1759cd5d9caa281d1", "src_encoding": "UTF-8", "star_events_count": 2253, "url": "https://raw.githubusercontent.com/Kitware/VTK/dd4138e17f1ed5dfe6ef1eab0ff6643fdc07e271/ThirdParty/exodusII/vtkexodusII/src/ex_get_set_param.c", "visit_date": "2023-09-01T10:21:57.496189" }
stackv2
/* * Copyright(C) 1999-2020 National Technology & Engineering Solutions * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with * NTESS, the U.S. Government retains certain rights in this software. * * See packages/seacas/LICENSE for details */ /***************************************************************************** * * exgsetp - ex_get_set_param * * entry conditions - * input parameters: * int exoid exodus file id * int set_type the type of set * int set_id set id * * exit conditions - * int* num_entries_in_set number of entries in the set * int* num_dist_fact_in_set number of distribution factors in the * set * * revision history - * * *****************************************************************************/ #include "exodusII.h" // for ex_err, etc #include "exodusII_int.h" // for EX_FATAL, EX_NOERR, etc /* * reads the number of entries and the number of distribution factors which * describe a single set */ int ex_get_set_param(int exoid, ex_entity_type set_type, ex_entity_id set_id, void_int *num_entry_in_set, void_int *num_dist_fact_in_set) { int status; int varid, dimid, set_id_ndx; size_t lnum_entry_in_set; size_t lnum_dist_fact_in_set; char errmsg[MAX_ERR_LENGTH]; char * numentryptr = NULL; char * numdfptr = NULL; EX_FUNC_ENTER(); if (ex__check_valid_file_id(exoid, __func__) == EX_FATAL) { EX_FUNC_LEAVE(EX_FATAL); } if (ex_int64_status(exoid) & EX_BULK_INT64_API) { if (num_entry_in_set) { *(int64_t *)num_entry_in_set = 0; } if (num_dist_fact_in_set) { *(int64_t *)num_dist_fact_in_set = 0; } } else { if (num_entry_in_set) { *(int *)num_entry_in_set = 0; } if (num_dist_fact_in_set) { *(int *)num_dist_fact_in_set = 0; } } /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex__dim_num_objects(set_type), &dimid)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "Warning: no %ss stored in file id %d", ex_name_of_object(set_type), exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_WARN); } /* Lookup index of set id in VAR_*S_IDS array */ set_id_ndx = ex__id_lkup(exoid, set_type, set_id); if (set_id_ndx <= 0) { ex_get_err(NULL, NULL, &status); if (status != 0) { if (status == EX_NULLENTITY) { EX_FUNC_LEAVE(EX_NOERR); } snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s id %" PRId64 " in id array in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } } /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { numentryptr = DIM_NUM_NOD_NS(set_id_ndx); /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */ numdfptr = DIM_NUM_NOD_NS(set_id_ndx); } else if (set_type == EX_EDGE_SET) { numentryptr = DIM_NUM_EDGE_ES(set_id_ndx); numdfptr = DIM_NUM_DF_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { numentryptr = DIM_NUM_FACE_FS(set_id_ndx); numdfptr = DIM_NUM_DF_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { numentryptr = DIM_NUM_SIDE_SS(set_id_ndx); numdfptr = DIM_NUM_DF_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { numentryptr = DIM_NUM_ELE_ELS(set_id_ndx); numdfptr = DIM_NUM_DF_ELS(set_id_ndx); } /* inquire values of dimension for number of entities in set */ if (ex__get_dimension(exoid, numentryptr, "entries", &lnum_entry_in_set, &dimid, __func__) != NC_NOERR) { EX_FUNC_LEAVE(EX_FATAL); } if (ex_int64_status(exoid) & EX_BULK_INT64_API) { if (num_entry_in_set) { *(int64_t *)num_entry_in_set = lnum_entry_in_set; } } else { if (num_entry_in_set) { *(int *)num_entry_in_set = lnum_entry_in_set; } } /* Inquire value of dimension of number of dist factors for this set. NOTE: For node sets, because DIM_NUM_DF_NS is not used, we check to see if the dist factor variable for a node set index exits. If it does not, the dist factor count is assumed to be zero, otherwise the dist factor count will be the same as the number of nodes in the set. */ if (set_type == EX_NODE_SET) { if ((status = nc_inq_varid(exoid, VAR_FACT_NS(set_id_ndx), &varid)) != NC_NOERR) { if (status == NC_ENOTVAR) { EX_FUNC_LEAVE(EX_NOERR); } snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate the dist factors for %s %" PRId64 " in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } if (ex_int64_status(exoid) & EX_BULK_INT64_API) { if (num_dist_fact_in_set) { *(int64_t *)num_dist_fact_in_set = lnum_entry_in_set; } } else { if (num_dist_fact_in_set) { *(int *)num_dist_fact_in_set = lnum_entry_in_set; } } } else { /* all other set types */ if ((status = nc_inq_dimid(exoid, numdfptr, &dimid)) != NC_NOERR) { if (status == NC_EBADDIM) { EX_FUNC_LEAVE(EX_NOERR); } snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate number of dist factors in %s %" PRId64 " in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, &lnum_dist_fact_in_set)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of dist factors in %s %" PRId64 " in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err_fn(exoid, __func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } if (ex_int64_status(exoid) & EX_BULK_INT64_API) { if (num_dist_fact_in_set) { *(int64_t *)num_dist_fact_in_set = lnum_dist_fact_in_set; } } else { if (num_dist_fact_in_set) { *(int *)num_dist_fact_in_set = lnum_dist_fact_in_set; } } } EX_FUNC_LEAVE(EX_NOERR); }
2.09375
2
2024-11-18T22:36:58.536652+00:00
2023-07-12T18:56:26
de3dfbb98f93593708ccf45ba5e73c97c456b537
{ "blob_id": "de3dfbb98f93593708ccf45ba5e73c97c456b537", "branch_name": "refs/heads/main", "committer_date": "2023-07-12T18:56:26", "content_id": "2ce28d6ffe3eb0d2313a9983e16bc85b42248a30", "detected_licenses": [ "MIT" ], "directory_id": "1bd90f1d200b381a5ff3aaeaad3ef7426ee15253", "extension": "c", "filename": "drv8833_mcpwm.c", "fork_events_count": 78, "gha_created_at": "2018-04-16T06:28:52", "gha_event_created_at": "2023-07-12T18:56:28", "gha_language": "C", "gha_license_id": "MIT", "github_id": 129695374, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7754, "license": "MIT", "license_type": "permissive", "path": "/esp32_sawppy/lib/hardware/drv8833_mcpwm.c", "provenance": "stackv2-0107.json.gz:85741", "repo_name": "Roger-random/Sawppy_Rover", "revision_date": "2023-07-12T18:56:26", "revision_id": "ac48ddcf21dd8153da8817ba1ea5e6a46f2a8298", "snapshot_id": "f0ff5346b9bf46e933f47608e5a07012663beb84", "src_encoding": "UTF-8", "star_events_count": 399, "url": "https://raw.githubusercontent.com/Roger-random/Sawppy_Rover/ac48ddcf21dd8153da8817ba1ea5e6a46f2a8298/esp32_sawppy/lib/hardware/drv8833_mcpwm.c", "visit_date": "2023-08-04T17:55:57.082822" }
stackv2
/* Using ESP32 MCPWM to control a DRV8833 DC Motor Control IC (And those compatible with its "two PWM pins per motor" control scheme.) Reference: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/mcpwm.html Portions copied from Espressif MCPWM sample code https://github.com/espressif/esp-idf/tree/master/examples/peripherals/mcpwm/mcpwm_brushed_dc_control Which they have placed in the public domain, or CC0 https://creativecommons.org/share-your-work/public-domain/cc0/ Remainder Copyright (c) Roger Cheng MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "drv8833_mcpwm.h" static const char *TAG = "drv8833_mcpwm"; /* * @brief Updates MCPWM duty cycles to deliver given velocity * @param velocity Target velocity in meters per second * @param MC Specify which MCPWM peripheral to update */ void update_motor_speed(float velocity, mcpwm_motor_control MC) { float duty_cycle; if (fabs(velocity) < wheel_speed_epsilon) { // Close enough to be zero to be treated as zero. duty_cycle = 0.0; } else if (fabs(velocity) < wheel_speed_min) { // Below the level our DC motor can sustain running by itself. However // it might have help from other wheels so we feed it enough power to // barely overcome geartrain friction duty_cycle = duty_cycle_min; } else { duty_cycle = duty_cycle_min + (fabs(velocity)/wheel_speed_max) * (duty_cycle_max - duty_cycle_min); } if (duty_cycle > 100.0) { // Velocity should not exceed wheel_speed_max. If it happens, that's a bug // elsewhere in this code. But if it happens anyway, clamp value and emit // warning message. duty_cycle = 100.0; ESP_LOGW(TAG, "Motor speed velocity %+.2f exceeded specified maximum %+.2f.", velocity, wheel_speed_max); } if (velocity > 0) { ESP_ERROR_CHECK(mcpwm_set_duty(MC.unit, MC.timer, MCPWM_GEN_A, duty_cycle)); ESP_ERROR_CHECK(mcpwm_set_duty(MC.unit, MC.timer, MCPWM_GEN_B, 0)); } else if (velocity < 0) { ESP_ERROR_CHECK(mcpwm_set_duty(MC.unit, MC.timer, MCPWM_GEN_A, 0)); ESP_ERROR_CHECK(mcpwm_set_duty(MC.unit, MC.timer, MCPWM_GEN_B, duty_cycle)); } else { ESP_ERROR_CHECK(mcpwm_set_duty(MC.unit, MC.timer, MCPWM_GEN_A, 0)); ESP_ERROR_CHECK(mcpwm_set_duty(MC.unit, MC.timer, MCPWM_GEN_B, 0)); } } void drv8833_mcpwm_task(void* pvParam) { wheel_msg message; float current_speed[wheel_count] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; // Retrieve input queue if (NULL == pvParam) { ESP_LOGE(TAG, "drv8833_mcpwm_task parameter is null. Expected handle to queue of wheel commands."); vTaskDelete(NULL); // Delete self. } QueueHandle_t xWheelQueue = (QueueHandle_t)pvParam; // Configure MCPWM peripheral mcpwm_config_t mcpwm_config = { .frequency = pwm_freq, .cmpr_a = 0, .cmpr_b = 0, .counter_mode = MCPWM_UP_COUNTER, .duty_mode = MCPWM_DUTY_MODE_0, }; for (int wheel = 0; wheel < wheel_count; wheel++) { ESP_ERROR_CHECK(mcpwm_init( speed_control[wheel].unit, speed_control[wheel].timer, &mcpwm_config)); ESP_ERROR_CHECK(mcpwm_gpio_init( speed_control[wheel].unit, speed_control[wheel].signalA, speed_control[wheel].gpioA)); ESP_ERROR_CHECK(mcpwm_gpio_init( speed_control[wheel].unit, speed_control[wheel].signalB, speed_control[wheel].gpioB)); current_speed[wheel] = 0.0; update_motor_speed(current_speed[wheel], speed_control[wheel]); } bool haltNotify = true; while(true) { // Wait for next wheel control message if (pdTRUE == xQueueReceive(xWheelQueue, &message, wheel_msg_timeout_interval)) { haltNotify = true; for (int wheel = 0; wheel < wheel_count; wheel++) { float currentSpeed = current_speed[wheel]; float targetSpeed = message.speed[wheel]; float newSpeed; // newSpeed speed moves towards targetSpeed, limited by acceleration cap if (targetSpeed > currentSpeed + wheel_accel_max) { newSpeed = currentSpeed + wheel_accel_max; } else if (targetSpeed < currentSpeed - wheel_accel_max) { newSpeed = currentSpeed - wheel_accel_max; } else { newSpeed = targetSpeed; } // If we are switching directions, minimum stopped deadtime of one update cycle. if ((currentSpeed < 0 && newSpeed > 0) || (currentSpeed > 0 && newSpeed < 0)) { newSpeed = 0; } // If starting from below minimum, give motor a startup kick. if (currentSpeed < wheel_speed_min && newSpeed > wheel_speed_min) { newSpeed = wheel_speed_startup; } else if (currentSpeed > -wheel_speed_min && newSpeed < -wheel_speed_min) { newSpeed = -wheel_speed_startup; } current_speed[wheel] = newSpeed; } // Calculated velocities has been stored in current_speed[]. But due to // rover geometry, it is possible for some wheels to end up with velocity // higher than wheel_speed_max. If so, scale every value of the range // [wheel_speed_startup, calc_max] to [wheel_speed_startup, wheel_speed_max] float calc_max = 0; for (int wheel = 0; wheel < wheel_count; wheel++) { if (fabs(current_speed[wheel]) > calc_max) { calc_max = fabs(current_speed[wheel]); } } if (calc_max > wheel_speed_max) { float scale = (wheel_speed_max-wheel_speed_startup) / (calc_max-wheel_speed_startup); float magnitude = 0; for (int wheel = 0; wheel < wheel_count; wheel++) { magnitude = fabs(current_speed[wheel]); if (magnitude > wheel_speed_startup) { magnitude -= wheel_speed_startup; magnitude *= scale; magnitude += wheel_speed_startup; current_speed[wheel] = copysignf(magnitude, current_speed[wheel]); } } } // All speed adjustments complete, send results to motor controllers. for (int wheel = 0; wheel < wheel_count; wheel++) { update_motor_speed(current_speed[wheel], speed_control[wheel]); } } else { if (haltNotify) { haltNotify = false; // Once per timeout is enough ESP_LOGE(TAG, "No wheel message received within timeout, stopping all motors."); } // In case of timeout, ramping is ignored. We go to zero immediately. for (int wheel = 0; wheel < wheel_count; wheel++) { current_speed[wheel] = 0.0; update_motor_speed(current_speed[wheel], speed_control[wheel]); } } } }
2.234375
2
2024-11-18T22:36:58.627473+00:00
2022-01-31T04:36:44
a4822db879141b64706152c2f431a6ec85b1c3da
{ "blob_id": "a4822db879141b64706152c2f431a6ec85b1c3da", "branch_name": "refs/heads/master", "committer_date": "2022-01-31T04:36:44", "content_id": "404482331a8d859fb306056d3c45e42c1b080fc2", "detected_licenses": [ "MIT" ], "directory_id": "e1c02087e71617b1bdfb6ed8f139a35f0e8ce9c7", "extension": "c", "filename": "btn-wait-for-click.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 186742104, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1179, "license": "MIT", "license_type": "permissive", "path": "/c/pi/btn-wait-for-click.c", "provenance": "stackv2-0107.json.gz:85871", "repo_name": "CrazyJ36/c", "revision_date": "2022-01-31T04:36:44", "revision_id": "ac37b0af76ef273199eeb0d3796549cc6bd06dc0", "snapshot_id": "fe21422de23ac93d3e6f8c3e20e1d45ddb55a33a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CrazyJ36/c/ac37b0af76ef273199eeb0d3796549cc6bd06dc0/c/pi/btn-wait-for-click.c", "visit_date": "2022-02-06T01:43:51.313389" }
stackv2
/* This app waits some time for a button press, * lights an led if button is pressed down. */ #include <bcm2835.h> #include <stdio.h> #define BTN 17 // or like: RPI_GPIO_P1_12 #define LED 4 // // get voltage level of pin to ground (is connected or not) #define pin_level bcm2835_gpio_lev(BTN) int main() { if (!bcm2835_init()) { printf("Couldn't run. Is the bcm2835 library installed from airspayce.com/mikem/bcm2835?\n"); return(1); } bcm2835_gpio_fsel(BTN, BCM2835_GPIO_FSEL_INPT); bcm2835_gpio_fsel(LED, BCM2835_GPIO_FSEL_OUTP); int count = 0; while(count < 50) { // timed function to find out if btn has been pushed if(pin_level == 0) { // if btn pin has connection(0 means true), turn led on bcm2835_gpio_set(LED); } else if (pin_level == 1) { // if btn pin gets no voltage through btn, turn led off bcm2835_gpio_clr(LED); } delay(100); // timed wait for btn response printf("wait: %d out of 50\n", count); // viewable app timer count++; } //if (pin_level == 0) bcm2835_gpio_clr(LED); // turn off led in case it is on still bcm2835_close(); // deallocate functions of bcm2835 library return(0); }
3.21875
3
2024-11-18T22:36:58.706257+00:00
2020-03-20T04:50:03
48eae8513d705595506ff626df31c4441d6c8336
{ "blob_id": "48eae8513d705595506ff626df31c4441d6c8336", "branch_name": "refs/heads/master", "committer_date": "2020-03-20T04:50:03", "content_id": "cf826aa051074fbded11e54cf9171b8a27090c45", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1f5660e858391e05944c57cfb221f7f555904bcc", "extension": "c", "filename": "hello.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 248668877, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 208, "license": "Apache-2.0", "license_type": "permissive", "path": "/hello.c", "provenance": "stackv2-0107.json.gz:86000", "repo_name": "PHolder-CS50/CS50-Problem-Set-1", "revision_date": "2020-03-20T04:50:03", "revision_id": "d8eec97ad911dbda0591059b8843c88c500abcf6", "snapshot_id": "9b93e2fee458fc525d3c437b9885c56237344f2c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PHolder-CS50/CS50-Problem-Set-1/d8eec97ad911dbda0591059b8843c88c500abcf6/hello.c", "visit_date": "2021-04-07T10:37:35.185019" }
stackv2
#include <stdio.h> #include <cs50.h> // Ask the user their name, and then say hello to them int main(void) { string usersName = get_string("What is your name? "); printf("hello, %s\n", usersName); }
2.75
3
2024-11-18T22:36:58.884313+00:00
2019-04-12T06:13:01
d315be4e6cb9019aa77a0460b9c4d9cec2a860e1
{ "blob_id": "d315be4e6cb9019aa77a0460b9c4d9cec2a860e1", "branch_name": "refs/heads/master", "committer_date": "2019-04-12T06:13:01", "content_id": "3d63852adb72ceca1893e8be07040374297cf050", "detected_licenses": [ "MIT" ], "directory_id": "4765bd42b54320e5afe84bdb0f9fb0987972deb4", "extension": "c", "filename": "packer.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": 3743, "license": "MIT", "license_type": "permissive", "path": "/packer.c", "provenance": "stackv2-0107.json.gz:86258", "repo_name": "bigbrobro/run-embedded-elf-from-memory", "revision_date": "2019-04-12T06:13:01", "revision_id": "b377044971f94394ddaaf03c16a92bd5d8373674", "snapshot_id": "749b8227565698b6e0577540fe2d070b82409fa8", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bigbrobro/run-embedded-elf-from-memory/b377044971f94394ddaaf03c16a92bd5d8373674/packer.c", "visit_date": "2022-01-09T20:43:16.187361" }
stackv2
// A packer that executes a second (embedded) ELF // // Copyright (c) 2018 Alexandre-Xavier Labonté-Lamoureux // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <stdio.h> #include <stdlib.h> #include <string.h> // memcpy #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> // Use "SYS_memfd_create", because the <sys/memfd.h> wrapper doesn't exist until Linux 4.10 // The "memfd_create" system call was added to Linux 3.17 so "syscall" can be used to call it #include <sys/syscall.h> int main(int argc, char* argv[], char** envp) { int pid = getpid(); printf("My PID is: %d\n", pid); printf("My filename is: %s\n", argv[0]); // Find the size of the file using <sys/stat.h> struct stat st; stat(argv[0], &st); size_t size = st.st_size; printf("My size is: %u\n", size); char procstring[32]; sprintf(procstring, "%s%d%s", "/proc/", pid, "/exe"); printf("Location (copy): %s\n", procstring); int filedesc = open(procstring, O_RDONLY); if (filedesc < 0) { printf("Invalid file descriptor for /proc: %d\n", filedesc); return 1; } // Delete self unlink(argv[0]); if (access(argv[0], F_OK) < 0) printf("I successfully deleted myself.\n"); else printf("Couldn't erase myself from the filesystem.\n"); // The real business starts here char* entirefile = (char*)malloc(size); read(filedesc, entirefile, size); // Yeah... use arbitrary values here. for (int i = size - 10; i > 1000; i--) { // The goal is to find the second ELF header if (entirefile[i] == 0x7F && entirefile[i + 1] == 'E' && entirefile[i + 2] == 'L' && entirefile[i + 3] == 'F') { printf("Second ELF header found at: 0x%x\n", i); // Create a buffer for this second ELF int newsize = size - i; char* newelf = (char*)malloc(newsize); // Copy ELF to buffer memcpy(newelf, entirefile + i, newsize); // It's in memory! Create a file descriptor. int memfd = syscall(SYS_memfd_create, "hidden", 0); if (memfd < 0) { printf("Invalid memfd %d.\n", i); free(newelf); return 1; } else printf("memfd is: %d\n", memfd); // Write ELF to temporary memory file write(memfd, newelf, newsize); // Deploy the payload as a different process fork(); int newpid = getpid(); if (newpid != pid) { // Execute the in-memory ELF int ret = fexecve(memfd, argv, envp); // The above function will only return if there's an error printf("ERROR EXECUTING PAYLOAD: Return value: %d. Errno is: ret %d\n", ret, errno); } else printf("The packer is done deploying the payload.\n"); free(newelf); } } // Free the resources free(entirefile); close(filedesc); return 0; }
2.75
3
2024-11-18T22:36:58.958034+00:00
2021-09-29T00:05:16
dc250602e9e5622135f92d194c5f4d60c0fee6af
{ "blob_id": "dc250602e9e5622135f92d194c5f4d60c0fee6af", "branch_name": "refs/heads/0616325", "committer_date": "2021-09-29T00:05:16", "content_id": "47f593b56bb1ee6b4692706f9b8350cddfec6524", "detected_licenses": [ "MIT" ], "directory_id": "0efc0abd0a2b7cce926db7913a6940bd91441ff8", "extension": "h", "filename": "vfs.h", "fork_events_count": 0, "gha_created_at": "2021-03-01T10:19:11", "gha_event_created_at": "2021-03-31T17:14:31", "gha_language": null, "gha_license_id": "MIT", "github_id": 343373285, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3565, "license": "MIT", "license_type": "permissive", "path": "/include/vfs.h", "provenance": "stackv2-0107.json.gz:86387", "repo_name": "cclin0816/osc2021", "revision_date": "2021-09-29T00:05:16", "revision_id": "7516f15661f1400206c771454f14dcf1a8cc628f", "snapshot_id": "6df1d201575459c1b3354941adc3b24bc26190db", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/cclin0816/osc2021/7516f15661f1400206c771454f14dcf1a8cc628f/include/vfs.h", "visit_date": "2023-08-11T17:26:29.841611" }
stackv2
#ifndef VFS_H #define VFS_H #include <stddef.h> #include "util.h" // super block for a file system typedef struct super_block { cdl_list sb_list; // sb list of fs struct dentry *root; // root dentry of this sb struct dentry *mnt_p; // dentry this sb mount on } super_block; // unique typedef struct inode { struct super_block *i_sb; struct inode_op *i_op; unsigned long i_mode; unsigned long i_size; void *i_data; } inode; // unique except hard link typedef struct dentry { char *name; // component name struct dentry_op *d_op; inode *d_inode; struct dentry *parent; cdl_list child; cdl_list sibli; struct super_block *mnt; // mount point void *d_data; unsigned long ref_cnt; } dentry; typedef struct file_system_t file_system_t; // file system type struct file_system_t { cdl_list fs_list; const char *name; int (*mount)(file_system_t *, dentry *, const char *); cdl_list sb_list; }; typedef struct file { struct dentry *path; struct file_op *f_op; inode *f_inode; unsigned long f_mode; // open mode unsigned long f_pos; // read / write pos } file; typedef struct dirent { char name[512]; unsigned long size; unsigned long mode; } dirent; // open* and close* is required typedef struct inode_op { // char * is component name possible null string int (*create)(struct dentry *, const char *); // char * is component name possible null string int (*remove)(struct dentry *, const char *); // char * is component name possible null string int (*mkdir)(struct dentry *, const char *); // char * is component name possible null string int (*rmdir)(struct dentry *, const char *); // dentry is the file to be open int (*open)(struct dentry *, struct file **, unsigned long); int (*close)(struct file *); // char * is component name dentry * possible file node int (*opendent)(struct dentry *, struct dentry **, const char *); int (*closedent)(struct dentry *); int (*getdent)(struct dentry *, unsigned long, struct dirent *); } inode_op; typedef struct dentry_op { int (*umount)(dentry *); } dentry_op; typedef struct file_op { long (*read)(struct file *, char *, unsigned long); long (*write)(struct file *, const char *, unsigned long); } file_op; int vfs_create(const char *path); int vfs_remove(const char *path); int vfs_mkdir(const char *path); int vfs_rmdir(const char *path); unsigned long vfs_open(const char *path, unsigned long flag); int vfs_close(unsigned long fd_num); int vfs_opendent(struct dentry **target, const char *path); int vfs_closedent(struct dentry *target); int vfs_getdent(unsigned long fd_num, unsigned long count, struct dirent *dent); long vfs_read(unsigned long fd_num, char *buf, unsigned long size); long vfs_write(unsigned long fd_num, const char *buf, unsigned long size); typedef struct file_discriptor { cdl_list fd_list; unsigned long fd_num; file *f; } file_discriptor; #define METHOD_NOT_IMP -1 #define INVALID_PATH -2 #define INVALID_FD -3 #define INVALID_FS -4 #define INVALID_DEV -5 #define TARGET_EXIST -6 #define TARGET_NO_EXIST -7 #define TARGET_INUSE -8 #define TYPE_DIR 1 #define TYPE_FILE 2 #define get_struct_head(stc, com, addr) \ ((stc *)((void *)addr - offsetof(stc, com))) void init_vfs(); int vfs_mount(const char *dev, const char *mp, const char *fs); int vfs_umount(const char *path); int vfs_chdir(const char *path); dentry *get_vfs_root(); void register_fs(file_system_t *fs); #define O_CREATE 1 << 0 unsigned long get_filesize(unsigned long fd_num); #endif
2.390625
2
2024-11-18T22:36:59.013106+00:00
2016-04-11T14:48:23
86d29e4f826b276788c6254da1b4919e3e973688
{ "blob_id": "86d29e4f826b276788c6254da1b4919e3e973688", "branch_name": "refs/heads/master", "committer_date": "2016-04-11T14:48:23", "content_id": "ec3b941748a83f4fdf99b43d8a1d45aea0ed1c90", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "directory_id": "7d73e72c7bc57278c5fd6cfea3ea54182315cf9c", "extension": "c", "filename": "test-buffer.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": 1087, "license": "BSD-3-Clause,BSD-2-Clause", "license_type": "permissive", "path": "/tests/test-buffer.c", "provenance": "stackv2-0107.json.gz:86515", "repo_name": "traderbagel/server-framework", "revision_date": "2016-04-11T14:48:23", "revision_id": "61180c603c20b8217b4eaad86353cb0d065cfa9d", "snapshot_id": "349452fb132327666a008269fd3acae359da57fa", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/traderbagel/server-framework/61180c603c20b8217b4eaad86353cb0d065cfa9d/tests/test-buffer.c", "visit_date": "2021-05-31T01:00:06.311980" }
stackv2
#include "buffer.h" #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> ssize_t writing_hook(server_pt srv, int fd, void *data, size_t len) { char prefix[5] = "hook-"; size_t totalLen = len + strlen(prefix) + 1; char *encryptData = malloc( totalLen ); strcpy( encryptData, prefix); strcat( encryptData, data); int sent = write(fd, encryptData, totalLen); if (sent < 0 && (errno & (EWOULDBLOCK | EAGAIN | EINTR))) sent = 0; return sent; } int main(void) { fprintf(stderr, "# Test buffer\n"); /* simple check buffer */ void *buf = Buffer.create(0); char strA[12] = "hello world\n"; char strB[12] = "good byyyye\n"; if ( Buffer.write( buf, strA, strlen(strA)) < 0 ) perror("write error"); if ( Buffer.write( buf, strB, strlen(strB)) < 0) perror("write_move error"); Buffer.set_whook( buf, writing_hook); while( !Buffer.is_empty( buf) ) { if ( Buffer.flush( buf, STDOUT_FILENO) < 0 ) { perror("flush failed"); } } return 0; }
2.75
3
2024-11-18T22:36:59.651747+00:00
2015-12-08T01:14:34
44fb371dfc9c948da029e7d10ecf1021025c0e0b
{ "blob_id": "44fb371dfc9c948da029e7d10ecf1021025c0e0b", "branch_name": "refs/heads/master", "committer_date": "2015-12-08T01:14:34", "content_id": "4f812a7c19d5b2e7a04acff0d563b9c25b1ff86c", "detected_licenses": [ "MIT" ], "directory_id": "d6f778a94209554b89f31fee6ab0e34c51963661", "extension": "h", "filename": "chlorine.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 46851452, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20135, "license": "MIT", "license_type": "permissive", "path": "/test/chlorine/chlorine.h", "provenance": "stackv2-0107.json.gz:87420", "repo_name": "lavignes/librts", "revision_date": "2015-12-08T01:14:34", "revision_id": "d0c69dd36ee8eec289316fd26b339cadb520f69e", "snapshot_id": "90e6232a47193a5ee571a5ee038ca7b7c120d9e4", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/lavignes/librts/d0c69dd36ee8eec289316fd26b339cadb520f69e/test/chlorine/chlorine.h", "visit_date": "2021-05-30T03:43:27.812566" }
stackv2
#ifndef CHLORINE2 #define CHLORINE2 #include <sys/time.h> #include <pthread.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <stdarg.h> #include <string.h> #ifndef CHLORINE_NO_COLORS #define __CL_RESET "\x1B[0m" #define __CL_BOLD "\x1B[1m" #define __CL_UL "\x1B[4m" #define __CL_TAB " " #define __CL_BLACK "0" #define __CL_RED "1" #define __CL_GREEN "2" #define __CL_YELLOW "3" #define __CL_BLUE "4" #define __CL_MAGENTA "5" #define __CL_CYAN "6" #define __CL_WHITE "7" #define __CL_FG(color) "\x1B[3"color"m" #define __CL_BG(color) "\x1B[4"color"m" #else #define __CL_RESET "" #define __CL_BOLD "" #define __CL_UL "" #define __CL_TAB " " #define __CL_BLACK "" #define __CL_RED "" #define __CL_GREEN "" #define __CL_YELLOW "" #define __CL_BLUE "" #define __CL_MAGENTA "" #define __CL_CYAN "" #define __CL_WHITE "" #define __CL_FG(color) "" #define __CL_BG(color) "" #endif pthread_key_t __CLEnvKey; typedef struct __CLSpecEnv { void* userdata; bool serial_pass; bool failed; char* test_name; char* output_buffer; size_t num_failed_asserts; size_t num_passed_asserts; } __CLSpecEnv; typedef void* (*__CLSpecType)(__CLSpecEnv *); typedef struct __CLWork { __CLSpecType* specs; __CLSpecEnv* envs; size_t num_specs; size_t index; bool serial_pass; pthread_mutex_t lock; } __CLWork; /** * Options used when building a CL_SPEC. */ typedef enum CLOptions { CL_OPTION_NONE = 0, /** * The SPEC will skip its setup fixture, even it doesn't * use the default setup fixture (CL_SETUP). */ CL_OPTION_SKIP_SETUP = 1 << 0, /** * The SPEC will skip its teardown fixture, even it doesn't * use the default teardown fixture (CL_TEARDOWN). */ CL_OPTION_SKIP_TEARDOWN = 1 << 1, /** * The SPEC will skip setup and teardown. */ CL_OPTION_SKIP_SETUP_AND_TEARDOWN = CL_OPTION_SKIP_SETUP | CL_OPTION_SKIP_TEARDOWN, /** * The SPEC will run in serial, after all parallel SPECS have ran, regardless * of the number of parallel jobs in the bundle. */ CL_OPTION_SERIAL = 1 << 2, } CLOptions; typedef void (*__CLSetupType)(); __CLSetupType __cl_setup; __CLSetupType __cl_teardown; __CLSetupType __cl_setup_once; __CLSetupType __cl_teardown_once; void __cl_env_init(__CLSpecEnv* env) { env->userdata = NULL; env->serial_pass = false; env->failed = false; env->test_name = NULL; env->output_buffer = malloc(16); env->output_buffer[0] = '\0'; env->num_failed_asserts = 0; env->num_passed_asserts = 0; } __CLSpecEnv* __cl_env() { return pthread_getspecific(__CLEnvKey); } void __cl_vappend(const char* format, va_list args) { __CLSpecEnv *env = __cl_env(); size_t cursor = 0; if (env->output_buffer) { cursor = strlen(env->output_buffer); } char* new_output = NULL; size_t new_output_size = vasprintf(&new_output, format, args) + 1; env->output_buffer = realloc(env->output_buffer, cursor + new_output_size); strncpy(env->output_buffer + cursor, new_output, new_output_size); free(new_output); } void __cl_append(const char* format, ...) { va_list args; va_start(args, format); __cl_vappend(format, args); va_end(args); } void __cl_print(const char* format, ...) { va_list args; va_start (args, format); vfprintf(stderr, format, args); va_end(args); } /** * Return the SPEC-specific custom pointer set using cl_set_userdata(). */ void* cl_get_userdata() { __CLSpecEnv* env = __cl_env(); if (!env) { __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET "Detecting call to cl_get_userdata() from outside the scope " "of a SPEC\n\n"); return NULL; } return env->userdata; } /** * Set the SPEC-specific custom pointer. Get it with cl_get_userdata(). */ void cl_set_userdata(void* userdata) { __CLSpecEnv* env = __cl_env(); if (!env) { __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET "Detecting call to cl_set_userdata() from outside the scope " "of a SPEC\n\n"); return; } env->userdata = userdata; } /** * Return the number of passed assertions so far in the SPEC. */ size_t cl_num_passed() { __CLSpecEnv* env = __cl_env(); if (!env) { __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET "Detecting call to cl_num_passed() from outside the scope " "of a SPEC\n\n"); return 0; } return env->num_passed_asserts; } /** * Return the number of failed assertions so far in the SPEC. */ size_t cl_num_failed() { __CLSpecEnv* env = __cl_env(); if (!env) { __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET "Detecting call to cl_num_passed() from outside the scope " "of a SPEC\n\n"); return 0; } return env->num_failed_asserts; } /** * Return the name of the SPEC as a string. */ const char* cl_get_name() { __CLSpecEnv* env = __cl_env(); if (!env) { __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET "Detecting call to cl_get_name() from outside the scope " "of a SPEC\n\n"); return NULL; } return env->test_name; } /** * Return whether the SPEC has failed. */ bool cl_has_failed() { __CLSpecEnv* env = __cl_env(); if (!env) { __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET "Detecting call to cl_has_failed() from outside the scope " "of a SPEC\n\n"); return false; } return env->failed; } void __cl_info(const char* format, ...) { __cl_append(__CL_BOLD __CL_FG(__CL_CYAN) "[INFO]" __CL_RESET " "); va_list args; va_start (args, format); __cl_vappend(format, args); va_end(args); } void __cl_error(const char* format, ...) { __cl_append(__CL_BOLD __CL_FG(__CL_YELLOW) __CL_TAB "[ERROR]" __CL_RESET " "); va_list args; va_start (args, format); __cl_vappend(format, args); va_end(args); } void __cl_pass(const char* format, ...) { __cl_append(__CL_BOLD __CL_FG(__CL_GREEN) __CL_TAB "[PASS] " __CL_RESET " "); va_list args; va_start (args, format); __cl_vappend(format, args); va_end(args); } void __cl_fail(const char* format, ...) { __cl_append(__CL_BOLD __CL_FG(__CL_RED) __CL_TAB "[FAIL] " __CL_RESET " "); va_list args; va_start (args, format); __cl_vappend(format, args); va_end(args); } void __cl_log(const char* format, ...) { __cl_append(__CL_BOLD __CL_FG(__CL_RED) __CL_TAB "[LOG] " __CL_RESET " "); va_list args; va_start (args, format); __cl_vappend(format, args); va_end(args); __cl_append("\n"); } double __cl_time() { struct timeval t; gettimeofday(&t, NULL); return (double) t.tv_sec + t.tv_usec / 1000000.0; } /** * Write a message to the SPEC's log. */ #define cl_log(format, ...) \ do { \ if (!__cl_env()) { \ __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET \ "Detecting call to cl_log() from outside the scope " \ "of a SPEC at %s:%d\n\n", __FILE__, __LINE__); \ return; \ } \ __cl_log(format, ##__VA_ARGS__); \ } while (0) \ /** * Force a SPEC to fail and exit. */ #define cl_abort() \ do { \ __CLSpecEnv* env = __cl_env(); \ if (!env) { \ __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET \ "Detecting call to cl_abort() from outside the scope " \ "of a SPEC at %s:%d\n\n", __FILE__, __LINE__); \ } \ env->failed = true; \ __cl_fail("Aborted\n\n"); \ __cl_append("======================================================\n\n"); \ pthread_exit(NULL); \ } while(0) \ /** * Return false if the running SPEC was created using CL_OPTION_SERIAL. */ bool cl_is_parallel() { __CLSpecEnv* env = __cl_env(); if (!env) { __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET "Detecting call to cl_is_parallel() from outside the scope " "of a SPEC\n\n"); return false; } return !env->serial_pass; } /** * Assert an expression is true, and print a message if the test fails. */ #define cl_assert_msg(test, format, ...) \ do { \ __CLSpecEnv* env = __cl_env(); \ if (!env) { \ __cl_print(__CL_BOLD __CL_FG(__CL_YELLOW) "[ERROR] " __CL_RESET \ "Detecting call to cl_assert() from outside the scope " \ "of a SPEC at %s:%d\n\n", __FILE__, __LINE__); \ } else if (!(test)) { \ env->num_failed_asserts++; \ /* Log the assert failure */ \ __cl_error("Assertion Failed: " __CL_FG(__CL_RED) __CL_BOLD \ "%s\n" __CL_RESET __CL_TAB __CL_TAB "in %s:%d\n" \ __CL_TAB __CL_TAB, #test, __FILE__, __LINE__); \ __cl_append(__CL_FG(__CL_BLUE)); \ __cl_append(format, ##__VA_ARGS__); \ __cl_append(__CL_RESET "\n\n"); \ } else { \ env->num_passed_asserts++; \ } \ } while(0) \ /** * Assert an expression is true. */ #define cl_assert(test) cl_assert_msg(test, "") /** * The default fixture that is run repeatedly before every test. */ #define CL_SETUP \ void __cl_setup_impl(); \ __CLSetupType __cl_setup = __cl_setup_impl; \ void __cl_setup_impl() \ /** * The default fixture that is run repeatedly after every test. */ #define CL_TEARDOWN \ void __cl_teardown_impl(); \ __CLSetupType __cl_teardown = __cl_teardown_impl; \ void __cl_teardown_impl() \ /** * A fixture ran once before all tests. You should not call any * cl_* functions from this fixture. If you do, an error will be added * to the log. */ #define CL_SETUP_ONCE \ void __cl_setup_once_impl(); \ __CLSetupType __cl_setup_once = __cl_setup_once_impl; \ void __cl_setup_once_impl() \ /** * A fixture ran once after all tests. You should not call any * cl_* functions from this fixture. If you do, an error will be added * to the log. */ #define CL_TEARDOWN_ONCE \ void __cl_teardown_once_impl(); \ __CLSetupType __cl_teardown_once = __cl_teardown_once_impl; \ void __cl_teardown_once_impl() \ void* __cl_spec( const char* name, __CLSetupType spec, __CLSpecEnv* env, __CLSetupType setup, __CLSetupType teardown, CLOptions options) { if (options & CL_OPTION_SERIAL) { if (!env->serial_pass) { return NULL; } } else if (env->serial_pass) { return NULL; } env->test_name = (char *) name; pthread_setspecific(__CLEnvKey, env); __cl_info("Executing SPEC => " __CL_FG(__CL_CYAN) __CL_BOLD "%s\n\n" __CL_RESET, name); double time_start = __cl_time(); if (!(options & CL_OPTION_SKIP_SETUP) && __cl_setup) { __cl_setup(); } if (setup) { setup(); } spec(); if (teardown) { teardown(); } if (!(options & CL_OPTION_SKIP_TEARDOWN) && __cl_teardown) { __cl_teardown(); } double elapsed = __cl_time() - time_start; size_t passed = env->num_passed_asserts; size_t failed = env->num_failed_asserts; size_t num_asserts = passed + failed; if (failed == 0) { __cl_pass("Passed SPEC in %.4f s -> " __CL_FG(__CL_GREEN) "%zu/%zu fail" __CL_RESET ", " __CL_FG(__CL_GREEN) "%zu/%zu pass" __CL_RESET "\n\n", elapsed, failed, num_asserts, passed, num_asserts); } else { env->failed = true; __cl_fail("Failed SPEC in %.4f s -> " __CL_FG(__CL_RED) "%zu/%zu fail" __CL_RESET ", " __CL_FG(__CL_RED) "%zu/%zu pass" __CL_RESET "\n\n", elapsed, failed, num_asserts, passed, num_asserts); } __cl_append("======================================================\n\n"); return NULL; } __CLSetupType __cl_fixture_CL_FIXTURE_NONE = NULL; /** * Define a custom fixture. */ #define CL_FIXTURE(name) void __cl_fixture_##name () /** * Call a fixture from any SPEC. */ #define CL_CALL_FIXTURE(name) \ __cl_fixture_##name() \ /** * Define a SPEC with custom fixtures and options. */ #define CL_SPEC_FIXTURE_OPTIONS(name, setup, teardown, options) \ void __cl_spec_##name (); \ void* name (__CLSpecEnv* env) { \ return __cl_spec(#name, __cl_spec_##name, env, \ __cl_fixture_##setup, \ __cl_fixture_##teardown, options); \ } \ void __cl_spec_##name () \ /** * Define a SPEC with options. */ #define CL_SPEC_OPTIONS(name, options) \ CL_SPEC_FIXTURE_OPTIONS(name, CL_FIXTURE_NONE, CL_FIXTURE_NONE, options) \ /** * Define a SPEC with custom fixtures. */ #define CL_SPEC_FIXTURE(name, setup, teardown) \ CL_SPEC_FIXTURE_OPTIONS(name, setup, teardown, CL_OPTION_NONE) \ /** * Define a SPEC. */ #define CL_SPEC(name) CL_SPEC_OPTIONS(name, CL_OPTION_NONE) void *__cl_do_work(void *ptr) { __CLWork *work = ptr; size_t index = 0; while (true) { pthread_mutex_lock(&work->lock); index = work->index; if (index == work->num_specs) { pthread_mutex_unlock(&work->lock); break; } work->index++; pthread_mutex_unlock(&work->lock); __CLSpecEnv *env = &work->envs[index]; if (!work->serial_pass) { __cl_env_init(env); } env->serial_pass = work->serial_pass; work->specs[index](env); } return NULL; } int __cl_main_parallel( int argc, char** argv, size_t num_threads, __CLSpecType* specs, size_t num_specs, const char* filename) { pthread_key_create(&__CLEnvKey, NULL); size_t i; size_t failed = 0; double time_start = __cl_time(); __cl_print(__CL_BOLD __CL_FG(__CL_CYAN) "[INFO] " __CL_RESET "Running BUNDLE: %s\n", filename); __cl_print(__CL_BOLD __CL_FG(__CL_CYAN) "[INFO] " __CL_RESET "Using %zu threads\n\n", num_threads); if (__cl_setup_once) { __cl_setup_once(); } pthread_t* threads = malloc(sizeof(pthread_t) * num_threads); __CLWork work = { .specs = specs, .envs = malloc(sizeof(__CLSpecEnv) * num_specs), .num_specs = num_specs, .index = 0, .serial_pass = false, }; pthread_mutex_init(&work.lock, NULL); for (i = 0; i < num_threads; i++) { pthread_create(&threads[i], NULL, __cl_do_work, &work); } for (i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } free(threads); work.index = 0; work.serial_pass = true; __cl_do_work(&work); pthread_mutex_destroy(&work.lock); for (i = 0; i < num_specs; i++) { __CLSpecEnv *env = &work.envs[i]; if (env->output_buffer) { fprintf(stderr, "%s", env->output_buffer); free(env->output_buffer); } if (env->failed) { failed++; } } free(work.envs); if (__cl_teardown_once) { __cl_teardown_once(); } size_t passed = num_specs - failed; double elapsed = __cl_time() - time_start; if (passed > 0 && failed == 0) { __cl_print(__CL_BOLD __CL_FG(__CL_GREEN) "[SUCCESS] " __CL_RESET); __cl_print(__CL_FG(__CL_GREEN) "%zu/%zu SPECS failed" __CL_RESET ", " __CL_FG(__CL_GREEN) "%zu/%zu SPECS passed" __CL_RESET " in %.4f s\n\n", failed, num_specs, passed, num_specs, elapsed); } else { __cl_print(__CL_BOLD __CL_FG(__CL_RED) "[FAILURE] " __CL_RESET); __cl_print(__CL_FG(__CL_RED) "%zu/%zu SPECS failed" __CL_RESET ", " __CL_FG(__CL_RED) "%zu/%zu SPECS passed" __CL_RESET " in %.4f s\n\n", failed, num_specs, passed, num_specs, elapsed); } return failed; } /** * Create a SPEC bundle with a custom job pool size. */ #define CL_BUNDLE_PARALLEL_JOBS(jobs, ...) \ int main(int argc, char** argv) { \ __CLSpecType specs[] = {__VA_ARGS__}; \ size_t num_specs = sizeof(specs) / sizeof(__CLSpecType); \ return __cl_main_parallel(argc, argv, (jobs), specs, num_specs, __FILE__); \ } \ /** * Create a SPEC bundle with a sane job pool size. */ #define CL_BUNDLE_PARALLEL(...) CL_BUNDLE_PARALLEL_JOBS(4, __VA_ARGS__) /** * Create a SPEC bundle with a job pool size of 1. */ #define CL_BUNDLE(...) CL_BUNDLE_PARALLEL_JOBS(1, __VA_ARGS__) #endif /* CHLORINE2 */
2.109375
2
2024-11-18T22:36:59.706765+00:00
2022-12-04T16:09:53
999781692b1fed70f1aa2c7b5d03543d452807cb
{ "blob_id": "999781692b1fed70f1aa2c7b5d03543d452807cb", "branch_name": "refs/heads/master", "committer_date": "2023-06-23T10:31:16", "content_id": "292940a89da3bbb080f698bd244a7317c078b886", "detected_licenses": [ "MIT" ], "directory_id": "4d7da853a34ac4371bf48d516b2a183a789afe63", "extension": "h", "filename": "log.h", "fork_events_count": 59, "gha_created_at": "2019-01-12T14:23:32", "gha_event_created_at": "2023-06-23T10:31:18", "gha_language": "C", "gha_license_id": "MIT", "github_id": 165396470, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 765, "license": "MIT", "license_type": "permissive", "path": "/log.h", "provenance": "stackv2-0107.json.gz:87549", "repo_name": "swaywm/swayidle", "revision_date": "2022-12-04T16:09:53", "revision_id": "61d653fb7a752910f71efb3e7d08d75b266cf3ea", "snapshot_id": "74d6b9c12e5a6a1ed889577e55feb9ac969b34e2", "src_encoding": "UTF-8", "star_events_count": 445, "url": "https://raw.githubusercontent.com/swaywm/swayidle/61d653fb7a752910f71efb3e7d08d75b266cf3ea/log.h", "visit_date": "2023-09-05T04:59:05.103942" }
stackv2
#ifndef _SWAYIDLE_LOG_H #define _SWAYIDLE_LOG_H #include <stdarg.h> #include <string.h> #include <errno.h> enum log_importance { LOG_SILENT = 0, LOG_ERROR = 1, LOG_INFO = 2, LOG_DEBUG = 3, LOG_IMPORTANCE_LAST, }; void swayidle_log_init(enum log_importance verbosity); #ifdef __GNUC__ #define _ATTRIB_PRINTF(start, end) __attribute__((format(printf, start, end))) #else #define _ATTRIB_PRINTF(start, end) #endif void _swayidle_log(enum log_importance verbosity, const char *format, ...) _ATTRIB_PRINTF(2, 3); #define swayidle_log(verb, fmt, ...) \ _swayidle_log(verb, "[Line %d] " fmt, __LINE__, ##__VA_ARGS__) #define swayidle_log_errno(verb, fmt, ...) \ swayidle_log(verb, fmt ": %s", ##__VA_ARGS__, strerror(errno)) #endif
2
2
2024-11-18T22:36:59.922884+00:00
2018-06-22T08:13:56
3c339fdf26c66b81700ae5847275a63e545472c5
{ "blob_id": "3c339fdf26c66b81700ae5847275a63e545472c5", "branch_name": "refs/heads/master", "committer_date": "2018-06-22T08:13:56", "content_id": "dc29bf425b40bd9370d10519c8992dd09a5d5f4e", "detected_licenses": [ "MIT" ], "directory_id": "b095b03fed35257501500b8dc440e637fc9961d2", "extension": "c", "filename": "usbd_storage_msd.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120990708, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3986, "license": "MIT", "license_type": "permissive", "path": "/code/wireless_brain/arch/m4/usb_port/usbd_storage_msd.c", "provenance": "stackv2-0107.json.gz:87805", "repo_name": "dh-linghaibin/wireless_plc", "revision_date": "2018-06-22T08:13:56", "revision_id": "8fa32241417958c6c709e376bb89832c1106d259", "snapshot_id": "4a98558b5e068f5d784f828197d61bcf76f15834", "src_encoding": "GB18030", "star_events_count": 2, "url": "https://raw.githubusercontent.com/dh-linghaibin/wireless_plc/8fa32241417958c6c709e376bb89832c1106d259/code/wireless_brain/arch/m4/usb_port/usbd_storage_msd.c", "visit_date": "2021-05-01T16:58:10.601932" }
stackv2
#include "usbd_msc_mem.h" #include "usb_conf.h" #include "w25qxx.h" //最大支持的设备数,2个 #define STORAGE_LUN_NBR 0 ////////////////////////////自己定义的一个标记USB状态的寄存器/////////////////// //bit0:表示电脑正在向SD卡写入数据 //bit1:表示电脑正从SD卡读出数据 //bit2:SD卡写数据错误标志位 //bit3:SD卡读数据错误标志位 //bit4:1,表示电脑有轮询操作(表明连接还保持着) vu8 USB_STATUS_REG=0; //////////////////////////////////////////////////////////////////////////////// //USB Mass storage 标准查询数据(每个lun占36字节) const int8_t STORAGE_Inquirydata[] = { /* LUN 0 SD卡 */ 0x00, 0x80, 0x02, 0x02, (USBD_STD_INQUIRY_LENGTH - 5), 0x00, 0x00, 0x00, 'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer : 8 bytes */ 'S', 'P', 'I', 'P', ' ', ' ', ' ', ' ', /* Product : 16 Bytes */ 'F', 'l', 'a', 's', 'h', ' ', ' ', ' ', '1', '.', '0' ,'0', /* Version : 4 Bytes */ }; int8_t STORAGE_Init (uint8_t lun); int8_t STORAGE_GetCapacity (uint8_t lun,uint32_t *block_num,uint32_t *block_size); int8_t STORAGE_IsReady (uint8_t lun); int8_t STORAGE_IsWriteProtected (uint8_t lun); int8_t STORAGE_Read (uint8_t lun,uint8_t *buf,uint32_t blk_addr,uint16_t blk_len); int8_t STORAGE_Write (uint8_t lun,uint8_t *buf,uint32_t blk_addr,uint16_t blk_len); int8_t STORAGE_GetMaxLun (void); //USB Device 用户回调函数接口 USBD_STORAGE_cb_TypeDef USBD_MICRO_SDIO_fops = { STORAGE_Init, STORAGE_GetCapacity, STORAGE_IsReady, STORAGE_IsWriteProtected, STORAGE_Read, STORAGE_Write, STORAGE_GetMaxLun, (int8_t *)STORAGE_Inquirydata, }; USBD_STORAGE_cb_TypeDef *USBD_STORAGE_fops=&USBD_MICRO_SDIO_fops;//指向USBD_MICRO_SDIO_fops结构体. //初始化存储设备 //lun:逻辑单元编号,0,SD卡;1,SPI FLASH //返回值:0,成功; // 其他,错误代码 int8_t STORAGE_Init (uint8_t lun) { return 0; } //获取存储设备的容量和块大小 //lun:逻辑单元编号,0,SD卡;1,SPI FLASH //block_num:块数量(扇区数) //block_size:块大小(扇区大小) //返回值:0,成功; // 其他,错误代码 int8_t STORAGE_GetCapacity (uint8_t lun, uint32_t *block_num, uint32_t *block_size) { *block_size=512; *block_num=1024*1024*12/512; //SPI FLASH的前面12M字节,文件系统用 //printf("size %d, %d",*block_size,*block_num); return 0; } //查看存储设备是否就绪 //lun:逻辑单元编号,0,SD卡;1,SPI FLASH //返回值:0,就绪; // 其他,未就绪 int8_t STORAGE_IsReady (uint8_t lun) { USB_STATUS_REG|=0X10;//标记轮询 return 0; } //查看存储设备是否写保护 //lun:逻辑单元编号,0,SD卡;1,SPI FLASH //返回值:0,没有写保护; // 其他,写保护(只读) int8_t STORAGE_IsWriteProtected (uint8_t lun) { return 0; } //从存储设备读取数据 //lun:逻辑单元编号,0,SD卡;1,SPI FLASH //buf:数据存储区首地址指针 //blk_addr:要读取的地址(扇区地址) //blk_len:要读取的块数(扇区数) //返回值:0,成功; // 其他,错误代码 int8_t STORAGE_Read (uint8_t lun,uint8_t *buf,uint32_t blk_addr,uint16_t blk_len) { int8_t res=0; USB_STATUS_REG|=0X02;//标记正在读数据 W25QXX_Read(buf,blk_addr*512,blk_len*512); return res; } //向存储设备写数据 //lun:逻辑单元编号,0,SD卡;1,SPI FLASH //buf:数据存储区首地址指针 //blk_addr:要写入的地址(扇区地址) //blk_len:要写入的块数(扇区数) //返回值:0,成功; // 其他,错误代码 int8_t STORAGE_Write (uint8_t lun,uint8_t *buf,uint32_t blk_addr,uint16_t blk_len) { int8_t res=0; USB_STATUS_REG|=0X01;//标记正在写数据 W25QXX_Write(buf,blk_addr*512,blk_len*512); return res; } //获取支持的最大逻辑单元个数 //返回值:支持的逻辑单元个数-1 int8_t STORAGE_GetMaxLun (void) { return (STORAGE_LUN_NBR - 1); }
2.328125
2
2024-11-18T22:37:00.368219+00:00
2021-01-29T07:09:02
ec404f5d8de4a8c5bbb45628a6afefca2e557bf2
{ "blob_id": "ec404f5d8de4a8c5bbb45628a6afefca2e557bf2", "branch_name": "refs/heads/master", "committer_date": "2021-01-29T07:09:02", "content_id": "e495140ad3fc0621677c0f800711644ad2088d37", "detected_licenses": [ "MIT" ], "directory_id": "d223f5f893c4173256eb8b94336f02ad2757459d", "extension": "c", "filename": "students_marks_sum.c", "fork_events_count": 0, "gha_created_at": "2020-12-30T07:20:35", "gha_event_created_at": "2021-01-29T07:09:03", "gha_language": null, "gha_license_id": "MIT", "github_id": 325483258, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1599, "license": "MIT", "license_type": "permissive", "path": "/HackerRank/C/students_marks_sum.c", "provenance": "stackv2-0107.json.gz:88063", "repo_name": "tanvipenumudy/Competitive-Programming-Solutions", "revision_date": "2021-01-29T07:09:02", "revision_id": "9619181d79b7a861bbc80eff8a796866880b95e0", "snapshot_id": "679c3f426bf0405447da373e27a2d956c6511989", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tanvipenumudy/Competitive-Programming-Solutions/9619181d79b7a861bbc80eff8a796866880b95e0/HackerRank/C/students_marks_sum.c", "visit_date": "2023-02-26T14:20:41.213055" }
stackv2
/* Complete the function, marks_summation(int* marks, char gender, int number_of_students) which returns the total sum of: 1. marks of boys if gender = b 2. marks of girls if gender = g The locked code stub reads the elements of marks along with gender. Then, it calls the function marks_summation(marks, gender, number_of_students) to get the sum of alternate elements as explained above and then prints the sum. */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> //Complete the following function. int marks_summation(int* marks, int n, char gender) { //Write your code here. int sum = 0; if (gender == 'b') { for(int i=0; i<n; i+=2) { sum += marks[i]; } } else { for(int i=1; i<n; i+=2) { sum += marks[i]; } } return sum; } int main() { int number_of_students; char gender; int sum; scanf("%d", &number_of_students); int *marks = (int *) malloc(number_of_students * sizeof (int)); for (int student = 0; student < number_of_students; student++) { scanf("%d", (marks + student)); } scanf(" %c", &gender); sum = marks_summation(marks, number_of_students, gender); printf("%d", sum); free(marks); return 0; } /* Sample Input 0 3 3 2 5 b Sample Output 0 8 Explanation 0 marks = [3, 2, 5] and gender = b. So,marks0 + marks2 = 3 + 5 = 8. Sample Input 1 5 1 2 3 4 5 g Sample Output 1 6 Explanation 1 marks = [1, 2, 3, 4, 5] and gender = g So, sum = marks1 + marks3 = 2 + 5 = 8. */
4.03125
4
2024-11-18T22:37:00.813786+00:00
2015-02-06T09:02:37
8c072d2931b1eaf21fb8cc7691f738f9a4df4f4d
{ "blob_id": "8c072d2931b1eaf21fb8cc7691f738f9a4df4f4d", "branch_name": "refs/heads/master", "committer_date": "2015-02-06T09:02:37", "content_id": "09428f2b26385333cc8aaa17b33475044a685c32", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "94d94af4917e337355cceb81251cd4e10e0bc077", "extension": "c", "filename": "CompressedResource.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": 4149, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Source/C/CompressedResource.c", "provenance": "stackv2-0107.json.gz:88192", "repo_name": "jjuran/JPEGView", "revision_date": "2015-02-06T09:02:37", "revision_id": "7a83a40c6cd987e483f2a242cb70e2b4194cea0c", "snapshot_id": "bee5756884a2629c453e301c4b5aa2c330c57e24", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/jjuran/JPEGView/7a83a40c6cd987e483f2a242cb70e2b4194cea0c/Source/C/CompressedResource.c", "visit_date": "2021-01-18T11:26:30.029708" }
stackv2
/*********************************************************/ /* This source code copyright (c) 1991-2001, Aaron Giles */ /* See the Read Me file for licensing information. */ /* Contact email: mac@aarongiles.com */ /*********************************************************/ #if THINK_C #include "THINK.Header" #elif applec #pragma load ":Headers:MPW.Header" #elif __MWERKS__ //#include "MW.Header" #else #include "JPEGView.h" #endif static void compress_decompress(uchar *src_adr, ulong src_len, uchar *dst_adr, ulong *p_dst_len); static void fast_copy(uchar *p_src,uchar *p_dst,ulong len); Handle GetCompResource(OSType theType, short theID) { long srcLen, dstLen; Handle srcHandle; srcHandle = GetResource(theType, theID); if (!srcHandle) return nil; srcLen = GetHandleSize(srcHandle); SetHandleSize(srcHandle, 32768L); if (MemError()) { ReleaseResource(srcHandle); return nil; } HLock(srcHandle); BlockMove(*srcHandle, (uchar *)*srcHandle + 32768L - srcLen, srcLen); compress_decompress((uchar *)*srcHandle + 32768L - srcLen, srcLen, (uchar *)*srcHandle, (ulong *)&dstLen); SetHandleSize(srcHandle, dstLen); HUnlock(srcHandle); return srcHandle; } //------------------------------------------------------------------------------ #define UBYTE unsigned char /* Unsigned byte */ #define UWORD unsigned int /* Unsigned word (2 bytes) */ #define ULONG unsigned long /* Unsigned word (4 bytes) */ #define BOOL unsigned char /* Boolean */ #define REAL double /* USed for floating point stuff. */ #define DONE_PORT /* Don't do all this again. */ #define MALLOC_FAIL NULL /* Failure status from malloc() */ #define LOCAL static /* For non-exported routines. */ #define EXPORT /* Signals exported function. */ #define then /* Useful for aligning ifs. */ #define FLAG_BYTES 4 /* How many bytes does the flag use up? */ #define FLAG_COMPRESS 0 /* Signals that output was result of compression. */ #define FLAG_COPY 1 /* Signals that output was simply copied over. */ #define GROUP_CMP 34 #define GROUP_RAW 288 #define CONTROL_INIT 0xFFFF8000 void fast_copy(UBYTE *p_src,UBYTE *p_dst,ULONG len) /* Fast copy routine. */ {while (len--) *p_dst++=*p_src++;} static void compress_decompress(uchar *p_src_first, ulong src_len, uchar *p_dst_first, ulong *p_dst_len) /* Input : Specify input block using p_src_first and src_len. */ /* Input : Point p_dst_first to the start of the output zone. */ /* Input : Point p_dst_len to a ULONG to receive the output length. */ /* Input : Input block and output zone must not overlap. User knows */ /* Input : upperbound on output block length from earlier compression. */ /* Input : In any case, maximum expansion possible is nine times. */ /* Output : Length of output block written to *p_dst_len. */ /* Output : Output block in Mem[p_dst_first..p_dst_first+*p_dst_len-1]. */ /* Output : Writes only in Mem[p_dst_first..p_dst_first+*p_dst_len-1]. */ { register UBYTE *p_src=p_src_first+FLAG_BYTES, *p_dst=p_dst_first; UBYTE *p_src_post=p_src_first+src_len; UBYTE *p_src_max16=p_src_first+src_len-(16*2); register ULONG control=1; if (*p_src_first==FLAG_COPY) {fast_copy(p_src_first+FLAG_BYTES,p_dst_first,src_len-FLAG_BYTES); *p_dst_len=src_len-FLAG_BYTES; return;} while (p_src!=p_src_post) {register UWORD unroll; if (control==1) {control=0x10000|*p_src++; control|=(*p_src++)<<8;} unroll= p_src<=p_src_max16 ? 16 : 1; while (unroll--) {if (control&1) {register UWORD lenmt; register UBYTE *p; lenmt=*p_src++; p=p_dst-(((lenmt&0xF0)<<4)|*p_src++); *p_dst++=*p++; *p_dst++=*p++; *p_dst++=*p++; lenmt&=0xF; while (lenmt--) *p_dst++=*p++;} else *p_dst++=*p_src++; control>>=1; } } *p_dst_len=p_dst-p_dst_first; }
2.03125
2
2024-11-18T22:37:00.995834+00:00
2017-02-01T18:22:23
52627430201bb9ab49f0a5425862039ca5a8f5ca
{ "blob_id": "52627430201bb9ab49f0a5425862039ca5a8f5ca", "branch_name": "refs/heads/master", "committer_date": "2017-02-01T18:22:23", "content_id": "23fe7a27a12828557caa71af686734e1a7eb5556", "detected_licenses": [ "MIT" ], "directory_id": "17629b76f4c97052ff5cbfae38405aa350613492", "extension": "c", "filename": "gennum.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 71114081, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 625, "license": "MIT", "license_type": "permissive", "path": "/6/gennum.c", "provenance": "stackv2-0107.json.gz:88322", "repo_name": "rgeorgiev583/sp-2016-2017", "revision_date": "2017-02-01T18:22:23", "revision_id": "a16e61268b80de07026cdabda05e38d412fb023c", "snapshot_id": "1088a6afb721cbce039c0f2765d060f0edca5c19", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rgeorgiev583/sp-2016-2017/a16e61268b80de07026cdabda05e38d412fb023c/6/gennum.c", "visit_date": "2021-05-04T01:03:38.254001" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #define MAX_LEN 10 int main(int argc, char** argv) { if (argc < 3) exit(1); int count_files = atoi(argv[1]), count_num = atoi(argv[2]), offset = 1; char count_num_str[MAX_LEN]; sprintf(count_num_str, "%d", count_num); for (int i = 0; i < count_files; i++) { char i_str[MAX_LEN], offset_str[MAX_LEN]; sprintf(i_str, "%d", i); sprintf(offset_str, "%d", offset); if (!fork()) execl("./helper", i_str, offset_str, count_num_str, NULL); offset += count_num; } return 0; }
2.375
2
2024-11-18T22:37:01.095498+00:00
2017-01-19T02:02:50
89c880a823596f992dd012e26094c131e6d92a8c
{ "blob_id": "89c880a823596f992dd012e26094c131e6d92a8c", "branch_name": "refs/heads/master", "committer_date": "2017-01-19T02:02:50", "content_id": "cb28bf5e7a2ebb393a851cd78d982f1a1d3aebf7", "detected_licenses": [ "PostgreSQL", "BSD-2-Clause" ], "directory_id": "4d5f2cdc0b7120f74ba6f357b21dac063e71b606", "extension": "c", "filename": "pg_logger.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79404002, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1968, "license": "PostgreSQL,BSD-2-Clause", "license_type": "permissive", "path": "/postgresql/contrib/pg_logger/pg_logger.c", "provenance": "stackv2-0107.json.gz:88581", "repo_name": "anjingbin/starccm", "revision_date": "2017-01-19T02:02:50", "revision_id": "70db48004aa20bbb82cc24de80802b40c7024eff", "snapshot_id": "cf499238ceb1e4f0235421cb6f3cb823b932a2cd", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/anjingbin/starccm/70db48004aa20bbb82cc24de80802b40c7024eff/postgresql/contrib/pg_logger/pg_logger.c", "visit_date": "2021-01-11T19:49:04.306906" }
stackv2
/* pg_logger: stdin-to-syslog gateway for postgresql. * * Copyright 2001 by Nathan Myers <ncm@nospam.cantrip.org> * This software is distributed free of charge with no warranty of any kind. * You have permission to make copies for any purpose, provided that (1) * this copyright notice is retained unchanged, and (2) you agree to * absolve the author of all responsibility for all consequences arising * from any use. */ #include <stdio.h> #include <stddef.h> #include <syslog.h> #include <string.h> struct { const char *tag; int size; int priority; } tags[] = { { "", 0, LOG_NOTICE }, { "emerg:", sizeof("emerg"), LOG_EMERG }, { "alert:", sizeof("alert"), LOG_ALERT }, { "crit:", sizeof("crit"), LOG_CRIT }, { "err:", sizeof("err"), LOG_ERR }, { "error:", sizeof("error"), LOG_ERR }, { "warning:", sizeof("warning"), LOG_WARNING }, { "notice:", sizeof("notice"), LOG_NOTICE }, { "info:", sizeof("info"), LOG_INFO }, { "debug:", sizeof("debug"), LOG_DEBUG } }; int main() { char buf[301]; int c; char *pos = buf; const char *colon = 0; #ifndef DEBUG openlog("postgresql", LOG_CONS, LOG_LOCAL1); #endif while ((c = getchar()) != EOF) { if (c == '\r') continue; if (c == '\n') { int level = sizeof(tags) / sizeof(*tags); char *bol; if (colon == 0 || (size_t) (colon - buf) > sizeof("warning")) level = 1; *pos = 0; while (--level) { if (pos - buf >= tags[level].size && strncmp(buf, tags[level].tag, tags[level].size) == 0) break; } bol = buf + tags[level].size; if (bol > buf && *bol == ' ') ++bol; if (pos - bol > 0) { #ifndef DEBUG syslog(tags[level].priority, "%s", bol); #else printf("%d/%s\n", tags[level].priority, bol); #endif } pos = buf; colon = (char const *) 0; continue; } if (c == ':' && !colon) colon = pos; if ((size_t) (pos - buf) < sizeof(buf) - 1) *pos++ = c; } return 0; }
2.453125
2
2024-11-18T22:37:02.058716+00:00
2019-05-10T11:47:18
e9aec6c0f81666851bdc49310b9d2c586e8e5f49
{ "blob_id": "e9aec6c0f81666851bdc49310b9d2c586e8e5f49", "branch_name": "refs/heads/master", "committer_date": "2019-11-07T14:44:27", "content_id": "2bbf0e76a709d8df02e5f3bf943b0a7873c1b14d", "detected_licenses": [ "MIT" ], "directory_id": "cc4068055b4b1dd359641cf8b54a6d3e6fe7d2f3", "extension": "c", "filename": "bench_ak_ecb_aes.c", "fork_events_count": 1, "gha_created_at": "2019-02-07T09:43:08", "gha_event_created_at": "2019-11-07T14:44:29", "gha_language": "C", "gha_license_id": "MIT", "github_id": 169548889, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3262, "license": "MIT", "license_type": "permissive", "path": "/sandbox/bench_AES/src/bench_ak_ecb_aes.c", "provenance": "stackv2-0107.json.gz:89096", "repo_name": "pedagand/PSAR-crypto-kernel", "revision_date": "2019-05-10T11:47:18", "revision_id": "06083b1d2bd51251d062f13c5294cb188dd86e5e", "snapshot_id": "6233dcb125aa0e1deb40d51c859a5abf4388bf1e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pedagand/PSAR-crypto-kernel/06083b1d2bd51251d062f13c5294cb188dd86e5e/sandbox/bench_AES/src/bench_ak_ecb_aes.c", "visit_date": "2020-04-21T12:01:48.145488" }
stackv2
#include <kcapi.h> #include <time.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define TEST_COUNT 5 #define SECONDS 1 int test=0; int test_async(uint8_t key_length,const char* ciphername){ //init handle struct kcapi_handle *handle1; if(kcapi_cipher_init(&handle1,ciphername,KCAPI_INIT_AIO)){ perror("kcapi_cipher_init "); return 1; } //init key uint8_t* key= ( uint8_t *)malloc(key_length * sizeof(uint8_t)); if(!key){ perror("malloc key"); kcapi_cipher_destroy(handle1); return 1; } if((kcapi_rng_get_bytes(key, (uint32_t) key_length)) != key_length ){ perror("kcapi_rng_get_bytes") ; kcapi_cipher_destroy(handle1); return 1; } if(kcapi_cipher_setkey(handle1,key,key_length)){ perror("kcapi_cipher_setkey") ; kcapi_cipher_destroy(handle1); return 1; } free(key); //init input iovecs struct iovec input16={NULL,16},input64={NULL,64},input256={NULL,256},input1024={NULL,1024},input8192={NULL,8192}; struct iovec inIOVecs[TEST_COUNT]={input16,input64,input256,input1024,input8192}; for(int i=0;i<TEST_COUNT;++i){ inIOVecs[i].iov_base=malloc(inIOVecs[i].iov_len*sizeof(uint8_t)); if(!inIOVecs[i].iov_base){ for(int j=0;j<i;++j) free(inIOVecs[j].iov_base); kcapi_cipher_destroy(handle1); return 1; } } //init iv uint32_t ivsize= kcapi_cipher_ivsize(handle1); uint8_t iv [ivsize]; if((kcapi_rng_get_bytes((uint8_t*)&iv, (uint32_t) ivsize)) != ivsize ){ perror("generating IV not successful") ; kcapi_cipher_destroy(handle1); return 1; } for(int i = 0 ; i< TEST_COUNT; i++){ //init iovecs if((kcapi_rng_get_bytes((uint8_t*)(inIOVecs[i].iov_base), (uint32_t) inIOVecs[i].iov_len)) != inIOVecs[i].iov_len ){ perror("generating input iovec failed "); kcapi_cipher_destroy(handle1); return 1; } clock_t start,finish,now; long ciphered,total_ciphered=0; long operations=0; start=clock(); now=clock(); finish=start+SECONDS*CLOCKS_PER_SEC; while ((finish-now)>0){ ciphered = kcapi_cipher_encrypt_aio(handle1,&inIOVecs[i],&inIOVecs[i],1,iv,KCAPI_ACCESS_HEURISTIC); if(ciphered!= inIOVecs[i].iov_len){ perror("kcapi_cipher_encrypt_aio"); printf("cipher failed ! expected %zu ciphered= %ld\n", inIOVecs[i].iov_len,ciphered); kcapi_cipher_destroy(handle1); return 1; } total_ciphered+=ciphered; operations++; now=clock(); } printf("test %d (%d bit key, %zu byte blocks): %li operations in %d seconds (%li bytes)\n",test,key_length*8,inIOVecs[i].iov_len,operations, SECONDS,total_ciphered); test++; } for(int i=0;i<TEST_COUNT;++i){ free(inIOVecs[i].iov_base); } kcapi_cipher_destroy(handle1); return 0; } int main(int argc, char const *argv[]) { test_async(16,"ecb(aes)"); test_async(24,"ecb(aes)"); test_async(32,"ecb(aes)"); return 0; }
2.59375
3
2024-11-18T22:37:02.284040+00:00
2023-08-31T11:13:23
4e526fed68baf2cf02ecc7afcddd469a6d3458d6
{ "blob_id": "4e526fed68baf2cf02ecc7afcddd469a6d3458d6", "branch_name": "refs/heads/master", "committer_date": "2023-08-31T11:13:23", "content_id": "33cfec6d8bf9179a52cdfb2aa1e7452caebd5fe7", "detected_licenses": [ "MIT" ], "directory_id": "549270020f6c8724e2ef1b12e38d11b025579f8d", "extension": "c", "filename": "test_package.c", "fork_events_count": 1820, "gha_created_at": "2019-08-27T09:43:58", "gha_event_created_at": "2023-09-14T21:22:42", "gha_language": "Python", "gha_license_id": "MIT", "github_id": 204671232, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 865, "license": "MIT", "license_type": "permissive", "path": "/recipes/libdwarf/all/test_package/test_package.c", "provenance": "stackv2-0107.json.gz:89354", "repo_name": "conan-io/conan-center-index", "revision_date": "2023-08-31T11:13:23", "revision_id": "3b17e69bb4e5601a850b6e006e44775e690bac33", "snapshot_id": "1bcec065ccd65aa38b1fed93fbd94d9d5fe6bc43", "src_encoding": "UTF-8", "star_events_count": 844, "url": "https://raw.githubusercontent.com/conan-io/conan-center-index/3b17e69bb4e5601a850b6e006e44775e690bac33/recipes/libdwarf/all/test_package/test_package.c", "visit_date": "2023-08-31T11:34:45.403978" }
stackv2
#include <stdint.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #ifndef LIBDWARF_NEW_STRUCTURE #include "dwarf.h" #include "libdwarf.h" #else #include "libdwarf/libdwarf.h" #endif void example1(Dwarf_Die somedie) { Dwarf_Debug dbg = 0; Dwarf_Signed atcount; Dwarf_Attribute *atlist; Dwarf_Error error = 0; Dwarf_Signed i = 0; int errv; errv = dwarf_attrlist(somedie, &atlist, &atcount, &error); if (errv == DW_DLV_OK) { for (i = 0; i < atcount; ++i) { dwarf_dealloc(dbg, atlist[i], DW_DLA_ATTR); } dwarf_dealloc(dbg, atlist, DW_DLA_LIST); } else if(errv == DW_DLV_ERROR){ dwarf_dealloc(dbg, error, DW_DLA_ERROR); } } int main(void){ Dwarf_Die somedie; memset(&somedie, 0, sizeof(somedie)); example1(somedie); return EXIT_SUCCESS; }
2.109375
2
2024-11-18T22:37:02.406887+00:00
2020-06-28T17:18:49
06c585f53df16bb5fb0554bf7ee03a2a76f57bbc
{ "blob_id": "06c585f53df16bb5fb0554bf7ee03a2a76f57bbc", "branch_name": "refs/heads/master", "committer_date": "2020-06-28T17:18:49", "content_id": "acc4fae9c532b555433201627ac7735f8db0e86b", "detected_licenses": [ "MIT" ], "directory_id": "75f10d4042ea53b419d2df1a7f568b93144de294", "extension": "c", "filename": "debugger.c", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 273945421, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5958, "license": "MIT", "license_type": "permissive", "path": "/asmgolf/debugger.c", "provenance": "stackv2-0107.json.gz:89484", "repo_name": "TrungNguyen1909/HSGSSec2020Challs", "revision_date": "2020-06-28T17:18:49", "revision_id": "f2e81c4ce81822b1f89d1c70836f831e2ebe9321", "snapshot_id": "d6554e64ee38b7220add590d4088e36f37cae8a3", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/TrungNguyen1909/HSGSSec2020Challs/f2e81c4ce81822b1f89d1c70836f831e2ebe9321/asmgolf/debugger.c", "visit_date": "2022-11-06T08:41:30.061417" }
stackv2
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <keystone/keystone.h> #include <unicorn/unicorn.h> #include "emu.h" #include <capstone/capstone.h> #define ADDRESS 0x1000000 csh handle; static void hook_code64(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) { uint64_t rip; uc_reg_read(uc, UC_X86_REG_RIP, &rip); printf(">>> Tracing instruction at %p, instruction size = 0x%x\n", address, size); cs_insn *insn; size_t count; char* buffer = calloc(1, size+1); if(uc_mem_read(uc, address, buffer, size)){ fprintf(stderr, "Failed to read memory at instruction."); abort(); } count = cs_disasm(handle, buffer, size, address, 0, &insn); if (count > 0) { size_t j; for (j = 0; j < count; j++) { printf("%p:\t%s\t\t%s\n", insn[j].address, insn[j].mnemonic, insn[j].op_str); } cs_free(insn, count); } else { fprintf(stderr, "ERROR: Failed to disassemble given code!\n"); } register_state_t result = calloc(1, sizeof(struct register_state)); void* ptr[regs_nums]; for(int i=0;i<regs_nums;i++){ ptr[i] = &result->regs[i]; } uc_reg_read_batch(uc, regs, ptr, regs_nums); // now print out some registers fprintf(stderr, ">>> Emulation Paused.\n"); for(int i=0;i<regs_nums;i++) printf("%s = 0x%lx\n", reg_names[i], result->regs[i]); free(result); char c = 0; fprintf(stderr, ">> "); while(1){ scanf("%c",&c); if(c=='s'||c=='S') break; } } register_state_t start_emulation(unsigned char* asmbuf,size_t size, register_state_t init_regs){ uc_engine *uc; uc_err err; uc_hook trace2; fprintf(stderr, "Starting emulation...\n"); err = uc_open(UC_ARCH_X86, UC_MODE_64, &uc); uc_hook_add(uc, &trace2, UC_HOOK_CODE, hook_code64, NULL, 1, 0); if(err!=UC_ERR_OK){ fprintf(stderr, "Failed uc_open(): %d, %s\n", err,uc_strerror(err)); exit(3); } //Alignment size_t executable_size = size; executable_size &=((-1ULL)<<12); executable_size += (1LL<<12); //Map binary uc_mem_map(uc, ADDRESS, executable_size, UC_PROT_ALL); uc_mem_write(uc, ADDRESS, asmbuf, size); //Map stack int64_t stack_top = ((int64_t)(&uc)&((-1ULL<<12))); uc_mem_map(uc, stack_top, 0x20000, UC_PROT_ALL); int64_t rsp = stack_top + 0x20000 - (1ULL<<12); //Initailize registers void* ptr[regs_nums]; for(int i=0;i<regs_nums;i++){ ptr[i] = &init_regs->regs[i]; } uc_reg_write_batch(uc, regs, ptr, regs_nums); if(!init_regs->nostack){ uc_reg_write(uc, UC_X86_REG_RSP, &rsp); uc_reg_write(uc, UC_X86_REG_RBP, &rsp); } err = uc_emu_start(uc, ADDRESS, ADDRESS + size - 1, 0, 0);//0.5 seconds timeout if (err!=UC_ERR_OK) { fprintf(stderr,"Failed on uc_emu_start() with error returned %u: %s\n", err, uc_strerror(err)); exit(4); } register_state_t result = calloc(1, sizeof(struct register_state)); for(int i=0;i<regs_nums;i++){ ptr[i] = &result->regs[i]; } uc_reg_read_batch(uc, regs, ptr, regs_nums); // now print out some registers fprintf(stderr, ">>> Emulation done.\n"); for(int i=0;i<regs_nums;i++) printf("%s = 0x%lx\n", reg_names[i], result->regs[i]); uc_close(uc); return result; } register_state_t parse_init_regs(){ char reg[8]; int64_t reg_value = 0; memset(reg,0,sizeof(reg)); register_state_t result = calloc(1, sizeof(struct register_state)); while(scanf("%4s = %lx\n",reg,&reg_value)==2){ for(int i=0;i<sizeof(reg_names)/sizeof(long);i++) if(strncasecmp(reg, reg_names[i], strlen(reg))==0){ result->regs[i] = reg_value; break; } memset(reg,0,sizeof(reg)); reg_value = 0; } return result; } register_state_t parse_regs_from_file(const char* path){ FILE* fd = fopen(path, "r"); char reg[8]; int64_t reg_value = 0; memset(reg,0,sizeof(reg)); register_state_t result = (register_state_t)calloc(1, sizeof(struct register_state)); while(fscanf(fd, "%4s = %llx\n",reg,&reg_value)==2){ for(int i=0;i<regs_nums;i++) if(strncasecmp(reg, reg_names[i], strlen(reg))==0){ result->regs[i] = reg_value; break; } memset(reg,0,sizeof(reg)); reg_value = 0; } fclose(fd); return result; } double score_registers_from_file(register_state_t state, const char* path){ FILE* fd = fopen(path, "r"); char reg[8]; int64_t reg_value = 0; memset(reg,0,sizeof(reg)); long count = 0; long correct = 0; register_state_t result = calloc(1, sizeof(struct register_state)); while(fscanf(fd,"%4s = %lx\n",reg,&reg_value)==2){ for(int i=0;i<sizeof(reg_names)/sizeof(long);i++) if(strncasecmp(reg, reg_names[i], strlen(reg))==0){ correct += (reg_value == state->regs[i]?1:0); count ++; break; } memset(reg,0,sizeof(reg)); reg_value = 0; } fclose(fd); if(count==0) return 0; else return (double)correct/(double)count; } int main(int argc, char *argv[]) { ks_engine *ks; ks_err err; size_t count; unsigned char *asmbuf; size_t size; if(argc<3){ fprintf(stderr, "%s code.s reg.init\n", argv[0]); abort(); } int fd = open(argv[1],O_RDONLY); struct stat* fs = calloc(1, sizeof(struct stat)); fstat(fd, fs); off_t fsize = fs->st_size; char* inbuf = calloc(1, fsize+1); assert(inbuf!=0); lseek(0, 0, SEEK_SET); read(fd, inbuf, fsize); puts(inbuf); close(fd); fprintf(stderr, "Compiling..."); err = ks_open(KS_ARCH_X86, KS_MODE_64, &ks); if(err!=KS_ERR_OK){ fprintf(stderr, "Failed to open keystone engine"); exit(1); } if(ks_asm(ks, inbuf, ADDRESS, &asmbuf, &size, &count)!=KS_ERR_OK){ fprintf(stderr, "ERROR: ks_asm() failed & count = %lu, error = %u\n", count, ks_errno(ks)); exit(2); } fprintf(stderr, "Compiled: %lu bytes, statements: %lu\n", size, count); if (cs_open(CS_ARCH_X86, CS_MODE_64, &handle) != CS_ERR_OK) { fprintf(stderr, "Failed to open capstone engine."); abort(); } register_state_t init_regs = parse_regs_from_file(argv[2]); register_state_t result_regs = start_emulation(asmbuf,size,init_regs); free(init_regs); free(result_regs); ks_free(asmbuf); ks_close(ks); }
2.34375
2
2024-11-18T22:37:02.538433+00:00
2013-09-23T20:10:32
4a7cc36f2c2fcb6ba9539caca017fa12aa764eac
{ "blob_id": "4a7cc36f2c2fcb6ba9539caca017fa12aa764eac", "branch_name": "refs/heads/master", "committer_date": "2013-09-23T20:10:32", "content_id": "192881e43a593e94df6aec861c3db65dee5d98fb", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "4ecd9ef08adb9e5d35db012d14a3a8399376d050", "extension": "c", "filename": "socketcan.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": 2729, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/epos2/socketcan/socketcan.c", "provenance": "stackv2-0107.json.gz:89614", "repo_name": "reneulab/ReNeu_Lab", "revision_date": "2013-09-23T20:10:32", "revision_id": "9e92f3780f1f8eed1ed2604f1d9c2ff1ddecb2af", "snapshot_id": "62ec9aefe4f16d9dd8761267f53bb729b31394cb", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/reneulab/ReNeu_Lab/9e92f3780f1f8eed1ed2604f1d9c2ff1ddecb2af/epos2/socketcan/socketcan.c", "visit_date": "2021-01-20T23:26:38.028965" }
stackv2
#include "socketcan.h" #include "printd.h" #include <string.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <poll.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <linux/can.h> #include <linux/can/raw.h> /* #ifndef AF_CAN #define AF_CAN PF_CAN #endif */ /*int32_t socketcan_open(uint16_t filter[], uint16_t filtermask[], uint16_t num_filters) { NTCAN_HANDLE handle = -1; // Create the socket handle = socket( PF_CAN, SOCK_RAW, CAN_RAW ); if(handle == -1) { printd(LOG_ERROR, "socketcan: Error opening socket\n"); return handle; } // Locate the interface you wish to use struct ifreq ifr; strcpy(ifr.ifr_name, "can0"); ioctl(handle, SIOCGIFINDEX, &ifr); // ifr.ifr_ifindex gets filled with that device's index // Set Filter for this conection struct can_filter rfilter[num_filters]; for(int i=0; i<num_filters; i++) { rfilter[i].can_id = filter[i]; rfilter[i].can_mask = filtermask[i]; } setsockopt(handle, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)); // Select that CAN interface, and bind the socket to it. struct sockaddr_can addr; addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; bind(handle, (struct sockaddr*)&addr, sizeof(addr)); // Set to non blocking fcntl(handle, F_SETFL, O_NONBLOCK); return handle; } */ void socketcan_close(NTCAN_HANDLE handle) { canClose(handle); } int32_t socketcan_read(NTCAN_HANDLE handle, CMSG* frame, int32_t timeout) { // Wait for data or timeout int32_t t; int32_t len; struct pollfd p[1]; NTCAN_RESULT result; p[0].fd = handle; p[0].events = POLLIN; t = poll(p, 1, timeout); len = frame->len; // Try to read available data result = canRead(handle, frame, &len, NULL); if(result != 0) { // Error, no bytes read frame->id = 0; frame->len = 0; if (result == NTCAN_RX_TIMEOUT) { return SOCKETCAN_TIMEOUT; } //printd(LOG_ERROR, "socketcan: Could not read data from CAN-bus\n"); return SOCKETCAN_ERROR; } return 0; } int32_t socketcan_write(NTCAN_HANDLE handle, uint16_t id, uint8_t length, Socketcan_t data[]) { NTCAN_RESULT result; uint8_t byte, n; CMSG frame; int32_t temp=0; frame.id = id; byte = 0; for(int i=0; i<length; i++) { n = 0; while(n < data[i].size) { frame.data[byte] = (data[i].data >> 8*n); n++; byte++; } } temp = (int32_t) frame.len; frame.len = byte; result = canWrite(handle, &frame, &temp, NULL); if(result != 0) { // Error, no data written printd(LOG_ERROR, "socketcan: Could not write data to CAN-bus\n"); return SOCKETCAN_ERROR; } return 0; }
2.46875
2
2024-11-18T22:37:02.603174+00:00
2016-05-18T19:42:46
f71ea97816a7a8cf1aabdbdd0174dda881da8e53
{ "blob_id": "f71ea97816a7a8cf1aabdbdd0174dda881da8e53", "branch_name": "refs/heads/master", "committer_date": "2016-05-18T19:42:46", "content_id": "048236994a32f08e694b7aa30e9d448ea33df4d4", "detected_licenses": [ "MIT" ], "directory_id": "de6604045fb627b86b6bb03c9f99fc69ed01a954", "extension": "c", "filename": "ora_month.c", "fork_events_count": 3, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 59128508, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 653, "license": "MIT", "license_type": "permissive", "path": "/ora/DATETIME/ora_month.c", "provenance": "stackv2-0107.json.gz:89745", "repo_name": "sfaroult/sqlite_libs", "revision_date": "2016-05-18T19:42:46", "revision_id": "c9d3937ce1756eab4c8d9dab5aede889393830e8", "snapshot_id": "a522433a39c6352c2fcc11f6d7369face2f600f8", "src_encoding": "UTF-8", "star_events_count": 7, "url": "https://raw.githubusercontent.com/sfaroult/sqlite_libs/c9d3937ce1756eab4c8d9dab5aede889393830e8/ora/DATETIME/ora_month.c", "visit_date": "2016-09-14T08:26:24.877481" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ksu_common.h> extern void ora_month(sqlite3_context * context, int argc, sqlite3_value ** argv) { char *arg1; int y; int m; if (ksu_prm_ok(context, argc, argv, "month", KSU_PRM_DATETIME)) { arg1 = (char *)sqlite3_value_text(argv[0]); if (2 == sscanf(arg1, "%d-%d", &y, &m)) { sqlite3_result_int(context, m); } else { // Should not happen ksu_err_msg(context, KSU_ERR_INV_DATE, arg1, "month"); } } }
2
2
2024-11-18T22:37:02.659019+00:00
2017-03-11T11:09:43
751c0cdc29dfd588e6a6e25f46422dc945e88c9b
{ "blob_id": "751c0cdc29dfd588e6a6e25f46422dc945e88c9b", "branch_name": "refs/heads/master", "committer_date": "2017-03-11T11:09:43", "content_id": "8dbb0a69c5993302ff1dfb769e710d874cfc2a24", "detected_licenses": [ "MIT" ], "directory_id": "838a078bd8b496af74f849914542ac57f7dd4e33", "extension": "c", "filename": "WCTrieTree.c", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 78925339, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9743, "license": "MIT", "license_type": "permissive", "path": "/src/WCTrieTree.c", "provenance": "stackv2-0107.json.gz:89873", "repo_name": "BlackDragonF/WordCounter", "revision_date": "2017-03-11T11:09:43", "revision_id": "816291bb127244200e3c365bae590ec44ba503ce", "snapshot_id": "3a6be13fd177ac4635a196ab67fc3038d1b8f11d", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/BlackDragonF/WordCounter/816291bb127244200e3c365bae590ec44ba503ce/src/WCTrieTree.c", "visit_date": "2021-03-27T10:19:13.474851" }
stackv2
#include "WCTrieTree.h" /* macro definition */ #define MAX_CHARACTER_NUMBER (26) /* struct definition */ struct WCTrieNode { char character; struct WCTrieNode * child[MAX_CHARACTER_NUMBER]; WCIndex * index; }; struct WCTrieTree { struct WCTrieNode * root; int count; int unique; }; /* turn character into index */ static inline int wc_chararcter_index_convert(char character) { return tolower(character) - 'a'; } /* recursively free WCTrieNode */ static void wc_trie_node_destroy(struct WCTrieNode * node) { int index; for (index = 0 ; index < MAX_CHARACTER_NUMBER ; ++index) { if (node->child[index] != NULL) { wc_trie_node_destroy(node->child[index]); } } if (node->index != NULL) { WCError internalError; wc_index_destroy(node->index, &internalError); if (internalError != WCNoneError) { exit(internalError); } } free(node); } /* construct a WCTrieTree struct */ WCTrieTree * wc_trie_tree_create(WCError * error) { WCTrieTree * tree = malloc(sizeof(WCTrieTree)); if (tree == NULL) { *error = WCMemoryOverflowError; return NULL; } tree->root = malloc(sizeof(struct WCTrieNode)); if (tree->root == NULL) { *error = WCMemoryOverflowError; free(tree); return NULL; } tree->root->character = '\0'; memset(tree->root->child, 0, sizeof(struct WCTrieNode *) * MAX_CHARACTER_NUMBER); tree->root->index = NULL; tree->count = 0; tree->unique = 0; *error = WCNoneError; return tree; } /* destruct a WCTrieTree struct */ void wc_trie_tree_destroy(WCTrieTree * tree, WCError * error) { printf("%d\n", tree->count); if (tree == NULL) { *error = WCNullPointerError; return; } wc_trie_node_destroy(tree->root); free(tree); *error = WCNoneError; } /* insert a word into trie tree */ void wc_trie_tree_insert_word(WCTrieTree * tree, WCWord * word, WCError * error) { if (tree == NULL || word == NULL) { *error = WCNullPointerError; return; } WCError internalError; tree->count++; const char * wordPtr = wc_word_get_word(word, &internalError); if (internalError != WCNoneError) { exit(internalError); } int index; struct WCTrieNode * node = tree->root; while (*wordPtr) { index = wc_chararcter_index_convert(*wordPtr); if (node->child[index] == NULL) { struct WCTrieNode * temp = malloc(sizeof(struct WCTrieNode)); temp->character = *wordPtr; memset(temp->child, 0, sizeof(struct WCTrieNode *) * MAX_CHARACTER_NUMBER); temp->index = NULL; node->child[index] = temp; } node = node->child[index]; wordPtr++; } if (node->index == NULL) { node->index = wc_index_create(&internalError); if (internalError != WCNoneError) { exit(internalError); } tree->unique++; } WCWordInfo info = wc_word_get_info(word, &internalError); if (internalError != WCNoneError) { exit(internalError); } wc_index_add(node->index, info, &internalError); if (internalError != WCNoneError) { exit(internalError); } *error = WCNoneError; } /* recursively search a word in trie tree */ static struct WCTrieNode * wc_trie_tree_search_node(WCTrieTree * tree, WCWord * word, WCError * error) { if (tree == NULL || word == NULL) { *error = WCNullPointerError; return NULL; } WCError internalError; const char * wordPtr = wc_word_get_word(word, &internalError); if (internalError != WCNoneError) { exit(internalError); } int index; struct WCTrieNode * node = tree->root; while (*wordPtr) { index = wc_chararcter_index_convert(*wordPtr); if (node->child[index] == NULL) { *error = WCNoneError; return NULL; } node = node->child[index]; wordPtr++; } *error = WCNoneError; return node; } /* search a word in trie tree */ WCIndex * wc_trie_tree_search_word(WCTrieTree * tree, WCWord * word, WCError * error) { if (tree == NULL || word == NULL) { *error = WCNullPointerError; return NULL; } WCError internalError; struct WCTrieNode * node = wc_trie_tree_search_node(tree, word, &internalError); if (internalError != WCNoneError) { exit(internalError); } *error = WCNoneError; if (node != NULL) { return node->index; } else { return NULL; } } /* delete a word in trie tree */ void wc_trie_tree_delete_word(WCTrieTree * tree, WCWord * word, WCError * error) { if (tree == NULL || word == NULL) { *error = WCNullPointerError; return; } WCError internalError; struct WCTrieNode * node = wc_trie_tree_search_node(tree, word, &internalError); if (internalError != WCNoneError) { exit(internalError); } WCIndex * index = node->index; int count = wc_index_get_count(index, &internalError); if (internalError != WCNoneError) { exit(internalError); } tree->count -= count; wc_index_destroy(index, &internalError); if (internalError != WCNoneError) { exit(internalError); } node->index = NULL; *error = WCNoneError; } /* recursively traverse a trie tree */ static void wc_trie_tree_traverse_recursively(struct WCTrieNode * node, WCWord * word, WCTrieTreeTraverseResult * result, int * result_index) { int index; WCError internalError; if (node == NULL) { return; } if (node->index != NULL) { int length = wc_word_get_length(word, &internalError); if (internalError != WCNoneError) { exit(internalError); } const char * wordPtr = wc_word_get_word(word, &internalError); if (internalError != WCNoneError) { exit(internalError); } (result->words)[*result_index] = malloc(sizeof(char) * (length + 1)); if ((result->words)[*result_index] == NULL) { exit(WCMemoryOverflowError); } strcpy((result->words)[*result_index], wordPtr); WCIndexIterator * iterator = wc_index_iterator_create(node->index, &internalError); if (internalError != WCNoneError) { exit(internalError); } do { WCWordInfo info = wc_index_iterator_get_value(iterator, &internalError); if (internalError != WCNoneError) { exit(internalError); } (result->info)[*result_index] = info; (*result_index)++; } while (wc_index_iterator_next(iterator, &internalError), internalError != WCIndexRangeError); wc_index_iterator_destroy(iterator, &internalError); if (internalError != WCNoneError) { exit(internalError); } } for (index = 0 ; index < 26 ; ++index) { if (node->child[index] != NULL) { wc_character_expand(word, node->child[index]->character, &internalError); if(internalError != WCNoneError) { exit(internalError); } wc_trie_tree_traverse_recursively((node->child)[index], word, result, result_index); } } wc_character_shrink(word, &internalError); if(internalError != WCNoneError) { exit(internalError); } } /* traverse a trie tree */ WCTrieTreeTraverseResult * wc_trie_tree_traverse(WCTrieTree * tree, WCError * error) { if (tree == NULL) { *error = WCNullPointerError; return NULL; } WCTrieTreeTraverseResult * result = malloc(sizeof(WCTrieTreeTraverseResult)); if (result == NULL) { *error = WCMemoryOverflowError; return NULL; } WCError internalError; result->count = tree->count; result->info = malloc(sizeof(WCWordInfo) * result->count); if (result->info == NULL) { *error = WCMemoryOverflowError; free(result); return NULL; } result->words = malloc(sizeof(char *) * result->count); if (result->words == NULL) { *error = WCMemoryOverflowError; free(result->info); free(result); return NULL; } WCWord * word = wc_word_create(WC_DEFAULT_WORD_LENGTH, &internalError); if (internalError != WCNoneError) { exit(internalError); } int index = 0; wc_trie_tree_traverse_recursively(tree->root, word, result, &index); wc_word_destroy(word, &internalError); if (internalError != WCNoneError) { exit(internalError); } *error = WCNoneError; return result; } /* destruct the WCTrieTreeTraverseResult constructed by traverse operation */ void wc_trie_tree_traverse_result_destroy(WCTrieTreeTraverseResult * result, WCError * error) { if (result == NULL) { *error = WCNullPointerError; return; } free(result->info); int index; for (index = 0 ; index < result->count ; ++index) { if ((result->words)[index] != NULL) { free((result->words)[index]); } } free(result->words); free(result); *error = WCNoneError; } /* get count from given WCTrieTree struct */ int wc_trie_tree_get_count(WCTrieTree * tree, WCError * error) { if (tree == NULL) { *error = WCNullPointerError; return 0; } *error = WCNoneError; return tree->count; } /* get unique from given WCTrieTree struct */ int wc_trie_tree_get_unique(WCTrieTree * tree, WCError * error) { if (tree == NULL) { *error = WCNullPointerError; return 0; } *error = WCNoneError; return tree->unique; }
3.3125
3
2024-11-18T22:37:03.414772+00:00
2017-04-20T10:17:49
b2dc43f5e666cb5fc090e1ef667d98133345c6c1
{ "blob_id": "b2dc43f5e666cb5fc090e1ef667d98133345c6c1", "branch_name": "refs/heads/master", "committer_date": "2017-04-20T10:17:49", "content_id": "a47e6dc19dda4cecd58f91c49df4f0c77dd25c92", "detected_licenses": [ "Apache-2.0" ], "directory_id": "ebd585fdafb22d31fcd6d04b209f81e88d1a2083", "extension": "c", "filename": "qmi_ping_clnt_test_1001.c", "fork_events_count": 10, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 88847837, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4854, "license": "Apache-2.0", "license_type": "permissive", "path": "/apps_proc/qmi-framework/qcci/test/qmi_ping_clnt_test_1001.c", "provenance": "stackv2-0107.json.gz:90001", "repo_name": "xusl/android-wilhelm", "revision_date": "2017-04-20T10:17:49", "revision_id": "13c59cb5b0913252fe0b5c672d8dc2bf938bb720", "snapshot_id": "fd28144253cd9d7de0646f96ff27a1f4a9bec6e3", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/xusl/android-wilhelm/13c59cb5b0913252fe0b5c672d8dc2bf938bb720/apps_proc/qmi-framework/qcci/test/qmi_ping_clnt_test_1001.c", "visit_date": "2018-04-03T21:46:10.195170" }
stackv2
/****************************************************************************** ----------------------------------------------------------------------------- Copyright (c) 2011-2012 QUALCOMM Technologies Incorporated. All Rights Reserved. QUALCOMM Proprietary and Confidential. ----------------------------------------------------------------------------- ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "qmi_cci_target.h" #include "qmi_client.h" #include "qmi_idl_lib.h" #include "qmi_cci_common.h" #include "qmi_ping_clnt_common_stats.h" #include "qmi_ping_clnt_common.h" #include "qmi_ping_api_v01.h" extern ping_error_cb(qmi_client_type clnt, qmi_client_error_type error, void *error_cb_data); /*=========================================================================== FUNCTION qmi_ping_test_main ===========================================================================*/ /*! @brief Main body of qmi ping clnt test @return 0 for pass, -1 for fail @note - Dependencies - N/A - Side Effects */ /*=========================================================================*/ static int qmi_ping_test_main(int test_length, int test_duration_ms) { qmi_txn_handle txn; uint32_t num_services, num_entries=0; int rc, service_connect; qmi_client_type clnt, notifier; qmi_cci_os_signal_type os_params; qmi_service_info info[10]; int data_size_bytes = 1; qmi_ping_clnt_results_type results; qmi_ping_clnt_common_print_stats(&results, QMI_PING_SINGLE_LINE_HEADER_PRINT_FORMAT); /* Get the service object for the ping API */ qmi_idl_service_object_type ping_service_object = ping_get_service_object_v01(); if (!ping_service_object) { printf("PING: ping_get_serivce_object failed, verify qmi_ping_api_v01.h and .c match.\n"); return -1; } ssr_retry: rc = qmi_client_notifier_init(ping_service_object, &os_params, &notifier); /* Check if the service is up, if not wait on a signal */ while(1) { rc = qmi_client_get_service_list( ping_service_object, NULL, NULL, &num_services); if(rc == QMI_NO_ERR) break; /* wait for server to come up */ QMI_CCI_OS_SIGNAL_WAIT(&os_params, 0); } num_entries = num_services; /* The server has come up, store the information in info variable */ rc = qmi_client_get_service_list( ping_service_object, info, &num_entries, &num_services); service_connect = 0; if (num_services > 1) service_connect = (rand() % num_services); rc = qmi_client_init(&info[service_connect], ping_service_object, NULL, NULL, NULL, &clnt); qmi_client_register_error_cb(clnt, ping_error_cb, NULL); for (;data_size_bytes < PING_MAX_DATA_SIZE_V01; data_size_bytes = (data_size_bytes << 1)) { rc |= qmi_ping_clnt_common_sync_data_test(&clnt, test_length, data_size_bytes, test_duration_ms, 0, &results); if (rc) { qmi_client_release(clnt); goto ssr_retry; } qmi_ping_clnt_common_print_stats(&results, QMI_PING_SINGLE_LINE_PRINT_FORMAT); } rc = qmi_client_release(clnt); printf("PING: qmi_client_release of clnt returned %d\n", rc); rc = qmi_client_release(notifier); printf("PING: qmi_client_release of notifier returned %d\n", rc); return(rc); } /*=========================================================================== FUNCTION main ===========================================================================*/ /*! @brief program enty @return rc @note - Dependencies - N/A - Side Effects */ /*=========================================================================*/ int main(int argc, char *argv[]) { uint32_t test_length; uint32_t test_duration_ms; int rc; printf("Usage: qmi_ping_clnt_test_0000 test_duration_ms(2000 msec) test_length(0) \n"); printf("- To run for a time period, specify test_duration_ms and omit test_length \n"); printf("- To run for a number of QMI txns, specify test_duration_ms = 0 \n and specify test_length \n"); /* Setup defaults */ test_length = 0; test_duration_ms=500; switch(argc) { case 3: test_length = atoi(argv[2]); case 2: test_duration_ms = atoi(argv[1]); break; default: printf("Using defaults test_length:%d, test_duration_ms:%d\n", (unsigned int)test_length , (unsigned int)test_duration_ms); } printf("\n\n\nPING TEST 1001 STARTED...\n"); printf("Test parameters\n"); printf(" Duration : %6d ms\n",(int)test_duration_ms); if(test_length) { printf(" Test Length : %6d \n",(int)test_length); } printf("\n"); rc = qmi_ping_test_main(test_length, test_duration_ms); if( rc == 0 ) { printf("PASS\n"); } else { printf("FAIL\n"); } printf("Sleeping before exit ...\n"); sleep(1); return(rc); }
2.125
2
2024-11-18T22:37:03.485272+00:00
2013-01-11T06:42:12
df578fdb5d81b76e5b5765d3611b6be0de2bb7e5
{ "blob_id": "df578fdb5d81b76e5b5765d3611b6be0de2bb7e5", "branch_name": "refs/heads/master", "committer_date": "2013-01-11T06:42:12", "content_id": "1cd50331748fec87b8d2265ea6705247d823f4a0", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f44869b9ff34f4c57905080ff1c25e25f3b63892", "extension": "c", "filename": "create_discodb.c", "fork_events_count": 18, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 36775, "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2555, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/contrib/discodb/util/create_discodb.c", "provenance": "stackv2-0107.json.gz:90132", "repo_name": "tuulos/disco", "revision_date": "2013-01-11T06:42:12", "revision_id": "63f8746bb2007769cfc12d8eae919ff724e97d0c", "snapshot_id": "6755fd8bf0f7b9bef3ffcc4f99df47bb867a92c3", "src_encoding": "UTF-8", "star_events_count": 96, "url": "https://raw.githubusercontent.com/tuulos/disco/63f8746bb2007769cfc12d8eae919ff724e97d0c/contrib/discodb/util/create_discodb.c", "visit_date": "2021-01-15T22:33:41.942608" }
stackv2
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <discodb.h> static void read_pairs(FILE *in, struct ddb_cons *db) { char *key; char *value; uint32_t lc = 0; while(fscanf(in, "%as %as\n", &key, &value) == 2){ struct ddb_entry key_e = {.data = key, .length = strlen(key)}; struct ddb_entry val_e = {.data = value, .length = strlen(value)}; if (ddb_cons_add(db, &key_e, &val_e)){ fprintf(stderr, "Adding '%s':'%s' failed\n", key, value); exit(1); } free(key); free(value); ++lc; } fclose(in); fprintf(stderr, "%u key-value pairs read.\n", lc); } static void read_keys(FILE *in, struct ddb_cons *db) { char *key; uint32_t lc = 0; while(fscanf(in, "%as\n", &key) == 1){ struct ddb_entry key_e = {.data = key, .length = strlen(key)}; if (ddb_cons_add(db, &key_e, NULL)){ fprintf(stderr, "Adding '%s' failed\n", key); exit(1); } free(key); ++lc; } fclose(in); fprintf(stderr, "%u keys read.\n", lc); } int main(int argc, char **argv) { if (argc < 2){ fprintf(stderr, "Usage:\n"); fprintf(stderr, "create_discodb discodb.out input.txt\n"); fprintf(stderr, "where input.txt contain a key-value pair on each line, devided by space.\n"); exit(1); } FILE *in; FILE *out; uint64_t size; char *data; struct ddb_cons *db = ddb_cons_new(); uint64_t flags = 0; flags |= getenv("DONT_COMPRESS") ? DDB_OPT_DISABLE_COMPRESSION: 0; flags |= getenv("UNIQUE_ITEMS") ? DDB_OPT_UNIQUE_ITEMS: 0; if (!db){ fprintf(stderr, "DB init failed\n"); exit(1); } if (!(in = fopen(argv[2], "r"))){ fprintf(stderr, "Couldn't open %s\n", argv[2]); exit(1); } if (getenv("KEYS_ONLY")) read_keys(in, db); else read_pairs(in, db); fprintf(stderr, "Packing the index..\n"); if (!(data = ddb_cons_finalize(db, &size, flags))){ fprintf(stderr, "Packing the index failed\n"); exit(1); } ddb_cons_free(db); if (!(out = fopen(argv[1], "w"))){ fprintf(stderr, "Opening file %s failed\n", argv[1]); exit(1); } if (!fwrite(data, size, 1, out)){ fprintf(stderr, "Writing file %s failed\n", argv[1]); exit(1); } fclose(out); free(data); fprintf(stderr, "Ok! Index written to %s\n", argv[1]); return 0; }
3.03125
3