language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
char num[100];
int dec=0,i,j,len;
printf("enter a number:");
gets(num);
len=strlen(num);
for(i=0;i<len;i++)
{
dec=dec*10+(num[i]-'0');
}
printf("%d",dec);
getch();
}
|
C
|
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
/* ANSI 3-bit and 4-bit color with escaped sequences.
* According to specification, it produces 8 colors.
* Later terminals started supporting background(BG) colors.
*/
#define R0 "\033[0;0m"
#define BLK "\033[0;30m"
#define RED "\033[0;31m"
#define GRN "\033[0;32m"
#define YLW "\033[0;33m"
#define BLU "\033[0;34m"
#define MGN "\033[0;35m"
#define CYN "\033[0;36m"
#define REDBG "\033[0;41m"
#define GRNBG "\033[0;42m"
/* Given a variable name,
* Returns an integer, representing the type of the variable.
*/
#define typeof(var) _Generic(var, \
int: 1, char: 2, char*: 3, long: 4, \
double: 5, float: 6, default: 0)
/* Given an array,
* Returns the len of the array.
*/
#define len(arr) sizeof(arr)/sizeof(arr[0])
/* Given a valid C statement,
* asserts it.
* Development/learning purposes, mainly.
*/
#define assert(expression) \
(expression) ? printf(GRNBG "True" R0) : printf(REDBG "False" R0); \
printf("\n");
/* Given a filename,
* reads a file.
* Returns the contents of the file.
*/
char* file_read(char* filename) {
FILE *file = fopen(filename, "r");
static char *fileContent;
char ch;
while (fscanf(file, "%c", &ch) == 1) {
strcat(fileContent, &ch);
}
fclose(file);
return fileContent;
}
/* Given an int,
* converts into string,
* Returns the string.
*/
char* int_str(int a) {
static char str[100000];
sprintf(str, "%d", a);
return str;
}
/* Given a string, and a substring,
* searches the substring in the string
* Returns up to what is matched.
*/
char* substr(char* string, char* substr) {
static char matched[1000000];
int i = 0; // counter for substr
int j = 0; // counter for string
for(j = 0; j < strlen(string); j++) {
if (substr[i] == string[j]) {
strcat(matched, &substr[i]); //substr[i] matched!
i++;
}
if (strcmp(matched, substr)==0) { break; }
}
return matched;
}
/* Given an array of numbers, and len of the array,
* determines the sum of the array
* Returns the sum.
*/
double sum(double numbers[], int arrlen) {
double sum = 0;
for (int i=0; i < arrlen; i++) {
sum += numbers[i];
}
return sum;
}
/* Given an array of numbers, and length of the array,
* determines the maximum value of the array
* Returns the maximum item.
*/
double max (double numbers[], int arrlen) {
double maxitem = numbers[0];
for(int i=1; i<arrlen; i++) {
if (numbers[i] > maxitem) {
maxitem = numbers[i];
}
}
return maxitem;
}
/* Given an array of numbers, and length of the array,
* determines the minimum value of the array
* Returns the minimum item.
*/
double min(double numbers[], int arrlen) {
double minitem = numbers[0];
for(int i=1; i < arrlen; i++) {
if (numbers[i] < minitem) {
minitem = numbers[i];
}
}
return minitem;
}
|
C
|
#include "ej12guindows.h"
#include <stdio.h>
// Ejercicio 12: observación:
/* Para verificar el apartado 12_c), desconmentar las líneas que dicen
'apartado c)' y comentar los bucles 'for'.
*/
static task t1, t2, t3, taskmain;
static void ft1(void)
{
// unsigned j; // Apartado c)
// printf("t1: %p\n", &j); // Apartado c)
for (double d = -1; ; d += 0.001) {
printf("d=%f\n", d);
TRANSFER(t1, t2);
}
TRANSFER(t1, t2);
}
static void ft2(void)
{
unsigned j;
// printf("t2: %p\n", &j); // Apartado c)
for (unsigned i = 0; i < 10000; i++) {
printf("i=%u\n", i);
TRANSFER(t2, t3);
}
// TRANSFER(t2, t3); // Apartado c)
TRANSFER(t2, taskmain);
}
static void ft3(void){
unsigned j;
// printf("t3: %p\n", &j); // Apartado c)
for (unsigned i = 0; i < 5000; i++){
printf("t3: i=%u\n", i);
TRANSFER(t3, t1);
}
TRANSFER(t3, taskmain);
}
int main(void)
{
stack(t1, ft1);
stack(t2, ft2);
stack(t3, ft3);
TRANSFER(taskmain, t1);
return 0;
}
|
C
|
#include <stdio.h>
// Skriver ut välkomstmenyn som visar alternativ för att välja svårighetsgrad
void welcome_menu()
{
printf("\nVälkommen till “The One Armed Bandit”.\n");
printf("*************************************\n");
printf("\nVälj svårighetsgrad på spelet.\n");
printf("Ju svårare spel, desto mindre är chansen att vinna, men desto högre blir vinsten.\n\n");
printf("1) Lätt\n");
printf("2) Medel\n");
printf("3) Svår\n");
printf("Ange en siffra 1-3: ");
}
// Skriver meny som visar vilka belopp man kan överföra till spelkontot
void transaction_menu()
{
printf("\nSätt in pengar på ditt spelkonto.\n");
printf("Du kan sätta in:\n");
printf("1) 20 kr.\n");
printf("2) 50 kr.\n");
printf("3) 100 kr.\n");
printf("4) 250 kr.\n");
printf("5) 500 kr.\n");
printf("6) 1000 kr.\n");
printf ("Ange en siffra 1-6: ");
}
// Hämtar användarens input vid vald svårighetsgrad
int severity_select()
{
int menu_in = 0;
while (1) {
scanf("%d", &menu_in);
if (menu_in < 1 || menu_in > 3) {
printf("Fel. Du måste ange en siffra mellan 1 och 3. Försök igen: ");
} else {
printf("\nVald svårighetsgrad: ");
if (menu_in == 1) {
printf("*** LÄTT ***\n");
} else if (menu_in == 2) {
printf("*** MEDEL ***\n");
} else if (menu_in == 3) {
printf("*** SVÅR ***\n");
}
return menu_in;
}
}
}
// Hämtar användarens inmatade belopp att överföra till spelkontot
int make_transaction()
{
int menu_in; // meny input
int value = 0; // beloppet
while (1) {
scanf("%d", &menu_in);
if (menu_in < 1 || menu_in > 6) { // endast ett val mellan 1 och 6
printf("Fel. Du måste ange en siffra mellan 1 och 6. Försök igen: ");
} else {
// översätt menyval till rätt pengabelopp
if (menu_in == 1) {
value = 20;
} else if (menu_in == 2) {
value = 50;
} else if (menu_in == 3) {
value = 100;
} else if (menu_in == 4) {
value = 250;
} else if (menu_in == 5) {
value = 500;
} else if (menu_in == 6) {
value = 1000;
}
return value; // returnera det insatta beloppet
}
}
}
// Fråga efter belopp tills ett korrekt belopp angivits, eller spelare avslutar.
void make_bet(int *account, int *bet)
{
// Skriver ut saldo och ber spelaren att satsa.
printf("Ditt saldo är: %i kr.\n\n", *account);
printf("Ange hur mycket du vill satsa. Avsluta med \"0\": ");
while (1) {
scanf("%d", &*bet);
if (*bet > 0 && *bet <= *account) { // Beloppet får ej överstiga kontots salda
*account -= *bet; // Dra av satsat belopp från konto
break;
} else if (*bet == 0) { // Avslutar med 0
break;
} else {
printf("Ange ett korrekt belopp: ");
}
}
}
void print_result(int row_won_count, int bet, int money_won)
{
printf("\n\n*************************************\n");
if (row_won_count == 1) {
printf("\nDu fick %i rad.", row_won_count);
} else {
printf("\nDu fick %i rader.", row_won_count);
}
printf("\nDu satsade %i kr och fick %i kr tillbaka.\n", bet, money_won);
}
|
C
|
#include "mruby.h"
#include "mruby/range.h"
#include <math.h>
static mrb_bool
r_le(mrb_state *mrb, mrb_value a, mrb_value b)
{
mrb_value r = mrb_funcall(mrb, a, "<=>", 1, b); /* compare result */
/* output :a < b => -1, a = b => 0, a > b => +1 */
if (mrb_fixnum_p(r)) {
mrb_int c = mrb_fixnum(r);
if (c == 0 || c == -1) return TRUE;
}
return FALSE;
}
static mrb_bool
r_lt(mrb_state *mrb, mrb_value a, mrb_value b)
{
mrb_value r = mrb_funcall(mrb, a, "<=>", 1, b);
/* output :a < b => -1, a = b => 0, a > b => +1 */
return mrb_fixnum_p(r) && mrb_fixnum(r) == -1;
}
/*
* call-seq:
* rng.cover?(obj) -> true or false
*
* Returns <code>true</code> if +obj+ is between the begin and end of
* the range.
*
* This tests <code>begin <= obj <= end</code> when #exclude_end? is +false+
* and <code>begin <= obj < end</code> when #exclude_end? is +true+.
*
* ("a".."z").cover?("c") #=> true
* ("a".."z").cover?("5") #=> false
* ("a".."z").cover?("cc") #=> true
*/
static mrb_value
mrb_range_cover(mrb_state *mrb, mrb_value range)
{
mrb_value val;
struct RRange *r = mrb_range_ptr(range);
mrb_value beg, end;
mrb_get_args(mrb, "o", &val);
beg = r->edges->beg;
end = r->edges->end;
if (r_le(mrb, beg, val)) {
if (r->excl) {
if (r_lt(mrb, val, end))
return mrb_true_value();
}
else {
if (r_le(mrb, val, end))
return mrb_true_value();
}
}
return mrb_false_value();
}
/*
* call-seq:
* rng.first -> obj
* rng.first(n) -> an_array
*
* Returns the first object in the range, or an array of the first +n+
* elements.
*
* (10..20).first #=> 10
* (10..20).first(3) #=> [10, 11, 12]
*/
static mrb_value
mrb_range_first(mrb_state *mrb, mrb_value range)
{
mrb_int num;
mrb_value array;
struct RRange *r = mrb_range_ptr(range);
if (mrb_get_args(mrb, "|i", &num) == 0) {
return r->edges->beg;
}
array = mrb_funcall(mrb, range, "to_a", 0);
return mrb_funcall(mrb, array, "first", 1, mrb_fixnum_value(num));
}
/*
* call-seq:
* rng.last -> obj
* rng.last(n) -> an_array
*
* Returns the last object in the range,
* or an array of the last +n+ elements.
*
* Note that with no arguments +last+ will return the object that defines
* the end of the range even if #exclude_end? is +true+.
*
* (10..20).last #=> 20
* (10...20).last #=> 20
* (10..20).last(3) #=> [18, 19, 20]
* (10...20).last(3) #=> [17, 18, 19]
*/
static mrb_value
mrb_range_last(mrb_state *mrb, mrb_value range)
{
mrb_value num;
mrb_value array;
struct RRange *r = mrb_range_ptr(range);
if (mrb_get_args(mrb, "|o", &num) == 0) {
return r->edges->end;
}
array = mrb_funcall(mrb, range, "to_a", 0);
return mrb_funcall(mrb, array, "last", 1, mrb_to_int(mrb, num));
}
/*
* call-seq:
* rng.size -> num
*
* Returns the number of elements in the range. Both the begin and the end of
* the Range must be Numeric, otherwise nil is returned.
*
* (10..20).size #=> 11
* ('a'..'z').size #=> nil
*/
static mrb_value
mrb_range_size(mrb_state *mrb, mrb_value range)
{
struct RRange *r = mrb_range_ptr(range);
mrb_value beg, end;
double beg_f, end_f;
mrb_bool num_p = TRUE;
beg = r->edges->beg;
end = r->edges->end;
if (mrb_fixnum_p(beg)) {
beg_f = (double)mrb_fixnum(beg);
}
else if (mrb_float_p(beg)) {
beg_f = mrb_float(beg);
}
else {
num_p = FALSE;
}
if (mrb_fixnum_p(end)) {
end_f = (double)mrb_fixnum(end);
}
else if (mrb_float_p(end)) {
end_f = mrb_float(end);
}
else {
num_p = FALSE;
}
if (num_p) {
double f;
if (beg_f > end_f) return mrb_fixnum_value(0);
f = end_f - beg_f;
if (!r->excl) {
return mrb_fixnum_value((mrb_int)ceil(f + 1));
}
return mrb_fixnum_value((mrb_int)ceil(f));
}
return mrb_nil_value();
}
void
mrb_mruby_range_ext_gem_init(mrb_state* mrb)
{
struct RClass * s = mrb_class_get(mrb, "Range");
mrb_define_method(mrb, s, "cover?", mrb_range_cover, MRB_ARGS_REQ(1));
mrb_define_method(mrb, s, "first", mrb_range_first, MRB_ARGS_OPT(1));
mrb_define_method(mrb, s, "last", mrb_range_last, MRB_ARGS_OPT(1));
mrb_define_method(mrb, s, "size", mrb_range_size, MRB_ARGS_NONE());
}
void
mrb_mruby_range_ext_gem_final(mrb_state* mrb)
{
}
|
C
|
char* solution(const char* s) {
int i = 0, EvenOrOdd = 0;
char* answer = (char*)malloc(sizeof(char) * strlen(s) + 1);
strcpy(answer, s);
while (answer[i] != '\0') {
if (answer[i] == ' ') {
EvenOrOdd = -1;
}
else if (EvenOrOdd % 2 == 0) {
if (answer[i] >= 'a' && answer[i] <= 'z') {
answer[i] = answer[i] - 32;
}
}
else if (EvenOrOdd % 2 == 1){
if (answer[i] >= 'A' && answer[i] <= 'Z') {
answer[i] = answer[i] + 32;
}
}
i++;
EvenOrOdd++;
}
return answer;
}
|
C
|
#include<stdio.h>
int main(void){
int arrayN[1000000];
int N;
int max = -1000000, min = 10000000;
scanf("%d", &N);
for (int i = 0; i < N; i++) {
scanf("%d",&arrayN[i]);
}
for (int i = 0; i < N; i++) {
if (arrayN[i] > max)
max = arrayN[i];
if (arrayN[i] < min)
min = arrayN[i];
}
printf("%d %d", min, max);
return 0;
}
|
C
|
#include "../include/binaryMaxHeap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "../include/bst.h"
void swap(void ** node1, void ** node2)
{
void * temp = *node1;
*node1 = *node2;
*node2 = temp;
}
BinaryTreeNode * CreateBinaryTreeNode(char * dc_name, size_t total_patientes)
{
BinaryTreeNode * node;
if( (node = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode))) == NULL)
{
perror("Error(CreateBinaryTreeNode): ");
exit(EXIT_FAILURE);
}
node -> dc_name = ( char *)malloc(1 + sizeof(char) * strlen(dc_name));
strcpy(node -> dc_name,(const char *)dc_name);
node -> total_patientes = total_patientes;
node -> left = NULL;
node -> right = NULL;
node -> parent = NULL;
return node;
}
BinaryMaxHeap * CreateBinaryMaxHeap()
{
BinaryMaxHeap * bst;
if(((bst = (BinaryMaxHeap *)malloc(sizeof(BinaryMaxHeap))) == NULL))
{
perror("Error(CreateBinaryMaxHeap): ");
exit(EXIT_FAILURE);
}
bst -> root = NULL;
bst -> totalNodes = 0;
return bst;
}
void inorderMaxHeap(BinaryTreeNode * node)
{
if(node != NULL)
{
inorderMaxHeap(node -> left);
if(node -> parent == NULL)
{
printf("Parent = NULL\t\t----->");
}
else
{
printf("Parent = (%s , %ld)\t----->",node -> parent -> dc_name, node -> parent -> total_patientes);
}
printf("\tChild = (%s , %ld)\n", node -> dc_name, node -> total_patientes);
inorderMaxHeap(node -> right);
}
}
void setParent(BinaryTreeNode * node,BinaryTreeNode * parent)
{
if(node != NULL)
{
setParent(node -> left, node);
if(node == parent)
{
node -> parent = NULL;
}
else
{
node -> parent = parent;
}
setParent(node -> right, node);
}
}
BinaryTreeNode * BuildMaxHeap(BinaryTreeNode ** arr, BinaryTreeNode * node, size_t i, size_t n)
{
if(i < n)
{
BinaryTreeNode * newBinaryTreeNode = CreateBinaryTreeNode(arr[i] -> dc_name, arr[i] -> total_patientes);
node = newBinaryTreeNode;
node -> left = BuildMaxHeap(arr, node -> left, 2*i+1 ,n);;
node -> right = BuildMaxHeap(arr, node -> right, 2*i+2 ,n);
return node;
}
return node;
}
void MaxHeapify(BinaryTreeNode * root, BinaryTreeNode * node)
{
if(root == NULL)
{
return;
}
MaxHeapify(root -> left, root);
MaxHeapify(root -> right, root);
if(node != NULL && (root -> total_patientes > node -> total_patientes))
{
swap((void **)&(root -> dc_name), (void **)&(node -> dc_name));
swap((void **)&(root -> total_patientes), (void **)&(node -> total_patientes));
}
}
void preorderMaxHeapify(BinaryTreeNode * root)
{
if(root == NULL)
{
return;
}
MaxHeapify(root,NULL);
preorderMaxHeapify(root -> left);
preorderMaxHeapify(root -> right);
}
void GetKMaxValues(BinaryTreeNode * root, size_t k)
{
for (size_t i = 0; i < k; i++)
{
if(root == NULL)
{
return;
}
printf("%s %ld\n",root -> dc_name, root -> total_patientes);
root -> total_patientes = 0;
preorderMaxHeapify(root);
}
}
void DeallocateMaxHeap(BinaryTreeNode * temp)
{
if(temp == NULL)
{
return;
}
DeallocateMaxHeap(temp -> left);
DeallocateMaxHeap(temp -> right);
free(temp);
}
|
C
|
#include<stdio.h>
#include<string.h>
#define maxl 2000
#define max(a,b) (a>b)?(a):(b)
void add(char *s,char *t,char *u);
int main()
{
char s[maxl],t[maxl],u[maxl];
while(~scanf("%s %s",s,t)){
add(s,t,u);
printf("%s\n",u);
}
return 0;
}
void add(char *s,char *t,char *u)
{
int i;
int lens=strlen(s),lent=strlen(t);
int k=max(lens,lent)+1;
for(i=0;i<lens;i++){
s[i]-='0';
}
for(i=0;i<lent;i++){
t[i]-='0';
}
int cc=0,p=lens-1,q=lent-1;
for(i=k;i>=0;i--){
int x=cc;
if(p>=0){
x+=s[p];
p--;
}
if(q>=0){
x+=t[q];
q--;
}
u[i]=x%10+'0';
cc=x/10;
}
u[k+1]='\0';
while(u[0]=='0'){
for(i=0;i<k+1;i++){
u[i]=u[i+1];
}
}
if(strlen(u)==0){
u[0]='0',u[1]='\0';
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
/*
* This program creates a text document that contains commands for the vecalc
* execuatable according to the format specified in the fprintf statement. The
* text document can then be redirected into vecalc to run vecalc.
*/
int main() {
/*List of all the available commands in vecalc*/
char cmdsList[8] = {'a', '+', 'r', '*', 'm', '/', '-', 'c'};
/*Number of commands to print*/
int c = 200;
time_t t;
srand(time(&t));
/*File for commands to be stored in*/
FILE *vecalcCmds;
vecalcCmds = fopen("vecalcCmds.txt", "w+");
/*
* rand() % x means generate random numbers between 1 and x
*/
int i;
for(i = 0; i < c; i++) {
fprintf(vecalcCmds, "%c %d\n", cmdsList[rand() % 7], rand() % 100);
}
for(i = 0; i < c; i++) {
fprintf(vecalcCmds, "%c %d %c %d\n", cmdsList[rand() % 7], rand() % 100, cmdsList[rand() % 7], rand() % 100);
}
for(i = 0; i < c; i++) {
fprintf(vecalcCmds, "%c %d %c %d %c %d\n", cmdsList[rand() % 7], rand() % 100, cmdsList[rand() % 7], rand() % 100, cmdsList[rand() % 7], rand() % 100);
}
for(i = 0; i < c; i++) {
fprintf(vecalcCmds, "%c %d %c %d %c %d %c %d\n", cmdsList[rand() % 7], rand() % 100, cmdsList[rand() % 7], rand() % 100, cmdsList[rand() % 7], rand() % 100, cmdsList[rand() % 7], rand() % 100);
}
fprintf(vecalcCmds, "q");
return 0;
}
|
C
|
/*
** command.c for in /home/empoci_k/PSU_2014_42sh/Levenshtein
**
** Made by Kévin Empociello
** Login <empoci_k@epitech.net>
**
** Started on Fri May 22 01:30:50 2015 Kévin Empociello
** Last update Sun May 31 23:05:02 2015 guillaume wilmot
*/
#include "edit.h"
#include "minishell.h"
int command_is_good(char *command, char **env)
{
int i;
int check;
char *s;
char *tmp;
char *str;
i = ((s = NULL) == NULL) ? 0 : 0;
check = 0;
if ((i = place_env(env)) == -1)
return (-1);
else
{
tmp = cpy(env[i]);
s = strtok(tmp, ":");
while ((s = strtok(NULL, ":")) != NULL)
{
if (access((str = concatenate(s, command, '/')), R_OK) == 0)
check = 1;
free(str);
}
free(tmp);
}
return (((check == 0) ? -1 : 0));
}
int is_bult(char *str)
{
if ((strncmp(str, "cd", 2) == 0) || (strncmp(str, "env", 3) == 0) ||
(strncmp(str, "unsetenv", 8) == 0) || (strncmp(str, "setenv", 6) == 0) ||
(strncmp(str, "echo", 4) == 0) || (strncmp(str, "history", 7) == 0) ||
(strncmp(str, "exit", 4) == 0) || (strncmp(str, "fg", 2) == 0) ||
(strncmp(str, "!", 1) == 0) || (strncmp(str, "ll", 2) == 0) ||
(strncmp(str, "la", 2) == 0) || (strncmp(str, "ne", 2) == 0))
return (0);
return (-1);
}
int check_command(char *str, char **env)
{
if (access(str, F_OK) == 0)
return (0);
if (command_is_good(str, env) == 0 || is_bult(str) == 0)
return (0);
else
return (-1);
}
char **cut_command(char *str)
{
char **tabl;
int i;
int k;
int j;
i = 0;
j = 0;
if ((tabl = malloc((my_strlen(str) + 2) * sizeof(char *))) == NULL)
return (NULL);
while (str && str[i])
{
while (str && str[i] && str[i] == ' ')
i++;
if ((tabl[j] = malloc((my_strlen(str) + 2) * sizeof(char))) == NULL)
return (NULL);
k = 0;
while (str && str[i] && str[i] != ' ')
tabl[j][k++] = str[i++];
tabl[j][k] = '\0';
while (str && str[i] && str[i] == ' ')
i++;
j++;
}
tabl[j] = NULL;
return (tabl);
}
char *change_command(char *cmd, char *new_cmd)
{
char *new;
int j;
int i;
i = 0;
j = 0;
if (new_cmd == NULL)
return (cmd);
if ((new = malloc((strlen(cmd) + strlen(new_cmd)) * sizeof(char))) == NULL)
return (NULL);
while (new_cmd && new_cmd[i] != '\0')
{
new[i] = new_cmd[i];
i++;
}
while (cmd && cmd[j] != '\0' && cmd[j] != ' ')
j++;
while (cmd && cmd[j] != '\0' && cmd[j] != ' ')
new[i++] = cmd[j++];
new[i] = '\0';
return (new);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int mainMenu();
void q1(), q2(), q3(), q4(), q5(), q6(), q7();
void breakUpInts(int *, int, int);
int noOfDigits(int);
int main() {
int userSelection;
do {
userSelection = mainMenu();
switch (userSelection) {
case 1:
q1();
break;
case 2:
q2();
break;
case 3:
q3();
break;
case 4:
q4();
break;
case 5:
q5();
break;
case 6:
q6();
break;
case 7:
q7();
break;
default:
printf("You must enter a number from the menu.\n");
}
} while (userSelection != 0);
printf("Goodbye.\n");
return 0;
}
int mainMenu() {
int userSelection;
printf("Select a question number:\n");
printf("0:\tQUIT\n");
printf("1:\tPrint integers\n");
printf("2:\tSum even numbers between 1 and x\n");
printf("3:\tCount the number of vowels\n");
printf("4:\tPrint address\n");
printf("5:\tAdd to floats and store in int\n");
printf("6:\tAccess the parts of a float\n");
printf("7:\tCalculate simple and compound interest\n");
scanf("%d", &userSelection);
return userSelection;
}
void q7() {
printf("\n**********************************************\n");
printf("Question 7\n");
printf("**********************************************\n\n");
double years, rate, principal, simpleinterest, compinterest, comprate;
int noDays;
printf("This will program will calculate interest payable - both simple and compound.\n\n");
printf("Enter a loan principal amount: ");
scanf("%lf", &principal);
printf("Enter an interest rate (eg. 4.05 for 4.05%): ");
scanf("%lf", &rate);
printf("Enter a loan period in years (eg. 0.5 for 6 months): ");
scanf("%lf", &years);
simpleinterest = principal * rate / 100 * years;
noDays = years * 365;
comprate = pow(1 + rate/(100.0 * 365.0), (double)noDays) - 1;
compinterest = principal * comprate;
printf("\nLoan details: principal $%.2lf\tinterest rate %.2lf%\tterm %.1lf years\n", principal, rate, years);
printf("Simple interest payable:\t\t$%8.2lf\n", simpleinterest);
printf("Compound interest payable:\t\t$%8.2lf\n", compinterest);
printf("Simple interest rate for the period:\t\t%8.2lf%\n", rate * years);
printf("Compound interest rate for the period:\t\t%8.2lf%\n", comprate * 100);
printf("\n**********************************************\n");
}
void q6() {
printf("\n**********************************************\n");
printf("Question 6\n");
printf("**********************************************\n\n");
double flt, fractional, integral;
printf("Please enter a floating point number: ");
scanf("%lf", &flt);
printf("You entered %lf\n", flt);
fractional = modf(flt, &integral);
printf("That float has integral component %lf and fractional component %lf\n", integral, fractional);
int ndigs = 0;
ndigs = noOfDigits(integral);
int ints[ndigs];
breakUpInts(ints, ndigs, integral);
printf("The integral component is made up of the following digits from least to most significant:\n");
for(int i = 0; i < ndigs; i++) {
printf("\t%d", ints[i]);
}
printf("\n**********************************************\n");
}
int noOfDigits(int val) {
int ct = 1;
while(val/=10) ct++;
return ct;
}
void breakUpInts(int * ints, int ndigs, int val) {
for(int i = 0; i < ndigs; i++) {
ints[i] = (val%10);
val/=10;
}
}
void q5() {
printf("\n**********************************************\n");
printf("Question 5\n");
printf("**********************************************\n\n");
float f1, f2;
int sum;
printf("Please enter 2 floating point numbers: ");
scanf("%f %f", &f1, &f2);
printf("\nYou entered %f1 and %f2\n", f1, f2);
sum = f1 + f2;
printf("There sum stored in an int is %d\n", sum);
printf("\n**********************************************\n");
}
void q4() {
printf("\n**********************************************\n");
printf("Question 4\n");
printf("**********************************************\n\n");
printf("Dear user, please enter you name and address (with , separators and . terminator)\n");
unsigned int len_max = 128;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
current_size = len_max;
printf("\nPlease enter one line of text ended with a } (can be of arbitrary length): ");
if(pStr != NULL)
{
int c;
unsigned int i = 0;
//accept user input until hit enter or end of file
do {
c = getchar();
pStr[i++]=c;
//if i reached maximize size then realloc size
if(i == current_size)
{
current_size = i+len_max;
pStr = realloc(pStr, current_size);
}
} while (c != '.' && c != EOF);
pStr[i-1] = '\0';
int startOfLine = 0;
for (i = 0; i < strlen(pStr); i++) {
if (pStr[i] == ',') {
printf("\n");
startOfLine = 1;
continue;
} else if ((pStr[i] == ' ') && (startOfLine == 1)) {
startOfLine = 0;
continue;
} else {
printf("%c", pStr[i]);
}
}
//free the memory
free(pStr);
pStr = NULL;
}
printf("\n**********************************************\n");
}
void q3() {
printf("\n**********************************************\n");
printf("Question 3\n");
printf("**********************************************\n\n");
unsigned int len_max = 128;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
current_size = len_max;
printf("\nPlease enter one line of text ended with a } (can be of arbitrary length): ");
if(pStr != NULL)
{
int c;
unsigned int i = 0;
//accept user input until hit enter or end of file
do {
c = getchar();
pStr[i++]=c;
//if i reached maximize size then realloc size
if(i == current_size)
{
current_size = i+len_max;
pStr = realloc(pStr, current_size);
}
} while (c != '}' && c != EOF);
pStr[i-1] = '\0';
int vowels = 0;
for (i = 0; i < strlen(pStr); i++) {
switch (pStr[i]) {
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
vowels++;
}
}
printf("\nThe string entered was: %s\n",pStr);
printf("This string contains %d vowels.\n", vowels);
//free the memory
free(pStr);
pStr = NULL;
}
printf("\n**********************************************\n");
}
void q2() {
printf("\n**********************************************\n");
printf("Question 2\n");
printf("**********************************************\n\n");
int userInt;
printf("Please enter an integer number:");
scanf("%d:", &userInt);
int totalEvens = 0;
for (int i = 2; i <= userInt; i += 2) {
totalEvens += i;
}
printf("The sum total of the even numbers between 1 and %d id %d.\n", userInt, totalEvens);
printf("\n**********************************************\n");
}
void q1() {
printf("\n**********************************************\n");
printf("Question 1\n");
printf("**********************************************\n\n");
int noInts = 10;
int ints[noInts];
for (int i = 0; i < noInts; i++) {
printf("%\tEnter integer number %d\n", i+1);
scanf("%d", &ints[i]);
}
unsigned char delimit;
for (int i = 0; i < noInts; i++) {
if (((i + 1) % 3 == 0) || ((i + 1) == noInts)) {
delimit= 0x0a;
} else {
delimit= 0x2c;
}
printf("%d%c", ints[i], delimit);
}
printf("\n**********************************************\n");
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct rdtgroup {int dummy; } ;
struct kernfs_node {struct rdtgroup* priv; struct kernfs_node* parent; } ;
/* Variables and functions */
scalar_t__ KERNFS_DIR ;
scalar_t__ kernfs_type (struct kernfs_node*) ;
struct kernfs_node* kn_info ;
__attribute__((used)) static struct rdtgroup *kernfs_to_rdtgroup(struct kernfs_node *kn)
{
if (kernfs_type(kn) == KERNFS_DIR) {
/*
* All the resource directories use "kn->priv"
* to point to the "struct rdtgroup" for the
* resource. "info" and its subdirectories don't
* have rdtgroup structures, so return NULL here.
*/
if (kn == kn_info || kn->parent == kn_info)
return NULL;
else
return kn->priv;
} else {
return kn->parent->priv;
}
}
|
C
|
#include <netinet/ip.h>
#include <stdio.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "packets_settings.h"
#define DEFAULT_IP "::1"
#define DEFAULT_PORT 443
// typedef struct Target {
// char* _ip;
// int _port;
// char* _type;
// } Target;
void get_cli(int argc, char* argv[], struct packet* pkt) {
switch (argc) {
default:
printf("Error, too many values or incorrect entry\n");
exit(1);
break;
case 1:
printf("There is no input.\nDefault values will be entered\n\n");
strcpy(pkt->target_ip_address, DEFAULT_IP);
pkt->target_port = 443;
pkt->protocol = IPPROTO_UDP;
break;
case 5:
if ((strcmp(argv[1], "-t") == 0) && (strcmp(argv[3], "-p") == 0)) {
strcpy(pkt->target_ip_address, argv[2]);
pkt->target_port = atoi((char*)argv[4]);
pkt->protocol = IPPROTO_UDP;
break;
} else {
printf("Error, too many values or incorrect entry\n");
exit(1);
break;
}
}
}
void run(struct packet* pkt) {
}
/*
The following main function can have the following parameters (flags)
-t The target IP address for the flood attacks, default is ::1
-p The target port, default is 443
*/
int main(int argc, char* argv[]) {
srand(time(NULL)); //Get different random result
// //Get user choices
// get_cli(argc, argv, &target);
struct packet pkt;
memset(&pkt, 0, sizeof(struct packet));
//Get user choices
get_cli(argc, argv, &pkt);
int enable = 1;
// MUST use sudo, otherwise we'll encounter an error here
int sock = socket(AF_INET6, SOCK_RAW, IPPROTO_RAW);
int sockopt = setsockopt(sock, IPPROTO_IPV6, IPV6_HDRINCL, &enable, sizeof(enable));
if (sockopt == -1 || sock == -1) exit(1);
struct sockaddr_in6 dst;
dst.sin6_family = AF_INET6;
dst.sin6_port = htons(pkt.source_port);
char packet[48];
printf("Attack Type: UDP FLOOD\nTarget: %s:%d\n", pkt.target_ip_address, pkt.target_port);
// infinite loop, up to user exit
while (1) {
memset(packet, 0, 48);
create_packet(packet, &pkt);
// printf("%s\n", pkt.source_ip_address);
sendto(sock, packet, (IPHDR_SZ + sizeof(struct udphdr)), 0, (struct sockaddr*)&dst, sizeof(dst));
}
close(sock);
return 0;
}
|
C
|
/**
* @file tft_lcd.c
* @brief TFT LCD Driver
* @author matyunin.d
* @date 14.06.2019
*/
#include "tft_lcd.h"
#include <string.h>
#define LCD_CMD 0
#define LCD_DATA 1
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
extern const uint8_t ch_font_1206[95][12];
extern const uint8_t ch_font_1608[95][16];
extern void tft_bkl_set(void);
extern void tft_bkl_clr(void);
extern void tft_lcd_cs_set(void);
extern void tft_lcd_cs_clr(void);
extern void tft_dc_set(void);
extern void tft_dc_clr(void);
extern void tft_write(uint8_t *data, uint16_t count);
extern void tft_delay_ms(uint16_t value);
/**
* @brief Write byte to LCD
* @param byte
* @param cmd
* @return void
*/
static void lcd_write_byte(uint8_t byte, uint8_t cmd)
{
uint8_t data = byte;
if (cmd) {
tft_dc_set();
} else {
tft_dc_clr();
}
tft_lcd_cs_clr();
tft_write(&data, 1);
tft_lcd_cs_set();
}
/**
* @brief Write word (2 bytes) to LCD
* @param word
* @return void
*/
static void lcd_write_word(uint16_t word)
{
uint8_t data[2] = {word >> 8, word & 0xFF};
tft_dc_set();
tft_lcd_cs_clr();
tft_write(data, 2);
tft_lcd_cs_set();
}
/**
* @brief Write value to LCD register
* @param reg
* @param value
* @return void
*/
static void lcd_write_register(uint8_t reg, uint8_t value)
{
lcd_write_byte(reg, LCD_CMD);
lcd_write_byte(value, LCD_DATA);
}
/**
* @brief Set the specified position of cursor on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @return void
*/
void lcd_set_cursor(uint16_t xpos, uint16_t ypos)
{
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
lcd_write_register(0x02, xpos >> 8);
lcd_write_register(0x03, xpos & 0xFF); //Column Start
lcd_write_register(0x06, ypos >> 8);
lcd_write_register(0x07, ypos & 0xFF); //Row Start
}
/**
* @brief Clear the lcd with the specified color
* @param color Color of the screen
* @return void
*/
void lcd_clear_screen(uint16_t color)
{
uint8_t tmp[LCD_WIDTH*2];
for (int i = 0; i < LCD_WIDTH*2; i+=2) {
tmp[i] = color >> 8;
tmp[i+1] = color & 0xFF;
}
for (int i = 0; i < LCD_HEIGHT; i++)
{
lcd_set_cursor(0, i);
lcd_write_byte(0x22, LCD_CMD);
tft_dc_set();
tft_lcd_cs_clr();
tft_write(tmp, LCD_WIDTH*2);
tft_lcd_cs_set();
}
}
/**
* @brief Draw a point on the lcd with the specified color.
* @param xpos Specify x position
* @param ypos Specify y position
* @param color Color of the point
* @return void
*/
void lcd_draw_point(uint16_t xpos, uint16_t ypos, uint16_t color)
{
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
lcd_set_cursor(xpos, ypos);
lcd_write_byte(0x22, LCD_CMD);
lcd_write_word(color);
}
/**
* @brief Display a char at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param chr A char is display
* @param size Specify the size of the char
* @param color Specify the color of the char
* @return void
*/
void lcd_display_char(uint16_t xpos, uint16_t ypos, uint8_t chr, uint8_t size, uint16_t color)
{
uint8_t i, j, tmp;
uint16_t ypos0 = ypos, color_val = 0;
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
for (i = 0; i < size; i ++) {
if (FONT_1206 == size) {
tmp = ch_font_1206[chr - 0x20][i];
} else if (FONT_1608 == size) {
tmp = ch_font_1608[chr - 0x20][i];
}
for (j = 0; j < 8; j ++) {
if (tmp & 0x80) {
color_val = color;
lcd_draw_point(xpos, ypos, color_val);
}
tmp <<= 1;
ypos++;
if ((ypos - ypos0) == size) {
ypos = ypos0;
xpos++;
break;
}
}
}
}
/**
* @brief Calculate power of n
* @param m
* @param n
* @return M^N
*/
static uint32_t _pow(uint8_t m, uint8_t n)
{
uint32_t result = 1;
while (n--)
result *= m;
return result;
}
/**
* @brief Display a number at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param num A number is display
* @param len Length ot the number
* @param size Specify the size of the number
* @param color Specify the color of the number
* @return void
*/
void lcd_display_num(uint16_t xpos, uint16_t ypos, uint32_t num, uint8_t len, uint8_t size, uint16_t color)
{
uint8_t i;
uint8_t tmp, show = 0;
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
for(i = 0; i < len; i ++) {
tmp = (num / _pow(10, len - i - 1)) % 10;
if (show == 0 && i < (len - 1)) {
if(tmp == 0) {
lcd_display_char(xpos + (size / 2) * i, ypos, ' ', size, color);
continue;
} else {
show = 1;
}
}
lcd_display_char(xpos + (size / 2) * i, ypos, tmp + '0', size, color);
}
}
/**
* @brief Display a string at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param str A pointer to string
* @param size The size of the string
* @param color Specify the color of the string
* @return void
*/
void lcd_display_string(uint16_t xpos, uint16_t ypos, const uint8_t *str, uint8_t size, uint16_t color)
{
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
while (*str != '\0') {
if (xpos > (LCD_WIDTH - size / 2)) {
xpos = 0;
ypos += size;
if (ypos > (LCD_HEIGHT - size)) {
ypos = xpos = 0;
lcd_clear_screen(0x00);
}
}
lcd_display_char(xpos, ypos, (uint8_t)*str, size, color);
xpos += size / 2;
str++;
}
}
/**
* @brief Draw a line at the specified position on LCD
* @param xpos0 Specify x0 position
* @param ypos0 Specify y0 position
* @param xpos1 Specify x1 position
* @param ypos1 Specify y1 position
* @param color Specify the color of the line
* @return void
*/
void lcd_draw_line(uint16_t xpos0, uint16_t ypos0, uint16_t xpos1, uint16_t ypos1, uint16_t color)
{
int x = xpos1 - xpos0;
int y = ypos1 - ypos0;
int dx = abs(x), sx = xpos0 < xpos1 ? 1 : -1;
int dy = -abs(y), sy = ypos0 < ypos1 ? 1 : -1;
int err = dx + dy, e2;
if (xpos0 >= LCD_WIDTH || ypos0 >= LCD_HEIGHT || xpos1 >= LCD_WIDTH || ypos1 >= LCD_HEIGHT)
return;
for (;;){
lcd_draw_point(xpos0, ypos0 , color);
e2 = 2 * err;
if (e2 >= dy) {
if (xpos0 == xpos1)
break;
err += dy;
xpos0 += sx;
}
if (e2 <= dx) {
if (ypos0 == ypos1)
break;
err += dx;
ypos0 += sy;
}
}
}
/**
* @brief Draw a circle at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param radius Specify the radius of the circle
* @param color Specify the color of the circle
* @return void
*/
void lcd_draw_circle(uint16_t xpos, uint16_t ypos, uint16_t radius, uint16_t color)
{
int x = -radius, y = 0, err = 2 - 2 * radius, e2;
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
do {
lcd_draw_point(xpos - x, ypos + y, color);
lcd_draw_point(xpos + x, ypos + y, color);
lcd_draw_point(xpos + x, ypos - y, color);
lcd_draw_point(xpos - x, ypos - y, color);
e2 = err;
if (e2 <= y) {
err += ++ y * 2 + 1;
if(-x == y && e2 <= x)
e2 = 0;
}
if(e2 > x)
err += ++ x * 2 + 1;
} while(x <= 0);
}
/**
* @brief Fill a rectangle out at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param width Specify the width of the rectangle
* @param height Specify the height of the rectangle
* @param color Specify the color of rectangle
* @return void
*/
void lcd_fill_rect(uint16_t xpos, uint16_t ypos, uint16_t width, uint16_t height, uint16_t color)
{
uint16_t i, j;
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
for(i = 0; i < height; i ++){
for(j = 0; j < width; j ++){
lcd_draw_point(xpos + j, ypos + i, color);
}
}
}
/**
* @brief Draw a vertical line at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param height Specify the height of the vertical line
* @param color Specify the color of the vertical line
* @return void
*/
void lcd_draw_v_line(uint16_t xpos, uint16_t ypos, uint16_t height, uint16_t color)
{
uint16_t i, y1 = MIN(ypos + height, LCD_HEIGHT - 1);
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
for (i = ypos; i < y1; i ++) {
lcd_draw_point(xpos, i, color);
}
}
/**
* @brief Draw a horizonal line at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param width Specify the width of the horizonal line
* @param color Specify the color of the horizonal line
* @return void
*/
void lcd_draw_h_line(uint16_t xpos, uint16_t ypos, uint16_t width, uint16_t color)
{
uint16_t i, x1 = MIN(xpos + width, LCD_WIDTH - 1);
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
for (i = xpos; i < x1; i ++)
lcd_draw_point(i, ypos, color);
}
/**
* @brief Draw a rectangle at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param width Specify the width of the rectangle
* @param height Specify the height of the rectangle
* @param color Specify the color of rectangle
* @return void
*/
void lcd_draw_rect(uint16_t xpos, uint16_t ypos, uint16_t width, uint16_t height, uint16_t color)
{
if (xpos >= LCD_WIDTH || ypos >= LCD_HEIGHT)
return;
lcd_draw_h_line(xpos, ypos, width, color);
lcd_draw_h_line(xpos, ypos + height, width, color);
lcd_draw_v_line(xpos, ypos, height, color);
lcd_draw_v_line(xpos + width, ypos, height + 1, color);
}
/**
* @brief Initialize the LCD
* @return void
*/
void lcd_init(void)
{
tft_dc_clr();
tft_lcd_cs_clr();
tft_dc_set();
tft_lcd_cs_set();
tft_bkl_clr();
//Driving ability Setting
lcd_write_register(0xEA,0x00); //PTBA[15:8]
lcd_write_register(0xEB,0x20); //PTBA[7:0]
lcd_write_register(0xEC,0x0C); //STBA[15:8]
lcd_write_register(0xED,0xC4); //STBA[7:0]
lcd_write_register(0xE8,0x38); //OPON[7:0]
lcd_write_register(0xE9,0x10); //OPON1[7:0]
lcd_write_register(0xF1,0x01); //OTPS1B
lcd_write_register(0xF2,0x10); //GEN
//Gamma 2.2 Setting
lcd_write_register(0x40,0x01); //
lcd_write_register(0x41,0x00); //
lcd_write_register(0x42,0x00); //
lcd_write_register(0x43,0x10); //
lcd_write_register(0x44,0x0E); //
lcd_write_register(0x45,0x24); //
lcd_write_register(0x46,0x04); //
lcd_write_register(0x47,0x50); //
lcd_write_register(0x48,0x02); //
lcd_write_register(0x49,0x13); //
lcd_write_register(0x4A,0x19); //
lcd_write_register(0x4B,0x19); //
lcd_write_register(0x4C,0x16); //
lcd_write_register(0x50,0x1B); //
lcd_write_register(0x51,0x31); //
lcd_write_register(0x52,0x2F); //
lcd_write_register(0x53,0x3F); //
lcd_write_register(0x54,0x3F); //
lcd_write_register(0x55,0x3E); //
lcd_write_register(0x56,0x2F); //
lcd_write_register(0x57,0x7B); //
lcd_write_register(0x58,0x09); //
lcd_write_register(0x59,0x06); //
lcd_write_register(0x5A,0x06); //
lcd_write_register(0x5B,0x0C); //
lcd_write_register(0x5C,0x1D); //
lcd_write_register(0x5D,0xCC); //
//Power Voltage Setting
lcd_write_register(0x1B,0x1B); //VRH=4.65V
lcd_write_register(0x1A,0x01); //BT (VGH~15V,VGL~-10V,DDVDH~5V)
lcd_write_register(0x24,0x2F); //VMH(VCOM High voltage ~3.2V)
lcd_write_register(0x25,0x57); //VML(VCOM Low voltage -1.2V)
//****VCOM offset**///
lcd_write_register(0x23,0x88); //for Flicker adjust //can reload from OTP
//Power on Setting
lcd_write_register(0x18,0x34); //I/P_RADJ,N/P_RADJ, Normal mode 60Hz
lcd_write_register(0x19,0x01); //OSC_EN='1', start Osc
lcd_write_register(0x01,0x00); //DP_STB='0', out deep sleep
lcd_write_register(0x1F,0x88);// GAS=1, VOMG=00, PON=0, DK=1, XDK=0, DVDH_TRI=0, STB=0
tft_delay_ms(5);
lcd_write_register(0x1F,0x80);// GAS=1, VOMG=00, PON=0, DK=0, XDK=0, DVDH_TRI=0, STB=0
tft_delay_ms(5);
lcd_write_register(0x1F,0x90);// GAS=1, VOMG=00, PON=1, DK=0, XDK=0, DVDH_TRI=0, STB=0
tft_delay_ms(5);
lcd_write_register(0x1F,0xD0);// GAS=1, VOMG=10, PON=1, DK=0, XDK=0, DDVDH_TRI=0, STB=0
tft_delay_ms(5);
//262k/65k color selection
lcd_write_register(0x17,0x05); //default 0x06 262k color // 0x05 65k color
//SET PANEL
lcd_write_register(0x36,0x00); //SS_P, GS_P,REV_P,BGR_P
//Display ON Setting
lcd_write_register(0x28,0x38); //GON=1, DTE=1, D=1000
tft_delay_ms(40);
lcd_write_register(0x28,0x3F); //GON=1, DTE=1, D=1100
lcd_write_register(0x16,0x18);
//Set GRAM Area
lcd_write_register(0x02,0x00);
lcd_write_register(0x03,0x00); //Column Start
lcd_write_register(0x04,0x00);
lcd_write_register(0x05,0xEF); //Column End
lcd_write_register(0x06,0x00);
lcd_write_register(0x07,0x00); //Row Start
lcd_write_register(0x08,0x01);
lcd_write_register(0x09,0x3F); //Row End
lcd_clear_screen(BLACK);
tft_bkl_set();
}
/**
* @brief Turn the backlight on
* @return void
*/
void lcd_on(void)
{
tft_bkl_set();
}
/**
* @brief Turn the backlight off
* @return void
*/
void lcd_off(void)
{
tft_bkl_clr();
}
/**
* @brief Draw a bitmap picture at the specified position on LCD
* @param xpos Specify x position
* @param ypos Specify y position
* @param bitmap A pointer to bitmap array
* @return void
*/
void lcd_draw_bitmap(uint16_t xpos, uint16_t ypos, uint8_t *bitmap)
{
uint32_t index = 0, width = 0, height = 0;
uint32_t bmpaddress, bit_pixel = 0;
uint16_t color = 0;
uint32_t offset = 0;
uint16_t k;
bmpaddress = (uint32_t)bitmap;
/* Get bitmap data address offset */
index = *(uint16_t *) (bmpaddress + 10);
index |= (*(uint16_t *) (bmpaddress + 12)) << 16;
/* Read bitmap width */
width = *(uint16_t *) (bmpaddress + 18);
width |= (*(uint16_t *) (bmpaddress + 20)) << 16;
/* Read bitmap height */
height = *(uint16_t *) (bmpaddress + 22);
height |= (*(uint16_t *) (bmpaddress + 24)) << 16;
/* Read bit/pixel */
bit_pixel = *(uint16_t *) (bmpaddress + 28);
if (bit_pixel != 24)
return;
offset = ((((width * bit_pixel) + 31 ) >> 5) << 2) >> 1;
uint8_t *ibuf = (uint8_t *)malloc(width*3);
if (!ibuf)
return;
for (int i = 0; i < height; i ++) {
memcpy(ibuf, &bitmap[index], offset);
index += offset;
memcpy(ibuf + offset, &bitmap[index], offset);
index += offset;
lcd_set_cursor(xpos, ypos + i);
lcd_write_byte(0x22, LCD_CMD);
for (int j = 0; j < width; j ++) {
k = j * 3;
color = (uint16_t)(((ibuf[k + 2] >> 3) << 11 ) | ((ibuf[k + 1] >> 2) << 5) | (ibuf[k] >> 3));
lcd_write_word(color);
}
}
free(ibuf);
}
|
C
|
#include<stdio.h>
void display(int s, int n)
{
if(s<=n)
{
printf("%d\n", s); //1 2 3 4 5
s++; //2 3 4 5 6
display(s, n);
}
}
void main()
{
int s=1;
int n=5;
display(s, n); //initial call
}
|
C
|
#include <stdio.h>
#include <string.h>
int main() {
char mohammad[512];
char * find;
printf("I will collect everything you type BUT new-line: \n");
fgets(mohammad, 512, stdin);
find = strchr(mohammad, '\n');
if (find) {
*find = '\0';
} else {
while (getchar() != '\n') {
continue;
}
}
printf("\"%s\"", mohammad);
getchar();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int m[100][100], i, j, x, y, som=0, prod=1;
printf("I x J: \n");
scanf("%d %d", &i, &j);
for (x = 0; x < i; x++){
for (y = 0; y < j; y++){
printf("M[%d][%d]: ", x, y);
scanf("%d", &m[x][y]);
}
}
for (x = 0; x < i; x++){
for (y = 0; y < j; y++){
if ((x+y) % 2 == 0)
som += m[x][y];
else
prod *= m[x][y];
}
}
printf("O somatório dos elementos cuja soma dos ı́ndices seja par: %d\n", som);
printf("O produtório dos elementos cuja soma dos ı́ndices seja ı́mpar: %d\n", prod);
return(0);
}
|
C
|
#include "net.h"
#include "string.h"
struct sockaddr_in new_addr(char *ip, unsigned int port) {
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip);
return addr;
}
int create_sock(char *ip, unsigned int port, struct sockaddr_storage *local_sas) {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
printf("Error creating socket\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
struct sockaddr_in local_addr = new_addr(ip, port);
if(bind(sockfd, (struct sockaddr *)&local_addr, sizeof(local_addr)) != 0) {
printf("Cannot bind");
fflush(stdout);
exit(EXIT_FAILURE);
}
if(!memcpy(local_sas, &local_addr, sizeof(local_addr))) {
printf("memcpy local_sas error\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
return sockfd;
}
|
C
|
int main ()
{
int m,sm,i;
scanf("%d",&i);
m=i;
scanf("%d",&i);
if (m>i)sm=i;
else
{
sm=m;
m=i;
}
while (i!=0)
{
scanf("%d",&i);
if (m>i) sm=i;
else
{
sm=m;
m=i;
}
}
printf ("O segundo maior é: %d",sm);
return 0;
}
|
C
|
#define EXTUNIX_WANT_ENDIAN
#include "config.h"
#include <stdint.h>
/* Copyright © 2012 Goswin von Brederlow <goswin-v-b@web.de> */
/* Convert an intX_t from one endianness to another */
#define CONV(name, type, conv, type_val, val_type) \
CAMLprim value caml_extunix_##name(value v_x) \
{ \
type x = type_val(v_x); \
x = conv(x); \
return (val_type(x)); \
}
/* Get an intX_t out of a string */
#define GET(name, type, conv, Val_type) \
CAMLprim value caml_extunix_get_##name(value v_str, value v_off) { \
char *str = String_val(v_str); \
size_t off = Long_val(v_off); \
type x; \
memcpy(&x, str + off, sizeof(x)); \
x = conv(x); \
return (Val_type(x)); \
}
/* Store an intX_t in a string */
#define SET(name, type, conv, Type_val) \
CAMLprim value caml_extunix_set_##name(value v_str, value v_off, value v_x) { \
char *str = String_val(v_str); \
size_t off = Long_val(v_off); \
type x = Type_val(v_x); \
x = conv(x); \
memcpy(str + off, &x, sizeof(x)); \
return Val_unit; \
}
#if defined(EXTUNIX_HAVE_ENDIAN)
#include <endian.h>
#include <arpa/inet.h>
/* Big endian */
CONV(htobe16, uint16_t, htobe16, Long_val, Val_long)
CONV(htobe16_signed, int16_t, htobe16, Long_val, Val_long)
CONV(be16toh, uint16_t, be16toh, Long_val, Val_long)
CONV(be16toh_signed, int16_t, be16toh, Long_val, Val_long)
CONV(htobe31, uint32_t, htobe32, Long_val, Val_long)
CONV(htobe31_signed, int32_t, htobe32, Long_val, Val_long)
CONV(be31toh, uint32_t, be32toh, Long_val, Val_long)
CONV(be31toh_signed, int32_t, be32toh, Long_val, Val_long)
CONV(htobe32, int32_t, htobe32, Int32_val, caml_copy_int32)
CONV(be32toh, int32_t, be32toh, Int32_val, caml_copy_int32)
CONV(htobe64, int64_t, htobe64, Int64_val, caml_copy_int64)
CONV(be64toh, int64_t, be64toh, Int64_val, caml_copy_int64)
GET(bu16, uint16_t, be16toh, Val_long)
GET(bs16, int16_t, be16toh, Val_long)
GET(bu31, uint32_t, be32toh, Val_long)
GET(bs31, int32_t, be32toh, Val_long)
GET(bs32, int32_t, be32toh, caml_copy_int32)
GET(bu63, uint64_t, be64toh, Val_long)
GET(bs63, int64_t, be64toh, Val_long)
GET(bs64, int64_t, be64toh, caml_copy_int64)
SET(b16, uint16_t, htobe16, Long_val)
SET(b31, uint32_t, htobe32, Long_val)
SET(b32, uint32_t, htobe32, Int32_val)
SET(b63, uint64_t, htobe64, Long_val)
SET(b64, uint64_t, htobe64, Int64_val)
/* Little endian */
CONV(htole16, uint16_t, htole16, Long_val, Val_long)
CONV(htole16_signed, int16_t, htole16, Long_val, Val_long)
CONV(le16toh, uint16_t, le16toh, Long_val, Val_long)
CONV(le16toh_signed, int16_t, le16toh, Long_val, Val_long)
CONV(htole31, uint32_t, htole32, Long_val, Val_long)
CONV(htole31_signed, int32_t, htole32, Long_val, Val_long)
CONV(le31toh, uint32_t, le32toh, Long_val, Val_long)
CONV(le31toh_signed, int32_t, le32toh, Long_val, Val_long)
CONV(htole32, int32_t, htole32, Int32_val, caml_copy_int32)
CONV(le32toh, int32_t, le32toh, Int32_val, caml_copy_int32)
CONV(htole64, int64_t, htole64, Int64_val, caml_copy_int64)
CONV(le64toh, int64_t, le64toh, Int64_val, caml_copy_int64)
GET(lu16, uint16_t, le16toh, Val_long)
GET(ls16, int16_t, le16toh, Val_long)
GET(lu31, uint32_t, le32toh, Val_long)
GET(ls31, int32_t, le32toh, Val_long)
GET(ls32, int32_t, le32toh, caml_copy_int32)
GET(lu63, uint64_t, le64toh, Val_long)
GET(ls63, int64_t, le64toh, Val_long)
GET(ls64, int64_t, le64toh, caml_copy_int64)
SET(l16, uint16_t, htole16, Long_val)
SET(l31, uint32_t, htole32, Long_val)
SET(l32, uint32_t, htole32, Int32_val)
SET(l63, uint64_t, htole64, Long_val)
SET(l64, uint64_t, htole64, Int64_val)
#endif /* EXTUNIX_HAVE_ENDIAN */
/* Host endian */
#define id(x) x
GET(u8, uint8_t, id, Val_long)
GET(s8, int8_t, id, Val_long)
GET(hu16, uint16_t, id, Val_long)
GET(hs16, int16_t, id, Val_long)
GET(hu31, uint32_t, id, Val_long)
GET(hs31, int32_t, id, Val_long)
GET(hs32, int32_t, id, caml_copy_int32)
GET(hu63, uint64_t, id, Val_long)
GET(hs63, int64_t, id, Val_long)
GET(hs64, int64_t, id, caml_copy_int64)
SET(8, uint8_t, id, Long_val)
SET(h16, uint16_t, id, Long_val)
SET(h31, uint32_t, id, Long_val)
SET(h32, uint32_t, id, Int32_val)
SET(h63, uint64_t, id, Long_val)
SET(h64, uint64_t, id, Int64_val)
|
C
|
#include<stdio.h>
int main()
{
int n,o=0,i;
scanf("%d",&n);
char a[n];
scanf("%s",a);
for( i=0;i<n;i++)
{
if(a[i]==a[i+1])
o++;
}
printf("%d",o);
}
|
C
|
#include <stdio.h>
#include <ctype.h>
int are_anagram(char *word1, char *word2);
int read_line(char *str, int n);
int main() {
char sen1[101];
char sen2[101];
printf("Please enter the first word\n");
read_line(sen1, 30);
printf("Please enter the second word\n");
read_line(sen2, 30);
if (are_anagram(sen1, sen2))
printf("The words are anagrams.\n");
else
printf("The words are NOT anagrams.\n");
return 0;
}
int read_line(char *str, int n) {
int ch, i = 0;
while ((ch = getchar()) != '\n') {// printf("reading %c", ch);
if (i < n)
*str++ = ch;
}
*str = '\0';
return i;
}
int are_anagram(char *word1, char *word2) {
int letter_counts[26] = {0};
char *p;
char *q;
int i, count = 0;
char ch;
for (p = word1; *p != '\0'; p++)
if (isalpha(*p)) {
ch = tolower(*p);
letter_counts[ch - 'a']++;
}
for (q = word2; *q != '\0'; q++)
if (isalpha(*q)) {
ch = tolower(*q);
letter_counts[ch - 'a']--;
}
for (i = 0; i < 26; i++) {
if (letter_counts[i] == 0)
count++;
}
if (count == 26)
return 1;
else
return 0;
return 0;
}
|
C
|
/*
* Copyright (C) 2013 Politecnico di Torino, Italy
* TORSEC group -- http://security.polito.it
*
* Author: Roberto Sassu <roberto.sassu@polito.it>
*
* 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 2 of the
* License.
*
* File: ima_template_lib.c
* Library of supported template fields.
*/
#include "ima_template_lib.h"
static bool ima_template_hash_algo_allowed(u8 algo)
{
if (algo == HASH_ALGO_SHA1 || algo == HASH_ALGO_MD5)
return true;
return false;
}
enum data_formats {
DATA_FMT_DIGEST = 0,
DATA_FMT_DIGEST_WITH_ALGO,
DATA_FMT_STRING,
DATA_FMT_HEX
};
static int ima_write_template_field_data(const void *data, const u32 datalen,
enum data_formats datafmt,
struct ima_field_data *field_data)
{
u8 *buf, *buf_ptr;
u32 buflen = datalen;
if (datafmt == DATA_FMT_STRING)
buflen = datalen + 1;
buf = kzalloc(buflen, GFP_KERNEL);
if (!buf)
return -ENOMEM;
memcpy(buf, data, datalen);
/*
* Replace all space characters with underscore for event names and
* strings. This avoid that, during the parsing of a measurements list,
* filenames with spaces or that end with the suffix ' (deleted)' are
* split into multiple template fields (the space is the delimitator
* character for measurements lists in ASCII format).
*/
if (datafmt == DATA_FMT_STRING) {
for (buf_ptr = buf; buf_ptr - buf < datalen; buf_ptr++)
if (*buf_ptr == ' ')
*buf_ptr = '_';
}
field_data->data = buf;
field_data->len = buflen;
return 0;
}
static void ima_show_template_data_ascii(struct seq_file *m,
enum ima_show_type show,
enum data_formats datafmt,
struct ima_field_data *field_data)
{
u8 *buf_ptr = field_data->data;
u32 buflen = field_data->len;
switch (datafmt) {
case DATA_FMT_DIGEST_WITH_ALGO:
buf_ptr = strnchr(field_data->data, buflen, ':');
if (buf_ptr != field_data->data)
seq_printf(m, "%s", field_data->data);
/* skip ':' and '\0' */
buf_ptr += 2;
buflen -= buf_ptr - field_data->data;
case DATA_FMT_DIGEST:
case DATA_FMT_HEX:
if (!buflen)
break;
ima_print_digest(m, buf_ptr, buflen);
break;
case DATA_FMT_STRING:
seq_printf(m, "%s", buf_ptr);
break;
default:
break;
}
}
static void ima_show_template_data_binary(struct seq_file *m,
enum ima_show_type show,
enum data_formats datafmt,
struct ima_field_data *field_data)
{
u32 len = (show == IMA_SHOW_BINARY_OLD_STRING_FMT) ?
strlen(field_data->data) : field_data->len;
if (show != IMA_SHOW_BINARY_NO_FIELD_LEN) {
u32 field_len = !ima_canonical_fmt ? len : cpu_to_le32(len);
ima_putc(m, &field_len, sizeof(field_len));
}
if (!len)
return;
ima_putc(m, field_data->data, len);
}
static void ima_show_template_field_data(struct seq_file *m,
enum ima_show_type show,
enum data_formats datafmt,
struct ima_field_data *field_data)
{
switch (show) {
case IMA_SHOW_ASCII:
ima_show_template_data_ascii(m, show, datafmt, field_data);
break;
case IMA_SHOW_BINARY:
case IMA_SHOW_BINARY_NO_FIELD_LEN:
case IMA_SHOW_BINARY_OLD_STRING_FMT:
ima_show_template_data_binary(m, show, datafmt, field_data);
break;
default:
break;
}
}
void ima_show_template_digest(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data)
{
ima_show_template_field_data(m, show, DATA_FMT_DIGEST, field_data);
}
void ima_show_template_digest_ng(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data)
{
ima_show_template_field_data(m, show, DATA_FMT_DIGEST_WITH_ALGO,
field_data);
}
void ima_show_template_string(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data)
{
ima_show_template_field_data(m, show, DATA_FMT_STRING, field_data);
}
void ima_show_template_sig(struct seq_file *m, enum ima_show_type show,
struct ima_field_data *field_data)
{
ima_show_template_field_data(m, show, DATA_FMT_HEX, field_data);
}
static int ima_eventdigest_init_common(u8 *digest, u32 digestsize, u8 hash_algo,
struct ima_field_data *field_data)
{
/*
* digest formats:
* - DATA_FMT_DIGEST: digest
* - DATA_FMT_DIGEST_WITH_ALGO: [<hash algo>] + ':' + '\0' + digest,
* where <hash algo> is provided if the hash algoritm is not
* SHA1 or MD5
*/
u8 buffer[CRYPTO_MAX_ALG_NAME + 2 + IMA_MAX_DIGEST_SIZE] = { 0 };
enum data_formats fmt = DATA_FMT_DIGEST;
u32 offset = 0;
if (hash_algo < HASH_ALGO__LAST) {
fmt = DATA_FMT_DIGEST_WITH_ALGO;
offset += snprintf(buffer, CRYPTO_MAX_ALG_NAME + 1, "%s",
hash_algo_name[hash_algo]);
buffer[offset] = ':';
offset += 2;
}
if (digest)
memcpy(buffer + offset, digest, digestsize);
else
/*
* If digest is NULL, the event being recorded is a violation.
* Make room for the digest by increasing the offset of
* IMA_DIGEST_SIZE.
*/
offset += IMA_DIGEST_SIZE;
return ima_write_template_field_data(buffer, offset + digestsize,
fmt, field_data);
}
/*
* This function writes the digest of an event (with size limit).
*/
int ima_eventdigest_init(struct ima_event_data *event_data,
struct ima_field_data *field_data)
{
struct {
struct ima_digest_data hdr;
char digest[IMA_MAX_DIGEST_SIZE];
} hash;
u8 *cur_digest = NULL;
u32 cur_digestsize = 0;
struct inode *inode;
int result;
memset(&hash, 0, sizeof(hash));
if (event_data->violation) /* recording a violation. */
goto out;
if (ima_template_hash_algo_allowed(event_data->iint->ima_hash->algo)) {
cur_digest = event_data->iint->ima_hash->digest;
cur_digestsize = event_data->iint->ima_hash->length;
goto out;
}
if (!event_data->file) /* missing info to re-calculate the digest */
return -EINVAL;
inode = file_inode(event_data->file);
hash.hdr.algo = ima_template_hash_algo_allowed(ima_hash_algo) ?
ima_hash_algo : HASH_ALGO_SHA1;
result = ima_calc_file_hash(event_data->file, &hash.hdr);
if (result) {
integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode,
event_data->filename, "collect_data",
"failed", result, 0);
return result;
}
cur_digest = hash.hdr.digest;
cur_digestsize = hash.hdr.length;
out:
return ima_eventdigest_init_common(cur_digest, cur_digestsize,
HASH_ALGO__LAST, field_data);
}
/*
* This function writes the digest of an event (without size limit).
*/
int ima_eventdigest_ng_init(struct ima_event_data *event_data,
struct ima_field_data *field_data)
{
u8 *cur_digest = NULL, hash_algo = HASH_ALGO_SHA1;
u32 cur_digestsize = 0;
if (event_data->violation) /* recording a violation. */
goto out;
cur_digest = event_data->iint->ima_hash->digest;
cur_digestsize = event_data->iint->ima_hash->length;
hash_algo = event_data->iint->ima_hash->algo;
out:
return ima_eventdigest_init_common(cur_digest, cur_digestsize,
hash_algo, field_data);
}
static int ima_eventname_init_common(struct ima_event_data *event_data,
struct ima_field_data *field_data,
bool size_limit)
{
const char *cur_filename = NULL;
u32 cur_filename_len = 0;
BUG_ON(event_data->filename == NULL && event_data->file == NULL);
if (event_data->filename) {
cur_filename = event_data->filename;
cur_filename_len = strlen(event_data->filename);
if (!size_limit || cur_filename_len <= IMA_EVENT_NAME_LEN_MAX)
goto out;
}
if (event_data->file) {
cur_filename = event_data->file->f_path.dentry->d_name.name;
cur_filename_len = strlen(cur_filename);
} else
/*
* Truncate filename if the latter is too long and
* the file descriptor is not available.
*/
cur_filename_len = IMA_EVENT_NAME_LEN_MAX;
out:
return ima_write_template_field_data(cur_filename, cur_filename_len,
DATA_FMT_STRING, field_data);
}
/*
* This function writes the name of an event (with size limit).
*/
int ima_eventname_init(struct ima_event_data *event_data,
struct ima_field_data *field_data)
{
return ima_eventname_init_common(event_data, field_data, true);
}
/*
* This function writes the name of an event (without size limit).
*/
int ima_eventname_ng_init(struct ima_event_data *event_data,
struct ima_field_data *field_data)
{
return ima_eventname_init_common(event_data, field_data, false);
}
/*
* ima_eventsig_init - include the file signature as part of the template data
*/
int ima_eventsig_init(struct ima_event_data *event_data,
struct ima_field_data *field_data)
{
enum data_formats fmt = DATA_FMT_HEX;
struct evm_ima_xattr_data *xattr_value = event_data->xattr_value;
int xattr_len = event_data->xattr_len;
int rc = 0;
if ((!xattr_value) || (xattr_value->type != EVM_IMA_XATTR_DIGSIG))
goto out;
rc = ima_write_template_field_data(xattr_value, xattr_len, fmt,
field_data);
out:
return rc;
}
|
C
|
#include "listasimple.h"
#include <stdlib.h>
#include <stdio.h>
int inicializarLista(ListaSimple * lista){
lista->primero = NULL;
lista->ultimo = NULL;
lista->length = 0;
return 0;
}
int insertarInicio(ListaSimple* lista, int val){
Nodo * nuevo = (Nodo * )malloc(sizeof(Nodo));
nuevo->val = val;
if (lista->primero == NULL){
lista->primero = nuevo;
lista->ultimo = nuevo;
lista->length++;
}else{
lista->ultimo->siguiente = nuevo;
nuevo->anterior = lista->ultimo;
lista->ultimo = nuevo;
}
return 0;
}
int eliminarUltimo(ListaSimple* lista){
if(lista->ultimo != NULL){
if(lista->ultimo->anterior != NULL){
lista->ultimo = lista->ultimo->anterior;
lista->ultimo->siguiente = NULL;
}else{
lista->ultimo = NULL;
lista->primero = NULL;
}
}
return 0;
}
int imprimirLista(ListaSimple* lista){
if (lista->primero != NULL){
Nodo *aux = lista->primero;
while(aux != NULL){
printf("%d\n",aux->val);
aux = aux->siguiente;
}
}else{
printf("La lista está vacía\n");
}
return 0;
}
int eliminarPorBusqueda(ListaSimple* lista, int posicion){
int contador = 1;
if (lista->primero != NULL){
Nodo *aux = lista->primero;
while(contador < posicion){
if(aux != NULL){
printf("a");
aux = aux->siguiente;
contador++;
}else{
break;
}
}
if(aux->anterior != NULL){
if(aux->siguiente != NULL){
//Tiene nodo antes y después
aux->anterior->siguiente = aux->siguiente;
aux->siguiente->anterior = aux->anterior;
}else{
//Tiene nodo antes pero no después
lista->ultimo = aux->anterior;
aux->anterior->siguiente = NULL;
}
}else{
if(aux->siguiente != NULL){
//No tiene nodo antes pero si después
lista->primero = aux->siguiente;
aux->siguiente->anterior = NULL;
}else{
//No tiene nodo antes ni después
lista->primero = NULL;
lista->ultimo = NULL;
}
}
}else{
printf("La lista está vacía\n");
}
return 0;
}
|
C
|
#include "../headers/SFCodes.h"
int getIndexOfSymbol(char c)
{
int index = (int) c;
if(c>=0) return c;
return c*(-1) + 2*(128+c);
}
char getSymbolOfIndex(int index)
{
char c;
if(index<=127) return (char) index;
return (char) (index-256);
}
SFCodes initializeSFCodes()
{
int i;
SFCodes bloco = (SFCodes) malloc(sizeof(struct sfc));
bloco->codes = (char**) malloc( sizeof(char*)*256 );
for(i=0;i<256;i++)
bloco->codes[i] = NULL;
bloco->nBytes = bloco->nBits_compressed = 0;
return bloco;
}
SFCodes freeSFCodes(SFCodes bloco)
{
int i;
for(i=0;i<256;i++)
free(bloco->codes[i]);
free(bloco);
return NULL;
}
void setBytes(SFCodes bloco, int bytes)
{
bloco->nBytes = bytes;
}
int getBytes(SFCodes bloco)
{
return bloco->nBytes;
}
char* getCodeSF(SFCodes bloco, char c)
{
return bloco->codes[getIndexOfSymbol(c)];
}
void setCodeSF(SFCodes bloco, int index, char* code)
{
bloco->codes[index] = strdup(code);
}
void addBitsS_bloco(SFCodes bloco, char* code)
{
bloco->nBits_compressed += strlen(code);
}
void addBitsI_bloco(SFCodes bloco,int bits)
{
bloco->nBits_compressed += bits;
}
int getBits_bloco(SFCodes bloco)
{
return bloco->nBits_compressed;
}
float getCompression_bloco(SFCodes bloco)
{
return bloco->nBits_compressed / (bloco->nBytes * 8.0);
}
|
C
|
#include <stdio.h>
#include <inttypes.h>
// gcc -std=c99 max.c max.s ; ./a.out
int64_t getmax(int64_t a, int64_t b, int64_t c);
int main(){
printf("%ld\n", getmax(40, -9, 67));
printf("%ld\n", getmax( 0, 4, -7));
printf("%ld\n", getmax(33, -99, 4));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char *argv[]) {
/* Error */
if (2 != argc) {
printf("Error\n");
return 1;
}
int num = atoi(argv[1]);
int i, j;
bool flag = false;
for (i = 1; i < num; i++) {
for (j = 1; j < num; j++) {
if ((num-(i+j)) * (num-(i+j)) == i*i + j*j) {
printf("%d %d %d\n", i, j, num-(i+j));
flag = true;
}
if (flag) {
break;
}
}
if (flag) {
break;
}
}
printf("ans=%d\n", i * j * (num-(i+j)));
return 0;
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mytar.h"
extern char *use;
/** Copy nBytes bytes from the origin file to the destination file.
*
* origin: pointer to the FILE descriptor associated with the origin file
* destination: pointer to the FILE descriptor associated with the destination file
* nBytes: number of bytes to copy
*
* Returns the number of bytes actually copied or -1 if an error occured.
*/
int
copynFile(FILE * origin, FILE * destination, int nBytes)
{
// Complete the function
int c,contador = 0;
/* Read file byte by byte */
while ((c = getc(origin)) != EOF && (contador < nBytes)) {
/* Print byte to stdout */
putc(c, destination);
contador++;
}
return contador;
}
/** Loads a string from a file.
*
* file: pointer to the FILE descriptor
*
* The loadstr() function must allocate memory from the heap to store
* the contents of the string read from the FILE.
* Once the string has been properly built in memory, the function returns
* the starting address of the string (pointer returned by malloc())
*
* Returns: !=NULL if success, NULL if error
*/
char*
loadstr(FILE * file)
{
// Complete the function
int n, contador = 0;
char *buffer;
while((n!= EOF) && (n!=(int)'\0'))
{
n = getc(file);
contador++;
if(n == EOF) return NULL;
}
buffer = (char*)malloc(contador);
fseek(file, -contador, SEEK_CUR); //vuelve a la pos inicial
fread(buffer,1,contador, file);
return buffer;
}
/** Read tarball header and store it in memory.
*
* tarFile: pointer to the tarball's FILE descriptor
* nFiles: output parameter. Used to return the number
* of files stored in the tarball archive (first 4 bytes of the header).
*
* On success it returns the starting memory address of an array that stores
* the (name,size) pairs read from the tar file. Upon failure, the function returns NULL.
*/
stHeaderEntry*
readHeader(FILE * tarFile, int *nFiles)
{
// Complete the function
int i ;
stHeaderEntry *stH = NULL;
if(tarFile == NULL){
perror("Ha habido un problema con el tarFile");
return NULL;
}
else {
fread(nFiles, sizeof(int), 1, tarFile);
stH = (stHeaderEntry *) malloc(sizeof(stHeaderEntry) * (*nFiles));
for (i = 0; i < (*nFiles); i++) {
stH[i].name = loadstr(tarFile);
fread(&stH[i].size, sizeof(int), 1, tarFile);
}
return stH;
}
}
/** Creates a tarball archive
*
* nfiles: number of files to be stored in the tarball
* filenames: array with the path names of the files to be included in the tarball
* tarname: name of the tarball archive
*
* On success, it returns EXIT_SUCCESS; upon error it returns EXIT_FAILURE.
* (macros defined in stdlib.h).
*
* HINTS: First reserve room in the file to store the tarball header.
* Move the file's position indicator to the data section (skip the header)
* and dump the contents of the source files (one by one) in the tarball archive.
* At the same time, build the representation of the tarball header in memory.
* Finally, rewind the file's position indicator, write the number of files as well as
* the (file name,file size) pairs in the tar archive.
*
* Important reminder: to calculate the room needed for the header, a simple sizeof
* of stHeaderEntry will not work. Bear in mind that, on disk, file names found in (name,size)
* pairs occupy strlen(name)+1 bytes.
*
*/
int
createTar(int nFiles, char *fileNames[], char tarName[])
{
// Complete the function
FILE *tFile, *iFile;
unsigned headerSize;
stHeaderEntry* header;
if(nFiles<=0){
fprintf (stderr, "%s", use);
return EXIT_FAILURE;
}
tFile= fopen(tarName, "wx");
headerSize = sizeof(int);
header = (stHeaderEntry*)malloc(sizeof(stHeaderEntry) *nFiles);
for(int i=0; i < nFiles; ++i){
int nameSize = strlen(fileNames[i]) + 1;
header[i].name = (char*)malloc(nameSize);
strcpy(header[i].name, fileNames[i]);
headerSize += nameSize + sizeof(header->size);
}
fseek(tFile, headerSize, SEEK_SET);
for(int i=0; i< nFiles; ++i){
iFile = fopen(fileNames[i], "r");
header[i].size = copynFile(iFile, tFile, INT_MAX);
fclose(iFile);
}
rewind(tFile);
fwrite(&nFiles, sizeof(int),1,tFile);
for(int i=0; i<nFiles; ++i){
fwrite(header[i].name, 1, strlen(header[i].name) + 1, tFile);
fwrite(&(header[i].size), sizeof(header[i].size), 1, tFile);
}
fprintf(stdout, "El archivo mtar se ha creado satisfactoriamente\n");
for(int i=0; i<nFiles;++i){
free(header[i].name);
}
free(header);
fclose(tFile);
return EXIT_SUCCESS;
}
/** Extract files stored in a tarball archive
*
* tarName: tarball's pathname
*
* On success, it returns EXIT_SUCCESS; upon error it returns EXIT_FAILURE.
* (macros defined in stdlib.h).
*
* HINTS: First load the tarball's header into memory.
* After reading the header, the file position indicator will be located at the
* tarball's data section. By using information from the
* header --number of files and (file name, file size) pairs--, extract files
* stored in the data section of the tarball.
*
*/
int
extractTar(char tarName[])
{
// Complete the function
FILE *tFile = NULL;
FILE *dFile = NULL;
int i;
unsigned char* c;
int nFiles;
stHeaderEntry *stH = NULL;
//stH = (stHeaderEntry *) malloc(sizeof(stHeaderEntry) * (nFiles));
tFile = fopen(tarName, "r");
if(tFile == NULL){
perror("Error en el archivo tar. Inténtalo de nuevo!");
return EXIT_FAILURE;
}
stH = readHeader(tFile, &nFiles);
for (i = 0; i < nFiles; i++) {
dFile = fopen(stH[i].name, "w");
if(dFile == NULL){
perror("Ha habido un error con el fichero destino.");
return EXIT_FAILURE;
}
else {
c = (unsigned char*) malloc(stH[i].size);
copynFile(tFile,dFile, stH[i].size);
fclose(dFile);
}
}
for (i = 0; i < nFiles; i++){
free(stH[i].name);
}
free(stH);
fclose(tFile);
printf("\nEnhorabuena !! El fichero se acaba de extraer correctamente\n\n");
return EXIT_SUCCESS;
}
//extension 1: listar ficheros del mtar
int listTar(char tarName[])
{
int ret = EXIT_SUCCESS, i = 0;
FILE* fo = fopen(tarName, "r");
int* nFiles = malloc(sizeof(int));
stHeaderEntry* stHE;
if(fo == NULL)
{
perror("Error al abrir el archivo");
ret = EXIT_FAILURE;
}
else
{
stHE = readHeader(fo,nFiles);
if(stHE == NULL) ret = EXIT_FAILURE;
else
{
printf("Existen en el .mtar %d archivos.\n\n", *nFiles);
for(; i < *nFiles; i++)
{
printf("Nombre del fichero %d : %s.\n", i,stHE[i].name);
printf("Tam del fichero %d : %d.\n\n", i,stHE[i].size);
}
free(stHE);
}
fclose(fo);
}
return ret;
}
//extension 2: add fichero de un mtar
int addFile(char tarName[], char fileName[])
{
int ret = EXIT_SUCCESS, i;
FILE* fo = fopen(tarName, "r");
int* nFiles = malloc(sizeof(int));
stHeaderEntry* stHE;
stHeaderEntry* stHEn;
if(fo == NULL)
{
perror("Error al abrir el archivo");
ret = EXIT_FAILURE;
}
else
{
stHE = readHeader(fo,nFiles);
if(stHE == NULL) ret = EXIT_FAILURE;
else
{
stHEn = (stHeaderEntry *) malloc(sizeof(stHeaderEntry) * (*nFiles + 1));
for(i = 0; i < *nFiles; i++)
{
stHEn[i].name = stHE[i].name;
stHEn[i].size = stHE[i].size;
}
stHEn[i].name = fileName;
stHEn[i].size = strlen(fileName); //mal habria que leer el ficheroo para saber su tammm
*nFiles = *nFiles + 1;
//Tenemos el Header nuevo faltan por copiar los datos
free(stHE);
free(stHEn);
}
fclose(fo);
}
return ret;
}
//extension 3: eliminar fichero de un mtar
int removeFile(char tarName[], char fileName[])
{
int ret = EXIT_SUCCESS;
return ret;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include "Glue_utilities.h"
#include "SarsaAgent.h"
#include<iostream>
#include "AgentMessages.h"
int numActions=1;
Action action;
void agent_init(const Task_specification task_spec)
{
task_spec_struct tss; /*declare task_spec_struct*/
srand(0);/*seed the randomness*/
assert (task_spec != 0);
parse_task_spec(task_spec, &tss); /*Parsing task_specification*/
/*allocating memory for one Action*/
action.numInts = tss.num_discrete_action_dims;
action.intArray = (int*)malloc(sizeof(int)*action.numInts);
action.numDoubles = tss.num_continuous_action_dims;
action.doubleArray = (double*)malloc(sizeof(double)*action.numDoubles);
std::cerr<<"\tSarsa agent thinks there are"<<action.numInts<<" actions"<<std::endl;
numActions=(int)tss.action_maxs[0];
free(tss.obs_types);
free(tss.obs_mins);
free(tss.obs_maxs);
free(tss.action_types);
free(tss.action_mins);
free(tss.action_maxs);
}
Action agent_start(Observation o)
{
unsigned int i = 0;
/*pick the next action. Note: the policy is frozen internally. We haven't written an egreedy
*and a greedy method like in sample_agent.c The epsilon is removed within the egreedy method if
*the policy is frozen*/
action.intArray[0] = rand()%numActions;
return action;
}
Action agent_step(Reward r, Observation o)
{
action.intArray[0] = rand()%numActions;
return action;
}
void agent_end(Reward r)
{
}
void agent_cleanup(){
/*free all the memory*/
free(action.intArray);
/*clear all values in the actions*/
action.numInts = 0;
action.numDoubles = 0;
action.intArray = 0;
action.doubleArray = 0;
}
Message agent_message(const Message theMessage){
AgentMessages theMessageObject = AgentMessageParser::parseMessage(theMessage);
return "This agent does not respond to any messages.";
// } catch (NotAnRLVizMessageException e) {
// System.err.println("Someone sent EnvironmentShell a message that wasn't RL-Viz compatible");
// return "I only respond to RL-Viz messages!";
// }
// if(theMessageObject.canHandleAutomatically(null))
// return theMessageObject.handleAutomatically(this);
// System.out.println("We need some code written in Agent Message for DynaSars!");
// Thread.dumpStack();
// return null;
// }
/*no messages currently implemented*/
}
void agent_freeze(){
/*sets the agent to freeze mode*/
}
|
C
|
/*====================================================================*
*
* double _cosh(double x);
*
* _math.h
*
* Compute the hyperbolic cosine of a double precision vlue using the approximation series
* shown below. Terminate when two successive approximations are indistinguishable.
*
* _cosh(x) = 1 + (x^2)/2! + (x^4)/4! + (x^6)/6! + ...
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef _COSH_SOURCE
#define _COSH_SOURCE
#include "../math/_math.h"
double _cosh (register double x)
{
register int term = 0;
register double prod = 1;
register double fact = 1;
register double old = 0.0;
register double sum;
for (sum = 1; sum != old; sum += prod /fact)
{
prod *= x;
prod *= x;
fact *= ++term;
fact *= ++term;
old = sum;
}
return (sum);
}
#endif
|
C
|
#include <stdio.h>
int main(){
float marks;
char grade='A';
printf("Enter percentage marks of student: ");
scanf("%f",&marks);
if(marks>90)
grade='A';
else if(marks>80)
grade='B';
else if(marks>70)
grade='C';
else if(marks>60)
grade='D';
else if(marks>50)
grade='E';
else
grade='F';
printf("Grade of student is: %c\n",grade);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int a[5],b,i,sum=0,c;
for(i=0;i<5;i++)
{
printf("enter a number:");
scanf("%d",&a[i]);
sum+=i;
}
printf("Enter the number to be searched:");
scanf("%d",&b);
for(i=0;i<5;i++)
{
if(a[i]==b){
c=b;
break;
}
}
if(c=b)
printf("The number %d appears in the first %d numbers.",c,sum);
else
printf("The number %d is not appears in the first %d numbers.",c,sum);
return 0;
}
|
C
|
/*
============================================================================
Name : Binary_Search.c
Author : Dhirendra Tiwari
Version :
Copyright : Your copyright notice
Description : Binary Search in array in C
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
void input(int arr[], int n)
{
printf("Enter values of array : ");
for(int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
}
void sorting(int arr[], int n)
{
int i,j,temp;
for(i = 0; i < n ; i++)
{
for(j = i+1; j <= n; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void display(int arr[] , int n)
{
printf("After sorting : ");
for(int i = 0; i < n; i++)
{
printf("%d",arr[i]);
}
}
int BSArray(int arr[],int start,int end,int key)
{
int mid = start+((end-start)/2);
if (end<start) return -1;
if (key == arr[mid]) return mid;
if (key > arr[mid]) return BSArray(arr,mid+1,end,key);
return BSArray(arr,start,mid-1,key);
}
int main()
{
int key,n;
printf("Enter size of array : ");
scanf("%d",&n);
int arr[n];
input(arr , n);
sorting(arr , n);
display(arr , n);
int start = 0;
int end = n-1;
printf("\nEnter key : ");
scanf("%d",&key);
printf("\nIndex of key %d is : %d",key,BSArray(arr,start,end,key));
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b,c,max;
puts("请输入a,b,c的");
scanf("%d %d %d",&a,&b,&c);
max=(a>b)?a:b;
max=(max>c)?max:c;
printf("最大的数字是%d",max);
return 0;
}
|
C
|
#include <stdio.h>
void strcat(char s[], char t[]);
main() {
char x[100], y[100];
x[0] = 'a';
x[1] = 'w';
x[2] = 'f';
x[3] = 'q';
x[4] = '1';
x[5] = '\0';
y[0] = '\0';
printf("X var: %s\n", x);
strcat(y, x);
printf("Y var: %s\n", y);
return 0;
}
void strcat(char s[], char t[]) {
int i, j;
i = j = 0;
while (s[i] != '\0')
i++;
while ((s[i++] = t[j++]) != '\0')
;
}
|
C
|
#include<stdio.h>
int main(void)
{
int n,count=0,max=0,i=0;
char ch;
scanf("%d ",&n);
do{
i++;
scanf("%c",&ch);
if(ch==' '||i>n){
if(count>max) max=count;
count=0;
}
else if(ch>='A'&&ch<='Z') count++;
}while(i<=n);
printf("%d\n",max);
return 0;
}
|
C
|
/* Program for exercise 3.42 */
/* It needs to calculate circle parameters
2piR, piR2/2 */
#include <stdio.h>
int main () {
float pi = 3.14159;
int ra;
printf ("Enter radius\n");
scanf ("%d" , &ra);
printf ("Diameter is: %d\n" , 2*ra);
printf ("Length is %.5f\n" , 2*pi*ra);
printf ("Square is %.5f\n" , pi*ra*ra/2);
return 0;
}
|
C
|
#pragma once
#include "game.h"
#include "entity.h"
struct particle
{
int32 TimeToLive;
sprite Sprite;
real32 StoredVariables[ProjectileStorageSize];
particle_update_function UpdateFunction;
// Transient
bool32 Active;
int32 Timer;
spatial Spatial;
real32 Scale;
color_spec ColorSpec;
blend_mode BlendMode;
int32 Layer;
v3 Rotation;
interpolator ScaleInterpolator;
interpolator AlphaInterpolator;
};
// Note: Only called by other CreateParticle functions!
particle*
CreateParticleCommon(game_mode_world* World,
v2 Position,
v2 Velocity,
int32 TimeToLive,
real32 Scale,
color_spec ColorSpec,
blend_mode BlendMode,
int32 Layer,
particle_update_function UpdateFunction)
{
Assert("Out of particle memory.", World->ParticleCount < ParticleCountMax);
particle* Result = 0;
for (uint32 ParticleIndex = 0;
ParticleIndex < ParticleCountMax;
++ParticleIndex)
{
particle* Particle= World->Particles + ParticleIndex;
if (!Particle->Active)
{
Particle->TimeToLive = TimeToLive;
Particle->Scale = Scale;
Particle->ScaleInterpolator.Active = false;
Particle->ScaleInterpolator.ValuePointer = &Particle->Scale;
Particle->ColorSpec = ColorSpec;
Particle->BlendMode = BlendMode;
Particle->AlphaInterpolator.Active = false;
Particle->AlphaInterpolator.ValuePointer = &Particle->ColorSpec.Color.A;
Particle->Rotation = V3(0.0f, 0.0f, 0.0f);
Particle->Layer = Layer;
Particle->UpdateFunction = UpdateFunction;
Particle->Active = true;
Particle->Timer = 0;
InitializeSpatial_Linear(&Particle->Spatial, Position, Velocity);
++World->ParticleCount;
Result = Particle;
break;
}
}
Assert("No ununsed particles in pool.", Result);
return Result;
}
particle*
CreateParticle(game_state* GameState,
v2 Position,
v2 Velocity,
int32 TimeToLive,
real32 Scale,
color_spec ColorSpec,
blend_mode BlendMode,
int32 Layer,
texture_id TextureId,
particle_update_function UpdateFunction)
{
game_mode_world* World = GameState->World;
particle* Particle = CreateParticleCommon(World, Position, Velocity, TimeToLive,
Scale, ColorSpec, BlendMode, Layer, UpdateFunction);
InitializeSprite(&Particle->Sprite, TextureId);
return Particle;
}
particle*
CreateParticle_Animated(game_state* GameState,
v2 Position,
v2 Velocity,
int32 TimeToLive,
real32 Scale,
color_spec ColorSpec,
blend_mode BlendMode,
int32 Layer,
animation_spec_id AnimationSpecId,
particle_update_function UpdateFunction)
{
game_mode_world* World = GameState->World;
particle* Particle = CreateParticleCommon(World, Position, Velocity, TimeToLive,
Scale, ColorSpec, BlendMode, Layer, UpdateFunction);
InitializeSprite_Animated(&Particle->Sprite, AnimationSpecId);
return Particle;
}
void
CreateExplosion(game_state* GameState,
v2 Position,
real32 SpawnRadius,
real32 ParticleSpeedMin,
real32 ParticleSpeedMax,
int32 ParticleTimeToLiveMin,
int32 ParticleTimeToLiveMax,
texture_id TextureId,
uint32 ParticleCount)
{
Assert("Passed Max < Min", ParticleSpeedMax >= ParticleSpeedMin);
Assert("Passed Max < Min", ParticleTimeToLiveMax >= ParticleTimeToLiveMin);
real32 ParticleSpeedRange = ParticleSpeedMax - ParticleSpeedMin;
int32 ParticleTimeToLiveRange = ParticleTimeToLiveMax - ParticleTimeToLiveMin;
game_mode_world* World = GameState->World;
for (uint32 ParticleIndex = 0;
ParticleIndex < ParticleCount;
++ParticleIndex)
{
v2 PositionOffset = V2(RandomPerturb(GameState, 0.0f, SpawnRadius),
RandomPerturb(GameState, 0.0f, SpawnRadius));
v2 ParticleDirection = GetDirectionFromAngle(RandomRange(GameState, 360.0f));
real32 ParticleSpeed = RandomRange(GameState, ParticleSpeedMin, ParticleSpeedRange);
v2 ParticleVelocity = ParticleDirection * ParticleSpeed;
int32 ParticleTimeToLive = RoundReal32(RandomRange(GameState, ParticleTimeToLiveMin, ParticleTimeToLiveRange));
particle* Particle = CreateParticle(GameState, Position + PositionOffset,
ParticleVelocity, ParticleTimeToLive, 0.5f,
ColorSpec(Color(Colors.White, 0.8f), ColorTint_Mod),
BlendMode_Blend,
1, TextureId, 0);
Interpolate(&Particle->AlphaInterpolator, 0.6f, 0.0f, 30, ParticleTimeToLive);
}
CreateParticle_Animated(GameState, Position, V2(0.0f, 0.0f),
15, 1.0f,
ColorSpec_None, BlendMode_Blend,
20, AnimationSpecId_Explosion_0, 0);
}
void
CreateExplosion2(game_state* GameState,
v2 Position)
{
CreateParticle_Animated(GameState,
Position,
V2(0.0f, 0.0f),
15, 1.0f,
ColorSpec_None, BlendMode_Blend,
20, AnimationSpecId_Explosion_1, 0);
}
void
CreateGrazeParticle(game_state* GameState,
v2 GrazePosition)
{
game_mode_world* World = GameState->World;
real32 ParticleSpeedMin = 0.3f;
real32 ParticleSpeedRange = 0.85f;
v2 ParticleVelocity = V2(RandomSign(GameState) * RandomRange(GameState, ParticleSpeedMin, ParticleSpeedRange),
RandomSign(GameState) * RandomRange(GameState, ParticleSpeedMin, ParticleSpeedRange));
real32 ParticleTimeToLive = 40;
particle* Particle = CreateParticle(GameState,
GrazePosition,
ParticleVelocity,
ParticleTimeToLive,
0.5f,
ColorSpec_None,
BlendMode_Blend,
1, TextureId_Graze, 0);
Interpolate(&Particle->ScaleInterpolator, Particle->Scale, 0.3f, 0, ParticleTimeToLive);
Interpolate(&Particle->AlphaInterpolator, Particle->ColorSpec.Color.A, 0.0f, 30, ParticleTimeToLive);
}
void
UpdateParticles(game_state* GameState,
real32 DeltaTime)
{
game_mode_world* World = GameState->World;
for (uint32 ParticleIndex = 0;
ParticleIndex < ParticleCountMax;
++ParticleIndex)
{
particle* Particle = World->Particles + ParticleIndex;
if (Particle->Active)
{
if (Particle->UpdateFunction)
{
Particle->UpdateFunction(GameState, Particle, Particle->Timer);
if (!Particle->Active)
{
continue;
}
}
UpdateSpatial(&Particle->Spatial);
++Particle->Timer;
if (Particle->Timer > Particle->TimeToLive)
{
Particle->Active = false;
--World->ParticleCount;
continue;
}
// TODO: Keep these in a list
UpdateInterpolator(&Particle->ScaleInterpolator, Particle->Timer);
UpdateInterpolator(&Particle->AlphaInterpolator, Particle->Timer);
// Render
UpdateSprite(GameState, &Particle->Sprite);
PushSprite(GameState,
&Particle->Sprite,
Particle->Spatial.Position,
Particle->Scale,
V2(0.0f, 0.0f), Particle->Rotation,
Particle->ColorSpec,
Particle->Layer, Particle->BlendMode);
}
}
}
void
ClearParticles(game_mode_world* World)
{
World->ParticleCount = 0;
for (uint32 ParticleIndex = 0;
ParticleIndex < ParticleCountMax;
++ParticleIndex)
{
particle* Particle = World->Particles + ParticleIndex;
Particle->Active = false;
}
}
// API
void
Particle_SetPosition(particle* Particle, v2 Position)
{
Particle->Spatial.Position = Position;
}
void
Particle_ChangePosition(particle* Particle, v2 DeltaPosition)
{
Particle->Spatial.Position += DeltaPosition;
}
void
Particle_SetAlpha(particle* Particle, real32 Alpha)
{
Particle->ColorSpec.Color.A = Alpha;
}
real32
Particle_GetScale(particle* Particle)
{
return Particle->Scale;
}
void
Particle_SetScale(particle* Particle, real32 Scale)
{
Particle->Scale = Scale;
}
void
Particle_SetRotation(particle* Particle, v3 Rotation)
{
Particle->Rotation = Rotation;
}
void
Particle_ChangeRotation(particle* Particle, v3 DeltaRotation)
{
Particle->Rotation += DeltaRotation;
}
int32
Particle_GetTimeToLive(particle* Particle)
{
return Particle->TimeToLive;
}
real32
GetStoredVariable(particle* Particle, uint32 Number)
{
return Particle->StoredVariables[Number];
}
void
SetStoredVariable(particle* Particle, uint32 Number, real32 Value)
{
Particle->StoredVariables[Number] = Value;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
pthread_mutex_t m;//pthread_mutex_t m=INITIALIZER;
void *func(void *p)
{//辅助线程排序
pthread_mutex_lock(&m);
int i;
int *a=p;
for(i=0;i<10;i++)
{
int t=a[i];
int j;
for(j=i;j>0&&t<a[j-1];j--)
a[j]=a[j-1];
a[j]=t;
printf("\n****************\n");
for(i=0;i<10;i++)
{
printf("%d ",a[i]);
}
printf("\n****************\n");
pthread_mutex_unlock(&m);
usleep(1);
//pthread_mutex_lock(&m);
}
printf("main\n");
for(i=0;i<10;i++)
{
printf("%d ",a[i]);
}
}
int main()
{//主线程输出数字,辅助线程完成排序
pthread_t thread_id;
int a[10]={0};
pthread_mutex_init(&m,NULL);
pthread_mutex_lock(&m);
pthread_create(&thread_id,NULL,func,&a);
puts("请输入10个数字:");
int i;
for(i=0;i<10;i++)
{
printf("请输入的%d个数据:",i);
scanf("%d",&a[i]);
pthread_mutex_unlock(&m);
usleep(1);
pthread_mutex_lock(&m);
}
pthread_mutex_unlock(&m);
}
|
C
|
/***********************************
TODO
- IMPORTANT: It's not immutable.
- IMPORTANT: Better data structure.
- String interning.
***********************************/
#include <stdlib.h>
#include <string.h>
#include "types.h"
#define REG_SIZE 8 // AMD64 Architecture
void initialize_table(table_t *table) {
table->cap = 10;
table->used = 0;
table->data = malloc(table->cap * sizeof(symbol_t));
table->stack_top = 0;
}
// NOTE(stefanos): Currently, we compile for 64bit architectures,
// meaning that by default, registers are 8 bytes (and so when
// we push them, we use 8 bytes from the stack memory).
void increment_stack_top(table_t *table) {
table->stack_top += REG_SIZE;
}
void decrement_stack_top(table_t *table) {
table->stack_top -= REG_SIZE;
}
int is_stack_aligned(table_t *table, int a) {
return (table->stack_top % a == 0);
}
void insert(table_t *table, char *id, int line) {
if(table->used >= table->cap) {
table->cap *= 2;
table->data = realloc(table->data, table->cap * sizeof(symbol_t));
}
table->data[table->used].id = id;
table->data[table->used].line = line;
increment_stack_top(table);
table->data[table->used].offset = table->stack_top;
table->used += 1;
}
int search(table_t *table, char *id) {
for(int i = 0; i < table->used; ++i) {
if(!strcmp(table->data[i].id, id))
return i;
}
return -1;
}
void clean_table(table_t *table) {
if(table && table->data)
free(table->data);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#define MAXDATASIZE 100
int main(int argc, char *argv[]) {
struct addrinfo hints, *res;
int status, sockfd, newfd, numbytes;
struct sockaddr_storage their_addr;
socklen_t addr_size;
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
return 1;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo("localhost", argv[1], &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}
if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) {
perror("socket");
exit(1);
}
if (bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) {
perror("bind");
exit(1);
}
if (listen(sockfd, 10) == -1) {
perror("listen");
exit(1);
}
addr_size = sizeof their_addr;
if ((newfd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size)) == -1) {
perror("accept");
exit(1);
}
char buf[MAXDATASIZE];
while (1) {
if ((numbytes = recv(newfd, buf, MAXDATASIZE - 1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("message: \"%s\"", buf);
}
close(sockfd);
close(newfd);
freeaddrinfo(res);
return 0;
}
|
C
|
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPUpdateServer.h>
#include <ESP8266WebServer.h>
//#include "2SPIFFS.h"
#include "7Function.h"
ESP8266WebServer server(80); // create a web server on port 80
ESP8266HTTPUpdateServer httpUpdater;
File fsUploadFile; // a File variable to temporarily store the received file
String code;
//String call;
int call;
String getContentType(String filename) { // determine the filetype of a given filename, based on the extension
if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".ico")) return "image/x-icon";
else if (filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}
/*__________________________________________________________WEB_FUNCTIONS - Using SPIFFS__________________________________________________________*/
bool handleFileRead(String path) { // send the right file to the client (if it exists)
Serial.println("handleFileRead: " + path);
if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
String contentType = getContentType(path); // Get the MIME type
String pathWithGz = path + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { // If the file exists, either as a compressed archive, or normal
if (SPIFFS.exists(pathWithGz)) // If there's a compressed version available
path += ".gz"; // Use the compressed verion
File file = SPIFFS.open(path, "r"); // Open the file
size_t sent = server.streamFile(file, contentType); // Send it to the client
file.close(); // Close the file again
Serial.println(String("\tSent file: ") + path);
return true;
}
Serial.println(String("\tFile Not Found: ") + path); // If the file doesn't exist, return false
return false;
}
void handleFileUpload() { // upload a new file to the SPIFFS
HTTPUpload& upload = server.upload();
String path;
if (upload.status == UPLOAD_FILE_START) {
path = upload.filename;
if (!path.startsWith("/")) path = "/" + path;
if (!path.endsWith(".gz")) { // The file server always prefers a compressed version of a file
String pathWithGz = path + ".gz"; // So if an uploaded file is not compressed, the existing compressed
if (SPIFFS.exists(pathWithGz)) // version of that file must be deleted (if it exists)
SPIFFS.remove(pathWithGz);
}
Serial.print("handleFileUpload Name: "); Serial.println(path);
fsUploadFile = SPIFFS.open(path, "w"); // Open the file for writing in SPIFFS (create if it doesn't exist)
path = String();
} else if (upload.status == UPLOAD_FILE_WRITE) {
if (fsUploadFile)
fsUploadFile.write(upload.buf, upload.currentSize); // Write the received bytes to the file
} else if (upload.status == UPLOAD_FILE_END) {
if (fsUploadFile) { // If the file was successfully created
fsUploadFile.close(); // Close the file again
Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize);
server.sendHeader("Location", "/success.html"); // Redirect the client to the success page
server.send(303);
} else {
server.send(500, "text/plain", "500: couldn't create file");
}
}
}
void handleNotFound() { // if the requested file or page doesn't exist, return a 404 not found error
if (!handleFileRead(server.uri())) { // check if the file exists in the flash memory (SPIFFS), if so, send it
server.send(404, "text/plain", "404: File Not Found");
}
}
//version 1
/*
void handlepraise() {
code = server.arg("Code"); //.toInt(); // remove toInt
call = server.arg("String"); //.toInt(); // remove toInt
Serial.print("Code: ");
Serial.println(code);
Serial.print("String: ");
Serial.println(call);
if (code == config.passcode1 and call == "Function_1")
{
Serial.println("Function 1 Called");
Function_1();
server.send(200, "text/plain", "Function 1 Complete");
Serial.println("Function 1 Complete");
}
else
{
if (code == config.passcode1 and call == "Function_2")
{
Serial.println("Function 2 Called");
Function_2();
server.send(200, "text/plain", "Function 2 Complete");
Serial.println("Function 2 Complete");
}
else
{
Serial.println("Function or Code Incorrect and unable to praise");
server.send(404, "text/plain", "404: File Not Found");
}
}
}
*/
// version 2
void handlepraise() {
code = server.arg("Code"); //.toInt(); // remove toInt
call = server.arg("String").toInt(); // remove toInt
Serial.print("Code: ");
Serial.println(code);
Serial.print("String: ");
Serial.println(call);
if (code == config.passcode1)
{
switch (call) {
case 1:
GPIO_toggle (config.function1_gpio, config.function1_high_low);
server.send(200, "text/plain", "Function 1 Complete");
Serial.println("Function 1 Complete");
break;
case 2:
GPIO_toggle (config.function2_gpio, config.function2_high_low);
server.send(200, "text/plain", "Function 2 Complete");
Serial.println("Function 2 Complete");
break;
default:
server.send(200, "text/plain", "Incorrect Function Called");
Serial.println("Incorrect Function Called");
break;
}}
else
{
Serial.println("Function or Code Incorrect and unable to praise");
server.send(404, "text/plain", "404: File Not Found");
}
}
void settingspraise() {
String data = server.arg("plain");
Serial.println(data);
webConfig(data);
saveConfig();
}
/*__________________________________________________________WEBSERVER_Actions and Setup__________________________________________________________*/
void startServer() { // Start a HTTP server with a file read handler and an upload handler
server.on("/edit.html", HTTP_POST, []() { // If a POST request is sent to the /edit.html address,
server.send(200, "text/plain", "");
}, handleFileUpload); // go to 'handleFileUpload'
server.onNotFound(handleNotFound); // if someone requests any other file or page, go to function 'handleNotFound'
// and check if the file exists
server.on("/restart", []() {
server.send(200, "text/plain", "Restarting...");
WiFi.disconnect(true);
delay(1000);
ESP.restart();
});
server.on("/del", []() {
server.send(200, "text/plain", "Deleting files...");
//SPIFFS.remove("/config.json");
SPIFFS.format();
WiFi.disconnect(true);
server.send(200, "text/plain", "Restarting...");
});
server.on("/files", []() {
server.send(200, "text/plain", "Deleting files...");
// code to display SPIFFS contense
server.send(200, "text/plain", "Restarting...");
});
server.on("/praise.html", []() {
handlepraise();
server.send(200, "text/plain", "Deleting files...");
// code to display SPIFFS contense
});
server.on("/updatesettings", []() {
settingspraise();
server.send(200, "text/plain", "Settings Updated...");
// code to display SPIFFS contense
});
//server.on settings...goes here
httpUpdater.setup(&server);
server.begin(); // start the HTTP server
Serial.println("HTTP server started.");
}
|
C
|
/* Arduino Audio Loopback Test
*
* Arduino Realtime Audio Processing
* 2 ADC 8-Bit Mode
* anaog input 1 is used to sample the audio signal
* analog input 0 is used to control an audio effect
* PWM DAC with Timer2 as analog output
* KHM 2008 / Lab3/ Martin Nawrath nawrath@khm.de
* Kunsthochschule fuer Medien Koeln
* Academy of Media Arts Cologne
*/
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
int ledPin = 13; // LED connected to digital pin 13
int testPin = 7;
boolean div32;
boolean div16;
// interrupt variables accessed globally
volatile boolean f_sample;
volatile byte badc0;
volatile byte badc1;
volatile byte ibb;
int ii;
int icnt;
int cnt2;
float pi = 3.141592;
float dx ;
float fd ;
float fcnt;
int iw;
byte bb;
byte dd[512]; // Audio Memory Array 8-Bit
void fill_sinewave(); // load memory with sine table
void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
pinMode(testPin, OUTPUT);
Serial.begin(57600); // connect to the serial port
Serial.println("Arduino Audio");
fill_sinewave(); // load memory with sine table
// set adc prescaler to 64 for 19kHz sampling frequency
cbi(ADCSRA, ADPS2);
sbi(ADCSRA, ADPS1);
sbi(ADCSRA, ADPS0);
sbi(ADMUX,ADLAR); // 8-Bit ADC in ADCH Register
sbi(ADMUX,REFS0); // VCC Reference
cbi(ADMUX,REFS1);
cbi(ADMUX,MUX0); // Set Input Multiplexer to Channel 0
cbi(ADMUX,MUX1);
cbi(ADMUX,MUX2);
cbi(ADMUX,MUX3);
// Timer2 PWM Mode set to fast PWM
cbi (TCCR2A, COM2A0);
sbi (TCCR2A, COM2A1);
sbi (TCCR2A, WGM20);
sbi (TCCR2A, WGM21);
cbi (TCCR2B, WGM22);
// Timer2 Clock Prescaler to : 1
sbi (TCCR2B, CS20);
cbi (TCCR2B, CS21);
cbi (TCCR2B, CS22);
// Timer2 PWM Port Enable
sbi(DDRB,3); // set digital pin 11 to output
//cli(); // disable interrupts to avoid distortion
cbi (TIMSK0,TOIE0); // disable Timer0 !!! delay is off now
sbi (TIMSK2,TOIE2); // enable Timer2 Interrupt
}
void loop()
{
while (!f_sample) { // wait for Sample Value from ADC
} // Cycle 15625 KHz = 64uSec
PORTD = PORTD | 128; // Test Output on pin 7
f_sample=false; // reset Flag
badc1=dd[icnt]; // get the buffervalue on indexposition
icnt++; // increment index
icnt=icnt + badc0; // Variable frequency with potentiometer
icnt = icnt & 511; // limit index 0..511
cnt2++; // let the led blink every second
if (cnt2 >= 15625){
cnt2=0;
PORTB = PORTB ^ 32; // toggle LED on pin 11
}
OCR2A=badc1; // Sample Value to PWM Output
PORTD = PORTD ^ 128; // Test Output on pin 7
} // loop
//******************************************************************
void fill_sinewave(){
dx=2 * pi / 512; // fill the 512 byte bufferarry
for (iw = 0; iw <= 511; iw++){ // with 50 periods sinewawe
fd= 127*sin(fcnt); // fundamental tone
fcnt=fcnt+dx; // in the range of 0 to 2xpi and 1/512 increments
bb=127+fd; // add dc offset to sinewawe
dd[iw]=bb; // write value into array
}
}
//******************************************************************
// Timer2 Interrupt Service at 62.5 KHz
// here the audio and pot signal is sampled in a rate of: 16Mhz / 256 / 2 / 2 = 15625 Hz
// runtime : xxxx microseconds
ISR(TIMER2_OVF_vect) {
PORTB = PORTB | 1 ;
div32=!div32; // divide timer2 frequency / 2 to 31.25kHz
if (div32){
div16=!div16; //
if (div16) { // sample channel 0 and 1 alternately so each channel is sampled with 15.6kHz
badc0=ADCH; // get ADC channel 0
sbi(ADMUX,MUX0); // set multiplexer to channel 1
}
else
{
badc1=ADCH; // get ADC channel 1
cbi(ADMUX,MUX0); // set multiplexer to channel 0
f_sample=true;
}
ibb++;
ibb--;
ibb++;
ibb--; // short delay before start conversion
sbi(ADCSRA,ADSC); // start next conversion
}
}
|
C
|
/*
* Time_Tester.c
*
* Created: 24/04/2021 13:10:11
* Author: Ruzhev
*/
#include "Time_Tester.h"
inline void time_record_timestamp(void){
int current_systick = SysTick->VAL;
timestamp = current_systick;
}
inline float time_get_delta_us(void){
int current_systick = SysTick->VAL;
int delta = timestamp - current_systick;
if(delta <= 0) delta += (1<<24);
//systick clock frequency equals MCU clock at 300MHz
return (float) delta / 300;
}
|
C
|
#include <linux/init.h>
#include <linux/module.h> //try_module_get, module_put
#include <linux/kernel.h>// Needed for KERN_INFO
#include <linux/fs.h> //file_operations
#include <asm/uaccess.h> //memory access
#include <linux/sched/signal.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/syscalls.h>
////what i wrote inside syscalls.h /////////////
// asmlinkage long sys_2017510007(void);
// asmlinkage long sys_mysyscall(char *arg, char *pid, char *userBuf);
/////what i wrote inside syscall_64.tbl//////////////
//335 64 2017510007 sys_2017510007
//336 common mysyscall __x64_sys_mysyscall
// I got errors trying to compile.
//Although I researched and looked at
//the forum part on Sakai but unfortunately
//I could not figure out. The errors I received
//are in the error.png screenshot.
//system call define
SYSCALL_DEFINE3(mysyscall, char __user *, arg, char __user *, pid, char __user *, userB)
{
int return_val = 0;
char param_arg[16] = {'\0'};
int pNum = toInt(pid);
if(copy_from_user(param_arg, arg, 16) == 0)
printk(KERN_INFO "Argument is taken!");
//functions work according to the arguments entered
if(stringcheck(param_arg,"-all") == 0) //if entered argument is -all
return_val = all();
else if( stringcheck(param_arg,"-p") == 0) //if entered argument is -p
return_val = cmdline();
else if( stringcheck(param_arg,"-k") == 0) //if entered argument is -k
return_val = kill_proc();
else
return_val = no_argument(); //if there is no argument
return_val = copy_to_user(userB, param_arg, 16);
if(return_val == 0){
printk(KERN_INFO "%s\nhas been copied to usr_write_back_dst!", param_arg);
}
return return_val;
}
////////////////////////////////////////////
//without argument function
int no_argument(void)
{
printk("Right Usage:\n-all prints some information (process id and its argument/s) about all processes\n-p takes process id and prints the details of it\n-k takes process id\n");
return 0;
}
////////////////////////////////////
//cmdline function
int cmdline(char __user *, pid)
{
struct file *f;
char buf[128];
mm_segment_t fs;
int i;
//The part of placing the incoming id in the path with using strcpy and strcat
char first[50], second[50];
strcpy(first, "/proc/");
strcat (first, pid);
strcpy(second, "/stat");
strcat(first, second )
for(i=0;i<128;i++)
buf[i] = 0;
printk(KERN_INFO "My module is loaded\n");
f = filp_open(first, O_RDONLY, 0);
if(f == NULL)
printk(KERN_ALERT "filp_open error!!.\n");
else{
fs = get_fs();
set_fs(get_ds());
f->f_op->read(f, buf, 128, &f->f_pos);
set_fs(fs);
//printk(KERN_INFO "buf:%s\n",buf);
int unused;
char comm[1000];
int pid;
char state;
int ppid;
sscanf(buf, "%s", comm);
printk(KERN_INFO "cmdline = %s\n", comm);
}
filp_close(f,NULL);
return 0;
}
///////////////////////////////////////////////
//all function
char buffer[256];
char * get_task_state(long state){
printk(buffer, "Unknow type: %ld\n", state);
return buffer;
}
int all(void){
//Reaching ids with task_struct pattern
struct task_struct *task_list;
for_each_process(task_list){
pr_info("UID:[%d]\t PPID:[%d]\t PID:[%d]\t Process: %s\t State:%ld\n",
task_list->real_cred->uid.val, task_ppid_nr(task_list), task_list->pid, task_list->comm,
get_task_state(task_list->state));
}
return 0;
}
MODULE_LICENSE("GPL");
////////////////////////////////////////////
//kill function
int kill_proc(char __user *, pid)
{
int pnum = toInt(pid);
printk(KERN_INFO "My module is loaded\n");
if(kill_pid(find_vpid(pnum),SIGKILL,1) == 0)
{
printk(KERN_INFO "Process %d killed\n", pnum);
}
return 0;
}
//////////////////////////////////////////////////
// cleanup module
void cleanup_module(void)
{ printk(KERN_INFO "My module is unloaded\n");
}
|
C
|
#include <stdio.h>
#include "SqList_int.h"
#define EMPTY 0 //空
#define UNEMPTY 1 //非空
//比较两个顺序表的大小
//返回值result,若A>B,result=1; A==B,result=0; A<B,result==-1
int CompareList(SqList * listA,SqList * listB){
int *pa,*pb,*qa_last,*qb_last;
int a_,b_,result;
//ListA/B的尾节点
qa_last=&(listA->list[listA->used-1]);
qb_last=&(listB->list[listB->used-1]);
pa=listA->list;
pb=listB->list;
//判空
for( ;
*pa==*pb && pa!=qa_last && pb!=qb_last;
++pa,++pb)
;
//A`,B`都不空
if (*pa!=*pb)
a_=b_=UNEMPTY;
//A`,B`都空
else if (*pa==*pb && pa==qa_last && pb==qb_last)
a_=b_=EMPTY;
//A`空,B`不空
else if (*pa==*pb && pa==qa_last && pb!=qb_last)
a_=EMPTY,b_=UNEMPTY;
//A`不空,B`空
else if (*pa==*pb && pb==qb_last && pa!=qa_last)
a_=UNEMPTY,b_=EMPTY;
//比较大小
if(a_==EMPTY && b_==EMPTY)
result=0;//A==B
else if( (a_!=EMPTY && b_==EMPTY)
|| (a_!=EMPTY && b_!=EMPTY && *pa>*pb)
)
result=1;//A>B
else if( (a_==EMPTY && b_!=EMPTY)
|| (a_!=EMPTY && b_!=EMPTY && *pa<*pb)
)
result=-1;//A>B
else{
printf("比较大小出现未考虑的情况,请检查");
result=0;
}
return result;
}
int main() {
// printf("Hello, World!\n");
//test数据
int A[]={1,2,3,4,5},
B[]={1,2,3,4,5};
int result;
SqList listA,listB;
//创建两个顺序表,数据为我上面指定的两组test数据
CreatMyList(&listA,A,5);
CreatMyList(&listB,B,5);
//打印两个顺序表
DisplayList(&listA);
DisplayList(&listB);
//比较
result=CompareList(&listA,&listB);
//输出结果
if(result==0)
printf("A==B\n");
else if (result>0)
printf("A>B\n");
else
printf("A<B\n");
return 0;
}
|
C
|
#include "atbash_cipher.h"
#define STRLEN 64
char flipchar(char c) {
if (isalpha(c))
return 'z' - (tolower(c) - 'a');
return c;
}
char* atbash(char* input, int group_size) {
char* output = (char*) calloc(STRLEN, sizeof(char));
char* pt = output;
for (int s = group_size; *input; ++input) {
if (isalnum(*input)) {
*(pt++) = flipchar(*input);
if (--s == 0) {
*(pt++) = ' ';
s = group_size;
}
}
}
if (*(--pt) == ' ') *pt = '\0';
return output;
}
char* atbash_encode(char* input) { return atbash(input, 5); }
char* atbash_decode(char* input) { return atbash(input, 0); }
|
C
|
/* Author: Prescott J. Traversi
* Source: https://leetcode.com/problems/merge-sorted-array/
*
* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as
* one sorted array.
*
* Time: O(m + n)
* Space: O(1)
*/
#include <stdlib.h>
#include <assert.h>
/* --------------------------------- problem -------------------------------- */
void merge(int *nums1, int nums1Size, int m, int *nums2, int nums2Size, int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;
while (i >= 0 && j >= 0) {
if (nums1[i] > nums2[j])
nums1[k--] = nums1[i--];
else
nums1[k--] = nums2[j--];
}
while (j >= 0)
nums1[k--] = nums2[j--];
}
/* --------------------------------- testing -------------------------------- */
typedef struct testCase {
int *nums1;
int m;
int *nums2;
int n;
int *expected;
} testCase;
static void buildArr(int **to, int *from, int n) {
*to = malloc(sizeof(int) * n);
assert(to);
for (int i = 0; i < n; i++)
(*to)[i] = from[i];
}
static void assertarr(int *actual, int *expected, int n) {
for (int i = 0; i < n; i++) {
assert(actual[i] == expected[i]);
}
}
int main(void) {
testCase test;
// TEST CASE 1
buildArr(&test.nums1, (int[]){1, 2, 3, 0, 0, 0}, 6);
test.m = 3;
buildArr(&test.nums2, (int[]){2, 5, 6}, 3);
test.n = 3;
buildArr(&test.expected, (int[]){1, 2, 2, 3, 5, 6}, 6);
merge(test.nums1, test.m, test.m, test.nums2, test.n, test.n);
assertarr(test.nums1, test.expected, 6);
// TEST CASE 2
buildArr(&test.nums1, (int[]){1}, 1);
test.m = 1;
buildArr(&test.nums2, (int[]){}, 0);
test.n = 0;
buildArr(&test.expected, (int[]){1}, 1);
merge(test.nums1, test.m, test.m, test.nums2, test.n, test.n);
assertarr(test.nums1, test.expected, 1);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,a[10],j;
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
if(a[j]==a[i]&&j!=i)
a[j]=-1;
}
if(a[i]!=-1)
printf("%d\n",a[i]);
}
return 0;
}
|
C
|
/*
* robotcontrol-api.h
*
* Created on: Oct 17, 2021
* Author: ksstms
*/
#ifndef INC_ROBOTCONTROL_API_H_
#define INC_ROBOTCONTROL_API_H_
#include <stdint.h>
#define MOT_R 0
#define MOT_L 1
typedef struct {
uint16_t h;
uint8_t s;
uint8_t v;
} Color;
/**
* Set motor speed
* @param mot_lr MOT_L for left, MOT_R for right
* @param speed between -100 and +100
* @return 0 on success
*/
int setMotorSpeed(uint8_t mot_lr, float speed);
/**
* Read the current value of the encoder's counter
* @param mot_lr MOT_L for left, MOT_R for right motor
* @return encoder counter value
*/
uint32_t getEncoderPosition(uint8_t mot_lr);
/**
* Works just like printf after the position specifiers
* @param row of starting position
* @param col of starting position
* @param fmt printf-like format string followed by a variable number of arguments
*/
int lcdPrintf(uint8_t row, uint8_t col, const char *fmt, ...);
/**
* Print to the USB serial port. Works just like regular printf.
*/
int uartPrintf(const char *fmt, ...);
/**
* Read color in HSV format
* @param color
*/
void getColorHsv(Color* color);
/**
* Set the servo's position in degrees
* @param position must be between -90 and 90. Otherwise it will be clipped to those values.
*/
void setServoPosition(int8_t position);
/**
* Get the distance measured by the ultrasonic ranging sensor
* @return distance in cm
*/
uint16_t getUsDistance();
/**
* Do nothing for the specified time
* @param delay in ms
*/
void delayMs(uint32_t delay);
#endif /* INC_ROBOTCONTROL_API_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
int *randomNumberGen(int n) {
int *arr = (int *)malloc(sizeof(int) * n);
for (int i = 0; i < n; i++) {
arr[i] = rand()%100;
}
return arr;
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void heapify(int *arr, int n, int i)
{
int max = i;
int leftChild = 2 * i + 1;
int rightChild = 2 * i + 2;
if (leftChild < n && arr[leftChild] > arr[max])
max = leftChild;
if (rightChild < n && arr[rightChild] > arr[max])
max = rightChild;
if (max != i)
{
swap(&arr[i], &arr[max]);
heapify(arr, n, max);
}
}
void heapSort(int *arr, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--)
{
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
void sortDescending(int *arr,int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] < key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int *arr,int n)
{
for(int i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");
}
int largest(int *arr, int n)
{
int i;
int max = arr[0];
for (i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
printf("Maximum element is: %d\n",max);
}
void delete(int *arr,int n)
{
int last = arr[n - 1];
arr[0] = last;
heapSort(arr,n);
}
void insert(int *arr,int n,int key)
{
arr[n-1] = key;
heapSort(arr, n);
}
void replace(int *arr,int n)
{
int k,in;
printf("Enter Element and Index of Replacement:\n");
scanf("%d%d",&k,&in);
arr[in]=k;
heapSort(arr,n);
}
int main()
{
int choice,n;
do
{
printf("0. Exit\n1. Insert Random Elements\n2. Display the Array\n3. Sort the Array in Ascending Order by using Max-Heap Sort Algorithm\n4. Sort the Array in Descending Order by using any sorting algorithm\n5. Time Complexity to sort ascending of random data\n6. Time Complexity to sort ascending of data already sorted in ascending order\n7. Time Complexity to sort ascending of data already sorted in descending order\n8. Time Complexity to sort ascending of data for all Cases.\n9. Maximum Element\n10. Replace value at a node with new value. \n11. Insert a new element.\n12. Delete an element\n");
scanf("%d",&choice);
switch(choice)
{
case 0:printf("Exiting !!!\n");
exit(1);
case 1:
printf("Enter N:");
scanf("%d", &n);
int *arr;
arr = randomNumberGen(n);
break;
case 2:
printArray(arr,n);
break;
case 3:
heapSort(arr, n);
break;
case 4:
sortDescending(arr,n);
break;
case 5:
printf("\n");
int *arr1;
arr1=randomNumberGen(10000);
clock_t start,end;
double total=0.0;
start=clock();
heapSort(arr1, 10000);
end=clock();
total+=(double)(end-start)/CLOCKS_PER_SEC;
printf("\nTime elpased is %f seconds\n", total);
printf("Time Complexity=O(nlog n)\n\n");
break;
case 6:
printf("\n");
clock_t start1,end1;
double total1=0.0;
start1=clock();
heapSort(arr1, 10000);
end1=clock();
total1+=(double)(end1-start1)/CLOCKS_PER_SEC;
printf("\nTime elpased is %f seconds\n", total1);
printf("Time Complexity=O(nlog n)\n");
break;
case 7:
sortDescending(arr1,10000);
clock_t start2,end2;
double total2=0.0;
start2=clock();
heapSort(arr1, 10000);
end2=clock();
total2+=(double)(end2-start2)/CLOCKS_PER_SEC;
printf("\nTime elpased is %f seconds\n", total2);
printf("Time Complexity=O(nlog n)\n");
break;
case 8:
printf("Already Sorted: O(nlog n)\n");
printf("Reverse Sorted: O(nlog n)\n");
printf("Random Sample: O(nlog n)\n");
break;
case 9:
largest(arr,n);
break;
case 10:
replace(arr,n);
break;
case 11:
printf("Enter the Element\n");
int key;
scanf("%d",&key);
n=n+1;
insert(arr,n,key);
case 12:
n=n-1;
delete(arr,n);
break;
}
}while (choice!=0);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char filename[8]; //designate memory for filename
int jpeg_count = 0; // counter to check condition in while loop for first jpeg
unsigned char buffer[512]; // designate space to read file
if (argc != 2)
{
printf("Usage: ./recover.c key\n"); //error for invalid usage
return 1;
}
FILE *f = fopen(argv[1], "r");
if (f == NULL)
{
printf("Unable to open file\n"); // error for invalid file
return 1;
}
FILE *img = NULL; //initialize file for later reference
int open = 0; //variable to see if a file has been opened yet
while (fread(&buffer, 512, 1, f) == 1)
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) // checks file format for jpeg header
{
open = 1;
if (jpeg_count == 0) //enters this portion on the finding of first jpeg
{
sprintf(filename, "%03i.jpg", jpeg_count);
jpeg_count++;
img = fopen(filename, "w"); // opens img with designated file name
fwrite(&buffer, 512, 1, img); // writes over jpeg file opened
}
else if (jpeg_count > 0) // enters this portion finding any subsquent jpegs
{
fclose(img); // close previously opened image
sprintf(filename, "%03i.jpg", jpeg_count);
jpeg_count++;
img = fopen(filename, "w");
fwrite(&buffer, 512, 1, img);
}
}
else if (open == 1) // continues to write if jpeg is larger than 512 bytes
{
fwrite(buffer, 512, 1, img);
}
}
fclose(img); // closes last image
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
/*
题目描述:
将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于(小于的时候,继续执行循环)n,则说明分解质因数的过程已经结束,另外 打印出即可。
(2)但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数n.重复执行第二步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
*/
void main()
{
int n,i;
printf("请输入要分解的正整数:");
scanf("%d",&n);
printf("%d = ",n);
for(i = 2;i <= n;i++) //小于等于n
{
while(n%i == 0)
{
printf("%d",i);
n/=i; //n=n/i!!!
if(n != 1)
printf("*");
}
}
}
|
C
|
/*
* Chad Benson
* Nghia Nguyen
*
* 315
* lab5 - mips simulator
* code reused from lab 4
* https://codeshare.io/hCJiL
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mips_asm_header.h"
#define BASE 0x000000000
typedef unsigned int MIPS, *MIPS_PTR;
MB_HDR mb_hdr; /* Header area */
MIPS mem[4096]; /* Memory space */
char* table[32] = {"$zero", "$at", "$v0", "$v1", "$a0", "$a1", "$a2", "$a3", "$t0", "$t1", "$t2", "$t3", "$t4",
"$t5", "$t6", "$t7", "$s0", "$s1", "$s2", "$s3", "$s4", "$s5", "$s6", "$s7", "$t8", "$t9",
"$k0", "$k1", "$gp","$sp", "$fp", "$ra"};
typedef struct mipsSim
{
unsigned int regs[32]; /* sim mips registers */
// int simMem[2][32768]; /* sim memory, row 0 -> PC, row 1 -> instruction */
unsigned int pcValue; /* program counter */
int *memp; /* instruction */
int numOfInstr; /* number of instructions in program */
int numOfRWs; /* number of read and writes in the program */
int numClock; /* number of clock cycles */
} MIPS_SIM;
/* Function Declarations */
/* Functs for decoding instructions */
int getFunct(int n);
int getrs(int n);
int getrt(int n);
int getrd(int n);
int getshift(int n);
int getimm8(int n);
int getimm16(int n);
int geteff(int n, int i);
void decodeR(int n, int opc, int funct, int i, MIPS_SIM* sim);
void decodeIJ(int n, int opc, int i, MIPS_SIM* sim);
/* Functs for running simulator */
int prompt();
void initProgram();
int getPC();
void getInstr(int pc, MIPS_SIM* sim);
void printRegs(MIPS_SIM* sim);
/*************************************** MAIN ******************************/
int main()
{
int run = 2, i; /* loop flag value */
MIPS_SIM* sim = malloc(sizeof(MIPS_SIM)); /* init sim structure */
for(i=0; i<32; i++)
sim->regs[i] = 0;
sim->pcValue = BASE; /* Set PC value */
sim->numClock = 0;
initProgram(); /* prompt user for file and read in mips program to buffer */
do
{
if(run == 2)
run = prompt(); /* prompt user for command */
if(run == 0)
break;
printf("\n PC: %.8x - 0x%.8x - ", sim->pcValue, mem[sim->pcValue/4]);
// get instr
getInstr(sim->pcValue, sim);
// print regs
printRegs(sim);
// print #instruct, readn writes
sim->numOfInstr++;
if(sim->regs[2] == 10 && mem[(sim->pcValue-4)/4] == 0xC)
break;
} while(1); /* run until user quits or $v0 is 10 */
printf("\n Total instunctions: %d\n", sim->numOfInstr);
printf(" Total read-write instructions: %d\n", sim->numOfRWs);
printf(" Total clock cycles: %d\n\n", sim->numClock);
free(sim);
return 0;
} /* End Main */
/* Function prompt */
int prompt()
{
int val;
printf(" \n ******* Welcome to our 315 MIPS simulator: *******\n"
" enter 1 to run program \n"
" or enter 2 to step through program \n"
" or enter 0 to exit ");
scanf("%d", &val);
return val;
}
/* Function printRegs - prints all 32 registers */
void printRegs(MIPS_SIM* sim)
{
int i, j;
for (i=0; i<4; i++)
{
for (j=0; j<8; j++)
{
printf(" %-9s", table[j + 8*i]);
}
printf("\n");
for(j=0; j<8; j++)
{
printf(" %.8x ", sim->regs[j + 8*i]);
}
printf("\n");
}
}
/* Function getPC - returns pc value */
int getPC(MIPS_SIM* sim)
{
return sim->pcValue;
}
/* Function getInstr */
void getInstr(int i, MIPS_SIM* sim)
{
int opc, funct;
if(mem[i/4] == 0)
{
// todo print for nop *****************************************
printf("Instruction: nop \n"
" Number of cycles: 2 \n");
sim->pcValue += 4;
sim->numClock +=4;
return;
}
// printf("Instruction@%08X : %08X\n", i, mem[i/4]); /* print instruction */
opc = mem[i/4] >> 26; /* get opcode */
if(opc == 0) /* check if R type instr */
{
funct = getFunct(mem[i/4]);
decodeR(mem[i/4], opc, funct, i, sim); /* decode R type instruction */
}
else
decodeIJ(mem[i/4], opc, i, sim); /* Decode I or J type instr */
}
/* Funct initProgram prompts user for file and reads into a buffer */
void initProgram()
{
/* Function load program
* Prompts and reads mips program
* from user given filename
*/
/* Vars */
FILE *fd; /* points to a file */
int n; /* for reading instructions */
int memp;
char filename[20]; /* for file name */
/************************************** I / O ******************************/
printf("Enter a mips file to decode: "); /* prompt user for a file */
scanf("%s", filename);
/* format the MIPS Binary header */
fd = fopen(filename, "rb");
/* fd = fopen("testcase1.mb", "rb"); */
if (fd == NULL) { printf("\nCouldn't load test case - quitting.\n"); exit(99); }
memp = 0; /* This is the memory pointer, a byte offset */
/* read the header and verify it. */
fread((void *) &mb_hdr, sizeof(mb_hdr), 1, fd);
if (! strcmp(mb_hdr.signature, "~MB") == 0)
{ printf("\nThis isn't really a mips_asm binary file - quitting.\n"); exit(98); }
printf("\n%s Loaded ok, program size=%d bytes.\n\n", filename, mb_hdr.size);
/* read the binary code a word at a time */
do {
n = fread((void *) &mem[memp/4], 4, 1, fd); /* note div/4 to make word index */
if (n)
memp += 4; /* Increment byte pointer by size of instruction */
else
break;
} while (memp < sizeof(mem)) ;
fclose(fd);
return;
}
/* Function getFunct
* returns function value for R type instru
* Assume integer instruction
*/
int getFunct(int n)
{
n &= 0x3F;
return n;
}
/* Function DecodeR
* DecodeR decodes and prints R type instruction
* Assumes integer instruction, opcode, function value and PC
*/
void decodeR(int n, int opc, int funct, int i, MIPS_SIM* sim) // add struct ptr*
{
if (funct == 0xC)
{
printf(" Syscall\n");
sim->pcValue += 4;
}
else if(funct == 0x20) /* add */
{
printf(" add %s, %s, %s \n",
table[getrd(n)], table[getrt(n)], table[getrs(n)]);
sim->regs[getrd(n)] = sim->regs[getrt(n)] + sim->regs[getrs(n)];
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x21) /* addu */
{
printf(" addu %s, %s, %s \n",
table[getrd(n)], table[getrt(n)], table[getrs(n)]);
sim->regs[getrd(n)] = sim->regs[getrs(n)] + sim->regs[getrt(n)];
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x22) /* subtract */
{
printf(" subtract %s, %s, %s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
sim->regs[getrd(n)] = sim->regs[getrs(n)] - sim->regs[getrt(n)];
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x23) /* subtract unsigned */
{
printf(" subtract unsigned %s, %s, %s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
sim->regs[getrd(n)] = sim->regs[getrs(n)] - sim->regs[getrt(n)];
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x24) /* and */
{
printf(" and %s %s, %s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
sim->regs[getrd(n)] = sim->regs[getrs(n)] & sim->regs[getrt(n)];
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x27) /* nor */
{
printf(" nor %s, %s, %s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
sim->regs[getrd(n)] = ~(sim->regs[getrs(n)] | sim->regs[getrt(n)]);
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x25) /* or */
{
printf(" or %s, %s, %s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
sim->regs[getrd(n)] = (sim->regs[getrs(n)] | sim->regs[getrt(n)]);
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x26) /* xor */
{
printf(" xor %s, %s,%s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
sim->regs[getrd(n)] = (sim->regs[getrs(n)] ^ sim->regs[getrt(n)]);
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x00) /* sll */
{
printf(" sll %s, %s, %d \n",
table[getrd(n)], table[getrt(n)], getshift(n));
sim->regs[getrd(n)] = sim->regs[getrt(n)] << getshift(n);
printf(" Number of cycles: 4 \n");
sim->pcValue += 4;
sim->numClock += 4;
}
else if(funct == 0x02) /* srl */
{
printf(" srl %s, %s, %d \n",
table[getrd(n)], table[getrt(n)], getshift(n));
sim->regs[getrd(n)] = (sim->regs[getrt(n)] >> getshift(n));
sim->pcValue += 4;
sim->numClock += 4;
printf(" Number of cycles: 4 \n");
}
else if(funct == 0x03) /* sra */
{
int temp = 0x80000000, i=0;
printf(" sra %s, %s, %d \n",
table[getrd(n)], table[getrt(n)], getshift(n));
sim->regs[getrd(n)] = sim->regs[getrt(n)];
if ((sim->regs[getrt(n)] & temp) != 0)
{
while (i < getshift(n))
{
sim->regs[getrd(n)] >>= 1;
sim->regs[getrd(n)] += temp;
i++;
}
}
else
sim->regs[getrd(n)] >>= getshift(n);
sim->pcValue += 4;
sim->numClock += 4;
printf(" Number of cycles: 4 \n");
}
else if(funct == 0x04) /* sllv */
{
printf(" sllv %s, %s, %s \n",
table[getrd(n)], table[getrt(n)], table[getrs(n)]);
sim->regs[getrd(n)] = sim->regs[getrt(n)] << sim->regs[getrs(n)];
sim->pcValue += 4;
sim->numClock += 4;
printf(" Number of cycles: 4 \n");
}
else if(funct == 0x06) /* srlv */
{
printf(" srlv %s, %s, %s \n",
table[getrd(n)], table[getrt(n)], table[getrs(n)]);
sim->regs[getrd(n)] = (sim->regs[getrt(n)] >> sim->regs[getrs(n)]);
sim->pcValue += 4;
sim->numClock += 4;
printf(" Number of cycles: 4 \n");
}
else if(funct == 0x07) /* srav */
{
int temp = 0x80000000, i=0;
printf(" srav %s, %s, %s \n",
table[getrd(n)], table[getrt(n)], table[getrs(n)]);
sim->regs[getrd(n)] = sim->regs[getrt(n)];
if ((sim->regs[getrt(n)] & temp) != 0)
{
while (i < sim->regs[getrs(n)])
{
sim->regs[getrd(n)] >>= 1;
sim->regs[getrd(n)] += temp;
i++;
}
}
else
sim->regs[getrd(n)] >>= sim->regs[getrs(n)];
sim->pcValue += 4;
sim->numClock += 4;
printf(" Number of cycles: 4 \n");
}
else if(funct == 0x2A) /* slt */
{
sim->pcValue += 4;
sim->numClock += 4;
printf(" slt %s, %s, %s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
if(sim->regs[getrs(n)] < sim->regs[getrt(n)])
sim->regs[getrd(n)] = 1;
else
sim->regs[getrd(n)] = 0;
printf(" Number of cycles: 4 \n");
}
else if(funct == 0x2B) /* sltu */
{
sim->pcValue += 4;
sim->numClock += 4;
printf(" sltu %s, %s, %s \n",
table[getrd(n)], table[getrs(n)], table[getrt(n)]);
if(sim->regs[getrs(n)] < sim->regs[getrt(n)])
sim->regs[getrd(n)] = 1;
else
sim->regs[getrd(n)] = 0;
printf(" Number of cycles: 4 \n");
}
else if(funct == 0x08) /* jump register */
{
printf(" jr %s \n", table[getrs(n)]);
sim->pcValue = sim->regs[getrs(n)];
sim->numClock += 3;
printf(" Number of cycles: 3 \n");
}
else if(funct == 0x09) /* jalr */
{
sim->pcValue += 4;
sim->numClock += 3;
printf(" jalr %s \n", table[getrs(n)]);
sim->regs[31] = sim->pcValue;
sim->pcValue = sim->regs[getrs(n)];
printf(" Number of cycles: 3 \n");
}
else
{
printf("Instruction@%08X : %08X is not a valid instruction! \n", i, n);
}
}
/* Function DecodeIJ
* Decodes and prints I or J type if valid
*/
void decodeIJ(int n, int opc, int i, MIPS_SIM* sim)
{
if(opc == 0x02 || opc == 0x03) /* j or jal */
{
//int temp = n;
//n &= 0xF0000000; /* save PC */
//temp &= 0x0FFFFFFF; /* obtain 26 address*/
//temp <<= 2; /* multiply by 4 */
//n += temp; /* effective address */
n &= 0x03FFFFFF;
n <<= 2;
if(opc == 0x02)
{
printf(" j %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], n);
sim->pcValue = n;
printf(" Number of cycles: 3 \n");
sim->numClock += 3;
}
else
{
printf(" jal %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], n);
sim->regs[31] = sim->pcValue + 4;
sim->pcValue = n;
printf(" Number of cycles: 3 \n");
sim->numClock += 3;
}
}
else if(opc == 0x08) /* addi */
{
printf(" addi %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], getimm16(n));
sim->regs[getrt(n)] = sim->regs[getrs(n)] + getimm16(n);
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numClock += 4;
}
else if(opc == 0x09) /* addiu */
{
printf(" addiu %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], getimm16(n));
sim->regs[getrt(n)] = sim->regs[getrs(n)] + getimm16(n);
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numClock += 4;
}
else if(opc == 0x0C) /* andi */
{
printf(" andi %s, %s, 0x%.8x \n ",
table[getrt(n)], table[getrs(n)], n & 0X0000FFFF);
sim->regs[getrt(n)] = sim->regs[getrs(n)] & (n & 0x0000FFFF);
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numClock += 4;
}
else if(opc == 0x0D) /* ori */
{
printf(" ori %s, %s 0x%.8x \n",
table[getrt(n)], table[getrs(n)], n & 0X0000FFFF);
sim->regs[getrt(n)] = sim->regs[getrs(n)] | (n & 0x0000FFFF);
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numClock += 4;
}
else if(opc == 0x0E) /* xori */
{
printf(" xori %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], n & 0X0000FFFF);
sim->regs[getrt(n)] = sim->regs[getrs(n)] ^ (n & 0x0000FFFF);
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numClock += 4;
}
else if(opc == 0x0A) /* slti */
{
printf(" slti %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], getimm16(n));
sim->regs[getrt(n)] = sim->regs[getrs(n)] < (n & 0x0000FFFF) ? 1 : 0;
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numClock += 4;
}
else if(opc == 0x0B) /* sltiu */
{
printf(" sltiu %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], getimm16(n));
sim->regs[getrt(n)] = sim->regs[getrs(n)] < (n & 0x0000FFFF) ? 1 : 0;
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numClock += 4;
}
else if(opc == 0x04) /* beq */
{
printf(" beq %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], geteff(n, i));
if (sim->regs[getrt(n)] == sim->regs[getrs(n)])
sim->pcValue = geteff(n,i);
else
sim->pcValue += 4 ;
printf(" Number of cycles: 3 \n");
sim->numClock += 3;
}
else if(opc == 0x05) /* bne */
{
printf(" bne %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], geteff(n, i));
if (sim->regs[getrt(n)] != sim->regs[getrs(n)])
sim->pcValue = geteff(n,i);
else
sim->pcValue += 4;
printf(" Number of cycles: 3 \n");
sim->numClock += 3;
}
else if(opc == 0x20) /* lb */
{
printf(" lb, %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], getimm8(n));
sim->regs[getrt(n)] = mem[(sim->regs[getrs(n)] + getimm8(n))/4];
if ((sim->regs[getrt(n)] & 0x00000080) != 0)
sim->regs[getrt(n)] |= 0xFFFFFF00;
sim->pcValue +=4;
printf(" Number of cycles: 5 \n");
sim->numOfRWs ++;
sim->numClock += 5;
}
else if(opc == 0x24) /* lbu */
{
printf(" lbu %s, %s, 1x%.8x \n",
table[getrt(n)], table[getrs(n)], n & 0x000000FF);
sim->regs[getrt(n)] = mem[(sim->regs[getrs(n)] + (n & 0x000000FF))/4];
sim->regs[getrt(n)] &= 0x000000FF;
sim->pcValue += 4;
printf(" Number of cycles: 5 \n");
sim->numOfRWs ++;
sim->numClock += 5;
}
else if(opc == 0x21) /* lh */
{
printf(" lh %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], getimm16(n));
sim->regs[getrt(n)] = mem[(sim->regs[getrs(n)] + getimm16(n))/4];
sim->regs[getrt(n)] <<= 16;
sim->regs[getrt(n)] >>= 16;
sim->pcValue += 4;
printf(" Number of cycles: 5 \n");
sim->numOfRWs ++;
sim->numClock += 5;
}
else if(opc == 0x21) /* lhu */
{
printf(" lhu %s, %s, 0x%.8x \n",
table[getrt(n)], table[getrs(n)], n & 0x0000FFFF);
sim->regs[getrt(n)] = mem[(sim->regs[getrs(n)] + (n & 0x0000FFFF))/4];
sim->regs[getrt(n)] &= 0x0000FFFF;
sim->pcValue += 4;
printf(" Number of cycles: 5 \n");
sim->numOfRWs ++;
sim->numClock += 5;
}
else if(opc == 0x0F) /* lui */
{
printf(" lui %s, 0x%.8x \n",
table[getrt(n)], getimm16(n));
sim->regs[getrt(n)] = n << 16;
sim->pcValue += 4;
printf(" Number of cycles: 5 \n");
sim->numOfRWs ++;
sim->numClock += 5;
}
else if(opc == 0x23) /* lw */
{
printf(" lw %s, %s,0x%.8x \n",
table[getrs(n)], table[getrt(n)], getimm16(n));
sim->regs[getrt(n)] = mem[(sim->regs[getrs(n)] + getimm16(n))/4];
sim->pcValue += 4;
printf(" Number of cycles: 5 \n");
sim->numOfRWs ++;
sim->numClock += 5;
}
else if(opc == 0x28) /* sb */
{
printf(" sb %s, 0x%.8x (%s) \n",
table[getrt(n)], getimm8(n), table[getrs(n)]);
mem[(getimm8(n) + sim->regs[getrs(n)])/4] = sim->regs[getrt(n)];
mem[(getimm8(n) + sim->regs[getrs(n)])/4]&= 0x000000FF;
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numOfRWs ++;
sim->numClock += 4;
}
else if(opc == 0x29) /* sh */
{
printf(" lw %s, 0x%.8x (%s)\n",
table[getrt(n)], getimm16(n), table[getrs(n)]);
mem[(getimm16(n) + sim->regs[getrs(n)])/4] = sim->regs[getrt(n)];
mem[(getimm16(n) + sim->regs[getrs(n)])/4] &= 0x0000FFFF;
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numOfRWs ++;
sim->numClock += 4;
}
else if(opc == 0x2B) /* sw */
{
printf(" lw %s, 0x%.8x (%s) \n",
table[getrt(n)], getimm16(n), table[getrs(n)]);
mem[(getimm16(n) + sim->regs[getrs(n)])/4] = sim->regs[getrt(n)];
sim->pcValue += 4;
printf(" Number of cycles: 4 \n");
sim->numOfRWs ++;
sim->numClock += 4;
}
else
{
printf("Instruction@%08X : %08X is not a valid instruction! \n \n", i, n);
sim->pcValue += 4;
}
}
/* Function getimm8 - get immediate byte sign ext*/
int getimm8(int n)
{
int extBit, temp;
extBit = n & 0x00000080;
extBit >>= 7;
if(extBit) /* sign extend if 7th bit is set */
{
temp = n & 0x000000FF;
return temp += 0xFFFFFF00;
} else /* zero sign extend */
{
return n &= 0x000000FF;
}
}
/* Function getimm16 - get immediate halfword sign ext */
int getimm16(int n)
{
int extBit, temp;
extBit = n & 0x00008000;
extBit >>= 15;
if(extBit) /* sign extend if bit is set */
{
temp = n & 0x0000FFFF;
return temp += 0xFFFF0000;
} else /* zero sign extend */
{
return n &= 0x0000FFFF;
}
}
/*Function geteff returns effective address */
int geteff(int n, int i)
{
i += 4; /* advance PC */
n = getimm16(n); /* get immediate value (might be sign extended) */
n <<= 2; /* word align the value */
return n + i; /* add PC to Branch Address */
}
/* Functions get registers and get shift */
int getrs(int n)
{
n &= 0x03E00000; /* return $rs register */
return n >> 21;
}
int getrt(int n)
{
n &= 0x001F0000; /* return $rt register */
return n >> 16;
}
int getrd(int n)
{
n &= 0x0000F800; /* return $rd register */
return n >> 11;
}
int getshift(int n)
{
n &= 0x000007C0; /* return shift amount */
return n >> 6;
}
|
C
|
/*
Practica 4
imprimir numeros del 0 al n.
Mario Arturo Perez Rangel
*/
#include <stdio.h>
int main()
{
int i,n;
printf("Escriba un numero positivo: ");
scanf("%u", &n);
for (i=0;i<=n;i++) {
printf ("%u\n", i);
}
}
|
C
|
#include <stdio.h>
void ponervalores (float* , int, float );
int main()
{
float arreglo[20]; /// ESTE ES EL QUE PUSE DE ARGUMENTO
ponervalores(arreglo, 20, 2.5);
for (int i=0; i < 20; i++){
printf("%.2f\n", arreglo[i]);
}
return 0;
}
void ponervalores (float* array, int tamano, float numero){
for (int i=0; i < tamano; i++){
array[i]=numero * (i+1);
}
}
|
C
|
#include <stdlib.h>
#include <limits.h>
#include <stdio.h> //RICRODA
#include "singleP.h"
tree* newTree(int &nodes);
tree* newRandomTree(){
int nodes=rand()%1000+99;
tree* t= (tree*) malloc(sizeof(tree));
t->info=rand();
t->son=newTree(&nodes);
t->bro=newTree(&nodes);
return t;
}
tree* newTree(int* nodes){
tree* t=NULL;
if(*nodes>0){
nodes--;
t->info=rand();
t->son=newTree(&nodes-1);
t->bro=newTree(&nodes-1);
}
return t;
}
int max(tree* t){
if(t!=NULL){
int me=t->info;
int son=max(t->son);
int bro=max(t->bro);
if(me>son){
if(me>bro) return bro;
return me;
} else if(son>bro)
return son;
return bro;
}
return INT_MIN;
}
|
C
|
#ifndef MAIN_H
#define MAIN_H
#include <stdio.h>
#include <stdlib.h>
#define SUCCESS 1
#define FAILURE 0
#define LIST_EMPTY -1
#define DATA_FOUND 5
#define DATA_NOT_FOUND 6
typedef int data_t;
typedef struct node
{
data_t data;
struct node *prev;
struct node *next;
}dlist;
int insert_first(dlist **head, data_t data, dlist **tail);
void print_list(dlist *head);
int insert_after(dlist **head, dlist **tail, data_t data, data_t new_data);
int insert_before(dlist **head, dlist **tail, data_t data, data_t new_data);
int delete_element(dlist **head, dlist **tail, data_t data);
#endif
|
C
|
#include "../include/util_discordiador.h"
//funcion agregada
bool esBloqueante(Tarea *tarea)
{
//pendiente
return true;
}
Patota *map_to_patota(t_iniciar_patota datosPatota)
{
// numeroTripulante--;
Patota *patota_new = malloc(sizeof(Patota));
patota_new->id = numeroPatota;
patota_new->tareas = list_create(); //Lista [Tarea]
patota_new->tripulantes = list_create(); //Lista [Tripulante]
t_list *posiciones_lista = list_create();
char **posiciones_string;
if (strcmp(datosPatota.posiciones, "") != 0)
{
posiciones_string = string_split(datosPatota.posiciones, " ");
void recorrer_posiciones(char *item)
{
list_add(posiciones_lista, item);
}
string_iterate_lines(posiciones_string, recorrer_posiciones);
}
for (int c = 0; c < datosPatota.cant_tripulantes; c++)
{
Tripulante *tripulante = malloc(sizeof(Tripulante));
tripulante->id = numeroTripulante;
tripulante->status = NEW;
tripulante->tarea = malloc(sizeof(t_info_tarea));
tripulante->tarea = NULL;
tripulante->posicion = malloc(sizeof(Posicion));
tripulante->posicion->posx = 0;
tripulante->posicion->posy = 0;
tripulante->posicion_anterior = malloc(sizeof(Posicion));
tripulante->posicion_anterior->posx = 0;
tripulante->posicion_anterior->posy = 0;
tripulante->patota_id = numeroPatota;
//se inicializan los semaforos de los tripulantes
sem_init(&tripulante->activo, 0, 0);
sem_init(&tripulante->seleccionado, 0, 0);
sem_init(&tripulante->seleccionado_bloqueado, 0, 0);
//sem_init(&tripulante->sabotaje, 0, 0);
// pthread_mutex_init(&tripulante->seleccionado, NULL);
// pthread_mutex_init(&tripulante->seleccionado_bloqueado, NULL);
//pthread_mutex_init(&tripulante->sabotaje,0);
list_add(patota_new->tripulantes, tripulante);
// defino los sockets en -1
tripulante->socket_cliente_mongo_store = -1;
tripulante->socket_cliente_mi_ram = -1;
tripulante->expulsado = false;
numeroTripulante++;
}
int posx = 0;
int posy = 0;
for (int c = 0; c < list_size(posiciones_lista); c++)
{
Tripulante *tripulante = list_get(patota_new->tripulantes, c);
char *posicion_string = list_get(posiciones_lista, c);
char **coordenadas = string_split(posicion_string, "|");
posx = atoi(coordenadas[0]);
posy = atoi(coordenadas[1]);
tripulante->posicion->posx = posx;
tripulante->posicion->posy = posy;
}
//Falta mapeo de tareas para patota
//list_clean(posiciones_lista);
//list_destroy(posiciones_lista);
//liberar_puntero_doble(posiciones_string);
numeroPatota++;
return patota_new;
}
void mostrar_t_patota(Patota *patota)
{
printf("Inicio de patota\n");
printf("Patota id: %d\n", patota->id);
for (int c = 0; c < list_size(patota->tripulantes); c++)
{
Tripulante *tripulante = list_get(patota->tripulantes, c);
printf("Tripulante id: %d ", tripulante->id);
printf("Status: %s ", get_status_string(tripulante->status));
printf("Posicion: %d-%d\n", tripulante->posicion->posx, tripulante->posicion->posy);
}
}
void mostrar_datos_patota(t_iniciar_patota *datosPatota)
{
printf("tripulantes: %d\n", datosPatota->cant_tripulantes);
printf("long path tares: %d\n", datosPatota->long_tareas);
printf("long posiciones: %d\n", datosPatota->long_posicion);
printf("posiciones: %s\n", datosPatota->posiciones);
printf("pathTareas: %s\n", datosPatota->tareas);
}
char *get_status_string(status_tripulante status)
{
char *texto = "";
switch (status)
{
case NEW:
texto = "New";
break;
case READY:
texto = "Ready";
break;
case EXEC:
texto = "Exec";
break;
case BLOCKED:
texto = "Block I/0";
break;
case EXIT:
texto = "Exit";
break;
case BLOCKED_SABOTAJE:
texto = "Block sabotaje";
break;
}
return texto;
}
t_list *get_tripulantes_all()
{
t_list *tripulantes = lista_tripulantes;
for (int i = 0; i < list_size(tripulantes); i++)
{
Tripulante *tripulante = list_get(tripulantes, i);
printf("ID del tripulante : %d\n", tripulante->id);
}
return tripulantes;
}
Tripulante *tripulante_segun_id(int id)
{
_Bool mismo_id(void *param)
{
Tripulante *tripulante = param;
return tripulante->id == id;
}
return (Tripulante *)list_find(get_tripulantes_all(), &mismo_id);
}
//lista_tripulante= get
int existe_tripulante(int id)
{
return tripulante_segun_id(id) == NULL ? false : true;
}
int obtener_cantidad_argumentos(char **tokens)
{
int i = 1;
int cantidad = 0;
while (*(tokens + i) != NULL)
{
cantidad++;
i++;
}
return cantidad;
}
int guardar_contenido_archivo(const char *ruta, char **contenido)
{
FILE *arch = fopen(ruta, "r");
int bytes;
*contenido = NULL;
fseek(arch, 0, SEEK_END);
bytes = ftell(arch);
fseek(arch, 0, SEEK_SET);
*contenido = malloc(bytes);
fread(*contenido, 1, bytes, arch);
fclose(arch);
return bytes;
}
char *get_tareas_from_path(char *path)
{
int file_size = 1000;
int fd = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
ftruncate(fd, file_size);
char *tareas = mmap(NULL, file_size, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0);
//printf("%s %d\n", space, strlen(space));
return tareas;
}
|
C
|
#include <stdio.h>
#include <string.h> // ڿ Լ
#pragma warning(disable:4996)
/*
* ڿ ( ) ȯ
* strlen(ڿ);
* strlen(ڹ迭);
*
* ڿ ȯ
* strcmp(ڿ1, ڿ2);
* int strcmp(char const *_Str1, char const *_Str2);
*
* -1: ASCII ڵ ڿ2(s2) Ŭ
* 0: ASCII ڵ ڿ
* 1: ASCII ڵ ڿ1(s1) Ŭ
*
* ڿ
* strcpy(ڿ, ڿ);
* char *strcpy(char *_Dest, char const *_Source);
* ڿ ȯ
*
* ڿ ̱
* strcat(ڿ, Ϲڿ);
* char *strcat(char *_Destination, char const *_Source);
* ڿ ȯ
*
* ڿ ȿ '' ˻
* strchr(ڿ, ˻ҹ);
* char *strchr(char * const _String, int const _Ch);
* ڸ ã ڷ ϴ ڿ ȯ, ڰ NULL ȯ
*
* ڿ ȿ 'ڿ' ˻
* strstr(ڿ, ˻ҹڿ);
* char *strstr(char * const _String, char const * const _SubString);
* ڿ ã ڿ ϴ ڿ ȯ, ڿ NULL ȯ
*
* ڿ ҹ ȯ
* strupr(ڿ) : ־ ڿ 빮ڷ ȯ
* strlwr(ڿ) : ־ ڿ ҹڷ ȯ
* ڿ ȭ (!)
*/
int main()
{
char *s1 = "Hello"; // s1 ڿ "Hello" ּ
char s2[10] = "Hello"; // ũⰡ 10 char 迭 ϰ ڿ Hello .
// ڿ strlen()
{
printf("%d\n", strlen(s1));
printf("%d\n", strlen(s2));
printf("%d\n", strlen("Thank you"));
}
// ڿ strcmp()
{
int ret = strcmp(s1, s2);
printf("%d\n", ret); // 0 : ڿ 0
if (strcmp(s1, s2)) {
printf("%s %s ٸϴ\n", s1, s2);
}
else {
printf("%s %s ϴ\n", s1, s2);
}
// aaa ASCII ڵ 97 97 97
// aab ASCII ڵ 97 97 98
// aac ASCII ڵ 97 97 99
printf("%d\n", strcmp("aaa", "aaa"));
printf("%d\n", strcmp("aab", "aaa"));
printf("%d\n", strcmp("aab", "aac"));
printf("%d\n", strcmp("aAaA", "AaAa"));
}
// ڿ strcpy()
{
char s1[10] = "Hello"; // s1[10] '' . <--
char s2[10] = "Mickey";
printf("strcpy() s2 = %s\n", s2);
strcpy(s2, s1); // s1 ڿ s2 .
printf("strcpy() s2 = %s\n", s2);
s2[1] = 'a'; // ÿ <--
printf("%s\n", s2);
}
{
//
char *s1 = "Hello"; // ڿ ' (data segment)' <-- Ұ(read only)
char *s2 = "Mickey";
// VS2017 ̻ ڿ ͷ const char* Ѿ Ѵ.
//strcpy(s2, s1); // ?
// s2[1] = 'a'; // "Mackey"???
printf("%s\n", s2);
}
// ڿ ̱ strcat() string concatenation
{
char s1[10] = "world";
char s2[20] = "Hello";
printf("strcat() s2 = %s\n", s2);
strcat(s2, s1); // s2 ڿ s1
printf("strcat() s2 = %s\n", s2);
}
// ڿ ȿ ڷ ˻ strchr()
{
char s1[30] = "A Garden Diary abc aaa";
char *ptr = strchr(s1, 'a'); // ڿ s1 'a' ˻. ã ġ
//ptr = strchr(s1, 'x'); // NULL
if (ptr) {
printf("%d ° ãҴ\n", ptr - s1);
}
else {
printf("\n");
}
printf("%s\n", ptr);
while (ptr != NULL) // ̻ ˻ '' ݺ ˻
{
printf("%d ° ߰ %s\n", ptr - s1, ptr);
ptr = strchr(ptr + 1, 'a'); // Ϳ +1 Ͽ, ߰ߵ ٽ ˻
}
}
// ڿ ȿ ڿ ˻ strstr()
{
char s1[30] = "A Garden Diary";
char *ptr = strstr(s1, "den"); // ڿ s1 "den" ˻, ߰ ġ
if (ptr) {
printf("%d ° ãҴ\n", ptr - s1);
}
else {
printf("\n");
}
}
// ڿ ҹ ȯ strupr(), strlwr()
{
char s1[30] = "A Garden Diary";
printf("strupr() => %s, s1 => %s\n", strupr(s1), s1); // ȭ
printf("strlwr() => %s, s2 => %s\n", strlwr(s1), s1); // ȭ
}
printf("\nENTER α ˴ϴ\n");
getchar();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int continuer = 0;
do
{
int premierNombre = 0, deuxiemeNombre = 0, resultat = 0, reste = 0;
printf("Division avec reste : premier nombre ?");
scanf("%d", &premierNombre);
printf("\nDeuxieme nombre ?");
scanf("%d", &deuxiemeNombre);
if (deuxiemeNombre != 0)
{
resultat = premierNombre/deuxiemeNombre;
reste = premierNombre%deuxiemeNombre;
printf("\nQuand on divise %d par %d, il y va %d fois, reste %d \n", premierNombre, deuxiemeNombre, resultat, reste);
}
else
{
printf("Desole, les divisions par 0 sont trop difficiles. :( \n");
}
printf("Si vous souhaitez faire une autre division, tapez 1.");
scanf("%d", &continuer);
printf("\n\n");
}while (continuer == 1);
return 0;
}
|
C
|
#include<stdio.h>
#include<time.h>
int main()
{
time_t t = time(NULL);//0 ==NULL
int y = 0,d = 0,h = 0,m = 0,s = 0;
m =t%3600;
h = (t-m)/3600;
d = h/24;
h = h-d*24;
s = m%60;
m = (m-s)/60;
y= d/365;
d = d%365;
printf("%d:%d:%d:%d:%d\n",y+1970,d,h+8,m,s);
return 0;
}
|
C
|
#include <stdio.h>
int Partition(int a[],int l, int r)
{
int pivot, i, j, t;
// 피벗을 첫번째 요소로 정하자
pivot = a[l];
// i 는 다음칸
i = l + 1;
// j 는 r
j = r;
while(1)
{
while(a[i] <= pivot && i <= r)
i++;
while(a[j] > pivot)
j--;
if( i >= j)
break;
t = a[i]; a[i] = a[j]; a[j] = t;
}
t = a[l]; a[l] = a[j]; a[j] = t;
return j;
}
void QuickSort(int a[],int l, int r)
{
for(int i = 0; i < 10; i ++)
printf("%d ",a[i]);
printf("\n");
int j;
// l 하고 r 같으면 퀵소트 그만하자..;;
if( l < r)
{
// 나누고 정복!!!
j = Partition(a, l, r);
// 나눈걸 통해 또다시 퀵소트
QuickSort(a, l, j - 1);
QuickSort(a, j + 1, r);
}
}
int main()
{
int arr[10] = {3, 7, 2, 1, 8, 4, 5, 6, 9, 0};
QuickSort(arr,0,9);
for(int i = 0; i < 10; i ++)
printf("%d ",arr[i]);
printf("\n");
return 0;
}
|
C
|
#if !defined(_MSC_VER)
/*
* We're asking whether the OS supports AVX.
*
* Quoting from: https://en.wikipedia.org/wiki/Advanced_Vector_Extensions
* "AVX adds new register-state through the 256-bit wide YMM register file, so
* explicit operating system support is required to properly save and restore
* AVX's expanded registers between context switches."
*
* In order to save the registers:
* - the CPU needs to support XSAVE, XRESTOR, XSETBV, XGETBV instructions
* (checked elsewhere with _cpuid(1) call, checking bit 26 of ECX);
* - the XSAVE instruction should be "enabled by OS" (cpuid(1), bit 27 of
* ECX, checked elsewhere);
* - A check whether the expanded YMM registers are saved / restored on
* context switch.
*
* The routines here check do this last check.
*
* If we can use assembly, we can use the XGETBV x86 instruction to tell us
* whether the registers are preserved on context switch:
* https://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled/
*
* On MSVC we have a problem, because the MSVC 2010 SP1 is the first version
* of MSVC to have a compiler intrinsic for XGETBV, and MSVC does not support
* inline ``__asm`` in 64-bit:
* http://forums.codeguru.com/showthread.php?551499-xgetbv
* https://msdn.microsoft.com/en-us/library/hb5z4sxd.aspx
*
* Therefore, for MSVC, we have to use the GetEnabledXStateFeatures function
* to check if the feature is enabled:
* https://msdn.microsoft.com/en-us/library/windows/desktop/hh134235(v=vs.85).aspx
* https://msdn.microsoft.com/en-us/library/windows/desktop/hh134240(v=vs.85).aspx
*
* When we can drop support for MSVC < 2010 SP1, then we can use the
* ``_XGETBV`` intrinsic instead of this workaround:
* https://msdn.microsoft.com/en-us/library/hh977023.aspx
*/
#include <stdint.h>
void _xgetbv(uint32_t op, uint32_t* eax_var, uint32_t* edx_var)
{
/* Use binary code for xgetbv
*
* We should not reach this check unless cpuid says the CPU has xgetbv
* instructions via cpuid(1) and ECX bit 26 (xsave):
* https://en.wikipedia.org/wiki/CPUID
*/
__asm__ __volatile__
(".byte 0x0f, 0x01, 0xd0": "=a" (*eax_var), "=d" (*edx_var) : "c" (op) : "cc");
}
int os_restores_ymm(void)
{
uint32_t eax_val, edx_val;
// XFEATURE_ENABLED_MASK/XCR0 register number = 0
_xgetbv(0, &eax_val, &edx_val);
// XFEATURE_ENABLED_MASK register is in edx:eax
return (eax_val & 6) == 6;
}
#else
/*
* This is the workaround where we cannot use the XGETBV instruction for the
* check.
*
* Much of this code fragment copied from:
* https://msdn.microsoft.com/en-us/library/windows/desktop/hh134240(v=vs.85).aspx
* I (MB) assume this code is public domain given its apparent intended
* purpose as an exmaple of code usage.
*/
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <winerror.h>
// Windows 7 SP1 is the first version of Windows to support the AVX API.
// Since the AVX API is not declared in the Windows 7 SDK headers and
// since we don't have the proper libs to work with, we will declare
// the API as function pointers and get them with GetProcAddress calls
// from kernel32.dll. We also need to set some #defines.
#define XSTATE_AVX (XSTATE_GSSE)
#define XSTATE_MASK_AVX (XSTATE_MASK_GSSE)
typedef DWORD64 (WINAPI *PGETENABLEDXSTATEFEATURES)();
PGETENABLEDXSTATEFEATURES pfnGetEnabledXStateFeatures = NULL;
typedef BOOL (WINAPI *PINITIALIZECONTEXT)(PVOID Buffer, DWORD ContextFlags, PCONTEXT* Context, PDWORD ContextLength);
PINITIALIZECONTEXT pfnInitializeContext = NULL;
typedef BOOL (WINAPI *PGETXSTATEFEATURESMASK)(PCONTEXT Context, PDWORD64 FeatureMask);
PGETXSTATEFEATURESMASK pfnGetXStateFeaturesMask = NULL;
typedef PVOID (WINAPI *LOCATEXSTATEFEATURE)(PCONTEXT Context, DWORD FeatureId, PDWORD Length);
LOCATEXSTATEFEATURE pfnLocateXStateFeature = NULL;
typedef BOOL (WINAPI *SETXSTATEFEATURESMASK)(PCONTEXT Context, DWORD64 FeatureMask);
SETXSTATEFEATURESMASK pfnSetXStateFeaturesMask = NULL;
int xstate_has_avx(void)
{
DWORD64 FeatureMask;
// If this function was called before and we were not running on
// at least Windws 7 SP1, then bail.
if (pfnGetEnabledXStateFeatures == (PGETENABLEDXSTATEFEATURES)-1)
{
return -1;
}
// Get the addresses of the AVX XState functions.
if (pfnGetEnabledXStateFeatures == NULL)
{
HMODULE hm = GetModuleHandle(_T("kernel32.dll"));
if (hm == NULL)
{
pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)-1;
return -2;
}
pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)GetProcAddress(hm, "GetEnabledXStateFeatures");
pfnInitializeContext = (PINITIALIZECONTEXT)GetProcAddress(hm, "InitializeContext");
pfnGetXStateFeaturesMask = (PGETXSTATEFEATURESMASK)GetProcAddress(hm, "GetXStateFeaturesMask");
pfnLocateXStateFeature = (LOCATEXSTATEFEATURE)GetProcAddress(hm, "LocateXStateFeature");
pfnSetXStateFeaturesMask = (SETXSTATEFEATURESMASK)GetProcAddress(hm, "SetXStateFeaturesMask");
if (pfnGetEnabledXStateFeatures == NULL
|| pfnInitializeContext == NULL
|| pfnGetXStateFeaturesMask == NULL
|| pfnLocateXStateFeature == NULL
|| pfnSetXStateFeaturesMask == NULL)
{
pfnGetEnabledXStateFeatures = (PGETENABLEDXSTATEFEATURES)-1;
return -3;
}
}
FeatureMask = pfnGetEnabledXStateFeatures();
return ((FeatureMask & XSTATE_MASK_AVX) != 0);
}
int os_restores_ymm(void)
{
return xstate_has_avx() > 0;
}
#endif
|
C
|
/*
* Copyright (c) 1991 Michael Landy
*
* Disclaimer: No guarantees of performance accompany this software,
* nor is any responsibility assumed on the part of the authors. All the
* software has been tested extensively and every effort has been made to
* insure its reliability.
*/
/*
* h_discedge.c - a discrete domain regional edge detector
*
* size is the length of a side of the nonoverlapping domains in which
* the algorithm operates, and varcrit is the threshold on the variance
* in the normalized region (normalized by mean only) below which no
* edge is sought in that region.
*
* This program is an implementation of the discrete domain regional operator
* described by G. B. Shaw (Comp. Graph. and Image Proc., 9, pp. 135-149 (1979).
* The algorithm outlined therein is sketchy and contains errors, which
* hopefully are corrected here. Also, the article does not clarify what to do
* with edges which appear to travel along a border of the region (the algorithm
* purports to be symmetric with respect to horizontal and vertical edges, but
* isn't really). In this implementation, the first pixels on the light
* side of a light/dark edge are marked, and when the light/dark boundary
* travels along the boundary of the region, only the "middlemost" pixel is
* marked, since otherwise horizontal edges will all include little "tails" at
* an edge of each region. Lastly, note that any excess after multiples of
* size in rows and columns is not edge detected. The output image is integer
* (not byte), and gives the score for the edge to each edgel in a given region.
* The computations are done with integer arithmetic with all pixels scaled by
* size*size in order that the normalization by the mean can be exact.
*
* pixel formats: BYTE
*
* Mike Landy 6/1/82
* HIPS 2 - msl - 8/8/91
*/
#include <hipl_format.h>
#include <math.h>
static int dalloc = FALSE;
static int *a,*b,*template,*normal;
static int savesize = -1;
int h_discedge(hdi,hdo,size,varcrit)
struct header *hdi,*hdo;
int size;
float varcrit;
{
switch(hdi->pixel_format) {
case PFBYTE: return(h_discedge_b(hdi,hdo,size,varcrit));
default: return(perr(HE_FMTSUBR,"h_discedge",
hformatname(hdi->pixel_format)));
}
}
int h_discedge_b(hdi,hdo,size,varcrit)
struct header *hdi,*hdo;
int size;
float varcrit;
{
return(h_discedge_B(hdi->firstpix,(int *) hdo->firstpix,hdi->rows,
hdi->cols,hdi->ocols,hdo->ocols,size,varcrit));
}
int h_discedge_B(imagei,imageo,nr,nc,nlpi,nlpo,size,varcrit)
byte *imagei;
int *imageo,nr,nc,nlpi,nlpo,size;
float varcrit;
{
float sumsq;
int *np,*ap,*bp,*b1,*b2,*b3,*b4;
int *b1p,*b2p,*b3p,*b4p,bedge;
int *b1pp,*b2pp,*b3pp,*b4pp;
int sum,min,max;
int *tp,pos,bpos,btype;
int r,c,i,rr,rc,nexi;
byte *ip;
if (dalloc && savesize < size) {
free(a); free(b); free(template); free(normal);
dalloc = FALSE;
}
if (!dalloc) {
if ((a = (int *) memalloc(size*(size+1),sizeof (int))) ==
(int *) HIPS_ERROR)
return(HIPS_ERROR);
if ((b = (int *) memalloc(size*(size+1)*4,sizeof (int))) ==
(int *) HIPS_ERROR)
return(HIPS_ERROR);
if ((template = (int *) memalloc(size,sizeof (int))) ==
(int *) HIPS_ERROR)
return(HIPS_ERROR);
if ((normal = (int *) memalloc(size*size,sizeof (int))) ==
(int *) HIPS_ERROR)
return(HIPS_ERROR);
dalloc = TRUE;
savesize = size;
}
nexi = nlpi - size;
b1 = b;
b2 = b + (size+1)*size;
b3 = b2 + (size+1)*size;
b4 = b3 + (size+1)*size;
h_setimage_I(imageo,nr,nc,nlpo,0);
for (rr=0;rr<=nr-size;rr+=size) {
for (rc=0;rc<=nc-size;rc+=size) {
/* extract the region */
ip = imagei + rr*nlpi + rc;
np = normal;
sum = 0;
for (r=0;r<size;r++) {
for (c=0;c<size;c++) {
sum += *ip;
*np++ = *ip++ * size * size;
}
ip += nexi;
}
np = normal;
sumsq = 0;
/* normalize by mean, compute variance */
for (i=0;i<size*size;i++) {
*np -= sum;
sumsq += *np * *np;
np++;
}
sumsq /= size*size*size*size;
/* skip region if variance is too low */
if (sumsq <= varcrit)
continue;
/* compute a */
ap = a;
for (r=0;r<size;r++) {
for (c=0;c<=size;c++) {
*ap = 0;
np = &normal[r*size];
for (i=0;i<c;i++)
*ap += *np++;
for (;i<size;i++)
*ap -= *np++;
ap++;
}
}
/* the first row of b1,...,b4 equals the
first row of a */
b1p = b1;
b2p = b2;
b3p = b3;
b4p = b4;
ap = a;
for (c=0;c<=size;c++) {
*b1p++ = *ap;
*b2p++ = *ap;
*b3p++ = *ap;
*b4p++ = *ap++;
}
for (r=1;r<size;r++) {
/* compute b1/b2 from left to right*/
b1p = b1 + r*(size+1);
b1pp = b1p - (size+1);
b2p = b2 + r*(size+1);
b2pp = b2p - (size+1);
ap = a + r*(size+1);
max = *b1pp++;
min = *b2pp++;
*b1p++ = max + *ap;
*b2p++ = min + *ap++;
for (c=1;c<=size;c++) {
max = *b1pp>max ? *b1pp : max;
b1pp++;
*b1p++ = max + *ap;
min = *b2pp<min ? *b2pp : min;
b2pp++;
*b2p++ = min + *ap++;
}
/* compute b3/b4 from right to left */
b3pp = b3 + r*(size+1);
b3p = b3pp + (size+1);
b4pp = b4 + r*(size+1);
b4p = b4pp + (size+1);
ap = a + (r+1)*(size+1);
max = *--b3pp;
min = *--b4pp;
*--b3p = max + *--ap;
*--b4p = min + *ap;
for (c=size-1;c>=0;c--) {
max = *--b3pp>max ? *b3pp : max;
*--b3p = max + *--ap;
min = *--b4pp<min ? *b4pp : min;
*--b4p = min + *ap;
}
}
/* find best edge value/type/pos in top row */
b1p = b1 + (size-1)*(size+1);
b2p = b2 + (size-1)*(size+1);
b3p = b3 + (size-1)*(size+1);
b4p = b4 + (size-1)*(size+1);
bedge = *b1p;
bpos = 0;
btype = 1;
for (c=0;c<=size;c++) {
if (*b1p>bedge) {
bedge = *b1p++;
bpos = c;
btype = 1;
}
else
b1p++;
if (-*b2p>bedge) {
bedge = - *b2p++;
bpos = c;
btype = 2;
}
else
b2p++;
if (*b3p>bedge) {
bedge = *b3p++;
bpos = c;
btype = 3;
}
else
b3p++;
if (-*b4p>bedge) {
bedge = - *b4p++;
bpos = c;
btype = 4;
}
else
b4p++;
}
tp = template + size;
*--tp = bpos;
switch (btype) {
/* light on left, edge moves rightward as row increases */
case 1:
/* compute template */
b1pp = b1 + (size-1)*(size+1) + bpos;
pos = bpos;
for (r=size-1;r>=0;r--) {
b1p = b1pp - (size+1);
max = *b1p;
bp = b1p;
if (pos != 0) {
for (c=pos;c>=0;c--) {
if (*b1p>max) {
pos = c;
bp = b1p;
max = *b1p--;
}
else
b1p--;
}
}
*--tp = pos;
b1pp = bp;
}
/* compute edgels */
pos = template[0] - 1;
tp = template - 1;
for (r=0;r<size;r++) {
if (*++tp == 0)
continue;
if (pos+1>=*tp)
pos = *tp - 2;
for (c=pos+1;c<*tp;c++)
imageo[(rr+r)*nlpo+
rc+c] = bedge;
pos = *tp - 1;
if (pos == size-1)
break;
}
break;
/* light on right, edge moves rightward as row increases */
case 2:
/* compute template */
b2pp = b2 + (size-1)*(size+1) + bpos;
pos = bpos;
for (r=size-1;r>=0;r--) {
b2p = b2pp - (size+1);
max = - *b2p;
bp = b2p;
if (pos != 0) {
for (c=pos;c>=0;c--) {
if (-*b2p>max) {
pos = c;
bp = b2p;
max = - *b2p--;
}
else
b2p--;
}
}
*--tp = pos;
b2pp = bp;
}
/* compute edgels */
pos = template[size-1];
tp = template + size;
for (r=size-1;r>=0;r--) {
if (*--tp == size)
continue;
if (pos-1<*tp)
pos = *tp + 1;
for (c=pos-1;c>=*tp;c--)
imageo[(rr+r)*nlpo+
rc+c] = bedge;
pos = *tp;
if (pos == 0)
break;
}
break;
/* light on left, edge moves leftward as row increases */
case 3:
/* compute template */
b3pp = b3 + (size-1)*(size+1) + bpos;
pos = bpos;
for (r=size-1;r>=0;r--) {
b3p = b3pp - (size+1);
max = *b3p;
bp = b3p;
if (pos != size) {
for (c=pos;c<=size;c++) {
if (*b3p>max) {
pos = c;
bp = b3p;
max = *b3p++;
}
else
b3p++;
}
}
*--tp = pos;
b3pp = bp;
}
/* compute edgels */
pos = template[size-1] - 1;
tp = template + size;
for (r=size-1;r>=0;r--) {
if (*--tp == 0)
continue;
if (pos+1 >= *tp)
pos = *tp - 2;
for (c=pos+1;c<*tp;c++)
imageo[(rr+r)*nlpo+
rc+c] = bedge;
pos = *tp - 1;
if (pos == size-1)
break;
}
break;
/* light on right, edge moves leftward as row increases*/
case 4:
/* compute template */
b4pp = b4 + (size-1)*(size+1) + bpos;
pos = bpos;
for (r=size-1;r>=0;r--) {
b4p = b4pp - (size+1);
max = - *b4p;
bp = b4p;
if (pos != size) {
for (c=pos;c<=size;c++) {
if (-*b4p>max) {
pos = c;
bp = b4p;
max = - *b4p++;
}
else
b4p++;
}
}
*--tp = pos;
b4pp = bp;
}
/* compute edgels */
pos = template[0];
tp = template - 1;
for (r=0;r<size;r++) {
if (*++tp == size)
continue;
if (pos-1<*tp)
pos = *tp + 1;
for (c=pos-1;c>=*tp;c--)
imageo[(rr+r)*nlpo+
rc+c] = bedge;
pos = *tp;
if (pos == 0)
break;
}
break;
default:
perr(HE_MSG,"type confusion!!");
}
}
}
return(HIPS_OK);
}
|
C
|
#include "xmame.h"
#include "driver.h"
static int mode_disable(struct rc_option *option, const char *s, int priority);
struct rc_option mode_opts[] = {
/* name, shortname, type, dest, deflt, min, max, func, help */
{ "Video Mode Selection Related", NULL, rc_seperator, NULL,
NULL, 0, 0, NULL,
NULL },
{ "keepaspect", "ka", rc_bool, &normal_use_aspect_ratio,
"1", 0, 0, NULL,
"Try / don't try to keep the aspect ratio of a game when selecting the best videomode" },
{ "displayaspectratio", "dar", rc_float, &display_aspect_ratio,
"1.33", 0.75, 1.33, NULL,
"Set the display aspect ratio of your monitor. This is used for -keepaspect The default = 1.33 (4/3). Use 0.75 (3/4) for a portrait monitor" },
{ "disablemode", "dm", rc_use_function, NULL,
NULL, 0, 0, mode_disable,
"Don't use mode XRESxYRESxDEPTH this can be used to disable specific video modes which don't work on your system. The xDEPTH part of the string is optional. This option may be used more then once" },
{ NULL, NULL, rc_end, NULL,
NULL, 0, 0, NULL,
NULL }
};
#define MODE_DISABLED_MAX 32
static int disabled_modes_count = 0;
static struct
{
int width;
int height;
int depth;
} disabled_modes[MODE_DISABLED_MAX];
static int mode_disable(struct rc_option *option, const char *s, int priority)
{
if (disabled_modes_count == MODE_DISABLED_MAX)
{
/* stderr_file doesn't have a valid value yet when we're called ! */
fprintf(stderr, "OSD: Warning: You can't disable more then %d modes. Mode %s not disabled\n",
MODE_DISABLED_MAX, s);
return OSD_OK;
}
if (sscanf(s, "%dx%dx%d",
&disabled_modes[disabled_modes_count].width,
&disabled_modes[disabled_modes_count].height,
&disabled_modes[disabled_modes_count].depth) < 2)
return OSD_NOT_OK;
switch (disabled_modes[disabled_modes_count].depth)
{
case 0:
case 256:
case 65536:
break;
default:
/* stderr_file doesn't have a valid value yet when we're called ! */
fprintf(stderr, "Svgalib: Warning: No such depth: %d. Mode not disabled\n",
disabled_modes[disabled_modes_count].depth);
return OSD_NOT_OK;
}
disabled_modes_count++;
return OSD_OK;
}
int mode_disabled(int width, int height, int depth)
{
int i;
for(i=0; i<disabled_modes_count; i++)
{
if (disabled_modes[i].width == width &&
disabled_modes[i].height == height)
{
switch (disabled_modes[disabled_modes_count].depth)
{
case 0:
return TRUE;
case 256:
if(depth == 8)
return TRUE;
break;
case 65536:
if(depth == 16)
return TRUE;
break;
}
}
}
return FALSE;
}
void mode_perfect(int *width, int *height)
{
double pixel_aspect_ratio;
static int first_time = TRUE;
if (use_aspect_ratio)
{
/* first of all calculate the pixel aspect_ratio the game has */
if (Machine->drv->video_attributes & VIDEO_TYPE_VECTOR)
{
pixel_aspect_ratio = 1.0;
}
else
{
pixel_aspect_ratio = (visual_width * widthscale) /
(yarbsize ? yarbsize :
(visual_height * heightscale * aspect_ratio));
}
/* should we maximize the used height, or the used width? */
if (display_aspect_ratio >= aspect_ratio)
{
*height = yarbsize ? yarbsize : (visual_height * heightscale);
*width = *height * pixel_aspect_ratio * display_aspect_ratio;
}
else
{
*width = visual_width * widthscale;
*height = *width / (pixel_aspect_ratio * display_aspect_ratio);
}
if (first_time)
{
fprintf(stderr_file, "OSD: Info: Ideal mode for this game = %dx%d\n",
*width, *height);
first_time = FALSE;
}
}
else
{
*width = visual_width;
*height = visual_height;
}
}
/* match a given mode to the needed width, height and aspect ratio to
perfectly display a game.
This function returns 0 for a not usable mode and 100 for the perfect mode.
*/
int mode_match(int width, int height)
{
int wanted_width, wanted_height;
mode_perfect(&wanted_width, &wanted_height);
/* does the game fit at all ? */
if(width < (visual_width * widthscale) ||
height < (yarbsize ? yarbsize : (visual_height * heightscale)))
return 0;
return ( 100 *
((float)wanted_width / (abs(width -wanted_width )+wanted_width )) *
((float)wanted_height / (abs(height-wanted_height)+wanted_height)));
}
|
C
|
#include<stdio.h>
int main ()
{
int num;
printf ("Enter a number ");
scanf ("%d", &num);
float r, si;
printf("We are going to play a prank\n");
printf("You have just enter a number %d\n", num);
return 0;
}
|
C
|
#ifndef _USER_H_
#define _USER_H_
/* This file contains the interface of the functions that must be implemented
* to allow the user access to the file system and the files. IT CANNOT BE
* MODIFIED.
*/
#define DEVICE_IMAGE disk.dat
#define DEVICE_SIZE (100*1024)
#define MAX_FILE_SIZE 1024
#define MAX_VERSION 10
/***************************/
/* File system management. */
/***************************/
/*
* Formats a device.
* Returns 0 if the operation was correct or -1 in case of error.
*/
int mkFS(int maxNumFiles);
/*
* Mounts a file system from the device deviceName.
* Returns 0 if the operation was correct or -1 in case of error.
*/
int mountFS();
/*
* Unmount file system.
* Returns 0 if the operation was correct or -1 in case of error.
*/
int umountFS();
/*******************/
/* File read/write */
/*******************/
/*
* Creates or opens a file.
* Returns file descriptor or -1 in case of error.
*/
int openFS(char *fileName);
/*
* Closes a file.
* Returns 0 if the operation was correct or -1 in case of error.
*/
int closeFS(int fileDescriptor);
/*
* Reads a number of bytes from a file and stores them in a buffer.
* Returns the number of bytes read or -1 in case of error.
*/
int readFS(int fileDescriptor, void *buffer, int numBytes, int *currentVersion);
/*
* Reads number of bytes from a buffer and writes them in a file.
* Update parameter newVersion with the number of the version created for this
* write. Exceeding the number of versions allowed is considered an error.
* Returns the number of bytes written or -1 in case of error.
*/
int writeFS(int fileDescriptor, void *buffer, int numBytes, int *newVersion);
/*
* Repositions the pointer of a file. A greater offset than the current size is
* considered an error. Returns new position or -1 in case of error.
*/
int lseekFS(int fileDescriptor, long offset, int whence);
/**********************/
/* Version management */
/**********************/
/*
* Changes current version of the file to the one specified as a parameter.
* Changing to a non-existent version is considered an error.
* Returns 0 if the operation was correct or -1 in case of error.
*/
int switchFS(char *fileName, int version);
/*
* Deletes specified version from a file's list of versions. Updates current
* version if necessary. Trying to delete a non-existent version is considered
* an error. Returns 0 if the operation was correct or -1 in case of error.
*/
int deleteFS(char *filename, int version);
#endif
|
C
|
#include "sem_com.h"//信号量,pv以及各种库
/**老师好,我的想法是: 2个程序
创建2个共享内存(shmid1,shmid2)
shmid1: A 用来写数据 B 用来读数据
shmid2: A 用来读数据 B 用来写数据
通过 p v 操作 和 sleep() 实现互斥 A先写,B再读,接着B写,A再读
循环下去 -->直到一方输入 over 双方程序结束
*/
int main (){
int sem_id;//信号量标识符
//获取信号量
sem_id = getsem();
//对信号量初始化
init_sem(sem_id,0);
char buff1[1024];//缓冲区1
char buff2[1024];//缓冲区2
int shmid1,shmid2;//共享内存标识符
char* shm_addr1;//映射共享内存1
char* shm_addr2;//映射共享内存2
//创建共享内存--shmid为共享内存标识符
shmid1 = shmget(ftok(".",'a'),1024,0666);//1写
//映射共享内存
shm_addr1 = shmat(shmid1,0,0);
//创建共享内存--shmid为共享内存标识符
shmid2 = shmget(ftok(".",'b'),1024,0666);//2读
//映射共享内存
shm_addr2 = shmat(shmid2,0,0);
while(1){
/**----------------发送数据---------start-----*/
/**写*/memset(buff1,0,1024);//清空缓冲区
printf("请您输入:\n");
if(fgets(buff1,1023,stdin)<0)
perror("fgets");
strncpy(shm_addr1,buff1,sizeof(buff1));//2共享内存复制到shm_addr1
//判断内容
if(strncmp(buff1,"over",4)==0){
//写入完毕,v操作,打开B的读取
sem_v(sem_id);
sleep(1);
printf("关闭聊天!\n");
break;
// exit(-1);
}else{
//写入完毕,v操作,打开B的读取
sem_v(sem_id);
sleep(1);//睡1秒,确保B能使用到资源
memset(buff1,0,1024);//清空缓冲区
}
/**----------------发送数据---------end-----*/
/**----------------接受数据---------start-----*/
sem_p(sem_id);//等待b读完释放资源
/**读*/memset(buff2,0,1024);//清空缓冲区
strncpy(buff2,shm_addr2,1024);//2共享内存复制到buff
//判断内容
if(strncmp(buff2,"over",4)==0){
printf("对方不想理你了,并关闭了聊天!\n");
// exit(-1);
break;
}else{
printf("小姐姐B对你说:\n%s",buff2);
memset(buff2,0,1024);//清空缓冲区
}
/**----------------接受数据---------end-----*/
}
/**----------------结束操作--------------*/
shmdt(shm_addr1);//解除映射
shmdt(shm_addr2);//解除映射
shmctl(shmid1,IPC_RMID,NULL);//删除共享内存
shmctl(shmid2,IPC_RMID,NULL);//删除共享内存
return 0;
}
|
C
|
/*
Copyright 2011 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: lode.vandevenne@gmail.com (Lode Vandevenne)
Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
*/
/*
Zopfli compressor program. It can output gzip-, zlib- or deflate-compatible
data. By default it creates a .gz file. This tool can only compress, not
decompress. Decompression can be done by any standard gzip, zlib or deflate
decompressor.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "deflate.h"
#include "gzip_container.h"
#include "zlib_container.h"
/* Windows workaround for stdout output. */
#if _WIN32
#include <fcntl.h>
#endif
/*
Loads a file into a memory array. Returns 1 on success, 0 if file doesn't exist
or couldn't be opened.
*/
static int LoadFile(const char* filename,
unsigned char** out, size_t* outsize) {
FILE* file;
*out = 0;
*outsize = 0;
file = fopen(filename, "rb");
if (!file) return 0;
fseek(file , 0 , SEEK_END);
*outsize = ftell(file);
if(*outsize > 2147483647) {
fprintf(stderr,"Files larger than 2GB are not supported.\n");
exit(EXIT_FAILURE);
}
rewind(file);
*out = (unsigned char*)malloc(*outsize);
if (*outsize && (*out)) {
size_t testsize = fread(*out, 1, *outsize, file);
if (testsize != *outsize) {
/* It could be a directory */
free(*out);
*out = 0;
*outsize = 0;
fclose(file);
return 0;
}
}
assert(!(*outsize) || out); /* If size is not zero, out must be allocated. */
fclose(file);
return 1;
}
/*
Saves a file from a memory array, overwriting the file if it existed.
*/
static void SaveFile(const char* filename,
const unsigned char* in, size_t insize) {
FILE* file = fopen(filename, "wb" );
if (file == NULL) {
fprintf(stderr,"Error: Cannot write to output file, terminating.\n");
exit (EXIT_FAILURE);
}
assert(file);
fwrite((char*)in, 1, insize, file);
fclose(file);
}
/*
outfilename: filename to write output to, or 0 to write to stdout instead
returns 1 on error
*/
static int CompressFile(const ZopfliOptions* options,
ZopfliFormat output_type,
const char* infilename,
const char* outfilename) {
unsigned char* in;
size_t insize;
unsigned char* out = 0;
size_t outsize = 0;
if (!LoadFile(infilename, &in, &insize)) {
fprintf(stderr, "Invalid filename: %s\n", infilename);
return 1;
}
ZopfliCompress(options, output_type, in, insize, &out, &outsize);
if (outfilename) {
SaveFile(outfilename, out, outsize);
} else {
#if _WIN32
/* Windows workaround for stdout output. */
_setmode(_fileno(stdout), _O_BINARY);
#endif
fwrite(out, 1, outsize, stdout);
}
free(out);
free(in);
return 0;
}
/*
Add two strings together. Size does not matter. Result must be freed.
*/
static char* AddStrings(const char* str1, const char* str2) {
size_t len = strlen(str1) + strlen(str2);
char* result = (char*)malloc(len + 1);
if (!result) exit(-1); /* Allocation failed. */
strcpy(result, str1);
strcat(result, str2);
return result;
}
static char StringsEqual(const char* str1, const char* str2) {
return strcmp(str1, str2) == 0;
}
int main(int argc, char* argv[]) {
ZopfliOptions options;
ZopfliFormat output_type = ZOPFLI_FORMAT_GZIP;
const char* filename = 0;
int output_to_stdout = 0;
int total_errors = 0;
int i;
ZopfliInitOptions(&options);
for (i = 1; i < argc; i++) {
const char* arg = argv[i];
if (StringsEqual(arg, "-v")) options.verbose = 1;
else if (StringsEqual(arg, "-c")) output_to_stdout = 1;
else if (StringsEqual(arg, "--deflate")) {
output_type = ZOPFLI_FORMAT_DEFLATE;
}
else if (StringsEqual(arg, "--zlib")) output_type = ZOPFLI_FORMAT_ZLIB;
else if (StringsEqual(arg, "--gzip")) output_type = ZOPFLI_FORMAT_GZIP;
else if (StringsEqual(arg, "--splitlast")) /* Ignore */;
else if (arg[0] == '-' && arg[1] == '-' && arg[2] == 'i'
&& arg[3] >= '0' && arg[3] <= '9') {
options.numiterations = atoi(arg + 3);
}
else if (StringsEqual(arg, "-h")) {
fprintf(stderr,
"Usage: zopfli [OPTION]... FILE...\n"
" -h gives this help\n"
" -c write the result on standard output, instead of disk"
" filename + '.gz'\n"
" -v verbose mode\n"
" --i# perform # iterations (default 15). More gives"
" more compression but is slower."
" Examples: --i10, --i50, --i1000\n");
fprintf(stderr,
" --gzip output to gzip format (default)\n"
" --zlib output to zlib format instead of gzip\n"
" --deflate output to deflate format instead of gzip\n"
" --splitlast ignored, left for backwards compatibility\n");
return 0;
}
}
if (options.numiterations < 1) {
fprintf(stderr, "Error: must have 1 or more iterations\n");
return 1;
}
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-') {
char* outfilename;
filename = argv[i];
if (output_to_stdout) {
outfilename = 0;
} else if (output_type == ZOPFLI_FORMAT_GZIP) {
outfilename = AddStrings(filename, ".gz");
} else if (output_type == ZOPFLI_FORMAT_ZLIB) {
outfilename = AddStrings(filename, ".zlib");
} else {
assert(output_type == ZOPFLI_FORMAT_DEFLATE);
outfilename = AddStrings(filename, ".deflate");
}
if (options.verbose && outfilename) {
fprintf(stderr, "Saving to: %s\n", outfilename);
}
total_errors += CompressFile(&options, output_type, filename, outfilename);
free(outfilename);
}
}
if (!filename) {
fprintf(stderr,
"Please provide filename\nFor help, type: %s -h\n", argv[0]);
return 1;
}
return total_errors > 255 ? 255 : total_errors;
}
|
C
|
#include<stdio.h>
int main()
{
int n,m;
scanf("%d%d",&n,&m);
if(m>n)
{
printf("%d",-1);
return 0;
}
if(n%2==0)
mid=n/2;
else
mid=(n/2)+1;
printf("%d",-1);
return 0;
}
|
C
|
/*************************************************************************
> File Name: sum_pipe.c
> Author: sudingquan
> Mail: 1151015256@qq.com
> Created Time: 四 7/ 4 18:06:58 2019
************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
int main() {
pid_t pid;
int fd[2];
int x = 0;
long long sum = 0;
if (pipe(fd) < 0) {
printf("Create pipe error\n");
exit(1);
}
for (int i = 0; i < 10; i++) {
pid = fork();
if (pid == 0) {
x = i;
break;
}
}
if (pid == 0) {
close(fd[0]);
for (int i = 1; i <= 100000; i++) {
sum += i + x * 100000;
}
printf("child process %d : %lld\n", x, sum);
write(fd[1], &sum, sizeof(sum));
close(fd[1]);
} else if(pid > 0) {
close(fd[1]);
for (int i = 1; i <= 10; i++) {
long long p;
read(fd[0], &p, sizeof(p));
sum += p;
printf("main process %d loop : %lld\n", i, sum);
}
close(fd[0]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i, j;
returnSize = NULL;
for (i = 0; i < numsSize && nums[i] < target; i++) {
for (j = i+1; j < numsSize; j++)
if (nums[i] + nums[j] == target) {
returnSize = (int *)malloc(2*sizeof(int));
returnSize[0] = i;
returnSize[1] = j;
return returnSize;
}
}
return returnSize;
}
int main(int argc, char **argv)
{
int array[] = {2, 11, 10, 8};
int *result;
result = twoSum(array, sizeof(array)/sizeof(array[0]), 10, result);
if (result) {
printf("result[0]=%d, result[1]=%d\n", result[0], result[1]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include<conio.h>
#include <string.h>
int main()
{
char s[100];
int count=0,i;
clrscr();
printf("\n Write the integers:");
scanf("%[^\n]s",s);
for(i=0;s[i]>0;i++)
{
if(s[i]=='0'||s[i]=='1'||s[i]=='2'||s[i]=='3'||s[i]=='4'||s[i]=='5'||s[i]=='6'||s[i]=='7'||s[i]=='8'||s[i]=='9')
count++;
}
printf("\n Number of integers are: %d",count);
getch();
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int number=14;
void* func1(void* args)
{
while(number!=0)
{
sleep(1);
number--;
printf("%d %d\n",(int)args,number);
}
return NULL;
}
int main()
{
pthread_t tid1,tid2,tid3;
pthread_create(&tid1,NULL,&func1,(void*)111);
pthread_create(&tid2,NULL,&func1,(void*)222);
pthread_create(&tid2,NULL,&func1,(void*)333);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <sys/time.h>
struct timeval start, end;
////gcc -pthread -o main c.c
void tensorproduct(int **matriz1, int **matriz2, int linhas1, int linhas2,
int cols1, int cols2)
{
FILE *out = fopen("tensor_mlaj.out", "w");
int linhaTensorial = linhas1 * linhas2;
int colunaTensorial = cols1 * cols2;
int tensorMatriz[linhaTensorial][colunaTensorial];
int a, b, c, d;
for (int a = 0; a < linhas1; a++) {
for (int c = 0; c < linhas2; c++) {
for (int b = 0; b < cols1; b++) {
for (int d = 0; d < cols2; d++) {
tensorMatriz[a + d + 1][b + c + 1] = matriz1[a][b] * matriz2[c][d];
//printf("%d\t", tensorMatriz[a + d + 1][b + c + 1]);
fprintf (out, "%d\t", tensorMatriz[a + d + 1][b + c + 1]);
}
}
fprintf(out, "\n");
}
}
gettimeofday(&end, NULL);
double time_taken = end.tv_sec + end.tv_usec / 1e6 - start.tv_sec - start.tv_usec / 1e6; // in seconds
fprintf(out, "\nTempo gasto: %f .", time_taken);
fclose(out);
}
int **lermatriz(size_t *linhas, size_t *colunas, const char *nomearquivo)
{
*linhas = 0;
*colunas = 0;
FILE *fp = fopen(nomearquivo, "r");
//(2) se algum dos arquivos de entrada não existir ou não puder ser aberto,
if(fp == NULL)
{
fprintf(stderr, "Erro ao abrir arquivo %s: %s\n", nomearquivo, strerror(errno));
return NULL;
}
int **matriz = NULL, **tmp;
char line[1024];
while(fgets(line, sizeof line, fp))
{
if(*colunas == 0)
{
// Determinar o numero de colunas através da primeira linha
char *scan = line;
int valor;
int offset = 0;
while(sscanf(scan, "%d%n", &valor, &offset) == 1)
{
scan += offset;
(*colunas)++;
}
}
tmp = realloc(matriz, (*linhas + 1) * sizeof *matriz);
if(tmp == NULL)
{
fclose(fp);
return matriz;
}
matriz = tmp;
matriz[*linhas] = calloc(*colunas, sizeof *matriz[*linhas]);
if(matriz[*linhas] == NULL)
{
fclose(fp);
if(*linhas == 0)
{
fprintf(stderr, "\nFalha na leitura do arquivo.\n");
fclose(fp);
free(matriz);
return NULL;
}
return matriz;
}
int offset = 0;
char *scan = line;
for(size_t j = 0; j < *colunas; ++j)
{
if(sscanf(scan, "%d%n", matriz[*linhas] + j, &offset) == 1)
scan += offset;
else
matriz[*linhas][j] = 0;
}
(*linhas)++;
}
fclose(fp);
return matriz;
}
int main(int argc, char * argv[])
{
gettimeofday(&start, NULL);
/*
O programa não deve falhar se encontrar um erro, precisando checar todos os parâmetros antes
de aceita-los. Assim, seu programa deve apresentar um mensagem de erro coerente e encerrar
a execução quando:
*/
//(1) um número incorreto de argumento para os comando tensor for passado,
if((argv[3] != NULL) || (argv[2] == NULL) || (argv[1] == NULL)){
fprintf(stderr, "Erro: número incorreto de argumentos passados.\n");
return 0;
}
size_t cols1, linhas1, cols2, linhas2;
int **matriz1 = lermatriz(&linhas1, &cols1, argv[1]);
int **matriz2 = lermatriz(&linhas2, &cols2, argv[2]);
tensorproduct(matriz1, matriz2, linhas1, linhas2, cols1, cols2);
// Liberando a matriz 1
for(size_t i = 0; i < linhas1; ++i){
free(matriz1[i]);
}
// Liberando a matriz 2
for(size_t i = 0; i < linhas2; ++i){
free(matriz2[i]);
}
free(matriz1);
free(matriz2);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void MTC(float a){
int result;
result = a*100;
printf("%f metros equivalem a %d centimetros", a,Result);
break;
}
int main(){
float numemmetro;
scanf("%f", &numemmetro);
MTC(numemmetro);
return 0;
}
|
C
|
/**
* generate.c
*
* Computer Science 50
* Problem Set 3
*
* Generates pseudorandom numbers in [0,LIMIT), one per line.
*
* Usage: generate n [s]
*
* where n is number of pseudorandom numbers to print
* and s is an optional seed
*/
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LIMIT 65536
int main(int argc, string argv[])
{
// Checks for the Correctioness of the Command line arguments.
if (argc != 2 && argc != 3)
{
printf("Usage: ./generate n [s]\n");
return 1;
}
// Converting the string argv[1] to an integer
int n = atoi(argv[1]);
/* If seed is given, call srand function by passing the seed
else seed the srand with the number of seconds */
if (argc == 3)
{
srand((unsigned int) atoi(argv[2]));
}
else
{
srand((unsigned int) time(NULL));
}
// Prints the Random number within the specified limits.
for (int i = 0; i < n; i++)
{
printf("%i\n", rand() % LIMIT);
}
// that's all folks
return 0;
}
|
C
|
//
// Created by ruben on 8-9-18.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define DEFAULT_PORT 2012
#define BUFFER_SIZE 2048
int setup_socket(int port){
int fd,err;
struct sockaddr_in addr;
fd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if (fd<0) {
perror("Couln't create socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
err = bind(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
if (err<0) {
perror("Couln't bind to socket");
exit(1);
}
return fd;
}
int main(){
int fd, msg_length,sent_length, counter;
char buff[BUFFER_SIZE];
struct sockaddr_in from;
socklen_t from_len;
fd = setup_socket(DEFAULT_PORT);
from_len = sizeof(from);
printf("LISTENING ON PORT %d\n",DEFAULT_PORT);
counter = 1;
while(1){
msg_length = recvfrom(fd, &buff, BUFFER_SIZE, 0,(struct sockaddr *) &from, &from_len);
if(msg_length<0){
perror("Error retrieving bytes from UDP packet");
exit(1);
}
counter++;
if(counter%2==0){
printf("Received %d bytes from host %s port %d: %s\n", msg_length, inet_ntoa(from.sin_addr), ntohs(from.sin_port), buff);
}else{
printf("DROPPING PACKET OF %d bytes from host %s port %d: %s\n", msg_length, inet_ntoa(from.sin_addr), ntohs(from.sin_port), buff);
continue;
}
sent_length = sendto(fd, buff, msg_length, 0, (struct sockaddr *) &from, from_len);
if(sent_length!=msg_length){
perror("Did not sent the same amount of bytes as received");
exit(1);
}
}
}
|
C
|
#include <stdio.h>
long long int Fibonacci_Loop(int number_count);
int main(void)
{
int number_order;
printf("This program can calculate the Fibonacci array.\n");
printf("Now enter the order number of the Fibonacci:(q to quit)\n");
while (1 == scanf("%d", &number_order))
{
printf("Now the number of your order is %lld\n", Fibonacci_Loop(number_order));
printf("Please enter the order number again(q to quit):\n");
}
printf("Bye~.\n");
return 0;
}
long long int Fibonacci_Loop(int number_count)
{
long long int number_1 = 1, number_2 = 1;
long long result = 1;
if (number_count <= 2)
return result;
else
{
for (int i = 3; i < number_count; ++i) {
// 如果是偶数的话更新number_2 如果是基数的话更新number_1
if (i % 2 == 0)
number_2 = number_1 + number_2;
else
number_1 = number_2 + number_1;
}
}
result = number_2 + number_1;
return result;
}
|
C
|
# include <stdlib.h>
# include <stdio.h>
# include "prime_serial.h"
int main ( void );
void prime_number_sweep ( int n_lo, int n_hi, int n_factor );
/******************************************************************************/
int main ( void )
/******************************************************************************/
/*
Purpose:
MAIN is the main program for PRIME_SERIAL_PRB.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
06 August 2009
Author:
John Burkardt
*/
{
int n_factor;
int n_hi;
int n_lo;
timestamp ( );
printf ( "\n" );
printf ( "PRIME_SERIAL_PRB\n" );
printf ( " C version\n" );
n_lo = 1;
n_hi = 131072;
n_factor = 2;
prime_number_sweep ( n_lo, n_hi, n_factor );
n_lo = 5;
n_hi = 500000;
n_factor = 10;
prime_number_sweep ( n_lo, n_hi, n_factor );
/*
Terminate.
*/
printf ( "\n" );
printf ( "PRIME_SERIAL_PRB\n" );
printf ( " Normal end of execution.\n" );
printf ( "\n" );
timestamp ( );
return 0;
}
/******************************************************************************/
void prime_number_sweep ( int n_lo, int n_hi, int n_factor )
/******************************************************************************/
/*
Purpose:
PRIME_NUMBER_SWEEP does repeated calls to PRIME_NUMBER.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
06 August 2009
Author:
John Burkardt
Parameters:
Input, int N_LO, the first value of N.
Input, int N_HI, the last value of N.
Input, int N_FACTOR, the factor by which to increase N after
each iteration.
*/
{
int i;
int n;
int primes;
double ctime;
printf ( "\n" );
printf ( "TEST01\n" );
printf ( " Call PRIME_NUMBER to count the primes from 1 to N.\n" );
printf ( "\n" );
printf ( " N Pi Time\n" );
printf ( "\n" );
n = n_lo;
while ( n <= n_hi )
{
ctime = cpu_time ( );
primes = prime_number ( n );
ctime = cpu_time ( ) - ctime;
printf ( " %8d %8d %14f\n", n, primes, ctime );
n = n * n_factor;
}
return;
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define FIFONAME "fifo01"
#define BUFSIZE 4096
int main(int argc, char *argv[])
{
if(argc == 2)
{
//sender
int fifofd;
if(mkfifo(FIFONAME, 0777) == -1)
{
//can't create fifo
fifofd=open(FIFONAME, O_WRONLY);
if(fifofd == -1)
{
printf("Error: can't create fifo\n");
return -1;
}
close (fifofd);
remove(FIFONAME);
mkfifo(FIFONAME, 0777);
}
fifofd=open(FIFONAME, O_WRONLY);
if(fifofd == -1)
{
//error open
printf("Error: can't open fifo\n");
}
int filefd, read_amount;
char buf[BUFSIZE];
filefd=open(argv[1], O_RDONLY);
if(filefd == -1)
{
//error open
printf("Error: can't open file\n");
}
read_amount=read(filefd, &buf, BUFSIZE );
while(read_amount>0)
{
write(fifofd, &buf, read_amount);
read_amount=read(filefd, &buf, BUFSIZE);
}
close(fifofd);
return 0;
}
else if(argc == 1)
{
//reciever
int fifofd;
do
{
fifofd=open(FIFONAME, O_RDONLY);
} while(fifofd == -1);
char buf[BUFSIZE];
int i, read_amount;
read_amount=read(fifofd, &buf, BUFSIZE); while(read_amount>0)
{
write(1, &buf, read_amount);
read_amount = read(fifofd, &buf, BUFSIZE);
}
close(fifofd);
remove(FIFONAME);
return 0;
}
return 0;
}
|
C
|
#include <Python.h>
#include "structmember.h"
typedef struct{
PyObject_HEAD
float radius;
} Volume;
static void Volume_dealloc(Volume* self){
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject * Volume_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
Volume *self;
self = (Volume *)type->tp_alloc(type, 0);
if (self != NULL) {
self->radius = 0;
}
return (PyObject *)self;
}
static int Volume_init(Volume *self, PyObject *args, PyObject *kwds)
{
if (! PyArg_ParseTuple(args, "f", &self->radius))
return -1;
return 0;
}
static PyMemberDef Volume_members[] = {
{"radius", T_INT, offsetof(Volume, radius), 0, "sphere radius"},
{NULL}
};
static PyObject * Volume_getVolume(Volume* self)
{
return Py_BuildValue("f", 4/3 * 3.14159265358979323846*(pow(self->radius, 3)));
}
static PyMethodDef Volume_methods[] = {
{"getVolume", (PyCFunction)Volume_getVolume, METH_NOARGS, "Returns sphere volume"},
{NULL}
};
static PyObject* Volume_str(Volume* self){
return PyUnicode_FromFormat("(%f)", self->radius);
}
static PyTypeObject volumeType ={
PyVarObject_HEAD_INIT(NULL, 0)
"Volumes.Volume", /*tp_name*/
sizeof(Volume), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor) Volume_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
(reprfunc) Volume_str, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Spheres volume: consists of 1 float value radius", /* tp_doc */
0,
0,
0,
0,
0,
0,
Volume_methods,
Volume_members,
0,
0,
0,
0,
0,
0,
(initproc)Volume_init,
0,
Volume_new,
};
static struct PyModuleDef Volumes ={
PyModuleDef_HEAD_INIT,
"Volumes", // name of module
"Contains 1 class: Volume", // module documentation, may be NULL
-1, // size of per- interpreter state of the module, or -1 if the module keeps state in global variables.
NULL, NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_Volumes (void){
PyObject* m;
if (PyType_Ready(&volumeType)< 0)
return NULL;
m = PyModule_Create(&Volumes);
if (m == NULL)
return NULL;
Py_INCREF(&volumeType);
PyModule_AddObject(m, "Volume", (PyObject*)&volumeType);
return m;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** NWP_myteams_2019
** File description:
** functions_file
*/
#include "server.h"
#include "functions.h"
void append_infile(char *path, int nb_line, const char *str)
{
FILE *file = fopen(path, "r");
FILE *f_temp = fopen("replace.txt", "w");
char buffer[5024];
int count = 0;
while ((fgets(buffer, 5024, file)) != NULL) {
count++;
if (count == nb_line && strcmp(buffer, "\n") != 0) {
buffer[strlen(buffer)-1] = 0;
fprintf(f_temp, "%s;%s\n", buffer, str);
} else if (count == nb_line && !strcmp(buffer, "\n")) {
buffer[strlen(buffer)-1] = 0;
fprintf(f_temp, "%s\n", str);
} else
fputs(buffer, f_temp);
}
fclose(file);
fclose(f_temp);
remove(path);
rename("replace.txt", path);
}
bool check_occurence(char *path, int nb_line, char *occ)
{
FILE *file = fopen(USER_FILE, "r+");
char line[2024];
char **user = NULL;
int count = 0;
int len = 0;
for (int i = 0; fgets(line, sizeof(line), file);) {
i++;
if (i == nb_line) {
user = split_str_client(line, user, &len);
for (int i = 0; i != len; i++) {
if (!strcmp(user[i], occ)) {
fclose(file);
free_array(user, len);
return true;
}
}
}
}
fclose(file);
return false;
}
|
C
|
/* Author: Murali K
* email: muralik.msr@gmail.com
* Date: 2 Apr 2013
*/
#include "extended_euclid.h"
int modular_inverse(int a, int m) {
struct result r = extended_gcd(a, m);
if(r.g != 1) {
printf("\nERROR: No modular inverse!!!\n");
exit(0);
}
return r.x%m;
}
|
C
|
/**
* Sagi Dayan 2014 (c) - Use At Your Own Risk! v1.0
*
* For Ex1 - In "Computer Communication Applications" Course
*
*
* If This Tester Is Giving You Compiling Errors For Functions That I Used
* And Are Not Defined In The Blue Print Header File - Let Me Know!
* I Wrote It (the Tester) For My Own Use.
*
*
* sagidayan@gmail.com
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "GenericHashTable.h"
#define _info(msg) printf("[ INFO ]\t%s\n", msg)
#define _fail(msg) printf("[\x1B[31m ERROR \x1B[0m]\t%s\n", msg)
#define _pass(msg) printf("[\x1B[32m *PASSED* \x1B[0m]\t%s\n", msg)
#define _title(msg) printf("\t*******************\n");\
printf("\t %s\n", msg);\
printf("\t*******************\n\n");
void intTest();
void strTest();
void pointerTest();
void exTest();
void holdOn(char *);
int clean_stdin()
{
while (getchar() != '\n');
return 1;
}
int main(int argc, char const *argv[])
{
//_debug("Starting...");
int input;
menu:
printf("\x1B[32m _____ _ _ _ \n");
printf("| | |___ ___| |_ | |_ ___ ___| |_ \n");
printf("| | .'|_ -| | | _| -_|_ -| _|\n");
printf("|__|__|__,|___|_|_| |_| |___|___|_| \x1B[0m\n");
printf("\n\n%s\n", "Please select your test of choice: ");
printf("\t1. Integer Table Test\n");
printf("\t%s\n", "2. String Table Test");
printf("\t%s\n", "3. Pointer Validation Test (encapsulation test)");
printf("\t%s\n", "4. Extreme Case Test" );
printf("\t%s\n", "5. Exit" );
while ((scanf("%d", &input) != 1 && clean_stdin()) || input > 5 || input < 1 )
{
printf("%s\n", "Invalid menu item. please pick again.");
}
switch (input)
{
case 1:
intTest();
break;
case 2:
strTest();
break;
case 3:
pointerTest();
break;
case 4:
exTest();
break;
default:
printf("\t\t \x1b[34mThank You For Using FuckingTester (c) 2014 Sagi Dayan\x1B[0m\n\n\n\n");
return 0;
}
printf("%s\n", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
goto menu;
return 0;
}
/**
* Tests all integet Shit...
* it will add data, remove data - multiply the array - and check your hashing.
*/
void intTest()
{
_title("Integer Table Test");
int arr[20];
Table *tbl = createTable(2, INT_TYPE, 2);
int i;
for (i = 0; i < 20; i++)
arr[i] = i;
printTable(tbl);
_info("Addint one int");
add(tbl, &arr[0]);
_info("Added\n");
printTable(tbl);
if (search(tbl, &arr[0]) == NULL)
_fail("integer is not beeing plased in the right place!");
else
_pass("One element is right");
_info("Atempting to remove the one object within the table...");
if (removeObj(tbl, &arr[0]) != 0)
_fail("Not right index return from removeObjet() function");
else
_pass("removeObject() func returns the right index");
holdOn("Press Any Key To Continue...");
_info("Filling table for multiply... 4 items\n");
for (i = 0; i < 4; ++i)
add(tbl, &arr[i]);
printTable(tbl);
holdOn("Continue ? ...");
_info("Adding alot more: ");
for (; i < 20; ++i)
add(tbl, &arr[i]);
printTable(tbl);
_info("Now Cheacking If Data Is In The Right Place");
if (removeObj(tbl, &arr[0]) == 0 && removeObj(tbl, &arr[19]) == 9 && removeObj(tbl, &arr[8]) == 2)
_pass("Cheacked 3 Out Of 20 Numbers - And They Are In The Right Place!");
else
_fail("Cheacked 3 Out Of 20 Numbers - And They Are NOT The Right Place!");
_info("Checking if removed the objects correctly");
if (removeObj(tbl, &arr[0]) == -1 && removeObj(tbl, &arr[19]) == -1 && removeObj(tbl, &arr[8]) == -1)
_pass("Removed Successfully");
else
_fail("Something is wrong with removeObj() function");
holdOn("End Of Test");
freeTable(tbl);
tbl = NULL;
}
void strTest()
{
Table *tbl = createTable(3, STR_TYPE, 3);
int i;
if (tbl == NULL)
{
_fail("Table Was Not Created Successfully...");
_info("Cant continue The Test.. Aborting..");
holdOn("Press Any Key To Go To Menu");
}
_title("String Table Test");
holdOn("Press Any Key To Continue");
_info("Created a string table of size 3 and list length of 3");
printTable(tbl);
char *arr[5] = {"One", "Tow", "Tree", "pinnes", "boobs"};
/**
* First Test
*/
_info("Trying to add the string \"One\" to the array... needs to go to index 2");
add(tbl, arr[0]);
printTable(tbl);
if (removeObj(tbl, arr[0]) != 2)
_fail("Index Is not right - check removeObj() OR add()");
else
_pass("Nice Job");
holdOn("Press Any Key To Continue");
/**
* Second test
*/
_info("Adding to table 5 strings...");
for ( i = 0; i < 5; ++i)
add(tbl, arr[i]);
_info("Added. Your Array looks like this: ");
printTable(tbl);
_info("The String \"boobs\" should be in index 5");
if (removeObj(tbl, arr[4]) != 5)
_fail("Index Is not right - check removeObj() OR add()");
else
_pass("Nice Job");
holdOn("Press Any Key To Continue");
freeTable(tbl);
holdOn("Done with String Test...");
}
void pointerTest()
{
_title("Pointer Test");
_title("INTEGER:");
_info("creating table:");
Table *tbl = createTable(2, INT_TYPE, 1);
_info("done.");
int integer = 5, testInt = 5;
int *integerPtr = &integer;
int *testPtr = &testInt;
char *str = "test";
printTable(tbl);
_info("Addint the number 5 to table.");
add(tbl, integerPtr);
printTable(tbl);
_info("Changing value of that integer from the main.");
*integerPtr = 6;
printTable(tbl);
if (search(tbl, testPtr) == NULL)
_fail("User can change values of your objects from the main");
else
_pass("Nice worck with integer encapusalation!");
_info("Atempting to free the table");
freeTable(tbl);
tbl = NULL;
_info("done!");
holdOn("Press Any Key To Continue To char* Test");
_title("STRING: ");
_info("creating table");
tbl = createTable(2, STR_TYPE, 1);
_info("done.");
printTable(tbl);
_info("Adding string to table");
add(tbl, str);
printTable(tbl);
_info("Changing the string from the main.");
str = "test2";
printTable(tbl);
if (search(tbl, str) != NULL)
_fail("User can change values of your objects from the main");
else
_pass("Nice worck with String encapusalation!");
_info("Atempting to free the table");
_info("Now Cheacking If Data Is In The Right Place");
freeTable(tbl);
tbl = NULL;
_info("done!");
holdOn("Press Any key To Continue");
}
void exTest()
{
_title("Extreme Test");
_info("Trying to create a table with 0 as the list size...");
Table *tbl = createTable(1, INT_TYPE, 0);
Table *tbl2 = createTable(3, STR_TYPE, 2);
int answer;
char *arr[5] = {"One", "Tow", "Tree", "pinnes", "boobs"};
int arrInt[5];
int i;
for ( i = 0; i < 5; ++i)
arrInt[i] = i;
if (tbl != NULL)
_fail("You cannot create a table with listLength of 0.");
else
_pass("Good job, you made sure that user cannot do that!");
holdOn("To Continue press [Enter]");
_info("Trying to add a string to an Integer table: ");
tbl = createTable(2, INT_TYPE, 2);
add(tbl, arr[0]);
printTable(tbl);
printf("[ ?? ]Answer This: Look at the table, is the only element %d, and it is stored in %d? [y/n]\n", (int)(*(int *)arr[0]), removeObj(tbl, arr[0]));
answer = getchar();
if (answer == 'y' || answer == 'Y')
_pass("Nice Job handeling Strings in integer table!");
else
_fail("Somethig went wrong...");
holdOn("Coninue? ");
_info("Trying to add int to a string table");
add(tbl2, &arrInt[3]);
printTable(tbl2);
printf("[ ?? ]Answer This: Look at the table, is the only element %s, and it is stored in %d? [y/n]\n", (char *)&arrInt[3], removeObj(tbl2, &arrInt[3]));
answer = getchar();
if (answer == 'y' || answer == 'Y')
_pass("Nice Job handeling Strings in integer table!");
else
_fail("Something went wrong...");
freeTable(tbl2);
printf("\n\n\n");
_info("Trying to add NULL to integer table");
if (add(tbl, NULL) != -1)
_fail("You need to return -1 (from add() ) if there is a null pointer");
else
_pass("Nice job! - add returns -1 as expected!");
holdOn("Coninue? ");
freeTable(tbl);
holdOn("Done!");
}
void holdOn(char *msg)
{
printf("\n\n*** %s ***\n", msg);
clean_stdin();
getchar();
}
|
C
|
#include "lists.h"
/**
*listint_len -list
*@h:pointer
*Return:number element
*/
size_t listint_len(const listint_t *h)
{
int i;
for (i = 0; h != NULL; i++)
{
h = h->next;
}
return (i);
}
|
C
|
/* test code to illustrate use of Linux kernel container_of macro
*
* Copyright (c) 2008 Cliff Brake, BEC Systems LLC
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* This program illustrates how the container_of macro works.
* The container of macro is very useful in multi layered
* software systems where you have progressivly more detailed
* software layers. Below is an example of a bus layer,
* and then a device layer where a number of different
* devices might register with the bus.
* The device registers itself with the bus subsystem, and
* then the bus subsystem makes a callback into the device.
* Normally if there are multiple devices registered, the
* bus subsystem must store and pass a device structure
* when making callbacks. With the container_of macro, this is
* no longer necessary, and the bus subsystem only has to
* know about one generic device structure, and does not need visibility
* into lots of different device structures, or do tricks
* by casting void pointers, etc. With the container_of macro
* we can backcast from the generic data structure, to the containing
* datastructure. This forces good separation of code in that
* that bus layer cannot modifiy data structures that are specific
* to the device layer.
*
*/
/**
* (from Linux kernel source)
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
/*==========================================================
* BUS layer code
*==========================================================*/
/* generic bus device structure */
struct bus_device
{
int general_device_param_a;
int general_device_param_b;
void (*device_callback)(struct bus_device * bd);
};
/* the following is a global list of
* devices that have registered with the
* bus subsystem. Normally this would
* be something like a dynamic linked list.
*/
struct bus_device * bd_list[5];
/* function to register a device with the bus */
void register_with_bus(struct bus_device * bd)
{
/* since this example only deals with one
* device, will put it in slot 0
*/
bd_list[0] = bd;
}
void start_bus()
{
int i;
struct bus_device * bd;
/* make callbacks to all devices on bus */
for (i=0;i<sizeof(bd_list)/sizeof(bd_list[0]);i++) {
bd = bd_list[i];
if (!bd) continue;
/* call device callback with generic
* bus device structure
*/
bd->device_callback(bd);
}
}
/*==========================================================
* device X specific code
* this would normally be in a different module
*==========================================================*/
/* structure that holds device X specific stuff, as well as
* generic bus_device structure
*/
struct device_x
{
int device_x_specific_param_a;
int device_x_specific_param_b;
struct bus_device bd;
};
void device_x_callback(struct bus_device * bd)
{
/* if we know the structure type that contains the bus_device structure,
* we can extract a pointer to the containing structure using the container_of
* macro
*/
/* ptr type member */
struct device_x * devx = container_of(bd, struct device_x, bd);
/* the above statement expands to
* struct device_x * devx = (
* {
* const typeof( ((struct device_x *)0)->bd ) *__mptr = (bd);
* (struct device_x *)( (char *)__mptr - ((size_t) &((struct device_x *)0)->bd) );
* }
* );
*/
printf("device_x_callback called!, device_x_specific_param_a = %i\n",
devx->device_x_specific_param_a);
}
void device_x_init()
{
/* dynamically allocate structures */
struct device_x * devx = malloc(sizeof(*devx));
memset(devx, 0, sizeof(*devx));
/* set a parameter in the device_x structure so
* we can test for this in the callback
*/
devx->device_x_specific_param_a = 1001;
/* set up callback function */
devx->bd.device_callback = device_x_callback;
/* we register the generic bus device structure
* as the bus layer does not need to know
* about the device_x stucture. Note, the
* devx structure is not stored anywhere, yet
* its location is being preserved without
* specifically passing it to the bus
* layer.
*/
register_with_bus(&devx->bd);
}
int main()
{
/* test the above system */
/* first, initialize device_x */
device_x_init();
/* now, start the bus. This should make
* a callback into the device_x
*/
start_bus();
}
/* when run, this program returns:
* device_x_callback called!, device_x_specific_param_a = 1001
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
void five_digit_number_reverse() {
int number;
printf("Enter a five digit number \n");
scanf("%d", &number);
if (number < 10000 || number > 99999) {
printf("Didn't receive a five digit number, exiting...");
exit(1);
}
int rev = 0, remainder;
while (number > 0) {
remainder = number % 10;
rev = rev * 10 + remainder;
number /= 10;
}
printf("Reversed number is %d", rev);
}
void float_comparision() {
float num1, num2;
printf("Enter the first number\n");
scanf("%f", &num1);
printf("Enter the second number\n");
scanf("%f", &num2);
float larger = num1 > num2 ? num1 : num2;
printf("The larger number is %f", larger);
}
void number_operation_single_number() {
int num;
printf("Enter a number\n");
scanf("%d", &num);
if (num % 2 == 0) {
num /= 2;
} else {
num *= 3;
}
printf("Resulting number = %d", num);
}
void number_operation_three_equal() {
int a, b, c;
printf("Enter number one a \n");
scanf("%d", &a);
printf("Enter number one b \n");
scanf("%d", &b);
printf("Enter number one c \n");
scanf("%d", &c);
if (a == b || b == c || c == a) {
printf("One of the pair of the numbers are equal");
} else {
printf("None of these numbers are equal");
}
}
int main() {
int choice;
printf("Menu for Program, enter your choice\n");
printf("1. Reverse a 5 digit number \n");
printf("2. Compare two floats \n");
printf("3. Input a number and multiply it by 2 if is divisible by 2, "
"otherwise multiply it by 3\n");
printf("4. Determine if any of two of three numbers are equal \n");
scanf("%d", &choice);
switch (choice) {
case 1:
five_digit_number_reverse();
break;
case 2:
float_comparision();
break;
case 3:
number_operation_single_number();
break;
case 4:
number_operation_three_equal();
break;
default:
printf("You entered a wrong choice, exiting the program");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/**
* main - the primary function being ecexuted
* divide3 - returns Y if divisible by 3, returns N if not
* divide5 - returns Y if divisible by 5, returns N if not
* a blank line
* @current_number: the current number being counted, examined, and printed
* @current_number_converted: current number as a double
* @ticks: used to count qualifying factors of current number to/to not print
* @function_result: placeholder to recieve Y or N in main
*
*/
int divide3(double n)
{
int asInt;
float placeholder;
float placeholder_end;
int yes_no;
yes_no = 0;
placeholder = (n / 3);
asInt = (int)placeholder;
placeholder_end = placeholder - asInt;
printf("Result is %f\n", placeholder_end);
if (placeholder_end == 0.0f)
{
printf("Buzz");
yes_no = 1;
}
else
{
yes_no = 0;
}
return (yes_no);
}
int divide5(double n)
{
int asInt;
float placeholder;
float placeholder_end;
int yes_no;
yes_no = 0;
placeholder = (n / 3);
asInt = (int)placeholder;
placeholder_end = placeholder - asInt;
printf("Result is %f\n", placeholder_end);
if (placeholder_end == 0.0f)
{
printf("Fizz");
yes_no = 1; /** IS NOT DIVISIBLE */
} else
{
yes_no = 0;
}
return (yes_no);
}
int main(void)
{
int current_number;
float current_number_converted;
int ticks;
int function_result;
function_result = 0;
current_number = 453;
current_number_converted = current_number;
function_result = divide5(current_number_converted);
if (function_result = 0)
{
printf("It is divisible %d\n", function_result);
}
else if (function_result = 1)
{
printf("It is not! %d\n", function_result);
}
}
|
C
|
void intro_setup(int played, int finished) {
// the intro setuo and the menu apperance
// it displays if game is over
// of if you finshed the game
// and also displays the option to select the instructions
char *c;
char *intro_string;
intro_string = "A MarX Production Gaming Experience";
glColor3f(0.9, 0.0, 0.0);
glRasterPos2f(-0.35, -0.1);
for (c = intro_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glRasterPos2f(-0.35, -0.2);
intro_string = "Press the ENTER key to begin....";
for (c = intro_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glRasterPos2f(-0.9, -0.9);
intro_string = "Press M for Instructions";
for (c = intro_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
if ( played == 1) {
glColor3f(1.0, 1.0, 0.0);
glRasterPos2f(-0.30, -0.3);
intro_string = "Game Over.";
for (c = intro_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
}
if ( finished == 2) {
glColor3f(1.0, 1.0, 0.0);
glRasterPos2f(-0.3, -0.4);
intro_string = "You Finished The Game.";
for (c = intro_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glRasterPos2f(-0.3, -0.5);
intro_string = "CONGRATULATIONS!";
for (c = intro_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
}
glFlush();
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include<string.h>
int main()
{
char a[80],b[80];
int i,j,t;
printf("Enter 1st string\n");
gets(a);
fflush(stdin);
printf("Enter 2nd string\n");
gets(b);
printf("Common characters are :\n");
for(i=0;a[i]!='\0';i++)
{
for(j=i-1;j>=0;j--)
if(a[i]==a[j])
break;
if(j==-1)
for(t=0;b[t]!='\0';t++)
if(a[i]==b[t])
{
printf("%c",a[i]);
break;
}
}
getch();
return 0;
}
|
C
|
#include <math.h>
#include <stdio.h>
#include <string.h>
#define MAX_VALUE_STR 32
#define MAX_UNSIGNED_INT 4294967295
#define MAX_BIT_WIDTH 32
struct nt_info
{
char value_str[32];
unsigned int value;
int bit_width;
int range_start;
int range_end;
int type;
};
void nt_info_init(struct nt_info* nt_data)
{
nt_data->value_str[0]='\0';
nt_data->value=0;
nt_data->bit_width=32;
nt_data->range_start=0;
nt_data->range_end=31;
nt_data->type=0;
}
unsigned int power(double x, double y)
{
unsigned int total=1;
for (int i=0; i<y; i++)
{
total*=x;
}
return total;
}
unsigned int signed_int_to_unsigned(char*);
unsigned int str_to_unsigned_int(char*);
//error checking functions
int error_unsigned_bit_size(char* s)
{
int i; unsigned int m=1; unsigned int sum=0; int len; unsigned int x; char c;
len=strlen(s);
for (i=len-1; i>=0; i--)
{
if ((m==1000000000 && (s[i]>=53 || (s[i]==52 && sum>=294967296))))
{
return -1;
}
c=s[i];
x=((int)c)-48;
x*=m;
sum+=x;
m*=10;
}
return 1;
}
int error_check_input(char* s)
{
//binary
if (s[1]==98 && s[0]==48)
{
for (int i=2; i<strlen(s); i++)
{
if(s[i]!=48 && s[i]!=49)
{
printf("Error: %s contains characters other than 0 and 1\n", s);
return -1;
}
}
s+= 2;
if(strlen(s)>32)
{
printf("Error: %s cannot fit into 32 bits\n", s);
return -1;
}
return 2;
}
//hex
else if(s[1]==120 && s[0]==48)
{
for(int i=2; i<strlen(s); i++)
{
if((s[i]<48 || s[i]>57) && (s[i]<65 || s[i]>70))
{
printf("Error: %s contains characters other than 0-9 and A-F\n", s);
return -1;
}
}
s+= 2;
if(strlen(s)>8)
{
printf("Error: %s cannot fit into 32 bits\n", s);
return -1;
}
return 3;
}
//signed int
else if(s[0]==45)
{
for (int i=1; i<strlen(s); i++)
{
if(s[i]<48 || s[i]>57)
{
printf("Error: %s contains characters other than 0-9\n", s);
return -1;
}
}
if (strlen(s)>11)
{
printf("Error: %s cannot fit into 32 bits\n", s);
return -1;
}
unsigned int u=str_to_unsigned_int(s+1);
if (u>2147483648)
{
printf("Error: %s cannot fit into 32 bits\n", s);
return -1;
}
return 1;
}
//unsigned
else
{
for (int i=0; i<strlen(s); i++)
{
if(s[i]<48 || s[i]>57)
{
printf("Error: %s contains characters other than 0-9\n", s);
return -1;
}
}
if (strlen(s)>10)
{
printf("Error: %s cannot fit into 32 bits\n", s);
return -1;
}
if (error_unsigned_bit_size(s)==-1)
{
printf("Error: %s cannot fit into 32 bits\n", s);
return -1;
}
return 0;
}
}
int error_check_bit_width(int bit_width)
{
if (bit_width%4!=0)
{
printf("Error: Bit width must be a multiple of 4\n");
return -1;
}
if (bit_width<0 || bit_width>32)
{
printf("Error: Bit width must be between the range 0-32\n");
return -1;
}
}
int error_check_range(int start, int end)
{
if (start<0 || end>31)
{
printf("Error: Range must be between 0-32\n");
return -1;
}
if (start>end)
{
printf("Error: Range start must be larger than range end\n");
return -1;
}
}
int parse_command_line(int argc, char** argv, struct nt_info* nt_data)
{
char bit_wid[10]="-b";
char range[10]="-r";
for (int i=1; i<argc; i++)
{
if (strcmp(argv[i], bit_wid)==0)
{
i++;
int bit_width=str_to_unsigned_int(argv[i]);
if (error_check_bit_width(bit_width)!=-1)
{
nt_data->bit_width = bit_width;
}
else
return -1;
}
else if(strcmp(argv[i], range)==0)
{
i++;
char comma[2]=",";
char* s=argv[i];
char* r=strtok(s, comma);
int r_start=str_to_unsigned_int(r);
r=strtok(NULL, comma);
int r_end=str_to_unsigned_int(r);
if (error_check_range(r_start, r_end)!=-1)
{
nt_data->range_start=r_start;
nt_data->range_end=r_end;
}
else
return -1;
}
else
{
int check=error_check_input(argv[i]);
if (check!=-1)
{
strcpy(nt_data->value_str, argv[i]);
nt_data->type=check;
}
else
return -1;
}
}
}
//conversion functions
unsigned int str_to_unsigned_int(char* s)
{
int i; unsigned int m=1; unsigned int sum=0; int len; unsigned int x; char c;
len=strlen(s);
for (i=len-1; i>=0; i--)
{
c=s[i];
x=((int)c)-48;
x*=m;
sum+=x;
m*=10;
}
return sum;
}
unsigned int signed_int_to_unsigned(char* s)
{
int v;
unsigned int u;
s++;
v=str_to_unsigned_int(s);
v=v*-1;
u=(unsigned int)v;
return u;
}
unsigned int binary_to_unsigned(char* arg)
{
unsigned int num=0;
int tracker=0;
for (int i=strlen(arg)-1; i>=2; i--)
{
if(arg[i]==49)
num=num+power(2, tracker);
tracker++;
}
return num;
}
int str_to_hex(char s)
{
char* characters="0123456789ABCDEF";
//returns a pointer to the where s occurs in characters
char* p=strchr(characters, s);
//p minus characters then returns the index (or the numerical value of 0-F)
return p-characters;
}
unsigned int hex_to_unsigned(char* s)
{
int tracker=0;
unsigned int sum=0;
for (int i=strlen(s)-1; i>=2; i--)
{
int num=str_to_hex(s[i]);
sum+=(power(16, tracker)*num);
tracker++;
}
return sum;
}
void normalize_input_value(struct nt_info* nt_data)
{
switch(nt_data->type)
{
case 0:
nt_data->value=str_to_unsigned_int(nt_data->value_str);
break;
case 1:
nt_data->value=signed_int_to_unsigned(nt_data->value_str);
break;
case 2:
nt_data->value=binary_to_unsigned(nt_data->value_str);
break;
case 3:
nt_data->value=hex_to_unsigned(nt_data->value_str);
break;
}
}
//output conversions
void unsigned_to_computer_binary(unsigned int value, int bit_width, char* s)
{
s[bit_width]='\0';
for (int i=bit_width-1; i>=0; i--)
{
s[i]=(value%2)+'0';
value=value/2;
}
}
void unsigned_to_hex(unsigned int value, int bit_width, char* s)
{
//bit_width is divided by 4 because it holds 4 times the info as a bin bit
s[bit_width/4]='\0';
for (int i=(bit_width/4)-1; i>=0; i--)
{
if (value%16>=0 && value%16<=9)
{
s[i]=(value%16)+'0';
}
else
{
s[i]=((value%16)-10)+'A';
}
value=value/16;
}
}
void unsigned_to_str(unsigned int value, int bit_width, char* s)
{
if (bit_width<MAX_BIT_WIDTH)
value=value & (power(2, bit_width)-1);
else
value=value & MAX_UNSIGNED_INT;
s[10]='\0';
for (int i=9; i>=0; i--)
{
s[i]=(value%10)+'0';
value=value/10;
}
int i=0;
while (s[i]==48)
{
i++;
}
char* p=s+i;
if (s[i]=='\0')
strcpy(s, s+i-1);
else
strcpy(s, s+i);
}
void unsigned_to_signed(unsigned int value, int bit_width, char* s)
{
if (value>(power(2, bit_width-1)-1))
{
value=((~value)+1);
strcpy(s, "-");
}
else
strcpy(s, "");
char p[12];
unsigned_to_str(value, bit_width, p);
strcat(s, p);
}
void output_conversions(struct nt_info* nt_data)
{
//human binary output
char p[nt_data->bit_width+1];
unsigned_to_computer_binary(nt_data->value, nt_data->bit_width, p);
for (int i=0; i<nt_data->bit_width; i++)
{
if (i%4==0 && i!=0)
printf(" ");
printf("%c", p[i]);
}
printf(" (base 2)\n");
//computer binary
printf("0b%s (base 2)\n",p);
//hex
char h[(nt_data->bit_width/4)+1];
unsigned_to_hex(nt_data->value, nt_data->bit_width, h);
printf("0x%s (base 16)\n", h);
//unsigned
char u[11];
unsigned_to_str(nt_data->value, nt_data->bit_width, u);
printf("%s (base 10 unsigned)\n", u);
//signed
char sig[12];
unsigned_to_signed(nt_data->value, nt_data->bit_width, sig);
printf("%s (base 10 signed)\n", sig);
}
void range(struct nt_info* nt_data)
{
if (nt_data->range_start!=0 || nt_data->range_end!=31)
{
int len = (nt_data->range_end-nt_data->range_start)+1;
nt_data->value = nt_data->value >> nt_data->range_start;
nt_data->value = nt_data->value & ((1 << len)-1);
}
}
int main(int argc, char **argv)
{
if (argc<2)
printf("Not enough arguements\n");
else
{
struct nt_info nt_data;
nt_info_init(&nt_data);
if (parse_command_line(argc, argv, &nt_data)!=-1)
{
normalize_input_value(&nt_data);
range(&nt_data);
output_conversions(&nt_data);
}
}
return 0;
}
|
C
|
/* COMP2215 15/16: Task 02---MODELANSWER */
#include "pokedex.h"
#define PKMN_NO 9
#define SPRITE_SIZE 64
#define BG_COLOUR WHITE_SMOKE
#define FG_COLOUR BLACK
struct Pokemon *pkmn;
int8_t detail;
int8_t selected;
int8_t enc_delta(void);
volatile int8_t delta;
void format_string(char *fmt, va_list args, char *formatted_string);
void drawBorder(void) {
rectangle r = {6, display.width-7, 6, 12};
fill_rectangle(r, FG_COLOUR);
rectangle r2 = {6, display.width-7, display.height-13, display.height-7};
fill_rectangle(r2, FG_COLOUR);
rectangle r3 = {display.width-13, display.width-7, 6, display.height-7};
fill_rectangle(r3, FG_COLOUR);
rectangle r4 = {6, 12, 6, display.height-7};
fill_rectangle(r4, FG_COLOUR);
}
void printx(char *string, ...) {
printf(" ");
printf(string);
va_list args;
va_start(args, string);
vprintf(string, args);
va_end(args);
}
void drawSprite(char *a) {
printf("\n\n ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" \n");
display_color(FG_COLOUR, BG_COLOUR);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" ");
display_color(FG_COLOUR, WHITE);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" \n");
int i;
int8_t x;
display_color(FG_COLOUR, BG_COLOUR);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" ");
display_color(FG_COLOUR, WHITE);
printf(" ");
x = 0;
for (i = 0; i < SPRITE_SIZE; i++) {
if (x >= 8) {
display_color(FG_COLOUR, WHITE);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" ");
display_color(FG_COLOUR, BG_COLOUR);
printf("\n ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" ");
display_color(FG_COLOUR, WHITE);
printf(" ");
x = 0;
}
char tmp = a[i];
switch(tmp) {
case 'W' : display_color(FG_COLOUR, WHITE);
break;
case 'G' : display_color(FG_COLOUR, GREEN);
break;
case 'g' : display_color(FG_COLOUR, LIGHT_GREEN);
break;
case 'B' : display_color(FG_COLOUR, BLUE);
break;
case 'b' : display_color(FG_COLOUR, LIGHT_BLUE);
break;
case 'C' : display_color(FG_COLOUR, CYAN);
break;
case 'c' : display_color(FG_COLOUR, LIGHT_CYAN);
break;
case 'K' : display_color(FG_COLOUR, BLACK);
break;
case 'R' : display_color(FG_COLOUR, DARK_RED);
break;
case 'r' : display_color(FG_COLOUR, RED);
break;
case 'M' : display_color(FG_COLOUR, MAGENTA);
break;
case 'm' : display_color(FG_COLOUR, ORCHID);
break;
case 'k' : display_color(FG_COLOUR, BROWN);
break;
case 'Y' : display_color(FG_COLOUR, YELLOW);
break;
case 'O' : display_color(FG_COLOUR, ORANGE);
break;
case 'F' : display_color(FG_COLOUR, DARK_GRAY);
break;
case 'f' : display_color(FG_COLOUR, LIGHT_GRAY);
break;
case 'T' : display_color(FG_COLOUR, TURQUOISE);
break;
case 'o' : display_color(FG_COLOUR, GOLDENROD);
break;
case 'P' : display_color(FG_COLOUR, DARK_ORANGE);
break;
case 'w' : display_color(FG_COLOUR, CORNSILK);
break;
default : display_color(FG_COLOUR, WHITE);
break;
}
printf(" ");
x++;
}
display_color(FG_COLOUR, WHITE);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" \n");
display_color(FG_COLOUR, BG_COLOUR);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" ");
display_color(FG_COLOUR, WHITE);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" \n");
display_color(FG_COLOUR, BG_COLOUR);
printf(" ");
display_color(BG_COLOUR, FG_COLOUR);
printf(" \n");
}
void reset_screen(void) {
display.x = 0;
display.y = 0;
rectangle r = {13, display.width-14, 13, display.height-14};
fill_rectangle(r, display.background);
}
void draw(void) {
reset_screen();
display_color(FG_COLOUR, BG_COLOUR);
printf("\n\n\n");
rectangle r = {0, display.width-1, 0, display.height-1};
fill_rectangle(r, BG_COLOUR);
int8_t j = 0;
while (j < PKMN_NO) {
display_color(FG_COLOUR, BG_COLOUR);
printf(" ");
if (j == selected) {
display_color(BG_COLOUR, FG_COLOUR);
}
else {
display_color(FG_COLOUR, BG_COLOUR);
}
printf(pkmn[j].name); printf("\n");
j++;
}
drawBorder();
}
void showDetail(int number) {
reset_screen();
display_color(FG_COLOUR, BG_COLOUR);
rectangle r = {0, display.width-1, 0, display.height-1};
fill_rectangle(r, BG_COLOUR);
printf("\n\n\n");
if (number < 10) {
printf(" 00%d : ", pkmn[number].index);
}
else if (number < 100) {
printf(" 0%d : ", pkmn[number].index);
}
else {
printf(" %d : ", pkmn[number].index);
}
printf("%s\n", pkmn[number].name);
printf(" Height: %sm\n", pkmn[number].height);
printf(" Weight: %skg\n", pkmn[number].weight);
drawSprite(pkmn[number].sprite);
drawBorder();
}
void main(void) {
uint8_t cnt = MAX_STEP/2;
uint8_t i;
int16_t res;
init();
/* ENABLE GLOBAL INTERRUPTS HERE */
sei();
selected = 0;
detail = 0;
pkmn = loadPokemon();
draw();
for (;;) {
if (get_switch_short(_BV(SWC))) {
if (detail == 1) {
draw();
detail = 0;
}
else {
showDetail(selected);
detail = 1;
}
}
if (detail == 0) {
for (i=cnt; i > 0; --i) {
_delay_ms(STEP_DELAY_MS);
res = cnt + os_enc_delta();
if (res > cnt) {
cnt = MAX_STEP;
selected--;
while (selected < 0) {
selected += PKMN_NO;
}
draw();
}
else if (res < cnt) {
cnt = MIN_STEP;
selected = (selected+1)%PKMN_NO;
draw();
}
else {
cnt = res;
}
}
}
}
}
/* Configure I/O Ports */
void init(void) {
/* 8MHz clock, no prescaling (DS, p. 48) */
CLKPR = (1 << CLKPCE);
CLKPR = 0;
/* Configure I/O Ports */
/* ENABLE ENCODER INPUTS AND PULL-UPS */
DDRE |= _BV(PE4); /* ROTA input */
PORTE |= _BV(PE4); /* ROTA on */
DDRE |= _BV(PE5); /* ROTB input */
PORTE |= _BV(PE5); /* ROTB on */
DDRE &= ~_BV(SWC); /* Center button input */
PORTE |= _BV(SWC); /* Center button on */
/* Timer 0 for switch scan interrupt: */
TCCR0A = _BV(WGM01);
TCCR0B = _BV(CS01)
| _BV(CS00); /* F_CPU / 64 */
/* SET OCR0A FOR A 1 MS PERIOD */
const uint32_t ticksPerSec = F_CPU / 64;
OCR0A = ticksPerSec / 1000;
/* ENABLE TIMER INTERRUPT */
TIMSK0 |= _BV(OCIE0A);
init_lcd();
}
ISR( TIMER0_COMPA_vect ) {
static int8_t last;
int8_t new, diff;
uint8_t wheel;
/*
Scan rotary encoder
===================
This is adapted from Peter Dannegger's code available at:
http://www.mikrocontroller.net/articles/Drehgeber
*/
wheel = PINE;
new = 0;
if( wheel & _BV(PE4) ) new = 3;
if( wheel & _BV(PE5) )
new ^= 1;
diff = last - new;
if( diff & 1 ){
last = new;
delta += (diff & 2) - 1;
}
scan_switches(0);
}
|
C
|
void main()
{
int i,n,len,count=0;
char s[100];
scanf("%d",&n);
getchar();
while(n--)
{
gets(s);
len=strlen(s);
if((s[0]>='a'&&s[0]<='z')||(s[0]>='A'&&s[0]<='Z')||s[0]=='_')
{
if(len==1)
printf("1\n");
else if(len>1)
{
for(i=1;i<len;i++)
{
if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')||(s[i]=='_')||(s[i]>='0'&&s[i]<='9'))
{
count++;
}
}
if(count==len-1)
printf("1\n");
else printf("0\n");
}
}
else printf("0\n");
count=0;
}
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int basic_recursion(int, int);
int memoized_solution(int, int);
int tabular_solution(int, int);
#define N 5
#define K 3
int mem_table[N + 1][K + 1];
int tab_table[N + 1][K + 1];
int main()
{
printf("Basic Recursion: How many combinations of size %d are there in a set of size %d? %d\n", K, N, basic_recursion(N, K));
for (int i = 0; i <= N; ++i) {
mem_table[i][0] = 1;
for (int j = 1; j <= K; ++j){
mem_table[i][j] = 0;
}
}
printf("Memoized Solution: How many combinations of size %d are there in a set of size %d? %d\n", K, N, memoized_solution(N, K));
for (int i = 0; i <= N; ++i) {
tab_table[i][0] = 1;
if (i + 1 <= K) { tab_table[i][i + 1] = 0; }
}
printf("Tabular Solution: How many combinations of size %d are there in a set of size %d? %d\n", K, N, tabular_solution(N, K));
}
int basic_recursion(int n, int k)
{
if (n == k || k == 0) { return 1; }
if (k == 1) { return n; }
return basic_recursion(n - 1, k - 1) + basic_recursion(n - 1, k);
}
int memoized_solution(int n, int k)
{
if (n == k || k == 0) { return 1; }
if (k == 1) { return n; }
if (mem_table[n][k] > 0) { return mem_table[n][k]; }
mem_table[n][k] = memoized_solution(n - 1, k - 1) + memoized_solution(n - 1, k);
return mem_table[n][k];
}
int tabular_solution(int n, int k)
{
if (k == 0 || n == 0) { return tab_table[n][k]; }
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= i && j <= K; ++j) {
tab_table[i][j] = tab_table[i - 1][j - 1] + tab_table[i - 1][j];
}
}
return tab_table[n][k];
}
|
C
|
char *x="\";\nmain ()\n{ char *s;\n printf (\"char *x=\\\"\");\n for(s=x;*s;s++)\n { printf(*s=='\\\\'?\"\\\\\\\\\":*s=='\\\"'?\"\\\\\\\"\":*s=='\\n'?\"\\\\n\":\"%c\", *s); }\n printf (\"%s\", x);\n}\n";
main ()
{ char *s;
printf ("char *x=\"");
for(s=x;*s;s++)
{ printf (*s=='\\'?"\\\\":*s=='\"'?"\\\"":*s=='\n'?"\\n":"%c", *s); } printf ("%s", x);
}
|
C
|
#include<stdio.h>
void printTheArray(int arr[], int n){
for (int i = 0; i < n; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
void generateAllBinaryStrings(int n, int arr[], int i){
if (i == n){
printTheArray(arr, n);
return;
}
arr[i] = 0;
generateAllBinaryStrings(n, arr, i + 1);
arr[i] = 1;
generateAllBinaryStrings(n, arr, i + 1);
}
int main(){
int n = 4;
int arr[n];
generateAllBinaryStrings(n, arr, 0);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int a,b;
do {
printf("Nhap lan luot a,b: ");
scanf("%d%d", &a, &b);
} while ( a < 1 || b > 100000);
int max = (a>b) ? a : b; // toan tu ba ngoi thay cho lenh if else
// printf("%d", max);
int temp;
for (int i = max; i > 0; i--) {
if ( a % i == 0 && b % i == 0 ) {
temp = i;
break;
}
}
printf("%d/%d = %d/%d",a, b, a/temp, b/temp);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.