language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include<stdio.h>
void main()
{
int n,i,a,c=0;float s=0;
printf("enter n");
scanf("%d",&n);
printf("enter numbers");
for(i=1;i<=n;i++)
{
scanf("%d",&a);
if(a%2==0)
{
s=s+(a*i);
c=c+i;
}
}
s=s/c;
printf("the average weighted sum of even numbers=%.2f",s);
}
|
C
|
/* Fill in your Name and GNumber in the following two comment fields
* Name: Rushil Nandan Dubey
* GNumber: G01203932
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "clock.h"
#include "structs.h"
#include "constants.h"
/* Schedule Count
* - Return the number of Processes in the list.
*/
int schedule_count(Process *list) {
Process *walker=list;
int count=0;
//If the list is empty return 0.
if(list==NULL){
return 0;
}
//Keep on iterating the lsit till it will encounter a NULL and keep on incrementing the count.
while(walker!=NULL){
count++;
walker=walker->next;
}
/* Complete this Function */
return count;
}
/* Schedule Insert
* - Insert the Process into the List with the Following Constraints
* list is a pointer to the head pointer for a singly linked list.
* It may begin as NULL
* 1) Insert in the order of Ascending PIDs
* (eg. 1, 13, 14, 20, 32, 55)
* Remember to set list to the new head if it changes!
*/
void schedule_insert(Process **list, Process *node) {
Process *walker=*list;
//When insertion is done and the list is empty.
if(*list==NULL){
*list=node;
node->next= NULL;
}
//When insertion is done before the head and there is only one element in the list
else if(node->pid < (*list)->pid){
node->next=*list;
*list=node; //Head is updated gloabally
}
else{
while(walker != NULL){
//When insertion is done in between.
if(walker->next != NULL && walker->next->pid > node->pid && node->pid > walker->pid){
node->next = walker->next;
walker->next = node;
}
//When insertion is done at the end.
if(walker->next == NULL && node->pid >walker->pid){
walker->next=node;
node->next=NULL;
}
walker=walker->next;
}
}
return;
}
/* Schedule Terminate
* - Unallocate the Memory for the given Node
*/
void schedule_terminate(Process *node) {
free(node); //Free the memory of the given node.
return;
}
/* Schedule Generate
* - Allocate the Memory and Create the Process from the given Variables
* Remember to initialize all values, including next!
*/
Process *schedule_generate(const char *name, int pid, int time_remaining, int time_last_run) {
Process *new_node=malloc(sizeof(Process));
//If the memory has not been allocated to the new_node return NULL.
if(new_node == NULL){
return NULL;
}
strcpy(new_node->name,name);
new_node->pid=pid;
new_node->time_remaining = time_remaining;
new_node->time_last_run = time_last_run;
new_node->next=NULL;
/* Complete this Function */
return new_node;
}
/* Schedule Select
* - Select the next Process to be run using the following conditions:
* 1) The Process with the lowest time_remaining should run next.
* - If there are any ties, select the Process with the lowest PID
* 2) If there is a Process that has not run in >= TIME_STARVATION, then
* select that one instead.
* (Use the function clock_get_time() to get the current time)
* - If there are any ties, select the Process with the lowest PID
* 3) If the list is NULL, return NULL
* - Remove the selected Process from the list
* - Return the selected Process
*/
Process *schedule_select(Process **list) {
Process *walker=*list;
Process *temp=malloc(sizeof(Process)); //Allocate memory to the temporary node.
temp=*list;
//if the list is NULL return 0
if(*list==NULL){
return 0;
}
//Iterate the walker till it will encouter a null.
while(walker != NULL){
//When wait time of a process is greater than the starvation time then selection is done on the basis of this
if( (clock_get_time() - walker->time_last_run) >= TIME_STARVATION){
//When more than one processes are there in the starvation select the one with lowest pid.
if((clock_get_time() - temp->time_last_run) >= TIME_STARVATION){
if(temp->pid > walker->pid)
temp=walker;
}
else{
temp=walker;
}
}
//When no process is in the starvation state the selection is done on the basis of time remaining of the processes.
if( (clock_get_time() - temp->time_last_run) < TIME_STARVATION && (clock_get_time() - walker->time_last_run) < TIME_STARVATION){
//Select the process with lowest time remaining.
if(walker->time_remaining < temp->time_remaining){
temp=walker;
}
//If two or more processes have the same time remaining the selection is done on the bais of pid.
if(walker->time_remaining == temp->time_remaining){
//One with the lowest pid is selected.
if(temp->pid > walker->pid){
temp=walker;
}
}
}
//Increment the walker from one node to the other
walker=walker->next;
}
//Again assigning the walker to the head of that list, in order to remove the selected node.
walker=*list;
//Iterarte the walker till will encounter a NULL.
while(walker != NULL){
//When the selected node is the head node then update the head globally to the next node.
if((*list)->next !=NULL && temp == walker){
*list = (*list)->next;
break;
}
//When there is only one node in the list then update the list to NULL.
if((*list)->next == NULL && temp == walker){
*list=NULL;
break;
}
//When the selected node is somewhere in the middle of the node.
if(temp->next !=NULL && walker->next == temp){
walker->next=temp->next;
break;
}
//When the selected node is the last node of the list.
if(temp->next == NULL && walker->next == temp){
walker->next=NULL;
break;
}
//Increment the walker from one node to the other.
walker=walker->next;
}
//return the selcted node.
return temp;
}
|
C
|
#include "generic-list.h"
#include <assert.h>
#include <stdio.h>
typedef struct integ_list {
int size;
int *values;
node_t node;
} integ_list_t;
integ_list_t* integ_list_init()
{
integ_list_t *list = calloc(10, sizeof(integ_list_t));
if (!list)
return NULL;
list->values = calloc(2, sizeof(int));
list->size = 2;
if (!list->values)
return NULL;
return list;
}
void integ_list_destroy(integ_list_t *list)
{
free(list->values);
free(list);
}
GLIST_INIT(integ_list, integ_list_init, integ_list_destroy)
void print_integ_list(integ_list_t *list)
{
int i = 0;
printf("{ ");
for (; i < list->size - 1; i++)
printf("%d,", list->values[i]);
printf("%d }", list->values[i]);
}
void push_and_pop()
{
integ_list_t *l = integ_list_create();
l->values[0] = -1;
l->values[1] = -1;
for (int i = 0; i < 10; i++) {
integ_list_t *tmp_node = integ_list_create();
if (!tmp_node)
return;
tmp_node->values[0] = i;
l = integ_list_push(l, tmp_node);
}
assert (integ_list_get_size(l) == 11);
integ_list_print(l, print_integ_list);
for (int i = 0; i < 11; i++) {
l = integ_list_pop(l);
integ_list_print(l, print_integ_list);
}
assert (l == NULL);
assert (integ_list_get_size(l) == 0);
}
void insert_and_delete_front()
{
integ_list_t *new_node = NULL;
integ_list_t *l = integ_list_create();
l->values[0] = -1;
l->values[1] = -1;
for (int i = 0; i < 10; i++) {
new_node = integ_list_create();
new_node->values[0] = i;
l = integ_list_insert_at(l, new_node, 0);
}
integ_list_print(l, print_integ_list);
for (int i = 0; i < 10; i++) {
l = integ_list_delete_at(l, 0);
integ_list_print(l, print_integ_list);
}
integ_list_print(l, print_integ_list);
integ_list_erase(&l);
assert (l == NULL);
assert (integ_list_get_size(l) == 0);
}
void insert_delete_middle()
{
integ_list_t *new_node = NULL;
integ_list_t *l = integ_list_create();
l->values[0] = -1;
l->values[1] = -1;
new_node = integ_list_create();
new_node->values[0] = 0;
l = integ_list_push(l, new_node);
new_node = integ_list_create();
new_node->values[0] = 2;
l = integ_list_push(l, new_node);
new_node = integ_list_create();
new_node->values[0] = 1;
l = integ_list_insert_at(l, new_node, 2);
integ_list_print(l, print_integ_list);
l = integ_list_delete_at(l, 2);
integ_list_print(l, print_integ_list);
integ_list_erase(&l);
assert (l == NULL);
assert (integ_list_get_size(l) == 0);
}
int main(void)
{
push_and_pop();
insert_and_delete_front();
insert_delete_middle();
return 0;
}
|
C
|
#include "pila_estatica.h"
//Cmo saber calcular el espacio de mi pila y cunto llenarla. En este caso dijimos que es de 200 bytes en el define.
//TAM_PILA 200
//como nosotros declaramos que lo usaremos con una pila de enteros, esto indica que cada numero ocupa 4 bytes,
//pero ademas necesito otros 4 bytes para indicar que el elemento pesa eso (ver explicacion en la funcion poner_en_pila).
//por lo que se podria decir que "para cada entero necesitare 8 bytes", es decir 4 para el dato, y 4 para el tamao del
//dato. por tanto dividimos 200/8 = 25. Eso indica que podre guardar 25 numeros enteros.
//mas de eso, la pila me dira que esta lleno y no me dejara hacerlo
int main()
{
t_pila pila_enteros;
crear_pila(&pila_enteros);
int i;
//notar que solo me dejara llenar la pila hasta el entero 25. mas de eso me dira pila llena
for(i=0; i<10; i++)
{
if(!poner_en_pila(&pila_enteros, &i, sizeof(i)))
return 1;
}
int elem;
if(ver_tope(&pila_enteros, &elem, sizeof(elem)))
printf("el tope es %d\n", elem);
while(!pila_vacia(&pila_enteros))
{
sacar_de_pila(&pila_enteros, &elem, sizeof(elem));
printf("%d ", elem);
}
system("pause");
return 0;
}
|
C
|
#include <string.h>
#include <stdio.h>
#include "InputGenerator.h"
#include "ProfileTimer.h"
#if defined(WINDOWS_BUILD)
#include <stdlib.h>
#define MSBF16(x) (_byteswap_ushort(*((unsigned short const*)x)))
#define MSBF32(x) (_byteswap_ulong(*((unsigned long const*)x)))
#endif
#ifndef WINDOWS_BUILD
#if BYTE_ORDER == BIG_ENDIAN
#define MSBF16(x) (*(uint16_t const*__attribute((aligned(1))))x)
#define MSBF32(x) (*(uint32_t const*__attribute((aligned(1))))x)
#else
#define MSBF16(x) bswap16(*(uint16_t const*__attribute((aligned(1))))x)
#define MSBF32(x) bswap32(*(uint32_t const*__attribute((aligned(1))))x)
#endif
#endif
static int scanstr2(char const* tgt, const int64_t tgt_len, char const pat[2], int64_t len)
{
unsigned short head = MSBF16(pat), wind = MSBF16(tgt);
tgt += 2;
for (int64_t counter = 0; counter <= tgt_len - len; counter++)
{
if (wind == head)
return 1;
wind = (wind << 8) | tgt[0];
tgt++;
}
return 0;
}
static int scanstr3(char const* tgt, const int64_t tgt_len, char const pat[3], int64_t len)
{
unsigned int head = 0, wind = 0;
((char*)&head)[0] = pat[2];
((char*)&head)[1] = pat[1];
((char*)&head)[2] = pat[0];
((char*)&wind)[0] = tgt[2];
((char*)&wind)[1] = tgt[1];
((char*)&wind)[2] = tgt[0];
tgt += 3;
for (int64_t counter = 0; counter <= tgt_len - len; counter++)
{
if ((wind & 0x00FFFFFF) == head)
return 1;
wind = (wind << 8) | tgt[0];
tgt++;
}
return 0;
}
static int scanstr4(char const* tgt, const int64_t tgt_len, char const* pat, int64_t len)
{
unsigned int head = MSBF32(pat), wind = MSBF32(tgt);
tgt += 4;
for (int64_t counter = 0; counter <= tgt_len - len; counter++)
{
if (wind == head)
return 1;
wind = (wind << 8) | tgt[0];
tgt++;
}
return 0;
}
static int scanstrm(char const* tgt, const int64_t tgt_len, char const* pat, int64_t len)
{
unsigned int head = MSBF32(pat), wind = MSBF32(tgt);
tgt += 4;
pat += 4;
len -= 4;
for (int64_t counter = tgt_len - len + 4; counter >= 0; --counter)
{
if (wind == head && memcmp(tgt, pat, len) == 0)
return 1;
wind = (wind << 8) | tgt[0];
tgt++;
}
return 0;
}
int scanstr_ext(char const* tgt, int64_t tgt_len, char const* pat, const int64_t pat_len)
{
if (tgt_len < pat_len)
{
return 0;
}
else if (tgt_len == pat_len)
{
return memcmp(tgt, pat, tgt_len) == 0;
}
switch (pat_len)
{
case 0: return 1;
case 1: return strchr(tgt, *pat) != NULL;
case 2: return scanstr2(tgt, tgt_len, pat, 2);
case 3: return scanstr3(tgt, tgt_len, pat, 3);
case 4: return scanstr4(tgt, tgt_len, pat, 4);
default: return scanstrm(tgt, tgt_len, pat, pat_len);
}
}
_noinline_ void Run_strstr_Mischasan_Extended_test()
{
printf("Starting test %s ...", __FUNCTION__);
StartTimer();
size_t searchesMade = 0;
size_t foundCount = 0; // anti optimization
for (size_t repeatCount = 0; repeatCount < REPEAT_SAME_TEST_COUNT; repeatCount++)
for (size_t searchedIndex = 0; searchedIndex < uiSearchedStrCount; searchedIndex++)
{
for (size_t inputIndex = 0; inputIndex < uiInputStrCount; inputIndex++)
{
int testRes = scanstr_ext(sInputStrings[inputIndex].str, sInputStrings[inputIndex].len, sSearchedStrings[searchedIndex].str, sSearchedStrings[searchedIndex].len);
#ifdef _DEBUG
int debugstrstrRes = strstr(sInputStrings[inputIndex].str, sSearchedStrings[searchedIndex].str) != NULL;
if (testRes != debugstrstrRes)
{
testRes = scanstr_ext(sInputStrings[inputIndex].str, sInputStrings[inputIndex].len, sSearchedStrings[searchedIndex].str, sSearchedStrings[searchedIndex].len);
}
#endif
if (testRes != 0)
{
foundCount++;
}
searchesMade++;
}
}
double runtimeSec = EndTimer();
printf(" ... Done\n");
printf("Searches made %zu. Found the string %zu times. Seconds : %f\n\n", searchesMade, foundCount, (float)runtimeSec);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 100
#define MAX_ATTEMPTS 5
#define TRUE 1
#define FALSE 0
int getSecretNumber(int);
int getGuess(int);
int checkGuess(int, int);
int main(void) {
int secretNum;
int guess;
int attemptsRemaining = MAX_ATTEMPTS;
int gotIt = FALSE;
srand((unsigned)time(NULL));
secretNum = getSecretNumber(MAX_NUM);
printf("The guessing game!\nGuess a number between 1 and 100.\n\n");
while (attemptsRemaining > 0 && gotIt == FALSE) {
guess = getGuess(attemptsRemaining);
gotIt = checkGuess(guess, secretNum);
attemptsRemaining--;
}
if (gotIt)
printf("Congratulations!\n");
else {
printf("Sorry, you have no guesses remaining...\n");
printf("The secret number was %d\n", secretNum);
}
return 0;
}
int getSecretNumber(int maxNum) {
return rand() % maxNum + 1;
}
int getGuess(int attemptsRemaining) {
int guess;
printf("You have %d guesses remaining...\n", attemptsRemaining);
printf("Enter your guess: ");
scanf("%d", &guess);
return guess;
}
int checkGuess(int guess, int secretNum) {
if (guess < secretNum) {
printf("Your guess is too low...\n\n");
return FALSE;
}
else if (guess > secretNum) {
printf("Your guess is too high...\n\n");
return FALSE;
}
else {
printf("You got it!\n\n");
return TRUE;
}
}
|
C
|
// These two includes are here because streaming output was coded for the M2 (http://medesign.seas.upenn.edu/index.php/Guides/MaEvArM)
// For other systems, replace strcpy_P and m_usb_tx_char with strcpy and printf, or whatever is appropriate.
#include "m_general.h"
#include "m_usb.h"
#include "base64.h"
const char base64_err_str[] PROGMEM = "!BASE64!";
const char base64_chars[64] PROGMEM =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
inline char base64_char_from_byte (const uint8_t byte)
{
return pgm_read_byte (base64_chars + (byte & 0b00111111));
}
#ifdef BASE64_ENCODING
static void encode_triplet (const uint8_t *input, uint8_t *output)
{
// shove 6 bits of each input into the output bytes
// input: abcdefgh ijklmnop qrstuvwx
// output: 00abcdef 00ghijkl 00mnopqr 00stuvwx
output[0] = input[0] >> 2;
output[1] = ((input[0] << 4) & 0b00111111) | (input[1] >> 4);
output[2] = ((input[1] << 2) & 0b00111111) | (input[2] >> 6);
output[3] = input[2] & 0b00111111;
}
static void encode_doublet (const uint8_t *input, uint8_t *output)
{
// input: abcdefgh ijklmnop
// output: 00abcdef 00ghijkl 00mnop00 =
output[0] = input[0] >> 2;
output[1] = ((input[0] << 4) & 0b00111111) | (input[1] >> 4);
output[2] = (input[1] << 2) & 0b00111111;
}
static void encode_singlet (const uint8_t *input, uint8_t *output)
{
// input: abcdefgh
// output: 00abcdef 00gh0000 = =
output[0] = input[0] >> 2;
output[1] = (input[0] << 4) & 0b00111111;
}
#ifdef BASE64_STATIC
char base64_encoded_output[MAX_BASE64_LEN + 1];
void base64_encode (const uint8_t *input, const uint16_t len)
{
if (len > MAX_BASE64_BYTES)
{
strcpy_P (base64_encoded_output, base64_err_str);
return;
}
char *base64_output_ptr = base64_encoded_output;
// 3 bytes of input fit into 4 bytes of output
const uint16_t len_loops = len / 3;
for (uint16_t i = 0; i < len_loops; i++)
{
uint8_t output[4];
encode_triplet (input, output);
// output values are 0-63
for (int j = 0; j < 4; j++)
base64_output_ptr[j] = base64_char_from_byte (output[j]);
base64_output_ptr += 4;
input += 3;
}
// if the number of input bytes isn't divisible by 3, we need to pad the end
const uint8_t remainder = len % 3;
if (remainder == 1)
{
uint8_t output[2];
encode_singlet (input, output);
base64_output_ptr[0] = base64_char_from_byte(output[0]);
base64_output_ptr[1] = base64_char_from_byte(output[1]);
base64_output_ptr[2] = '=';
base64_output_ptr[3] = '=';
}
else if (remainder == 2)
{
uint8_t output[3];
encode_doublet (input, output);
base64_output_ptr[0] = base64_char_from_byte(output[0]);
base64_output_ptr[1] = base64_char_from_byte(output[1]);
base64_output_ptr[2] = base64_char_from_byte(output[2]);
base64_output_ptr[3] = '=';
}
base64_output_ptr[4] = '\0';
}
#endif
#ifdef BASE64_STREAMING
static uint8_t buffered_bytes = 0;
static uint8_t bytes[3];
void base64_begin_encode_stream (void)
{
buffered_bytes = 0;
}
void base64_encode_stream (const uint8_t *input, const uint16_t len)
{
if (len == 0)
return;
uint8_t output[4];
for (const uint8_t* offset = input; offset < input + len; offset++)
{
bytes[buffered_bytes] = *offset;
buffered_bytes++;
if (buffered_bytes == 3)
{
encode_triplet (bytes, output);
for (int j = 0; j < 4; j++)
m_usb_tx_char (base64_char_from_byte (output[j]));
buffered_bytes = 0;
}
}
}
void base64_end_encode_stream (void)
{
uint8_t output[3];
if (buffered_bytes == 2)
{
encode_doublet (bytes, output);
m_usb_tx_char (base64_char_from_byte (output[0]));
m_usb_tx_char (base64_char_from_byte (output[1]));
m_usb_tx_char (base64_char_from_byte (output[2]));
m_usb_tx_char ('=');
}
else if (buffered_bytes == 1)
{
encode_singlet (bytes, output);
m_usb_tx_char (base64_char_from_byte (output[0]));
m_usb_tx_char (base64_char_from_byte (output[1]));
m_usb_tx_char ('=');
m_usb_tx_char ('=');
}
buffered_bytes = 0;
}
#endif
#endif
#ifdef BASE64_DECODING
inline bool valid_char (const char c)
{
return (c >= '/' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '+';
}
inline uint8_t char_value(const char c)
{
if (c >= 'A' && c <= 'Z')
return c - 'A';
else if (c >= 'a' && c <= 'z')
return 26 + (c - 'a');
else if (c >= '0' && c <= '9')
return 52 + (c - '0');
else if (c == '+')
return 62;
else if (c == '/')
return 63;
else
return 0;
}
static void decode_4char (const char *input, uint8_t *output)
{
uint8_t in[4];
in[0] = char_value((uint8_t)input[0]);
in[1] = char_value((uint8_t)input[1]);
in[2] = char_value((uint8_t)input[2]);
in[3] = char_value((uint8_t)input[3]);
// restore the encoded bytes
// input: 00abcdef 00ghijkl 00mnopqr 00stuvwx
// output: abcdefgh ijklmnop qrstuvwx
output[0] = (in[0] << 2) | (in[1] >> 4);
output[1] = (in[1] << 4) | (in[2] >> 2);
output[2] = (in[2] << 6) | in[3];
}
static void decode_3char (const char *input, uint8_t *output)
{
uint8_t in[3];
in[0] = char_value((uint8_t)input[0]);
in[1] = char_value((uint8_t)input[1]);
in[2] = char_value((uint8_t)input[2]);
// input: 00abcdef 00ghijkl 00mnop00 =
// output: abcdefgh ijklmnop
output[0] = (in[0] << 2) | (in[1] >> 4);
output[1] = (in[1] << 4) | (in[2] >> 2);
}
static void decode_2char (const char *input, uint8_t *output)
{
uint8_t in[2];
in[0] = char_value((uint8_t)input[0]);
in[1] = char_value((uint8_t)input[1]);
// input: 00abcdef 00gh0000 = =
// output: abcdefgh
output[0] = (in[0] << 2) | (in[1] >> 4);
}
static void decode_4char (const char *input, uint8_t *output)
{
const uint8_t *in = (const uint8_t*)input; // cast to unsigned to avoid signedness issues when bitshifting
// restore the encoded bytes
// input: 00abcdef 00ghijkl 00mnopqr 00stuvwx
// output: abcdefgh ijklmnop qrstuvwx
output[0] = (in[0] << 2) | (in[1] >> 4);
output[1] = (in[1] << 4) | (in[2] >> 2);
output[2] = (in[2] << 6) | in[3];
}
static void decode_3char (const char *input, uint8_t *output)
{
const uint8_t *in = (const uint8_t*)input; // cast to unsigned to avoid signedness issues when bitshifting
// input: 00abcdef 00ghijkl 00mnop00 =
// output: abcdefgh ijklmnop
output[0] = (in[0] << 2) | (in[1] >> 4);
output[1] = (in[1] << 4) | (in[2] >> 2);
}
static void decode_2char (const char *input, uint8_t *output)
{
const uint8_t *in = (const uint8_t*)input; // cast to unsigned to avoid signedness issues when bitshifting
// input: 00abcdef 00gh0000 = =
// output: abcdefgh
output[0] = (in[0] << 2) | (in[1] >> 4);
}
#ifdef BASE64_STATIC
uint8_t base64_decoded_output[MAX_BASE64_BYTES];
void base64_decode (const char *base64str, uint16_t *len)
{
char buffer[4];
uint8_t buffer_idx = 0;
*len = 0;
while (*base64str && valid_char(*base64str) && *len < MAX_BASE64_BYTES - 3)
{
buffer[buffer_idx++] = *(base64str++);
if (buffer_idx >= 4)
{
decode_4char (buffer, &base64_decoded_output[*len]);
buffer_idx = 0;
*len += 3;
}
}
switch (buffer_idx)
{
case 1: // there should never be only a single character left in the buffer
base64_decoded_output[*len] = '!';
(*len)++;
break;
case 2:
decode_2char(buffer, &base64_decoded_output[*len]);
(*len)++;
break;
case 3:
decode_3char(buffer, &base64_decoded_output[*len]);
(*len) += 2;
break;
}
}
#endif
#ifdef BASE64_STREAMING
static char decode_buffer[4];
static uint8_t decode_buffer_idx = 0;
void base64_begin_decode_stream (void)
{
decode_buffer_idx = 0;
}
bool base64_decode_stream (uint8_t **output, const char input)
{
if (!valid_char (input))
{ // end of the stream
switch (decode_buffer_idx)
{
// there should never be only a single character left in the buffer
case 2:
decode_2char(decode_buffer, *output);
(*output) += 1;
break;
case 3:
decode_3char(decode_buffer, *output);
(*output) += 2;
break;
}
return false;
}
decode_buffer[decode_buffer_idx] = input;
decode_buffer_idx++;
if (decode_buffer_idx >= 4)
{
decode_4char (decode_buffer, *output);
decode_buffer_idx = 0;
(*output) += 3;
}
return true;
}
#endif
#endif
|
C
|
struct Point
{
int x;
int y;
};
Point *Point__init(Point *self, int x, int y)
{
self->x = x;
self->y = y;
}
Point *Point__create(int x, int y)
{
Point *result = (*Point) malloc(sizeof(Point));
Point__init(result, x, y);
return result;
}
void Point__reset(Point *self) {}
void Point__destroy(Point *point)
{
if (point)
{
Point__reset(point);
free(point);
}
}
int *Point__x(Point *self)
{
return self->x;
}
int *Point__y(Point *self)
{
self->y;
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int ages[] = {23, 43, 12, 89, 2};
char *name[] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
int count = sizeof(ages) / sizeof(int);
int i = 0;
for(i = count-1; i >= 0; i--) {
printf("%s has age %d \n",
name[i], ages[i]);
}
printf("-----\n");
int *cur_age = ages;
char **cur_name = name;
for(i = count-1; i >= 0; i--) {
printf("%s has age %d \n",
*(cur_name+i), *(cur_age+i));
printf("%s has age %d \n",
*(name+i), *(ages+i));
}
printf("-----\n");
for(i = count-1; i >= 0; i--) {
printf("%s has age %d \n",
cur_name[i], cur_age[i]);
}
printf("-----\n");
return 0;
}
|
C
|
../caseG/g.c
|
C
|
/*
* os.c
*
* Created on: Feb 12, 2020
* Author: Tim Buckley
*/
#include "osDef.h"
void TIM2_IRQ_Handler2(void)
{
HAL_TIM_IRQHandler(OS_Timer);
}
void OS_Init(TIM_HandleTypeDef* thisTimer)
{
__disable_irq();
OS_Timer = thisTimer;
OS_ThreadCreate("IDLE", OS_Idle, OS_PRIORITY_NONE, OS_IdleStack, OS_MIN_STACK_SIZE);
OS_SetupVectorTable();
}
void OS_Run(void)
{
/*Change the vector offset table to Ram so it can be set dynamically*/
SCB->VTOR = (uint32_t)&OS_VectorTable;
__DSB();
/*Get The highest priority Thread*/
OS_Next = OS_GetHighestPriorityThread();
OS_Current = OS_Next;
/*Start the Timer OS timer*/
HAL_TIM_Base_Start_IT(OS_Timer);
/*Start the OS*/
OS_Start();
}
static void OS_Idle(void)
{
while(1)
{
__WFI();
}
}
static void OS_Done(void)
{
OS_Kill();
}
static void OS_SetupVectorTable(void)
{
for(uint16_t i = 0; i < OS_VECTOR_TABLE_SIZE; i++)
{
OS_VectorTable[i] = isr_vector[i];
}
OS_VectorTable[16 + TIM2_IRQn] = (uint32_t)&TIM2_IRQ_Handler2;
}
static void OS_Sched(void)
{
OS_Thread_t* thisOsThread;
uint32_t workingMask;
/*If no thread is ready then run the idle Thread*/
if(OS_ReadyMask == 0U)
{
OS_Next = &OS_IdleThread;
}
else
{
/*Assign the Next task to highest Priority*/
OS_Next = OS_GetHighestPriorityThread();
/*Increment any thread-that-should-be-running's readySkip counter*/
workingMask = OS_ReadyMask;
while(workingMask != 0U)
{
thisOsThread = &OS_Threads[LOG2(workingMask) - 1];
if(thisOsThread == OS_Next)
{
/*For the thread about to be executed set its readySkip counter to 0*/
thisOsThread->readySkips = 0;
}
else
{
/*Increment any other threads readySkip counter*/
thisOsThread->readySkips++;
}
workingMask &= ~(1U << thisOsThread->id);
}
}
/*If the current thread is not the highest priority the trigger the PENDSV Handler to switch to it*/
if(OS_Next != OS_Current)
{
*(uint32_t volatile*)0xE000ED04 = (1U << 28);
}
}
static OS_Thread_t* OS_GetHighestPriorityThread(void)
{
OS_Thread_t* thisOsThread, *priorityThread = &OS_IdleThread;
uint32_t workingMask = OS_ReadyMask, priorityScore = 0;
/*Determine which is the highest priority thread*/
while(workingMask != 0U)
{
thisOsThread = &OS_Threads[LOG2(workingMask) - 1];
if(OS_CalculatePriorityScore(thisOsThread) > priorityScore)
{
priorityThread = thisOsThread;
priorityScore = OS_CalculatePriorityScore(thisOsThread);
}
workingMask &= ~(1U << thisOsThread->id);
}
return priorityThread;
}
static OS_Thread_t* OS_FindAvailableThread(void)
{
uint8_t i = 0;
while((i != OS_MAX_THREADS) && (OS_Threads[i].active))
{
i++;
}
if(i >= OS_MAX_THREADS)
{
return NULL;
}
OS_Threads[i].id = i;
return &OS_Threads[i];
}
static uint32_t OS_CalculatePriorityScore(OS_Thread_t* thisOsThread)
{
return (thisOsThread->readySkips + 1)*(uint32_t)thisOsThread->priority;
}
static void OS_Tick(void)
{
OS_Thread_t* thisOsThread;
uint32_t bit, workingMask = OS_DelayMask;
while(workingMask != 0U)
{
thisOsThread = &OS_Threads[LOG2(workingMask) - 1];
bit = 1U << thisOsThread->id;
thisOsThread->delay--;
if(thisOsThread->delay == 0U)
{
OS_DelayMask &= ~bit;
thisOsThread->semaphores = NULL;
OS_SetThreadActive(thisOsThread);
}
workingMask &= ~bit;
}
OS_TickCounter++;
}
static void OS_SetThreadActive(OS_Thread_t *waitingThread)
{
OS_Thread_t * eventThread;
OS_ReadyMask |= 1U << waitingThread->id;
/*Clear all the other waitingThreadMask of waitingThread id.*/
while(waitingThread->threadMask != 0)
{
eventThread = &OS_Threads[LOG2(waitingThread->threadMask) - 1];
eventThread->waitingThreadMask &= ~(1U << waitingThread->id);
waitingThread->threadMask &= ~(1U << eventThread->id);
}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
/*If the timer is the OS Timer*/
if(htim == OS_Timer)
{
/*Call the OS tick Handler*/
OS_Tick();
/*Check to see if a new task is ready.*/
OS_Sched();
}
}
extern int errno;
caddr_t _sbrk(int incr)
{
extern char end asm("_heap");
static char *heap_end;
char *prev_heap_end;
if (heap_end == 0)
heap_end = &end;
prev_heap_end = heap_end;
if (heap_end + incr > (char*)0x20018000)
{
errno = ENOMEM;
return (caddr_t) -1;
}
heap_end += incr;
return (caddr_t) prev_heap_end;
}
__attribute__ ((naked)) static void OS_Start(void)
{
__asm volatile("ldr r0, =0xE000ED08"); /* Use the NVIC offset register to locate the stack. */
__asm volatile("ldr r0, [r0]");
__asm volatile("ldr r0, [r0]");
__asm volatile("msr msp, r0"); /* Set the msp back to the start of the stack. */
__asm volatile("mov r0, #0"); /* Clear the bit that indicates the FPU is in use, see comment above. */
__asm volatile("msr control, r0");
__asm volatile("cpsie i"); /* Globally enable interrupts. */
__asm volatile("svc 0"); /* System call to start first task. */
__asm volatile("nop");
}
__attribute__ ((naked)) void SVC_Handler(void)
{
__asm volatile("ldr r3, =OS_Next"); /*Get OS_Next->sp and store in R3*/
__asm volatile("ldr r3, [r3, #0]");
__asm volatile("ldr r0, [r3, #0]"); /*Set R0 to OS_Next->sp(the new process Stack Pointer)*/
__asm volatile("ldmia r0!, {r4-r11, lr}");/*Pop R4-R11 from the new process stack and update R0*/
__asm volatile("vldmia r0!, {s16-s31}"); /*Pop S16-S11 from the new process stack and update R0*/
__asm volatile("msr psp, r0"); /*Load the value of R0(the new process stack Pointer) into PSP*/
__asm volatile("mov r0, #0"); /*Clear the BASEPRI register*/
__asm volatile("msr basepri, r0");
__asm volatile("bx lr");
}
__attribute__ ((naked)) void PendSV_Handler(void)
{
__asm volatile("mrs r0, psp"); /*Get the process stack Pointer store in R0*/
__asm volatile("isb"); /*Clear Pipe*/
__asm volatile("vstmdb r0!, {s16-s31}"); /*Push S16-S31 onto the stack with update of R0 to last stack address*/
__asm volatile("stmdb r0!, {r4-r11, lr}");/*Push R4-R11 onto the stack with update of R0 to last stack address*/
__asm volatile("ldr r3, =OS_Current"); /*Update the currentProcess stack Pointer with the address of R0*/
__asm volatile("ldr r3, [r3, #0]");
__asm volatile("str r0, [r3, #0]");
__asm volatile("ldr r3, =OS_Next"); /*Set OS_Current to OS_Next*/
__asm volatile("ldr r3, [r3, #0]");
__asm volatile("ldr r2, =OS_Current");
__asm volatile("str r3, [r2, #0]");
__asm volatile("ldr r0, [r3, #0]"); /*Set R0 to OS_Next->sp(the new process Stack Pointer)*/
__asm volatile("ldmia r0!, {r4-r11, lr}");/*Pop R4-R11 from the new process stack and update R0*/
__asm volatile("vldmia r0!, {s16-s31}"); /*Pop S16-S11 from the new process stack and update R0*/
__asm volatile("msr psp, r0"); /*Load the value of R0(the new process stack Pointer) into PSP*/
__asm volatile("isb"); /*Clear Pipe*/
__asm volatile("bx lr"); /*return from interrupt with value in LR(0xFFFFFFED)*/
}
//////////////////////////////
/*System Calls*/
//////////////////////////////
int OS_ThreadCreate(const char* name, OS_ThreadHandler_t threadMain, OS_Priority_e priority, void *stack, uint32_t stackSize)
{
uint32_t* sp;
OS_Thread_t* thisOsThread;
if(priority == OS_PRIORITY_NONE)
{
thisOsThread = &OS_IdleThread;
}
else
{
thisOsThread = OS_FindAvailableThread();
if(!thisOsThread)
{
return -1;
}
}
/*Assign the name to the string for it to be referenced*/
strcpy(thisOsThread->name, name);
/*Determine the top of the stack*/
thisOsThread->stack = stack;
sp = (uint32_t*)((((uint32_t)thisOsThread->stack + stackSize*4 + 1U) / 8) * 8);
/*Initialise The Stack*/
*(--sp) = 0x00000000U;
*(--sp) = (1U << 24); /*FPSCR*/
sp -= 0x10; /*S15 - S0*/
*(--sp) = (1U << 24); /*xPSR*/
*(--sp) = (uint32_t)(threadMain); /*PC*/
*(--sp) = (uint32_t)(OS_Done); /*LR*/
sp--; /*R12*/
sp -= 0x04; /*R3 - R0*/
sp -= 0x10; /*S31- S16*/
*(--sp) = 0xFFFFFFEDU; /*LR*/
sp--; /*R11*/
if(priority == OS_PRIORITY_NONE)
{
*(--sp) = 0x00000000U; /*R10*/
}
else
{
*(--sp) = (uint32_t)(void*)OS_Current->gotTable;/*R10*/
}
sp -= 0x06; /*R9- R4*/
/*Assign the struct variables*/
thisOsThread->sp = sp;
thisOsThread->priority = priority;
thisOsThread->main = threadMain;
thisOsThread->active = true;
if(priority != OS_PRIORITY_NONE)
{
thisOsThread->parentThread = OS_Current;
OS_ReadyMask |= 1U << thisOsThread->id;
}
return 0;
}
int OS_ThreadImageCreate(const OS_Image_t *image)
{
uint32_t* sp;
OS_Thread_t* thisOsThread;
thisOsThread = OS_FindAvailableThread();
if(!thisOsThread)
{
return -1;
}
/*Assign the name to the string for it to be referenced*/
strcpy(thisOsThread->name, image->name);
/*Allocate memory for the GOT Table.*/
thisOsThread->gotTable = malloc(image->gotSize);
/*Allocate memory for the ram of the Thread*/
thisOsThread->ram = malloc((image->ramSize + image->bssSize));
/*Initialise the Ram from the image*/
for(uint32_t i = 0; i < image->ramSize; i++)
{
thisOsThread->ram[i] = image->ram[i];
}
for(uint32_t i = 0; i < image->bssSize; i++)
{
thisOsThread->ram[image->ramSize + i] = 0;
}
/*Allocate memory for the stack of the thread*/
thisOsThread->stack = malloc(image->stackSize*sizeof(uint32_t));
for(uint32_t i = 0; i < image->gotSize/sizeof(uint32_t); i++)
{
if(image->got[i] < FLASH_BASE)
{
thisOsThread->gotTable[i] = image->got[i] + (uint32_t)(void*)thisOsThread->ram;
}
else
{
thisOsThread->gotTable[i] = image->got[i];
}
}
/*Determine the top of the stack*/
sp = (uint32_t*)((((uint32_t)thisOsThread->stack + image->stackSize*4 + 1U) / 8) * 8);
/*Initialise The Stack*/
*(--sp) = 0x00000000U;
*(--sp) = (1U << 24); /*FPSCR*/
sp -= 0x10; /*S15 - S0*/
*(--sp) = (1U << 24); /*xPSR*/
*(--sp) = (uint32_t)(image->main); /*PC*/
*(--sp) = (uint32_t)(OS_Done); /*LR*/
sp--; /*R12*/
sp -= 0x04; /*R3 - R0*/
sp -= 0x10; /*S31- S16*/
*(--sp) = 0xFFFFFFEDU; /*LR*/
sp--; /*R11*/
*(--sp) = (uint32_t)(void*)thisOsThread->gotTable;/*R10*/
sp -= 0x06; /*R9- R4*/
/*Assign the struct variables*/
thisOsThread->sp = sp;
thisOsThread->priority = image->priority;
thisOsThread->main = image->main;
thisOsThread->active = true;
OS_ReadyMask |= 1U << thisOsThread->id;
return 0;
}
void OS_Delay(uint32_t delay)
{
uint32_t bit;
__disable_irq();
OS_Current->delay = delay;
bit = 1U << OS_Current->id;
OS_ReadyMask &= ~bit;
OS_DelayMask |= bit;
OS_Sched();
__enable_irq();
}
OS_Semaphore_t OS_CreateSemaphore(const char *name, int num, ...)
{
va_list marker;
OS_Semaphore_t semaphore;
uint32_t event;
semaphore.thread = OS_GetThreadByName(name);
semaphore.events = 0;
va_start(marker, num);
for(int i = 0; i < num; i++)
{
event = va_arg(marker, uint32_t);
semaphore.events |= 1U << event;
}
va_end(marker);
return semaphore;
}
void OS_SetSemaphore(uint32_t event)
{
OS_Thread_t *waitingThread;
uint32_t workingMask = OS_Current->waitingThreadMask;
__disable_irq();
/*Loop through all the threads that are waiting for an event from this thread.*/
while(workingMask != 0)
{
waitingThread = &OS_Threads[LOG2(workingMask) - 1];
for(uint8_t i = 0; i < waitingThread->numSemaphores; i++)
{
if(waitingThread->semaphores[i].thread->id == OS_Current->id)
{
if((1U << event) & waitingThread->semaphores[i].events)
{
waitingThread->semaphores[i].triggered = event;
waitingThread->semaphores = &waitingThread->semaphores[i];
OS_SetThreadActive(waitingThread);
}
break;
}
}
workingMask &= ~(1U << waitingThread->id);
}
__enable_irq();
}
void OS_WaitSemaphores(uint8_t num, OS_Semaphore_t *semaphores, uint32_t timeout)
{
__disable_irq();
OS_Current->semaphores = semaphores;
OS_Current->numSemaphores = num;
if(timeout != OS_NO_TIMEOUT)
{
OS_Current->delay = timeout;
OS_DelayMask |= 1U << OS_Current->id;
}
OS_Current->threadMask = 0;
for(uint8_t i = 0; i < num; i++)
{
semaphores[i].triggered = OS_NO_EVENT;
semaphores[i].thread->waitingThreadMask |= 1U << OS_Current->id;
OS_Current->threadMask |= (1U << semaphores[i].thread->id);
}
/*Clear the ready mask of this thread.*/
OS_ReadyMask &= ~(1U << OS_Current->id);
/*Call the scheduler.*/
OS_Sched();
__enable_irq();
}
OS_Thread_t* OS_GetThreadByName(const char *name)
{
uint32_t threadTrack = 0;
while((strcmp(OS_Threads[threadTrack].name, name) != 0) && (threadTrack < OS_MAX_THREADS))
{
threadTrack++;
}
if(threadTrack < OS_MAX_THREADS)
{
return &OS_Threads[threadTrack];
}
return NULL;
}
bool OS_TriggeredThread(const char *name)
{
if(strcmp(OS_Current->semaphores->thread->name, name) == 0)
{
return true;
}
return false;
}
uint8_t OS_TriggeredEvent(void)
{
return OS_Current->semaphores->triggered;
}
void OS_SetThreadData(void *data)
{
OS_Current->channelData = data;
}
void *OS_GetThreadData(void)
{
return OS_Current->semaphores->thread->channelData;
}
void OS_SetInterrupt(OS_ThreadHandler_t interruptHandler, IRQn_Type interrupt)
{
OS_VectorTable[interrupt + 16] = (uint32_t)interruptHandler;
}
void OS_KillThread(const char *name)
{
OS_Thread_t* thisOsThread = OS_GetThreadByName(name);
if(thisOsThread->parentThread != OS_Current)
{
return;
}
thisOsThread->active = false;
if(thisOsThread->ram)
free(thisOsThread->ram);
if(thisOsThread->gotTable)
free(thisOsThread->gotTable);
if(thisOsThread->stack)
free(thisOsThread->stack);
OS_ReadyMask &= ~(1U << thisOsThread->id);
OS_DelayMask &= ~(1U << thisOsThread->id);
}
void OS_Kill(void)
{
OS_Current->active = false;
if(OS_Current->ram)
free(OS_Current->ram);
if(OS_Current->gotTable)
free(OS_Current->gotTable);
if(OS_Current->stack)
free(OS_Current->stack);
OS_ReadyMask &= ~(1U << OS_Current->id);
OS_DelayMask &= ~(1U << OS_Current->id);
OS_Sched();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ast_build.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jubalest <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/01/21 18:08:12 by jubalest #+# #+# */
/* Updated: 2016/01/21 18:08:13 by jubalest ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "../libft/includes/libft.h"
#include "../includes/minishell.h"
int is_operand(char *s, int i)
{
if (s[i] == '|' && s[i + 1] != '&')
return (1);
if (s[i] == '|' && s[i + 1] == '&')
return (11);
if (s[i] == '>')
{
if (s[i - 1] == '>')
return (2);
if (s[i + 1] && s[i + 1] != '&')
return (3);
}
if (s[i] == '<')
{
if (s[i - 1] == '<')
return (4);
return (5);
}
return (0);
}
void find_operand(char *input, int *tuple)
{
size_t len;
int ret;
tuple[0] = -1;
tuple[1] = -1;
if (!input)
return ;
len = ft_strlen(input) - 1;
while (len)
{
ret = is_operand(input, (int)len);
if (ret)
{
tuple[0] = ret;
tuple[1] = (int)len;
break ;
}
len--;
}
}
char **cut_input(char *input, int *tuple)
{
char **cut;
if ((cut = (char **)malloc(sizeof(char *) * 3)))
{
if (tuple[0] == 2 || tuple[0] == 4)
cut[0] = ft_strndup(input, (size_t)tuple[1] - 1);
else
cut[0] = ft_strndup(input, (size_t)tuple[1]);
cut[1] = ft_strdup(&input[tuple[1] + 1]);
cut[2] = NULL;
}
return (cut);
}
t_ast *ast_build(char *input, int eof, t_sh *shell)
{
t_ast *ast;
int tuple[2];
if ((ast = (t_ast *)malloc(sizeof(t_ast))))
{
find_operand(input, tuple);
ast->op = tuple[0];
ast->stdin = 0;
ast->stdout = 1;
ast->stderr = 2;
ast->from = -2;
ast->to = -2;
if (ast->op == -1)
trigger_command(ast, input, eof);
else
trigger_op_recurse(ast, input, tuple, shell);
}
free(input);
return (ast);
}
|
C
|
#include <stdio.h>
#pragma warning(disable : 4996)
#include <limits.h>
#include <math.h>
#define MONTHS 12
#define SECOND_PER_MINUTE 60
/*
int main(void)
{
printf("Hello World");
int x;
x = 5;
printf("%d", x);
printf(" x ũ %dԴϴ.", sizeof(x));
int x = 50;
float y = 123456789.123456789;
double z = 123456789.123456789;
printf("x = %d\n", x);
printf("y = %.2f\n", y);
printf("z = %.2f\n", z);
int x = INT_MAX;
printf("int ִ x %dԴϴ.\n",x);
printf("x + 1%dԴϴ./n", x + 1);
//̷ ִ Ѿ ѹƼ ּҰ ư
int x = 10;
int y = 20;
printf("x = %dԴϴ.\n", x);
printf("y = %dԴϴ.\n", y);
printf("x + y = %dԴϴ.\n", x + y);
double monthSalary = 1000.5;
printf("$ %.2f", monthSalary * MONTHS);
char x = 'A';
printf("%c", x);
int x = 100;
printf("10 : %d\n", x);
printf("8 : %o\n", x);
printf("16 : %x\n", x);
int input = 1000;
int minute = input / SECOND_PER_MINUTE;
int second = input % SECOND_PER_MINUTE;
printf("%d %d %d Դϴ.\n", input, minute, second);
int x = 0;
printf(" x %dԴϴ.\n", x);
x++;
printf(" x %dԴϴ.\n", x);
printf(" x %dԴϴ.\n", x--);
//++Ǵ -- ڿ ش Ŀ ̷
printf(" x %dԴϴ.\n", x);
printf(" x %dԴϴ.\n", --x);
//ڰ տ
int x = 100;
printf(" x %dԴϴ.\n", x);
x += 50; // x = x + 50 ȣ ȿ ȴٴ
printf(" x %dԴϴ.\n", x);
x *= 50;
printf(" x %dԴϴ.\n", x);
x %= 3; //50 3 1
printf(" x %dԴϴ.\n", x);
int x
int N;
printf("N = ");
scanf("%d", &N);
if (N > 0)
{
printf("N");
}
else
{
printf("ERROR");
}
//int => %d
//double = > % lf
//char = > % c
int N;
int M;
printf("N = ");
scanf("%d", &N);
printf("M = ");
scanf("%d", &M);
if (N > M)
{
printf("N");
}
else if (M == N)
{
printf("");
}
else
{
printf("M");
}
int main(void)
{
int N, M;
scanf("%d %d", &N, &M);
if (N > M)
{
printf("%d", N);
}
else if (N == M)
{
printf("");
}
else
{
printf("%d", M);
}
char c;
scanf("%c", &c);
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
printf("%c", c);
}
int i;
for (i = 1; i < 6; i++) {
printf("");
}
int x = 50, y = 30;
printf("x y ٸ ? %d\n", x != y);
and &&
or ||
int x = -50, y = 30;
int absoluteX = (x > 0) ? x : -x;
//ǿ - ̸ x ȯǰ ̸ -xȯ ȴٴ¶
int max = (x > y) ? x : y;
printf("x 밪 %dԴϴ./n", absoluteX);
printf("x y߿ ִ %dԴϤ./n", max);
//pow() ŵ, abs() 밪 -> <math.h>̺귯
double x = pow(2.0, 20.0);
printf("2 20 %.0fԴϴ.\n", x);
//Ҽ ķ 0 ڱ %.0f
return 0;
}*/
|
C
|
/*
Name: Joan Andoni González Rioz
Definition of an image data structure for PGM format images
Uses typedef, struct
Uses functions to read and write a file in PGM format, described here:
http://netpbm.sourceforge.net/doc/pgm.html
http://rosettacode.org/wiki/Bitmap/Write_a_PGM_file#C
Gilberto Echeverria
[email protected]
06/10/2016
*/
#include "pgm_image.h"
// Initialize the mutex to help the threads to not share memory
pthread_mutex_t lock;
// Generate space to store the image in memory
void allocateImage(image_t * image)
{
// Allocate the memory for INDEX array
image->pixels = malloc (image->height * sizeof(pixel_t *));
// Allocate the memory for all the DATA array
image->pixels[0] = calloc (image->height * image->width, sizeof(pixel_t));
// Add the rest of the pointers to the INDEX array
for (int i=1; i<image->height; i++)
{
// Add an offset from the beginning of the DATA array
image->pixels[i] = image->pixels[0] + image->width * i;
}
}
// Release the dynamic memory used by an image
void freeImage(image_t * image)
{
// Free the DATA array
free (image->pixels[0]);
// Free the INDEX array
free (image->pixels);
// Set the values for an empty image
image->width = 0;
image->height = 0;
image->pixels = NULL;
}
void readBoard(const char * filename, image_t * image)
{
FILE * file_ptr = NULL;
printf("\nReading file: '%s'\n", filename);
// Open the file
file_ptr = fopen(filename, "r");
if (file_ptr == NULL)
{
printf("Error: Unable to open file '%s'\n", filename);
exit(EXIT_FAILURE);
}
fscanf(file_ptr, "%d", &image->height);
fscanf(file_ptr, "%d", &image->width);
printf("Width: %d, Height: %d\n",image->width, image->height );
// Allocate the memory for the pixels in the board
allocateImage(image);
// Read the data for the pixels
for (int i=0; i<image->height; i++)
{
for (int j=0; j<image->width; j++)
{
// Read the value for the pixel
fscanf(file_ptr, "%hhu", &(image->pixels[i][j].value));
}
}
// Close the file
fclose(file_ptr);
printf("Done!\n");
}
void playGame(image_t * image)
{
// Local variable for an image structure
image_t destination = {0, 0, NULL};
// Local variable for using easier the matrix array
int double_matrix[3][3] = {0};
// Copy the size of the image
destination.height = image->height;
destination.width = image->width;
// Get the memory for the image data
allocateImage(&destination);
// Check the neighbors of all pixels
for (int row = 0; row < image->height; row++)
{
for (int column = 0; column < image->width; column++)
{
for (int matrixRow = -1; matrixRow <= 1; matrixRow++) {
for (int matrixColumn = -1; matrixColumn <= 1; matrixColumn++) {
int r = row+matrixRow;
int c = column+matrixColumn;
if (r < 0) {
r = image->height - 1;
} else if (r == image->height) {
r = 0;
}
if (c < 0) {
c = image->width - 1;
} else if (r == image->width) {
c = 0;
}
double_matrix[matrixRow+1][matrixColumn+1] = image->pixels[r][c].value;
}
}
destination.pixels[row][column].value = checkNeighbors(double_matrix);
}
}
// Free the previous memory data
freeImage(image);
// Copy the results back to the pointer received
*image = destination;
}
void playGameOMP(image_t * image)
{
// Local variable for an image structure
image_t destination = {0, 0, NULL};
// Local variable for using easier the matrix array
int double_matrix[3][3] = {0};
// Copy the size of the image
destination.height = image->height;
destination.width = image->width;
// Get the memory for the image data
allocateImage(&destination);
// Make the paralelism with Open MP
#pragma omp parallel for collapse(2) private(double_matrix)
// Check the neighbors of all pixels
for (int row = 0; row < image->height; row++)
{
for (int column = 0; column < image->width; column++)
{
for (int matrixRow = -1; matrixRow <= 1; matrixRow++) {
for (int matrixColumn = -1; matrixColumn <= 1; matrixColumn++) {
int r = row+matrixRow;
int c = column+matrixColumn;
if (r < 0) {
r = image->height - 1;
} else if (r == image->height) {
r = 0;
}
if (c < 0) {
c = image->width - 1;
} else if (r == image->width) {
c = 0;
}
double_matrix[matrixRow+1][matrixColumn+1] = image->pixels[r][c].value;
}
}
destination.pixels[row][column].value = checkNeighbors(double_matrix);
}
}
// Free the previous memory data
freeImage(image);
// Copy the results back to the pointer received
*image = destination;
}
void playGameThreads(image_t * image)
{
// Set the data that is going to be sended to the threads
data_t * thread_data = NULL;
pthread_t tid[NUM_THREADS];
// Make the calculations to split the iterations
int start = 0;
int stepsPerThread = image->height / NUM_THREADS;
int stepsLeft = image->height % NUM_THREADS;
for (int i = 0; i < NUM_THREADS; i++) {
// Allocate memory for the information that is going to be
// sended to the thread
thread_data = malloc (sizeof (data_t));
// Fill the data of the thread with the iterations
thread_data->start = start;
thread_data->steps = stepsPerThread;
thread_data->image = image;
// Check if there is some iterations that have to be done
if (stepsLeft > 0) {
thread_data->steps++;
stepsLeft--;
}
//Make thread
pthread_create(&tid[i], NULL, threadsGame, (void *)thread_data);
start += thread_data->steps;
}
// Wait the end of the threads
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(tid[i], NULL);
}
}
void * threadsGame(void * arg)
{
// Start the lock of the mutex here cause the threads are sharing
// information and the most important is that if i dont lock it it frees
// the memory of image multiple times and makes a sementation fault
pthread_mutex_lock(&lock);
// Recive the information of the thread
data_t * thread_data = (data_t *) arg;
// Local variable for an image structure
image_t destination = {0, 0, NULL};
// Local variable for using easier the matrix array
int double_matrix[3][3] = {0};
// Copy the size of the image
destination.height = thread_data->image->height;
destination.width = thread_data->image->width;
// Get the memory for the image data
allocateImage(&destination);
// Check the neighbors of all pixels
for (int row = 0; row < thread_data->image->height; row++)
{
for (int column = 0; column < thread_data->image->width; column++)
{
for (int matrixRow = -1; matrixRow <= 1; matrixRow++) {
for (int matrixColumn = -1; matrixColumn <= 1; matrixColumn++) {
int r = row+matrixRow;
int c = column+matrixColumn;
if (r < 0) {
r = thread_data->image->height - 1;
} else if (r == thread_data->image->height) {
r = 0;
}
if (c < 0) {
c = thread_data->image->width - 1;
} else if (r == thread_data->image->width) {
c = 0;
}
double_matrix[matrixRow+1][matrixColumn+1] = thread_data->image->pixels[r][c].value;
}
}
destination.pixels[row][column].value = checkNeighbors(double_matrix);
}
}
// Free the previous memory data
freeImage(thread_data->image);
// Copy the results back to the pointer received
*thread_data->image = destination;
// Unlock the mutex
pthread_mutex_unlock(&lock);
// Exit the thread
pthread_exit(NULL);
}
// Function to check the neighbors and return the value of the
// statement for the pixel
int checkNeighbors(int matrix[3][3])
{
// Initialize the value of the neighbors and the count for
// the number of neighbors 1 and the neighbors 2
int neighbors = 0, repetitions[2] = { 0, 0 }, value = 0, live = 0;
for (int matrixRow = 0; matrixRow < 3; matrixRow++) {
for (int matrixColumn = 0; matrixColumn < 3; matrixColumn++) {
if (matrixRow == 1 && matrixColumn == 1) {
continue;
}
if (matrix[matrixRow][matrixColumn] > 0) {
switch (matrix[matrixRow][matrixColumn]) {
case 1:
repetitions[0] += 1;
break;
case 2:
repetitions[1] += 1;
break;
}
neighbors += 1;
}
}
}
if (repetitions[1] >= repetitions[0]) {
value = 2;
} else if (repetitions[1] < repetitions[0]) {
value = 1;
}
if (neighbors >= 4) {
// Over population
live = 0;
} else if ( neighbors == 3 ) {
// Revive or stay with the live value
live = 1;
} else if ( neighbors == 2 ){
// Stay with the value that it has
if ( matrix[1][1] >= 1 ) {
// The pixel is alive
live = 1;
} else {
// The pixel is dead
live = 0;
}
} else if ( neighbors < 2 ) {
// Underpopulation or dead pixel
live = 0;
}
return live * value;
}
// Write the data in the image structure into a new PGM file
// Receive a pointer to the image, to avoid having to copy the data
void writePGMFile(const char * filename, const pgm_t * pgm_image)
{
FILE * file_ptr = NULL;
//printf("\nWriting file: '%s'\n", filename);
// Open the file
file_ptr = fopen(filename, "w");
if (file_ptr == NULL)
{
printf("Error: Unable to open file '%s'\n", filename);
exit(EXIT_FAILURE);
}
// Write the header for the file
fprintf(file_ptr, "%s\n", pgm_image->magic_number);
fprintf(file_ptr, "# %s\n", filename);
fprintf(file_ptr, "%d %d\n", pgm_image->image.width, pgm_image->image.height);
fprintf(file_ptr, "%d\n", pgm_image->max_value);
// Write the data acording to the type
if ( !strncmp(pgm_image->magic_number, "P2", 3) )
{
writePGMTextData(pgm_image, file_ptr);
}
else if ( !strncmp(pgm_image->magic_number, "P5", 3) )
{
writePGMBinaryData(pgm_image, file_ptr);
}
else
{
printf("Invalid file format. Unknown type: %s\n", pgm_image->magic_number);
exit(EXIT_FAILURE);
}
fclose(file_ptr);
//printf("Done!\n");
}
// Write the data in the image structure into a new PGM file
// Receive a pointer to the image, to avoid having to copy the data
void writePGMTextData(const pgm_t * pgm_image, FILE * file_ptr)
{
// Write the pixel data
for (int i=0; i<pgm_image->image.height; i++)
{
for (int j=0; j<pgm_image->image.width; j++)
{
fprintf(file_ptr, "%d", pgm_image->image.pixels[i][j].value);
// Separate pixels in the same row with tabs
if (j < pgm_image->image.width-1)
fprintf(file_ptr, "\t");
else
fprintf(file_ptr, "\n");
}
}
}
// Write the data in the image structure into a new PGM file
// Receive a pointer to the image, to avoid having to copy the data
void writePGMBinaryData(const pgm_t * pgm_image, FILE * file_ptr)
{
unsigned char * data = NULL;
int k = 0;
// Write the pixel data
size_t pixels = pgm_image->image.height * pgm_image->image.width;
// Create an array with the raw data for the image
data = (unsigned char *) malloc (pixels * 3 * sizeof (unsigned char));
// Copy the data into the new array
for (int i=0; i<pgm_image->image.height; i++)
{
for (int j=0; j<pgm_image->image.width; j++)
{
// Copy the data into the correct structure
data[k++] = pgm_image->image.pixels[i][j].value;
}
}
// Write the binary data to the file
fwrite(data, sizeof (unsigned char), pixels, file_ptr);
// Release the temporary array
free(data);
}
|
C
|
#include "uart.h"
// ڳʼ
void uart_init(void)
{
// ʼTx RxӦGPIO
rGPA0CON &= ~(0xff<<0); // ѼĴbit07ȫ
rGPA0CON |= 0x00000022; // 0b0010, Rx Tx
// ؼĴ
rULCON0 = 0x3;
rUCON0 = 0x5;
rUMCON0 = 0;
rUFCON0 = 0;
// DIV_VAL = (PCLK / (bps x 16))-1
// PCLK_PSYS66MHz 0.8
//rUBRDIV0 = 34;
//rUDIVSLOT0 = 0xdfdd;
// PCLK_PSYS66.7MHz 0.18
// DIV_VAL = (66700000/(115200*16)-1) = 35.18
rUBRDIV0 = 35;
// (rUDIVSLOTе1ĸ)/16=һ=0.18
// (rUDIVSLOTе1ĸ = 16*0.18= 2.88 = 3
rUDIVSLOT0 = 0x0888; // 31ٷƼõ
}
// ڷͳһֽ
void putc(char c)
{
// ڷһַʵǰһֽڶͻȥ
// Ϊڿ1ֽڵٶԶԶCPUٶȣCPU1ֽǰ
// ȷϴڿǰǿյģ˼ǴѾһֽڣ
// ǿλΪ0ʱӦѭֱλΪ1
while (!(rUTRSTAT0 & (1<<1)));
rUTXH0 = c;
}
// ڽճѯʽһֽ
char getc(void)
{
while (!(rUTRSTAT0 & (1<<0)));
return (rURXH0 & 0x0f);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "system_m.h"
#include "interrupt.h"
#include "kernel2.h"
/************* Symbolic constants and macros ************/
#define MAX_PROC 10
#define MAX_MONITORS 10
#define DPRINTA(text, ...) printf("[%d] " text "\n", head(&readyList), __VA_ARGS__)
#define DPRINT(text) DPRINTA(text, 0)
#define ERRA(text, ...) fprintf(stderr, "[%d] Error: " text "\n", head(&readyList), __VA_ARGS__)
#define ERR(text) ERRA(text, 0)
#define STACK_SIZE 10000
void idleFunction();
void clockFunction();
/************* Data structures **************/
typedef struct {
int next;
Process p;
int currentMonitor; /* points to the monitors array */
int monitors[MAX_MONITORS + 1]; /* used for nested calls; monitors[0] is always -1 */
int notified; // flag that tracks whether the process has been notified or not. Initial value 0
int counter; // -1 if inactive, 0 if active and counting
int sleeping;
} ProcessDescriptor;
typedef struct {
int timesTaken;
int takenBy;
int entryList;
int waitingList;
} MonitorDescriptor;
/********************** Global variables **********************/
/* Pointer to the head of the ready list */
static int readyList = -1;
/* Pointer to the head of the sleeping list */
static int sleepingList[MAX_PROC];
static int nextSleeper = 0;
/* List of process descriptors */
ProcessDescriptor processes[MAX_PROC];
static int nextProcessId = 0;
/* List of monitor descriptors */
MonitorDescriptor monitors[MAX_MONITORS];
static int nextMonitorId = 0;
static int idleIndex;
static int clockIndex;
static int slice = 0;
/*************** Functions for process list manipulation **********/
/* add element to the tail of the list */
static void addLast(int* list, int processId) {
if (*list == -1){
*list = processId;
}
else {
int temp = *list;
while (processes[temp].next != -1){
temp = processes[temp].next;
}
processes[temp].next = processId;
}
processes[processId].next = -1;
}
/* add element to the head of list */
static void addFirst(int* list, int processId){
processes[processId].next = *list;
*list = processId;
}
/* remove an element from the head of the list */
static int removeHead(int* list){
if (*list == -1){
return(-1);
}
else {
int head = *list;
int next = processes[*list].next;
processes[*list].next = -1;
*list = next;
return head;
}
}
/* returns the head of the list */
static int head(int* list){
return *list;
}
/* checks if the list is empty */
static int isEmpty(int* list) {
return *list < 0;
}
static int removeProc(int* list, int proc) { //removes a specific process in a list
if(processes[*list].next != proc)
removeProc(&processes[*list].next, proc);
else return removeHead(&processes[*list].next);
}
static void addSleeper(int proc) {
if(nextSleeper < MAX_PROC){
sleepingList[nextSleeper++] = int proc;
}
}
static void removeSleeper(int proc) {
}
/***********************************************************
***********************************************************
Kernel functions
************************************************************
* **********************************************************/
void createProcess (void (*f)(), int stackSize) {
if (nextProcessId == MAX_PROC){
ERR("Maximum number of processes reached!");
exit(1);
}
unsigned int* stack = malloc(stackSize);
if (stack==NULL) {
ERR("Could not allocate stack. Exiting...");
exit(1);
}
processes[nextProcessId].p = newProcess(f, stack, stackSize);
processes[nextProcessId].next = -1;
processes[nextProcessId].currentMonitor = 0;
processes[nextProcessId].monitors[0] = -1;
processes[nextProcessId].notified = 0;
processes[nextProcessId].counter = -1;
processes[nextProcessId].sleeping = 0;
addLast(&readyList, nextProcessId);
nextProcessId++;
}
static void checkAndTransfer() {
if (isEmpty(&readyList)){
ERR("No processes in the ready list! Exiting...");
exit(1);
}
Process process = processes[head(&readyList)].p;
transfer(process);
}
void start(){
DPRINT("Starting kernel...");
if(isEmpty(&readyList))
printf("ERROR: readyList is empty.");
idleIndex = nextProcessId;
createProcess(idleFunction, STACK_SIZE);
clockIndex = nextProcessId;
createProcess(clockFunction, STACK_SIZE);
init_button();
transfer(processes[clockIndex].p);
}
void yield(){
maskInterrupts();
int pid = removeHead(&readyList);
addLast(&readyList, pid);
checkAndTransfer();
allowInterrupts();
}
int createMonitor(){
maskInterrupts();
if (nextMonitorId == MAX_MONITORS){
ERR("Maximum number of monitors reached!\n");
exit(1);
}
monitors[nextMonitorId].timesTaken = 0;
monitors[nextMonitorId].takenBy = -1;
monitors[nextMonitorId].entryList = -1;
monitors[nextMonitorId].waitingList = -1;
return nextMonitorId++;
allowInterrupts();
}
static int getCurrentMonitor(int pid) {
return processes[pid].monitors[processes[pid].currentMonitor];
}
void enterMonitor(int monitorID) {
maskInterrupts();
int myID = head(&readyList);
if (monitorID > nextMonitorId || monitorID < 0) {
ERRA("Monitor %d does not exist.", nextMonitorId);
exit(1);
}
if (processes[myID].currentMonitor >= MAX_MONITORS) {
ERR("Too many nested calls.");
exit(1);
}
if (monitors[monitorID].timesTaken > 0 && monitors[monitorID].takenBy != myID) {
removeHead(&readyList);
addLast(&(monitors[monitorID].entryList), myID);
checkAndTransfer();
/* I am woken up by exitMonitor -- check if the monitor state is consistent */
if ((monitors[monitorID].timesTaken != 1) || (monitors[monitorID].takenBy != myID)) {
ERR("The kernel has performed an illegal operation. Please contact customer support.");
exit(1);
}
}
else {
monitors[monitorID].timesTaken++;
monitors[monitorID].takenBy = myID;
}
/* push the new call onto the call stack */
processes[myID].monitors[++processes[myID].currentMonitor] = monitorID;
allowInterrupts();
}
void exitMonitor() {
maskInterrupts();
int myID = head(&readyList);
int myMonitor = getCurrentMonitor(myID);
if (myMonitor < 0) {
ERRA("Process %d called exitMonitor outside of a monitor.", myID);
exit(1);
}
/* go backwards in the stack of called monitors */
processes[myID].currentMonitor--;
if (--monitors[myMonitor].timesTaken == 0) {
/* see if someone is waiting, and if yes, let the next process in */
if (!isEmpty(&(monitors[myMonitor].entryList))) {
int pid = removeHead(&(monitors[myMonitor].entryList));
addLast(&readyList, pid);
monitors[myMonitor].timesTaken = 1;
monitors[myMonitor].takenBy = pid;
} else {
monitors[myMonitor].takenBy = -1;
}
}
allowInterrupts();
}
void wait() {
maskInterrupts();
int myID = head(&readyList);
int myMonitor = getCurrentMonitor(myID);
int myTaken;
processes[myID].notified = 0;
if (myMonitor < 0) {
ERRA("Process %d called wait outside of a monitor.", myID);
exit(1);
}
removeHead(&readyList);
addLast(&monitors[myMonitor].waitingList, myID);
/* save timesTaken so we can restore it later */
myTaken = monitors[myMonitor].timesTaken;
/* let the next process in, if any */
if (!isEmpty(&(monitors[myMonitor].entryList))) {
int pid = removeHead(&(monitors[myMonitor].entryList));
addLast(&readyList, pid);
monitors[myMonitor].timesTaken = 1;
monitors[myMonitor].takenBy = pid;
} else {
monitors[myMonitor].timesTaken = 0;
monitors[myMonitor].takenBy = -1;
}
checkAndTransfer();
/* I am woken up by exitMonitor -- check if the monitor state is consistent */
if ((monitors[myMonitor].timesTaken != 1) || (monitors[myMonitor].takenBy != myID)) {
ERR("The kernel has performed an illegal operation. Please contact customer support.");
exit(1);
}
/* we're back, restore timesTaken */
monitors[myMonitor].timesTaken = myTaken;
allowInterrupts();
}
void notify() {
maskInterrupts();
int myID = head(&readyList);
int myMonitor = getCurrentMonitor(myID);
if (myMonitor < 0) {
ERRA("Process %d called notify outside of a monitor.", myID);
exit(1);
}
if (!isEmpty(&(monitors[myMonitor].waitingList))) {
int pid = removeHead(&monitors[myMonitor].waitingList);
processes[pid].notified = 1;
addLast(&monitors[myMonitor].entryList, pid);
}
allowInterrupts();
}
void notifyAll() {
maskInterrupts();
int myID = head(&readyList);
int myMonitor = getCurrentMonitor(myID);
if (myMonitor < 0) {
ERRA("Process %d called notify outside of a monitor.", myID);
exit(1);
}
while (!isEmpty(&(monitors[myMonitor].waitingList))) {
int pid = removeHead(&monitors[myMonitor].waitingList);
processes[pid].notified = 1;
addLast(&monitors[myMonitor].entryList, pid);
}
allowInterrupts();
}
void idleFunction() {
while(1){}
}
int checkandDecrement() {
for(int i = 0; i < nextProcessId - 3; i++) { //-next -clock -idle
while(!isEmpty(&sleepingList))
ProcessDescriptor proc = processes[i];
if(proc.notified) { //the process got the notify before timeout
proc.counter = -1;
}
if(proc.counter >= 0){
proc.counter--;
if(proc.counter < 0){
//removes the process in question from the waitingList and
//adds it to the end of the entryList of the monitor
//when the timer expires
if(!proc.sleeping)
addLast(&monitors[getCurrentMonitor(i)].entryList,
removeProc(&monitors[getCurrentMonitor(i)].waitingList, i));
else {
proc.sleeping = 0;
addLast(&readyList ,i);
}
}
}
}
}
void clockFunction() {
maskInterrupts();
init_clock();
while(1) {
if(!isEmpty(&readyList)) {
Process p = processes[head(&readyList)].p;
iotransfer(p, 0);
checkandDecrement();
}
else iotransfer(processes[idleIndex].p, 0);
if(slice % 20 != 0){
slice++;
} else {
slice = 0;
int q = removeHead(&readyList);
addLast(&readyList, q);
}
}
}
int timedWait(int msec) {
maskInterrupts();
int myID = head(&readyList);
if(msec < 0) {
ERR("Negative time given in timedWait");
exit(1);
}
processes[myID].notified = 0;
if(msec == 0) wait();
else {
processes[myID].counter = msec; /*activate counter*/
//addLast(&sleepingList, myID);
wait(); //real start of the waiting and countdown
}
processes[myID].counter = -1;
if(processes[myID].notified == 1) {
allowInterrupts();
return 1;
} else {
allowInterrupts();
return 0;
}
}
void sleep(int time) { //blocking or transfer()
maskInterrupts();
int processId = removeHead(&readyList);
processes[processId].counter = time;
//addLast(&sleepingList, processId);
processes[processId].sleeping = 1;
allowInterrupts();
}
void waitInterrupt(int peripherique) {
int elem = removeHead(&readyList);
Process p;
if(!isEmpty(&readyList))
p = processes[head(&readyList)].p;
else
p = processes[idleIndex].p;
iotransfer(p, peripherique);
addFirst(&readyList, elem);
}
|
C
|
/*********************************************************
* MATRIX ADD *
* Author: Reez Patel *
* Source: Ex: 11.4 (P-394) = ANSI-C *
**********************************************************/
#include <stdio.h>
#define LIMIT 3
void inputMat(int a[][3]);
void addMat(int a[][3],int b[][3],int c[][3]);
void printMat(int a[][3]);
int main()
{
int i,j;
int matA[LIMIT][LIMIT],matB[LIMIT][LIMIT],matC[LIMIT][LIMIT];
printf("Enter The Value of Matrix A (%dx%d) \n",LIMIT,LIMIT);
inputMat(matA);
printf("Enter The Value of Matrix B (%dx%d) \n",LIMIT,LIMIT);
inputMat(matB);
addMat(matA,matB,matC);
printf("ANS: \n");
printMat(matC);
return 0;
}
void addMat(int a[][LIMIT],int b[][LIMIT],int c[][LIMIT])
{
int i,j;
for(i=0;i<LIMIT;i++)
for(j=0;j<LIMIT;j++)
*(*(c+i)+j) = *(*(a+i)+j) + *(*(b+i)+j);
}
void inputMat(int matA[][LIMIT])
{
int i,j;
for(i=0;i<LIMIT;i++)
for(j=0;j<LIMIT;j++)
scanf("%d",(*(matA+i)+j));
}
void printMat(int matA[][LIMIT])
{
int i,j;
for(i=0;i<LIMIT;i++)
{
for(j=0;j<LIMIT;j++)
printf("%d ",*(*(matA+i)+j));
printf("\n");
}
}
|
C
|
#include <stdio.h>
int main(void)
{
printf("The controller char test\n");
int in,i;
printf("Input choice\n");
printf("\r 1.\\b \n 2.\\f \n 3.\\n \n 4.\\r \n 5.\\t \n 6.\\v \n");
for(i=0;i<10;i++)
{
printf("hello,world%d\n",i);
}
scanf("%d",&in);
switch(in)
{
case 1:
printf("\b");
break;
case 2:
printf("\f");
break;
case 3:
printf("\n");
break;
case 4:
printf("\r");
break;
case 5:
printf("\t");
break;
case 6:
printf("\v");
break;
}
return 0;
}
|
C
|
#ifndef __GETNUMBEROFK_H__
#define __GETNUMBEROFK_H__
//õһγʱ±
int GetFirstNum(int* a,int length ,int num)
{
for (int i = 0; i < length; i++)
{
if (a[i] == num)
return i;
}
return -1;
}
//õһγǵ±
int GetLastNum(int* a, int length, int num)
{
int prev = 0;
int cur = 0;
while (cur<length)
{
if (a[cur] != num)
{
cur++;
}
else
{
prev = cur;
cur++;
if (a[prev] != a[cur])
{
return prev;
}
}
}
return -1;
}
int GetNumberOfK(int* a,int length,int num)
{
if (a == NULL || length < 0)
return 0;
int first = GetFirstNum(a, length, num);
int end = GetLastNum(a, length, num);
int sum = 0;
if (end != -1 && first != -1)
sum = end - first + 1;
return sum;
}
void TestGet()
{
int a[10] = { 1, 3, 3, 3, 3, 3, 3, 3, 3, 5 };
cout << GetNumberOfK(a, 10, 3) << endl;
}
#endif //__GETNUMBEROFK_H__
|
C
|
#include "algorithms/aes-ecb.h"
#include "algorithms/aes-cbc.h"
#include <stdio.h>
#include <stdint.h>
#include "time.h"
#include "string.h"
#define ROUNDS 1000
#define MESSAGE_LENGTH 2048 // in BYTES
#define KEY_SIZE 24 // in BYTES
#define ECB_MODE 0 // 0=OFF, 1=ON
int main(void)
{
printf("Starting Benchmark ...\nNUMBER OF ROUNDS: %d\nWORDLENGTH: %d BYTES\n", ROUNDS, MESSAGE_LENGTH);
if(ECB_MODE){
printf("Mode: ELECTRONIC CODEBOOK\n");
executeAesEcb(ROUNDS, KEY_SIZE, MESSAGE_LENGTH);
} else {
printf("Mode: CIPHER BLOCKER CHAINING\n");
executeAesCbc(ROUNDS, KEY_SIZE, MESSAGE_LENGTH);
}
printf("Benchmark done!\n");
return 0;
}
|
C
|
#include"EQM.h"
#include <stdio.h>
#include<math.h>
float EQ1()
{
char temp;
printf("Which value you want to find");
scanf(" %c",&temp);
if(temp=='v'||temp=='V')
{
float V,U,A,T;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Time");
scanf("%f",&T);
return U+A*T;
}
else if(temp=='u'||temp=='U')
{
float V,U,A,T;
printf("Enter the value of Final Velocity");
scanf("%f",&V);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Time");
scanf("%f",&T);
return V-A*T;
}
else if(temp=='T'||temp=='t')
{
float V,U,A;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Final Velocity");
scanf("%f",&V);
return (V-U)/A;
}
else if(temp=='a'||temp=='A')
{
float V,U,A,T;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Final Velocity");
scanf("%f",&V);
printf("Enter the value of Time");
scanf("%f",&T);
return (V-U)/T;
}
}
float EQ2()
{
char temp;
printf("Which value you want to find");
scanf(" %c",&temp);
if(temp=='s'||temp=='S')
{
float S,U,A,T;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Time");
scanf("%f",&T);
return U*T+0.5*A*T*T;
}
else if(temp=='u'||temp=='U')
{
float S,U,A,T;
printf("Enter the value of Distance");
scanf("%f",&S);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Time");
scanf("%f",&T);
U=(S-0.5*A*T*T);
return U/T;
}
else if(temp=='A'||temp=='a')
{
float S,U,A,T;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Distance");
scanf("%f",&S);
printf("Enter the value of Time");
scanf("%f",&T);
A =2.0*(S-U*T)/(T*T);
return A;
}
else if(temp=='T'||temp=='t')
{
float S,U,V;
float temp2;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Displacement");
scanf("%f",&S);
printf("Enter the value of Final velocity");
scanf("%f",&V);
temp2=(S-0.5*(V-U))/U;
return temp2;
}
}
float EQ3()
{
char temp;
printf("Which value you want to find");
scanf(" %c",&temp);
if(temp=='v'||temp=='V')
{
float U,A,S,V;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Distance");
scanf("%f",&S);
V=sqrt(U*U+2*A*S);
return V;
}
else if(temp=='u'||temp=='U')
{
float V,U,A,S;
printf("Enter the value of Final Velocity");
scanf("%f",&V);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Distance");
scanf("%f",&S);
U=sqrt(V*V-2*A*S);
return U;
}
else if(temp=='s'||temp=='S')
{
float V,U,A,S;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Acceleration");
scanf("%f",&A);
printf("Enter the value of Final Velocity");
scanf("%f",&V);
S=(V*V-U*U)/2*A;
return S;
}
else if(temp=='a'||temp=='A')
{
float V,U,A,S;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Final Velocity");
scanf("%f",&V);
printf("Enter the value of Distance");
scanf("%f",&S);
A=(V*V-U*U)/2*S;
return A;
}
}
float EQ4()
{
char temp;
printf("Which value you want to find");
scanf(" %c",&temp);
if(temp=='v'||temp=='V')
{
float V,U,T,S;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Distance");
scanf("%f",&S);
printf("Enter the value of Time");
scanf("%f",&T);
V=(2*S/T)-U;
return V;
}
else if(temp=='u'||temp=='U')
{
float V,U,S,T;
printf("Enter the value of Final Velocity");
scanf("%f",&V);
printf("Enter the value of Distance");
scanf("%f",&S);
printf("Enter the value of Time");
scanf("%f",&T);
U=(2*S/T)-V;
return U;
}
else if(temp=='T'||temp=='t')
{
float V,U,S,T;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Distance");
scanf("%f",&S);
printf("Enter the value of Final Velocity");
scanf("%f",&V);
T=2*S/(U+V);
return T;
}
else if(temp=='S'||temp=='s')
{
float V,U,S,T;
printf("Enter the value of initial Velocity");
scanf("%f",&U);
printf("Enter the value of Final Velocity");
scanf("%f",&V);
printf("Enter the value of Time");
scanf("%f",&T);
S=0.5*(U+V)*T;
return S;
}
}
|
C
|
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#include <getopt.h>
#include <openenclave/host.h>
#include <openenclave/internal/raise.h>
#include <openenclave/internal/tests.h>
#include "oeseal_u.h"
#define COMMAND_NAME_SEAL "seal"
#define COMMAND_NAME_UNSEAL "unseal"
#define SKIP_RETURN_CODE 2
typedef enum _command_t
{
COMMAND_UNSUPPORTED,
COMMAND_SEAL,
COMMAND_UNSEAL
} command_t;
static void _print_helper()
{
printf("Usage: oeseal <command> [<args>]\n"
"command: seal, unseal\n"
"args:\n"
" -h, --help: Helper message\n"
" -e, --enclave: Enclave binary\n"
" -i, --input: Input file\n"
" -o, --output: Output file\n"
" -v, --verbose: Enable the verbose output\n");
}
static command_t _process_command(const char* command)
{
command_t result = COMMAND_UNSUPPORTED;
if (strcmp(command, COMMAND_NAME_SEAL) == 0)
result = COMMAND_SEAL;
else if (strcmp(command, COMMAND_NAME_UNSEAL) == 0)
result = COMMAND_UNSEAL;
return result;
}
static oe_result_t _create_enclave(const char* path, oe_enclave_t** enclave)
{
return oe_create_oeseal_enclave(
path,
OE_ENCLAVE_TYPE_SGX,
OE_ENCLAVE_FLAG_DEBUG_AUTO,
NULL,
0,
enclave);
}
static oe_result_t _read_file(const char* path, uint8_t** data, size_t* size)
{
oe_result_t result = OE_FAILURE;
uint8_t* _data = NULL;
long file_size = 0;
size_t _size = 0;
FILE* f = NULL;
if (!path || !data || !size)
OE_RAISE(OE_INVALID_PARAMETER);
f = fopen(path, "r");
if (f == NULL)
OE_RAISE_MSG(OE_FAILURE, "Unable to open %s", path);
fseek(f, 0, SEEK_END);
file_size = ftell(f);
if (file_size == -1)
OE_RAISE(OE_FAILURE);
_size = (size_t)file_size;
fseek(f, 0, SEEK_SET);
_data = malloc(_size);
if (_data == NULL)
OE_RAISE(OE_OUT_OF_MEMORY);
if (fread(_data, _size, 1, f) != 1)
OE_RAISE(OE_FAILURE);
*data = _data;
*size = _size;
result = OE_OK;
done:
if (f)
fclose(f);
return result;
}
static oe_result_t _write_file(const char* path, uint8_t* data, size_t size)
{
oe_result_t result = OE_FAILURE;
FILE* f = NULL;
if (!path || !data || !size)
OE_RAISE(OE_INVALID_PARAMETER);
f = fopen(path, "w");
if (f == NULL)
OE_RAISE_MSG(OE_FAILURE, "Unable to open %s", path);
if (fwrite(data, size, 1, f) != 1)
OE_RAISE(OE_FAILURE);
result = OE_OK;
done:
if (f)
fclose(f);
return result;
}
int main(int argc, const char* argv[])
{
command_t command = COMMAND_UNSUPPORTED;
oe_result_t result = OE_FAILURE;
oe_enclave_t* enclave = NULL;
output_t output_data = {0};
const char* output = NULL;
uint8_t* data = NULL;
bool verbose = false;
size_t size = 0;
int ret = 1;
int c = 0;
const uint32_t flags = oe_get_create_flags();
if ((flags & OE_ENCLAVE_FLAG_SIMULATE) != 0)
{
fprintf(stderr, "oeseal not supported in simulation mode.\n");
ret = SKIP_RETURN_CODE;
goto exit;
}
if (argc < 2)
{
_print_helper();
goto exit;
}
command = _process_command(argv[1]);
if (command == COMMAND_UNSUPPORTED)
{
fprintf(stderr, "Unknown command %s\n", argv[1]);
_print_helper();
goto exit;
}
while (1)
{
static struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"enclave", required_argument, NULL, 'e'},
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"verbose", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0},
};
static char short_options[] = "he:p:i:o:v";
c = getopt_long(
argc, (char* const*)argv, short_options, long_options, NULL);
if (c == -1)
break;
switch (c)
{
case 'h':
_print_helper();
break;
case 'e':
result = _create_enclave(optarg, &enclave);
if (result != OE_OK)
{
fprintf(stderr, "Failed to create the enclave\n");
goto exit;
}
break;
case 'i':
result = _read_file(optarg, &data, &size);
if (result != OE_OK)
{
fprintf(stderr, "Failed to read the file\n");
goto exit;
}
break;
case 'o':
output = optarg;
break;
case 'v':
verbose = true;
break;
default:
break;
}
}
if (command == COMMAND_SEAL)
enc_seal(enclave, &result, data, size, &output_data, verbose);
else // COMMAND_UNSEAL
enc_unseal(enclave, &result, data, size, &output_data, verbose);
if (result != OE_OK)
goto exit;
printf(
"oeseal %s succeeded.\n",
(command == COMMAND_SEAL) ? COMMAND_NAME_SEAL : COMMAND_NAME_UNSEAL);
if (output)
{
if (_write_file(output, output_data.data, output_data.size) != OE_OK)
{
fprintf(stderr, "Failed to write to the file\n");
goto exit;
}
printf("File %s created.\n", output);
}
printf("\n");
ret = 0;
exit:
if (enclave)
oe_terminate_enclave(enclave);
free(data);
free(output_data.data);
return ret;
}
|
C
|
#include <stdio.h>
#include <math.h>
main() {
int i, N; double Arctan1 = 0, x = 1/5.0, Arctan2 = 0, y = 1.0/239;
printf("Entrer un entier N: "); scanf("%d", &N);
for (i = 0; i < N+1; i++) {
Arctan1 = Arctan1 + pow(-1,i) * pow(x, 2*i+1)/(2*i+1);
Arctan2 = Arctan2 + pow(-1,i) * pow(y, 2*i+1)/(2*i+1);
}
printf("Pi = %lf", 16*Arctan1 - 4*Arctan2);
}
|
C
|
#include <stdio.h>
int main()
{
int num1, num2;
char name[20];
printf("Hello user, what is your name?\n");
scanf("%s", name);
printf("Hello %s\nEnter two numbers, please!\n", name);
scanf("%d %d", &num1, &num2);
printf("You entered: %d and %d\n", num1, num2);
printf("The sum of these numbers are %d\n", num1 + num2);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int** A;
size_t N = 50;
size_t M = 60;
size_t i;
A = (int**) malloc(sizeof(int*) * N * M);
for (i=0; i<N; ++i) {
A[i] = (int*) malloc(sizeof(int) * M);
}
A[1][2] = 3;
for (i=0; i<N; ++i) {
free(A[i]);
}
free(A);
}
|
C
|
#include <x86intrin.h>
#include "complement.h"
// Adapted from: https://github.com/adamkewley/reverse-complement/
extern void ssse3_reverse_complement(char* dst, const char* src, size_t len) {
const __m128i shuffle_mask = _mm_set_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
const __m128i and_mask = _mm_set1_epi8(0x1f);
const __m128i sixteen = _mm_set1_epi8(16);
const __m128i lo_lut = _mm_set_epi8(
'\0', 'N', 'K', '\0',
'M', '\n', '\0', 'D',
'C', '\0', '\0', 'H',
'G', 'V', 'T', '\0'
);
const __m128i hi_lut = _mm_set_epi8(
'\0', '\0', '\0', '\0',
'\0', '\0', 'R', '\0',
'W', 'B', 'A', 'A',
'S', 'Y', '\0', '\0'
);
while (len > sizeof(__m128i)) {
//
len -= sizeof(__m128i);
__m128i v = _mm_loadu_si128((__m128i*) &src[len]);
// reverse elements in the registers
v = _mm_shuffle_epi8(v, shuffle_mask);
// AND all elements with 0x1f, so that a smaller LUT (< 32 bytes)
// can be used. This is important with SIMD because, unlike
// single-char complement (above), SIMD uses 16-byte shuffles. The
// single-char LUT would require four shuffles, this LUT requires
// two.
v = _mm_and_si128(v, and_mask);
// Lookup for all elements <16
__m128i lo_mask = _mm_cmplt_epi8(v, sixteen);
__m128i lo_els = _mm_and_si128(v, lo_mask);
__m128i lo_vals = _mm_shuffle_epi8(lo_lut, lo_els);
// Lookup for all elements >16
__m128i hi_els = _mm_sub_epi8(v, sixteen);
__m128i hi_vals = _mm_shuffle_epi8(hi_lut, hi_els);
// OR both lookup results
_mm_storeu_si128((__m128i*) dst, _mm_or_si128(lo_vals, hi_vals));
dst += sizeof(__m128i);
}
while (len > 0) {
*dst = complement(src[--len]);
dst++;
}
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include "common.h"
#include "logging.h"
#include "pwm.h"
int pwm0_enable_fd = -1;
#if GPIO_FAKE != 1
static void write_file(char* path, char * content) { int r;
int fd = open(path, O_WRONLY);
error_check(fd);
r = dprintf(fd, "%s", content);
error_check(r);
r = close(fd);
error_check(r);
}
#endif
void gpio_pwm_initialize(void) {
#if GPIO_FAKE == 1
INFO("GPIO_FAKE");
pwm0_enable_fd = -2;
#else
write_file("/sys/class/pwm/pwmchip0/export", "0\n");
write_file("/sys/class/pwm/pwmchip0/pwm0/period", "20000000\n");
write_file("/sys/class/pwm/pwmchip0/pwm0/duty_cycle", "18000000\n");
pwm0_enable_fd = open("/sys/class/pwm/pwmchip0/pwm0/enable", O_WRONLY);
error_check(pwm0_enable_fd);
#endif
}
void gpio_pwm_set(u8 value) {
assert(pwm0_enable_fd != -1);
#if GPIO_FAKE == 1
INFO("GPIO_FAKE value:%d", value);
#else
DEBUG("%d", value);
assert(value == 0 || value == 1);
int r = dprintf(pwm0_enable_fd, "%d\n", value);
error_check(r);
#endif
}
|
C
|
//
// Created by lucas on 25/03/17.
//
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <netinet/in.h>
#include "socket.h"
#include "codon.h"
#include "common.h"
int init_server(unsigned int port) {
socket_t server, client;
if (socket_create(&server)) {
perror("Error creating the socket");
return 1;
}
if (socket_bind_and_listen(&server, port)) {
perror("Error binding the socket");
socket_destroy(&server);
return 1;
}
if (socket_accept(&server, &client)) {
perror("Error accepting a connection");
socket_destroy(&server);
return 1;
}
char codons[MAX_CODONS];
size_t len = (size_t) socket_receive(&client, codons, MAX_CODONS);
int count[CODON_AMT] = {0};
codon_count(codons, len, count);
char msg[MSG_SIZE];
if (codon_write_return_msg(count, msg, MSG_SIZE)) {
fprintf(stderr, "Error writing message, check validity of " \
"codons.txt and codon_types.txt\n");
socket_destroy(&server);
socket_destroy(&client);
return 1;
}
len = strlen(msg);
size_t offset = 0;
while (len) {
size_t to_send = len;
if (to_send > CHUNK_SIZE) {
to_send = CHUNK_SIZE;
}
ssize_t sent = socket_send(&client, msg + offset, to_send);
if (sent < 0) {
perror("Error sending message to client");
}
offset += sent;
len -= sent;
}
socket_shutdown(&client, SHUT_WR);
socket_destroy(&server);
socket_destroy(&client);
return 0;
}
|
C
|
#include <stdio.h>
/* invert: return x with n bits beginning at p inverted */
unsigned invert(unsigned x, int p, int n) {
return (x ^ (~(~0 << n) << (p+1-n)));
}
int main() {
unsigned x = 9;
printf("x is: %u\n", x);
printf("invert(x, 3, 2) expect 5: %u\n", invert(x, 3, 2));
x = 13;
printf("x is: %u\n", x);
printf("invert(x, 4, 3) expect 17: %u\n", invert(x, 4, 3));
x = 85;
printf("x is: %u\n", x);
printf("invert(x, 5, 5) expect 107: %u\n", invert(x, 5, 5));
}
|
C
|
#include "krad_tone.h"
krad_tone_t *krad_tone_create(float sample_rate) {
krad_tone_t *krad_tone = calloc(1, sizeof(krad_tone_t));
krad_tone->sample_rate = sample_rate;
krad_tone_volume(krad_tone, krad_tone_DEFAULT_VOLUME);
return krad_tone;
}
void krad_tone_volume(krad_tone_t *krad_tone, int volume) {
krad_tone->volume = volume;
krad_tone->volume_actual = (float)(krad_tone->volume/100.0f);
krad_tone->volume_actual *= krad_tone->volume_actual;
}
void krad_tone_add_preset(krad_tone_t *krad_tone, char *preset) {
if ((strstr(preset, "dialtone") != NULL) || (strstr(preset, "dialtone_us") != NULL)){
krad_tone_add(krad_tone, 350.0);
krad_tone_add(krad_tone, 440.0);
}
if (strstr(preset, "dialtone_eu") != NULL) {
krad_tone_add(krad_tone, 425.0);
}
if (strstr(preset, "dialtone_uk") != NULL) {
krad_tone_add(krad_tone, 350.0);
krad_tone_add(krad_tone, 450.0);
}
if (strstr(preset, "1") != NULL) {
krad_tone_add(krad_tone, 697.0);
krad_tone_add(krad_tone, 1209.0);
}
if (strstr(preset, "2") != NULL) {
krad_tone_add(krad_tone, 697.0);
krad_tone_add(krad_tone, 1336.0);
}
if (strstr(preset, "3") != NULL) {
krad_tone_add(krad_tone, 697.0);
krad_tone_add(krad_tone, 1477.0);
}
if (strstr(preset, "4") != NULL) {
krad_tone_add(krad_tone, 770.0);
krad_tone_add(krad_tone, 1209.0);
}
if (strstr(preset, "5") != NULL) {
krad_tone_add(krad_tone, 770.0);
krad_tone_add(krad_tone, 1336.0);
}
if (strstr(preset, "6") != NULL) {
krad_tone_add(krad_tone, 770.0);
krad_tone_add(krad_tone, 1477.0);
}
if (strstr(preset, "7") != NULL) {
krad_tone_add(krad_tone, 852.0);
krad_tone_add(krad_tone, 1209.0);
}
if (strstr(preset, "8") != NULL) {
krad_tone_add(krad_tone, 852.0);
krad_tone_add(krad_tone, 1336.0);
}
if (strstr(preset, "9") != NULL) {
krad_tone_add(krad_tone, 852.0);
krad_tone_add(krad_tone, 1477.0);
}
if (strstr(preset, "0") != NULL) {
krad_tone_add(krad_tone, 941.0);
krad_tone_add(krad_tone, 1336.0);
}
if (strstr(preset, "*") != NULL) {
krad_tone_add(krad_tone, 941.0);
krad_tone_add(krad_tone, 1209.0);
}
if (strstr(preset, "#") != NULL) {
krad_tone_add(krad_tone, 941.0);
krad_tone_add(krad_tone, 1477.0);
}
if (strstr(preset, "A") != NULL) {
krad_tone_add(krad_tone, 697.0);
krad_tone_add(krad_tone, 1633.0);
}
if (strstr(preset, "B") != NULL) {
krad_tone_add(krad_tone, 770.0);
krad_tone_add(krad_tone, 1633.0);
}
if (strstr(preset, "C") != NULL) {
krad_tone_add(krad_tone, 852.0);
krad_tone_add(krad_tone, 1633.0);
}
if (strstr(preset, "D") != NULL) {
krad_tone_add(krad_tone, 941.0);
krad_tone_add(krad_tone, 1633.0);
}
}
void krad_tone_add(krad_tone_t *krad_tone, float frequency) {
int i;
krad_tone->active_tones++;
for (i = 0; i < MAX_TONES; i++) {
if (krad_tone->tones[i].active == 0) {
krad_tone->tones[i].frequency = frequency;
krad_tone->tones[i].delta = (2.0f * M_PI * krad_tone->tones[i].frequency) / krad_tone->sample_rate;
krad_tone->tones[i].angle = 0.0f;
krad_tone->tones[i].active = 1;
break;
}
}
}
void krad_tone_remove(krad_tone_t *krad_tone, float frequency) {
int i;
krad_tone->active_tones--;
for (i = 0; i < MAX_TONES; i++) {
if (krad_tone->tones[i].active == 1) {
if (krad_tone->tones[i].frequency == frequency) {
krad_tone->tones[i].active = 0;
break;
}
}
}
}
void krad_tone_clear(krad_tone_t *krad_tone) {
int i;
for (i = 0; i < MAX_TONES; i++) {
if (krad_tone->tones[i].active == 1) {
krad_tone_remove(krad_tone, krad_tone->tones[i].frequency);
}
}
}
void krad_tone_run(krad_tone_t *krad_tone, float *buffer, int numsamples) {
int i;
for(krad_tone->s = 0; krad_tone->s < numsamples; krad_tone->s++) {
buffer[krad_tone->s] = 0.0f;
for (i = 0; i < krad_tone->active_tones; i++) {
buffer[krad_tone->s] += krad_tone->volume_actual * sin(krad_tone->tones[i].angle);
krad_tone->tones[i].angle += krad_tone->tones[i].delta;
if (krad_tone->tones[i].angle > M_PI) {
krad_tone->tones[i].angle -= 2.0f * M_PI;
}
}
}
}
void krad_tone_destroy(krad_tone_t *krad_tone) {
free(krad_tone);
}
|
C
|
#include <stdio.h>
#define SIZE 5
int q[SIZE], front = -1, rear = -1;
int isFull(){
if (front == rear+1 || (front == 0 && rear == SIZE -1)) return(1);
else return(0);
}
int isEmpty(){
if (front == -1) return(1);
else return(0);
}
void insert(int x){
if (isFull()) puts("\nQueue Overflow");
else{
if (front == -1){
front = 0;
}
rear = (rear+1)%SIZE;
q[rear] = x;
}
}
void delete(){
int x;
if (isEmpty())puts("\nQueue Underflow");
else {
if(front == rear){
front = -1;
rear = -1;
}
printf("%d", q[front]);
front = (front + 1)%SIZE;
}
}
void display(){
int i;
if (front == -1)puts("Queue Empty");
else{
printf("Front->");
for (i=front; i!=rear; i=(i+1)%SIZE)printf("%d->", q[i]);
printf("%d<-Rear", q[rear]);
}
}
void main(){
int op, x;
do{
puts("\n1.Insert\n2.Delete\n3.Display\n4.Exit");
scanf("%d", &op);
switch(op){
case 1:
puts("\nEnter the element: ");
scanf("%d", &x);
insert(x);
break;
case 2:
delete();
break;
case 3:
display();
break;
default: break;
}
}while (op!=4);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
float x = 1.1;
while(x==1.1)
{
printf("\n%f",x);
x = x-0.1;
}
return 0;
}
|
C
|
/*
** sort.c for pushswap in /home/slejeune/Elementary_Programming_in_C/CPE_2016_Pushswap/src
**
** Made by Simon LEJEUNE
** Login <[email protected]>
**
** Started on Wed Nov 23 16:42:25 2016 Simon LEJEUNE
** Last update Thu Nov 24 14:19:50 2016 Simon LEJEUNE
*/
#include "../include/pushswap.h"
#include <stdlib.h>
void push(t_list **list1, t_list **list2)
{
int nb;
t_list *temp_free;
nb = (*list1)->nb;
begin_list(list2, nb);
temp_free = *list1;
*list1 = (*list1)->next;
free(temp_free);
}
void rotate(t_list **list1)
{
int nb;
t_list *temp_free;
nb = (*list1)->nb;
end_list(list1, nb);
temp_free = *list1;
*list1 = (*list1)->next;
free(temp_free);
}
int calc_push(t_list *list)
{
int count;
int count2;
int nb;
count = 0;
count2 = 0;
nb = list->nb;
while (list != NULL)
{
if ((list->nb) < nb)
{
nb = list->nb;
count = count2;
}
list = list->next;
count2++;
}
return (count);
}
void pushswap2(t_list **list1, t_list **list2)
{
int i;
int j;
i = 0;
if (list_size(*list1) != 1)
{
j = calc_push(*list1);
while (i < j)
{
rotate(list1);
my_putstr("ra ");
i++;
}
push(list1, list2);
my_putstr("pb ");
pushswap2(list1, list2);
}
}
void pushswap(t_list **list1, t_list **list2)
{
int i;
pushswap2(list1, list2);
i = list_size(*list2);
while (i > 0)
{
push(list2, list1);
i--;
if (i > 0)
my_putstr("pa ");
else
my_putstr("pa\n");
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<math.h>
char square[9]={'1','2','3','4','5','6','7','8','9'};
char player='X';
int n;
void draw()
{
clrscr();
printf("tic tac toe v1\n");
printf("Player 1(X) - Player 2(O)\n\n");
printf("\t|\t|\t\n");
printf(" %c\t| %c\t| %c\t\n",square[0],square[1],square[2]);
printf("________|_______|________\n");
printf("\t|\t|\t\n");
printf(" %c\t| %c\t| %c\t\n",square[3],square[4],square[5]);
printf("________|_______|________\n");
printf("\t|\t|\t\n");
printf(" %c\t| %c\t| %c\t\n",square[6],square[7],square[8]);
printf("\t|\t|\t\n");
}
void input()
{
char ch;
printf("press no.\n");
scanf("%d",&n);
switch(ch)
{
case 1:
if(square[0]=='1')
{
square[0]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 2:
if(square[1]=='2')
{
square[1]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 3:
if(square[2]=='3')
{
square[2]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 4:
if (square[3]=='4')
{
square[3]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 5:
if(square[4]=='5')
{
square[4]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 6:
if(square[5]=='6')
{
square[5]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 7:
if (square[6]=='7')
{
square[6]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 8:
if(square[7]=='8')
{
square[7]=player;
}
else
{
printf("its already entered plz try again\n");
}
case 9:
if(square[8]=='9')
{
square[8]=player;
}
else
{
printf("its already entered plz try again\n");
}
}
}
void toggleplayer()
{
if(player=='X')
{
player='O';
}
else
{
player='X';
}
}
char win()
{
if(square[0]=='X' && square[1]=='X' && square[2]=='X')
{
return 'X';
}
if(square[3]=='X' && square[4]=='X' && square[5]=='X')
{
return 'X';
}
if(square[6]=='X' && square[7]=='X' && square[8]=='X')
{
return 'X';
}
if(square[0]=='X'&& square[4]=='X' && square[8]=='X')
{
return 'X';
}
if(square[2]=='X' && square[4]=='X' && square[6]=='X')
{
return 'X';
}
if(square[0]=='O' && square[1]=='O' && square[2]=='O')
{
return 'O';
}
if(square[3]=='O' && square[4]=='O' && square[5]=='O')
{
return 'O';
}
if(square[6]=='O'&& square[7]=='O'&& square[8]=='O')
{
return 'O';
}
if(square[0]=='O'&& square[4]=='O'&& square[8]=='O')
{
return 'O';
}
if(square[2]=='O'&& square[4]=='O'&& square[6]=='O')
{
return 'O';
}
return -1;
}
void main()
{
n=0;
draw();
while(1)
{
n++;
input();
draw();
if(win()=='X')
{
printf(" player X wins\n");
break;
}
else if(win()=='O')
{
printf(" player O wins\n");
break;
}
else if(win()=='/'|| n==9)
{
printf("draw \n");
break;
}
toggleplayer();
}
}
|
C
|
#pragma once
#include <Windows.h>
#include "register.h"
typedef void(*function)();
typedef struct uThread{
registers regs;//ebp 0h;ֲй,esp 4hʼָջ,ebx 8h,edi ch,esi 10h,eip 14hָһָĵַ
function func;//18h
void *stack;//1ch Ϊ̵߳Ķջ
int stackSize;//20hh ջС
DWORD sleepTime;//24h ˯߿ʼʱ---ֻstatusΪUtStatusSleepʱ
DWORD sleepDuri;//28h ˯߳ʱ---ֻstatusΪUtStatusSleepʱ
struct uThread * next;//2ch ָеһ̣߳Ƶȱ
int status;//30h ߳״̬
}*uThd;
registers pregs;//߳ⲿģ
//һ߳
uThd uThreadCreated(void *stack, int stackSize, function func);
uThd uThreadCreate(function func);
//һ̣߳next
void uThreadDestory(uThd u);
//ʼлָ
void utResume(uThd u);
//Ȩ
void utYield();
//˯
void utSleep(DWORD duri);
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int altura;
int countdireita;
int countesquerda;
int number;
struct node *left;
struct node *right;
}node;
struct arvore
{
int cont;
node **pai;
};
typedef struct arvore arvore;
node *add(int n2, node *noderaiz)
{
node *node2;
node2 = (struct node *)malloc(sizeof(struct node));
node2->number = n2;
int n1 = noderaiz->number;
if (n1 > n2)
{
noderaiz->right = node2;
printf("%d \n", noderaiz->right->number);
printf("w \n");
}
else
{
noderaiz->left = node2;
printf("%d \n", noderaiz->left->number);
printf("a \n");
}
return noderaiz;
}
node *insereno(node *noadd, int n)
{
noadd = (node *)malloc(sizeof(node));
noadd->left = NULL;
noadd->right = NULL;
noadd->number = n;
return noadd;
}
node *nodeadda(node *noadd, int n)
{
int contadireita = 0, contaesquerda = 0;
while (1)
{
if (noadd->number > n)
{
noadd = noadd->left;
contadireita++;
if (noadd == NULL)
{
noadd = insereno(noadd, n);
noadd->countdireita = contadireita;
noadd->altura = contadireita + contaesquerda;
printf("e %d \n",noadd->altura);
break;
}
}
else
{
noadd = noadd->right;
contaesquerda++;
if (noadd == NULL)
{
noadd = insereno(noadd, n);
noadd->countesquerda = contaesquerda;
noadd->altura = contadireita + contaesquerda;
printf("o %d \n",noadd->altura);
break;
}
}
}
return noadd;
}
arvore *atualiza(arvore *arvore1, node *contado)
{
int i;
i = arvore1->cont;
arvore1->pai[i] = contado;
arvore1->cont++;
printf("%d", arvore1->cont);
return arvore1;
}
arvore *crianoinicial(node *noinicial, arvore *arvore1, int n)
{
arvore1->pai = (node **)malloc(n * sizeof(node *));
arvore1->pai[0] = noinicial;
return arvore1;
}
arvore *countdireita(node *contado, int n)
{
int i3 = 0;
int i = 0;
arvore *arvore1;
arvore1 = (arvore *)malloc(sizeof(arvore));
crianoinicial(contado, arvore1, n);
while (i3 == 0)
{
if (contado->right == NULL)
{
i3 = 1;
}
else
{
arvore1 = atualiza(arvore1, contado->right);
contado = contado->right;
i++;
printf("z");
}
}
return arvore1;
}
arvore *countesquerda(node *contado, int n)
{
int i3 = 0;
arvore *arvore1;
arvore1 = (arvore *)malloc(sizeof(arvore));
crianoinicial(contado, arvore1, n);
while (i3 == 0)
{
if (arvore1->pai == NULL)
{
i3 = 1;
}
else
{
atualiza(arvore1, contado->left);
}
}
return arvore1;
}
int temfilho(node *pai, int n)
{
int n1, n2;
arvore *arvore1;
arvore1 = (arvore *)malloc(sizeof(arvore));
arvore1 = countdireita(pai, n);
arvore1 = countesquerda(pai, n);
n2 = arvore1->cont;
if (n2 >= 1)
{
return 1;
}
else
{
return 0;
};
}
arvore *carrega(arvore *arvorecarga, arvore *arvorecarregar)
{
int i, n, iinicio;
iinicio = arvorecarregar->cont;
n = arvorecarregar->cont + arvorecarga->cont;
arvorecarregar->pai = (node **)realloc(arvorecarregar->pai, arvorecarga->cont * sizeof(node));
for (i = iinicio; i < n; i++)
{
arvorecarregar->pai[i] = arvorecarga->pai[i - iinicio];
}
arvorecarregar->cont = n;
return arvorecarregar;
}
void flush_in()
{
int ch;
while ((ch = fgetc(stdin)) != EOF && ch != '\n')
{
}
}
arvore *abreesquerda(arvore *arvore1, arvore *arvoreg, int n)
{
int i;
node *noarvore;
for (i = 0; i < arvore1->cont; i++)
{
noarvore = arvore1->pai[i];
if (temfilho(noarvore, n) == 1)
{
arvore1 = countesquerda(arvore1->pai[i], n);
arvoreg = carrega(arvore1, arvoreg);
}
}
return arvoreg;
}
int converte(node *raiz)
{
if (raiz == NULL)
{
return 1;
}
else
{
return 0;
}
}
node *inicia_no(node *no)
{
no = (node *)malloc(sizeof(node));
no->left = NULL;
no->right = NULL;
return no;
}
void busca2(node *no, int n)
{
if (no == NULL)
{
return;
}
else if (no->number == n)
{
printf("o numero foi encontrado \n");
return;
}
busca2(no->left, n);
busca2(no->right, n);
printf("o numero nao foi encontrado \n");
}
void busca(int n2, node *raiz)
{
int n1;
int bool2 = 0;
bool2 = converte(raiz);
if (bool2 == 1)
{
printf(" o no esta nulo \n");
}
n1 = raiz->number;
while (bool2 == 0)
{
if (n1 > n2)
{
raiz = raiz->right;
}
else
{
raiz = raiz->left;
}
if (raiz == NULL || n1 == n2)
{
bool2 = 1;
}
else
{
bool2 = 0;
n1 = raiz->number;
}
}
if (n2 == n1)
{
printf("o numero foi encontrado \n");
}
else
{
printf("o numero nao foi encontrado \n");
}
//return raiz;
}
int tamanhohierarquia(node *pai, int n)
{
int n1, i;
arvore *arvore1;
arvore *arvoreg;
arvore *arvore2;
node *noarvore;
int *temfilho;
arvore1 = countdireita(pai, n);
arvoreg = (arvore *)malloc(sizeof(arvore));
arvoreg = carrega(arvore1, arvoreg);
abreesquerda(arvore1, arvoreg, n);
}
node *desenharvore(node *no)
{
char resposta;
resposta = 's';
int n;
node *noadd;
noadd = inicia_no(noadd);
int i = 0;
while (resposta == 's')
{
printf("digite o valor a ser colocado na arvore \n");
scanf("%d", &n);
flush_in();
if (i == 0)
{
noadd->number = n;
}
no = nodeadda(noadd, n);
printf("voce deseja criar um novo no digite s para sim ou n para nao \n");
scanf("%c", &resposta);
flush_in();
i++;
}
return no; //arvore1;
}
int main()
{
node *raiz, *no;
int n;
//arvore1=desenharvore(raiz,no);
no = desenharvore(no);
//printf("%d",countdireita(arvore1.pai[0], n)->cont);
printf("digite um valor para ser buscado \n");
scanf("%d", &n);
busca2(no, n);
return 0;
}
|
C
|
#include <stdio.h>
#include "type.h"
#include "SHA224.h"
/*ʼϣֵ*/
static const u32 SHA224_H[8] = { 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4};
/*ȫֱÿϣֵ*/
u32 SHA224_H1[8];
/*ʼ*/
static const u32 SHA224_K[64] =
{ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
/*************************************************
*function name:Byte2Word
*function:ֽϳ
*input:byte-ֽ len-ֽڳ,ȱΪ4ı
*output:word-
**˺Ϊģʽֽڴڵ͵ַ
**************************************************/
static void Byte2Word(u8 *byte,u32 *word,u8 len)
{
u8 i;
for(i=0;i<len;i+=4)
*(word+i/4) = *(byte+i)<<24 | *(byte+i+1)<<16 | *(byte+i+2)<<8 | *(byte+i+3);
}
/*************************************************
*function name:Word2Byte
*function:ֲֽ
*input:word-
*output:byte-ֽ
**˺Ϊģʽֽڴڵ͵ַ
**************************************************/
static void Word2Byte(u32 word, u8 *byte)
{
u8 i;
for(i=0;i<4;i++)
byte[i] = (u8)(word>>(8*(3-i)))&0xff;
}
/*************************************************
*function name:ROL
*function:ѭ
*input:data-32λ,len-λ
*output:32λ
**************************************************/
static u32 ROL(u32 data,u8 len)
{
u32 l,r;
l = data<<len;
r = data>>(32-len);
return (l|r);
}
/*************************************************
*function name:ROR
*function:ѭ
*input:data-32λ,len-λ
*output:32λ
**************************************************/
static u32 ROR(u32 data,u8 len)
{
u32 l,r;
r = data>>len;
l = data<<(32-len);
return (l|r);
}
/*************************************************
*function name:ExtendPlaintext
*function:չ飬80
*input: data-(ֽ)
*output:w-
**************************************************/
static void ExtendPlaintext(u8 *data,u32 *w)
{
u8 i;
u32 s[2]={0};
Byte2Word(data,w,64);//w[0]-w[15]
for(i=16;i<64;i++)
{
s[0] = ROR(w[i-15],7)^ROR(w[i-15],18)^(w[i-15]>>3);
s[1] = ROR(w[i-2],17)^ROR(w[i-2],19)^(w[i-2]>>10);
w[i] = w[i-16]+s[0]+w[i-7]+s[1];//
}
}
/*************************************************
*function name:Sha224Process
*function:SHA224ܹ
*input: data-(ֽ)
*output:w-
**************************************************/
static void Sha224Process(u8 *data)
{
u8 i;
u32 w[64];//64
u32 S1,ch,temp1,S0,maj,temp2;//м
u32 a,b,c,d,e,f,g,h;
ExtendPlaintext(data,w);//չ飬80
a=SHA224_H1[0]; b=SHA224_H1[1]; c=SHA224_H1[2]; d=SHA224_H1[3]; e=SHA224_H1[4]; f=SHA224_H1[5]; g=SHA224_H1[6]; h=SHA224_H1[7];//һֹϣֵ
for(i = 0;i<64;i++)//64ּ
{
S1 = ROR(e,6)^ROR(e,11)^ROR(e,25);
ch = (e&f)^((~e)&g);
temp1 = h+S1+ch+SHA224_K[i]+w[i];
S0 = ROR(a,2)^ROR(a,13)^ROR(a,22);
maj = (a&b)^(a&c)^(b&c);
temp2 = S0+maj;
h = g;
g = f;
f = e;
e = d + temp1;
d = c;
c = b;
b = a;
a = temp1+temp2;
}
SHA224_H1[0] +=a;
SHA224_H1[1] +=b;
SHA224_H1[2] +=c;
SHA224_H1[3] +=d;
SHA224_H1[4] +=e;
SHA224_H1[5] +=f;
SHA224_H1[6] +=g;
SHA224_H1[7] +=h;
}
/*************************************************
*function name:SHA224
*function:ͨԿļϢժҪ
*input: plaintext-ģlen-ij(ֽ)
*output:ciphertext-ϢժҪ
**ȣ2^64 bit,ijΪ2^32 Byte,4GB
**ժҪȣ224 bit
**************************************************/
void SHA224(u8 *plaintext,u32 bytelen, u8 *ciphertext)
{
u8 i;
u8 data[64]; //һ64ֽ
u32 bitlen[2]={0}; //س
for(i=0;i<8;i++) //ʼϣֵֵ
SHA224_H1[i] = SHA224_H[i];
while(bytelen>=64) //ijȴڷ鳤
{
for(i=0;i<64;i++)
data[i] = *plaintext++;
bytelen -=64; //ֽڳȼ64
if(bitlen[0] == 0xfffffe00) //سȴ0xffffffff,λ
{
bitlen[1]+=1;
bitlen[0] = 0;
}
else
bitlen[0] +=512;//سȼ512
Sha224Process(data);//
}
for(i=0;i<bytelen;i++)//ʣֽ
{
data[i] = *plaintext++;
if(bitlen[0] == 0xfffffff8) //سȴ0xffffffff,λ
{
bitlen[1]+=1;
bitlen[0] = 0;
}
else
bitlen[0] +=8;//سȼ
}
data[bytelen]=0x80;//ֱӲ1ֽڣ1000 0000
bytelen++;
/*ֽںʣֽڷ3:=56<56>56*/
if(bytelen == 56)//1ijȣbit
{
Word2Byte(bitlen[1],&data[56]);
Word2Byte(bitlen[0],&data[60]);
Sha224Process(data);//
}
else if(bytelen < 56)//2ֽ
{
for(i=bytelen;i<56;i++)
data[i] = 0x00;
Word2Byte(bitlen[1],&data[56]);//ijȣbit
Word2Byte(bitlen[0],&data[60]);
Sha224Process(data);//
}
else if(bytelen >56)//3ֽ
{
for(i=bytelen;i<64;i++)
data[i] = 0x00;
Sha224Process(data);//
for(i=0;i<56;i++)//ֽ
data[i] = 0x00;
Word2Byte(bitlen[1],&data[56]);//ijȣbit
Word2Byte(bitlen[0],&data[60]);
Sha224Process(data);//
}
/*ɣϣֵתΪֽ*/
for(i=0;i<7;i++)
Word2Byte(SHA224_H1[i],ciphertext+4*i);
}
|
C
|
#include "header.h"
unsigned int get_v1(t_vm *vm, int i)
{
if (vm->procs[i]->instruc.type_params[0] == T_REG
&& reg_correct(vm->procs[i]->instruc.params[0]))
return (get_value_inside_reg((unsigned char *)
vm->procs[i]->reg[vm->procs[i]->instruc.params[0] - 1]));
else if (vm->procs[i]->instruc.type_params[0] == T_IND)
return (get_value_from_mem((unsigned char *)vm->mem,
vm->procs[i]->instruc.params[0]));
else
return (vm->procs[i]->instruc.params[0]);
}
unsigned int get_v2(t_vm *vm, int i)
{
if (vm->procs[i]->instruc.type_params[1] == T_REG
&& reg_correct(vm->procs[i]->instruc.params[1]))
return (get_value_inside_reg((unsigned char *)
vm->procs[i]->reg[vm->procs[i]->instruc.params[1] - 1]));
else if (vm->procs[i]->instruc.type_params[1] == T_IND)
return (get_value_from_mem((unsigned char *)vm->mem,
vm->procs[i]->instruc.params[1]));
else
return (vm->procs[i]->instruc.params[1]);
}
void background_bitwise_op(t_vm *vm, int i, int op)
{
unsigned int v1;
unsigned int v2;
v1 = get_v1(vm, i);
v2 = get_v2(vm, i);
if (vm->procs[i]->instruc.nb_params == 3 &&
vm->procs[i]->instruc.type_params[2] == T_REG &&
(vm->procs[i]->instruc.params[2] <= REG_NUMBER)
&& (vm->procs[i]->instruc.params[2] > 0))
{
if (op == AND)
put_value_inside_reg((unsigned char *)vm->procs[i]->
reg[vm->procs[i]->instruc.params[2] - 1], v1 & v2);
else if (op == OR)
put_value_inside_reg((unsigned char *)vm->procs[i]->
reg[vm->procs[i]->instruc.params[2] - 1], v1 | v2);
else
put_value_inside_reg((unsigned char *)vm->procs[i]->
reg[vm->procs[i]->instruc.params[2] - 1], v1 ^ v2);
vm->procs[i]->carry = ((get_value_inside_reg(
(unsigned char *)vm->procs[i]->reg[vm->procs[i]->
instruc.params[2] - 1]) == 0) ? 1 : 0);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <sys/resource.h>
#include <unistd.h>
static void pr_times(clock_t, struct tms *, struct tms *);
static void do_cmd(char *);
int main(int argc, char *argv[]) {
int i;
setbuf(stdout, NULL);
for (i = 1; i < argc; ++i) {
do_cmd(argv[i]);
}
return 0;
}
static void pr_times(clock_t real, struct tms *start, struct tms *end) {
static long clk = 0;
if (clk == 0) {
if ((clk = sysconf(_SC_CLK_TCK)) < 0) {
printf("sysconf error");
exit(1);
}
}
printf(" real : %7.2f\n", real * 1.0 / clk);
printf(" user : %7.2f\n", (end->tms_utime - start->tms_utime) * 1.0 / clk);
printf(" sys : %7.2f\n", (end->tms_stime - start->tms_stime) * 1.0 / clk);
printf(" child user : %7.2f\n", (end->tms_cutime - start->tms_cutime) * 1.0 / clk);
printf(" child sys : %7.2f\n", (end->tms_cstime - start->tms_cstime) * 1.0 / clk);
}
static void do_cmd(char *cmd) {
struct tms tms_start, tms_end;
clock_t start, end;
int status;
printf("\n command : %s\n", cmd);
if ((start = times(&tms_start)) == -1) {
printf("times error");
exit(1);
}
if ((status = system(cmd)) < 0) {
printf("system() error");
exit(1);
}
if ((end = times(&tms_end)) == -1) {
printf("times error");
exit(1);
}
pr_times(end - start, &tms_start, &tms_end);
}
|
C
|
/**
******************************************************************************
* @file exercise3.c
* @author MDS, NPG
* @date 05122017
* @brief Enable the ADC1 on pin A0.
* See Section 13 (ADC), P385 of the STM32F4xx Reference Manual.
******************************************************************************
*
*/
/* Includes ------------------------------------------------------------------*/
#include "board.h"
#include "stm32f4xx_hal_conf.h"
#include "debug_printf.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef AdcHandle;
ADC_ChannelConfTypeDef AdcChanConfig;
/* Private function prototypes -----------------------------------------------*/
void Hardware_init(void);
/* Private functions ---------------------------------------------------------*/
/**
* @brief Main program
* @param None
* @retval None
*/
int main(void)
{
unsigned int adc_value;
BRD_init();
Hardware_init();
/* Infinite loop */
while (1)
{
HAL_ADC_Start(&AdcHandle); // Start ADC conversion
// Wait for ADC conversion to finish
while (HAL_ADC_PollForConversion(&AdcHandle, 10) != HAL_OK);
adc_value = (uint16_t)(HAL_ADC_GetValue(&AdcHandle));
// Print ADC conversion values
debug_printf("ADC Value: %X Voltage: %lf\n\r",adc_value, (adc_value/1240.0));
BRD_LEDBlueToggle();
HAL_Delay(1000);
}
}
/**
* @brief Initialise Hardware
* @param None
* @retval None
*/
void Hardware_init(void) {
BRD_LEDInit(); //Initialise LEDS
/* Turn off LEDs */
BRD_LEDRedOff();
BRD_LEDGreenOff();
BRD_LEDBlueOff();
GPIO_InitTypeDef GPIO_InitStructure;
__BRD_A0_GPIO_CLK();
GPIO_InitStructure.Pin = BRD_A0_PIN;
GPIO_InitStructure.Mode = GPIO_MODE_ANALOG;
GPIO_InitStructure.Pull = GPIO_NOPULL;
HAL_GPIO_Init(BRD_A0_GPIO_PORT, &GPIO_InitStructure);
__ADC1_CLK_ENABLE();
AdcHandle.Instance = (ADC_TypeDef *)(ADC1_BASE); //Use ADC1
AdcHandle.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV2; //Set clock prescaler
AdcHandle.Init.Resolution = ADC_RESOLUTION12b; //Set 12-bit data resolution
AdcHandle.Init.ScanConvMode = DISABLE;
AdcHandle.Init.ContinuousConvMode = DISABLE;
AdcHandle.Init.DiscontinuousConvMode = DISABLE;
AdcHandle.Init.NbrOfDiscConversion = 0;
AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; //No Trigger
AdcHandle.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T1_CC1; //No Trigger
AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT; //Right align data
AdcHandle.Init.NbrOfConversion = 1;
AdcHandle.Init.DMAContinuousRequests = DISABLE;
AdcHandle.Init.EOCSelection = DISABLE;
HAL_ADC_Init(&AdcHandle); //Initialise ADC
/* Configure ADC Channel */
AdcChanConfig.Channel = BRD_A0_ADC_CHAN; //Use AO pin
AdcChanConfig.Rank = 1;
AdcChanConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
AdcChanConfig.Offset = 0;
HAL_ADC_ConfigChannel(&AdcHandle, &AdcChanConfig); //Initialise ADC channel
}
|
C
|
#include "student.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Student *new_student(const char name[], unsigned int id, float shoe_size){
Student *s;
s = malloc(sizeof(Student));
if(name == NULL){
s->name = malloc(1);
s->name = "";
}
else{
s->name = malloc(strlen(name) + 1);
strcpy(s->name,name);
}
s->id = id;
s->shoe_size = shoe_size;
return s;
}
unsigned int has_id(Student *const student, unsigned int id){
if(student == NULL)
return 0;
if(student->id == id)
return 1;
return 0;
}
unsigned int has_name(Student *const student, const char name[]){
if(student == NULL || name == NULL || student->name == NULL)
return 0;
if(strcmp(student->name,name) == 0)
return 1;
return 0;
}
unsigned int get_id(Student *const student){
if(student == NULL)
return 0;
return student->id;
}
float get_shoe_size(Student *const student){
if(student == NULL)
return 0.0;
return student->shoe_size;
}
void change_shoe_size(Student *const student, float new_shoe_size){
if(student != NULL)
student->shoe_size = new_shoe_size;
}
void change_name(Student *const student, const char new_name[]){
if(student != NULL){
if(new_name == NULL){
student->name = realloc(student->name, 1);
student->name = "";
}
else{
student->name = realloc(student->name, sizeof(new_name));
strcpy(student->name, new_name);
}
}
}
void copy_student(Student *student1, Student *const student2){
if(student1 != NULL || student2 != NULL){
student1->id = get_id(student2);
change_shoe_size(student1,get_shoe_size(student2));
change_name(student1,student2->name);
}
}
|
C
|
#include "pstring.h"
char * pstrcpy(char * __restrict destination, char * __restrict source) {
if (destination == NULL) {
// destination is not allocated.
return NULL;
}
char * origin = source;
while(*destination++ = *source++);
return origin;
}
|
C
|
#include "search.h"
//Function to bubble_sort
int bubble_sort (int array[], int size)
{
int i , j;
//Loop to sort elements
for (i = 0; i < size; i++)
{
for (j = 0; j < size-i-1; j++)
{
if (array[j] > array[j+1])
{
swap(&array[j],&array[j+1]);
}
}
}
return SUCCESS;
}
|
C
|
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
*
* src/mailbox.c
*
* BCM2835 VideoCore mailboxes
*
* Author: Daniel Kudrow ([email protected])
* Date: March 7 2014
*
* Copyright (c) 2014, Daniel Kudrow
* All rights reserved, see LICENSE.txt for details.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
*
* The mailbox is the main point of communication between the ARM Core and
* the VideoCore. Before I go on, mailboxes are covered extensively here:
* https://github.com/raspberrypi/firmware/wiki/ so for a more thorough
* treatment look there. The mailbox contains channels that allow the ARM
* Core to communicate to different elements within the VC. The mailbox is
* laid out as follows:
*
* Mailbox base: 0x2000B880
*
* offset function
* ---------------------
* 0x00 Read
* 0x10 Peek
* 0x14 Sender
* 0x18 Status
* 0x1C Config
* 0x20 Write
*
* Messages are 32 bits arranged as follows:
*
* ---------------------------
* | 31:4 DATA | 3:0 CHANNEL |
* ---------------------------
*
* Be wary when writing addresses to the mailbox - the bottom 4 bits will
* be clobbered by the channel so make certain that the address is aligned
* to a 16-byte boundary. Also, addresses are read by the VC's MMU so
* physical addresses must start at 0x40000000 (L2 caching enabled) or
* 0x80000000 (L2 caching disabled). Likewise, addresses returned by the
* VC must be translated back into ARM physical addresses by subtracting
* 0x40000000 (or 0x80000000 as the case may be).
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *
*/
#include <errno.h>
#include <mailbox.h>
#include <platform.h>
#include <util.h>
static volatile mailbox_reg_t *mailbox_reg = (mailbox_reg_t *)MBOX_BASE;
#define WRITE_READY (1 << 31)
#define READ_READY (1 << 30)
/*
* Write a message to the VideoCore mailbox
* note: message data is *not* shifted!
*/
int mailbox_write(int channel, uint32_t message)
{
uint32_t reg;
/* validate inputs */
if (channel > MBOX_CHAN_MAX)
return -EINVAL;
if (message & 0xF)
return -EINVAL;
/* message takes upper 28 bits and channel takes lower 4 bits */
reg = (message & ~0xF) | (channel & 0xF);
/* wait for the status register to clear for writing */
/*while (READ4(MBOX_STATUS) & WRITE_READY)*/
while (mailbox_reg->status & WRITE_READY)
;
/* write message to mailbox */
/*WRITE4(MBOX_WRITE, reg);*/
mailbox_reg->write = reg;
return 0;
}
/*
* Read a message from the VideoCore mailbox
* note: message data is *not* shifted!
*/
int mailbox_read(int channel, uint32_t *message)
{
uint32_t reg;
/* validate input */
if (channel > MBOX_CHAN_MAX)
return -EINVAL;
/* loop until we are on the right channel */
do {
/* wait for the status register to clear for reading */
/*while (READ4(MBOX_STATUS) & READ_READY)*/
while (mailbox_reg->status & READ_READY)
;
/* read message to mailbox */
/*reg = READ4(MBOX_READ);*/
reg = mailbox_reg->read;
} while (channel != (reg & 0xF));
/* save message */
*message = reg & ~0xF;
return 0;
}
|
C
|
#include <hash.h>
#include <searchlib.h>
#include <assert.h>
#include <ctype.h>
enum { NHASH = 3571 };
void cswap(char * str, int a, int b) {
char tmp;
tmp = str[a];
str[a] = str[b];
str[b] = tmp;
}
void strsort(char * str, int len) {
int last = 0, i = 0;
if (len == 0)
return;
cswap(str, 0, random() % len);
for (i = 1; i < len; i++) {
if (str[i] < str[0]) {
cswap(str, ++last, i);
}
}
cswap(str, 0, last);
strsort(str, last);
strsort(str+last+1, len-last-1);
}
char * strtolower(char * str) {
int i = 0;
char * ret = strdup(str);
for (i = 0; i < strlen(str); i++) {
ret[i] = tolower(str[i]);
}
return ret;
}
int main() {
int h = 0, cmp = 0, ret = 0, i = 0;
char * sorttest = NULL;
DictNode * anags[NHASH];
DictNode * th[17];
DictNode * dp;
DictList list;
for (i = 0; i < 17; i++) {
th[i] = NULL;
}
for (i = 0; i < NHASH; i++) {
anags[i] = NULL;
}
sorttest = strdup("sorttest");
h = hash("damon", 37);
fprintf(stdout, "%s %u\n", __FUNCTION__, h);
h = hash("da", 17);
fprintf(stdout, "%s %u\n", __FUNCTION__, h);
h = hash("x\"33", 17);
fprintf(stdout, "%s %u\n", __FUNCTION__, h);
h = hash("x3\"3", 17);
fprintf(stdout, "%s %u\n", __FUNCTION__, h);
dp = lookup("damon", th, 0, 17);
assert((dp == NULL) && "lookup for 'damon' succeeded and shouldn't have");
dp = lookup("damon", th, 1, 17);
assert((dp != NULL) && "lookup for 'damon' failed on create");
assert((strcmp("damon", dp->word) == 0) && "'damon' was not created");
dp = lookup("damon", th, 0, 17);
fprintf(stderr, "checking last test %d\n", dp);
assert((dp != NULL) && "lookup for 'damon' failed");
strsort(sorttest, strlen(sorttest));
assert(strcmp("eorssttt", sorttest) == 0 && "string was sorted");
ret = load("/usr/share/dict/web2", &list, -1);
assert(ret > 0 && "sucessfully loaded dictionary file");
for (i = 0; i < list.nval; i++) {
sorttest = strtolower(list.words[i].word);
strsort(sorttest, strlen(sorttest));
/* fprintf(stderr, "looking up %s\n", sorttest); */
dp = lookup(sorttest, anags, 1, NHASH);
dp->value++;
}
for (i = 0; i < NHASH; i++) {
if (anags[i] != NULL) {
dict_node_apply(anags[i], printdn, "%d %-15s\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
int ft_str_is_printable(char *str);
int main(void)
{
char a[] = "\(null)";
char *b = a;
int resultado;
resultado = ft_str_is_printable(b);
printf("resultado: %d", resultado);
return (0);
}
|
C
|
#include <assert.h>
#include "bounds.h"
void bounds( const double *x, int n, double mm[] ) {
// If there is at least one element...
if( n-- > 0 ) {
// ...initialize results from it, and "mark it" as used.
double m = *x;
double M = *x++;
// Continue only as long as there are more elements.
assert( m < M || m == M );
while( n-- > 0 ) {
const double D = *x++;
if( m > D )
m = D;
else // "else" justified by the assert above.
if( M < D )
M = D;
}
// Output is produce IFF there was at least one element.
mm[0] = m;
mm[1] = M;
}
}
#ifdef UNIT_TEST_BOUNDS
#include <stdlib.h>
#include <stdio.h>
#include <alloca.h>
int main( int argc, char *argv[] ) {
const int N = argc - 1;
double *data = alloca( N*sizeof(double) );
double minmax[2];
for(int i = 0; i < N; i++ ) {
data[i] = atof( argv[i+1] );
}
bounds( data, N, minmax );
printf( "[%f, %f] (%d pts)\n", minmax[0], minmax[1], N );
return EXIT_SUCCESS;
}
#endif
|
C
|
#include "hal.h"
#include "drv_pwm.h"
#include "config.h"
#define PULSE_1MS (1000) // 1ms pulse width
#define MWII_PWM_MAX 1000
#define MWII_PWM_PRE 1
// returns whether driver is asking to calibrate throttle or not
bool pwmInit(drv_pwm_config_t *init)
{
CLK_EnableModuleClock(PWM01_MODULE);
CLK_EnableModuleClock(PWM45_MODULE);
// PWM clock source
CLK->CLKSEL1 &= ~(CLK_CLKSEL2_PWM45_S_Msk | CLK_CLKSEL1_PWM01_S_Msk);
CLK->CLKSEL1 |= CLK_CLKSEL2_PWM45_S_HCLK | CLK_CLKSEL1_PWM01_S_HCLK;
// Multifuncional pin set up PWM0-4
//P2.2/3/6
SYS->P2_MFP &= ~(SYS_MFP_P22_Msk | SYS_MFP_P23_Msk | SYS_MFP_P26_Msk);
SYS->P2_MFP |= SYS_MFP_P22_PWM0 | SYS_MFP_P23_PWM1 | SYS_MFP_P26_PWM4;
//P0.4 Pin
SYS->P0_MFP &= ~SYS_MFP_P04_Msk;
SYS->P0_MFP |= SYS_MFP_P04_PWM5;
#define MWII_PWM_MASK ((1 << 0) | (1 << 1) | (1 << 4) | (1 << 5))
// Even channel N and N+1 share prescaler
PWM_SET_PRESCALER(PWM, 0, MWII_PWM_PRE);
PWM_SET_PRESCALER(PWM, 4, MWII_PWM_PRE);
PWM_SET_DIVIDER(PWM, 0, PWM_CLK_DIV_1);
PWM_SET_DIVIDER(PWM, 1, PWM_CLK_DIV_1);
PWM_SET_DIVIDER(PWM, 4, PWM_CLK_DIV_1);
PWM_SET_DIVIDER(PWM, 5, PWM_CLK_DIV_1);
PWM_Start(PWM, MWII_PWM_MASK);
// No analog of PWM_Start for enabling auto-reload mode
PWM->PCR |= PWM_PCR_CH0MOD_Msk << (4 * 0);
PWM->PCR |= PWM_PCR_CH0MOD_Msk << (4 * 1);
PWM->PCR |= PWM_PCR_CH0MOD_Msk << (4 * 4);
PWM->PCR |= PWM_PCR_CH0MOD_Msk << (4 * 5);
// Duty
PWM_SET_CMR(PWM, 0, 0);
PWM_SET_CMR(PWM, 1, 0);
PWM_SET_CMR(PWM, 4, 0);
PWM_SET_CMR(PWM, 5, 0);
// Period, actually sets it to safe value 1000+1
PWM_SET_CNR(PWM, 0, MWII_PWM_MAX);
PWM_SET_CNR(PWM, 1, MWII_PWM_MAX);
PWM_SET_CNR(PWM, 4, MWII_PWM_MAX);
PWM_SET_CNR(PWM, 5, MWII_PWM_MAX);
PWM_EnableOutput(PWM, MWII_PWM_MASK);
return false;
}
void pwmWriteMotor(uint8_t index, uint16_t value)
{
// Motor 0 BACK_R - PWM0
// Motor 1 FRONT_R - PWM1
// Motor 2 BACK_L - PWM4
// Motor 3 FRONT_L - PWM5
static uint8_t motor_to_pwm[] = { 0, 1, 4, 5 };
if (index > 3) return;
PWM_SET_CMR(PWM, motor_to_pwm[index], value-1000);
}
// Not implmented
//void pwmWriteServo(uint8_t index, uint16_t value)
//{
//}
//uint16_t pwmRead(uint8_t channel)
//{
// return 0;
//}
|
C
|
//receber valores em um vetor e imprimir ORDENADO se o vetor estiver em ordem crescente
#include <stdio.h>
#include <stdlib.h>
int bubbleSort(int *vetor, int n);
int main(){
int n = 5;
int vetor[5] = {1, 2, 3, 4, 5};
if(bubbleSort(vetor, n)){
for(int i = 0; i < n; i++)
printf("%d ", vetor[i]);
}
puts("");
return 0;
}
int bubbleSort(int *vetor, int n){
int i, j;
int teste = 1;
for(i = 0; i < n-1; i++){
teste = 1;
for(j = i+1; j < n; j++){
if(vetor[i] > vetor[j]){
teste = 0;
break;
}
}
if(!teste)
break;
}
return teste;
}
|
C
|
#include "common.h"
int main()
{
s_array *s = malloc(sizeof(s_array));
//validation
if(s == NULL)
{
printf("memory allocation unsuccessful\n");
exit(0);
}
s->top = -1;
data_t data;
int opt, status;
while(1)
{
printf("Enter the option 1. PUSH\n 2. POP\n 3. PEEP\n 4. PEAK \n");
scanf("%d", &opt);
printf("\n");
switch(opt)
{
case 1:
{
printf("Enter the data to push\n");
scanf("%d", &data);
status = PUSH(s, data);
if(status == SUCCESS)
{
printf("data pushed successfylly into the stack\n");
}
else
{
printf("Data push unsuccessful\n");
}
break;
}
case 2:
{
status = POP(s, &data);
if(status == SUCCESS)
{
printf("data popped out successfylly from the stack is : %d \n", data);
}
else
{
printf("Data pop unsuccessful\n");
}
break;
}
case 3:
{
status = PEEP(*s);
if(status == SUCCESS)
{
printf("Print successful\n");
}
else if(status == STACK_OVERFLOW)
{
printf("STACK_OVERFLOW\n");
}
else
{
printf("STACK_UNDERFLOW\n");
}
break;
}
case 4:
{
status = PEAK(s, &data);
if(status == SUCCESS)
{
printf("The peak data from the stack is : %d \n", data);
}
else
{
printf("Data finding unsuccessful\n");
}
break;
}
default:
{
printf("Enter the correct option\n");
}
}
}
}
|
C
|
#include "p5lib.h"
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Example 5-2: More conditionals
// Three variables for the background color.
float r = 0;
float b = 0;
float g = 0;
void setup() {
p5_size(480,270);
p5_frameRate(10);
}
void draw() {
// Color the background and draw lines to divide the window in quadrants.
p5_backgroundRGB(r,g,b);
p5_stroke(255);
p5_line(p5_width/2,0,p5_width/2,p5_height);
p5_line(0,p5_height/2,p5_width,p5_height/2);
// If the mouse is on the right hand side of the window, increase red.
// Otherwise, it is on the left hand side and decrease red.
if (p5_mouseX > p5_width/2) {
r = r + 1;
} else {
r = r - 1;
}
// If the mouse is on the bottom of the window, increase blue.
// Otherwise, it is on the top and decrease blue.
if (p5_mouseY > p5_height/2) {
b = b + 1;
} else {
b = b - 1;
}
// If the mouse is pressed (using the system variable mousePressed)
if (p5_mousePressed) {
g = g + 1;
} else {
g = g - 1;
}
// Constrain all color values to between 0 and 255.
r = p5_constrain(r,0,255);
g = p5_constrain(g,0,255);
b = p5_constrain(b,0,255);
}
int main(int argc, char** argv) {
p5_setupFunc(setup);
p5_drawFunc(draw);
p5_init(argc,argv);
}
|
C
|
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
char buffer[1000];
int i;
int rtn;
while ((rtn = read(0, buffer, 1000)) > 0)
{
for(i = 0; i < rtn; i++)
if(islower(buffer[i]))
buffer[i] = toupper(buffer[i]);
write(1, buffer, rtn);
write(1, "\n", 1);
}
exit(10);
}
|
C
|
/*
<< ˰ >>
- :
prim ˰ Ͽ Ʈ ܰ Ȯس ̴.
ܰ迡 Ʈ տ Եȴ.
prim Ʈտ, ߿ Ͽ Ʈ ȮѴ.
Ʈ n-1 ӵȴ.
Ʒ ̹ Ʈ տ { a, f } ԵǾ ִ.
¿ Ʈ տ 캸 be ִ.( a, b ) ( f, e ) ġ ( f, e ) 27μ ( a, b ) 29 .
( f, e ) õǰ e Ʈ տ Եȴ.
ܰ迡 Ʈ { a, f, e } ǰ Ǯ ȴ.
Ʈ տ n-1 ӵȴ.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define VERTICES 7 /* */
#define INF 1000L /* ( ) */
int adj_mat[VERTICES][VERTICES] = //
{
/// a, b, c, d, e, f, g
{ 0, 29, INF, INF, INF, 10, INF }, // a
{ 29, 0, 16, INF, INF, INF, 15 }, // b
{ INF, 16, 0, 12, INF, INF, INF }, // c
{ INF, INF, 12, 0, 22, INF, 18 }, // d
{ INF, INF, INF, 22, 0, 27, 25 }, // e
{ 10, INF, INF, INF, 27, 0, INF }, // f
{ INF, 15, INF, 18, 25, INF, 0 } // g
};
int selected[VERTICES]; // 湮ǥø ϱ 迭
int dist[VERTICES]; // ּҰ ϱ 迭
int get_min_vertex(int n); // ּ dist[v] ȯ
void prim(int s, int n); // prim Լ
void main() // Ʈ
{
printf("\n <prim ˰> \n");
printf("\n ־ prim ּҺ Ʈ ˷ݴϴ.");
printf("\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
printf("\n + +");
printf("\n + [a]-------29------[b] +");
printf("\n + / / ( +");
printf("\n + / / ( +");
printf("\n + 10 15 16 +");
printf("\n + / / ( +");
printf("\n + / / ( +");
printf("\n + [f] [g] [c] +");
printf("\n + ( / ( / +");
printf("\n + ( / ( / +");
printf("\n + 27 25 18 12 +");
printf("\n + ( / ( / +");
printf("\n + ( / ( / +");
printf("\n + [e]------22-------[d] +");
printf("\n + +");
printf("\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
prim(0, VERTICES);
}
void prim(int s, int n)
{
int i, u, v, min = 0;
// i = ȣ
// u = 湮
// v = 湮
// min = ּҰŸ
for (u = 0; u < n; u++)
{
dist[u] = INF; // ּҰ ʱȭ
}
dist[s] = 0; // ù 湮Ÿ 0
for (i = 0; i<n; i++)
{
u = get_min_vertex(n);
selected[u] = TRUE; // 湮ǥ
if (dist[u] == INF)
{
return;
}
min += dist[u]; // 湮Ÿ ϱ
printf("\n\t %d° %c湮 Ÿ=%d, ּ =%d \n", i, u + 65, dist[u], min);
for (v = 0; v < n; v++)
{
if (adj_mat[u][v] != INF) // 湮 ߿ 湮 ְ ִ°
{
if (!selected[v] && adj_mat[u][v] < dist[v]) // 湮 ̸鼭, ª ϴ
{
dist[v] = adj_mat[u][v];
}
}
}
}
printf("\n");
}
int get_min_vertex(int n) // ּ dist[v] ȯ
{
int v, i;
// v = i
// i = 湮
for (i = 0; i < n; i++)
{
if (!selected[i]) // 湮 ã ۾
{
v = i;
break;
}
}
for (i = 0; i < n; i++)
{
if (!selected[i] && (dist[i] < dist[v])) // 湮 ߿ Ÿ ª ã ۾
{
v = i;
}
}
return (v);
}
|
C
|
void createGraphics()
{
int tmp[4][2] = { {0,1},{1,0},{-1,0},{0,-1} }; //上 右 左 下
memset(map, 0, sizeof(map));//把圖初始化為0
for (i = 0; i < row*column; i++)
{
//找到該點上下左右4個點初始map
int r = i / column;//X軸座標
int c = i % column;//Y軸座標
for (j = 0; j < 4; j++)//每個點最多有4個路徑
{
//(r,c)相鄰的點為(r1,c1)
int r1 = r + tmp[j][0];
int c1 = c + tmp[j][1]; //偵測路徑
if (r1 >= 0 && r1 < row&&c1 >= 0 && c1 < column)//限制圖的大小
{
map[i][r1*column + c1] = 1;//把會用到的路徑設為1
}
}
}
}
|
C
|
/* LINKSYNC.C
:Electronic gearing with synchronization based on I/O sensors.
This sample code link's two axes together and commands a velocity move on the
master axis. During the motion, the actual position of the slave axis is
displayed based on two input sensors. For this sample, the index inputs are
used as the input sensors.
Based on keyboard input, a synchronization routine adjusts the offset distance
between the input sensors.
Here is the synchronization algorithm:
1) Read the slave's position when the first sensor goes high.
2) Read the slave's position when the second sensor goes high.
3) Calculate the offset distance.
4) Command a motion to compensate for the offset distance.
Warning! This is a sample program to assist in the integration of the
DSP-Series controller with your application. It may not contain all
of the logic and safety features that your application requires.
Written for Version 2.5
*/
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
# include <math.h>
# include "pcdsp.h"
# define MASTER 0
# define SLAVE 1
# define VELOCITY 500.0
# define ACCEL 4000.0
# define RATIO 1.0
# define MAX_DIST 8192 /* Slave distance between sensors */
# define SENSOR_PORT 6 /* User I/O port */
# define M_MASK 0x04 /* Master sensor mask */
# define S_MASK 0x40 /* Slave sensor mask */
void error(int16 error_code)
{
char buffer[MAX_ERROR_LEN];
switch (error_code)
{
case DSP_OK:
/* No error, so we can ignore it. */
break ;
default:
error_msg(error_code, buffer) ;
fprintf(stderr, "ERROR: %s (%d).\n", buffer, error_code) ;
exit(1);
break;
}
}
void synchronize(int16 axis, int16 port, int16 m_mask, int16 s_mask)
{
int16 dir, value = 0;
double delta, offset, s_pos_0, s_pos_1;
while (!(value & m_mask)) /* wait for master sensor */
get_io(port, &value);
get_position(axis, &s_pos_0);
while (!(value & s_mask)) /* wait for slave sensor */
get_io(port, &value);
get_position(axis, &s_pos_1);
delta = s_pos_1 - s_pos_0;
if (delta > 0.0)
dir = 1;
else
dir = -1;
printf("\nDir: %d Delta: %6.0lf", dir, delta);
/* Make sure the delta is a fraction of one full sensor cycle. */
delta = fmod((dir * delta), MAX_DIST);
/* Calculate the shortest distance to synchronize the master and slave. */
if (delta > (MAX_DIST / 2.0))
offset = (dir * delta) - (dir * MAX_DIST);
else
offset = (dir * delta);
/* Command a relative move to compensate for the offset distance. */
start_r_move(axis, offset, VELOCITY, ACCEL);
printf("\nOffset: %6.0lf\n\n", offset);
}
void display(int16 axis, int16 sensor_port, int16 m_mask, int16 s_mask)
{
int16 value;
get_io(sensor_port, &value);
if ((value & m_mask) || (value & s_mask))
printf("I/O: 0x0%x Enc: %d\n", value, dsp_encoder(axis));
}
int16 main()
{
int16 error_code, key, done = 0;
error_code = do_dsp(); /* initialize communication with the controller */
error(error_code); /* any problems initializing? */
error(dsp_reset()); /* hardware reset */
set_home_index_config(MASTER, INDEX_ONLY); /* use index for simulation */
set_home_index_config(SLAVE, INDEX_ONLY);
mei_link(MASTER, SLAVE, RATIO, LINK_ACTUAL);
v_move(MASTER, VELOCITY, ACCEL); /* simulate master */
printf("\ns=synchronize, esc=quit\n");
while (!done)
{ display(SLAVE, SENSOR_PORT, M_MASK, S_MASK);
if (kbhit()) /* key pressed? */
{ key = getch();
switch (key)
{
case 's': /* Synchronize */
printf("\nSynchronizing...\n");
synchronize(SLAVE, SENSOR_PORT, M_MASK, S_MASK);
break;
case 0x1B: /* <ESC> */
v_move(MASTER, 0.0, ACCEL); /* Stop the master */
while (!motion_done(MASTER))
;
endlink(SLAVE);
done = TRUE;
break;
}
}
}
return 0;
}
|
C
|
/*
Team 14
Name : Umang Maurya
Roll no : 055
Name : Amardeep Singh(Lata)
Roll no : 009
Name : Yateesh Chandra
Roll no : 057
Name : Sachin Verma
Roll no : 038
*/
#include<stdio.h>
#define input "Input.txt"
#define output "Output.txt"
/***************************************variable declartion**********************************/
char non_terminal[100];
int count_non_terminal=0;
char terminal[200];
int count_terminal=0;
int no_of_production=0;
/***************************************function declartion*********************************/
void readInput();
void writeOutput();
void printOutPut();
void makeCanonical();
void solveSlr();
/****************************************Main File*****************************************/
int main(){
printf("---------------------------------------------------------------\n");
printf("------------------------SLR Parser-----------------------------\n");
printf("---------------------------------------------------------------\n\n");
printf("reading input...\t\t");
readInput();
printf("completed\n");
}
/*********************************function defination*************************************/
void readInput(){ //for reading input from file
FILE *f = fopen(input, "r");
int c = getc(f);
while (c != EOF) {
putchar(c);
c = getc(f);
}
}
void writeOutput(){//for writing output in file
}
void printOutput(){ //for displaying output in monitor
}
void solveSlr(){
}
void makeCanonical(){
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "net.h"
#define BACKLOG 10 // how many pending connections queue will hold
/**
* This gets an Internet address, either IPv4 or IPv6
*
* Helper function to make printing easier.
*/
void *get_in_addr(struct sockaddr *sa) {
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
/**
* Return the main listening socket
*
* Returns -1 or error
*/
int get_listener_socket(char *port) {
int sockfd = 0;
struct addrinfo hints, *servinfo, *p;
int yes = 1;
int rv;
// This block of code looks at the local network interfaces and
// tries to find some that match our requirements (namely either
// IPv4 or IPv6 (AF_UNSPEC) and TCP (SOCK_STREAM) and use any IP on
// this machine (AI_PASSIVE).
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return -1;
}
// Once we have a list of potential interfaces, loop through them
// and try to set up a socket on each. Quit looping the first time
// we have success.
for(p = servinfo; p != NULL; p = p->ai_next) {
// Try to make a socket based on this candidate interface
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
//perror("server: socket");
continue;
}
// SO_REUSEADDR prevents the "address already in use" errors
// that commonly come up when testing servers.
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
close(sockfd);
freeaddrinfo(servinfo); // all done with this structure
return -2;
}
// See if we can bind this socket to this local IP address. This
// associates the file descriptor (the socket descriptor) that
// we will read and write on with a specific IP address.
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
//perror("server: bind");
continue;
}
// If we got here, we got a bound socket and we're done
break;
}
freeaddrinfo(servinfo); // all done with this structure
// If p is NULL, it means we didn't break out of the loop, above,
// and we don't have a good socket.
if (p == NULL) {
fprintf(stderr, "webserver: failed to find local address\n");
return -3;
}
// Start listening. This is what allows remote computers to connect
// to this socket/IP.
if (listen(sockfd, BACKLOG) == -1) {
//perror("listen");
close(sockfd);
return -4;
}
return sockfd;
}
|
C
|
#ifndef STRUCT_STRING_ARRAY
#define STRUCT_STRING_ARRAY
#include <string.h>
typedef struct s_string_array
{
int size;
char **array;
} string_array;
#endif
char *my_join(string_array *param_1, char *param_2)
{
char *strings = malloc(sizeof(char));
int arr_size = param_1->size - 1;
for (int i = 0; i < arr_size; i++)
{
strings = strcat(strings, param_1->array[i]);
strings = strcat(strings, param_2);
}
strings = strcat(strings, param_1->array[arr_size]);
return strings;
}
|
C
|
#include <pebble.h>
static Window *main_window;
static Layer *ticks, *hands;
static TextLayer *date;
static GPath *minute_hand, *hour_hand;
static const GPathInfo MINUTE_HAND_POINTS = {
.num_points = 6,
.points = (GPoint []) {
{2, -72},
{5, -20},
{2, 0},
{-2, 0},
{-5, -20},
{-2, -72}}
};
static const GPathInfo HOUR_HAND_POINTS = {
.num_points = 5,
.points = (GPoint []) {
{0, -50},
{7, -20},
{3, 0},
{-3, 0},
{-7, -20}}
};
typedef struct {
GPoint lower_middle;
int min_size;
int half_min_size;
} LayerInfo;
static LayerInfo get_layer_info(Layer *layer) {
GRect bounds = layer_get_bounds(layer);
int max_size = bounds.size.w < bounds.size.h ?
bounds.size.h :
bounds.size.w;
int min_size = bounds.size.w > bounds.size.h ?
bounds.size.h :
bounds.size.w;
GPoint middle = GPoint(bounds.size.w/2, bounds.size.h/2);
int16_t size_difference = max_size - min_size;
return (LayerInfo) {
.lower_middle = GPoint(middle.x, middle.y + size_difference/2),
.min_size = min_size,
.half_min_size = min_size/2
};
}
static int is_special_tick(int tick, int special_tick_modulo) {
if (special_tick_modulo == -1) return false;
if ((tick % special_tick_modulo) != 0) return false;
return true;
}
static GPoint get_point_on_circle(int16_t radius, int16_t degree, GPoint offset) {
int32_t angle = (degree * TRIG_MAX_ANGLE) / 360;
int32_t sin = sin_lookup(angle);
int32_t cos = cos_lookup(angle);
// the y coordinate has to be negative because on the pebble y
// grows to the bottom, while in mathematical coordinate system,
// y grows to the top
return GPoint(
radius * cos / TRIG_MAX_RATIO + offset.x,
- radius * sin / TRIG_MAX_RATIO + offset.y
);
}
static void draw_ticks(Layer *layer, GContext *ctx, int ticks, int size_percent, int special_ticks) {
LayerInfo info = get_layer_info(layer);
int16_t big_length = info.min_size / 10;
int16_t small_length = info.min_size / 20;
for (int i = 0; i < ticks; i++) {
int32_t length = is_special_tick(i, special_ticks)
? big_length
: small_length;
int32_t degree = i * (360/ticks);
int16_t radius_outer = (info.half_min_size - 0 ) * size_percent / 100;
int16_t radius_inner = (info.half_min_size - length) * size_percent / 100;
GPoint from = get_point_on_circle(radius_inner, degree, info.lower_middle);
GPoint to = get_point_on_circle(radius_outer, degree, info.lower_middle);
graphics_context_set_stroke_color(ctx, GColorWhite);
graphics_draw_line(ctx, from, to);
}
}
static void update_ticks(Layer *layer, GContext *ctx) {
draw_ticks(layer, ctx, 60, 100, 5);
draw_ticks(layer, ctx, 24, 80, -1);
}
static int32_t clock_degree(int32_t degree) {
return (360 + (90 - degree)) % 360;
}
static void draw_seconds(Layer *layer, GContext *ctx, struct tm *t) {
LayerInfo info = get_layer_info(layer);
int32_t degree = clock_degree(360 * t->tm_sec / 60);
int16_t radius_outer = info.half_min_size;
GPoint from = info.lower_middle;
GPoint to = get_point_on_circle(radius_outer, degree, info.lower_middle);
graphics_context_set_stroke_color(ctx, GColorWhite);
graphics_draw_line(ctx, from, to);
}
static void draw_minutes(Layer *layer, GContext *ctx, struct tm *t) {
LayerInfo info = get_layer_info(layer);
int32_t degree = 360 * t->tm_min / 60;
int32_t angle = (degree * TRIG_MAX_ANGLE) / 360;
gpath_move_to(minute_hand, info.lower_middle);
gpath_rotate_to(minute_hand, angle);
graphics_context_set_stroke_color(ctx, GColorWhite);
graphics_context_set_fill_color(ctx, GColorWhite);
gpath_draw_filled(ctx, minute_hand);
}
static void draw_hours(Layer *layer, GContext *ctx, struct tm *t) {
LayerInfo info = get_layer_info(layer);
int32_t degree = 360 * (t->tm_hour * 60 + t->tm_min) / (24 * 60);
int32_t angle = (degree * TRIG_MAX_ANGLE) / 360;
gpath_move_to(hour_hand, info.lower_middle);
gpath_rotate_to(hour_hand, angle);
graphics_context_set_stroke_color(ctx, GColorBlack);
graphics_context_set_fill_color(ctx, GColorWhite);
gpath_draw_filled(ctx, hour_hand);
gpath_draw_outline(ctx, hour_hand);
}
static void update_hands(Layer *layer, GContext *ctx) {
time_t now = time(NULL);
struct tm *t = localtime(&now);
draw_seconds(layer, ctx, t);
draw_minutes(layer, ctx, t);
draw_hours(layer, ctx, t);
}
static void draw_date() {
static char buffer[] = "2015-01-01";
time_t now = time(NULL);
struct tm *t = localtime(&now);
strftime(buffer, sizeof("2015-01-01"), "%F", t);
text_layer_set_text(date, buffer);
}
static void main_window_load(Window *window) {
window_set_background_color(window, GColorBlack);
GRect bounds = layer_get_bounds(window_get_root_layer(window));
ticks = layer_create(bounds);
layer_set_update_proc(ticks, update_ticks);
layer_add_child(window_get_root_layer(window), ticks);
hands = layer_create(bounds);
layer_set_update_proc(hands, update_hands);
layer_add_child(window_get_root_layer(window), hands);
date = text_layer_create(GRect(0, 0, 144, 60));
text_layer_set_background_color(date, GColorClear);
text_layer_set_text_color(date, GColorWhite);
text_layer_set_font(date, fonts_get_system_font(FONT_KEY_GOTHIC_14));
text_layer_set_text_alignment(date, GTextAlignmentLeft);
draw_date();
layer_add_child(window_get_root_layer(window), text_layer_get_layer(date));
}
static void main_window_unload(Window *window) {
layer_destroy(ticks);
layer_destroy(hands);
text_layer_destroy(date);
}
static void seconds_tick_handler(struct tm *tick_time, TimeUnits units_changed) {
layer_mark_dirty(window_get_root_layer(main_window));
if (units_changed & DAY_UNIT) {
draw_date();
}
}
static void init() {
minute_hand = gpath_create(&MINUTE_HAND_POINTS);
hour_hand = gpath_create(&HOUR_HAND_POINTS);
main_window = window_create();
window_set_window_handlers(main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
window_stack_push(main_window, true);
tick_timer_service_subscribe(SECOND_UNIT, seconds_tick_handler);
}
static void deinit() {
gpath_destroy(minute_hand);
gpath_destroy(hour_hand);
window_destroy(main_window);
tick_timer_service_unsubscribe();
}
int main(void) {
init();
app_event_loop();
deinit();
}
|
C
|
#include "dynarray.h"
#include "command.h"
#include "program.h"
#include "token.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/* A command consists of name and arg token in a DynArray as well as
file redirect strings */
struct Command
{
/* Command name and Command arguments */
DynArray_T oCommandTokens;
/* Stdin redirection string */
char* pcStdinRedirect;
/* Stdout redirection string */
char* pcStdoutRedirect;
};
Command_T Command_newCommand(DynArray_T oNewCommandTokens,
char* pcNewStdin, char* pcNewStdout)
{
Command_T oCommand;
const char *pcPgmName;
assert(oNewCommandTokens != NULL);
pcPgmName = Program_getPgmName();
/* Allocate space for new command and set oCommandTokens field */
oCommand = (Command_T)malloc(sizeof(struct Command));
if (oCommand == NULL)
{perror(pcPgmName); exit(EXIT_FAILURE);}
oCommand->oCommandTokens = oNewCommandTokens;
/* Set redirect string fields */
oCommand->pcStdinRedirect = pcNewStdin;
oCommand->pcStdoutRedirect = pcNewStdout;
return oCommand;
}
void Command_writeCommand(Command_T oCommand)
{
size_t u;
size_t uLength;
Token_T oToken;
assert(oCommand != NULL);
uLength = DynArray_getLength(oCommand->oCommandTokens);
assert(uLength != 0);
/* First command is always the name token */
oToken = DynArray_get(oCommand->oCommandTokens, 0);
assert(oToken != NULL);
printf("Command name: %s\n", Token_getValue(oToken));
/* Additional commands are args */
for (u = 1; u < uLength; u++)
{
oToken = DynArray_get(oCommand->oCommandTokens, u);
assert(oToken != NULL);
printf("Command arg: %s\n", Token_getValue(oToken));
}
/* Name of file to which stdin/stdout is redirected to */
if (oCommand->pcStdinRedirect != NULL)
printf("Command stdin: %s\n", oCommand->pcStdinRedirect);
if (oCommand->pcStdoutRedirect != NULL)
printf("Command stdout: %s\n", oCommand->pcStdoutRedirect);
}
void Command_freeCommand(Command_T oCommand)
{
assert (oCommand != NULL);
DynArray_free(oCommand->oCommandTokens);
free(oCommand);
}
DynArray_T Command_getCommandTokens(Command_T oCommand)
{
return oCommand->oCommandTokens;
}
char* Command_getStdin(Command_T oCommand)
{
return oCommand->pcStdinRedirect;
}
char* Command_getStdout(Command_T oCommand)
{
return oCommand->pcStdoutRedirect;
}
|
C
|
#include<stdio.h>
#include<math.h>
int isPrime(int);
int main()
{
int n;
printf("enter a no.\n");
scanf("%d",&n);
isPrime(n)?printf("%d is prime\n",n):printf("%d is not prime\n",n);
}
int isPrime(int num)
{
if (num==0||num==1)
return 0;
for(int i=2;i<=sqrt(num);i++)
if (num%i==0)
return 0;
return 1;
}
|
C
|
#include "circ_linked_list.h"
/* Gives the length of given linked list */
int length(list *l) {
int i = 1;
node *ptr = *l;
if (*l == NULL) {
return 0;
}
while (ptr->next != *l) {
ptr = ptr->next;
i++;
}
return i;
}
/* Initializes the list to NULL */
void init(list *l) {
*l = NULL;
}
/* Inserts data at desired position in list
* Handles following cases:
* 1. Invalid position
* 2. Insert at begining
* 3. Insert at any other position
* */
void insert(list *l, char *data, int pos) {
node *temp;
temp = (node*)my_malloc(sizeof(node));
strcpy(temp->str, data);
if ((pos > length(l)+1) || (pos < 1)) {
printf("Did nothing\n");
return;
}
else if ((*l == NULL) || (pos == 1)) {
temp->next = temp;
*l = temp;
}
else {
int i;
node *ptr = *l;
for (i = 0; i < pos-2; i++) {
ptr = ptr->next;
}
temp->next = ptr->next;
ptr->next = temp;
}
}
/* Stores all the nodes' data in a static string and returns it */
char* traverse(list *l) {
static char str[200];
strcpy(str, "\0");
node *ptr = *l;
do {
strcat(str, ptr->str);
strcat(str, " ");
ptr = ptr->next;
}
while (ptr != *l);
return str;
}
/* Removes duplicate elements in a list */
void remDuplicate(list *l) {
node *ptr1 = *l, *ptr2, *temp;
do {
ptr2 = ptr1;
do {
if (!strcmp(ptr1->str, ptr2->next->str) && (ptr1 != ptr2->next)) {
temp = ptr2->next;
ptr2->next = ptr2->next->next;
my_free(temp);
}
ptr2 = ptr2->next;
}
while (ptr2 != *l);
ptr1 = ptr1->next;
}
while (ptr1 != *l);
}
/* Prints intersection of two lists */
void intersectlist(list *l1, list *l2) {
remDuplicate(l1);
remDuplicate(l2);
node *ptr1 = *l1, *ptr2;
char str[50] = "\0";
do {
ptr2 = *l2;
do {
if (!strcmp(ptr1->str, ptr2->str)) {
strcat(str, ptr1->str);
strcat(str, " ");
}
ptr2 = ptr2->next;
}
while (ptr2 != *l2);
ptr1 = ptr1->next;
}
while (ptr1 != *l1);
//printf("[%s]\n", str);
}
int main() {
list l, l2;
char str[100];
/* Initialization */
init(&l);
init(&l2);
/* Insertion */
insert(&l, "coll", 1);
insert(&l, "ege", 2);
insert(&l, "pune", 3);
insert(&l, "ege", 4);
insert(&l2, "ege", 1);
insert(&l2, "coll", 2);
/* Display */
strcpy(str, traverse(&l));
printf("[%s]\n", str);
strcpy(str, traverse(&l2));
printf("[%s]\n", str);
/* Print intersection by first removing duplicate elements */
intersectlist(&l, &l2);
return 0;
}
|
C
|
/*Tokenizer project using Linked List Structure to hold data*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*
Token Structure is based off a linked list
This was done so that we could store the tokens easily and then
be able to easily find a token or remove a token if needed
*/
struct Token
{
char *data;
char *tokenType;
struct Token *next;
}
*head;
typedef struct Token Token;
Token *CreateToken(char * ts, char * type)
{
/*if the token linked list is empty*/
if (head==NULL)
{
Token *newToken=(struct Token*)malloc(sizeof(Token));
newToken->data=ts;
newToken->tokenType=type;
newToken->next=NULL;
head=newToken;
return head;
}
/* If the token list has at least 1 or more things in it */
else
{
/*Iterator*/
Token *iter=head;
while (iter->next!=NULL)
{
iter=iter->next;
}
Token *newToken=(struct Token*)malloc(sizeof(Token));
newToken->data=ts;
newToken->tokenType=type;
iter->next=newToken;
newToken->next=NULL;
return newToken;
}
}
/*Destroys the linked list entirely, probably not the right way to do this */
void DestroyToken( Token * tk )
{
Token *iterator=head;
/*In case the linked list is empty*/
if (iterator==NULL)
{
return;
}
/*in case there is only one thing in the linked list*/
else if (iterator->next==NULL)
{
free(tk);
iterator->next=NULL;
}
/*for all other cases*/
else
{
while (iterator->next!=NULL)
{
if (strcmp(iterator->next->data,tk->data)==0)
{
iterator->next=tk->next;
free(tk);
}
iterator=iterator->next;
}
}
}
/*Prints the contens of the token linked list */
void printAllTokens()
{
Token *i=head;
while (i!=NULL)
{
printf("%s",i->tokenType);
printf(" %s\n",i->data);
i=i->next;
}
}
char *GetNextToken( Token * tk )
{
return NULL;
}
/* Creates a new token in the linked list, given a substring location, an input and the token type */
void createNewString (char* input, char* type, int y, int z)
{
/* Gets the start of the token */
int TokenStart = z;
/*Gets the length of the token */
int TokenLength = y-z;
/*Creates a string for just the token */
/*Fixes a null termination bug */
char *NewToken=malloc((TokenLength+1)*sizeof(char*));
/*removing +1 fixes a null termiantion thing*/
NewToken[TokenLength]='\0';
/* Temporary variable simply used to add the token to the NewToken string */
int b = 0;
/*Loops through the input string, and adds the token to the NewToken string*/
for (TokenStart=z; TokenStart<y; TokenStart++)
{
NewToken[b] = input[TokenStart];
b++;
}
if (strcmp(type,"Malformed Token")==0)
{
CreateToken(" ",type);
return;
}
CreateToken(NewToken,type);
}
/* Populates the token list during the initial run */
void populateTokenList(char* input)
{
/* indicates how many times to iterate */
int i = strlen(input);
/*Z keeps track of the beggining index*/
int z = 0;
/* Y keeps track of the ending */
int y = 0;
while (z < i)
{
/*This if statement handles tokens that start with 0 */
/*Hexadecimal eg. 0x */
/*Octal eg. 0532 */
if (input[z]=='0')
{
/*for finding hexadecimal characters*/
if(input[z+1]=='x' || input[z+1] == 'X')
{
/* Y is the stuff after the hexadecimal identifier */
y = z+2;
while (isalnum(input[y]) && input[y]<'g')
{
y++;
if (input[y] == '\0')
{
y++;
break;
}
}
createNewString(input,"Hexadecimal",y,z);
z=y;
continue;
}
/*checks octal */
else if (isdigit(input[z+1]) && (input[z+1]-'0')<=7)
{
int r = 0;
y=z+1;
while (isdigit(input[y]) && input[y]-'0'<=7)
{
/*keeps count of how many indexes have been iterated through*/
y++;
if (input[y] == '.')
{
r++;
}
/* if the end of string is hit, add 1 to y in order to account for the null character index */
else if (input[y] == '\0')
{
y++;
break;
}
}
if (r == 0)
{
createNewString(input,"Octal",y,z);
z=y;
}
else if (r!=0)
{
y = y+1;
while (isdigit(input[y]) || input[y]=='e' || input[y]=='E' || (input[y]=='-' && isdigit(input[y])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
if (input[y] == '0' && (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
}
/* added E for floating point stuff" */
else if (isdigit(input[z]) && (input[z+1]=='.' || (input[z+1]=='E' && input[z+2]!='E') || (input[z+1]=='e' && input[z+2]!='e')))
{
y=z+2;
while (isdigit(input[y]) || (input[y]=='E' && input[y+1]!='E') || (input[y]=='e' && input[y+1]!='e') || (input[y]=='-' && isdigit(input[y+1])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
if (input[y] == '0'&& (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
else
{
createNewString(input,"Malformed Token",0,0);
z=y;
z+=2;
}
}
/*for words */
else if (isalpha(input[z]))
{
y = z+1;
while (isalpha(input[y]))
{
y++;
if (input[y] == '\0')
{
y++;
break;
}
}
createNewString(input,"word",y,z);
z=y;
continue;
}
/*Does regular digits*/
else if (isdigit(input[z]) && input[z+1]!='.')
{
y = z+1;
int h = 0;
while (isdigit(input[y])) // in this statement we need to have something for floating point
{
if (input[y]=='0' && (input[y+1]=='x' || input[y+1] == 'X'))
{
break;
}
y++;
/*For floating point and floating point with E*/
if (input[y] == '.' || input[y] == 'E' || input[y] == 'e' )
{
h++;
}
else if (input[y] == '\0')
{ // if it hits the end of the string, this adds on the null character index.
y++;
break;
}
}
if (h == 0)
{
createNewString(input,"Decimal",y,z);
z=y;
}
else if (h!=0)
{
y = y+1;
while (isdigit(input[y]) || input[y]=='e' || input[y]=='E' || (input[y]=='-' && isdigit(input[y+1])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
if (input[y] == '0' && (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
}
/*added e for floating point*/
else if (isdigit(input[z]) && (input[z+1]=='.' || input[z+1]=='E' || input[z+1]=='e'))
{
y=z+2;
while (isdigit(input[y]) || input[y]=='e' || input[y]=='E' || (input[y]=='-' && isdigit(input[y+1])))
{
/*keeps count of how many indexes have been iterated through*/
y++;
/* if the end of string is hit, add 1 to y in order to account for the null character index */
if (input[y] == '\0')
{
y++;
break;
}
else if (input[y] == '0' && (input[y+1] == 'X' || input[y+1] == 'x'))
{
break;
}
}
createNewString(input,"Floating Point",y,z);
z=y;
continue;
}
/* Switch Statement for other characters */
if (input[z]=='<' && input[z+1]=='<' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Left Shift and Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='>' && input[z+1]=='>' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Right Shift and Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='+' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Plus Equals",y,z);
z=y;
continue;
}
else if (input[z]=='&' && input[z+1]=='&')
{
y=z+2;
createNewString(input,"Logical And",y,z);
z=y;
continue;
}
else if (input[z]=='-' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Minus Equals",y,z);
z=y;
continue;
}
else if (input[z]=='=' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Comparison",y,z);
z=y;
continue;
}
else if (input[z]=='*' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Multiplication Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='/' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Division Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='%' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Remainder Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='&' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Bitwise And Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='^' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Bitwise Exclusive Or Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='|' && input[z+1]=='=')
{
y=z+2;
createNewString(input,"Bitwise Inclusive Or Assignment",y,z);
z=y;
continue;
}
else if (input[z]=='|' && input[z+1]=='|')
{
y=z+2;
createNewString(input,"Logical Or",y,z);
z=y;
continue;
}
else if (input[z]=='<' && input[z+1]=='<')
{
y=z+2;
createNewString(input,"Left Shift",y,z);
z=y;
continue;
}
else if (input[z]=='>' && input[z+1]=='>')
{
y=z+2;
createNewString(input,"Right Shift",y,z);
z=y;
continue;
}
else if (input[z]=='-' && input[z+1]=='-')
{
y=z+2;
createNewString(input,"Decrement",y,z);
z=y;
continue;
}
else if (input[z]=='+' && input[z+1]=='+')
{
y=z+2;
createNewString(input,"Increment",y,z);
z=y;
continue;
}
else if (input[z]=='?' && input[z+1]=='-')
{
y=z+2;
createNewString(input,"Conditional Expression",y,z);
z=y;
continue;
}
else if (input[z]=='-' && input[z+1]=='>')
{
y=z+2;
createNewString(input,"Structure Pointer",y,z);
z=y;
continue;
}
switch (input[z])
{
case '+' :
y=z+1;
createNewString(input,"Addition",y,z);
z=y;
break;
case '-' :
y=z+1;
createNewString(input,"Subtraction",y,z);
z=y;
break;
case '*' :
y=z+1;
createNewString(input,"Multiplication",y,z);
z=y;
break;
case '%' :
y=z+1;
createNewString(input,"Modulus",y,z);
z=y;
break;
case '=' :
y=z+1;
createNewString(input,"Assignment",y,z);
z=y;
break;
case '>' :
y=z+1;
createNewString(input,"Greater Than",y,z);
z=y;
break;
case '<' :
y=z+1;
createNewString(input,"Less Than",y,z);
z=y;
break;
case '|' :
y=z+1;
createNewString(input,"Bitwise Inclusive Or / Line",y,z);
z=y;
break;
case '&' :
y=z+1;
createNewString(input,"Bitwise And / Ampersand",y,z);
z=y;
break;
case '^' :
y=z+1;
createNewString(input,"Exclusive Or / Carret",y,z);
z=y;
break;
case '?' :
y=z+1;
createNewString(input,"Question Mark",y,z);
z=y;
break;
case ':' :
y=z+1;
createNewString(input,"Conditional Expression / Colon",y,z);
z=y;
break;
case ',' :
y=z+1;
createNewString(input,"Comma",y,z);
z=y;
break;
case ';' :
y=z+1;
createNewString(input,"End of Expression / Semi Colon",y,z);
z=y;
break;
case '/' :
y=z+1;
createNewString(input,"Slash",y,z);
z=y;
break;
case '\\' :
y=z+1;
createNewString(input,"Backslash",y,z);
z=y;
break;
case '[' :
y=z+1;
createNewString(input,"Left Brace",y,z);
z=y;
break;
case ']' :
y=z+1;
createNewString(input,"Right Brace",y,z);
z=y;
break;
case '{' :
y=z+1;
createNewString(input,"Left Bracket",y,z);
z=y;
break;
case '}' :
y=z+1;
createNewString(input,"Right Bracket",y,z);
z=y;
break;
case '_' :
y=z+1;
createNewString(input,"Underscore",y,z);
z=y;
break;
case '#' :
y=z+1;
createNewString(input,"Hash",y,z);
z=y;
break;
case '!' :
y=z+1;
createNewString(input,"Not / Exclamation",y,z);
z=y;
break;
case '`' :
y=z+1;
createNewString(input,"Tilde",y,z);
z=y;
break;
case '(' :
y=z+1;
createNewString(input,"Left Parenthesis",y,z);
z=y;
break;
case ')' :
y=z+1;
createNewString(input,"Right Parenthesis",y,z);
z=y;
break;
default :
z++;
break;
}
}
}
/* The main function */
int main(int argc, char **argv)
{
if (argv[1]==NULL || strlen(argv[1])==0)
{
printf("%s\n", "No Argument");
return 0;
}
populateTokenList(argv[1]);
printAllTokens();
return 0;
}
|
C
|
#include "holberton.h"
/**
* _memset - fills n memory spaces with the constant char b
*
* @s: adress of memory
* @b: constant char
* @n: numbers of fields to fill
*
* Return: return the adress of the memory
*/
char *_memset(char *s, char b, unsigned int n)
{
unsigned int i;
for (i = 0; i < n; i++)
{
*(s + i) = b;
}
return (s);
}
|
C
|
#include<stdio.h>
int binary_search(int a[],int lb,int ub,int ele)
{ int mid;
if(lb<ub)
{ mid=(lb+ub)/2;
if(a[mid]==ele)
{ return (mid+1);
}
else if(a[mid]<ele)
{ return binary_search(a,mid+1,ub,ele);
}
else
{ return binary_search(a,lb,mid-1,ele);
}
}
else
{ return -1;
}
}
int main()
{ int n,i,pos,ele;
printf("enter the size of array\n");
scanf("%d",&n);
int a[n];
printf("enter the elements\n");
for(i=0;i<n;++i)
{ scanf("%d",&a[i]);
}
printf("enter the element to be searched\n");
scanf("%d",&ele);
int flag=0;
for(i=0;i<n;++i)
{ if(a[i]==ele)
{ flag=1;
}
}
if(flag==1)
{ pos=binary_search(a,0,n-1,ele);
printf("\nthe element found at position= %d",pos);
}
else
{ printf("element not found\n");
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: crycherd <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/22 22:18:16 by crycherd #+# #+# */
/* Updated: 2019/06/12 19:48:31 by crycherd ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static t_list *what_file(t_list **list, size_t fd)
{
t_list *search;
search = *list;
while (search)
{
if (search->content_size == fd)
return (search);
search = search->next;
}
search = ft_lstnew("\0", 1);
ft_lstadd(list, search);
search->content_size = fd;
return (search);
}
static void lstremovis(t_list **alst, size_t this)
{
t_list *remove;
t_list *lucky;
if (*alst)
{
lucky = *alst;
remove = *alst;
while (remove)
{
if (remove->content_size == this)
break ;
lucky = remove;
remove = remove->next;
}
lucky->next = remove->next;
free(remove->content);
free(remove);
remove = NULL;
}
}
static void *new_content(char *safe, char *buf, size_t size)
{
char *str;
str = ft_strnew(ft_strlen(safe) + size + 1);
str = ft_strcat(str, safe);
str = ft_strncat(str, buf, size);
return (str);
}
static void create_line(char **line, t_list *list, int *bit)
{
char *str;
char *safe;
size_t size;
safe = list->content;
if ((str = ft_strchr(list->content, '\n')))
{
size = str - safe;
*line = (char *)ft_strnew(size + 1);
*line = ft_memcpy(*line, safe, size);
list->content = ft_strdup(str + 1);
free(safe);
}
else if ((size = ft_strlen(list->content)) != 0)
{
*line = (char *)ft_strnew(size + 1);
*line = ft_memcpy(*line, safe, size);
list->content = ft_strnew(1);
free(safe);
*bit = size;
}
}
int get_next_line(const int fd, char **line)
{
char buf[BUFF_SIZE + 1];
char *safe_file;
static t_list *list;
t_list *file;
int size;
if (fd < 0 || !(line) || (read(fd, buf, 0) < 0))
return (-1);
file = what_file(&list, fd);
size = ft_strlen(file->content);
while (!ft_strchr(file->content, '\n') && (size = read(fd, buf, BUFF_SIZE)))
{
safe_file = file->content;
file->content = new_content(safe_file, buf, size);
free(safe_file);
}
create_line(line, file, &size);
if (size != 0)
return (1);
lstremovis(&list, fd);
if (list == file && list->next == NULL)
list = NULL;
return (0);
}
|
C
|
#include <stdio.h>
#include <math.h>
int main(void) {
FILE * data;
double f, f1, f2, g1, g2, dx, x, k1, k2, k3, k4, k, h1, h2, h3, h4, h;
int a, b;
data = fopen("problem_data.csv", "w");
printf("aを入力して下さい。 a = ");
scanf("%d", &a);
printf("bを入力して下さい。 b = ");
scanf("%d", &b);
printf("yを入力して下さい。 y = ");
scanf("%lf", &f1);
printf("dy/dxを入力して下さい。 dy/dx = ");
scanf("%lf", &g1);
printf("dxを入力して下さい。 dx = ");
scanf("%lf", &dx);
for (int i=0; i<=500; i++) {
x = i*dx;
k1 = dx*g1;
h1 = dx*( (-b)*g1 - a*f1);
k2 = dx*(g1 + h1/2.);
h2 = dx*( (-b)*(g1 + h1/2.) - a*(f1 + k1/2.) );
k3 = dx*(g1 + h2/2.);
h3 = dx*( (-b)*(g1 + h2/2.) - a*(f1 + k2/2.) );
k4 = dx*(g1 + h3);
h4 = dx*( (-b)*(g1 + h3) - a*(f1 + k3) );
k = (k1 + 2*k2 + 2*k3 + k4)/6.;
f2 = f1 + k;
h = (h1 + 2*h2 + 2*h3 + h4)/6.;
g2 = g1 + h;
f = 5*exp(3*x)*(1 - 3*x);
printf("x = %f, 数値解-> f1 = %f, dy/dx = %f, 正確な値-> f = %f \n", x, f1, g1, f);
fprintf(data,"%f, %f, %f\n", x, f1, g1);
f1 = f2;
g1 = g2;
}
fclose(data);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
{
char y;
char x[5]={'a','e','i','o','u'};
scanf("%d",&x);
if(y==x[5])
printf("vowel");
else
printf("consonent");
}
|
C
|
#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"
// #include "procstat.h"
#include <stddef.h>
int main(int argc, char *argv[]) {
int k, n, id;
// double x = 0, z;
// set_priority(4, 70);
if (argc < 2)
n = 1; // default value
else
n = atoi(argv[1]); // from command line
// if (n < 0 || n > 20)
// n = 2;
// x = 0;
id = 0;
for (k = 0; k < n; k++) {
// id = fork();
// // printf(1, "%d\n", o);
// if (id < 0) {
// printf(1, "%d failed in fork!\n", getpid());
// } else if (id > 0) { // parent
// // printf(1, "Parent %d creating child %d\n", getpid(), id);
// // wait();
// } else { // child
// // printf(1, "Child %d created\n", getpid());
// for (z = 0; z < 3000000.0; z += 0.1)
// x = x +
// 3.14 * 89.64; // useless calculations to consume CPU time
// exit();
// }
// // set_priority(6, 80);
id = fork();
if(id == 0)
{
for(int pq=0; pq<1000000000; pq++){
;
}
// sleep(2);
// sleep(2);
// sleep(2);
// sleep(2);
// sleep(2);
// sleep(2);
// sleep(2);
// sleep(2);
exit();
}
}
for (k = 0; k < n; k++) {
// int a, b;
// struct proc_stat q, *r;
// int pd = 4;
// waitx(&a, &b);
wait();
// printf(1, "%d %d\n", a, b);
// struct proc_stat *r = &q;
// printf(1, "et\n");
// int c = getpinfo(&q, pd);
// if (c == 1) {
// printf(1, "%p %p\n", &q, q.pid);
// r = &q;
// printf(1, "%p\n", r->pid);
// // printf(1, "%d \n", *(r->pid));
// }
// printf(1, "%p %p %p %p\n", (q.pid), (q.current_queue), (q.num_run),
// (q.runtime));
// waitx(&a, &b);
// printf(1, "%d %d\n", a, b);
}
exit();
}
|
C
|
#include<stdio.h>
int Fibonacci(int n)
{
if(n <=2)return 1;
return Fibonacci(n-1)+Fibonacci(n-2);
}
int Fibonacci2(int n)
{
if(n <=2)return 1;
int fn1 = 1;
int fn2 = 1;
int fn;
int i;
for(i = 3;i <= n;i++ )
{
fn = fn1+fn2;
fn2 = fn1;
fn1 = fn;
}
return fn;
}
int main()
{
printf("%d\n",Fibonacci2(50));
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
float i=1000,r1=0.0468,r2=0.054,p1,p ;
int n1=2,n2=3 ;
p1=i*(1+n1*r1) ;
p=p1*(1+n2*r2) ;
printf ("p=%f",p) ;
return 0 ;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bseven <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/31 12:59:32 by bseven #+# #+# */
/* Updated: 2021/10/31 12:59:35 by bseven ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/philo.h"
void init_null(t_args *args)
{
args->forks = NULL;
args->philos = NULL;
pthread_mutex_init(&args->output, NULL);
}
int init_table(t_args *args)
{
args->philos = malloc(sizeof(t_philos) * args->number_of_philosophers);
if (!(args->philos))
return (put_err(" philos alloc."));
args->forks = malloc(
sizeof(pthread_mutex_t) * args->number_of_philosophers);
if (!args->forks)
return (put_err(" forks alloc."));
return (0);
}
void init_philo(t_args *args)
{
int i;
i = 0;
while (i < args->number_of_philosophers - 1)
{
args->philos[i].name_philo = i + 1;
args->philos[i].left_fork = i;
args->philos[i].right_fork = i + 1;
args->philos[i].args = args;
args->philos[i].last_eat = current_time();
args->philos[i].full_saturation = 0;
i++;
}
args->philos[i].name_philo = i + 1;
args->philos[i].left_fork = i;
args->philos[i].right_fork = 0;
args->philos[i].args = args;
args->born_time = current_time();
args->philos[i].last_eat = current_time();
args->philos[i].full_saturation = 0;
}
|
C
|
#include "AD5410.h"
void DA_SendByte(unsigned char byte);
extern u8 data_ReadFormRegister[3];
void DA_control(unsigned char addr,unsigned int data) ;
void AD5410GpioInit()
{
GPIO_InitTypeDef g;
g.GPIO_Mode=GPIO_Mode_Out_PP;
g.GPIO_Speed=GPIO_Speed_50MHz;
g.GPIO_Pin=GPIO_Pin_10; //5410_CLEAR
GPIO_Init(GPIOB,&g);
g.GPIO_Pin=GPIO_Pin_11; //5410_LATCH
GPIO_Init(GPIOB,&g);
g.GPIO_Pin=GPIO_Pin_12; //5410_CLOCK
GPIO_Init(GPIOB,&g);
g.GPIO_Pin=GPIO_Pin_13; //5410_SLAVE_IN
GPIO_Init(GPIOB,&g);
g.GPIO_Mode=GPIO_Mode_IPU;
g.GPIO_Pin=GPIO_Pin_1; //5410_FAULT
GPIO_Init(GPIOB,&g);
g.GPIO_Mode=GPIO_Mode_IPU;
g.GPIO_Pin=GPIO_Pin_2; //5410_SLAVE_OUT
GPIO_Init(GPIOB,&g);
}
/******************************/
/* AD5410дһֽ */
/******************************/
void DA_SendByte(unsigned char byte)
{
unsigned char i;
for ( i = 0; i < 8; i++)
{
DA_CLK_LOW;
if ( byte & 0x80 )
{DA_SIMO_HIGH;
delay_us(1);}
else
{DA_SIMO_LOW;
delay_us(1);}
DA_CLK_HIGH;
byte <<= 1;
DA_CLK_LOW;
}
}
/***********************************/
/* AD5410д */
/* ܳ3ֽ addrĴַ */
/* dataָ */
void DA_control(unsigned char addr,unsigned int data)
{
u8 Hdata,Ldata;
Hdata=data>>8;
Ldata=data&255;
DA_latch_low;
DA_SendByte(addr);
DA_SendByte(Hdata);
DA_SendByte(Ldata);
DA_latch_high;
delay_us(2);
}
void LATCH()
{
DA_latch_low;
delay_us(5);
DA_latch_high;
delay_us(5);
DA_latch_low;
}
/**********************/
/* ʼAD5410 */
void AD5410_init()
{
AD5410GpioInit();
DA_control(0x56,0x0001); //λ 0x56λĴַ 0x0001λָ
DA_CLEAR_LOW;
LATCH();
DA_control(0x55,0x1016); //0-20ma 257730Ƶ 1/16С
LATCH();
}
/********************/
/* IOUT 0<=DATA<=20*/
void AD5410_IOUT(float DATA)
{
u16 I_OUT;
if(DATA>=20)
{
I_OUT=4095;
}
else if(DATA<=4)
{
DATA=4;
I_OUT=DATA*4096/20;
}
else
{
I_OUT=DATA*4096/20;
}
I_OUT=((int)I_OUT)<<4;
DA_control(0x01,I_OUT);///AD5410д
LATCH();
}
/************************************/
/* AD5410дضָ */
/* addrΪضļĴ */
/* 0x00ȡ״̬Ĵ */
/* 0x01ȡݼĴ */
/* 0x02ȡƼĴ */
void DA_Read_Register(unsigned char addr)
{
DA_latch_low;
DA_SendByte(0x02); //ضĴ
DA_SendByte(0x00);
DA_SendByte(addr);
DA_latch_high;
}
/***********************************************/
/* Registerлض */
/*ضݴ洢data_ReadFormRegister[x] */
void ReadDataFormRegister() //ضݴ洢data_ReadFormRegister[x]
{
u8 temp;
u8 i,j;
//DA_CLK_HIGH;
DA_latch_low;
DA_SIMO_LOW;
delay_us(1);
for(i=0; i<3; i++)
{
for(j=0; j<8; j++)
{
DA_CLK_LOW;
if(GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_2)==0)
{
temp=temp<<1;
}
else
{
temp=temp<<1;
temp=temp+0x01;
}
data_ReadFormRegister[i]=temp;
temp=0;
DA_CLK_HIGH;
}
}
DA_SIMO_HIGH;
DA_latch_high;
}
/************************************/
/* ReadDatafromAD5410 Only */
/* addrΪضļĴ */
/* 0x00ȡ״̬Ĵ */
/* 0x01ȡݼĴ */
/* 0x02ȡƼĴ */
void ReadDataFromAD5410(unsigned char addr)
{
DA_Read_Register(addr);
ReadDataFormRegister();
}
/********************/
/********************/
/*****Իض*******/
// void DA_Read_only(void)
// {
// DA_latch_low;
// DA_SendByte(0x00);
// DA_SendByte(0x00);
// DA_SendByte(0x00);
// DA_latch_high;
// }
// void TEST(unsigned char addr)
// {
// DA_Read_Register( addr);
// DA_Read_only();
// }
|
C
|
#include<stdio.h>
int main (void){
int n, i, j, k, t;
double h;
double max[100] = {0};
scanf("%d", &t);
for(k = 0; k < t; k++){
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf("%lf", &h);
if(h > max[k]){
max[k] = h;
}
}
}
for(j = 0; j < t; j++){
printf("%.2f\n", max[j]);
}
return 0;
}
|
C
|
#include "libkl.h"
void kl_putstr(char *str)
{
int j = 0;
while (str[j] != '\0')
{
kl_putchar(str[j]);
j++;
}
}
|
C
|
/*
** EPITECH PROJECT, 2019
** my_rpg_2018
** File description:
** init_ennemie
*/
#include "prototype.h"
void create_zone_enn(obj_t *ennemie, int zone)
{
sfFloatRect size_sp = sfSprite_getGlobalBounds(ennemie->sprite);
sfVector2f size;
sfVector2f pos;
pos.x = size_sp.left + size_sp.width / 2;
pos.y = size_sp.top + size_sp.height / 2;
size.x = zone;
size.y = zone;
ennemie->detect_zone = sfCircleShape_create();
sfCircleShape_setOutlineColor(ennemie->detect_zone, sfRed);
sfCircleShape_setOutlineThickness(ennemie->detect_zone, 2);
sfCircleShape_setFillColor(ennemie->detect_zone, sfTransparent);
sfCircleShape_setRadius(ennemie->detect_zone, zone);
sfCircleShape_setOrigin(ennemie->detect_zone, size);
sfCircleShape_setPosition(ennemie->detect_zone, pos);
}
void create_ennemie(obj_t *ennemie)
{
ennemie->texture = sfTexture_createFromFile(
"assets/textures/player_2.png", NULL);
ennemie->char_down = create_char_perso(8, 4, 24, 44);
ennemie->char_up = create_char_perso(202, 6, 24, 44);
ennemie->char_left = create_char_perso(72, 6, 24, 44);
ennemie->char_right = create_char_perso(138, 4, 24, 44);
ennemie->stat = (stats){100, 30, 30, 5};
ennemie->sprite = sfSprite_create();
sfSprite_setTexture(ennemie->sprite, ennemie->texture, sfFalse);
ennemie->move.y = 1.5;
ennemie->move.x = 1.5;
sfSprite_setTextureRect(ennemie->sprite, ennemie->char_down);
sfSprite_setScale(ennemie->sprite, ennemie->move);
ennemie->text.phrase = sfText_create();
ennemie->action.clock = sfClock_create();
}
int init_ennemie(scene_t *scene)
{
obj_t *ennemi = malloc(sizeof(obj_t));
sfVector2f pos = {1000, 500};
if (ennemi == NULL)
return (84);
memset(ennemi, 0, sizeof(obj_t) * 1);
create_ennemie(ennemi);
sfSprite_setPosition(ennemi->sprite, pos);
if (init_fight_perso(ennemi) == 84)
return (84);
create_zone_enn(ennemi, 150);
ennemi->anim_clock = sfClock_create();
ennemi->move_clock = sfClock_create();
ennemi->next = scene->ennemi;
scene->ennemi = ennemi;
return (0);
}
|
C
|
/**
* Copyright (c) 2018,
* National Instruments.
* All rights reserved.
*
* Overview:
* Demonstrates how to use the timer IRQ. Once the timer IRQ occurs (5 s), print
* the IRQ number, triggered times and main loop count number in the console.
* The timer IRQ will be triggered only once in this example.
* The output is maintained for 60 s.
*
* Instructions:
* Run this program and observe the console.
*
* Output:
* IRQ0, triggered times and main loop count number are shown in the console,
* The output is maintained for 60 s.
*
* Note:
* The Eclipse project defines the preprocessor symbol for the NI ELVIS III.
*/
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include "TimerIRQ.h"
#if !defined(LoopDuration)
#define LoopDuration 60 // How long to monitor the signal, in seconds
#endif
#if !defined(LoopSteps)
#define LoopSteps 3 // How long to step between printing, in seconds
#endif
extern ELVISIII_IrqTimer IrqTimer;
// Resources for the new thread.
typedef struct
{
NiFpga_IrqContext irqContext; // IRQ context reserved by Irq_ReserveContext()
NiFpga_Bool irqThreadRdy; // IRQ thread ready flag
} ThreadResource;
int main(int argc, char **argv)
{
int32_t status;
ThreadResource irqThread0;
pthread_t thread;
time_t currentTime;
time_t finalTime;
time_t printTime;
// Configure the timer IRQ and set the time interval. The IRQ occurs after the time interval.
const uint32_t timeoutValue = 5000000;
printf("Timer IRQ:\n");
// Open the NiELVISIIIv10 NiFpga Session.
// You must use this function before using all the other functions.
// After you finish using this function, the NI NiELVISIIIv10 target is ready to be used.
status = NiELVISIIIv10_Open();
if (NiELVISIIIv10_IsNotSuccess(status))
{
return status;
}
// Configure the timer IRQ. The Time IRQ occurs only once after Timer_IrqConfigure().
// If you want to trigger the timer IRQ repeatedly, use this function every time you trigger the IRQ.
// Or you can put the IRQ in a loop.
// Return a status message to indicate if the configuration is successful. The error code is defined in IRQConfigure.h.
status = Irq_RegisterTimerIrq(&IrqTimer,
&irqThread0.irqContext,
timeoutValue);
// Terminate the process if it is unsuccessful.
if (status != NiELVISIIIv10_Status_Success)
{
printf("CONFIGURE ERROR: %d, Configuration of Timer IRQ failed.", status);
return status;
}
// Set the indicator to allow the new thread.
irqThread0.irqThreadRdy = NiFpga_True;
// Create new threads to catch the specified IRQ numbers.
// Different IRQs should have different corresponding threads.
status = pthread_create(&thread, NULL, Timer_Irq_Thread, &irqThread0);
if (status != NiELVISIIIv10_Status_Success)
{
printf("CONFIGURE ERROR: %d, Failed to create a new thread!", status);
return status;
}
// Normally, the main function runs a long running or infinite loop.
// Read the console output for 60 seconds so that you can recognize the
// explanation and loop times.
time(¤tTime);
finalTime = currentTime + LoopDuration;
printTime = currentTime;
while (currentTime < finalTime)
{
static uint32_t loopCount = 0;
time(¤tTime);
// Don't print every loop iteration.
if (currentTime > printTime)
{
printf("main loop,%d\n", ++loopCount);
printTime += LoopSteps;
}
}
// Set the indicator to end the new thread.
irqThread0.irqThreadRdy = NiFpga_False;
// Wait for the end of the IRQ thread.
pthread_join(thread, NULL);
// Disable timer interrupt, so you can configure this I/O next time.
// Every IrqConfigure() function should have its corresponding clear function,
// and their parameters should also match.
status = Irq_UnregisterTimerIrq(&IrqTimer, irqThread0.irqContext);
if (status != NiELVISIIIv10_Status_Success)
{
printf("CONFIGURE ERROR: %d\n", status);
printf("Clear configuration of Timer IRQ failed.");
return status;
}
// Close the NiELVISIIIv10 NiFpga Session.
// You must use this function after using all the other functions.
status = NiELVISIIIv10_Close();
// Returns 0 if successful.
return status;
}
void *Timer_Irq_Thread(void* resource)
{
ThreadResource* threadResource = (ThreadResource*) resource;
while (1)
{
uint32_t irqAssert = 0;
static uint32_t irqCount = 0;
// Stop the calling thread, wait until a selected IRQ is asserted.
Irq_Wait(threadResource->irqContext,
TIMERIRQNO,
&irqAssert,
(NiFpga_Bool*) &(threadResource->irqThreadRdy));
// If an IRQ was asserted.
if (irqAssert & (1 << TIMERIRQNO))
{
printf("IRQ%d,%d\n", TIMERIRQNO, ++irqCount);
// Acknowledge the IRQ(s) when assertion is done.
Irq_Acknowledge(irqAssert);
}
// Check the indicator to see if the new thread is stopped.
if (!(threadResource->irqThreadRdy))
{
printf("The IRQ thread ends.\n");
break;
}
}
// Exit the new thread.
pthread_exit(NULL);
return NULL;
}
|
C
|
int isSameTree(treenode* A, treenode* B) {
if(A==NULL&&B==NULL)
return 1;
if((B==NULL)||(A==NULL)||(A->val!=B->val))
return 0;
int x=isSameTree(A->left,B->left);
int y=isSameTree(A->right,B->right);
if(x==1&&y==1)
return 1;
return 0;
}
|
C
|
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void fatal(char *str){
perror(str);
fflush(stdout);
exit(1);
}
int main(){
int fd;
struct flock first_lock;
struct flock second_lock;
first_lock.l_type=F_WRLCK;
first_lock.l_whence = SEEK_SET;
first_lock.l_start = 0;
first_lock.l_len = 10;
second_lock.l_type=F_WRLCK;
second_lock.l_whence = SEEK_SET;
second_lock.l_start = 10;
second_lock.l_len = 5;
fd = open("locktest", O_RDWR);
if(fcntl(fd, F_SETLKW, &first_lock) == -1)
fatal("A");
printf("A: lock succeeded(proc %d)\n", getpid());
switch(fork()){
case -1:
fatal("error on fork");
case 0:
if(fcntl(fd, F_SETLKW, &second_lock) == -1)
fatal("B");
printf("B: lock succeeded(proc %d)\n", getpid());
if(fcntl(fd, F_SETLKW, &first_lock) == -1)
fatal("C");
printf("C: lock succeeded(proc %d)\n", getpid());
exit(0);
default:
printf("parent sleeping\n");
sleep(10);
if(fcntl(fd, F_SETLKW, &second_lock) == -1)
fatal("D");
printf("D: lock succeeded(proc %d)\n", getpid());
}
}
|
C
|
#ifndef FILE_HANDLER_H
#define FILE_HANDLER_H
///FILE* file; // This is in constants, because it needs to be accessed by objectSave/Load functions.
void File_saveTiles(){
for (int x=0; x<WORLD_SIZE_X; ++x) {
for (int y=0; y<WORLD_SIZE_Y; ++y) {
for (int z=0; z<WORLD_SIZE_Z; ++z) {
fprintf(file, "%d\n", worldCells[x][y][z].tileType);
}
}
}
}
void File_loadTiles(){
int type=0;
for (int x=0; x<WORLD_SIZE_X; ++x) {
for (int y=0; y<WORLD_SIZE_Y; ++y) {
for (int z=0; z<WORLD_SIZE_Z; ++z) {
/// Reset worldCell values to zero. Technically part of the "destroy world", but faster if done at same time.
worldCells[x][y][z].isImpassable = false;
worldCells[x][y][z].numOccupants = 0;
for(int i=0; i<MAX_CELL_OCCUPANTS; ++i)
worldCells[x][y][z].occupants[i] = NULL;
/// Read in and set cell type.
fscanf(file, "%d\n", &type);
setCell(x, y, z, type);
}
}
}
}
void File_saveObjects(){
fprintf(file, "%d\n", numWorldObjects);
for (int i=0; i<numWorldObjects; ++i) {
saveObject( worldObjects[i] );
}
}
void File_loadObjects(){
int numObjects;
fscanf(file, "%d\n", &numObjects);
for (int i=0; i<numObjects; ++i) {
loadObject();
}
}
void Save_Game(){
file = fopen("save.txt", "w");
File_saveTiles();
File_saveObjects();
fclose(file);
}
void Load_Game(){
file = fopen("save.txt", "r");
/// Destroy world
cleanup_worldObjects();
/// Load
File_loadTiles();
File_loadObjects();
/// Reset Sensory Map
updateSoundMapDensity();
/// Set player
player = worldObjects[0];
fclose(file);
}
#endif
|
C
|
/*
** invalid_null_cmd.c for in /home/beche_f/PSU_2015_42sh/src/syntaxe
**
** Made by beche_f
** Login <[email protected]>
**
** Started on Wed May 25 15:22:26 2016 beche_f
** Last update Wed May 25 15:40:44 2016 beche_f
*/
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#include "lib.h"
int begin_by_token(char *cmd)
{
if (cmd[0] == '<' || cmd[0] == '>' || cmd[0] == '|' || cmd[0] == '&')
{
my_putstr("Invalid null command.\n");
return (-1);
}
return (0);
}
int end_by_token(char *cmd)
{
int i;
i = my_strlen(cmd) - 1;
if (cmd[i] == '<' || cmd[i] == '>' || cmd[i] == '|' || cmd[i] == '&')
{
my_putstr("Invalid null command.\n");
return (-1);
}
return (0);
}
int invalid_token(char *cmd)
{
int i;
i = 0;
while (cmd[i] != 0)
{
if (cmd[i] == '|' || cmd[i] == '&' || cmd[i] == '<' || cmd[i] == '>')
{
if (cmd[i + 1] == '|' || cmd[i + 1] == '&' ||
cmd[i + 1] == '<' || cmd[i + 1] == '>')
return (0);
else if (cmd[i + 2] == '|' || cmd[i + 2] == '&' ||
cmd[i + 2] == '<' || cmd[i + 2] == '>')
{
my_putstr("Invalid null command.\n");
return (-1);
}
}
i++;
}
return (0);
}
|
C
|
/**
* @file ctre.h
* Common header for all CTRE HAL modules.
*/
#ifndef CTRE_H
#define CTRE_H
//Bit Defines
#define BIT0 0x01
#define BIT1 0x02
#define BIT2 0x04
#define BIT3 0x08
#define BIT4 0x10
#define BIT5 0x20
#define BIT6 0x40
#define BIT7 0x80
#define BIT8 0x0100
#define BIT9 0x0200
#define BIT10 0x0400
#define BIT11 0x0800
#define BIT12 0x1000
#define BIT13 0x2000
#define BIT14 0x4000
#define BIT15 0x8000
//Signed
typedef signed char INT8;
typedef signed short INT16;
typedef signed int INT32;
typedef signed long long INT64;
//Unsigned
typedef unsigned char UINT8;
typedef unsigned short UINT16;
typedef unsigned int UINT32;
typedef unsigned long long UINT64;
//Other
typedef unsigned char UCHAR;
typedef unsigned short USHORT;
typedef unsigned int UINT;
typedef unsigned long ULONG;
typedef enum {
CTR_OKAY, //!< No Error - Function executed as expected
CTR_RxTimeout, //!< CAN frame has not been received within specified period of time.
CTR_TxTimeout, //!< Not used.
CTR_InvalidParamValue, //!< Caller passed an invalid param
CTR_UnexpectedArbId, //!< Specified CAN Id is invalid.
CTR_TxFailed, //!< Could not transmit the CAN frame.
CTR_SigNotUpdated, //!< Have not received an value response for signal.
CTR_BufferFull, //!< Caller attempted to insert data into a buffer that is full.
}CTR_Code;
#endif /* CTRE_H */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*rle: String Operations II
*Takes a single arguement
*Compresses a string for each repeating letter or punctuation
*-If the compress string it longer than the orginal string, print orginal string
*-If the string contains a # program must print "error" and nothing else
*/
int main(int argc, char *argv[])
{
int length = strlen(argv[1]); //Gets the length of the string
char buffer[256], temp[256]; //buffer holds the char and the number of times it has appeared
temp[0] = '\0'; //To avoid garbage values that would be detected from the strcat function
int i,j,counter = 0;
for(i = 0; i < length; i++){
for(j = i; j < length; j++){
if(isdigit(argv[1][j])){ //Checks to see if the string contains a #
printf("error\n");
exit(0);
}
/*If at the last index, will concat the strings
*Then compare the length of the new string to the orginal and print out the string accordingly
*/
if(argv[1][i] == argv[1][j] && j == length-1){
counter++;
sprintf(buffer, "%c%d", argv[1][i], counter); //Places the chars and ints into buffer
strcat(temp, buffer); //Concat the strings
if(length < strlen(temp)){
printf("%s\n", argv[1]);
}else{
printf("%s\n", temp);
}
return 0;
}
else if(argv[1][i] == argv[1][j]){ //If the charcters match its a hit
counter++;
}else{ /*If not the last index, will concatinate the char and counter with the new string*/
sprintf(buffer, "%c%d", argv[1][i], counter);
strcat(temp, buffer);
i = counter + i -1;
counter = 0;
break;
}
}
}
return 0;
}
|
C
|
/*
filename - main.c
version - 1.0
description - ⺻ Լ
--------------------------------------------------------------------------------
first created - 2020.02.01
writer - Hugo MG Sung.
*/
#include <stdio.h>
#include <stdlib.h>
// Լ
int main(void)
{
int a;
int n[20][20];
scanf("%d", &a);
for (int i = 0; i < a; i++)
{
for (int j = 0; j < a; j++)
{
n[i][j] = i + j + 1;
if (i == a-1)
{
n[i][j] = 3 * i - j + 1;
}
printf("%d\t", n[i][j]);
}
printf("\n");
}
system("pause");
return EXIT_SUCCESS;
}
//5
//
//1 2 3 4 5
//
//16 17 18 19 6
//
//15 24 25 20 7
//
//14 23 22 21 8
//
//13 12 11 10 9
|
C
|
#include<stdlib.h>
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<stdbool.h>
#include<linux/limits.h>
#define BUF_SIZE 1024
// 仿写 cp 命令
// usage: ./my_cp src_file dest(file or dir)
static bool file_exists(char *filename) {
struct stat buffer;
return (stat(filename, &buffer) == 0);
}
static void copy_file(int in_fd, int out_fd) {
char *buffer[BUF_SIZE];
int num_read;
while ((num_read = read(in_fd, buffer, BUF_SIZE)) > 0) {
write(out_fd, buffer, num_read);
}
}
static void new_path(char *path, char *file, char *new_path) {
int path_len = strlen(path);
int file_len = strlen(file);
if (path_len + file_len >= PATH_MAX) return;
memcpy(new_path, path, path_len);
// 检查 path 结尾是否已经有 / 符号
if (new_path[path_len-1] != '/') {
new_path[path_len] = '/';
path_len++;
}
// 得到文件的名字 filename
char *tmp = strrchr(file, '/');
if (tmp == NULL) {
tmp = file;
} else tmp++;
// 构建 path/filename 的路径
strncpy(new_path + path_len, tmp, file_len);
}
// 调用前保证 file 已经存在,让用户决定覆盖还是追加内容
// 成果返回新文件的 fd,失败返回 -1 或者
static int overwrite_or_append(char *file) {
printf("file '%s' exists! type 'o' to overwrite or 'a' to append!\n", file);
char cmd = getchar();
switch (cmd)
{
case 'o':
// 先删除原有文件
if (remove(file) != 0) {
printf("can not overwrite dest_file!\n");
return -1;
}
// 创建新的同名文件
return open(file, O_CREAT | O_EXCL | O_RDWR);
case 'a' :
// 追加模式
return open(file, O_RDWR | O_APPEND);
default:
printf("unknown option. exit!\n");
return -1;
}
}
int main(int argc, char *argv[]) {
// 判断参数是否正确
if (argc != 3) {
printf("usage error! usage: ./my_cp src_file dest(file or dir)\n");
return 0;
}
// 判断 src_file 是否存在
if (!file_exists(argv[1])) {
printf("src_file does not exist!\n");
return 0;
}
int in_fd = open(argv[1], O_RDONLY);
if (in_fd < 0) {
perror(argv[0]);
return 0;
}
struct stat src_stat, dest_stat;
if (fstat(in_fd, &src_stat) != 0) {
perror(argv[0]);
return 0;
}
// 判断 src_file 是否为目录
if (S_ISDIR(src_stat.st_mode)) {
printf("src_file must not be a dir\n");
return 0;
}
int out_fd;
// 查看 dest 是否存在,存在的话看是目录还是文件
if (stat(argv[2], &dest_stat) != 0) {
// dest 不存在,创建新文件
if (errno == ENOENT) {
out_fd = open(argv[2], O_CREAT | O_EXCL | O_RDWR);
if (out_fd < 0) {
perror(argv[0]);
return 0;
}
}
} else {
// dest 已经存在
if (S_ISDIR(dest_stat.st_mode)) {
// dest 为目录,构建新的文件,使用同名文件
char new_name[PATH_MAX];
memset(new_name, 0, PATH_MAX);
new_path(argv[2], argv[1], new_name);
// 查看新生成的文件名是否已经有文件存在,不存在则创建新的文件
out_fd = file_exists(new_name) ? overwrite_or_append(new_name) : open(new_name, O_CREAT | O_EXCL | O_RDWR);
} else {
// dest 是已经存在的文件
out_fd = overwrite_or_append(argv[2]);
}
}
// 复制内容
copy_file(in_fd, out_fd);
// 设置新文件的模式(和 src_file 一致)
if (fchmod(out_fd, src_stat.st_mode) < 0) {
perror(argv[0]);
return 0;
}
close(in_fd);
close(out_fd);
return 0;
}
|
C
|
/*
㵽nʱֵ﷽ʽ n-1 1¥ݡn-22¥
N¥ݵ=n-1+n-2
ƹʽͳ
fn=fn-1+fn-2
*/
#include <stdio.h>
int main()
{
int n,a[45],m,i;
a[1]=1;
a[2]=1;
while(scanf("%d",&n) != EOF)
{
for(i=3;i<=45;i++)
a[i]=a[i-1]+a[i-2];
while(n--)
{
scanf("%d",&m);
printf("%d\n",a[m]);
}
}
return 0;
}
|
C
|
/*
* Copyright (c) 2018 James, https://github.com/zhuguangxiang
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "options.h"
#include "stringbuf.h"
#include "mem.h"
#include "stringex.h"
#include "log.h"
LOGGER(0)
struct namevalue *namevalue_new(char *name, char *value)
{
struct namevalue *nv = Malloc(sizeof(struct namevalue));
assert(nv != NULL);
nv->name = name;
nv->value = value;
return nv;
}
void namevalue_free(struct namevalue *nv)
{
Mfree(nv->name);
Mfree(nv->value);
Mfree(nv);
}
struct namevalue *parse_namevalue(char *opt, Options *opts, char *prog)
{
char *name = opt;
char *eq = strchr(opt, '=');
if (eq == NULL || eq[1] == '\0') {
fprintf(stderr, "Error: invalid <name=value>.\n\n");
opts->usage(prog);
exit(0);
}
return namevalue_new(strndup(name, eq - name), string_dup(eq + 1));
}
void parse_options(int argc, char *argv[], Options *opts)
{
extern char *optarg;
extern int optind;
int opt;
char *slash;
char *arg;
int len;
while ((opt = getopt(argc, argv, "s:p:o:D:vh")) != -1) {
switch (opt) {
case 's':
opts->srcpath = optarg;
break;
case 'p': {
/* remove trailing slashes? */
arg = optarg;
slash = arg + strlen(arg);
while (*--slash == '/');
len = slash - arg + 1;
Vector_Append(&opts->pathes, string_ndup(arg, len));
break;
}
case 'o':
opts->outpath = string_dup(optarg);
break;
case 'D':
Vector_Append(&opts->nvs, parse_namevalue(optarg, opts, argv[0]));
break;
case 'v':
opts->version();
exit(0);
break;
case 'h':
/* fall-through */
case '?':
opts->usage(argv[0]);
exit(0);
break;
default:
fprintf(stderr, "Error: invalid option '%c'.\n\n", opt);
opts->usage(argv[0]);
exit(0);
break;
}
}
while (optind < argc) {
if (!strcmp(argv[optind], "?")) {
opts->usage(argv[0]);
exit(0);
}
/* remove trailing slashes? */
arg = argv[optind++];
slash = arg + strlen(arg);
while (*--slash == '/');
len = slash - arg + 1;
Vector_Append(&opts->args, string_ndup(arg, len));
}
if (Vector_Size(&opts->args) == 0) {
fprintf(stderr, "Error: please specify pacakge(s).\n\n");
opts->usage(argv[0]);
exit(0);
}
}
int init_options(Options *opts, void (*usage)(char *), void (*version)(void))
{
memset(opts, 0, sizeof(Options));
Vector_Init(&opts->pathes);
Vector_Init(&opts->nvs);
Vector_Init(&opts->args);
opts->usage = usage;
opts->version = version;
return 0;
}
static void free_string_func(void *item, void *arg)
{
Mfree(item);
}
static void free_namevalue_func(void *item, void *arg)
{
namevalue_free(item);
}
void fini_options(Options *opts)
{
Mfree(opts->srcpath);
Mfree(opts->outpath);
Vector_Fini(&opts->pathes, free_string_func, NULL);
Vector_Fini(&opts->nvs, free_namevalue_func, NULL);
Vector_Fini(&opts->args, free_string_func, NULL);
}
int options_number(Options *opts)
{
int num = Vector_Size(&(opts)->pathes) + Vector_Size(&(opts)->nvs);
if (opts->srcpath != NULL)
num++;
if (opts->outpath != NULL)
num++;
return 2 * num;
}
void options_toarray(Options *opts, char *array[], int ind)
{
if (opts->srcpath != NULL) {
array[ind++] = string_dup("-s");
array[ind++] = string_dup(opts->srcpath);
}
char *path;
Vector_ForEach(path, &opts->pathes) {
array[ind++] = string_dup("-p");
array[ind++] = string_dup(path);
}
if (opts->outpath != NULL) {
array[ind++] = string_dup("-o");
array[ind++] = string_dup(opts->outpath);
}
char *buf;
struct namevalue *nv;
Vector_ForEach(nv, &opts->nvs) {
array[ind++] = string_dup("-D");
buf = Malloc(strlen(nv->name) + strlen(nv->value) + 2);
sprintf(buf, "%s=%s", nv->name, nv->value);
array[ind++] = buf;
}
}
void show_options(Options *opts)
{
char *s;
if (opts->srcpath != NULL)
Log_Printf("srcput: %s\n", opts->srcpath);
if (opts->outpath != NULL)
Log_Printf("output: %s\n", opts->outpath);
Log_Puts("pathes:");
Vector_ForEach(s, &opts->pathes) {
Log_Printf(" [%d]: %s\n", i, s);
}
Log_Puts("name-values:");
Vector_ForEach(s, &opts->nvs) {
Log_Printf(" [%d]: %s\n", i, s);
}
Log_Puts("arguments:");
Vector_ForEach(s, &opts->args) {
Log_Printf(" [%d]: %s\n", i, s);
}
Log_Puts("\n");
}
|
C
|
#pragma once
struct Books
{
unsigned int publ_date_day : 5; // Дата издания.День
unsigned int publ_date_month : 4; // Дата издания.Месяц
unsigned int publ_date_year : 11; // Дата издания.Год
char title_book[50]; // Название.
char author_name[20]; // Автор.Имя
char author_surname[20]; // Автор.Фамилия
char author_middle_name[20]; // Автор.Отчество
char genres[50]; // Жанр.
float price; // Стоимость.(за день оренды)
float rating; // Рейтинг.
unsigned int popularity = 0; // Популярность(количество взятий книги)
unsigned int id_book; // ID номер книги.
bool status = true; // статус книги ,на руках = фолс ,в библиотеке = тру
char owner[100] = "Library"; // у кого находится книга (можно попробовать через айдишник юзера ,если он будет позицией - будет быстрее)
unsigned int fine_days = 0; // Текущее кол-во просроченых дней по книге
float fine_money = 0; // Текущий денежный долг по книге
unsigned int take_date_day : 5; // Дата взятия.День
unsigned int take_date_month : 4; // Дата взятия.Месяц
unsigned int take_date_year : 11; // Дата взятия.Год
unsigned int return_date_day : 5; // Дата сдачи.День
unsigned int return_date_month : 4; // Дата сдачи.Месяц
unsigned int return_date_year : 11; // Дата сдачи.Год
};
|
C
|
#include <math.h>
#include "snackpack/snackpack.h"
#include "snackpack/internal/blas1_real_internal.h"
/* sasum for vectors with inc_x = 1 */
float
sp_blas_sasum_inc1(
len_t n,
const float * const x)
{
float tmp = 0.0f;
for (len_t i = 0; i < n; i++) {
tmp += fabsf(x[i]);
}
return tmp;
}
/* sasum for vectors with inc_x != x */
float
sp_blas_sasum_incx(
len_t n,
const float * const x,
len_t inc_x)
{
float tmp = 0.0f;
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
for (len_t i = 0; i < n; i++) {
tmp += fabsf(x[ix]);
ix += inc_x;
}
return tmp;
}
/* saxpy for inc_x = inc_y = 1 */
void
sp_blas_saxpy_inc1(
len_t n,
float alpha,
const float * const x,
float * const y)
{
if (alpha != 0.0f) {
for (len_t i = 0; i < n; i++) {
y[i] += alpha * x[i];
}
}
/* If alpha == 0, nothing to do */
}
/* saxpy for inc_x != 1 or inc_y != 1 */
void
sp_blas_saxpy_incxy(
len_t n,
float alpha,
const float * const x,
len_t inc_x,
float * const y,
len_t inc_y)
{
if (alpha != 0.0f) {
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
len_t iy = inc_y < 0 ? (len_t)((1 - n) * inc_y) : 0;
for (len_t i = 0; i < n; i++) {
y[iy] += alpha * x[ix];
ix += inc_x;
iy += inc_y;
}
}
/* If alpha == 0, nothing to do */
}
/* srot for inc_x = inc_y = 1 */
void
sp_blas_srot_inc1(
len_t n,
float * const x,
float * const y,
float c,
float s)
{
for (len_t i = 0; i < n; i++) {
float tmp = c * x[i] + s * y[i];
y[i] = c * y[i] - s * x[i];
x[i] = tmp;
}
}
/* srot for inc_x or inc_y != 1 */
void
sp_blas_srot_incxy(
len_t n,
float * const x,
len_t inc_x,
float * const y,
len_t inc_y,
float c,
float s)
{
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
len_t iy = inc_y < 0 ? (len_t)((1 - n) * inc_y) : 0;
for (len_t i = 0; i < n; i++) {
float tmp = c * x[ix] + s * y[iy];
y[iy] = c * y[iy] - s * x[ix];
x[ix] = tmp;
ix += inc_x;
iy += inc_y;
}
}
/* sswap for inc_x = inc_y = 1 */
void
sp_blas_sswap_inc1(
len_t n,
float * const x,
float * const y)
{
for (len_t i = 0; i < n; i++) {
float tmp = x[i];
x[i] = y[i];
y[i] = tmp;
}
}
/* sswap for inc_x, inc_y != 1 */
void
sp_blas_sswap_incxy(
len_t n,
float * const x,
len_t inc_x,
float * const y,
len_t inc_y)
{
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
len_t iy = inc_y < 0 ? (len_t)((1 - n) * inc_y) : 0;
for (len_t i = 0; i < n; i++) {
float tmp = x[ix];
x[ix] = y[iy];
y[iy] = tmp;
ix += inc_x;
iy += inc_y;
}
}
/* scopy for inc_x, inc_y = 1 */
void
sp_blas_scopy_inc1(
len_t n,
const float * const x,
float * const y)
{
for (len_t i = 0; i < n; i++) {
y[i] = x[i];
}
}
/* scopy for inc_x, inc_y != 1 */
void
sp_blas_scopy_incxy(
len_t n,
const float * const x,
len_t inc_x,
float * const y,
len_t inc_y)
{
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
len_t iy = inc_y < 0 ? (len_t)((1 - n) * inc_y) : 0;
for (len_t i = 0; i < n; i++) {
y[iy] = x[ix];
ix += inc_x;
iy += inc_y;
}
}
/* snrm2 for inc_x = 1 */
float
sp_blas_snrm2_inc1(
len_t n,
const float * const x)
{
float scale = 0.0f;
float sq = 1.0f;
for (len_t i = 0; i < n; i++) {
if (x[i] != 0.0f) {
float absx = fabsf(x[i]);
if (scale < absx) {
float tmp = scale / absx;
sq = 1.0f + sq * tmp * tmp;
scale = absx;
} else {
float tmp = absx / scale;
sq += tmp * tmp;
}
}
}
return scale * sqrtf(sq);
}
/* snrm2 for inc_x != 1 */
float
sp_blas_snrm2_incx(
len_t n,
const float * const x,
len_t inc_x)
{
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
float scale = 0.0f;
float sq = 1.0f;
for (len_t i = 0; i < n; i++) {
if (x[ix] != 0.0f) {
float absx = fabsf(x[ix]);
if (scale < absx) {
float tmp = scale / absx;
sq = 1.0f + sq * tmp * tmp;
scale = absx;
} else {
float tmp = absx / scale;
sq += tmp * tmp;
}
}
ix += inc_x;
}
return scale * sqrtf(sq);
}
/* isamax for inc = 1 */
len_t
sp_blas_isamax_inc1(
len_t n,
const float * const x)
{
len_t imax = 0;
float max = fabsf(x[imax]);
for (len_t i = 1; i < n; i++) {
float max_xi = fabsf(x[i]);
if (max_xi > max) {
max = max_xi;
imax = i;
}
}
return imax;
}
/* isamax for incx != 1 */
len_t
sp_blas_isamax_incx(
len_t n,
const float * const x,
len_t inc_x)
{
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
float max = fabsf(x[ix]);
len_t imax = ix;
ix += inc_x;
for (len_t i = 1; i < n; i++) {
float max_xi = fabsf(x[ix]);
if (max_xi > max) {
max = max_xi;
imax = ix;
}
ix += inc_x;
}
return imax;
}
/* isamin for inc = 1 */
len_t
sp_blas_isamin_inc1(
len_t n,
const float * const x)
{
len_t imin = 0;
float min = fabsf(x[imin]);
for (len_t i = 1; i < n; i++) {
float min_xi = fabsf(x[i]);
if (min_xi < min) {
min = min_xi;
imin = i;
}
}
return imin;
}
/* isamin for inc != 1 */
len_t
sp_blas_isamin_incx(
len_t n,
const float * const x,
len_t inc_x)
{
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
float min = fabsf(x[ix]);
len_t imin = ix;
ix += inc_x;
for (len_t i = 1; i < n; i++) {
float min_xi = fabsf(x[ix]);
if (min_xi < min) {
min = min_xi;
imin = ix;
}
ix += inc_x;
}
return imin;
}
/* sscal for inc = 1 */
void
sp_blas_sscal_inc1(
len_t n,
float alpha,
float * const x)
{
if (alpha == 0.0f) {
for (len_t i = 0; i < n; i++) {
x[i] = 0.0f;
}
} else {
for (len_t i = 0; i < n; i++) {
x[i] *= alpha;
}
}
}
/* sccal for inc != 1 */
void
sp_blas_sscal_incx(
len_t n,
float alpha,
float * const x,
len_t inc_x)
{
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
if (alpha == 0.0f) {
for (len_t i = 0; i < n; i++) {
x[ix] = 0.0f;
ix += inc_x;
}
} else {
for (len_t i = 0; i < n; i++) {
x[ix] *= alpha;
ix += inc_x;
}
}
}
/* sdot for inc_x = inc_y = 1 */
float
sp_blas_sdot_inc1(
len_t n,
const float * const x,
const float * const y)
{
float tmp = 0.0f;
for (len_t i = 0; i < n; i++) {
tmp += x[i] * y[i];
}
return tmp;
}
/* sdot for inc_x or inc_y != 1 */
float
sp_blas_sdot_incxy(
len_t n,
const float * const x,
len_t inc_x,
const float * const y,
len_t inc_y)
{
float tmp = 0.0f;
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
len_t iy = inc_y < 0 ? (len_t)((1 - n) * inc_y) : 0;
for (len_t i = 0; i < n; i++) {
tmp += x[ix] * y[iy];
ix += inc_x;
iy += inc_y;
}
return tmp;
}
/* sdsdot for inc_x = inc_y = 1 */
float
sp_blas_sdsdot_inc1(
len_t n,
float sb,
const float * const x,
const float * const y)
{
double tmp = (double)sb;
for (len_t i = 0; i < n; i++) {
tmp += (double)x[i] * (double)y[i];
}
return (float)tmp;
}
/* sdsdot for inc_x, inc_y != 1 */
float
sp_blas_sdsdot_incxy(
len_t n,
float sb,
const float * const x,
len_t inc_x,
const float * const y,
len_t inc_y)
{
double tmp = (double)sb;
len_t ix = inc_x < 0 ? (len_t)((1 - n) * inc_x) : 0;
len_t iy = inc_y < 0 ? (len_t)((1 - n) * inc_y) : 0;
for (len_t i = 0; i < n; i++) {
tmp += (double)x[ix] * (double)y[iy];
ix += inc_x;
iy += inc_y;
}
return (float)tmp;
}
|
C
|
/**
* Ohjelma muuntaa dollarit euroiksi, käyttäjä syöttää dollareiden määrän.
* 180919 Johanna Lyytinen
*/
#include <stdio.h>
const float rate = 0.90;
int main() {
float dollars = 0;
float euros = 0;
printf("Syötä dollarit: \n");
scanf("%f", &dollars);
euros = dollars * rate;
printf("%.4f dollaria on %.4f euroa.", dollars, euros);
return 0;
}
|
C
|
/* Bounded Variable Least Squares
*
* Solves the Bounded Variable Least Squares problem (or box-constrained
* least squares) of:
* minimize ||Ax - b||
* x 2
*
* given lb <= x <= ub
*
* where:
* A is an m x n matrix
* b, x, lb, ub are n vectors
*
* Based on the article Stark and Parker "Bounded-Variable Least Squares: an
* Alogirthm and Applications" retrieved from:
* http://www.stat.berkeley.edu/~stark/Preprints/bvls.pdf
*
* Copyright David Wiltshire (c), 2014
* All rights reserved
*
* Licence: see file LICENSE
*/
// Local Includes
#include "bvls.h"
// Third Party Includes
#include "cblas.h"
#include "lapacke.h"
// Standard Library Includes
#include <assert.h>
#include <errno.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
struct problem {
const double *A;
const double *b;
const double *lb;
const double *ub;
const int m;
const int n;
};
struct work {
int *indices;
int *istate;
double *w;
double *s;
double *A;
double *z;
int num_free;
int prev;
int rank;
};
/* Computes w(*) = trans(A)(Ax -b), the negative gradient of the residual.*/
static void
negative_gradient(struct problem *prob, struct work *work, double *x)
{
int m = prob->m;
int n = prob->n;
// z = b
memcpy(work->z, prob->b, m * sizeof(*work->z));
// z = (-Ax + b) = (b - Ax)
cblas_dgemv(CblasColMajor, CblasNoTrans, m, n, -1.0, prob->A, m, x, 1, 1.0, work->z, 1);
// w = trans(A)z + 0w = trans(A)r
cblas_dgemv(CblasColMajor, CblasTrans, m, n, 1.0, prob->A, m, work->z, 1, 0.0, work->w, 1);
}
/* Find the index which most wants to be free. Or return -1 */
static int
find_index_to_free(int n, struct work *work)
{
int index = -1;
double max_grad = 0.0;
for (int i = 0; i < n; ++i) {
double gradient = -work->w[i] * work->istate[i];
if (gradient > max_grad) {
max_grad = gradient;
index = i;
}
}
return index;
}
/* Move index to the free set */
static void
free_index(int index, struct work *work)
{
assert(index >= 0);
work->istate[index] = 0;
work->indices[work->num_free] = index;
++(work->num_free);
}
/*
* Build matrix A' and b' where A' is those columns of A that are free
* and b' is the vector less the contribution of the bound variables
*/
static void
build_free_matrices(struct problem *prob, struct work *work, double *x)
{
int m = prob->m;
int n = prob->n;
/* Set A' to free columns of A */
for (int i = 0; i < work->num_free; ++i) {
int ii = work->indices[i];
memcpy((work->A + i * m), (prob->A + m * ii), m * sizeof(*work->A));
}
/* Set b' = b */
memcpy(work->z, prob->b, m * sizeof(*work->z));
/* Adjust b'j = bj - sum{Aij * x[j]} for i not in Free set */
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (work->istate[j] != 0)
work->z[i] -= *(prob->A + j * m + i) * x[j];
}
}
}
/* Check that suggested solution is with in bounds */
static bool
check_bounds(struct problem *prob, struct work *work)
{
for (int i = 0; i < work->num_free; ++i) {
int ii = work->indices[i];
if (work->z[i] < prob->lb[ii] || work->z[i] > prob->ub[ii])
return false;
}
return true;
}
/* Set variable to upper/lower bound */
static void
bind_index(int index, bool up, double fixed, struct work *work, double *x)
{
x[work->indices[index]] = fixed;
work->istate[work->indices[index]] = up ? 1 : -1;
--(work->num_free);
for (int i = index; i < work->num_free; ++i)
work->indices[i] = work->indices[i + 1];
}
/*
* Find a variable to bind to a limit, and interpolate the solution:
* xj = xj + alpha(zj' - xj)
*/
static int
find_index_to_bind(struct problem *prob, struct work *work, double *x)
{
int index = -1;
bool bind_up = false;
double alpha = DBL_MAX;
for (int i = 0; i < work->num_free; ++i) {
int ii = work->indices[i];
double interpolate;
if (work->z[i] <= prob->lb[ii]) {
interpolate = (prob->lb[ii] - x[ii]) / (work->z[i] - x[ii]);
if (interpolate < alpha) {
alpha = interpolate;
index = i;
bind_up = false;
}
} else if (work->z[i] >= prob->ub[ii]) {
interpolate = (prob->ub[ii] - x[ii]) / (work->z[i] - x[ii]);
if (interpolate < alpha) {
alpha = interpolate;
index = i;
bind_up = true;
}
}
}
assert(index >= 0);
for (int i = 0; i < work->num_free; ++i) {
int ii = work->indices[i];
x[ii] += alpha * (work->z[i] - x[ii]);
}
int ii = work->indices[index];
double limit = bind_up? prob->ub[ii] : prob->lb[ii];
bind_index(index, bind_up, limit, work, x);
return index;
}
/* Move variables that are out of bounds to their respective bound */
static void
adjust_sets(struct problem *prob, struct work *work, double *x)
{
// We must repeat each loop where we bind an index as we will
// have removed that entry from indices
for (int i = 0; i < work->num_free; ++i) {
int ii = work->indices[i];
if (x[ii] <= prob->lb[ii]) {
bind_index(i--, false, prob->lb[ii], work, x);
} else if (x[i] >= prob->ub[i]) {
bind_index(i--, true, prob->ub[ii], work, x);
}
}
}
/*
* Check the result and adjust the sets accordingly.
* Returns the index bound
*/
static int
check_result(struct problem *prob, struct work *work, double *x)
{
int err = 0;
if (check_bounds(prob, work)) {
for (int i = 0; i < work->num_free; ++i)
x[work->indices[i]] = work->z[i];
} else {
work->prev = find_index_to_bind(prob, work, x);
adjust_sets(prob, work, x);
err = -1;
}
return err;
}
/* Loop B in Lawson and Hanson. Continually loop solving the problem and
* binding at least one variable each step till we find a valid solution or
* until every variable is bound.
*/
static void
find_valid_result(struct problem *prob, struct work *work, double *x)
{
int m = prob->m;
int n = prob->n;
int mn = m > n ? m : n;
while (work->num_free > 0) {
build_free_matrices(prob, work, x);
int rc = LAPACKE_dgels(LAPACK_COL_MAJOR, 'N', m, work->num_free,
1, work->A, m, work->z, mn);
assert(rc == 0);
if (check_result(prob, work, x) == 0)
break;
}
}
/* Set all variables to be bound to the lower bound */
static void
set_to_lower_bound(struct problem *prob, struct work *work, double *x)
{
int m = prob->m;
int n = prob->n;
work->rank = m < n ? m : n;
for (int i = 0; i < n; ++i) {
x[i] = prob->lb[i];
work->istate[i] = -1;
work->indices[i] = -1;
}
work->num_free = 0;
}
/* Use SVD to solve the problem unconstrained. If that fails to find a
* solution within bounds then attempt to find a valid starting solution
* with some variables free
*/
static int
solve_unconstrained(struct problem *prob, struct work *work, double *x)
{
int m = prob->m;
int n = prob->n;
int rc;
memcpy(work->A, prob->A, m * n * sizeof(*work->A));
memcpy(work->z, prob->b, m * sizeof(*work->z));
for (int i = m; i < n; ++i)
work->z[i] = 0.0;
rc = LAPACKE_dgelss(LAPACK_COL_MAJOR, m, n, 1, work->A, m, work->z,
m > n ? m : n, work->s, FLT_MIN, &work->rank);
if (rc < 0) {
set_to_lower_bound(prob, work, x);
return -1;
}
for (int i = 0; i < work->num_free; ++i)
x[work->indices[i]] = work->z[i];
if (check_bounds(prob, work)) {
rc = 0;
return 0;
} else {
adjust_sets(prob, work, x);
find_valid_result(prob, work, x);
return -1;
}
}
/* Allocate working arrays */
static int
allocate(int m, int n, struct work *work)
{
int mn = (m > n ? m : n);
if ((work->w = malloc(n * sizeof(*work->w)) ) == NULL ||
(work->A = malloc(m * n * sizeof(*work->A)) ) == NULL ||
(work->z = malloc(mn * sizeof(*work->z)) ) == NULL ||
(work->s = malloc(mn * sizeof(*work->s)) ) == NULL ||
(work->istate = malloc(n * sizeof(*work->istate)) ) == NULL ||
(work->indices = malloc(n * sizeof(*work->indices)) ) == NULL)
return -ENOMEM;
else
return 0;
}
/* Free memory */
static void
clean_up(struct work *work)
{
free(work->w);
free(work->A);
free(work->z);
free(work->s);
free(work->istate);
free(work->indices);
}
/*
* Initializes the problems:
* - check that lb and ub are valid
* - add every element to the free set
*/
static int
init(struct problem *prob, struct work *work)
{
int n = prob->n;
work->prev = -1;
work->num_free = n;
for (int i = 0; i < n; ++i) {
if (prob->lb[i] > prob->ub[i])
return -1;
work->indices[i] = i;
work->istate[i] = 0;
}
return 0;
}
/* The BVLS main function */
int
bvls(int m, int n, const double *restrict A, const double *restrict b,
const double *restrict lb, const double *restrict ub, double *restrict x)
{
struct work work;
struct problem prob = {.m = m, .n = n, .A = A, .b = b, .lb = lb, .ub = ub};
int rc;
int loops = 3 * n;
rc = allocate(m, n, &work);
if (rc < 0)
goto out;
rc = init(&prob, &work);
if (rc < 0)
goto out;
if (solve_unconstrained(&prob, &work, x) == 0)
goto out;
negative_gradient(&prob, &work, x);
for (loops = 3 * n; loops > 0; --loops) {
int index_to_free = find_index_to_free(n, &work);
/*
* If no index on a bound wants to move in to the
* feasible region then we are done
*/
if (index_to_free < 0)
break;
if (index_to_free == work.prev) {
work.w[work.prev] = 0.0;
continue;
}
/* Move index to free set */
free_index(index_to_free, &work);
/* Solve Problem for free set */
build_free_matrices(&prob, &work, x);
rc = LAPACKE_dgels(LAPACK_COL_MAJOR, 'N', m, work.num_free, 1,
work.A, m, work.z, m > n ? m : n);
if (rc < 0) {
work.prev = index_to_free;
work.w[work.prev] = 0.0;
if (x[work.prev] == prob.lb[work.prev]) {
work.istate[work.prev] = -1;
} else {
work.istate[work.prev] = 1;
}
--work.num_free;
continue;
}
if (check_result(&prob, &work, x) == 0) {
work.prev = -1;
} else {
find_valid_result(&prob, &work, x);
}
if (work.num_free == work.rank)
break;
negative_gradient(&prob, &work, x);
}
if (loops == 0) // failed to converge
rc = -1;
out:
clean_up(&work);
return rc;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, const char * argv[]) {
if ( argc < 2 ) { printf("Not enough arguments, Exiting...\n"); return 0;}
FILE *file = fopen(argv[1], "r");
const int MAX_CHAR = 1000000;
char line[MAX_CHAR]; // ^--: <100 friends with addresses in the range of
// 0<A<10000 + a little extra...
while (fgets(line, MAX_CHAR, file)) {
/* Input parsing */
char* token = strdup(line);
int no_friends = 0;
int* addr = NULL;
// Read in how many entries we have
if ( (token = strtok(token, " ")) ) {
sscanf(token, "%d", &no_friends);
addr = calloc(no_friends, sizeof(int));
} else { printf("Number of friends input parsing failed\n"); return 0;}
token = NULL;
// put the address numbers into the array
int idx = 0;
while ( (token = strtok(token, " \n")) != NULL )
{
sscanf(token, "%d", (addr + idx) );
token = NULL;
++idx;
}
/* calculation */
// Although confusingly written, if we take the floor of the arithmetic
// mean to find the "center" of the distribution, we can then find a sum
// of the distances between this center point and the other houses and
// sum these value up to get the answer.
// this should calculate the mean position for the "optimal" position of
// the house
int sum_house = 0;
for ( int i = 0; i < no_friends; ++i) {
sum_house += addr[i];
}
// should be the arithmetic mean rounded to the nearest integer...
int center = (int) round( (double)sum_house / (double)no_friends);
// this should calculate the sum of the differences
int sum_diff = 0;
for ( int i = 0; i < no_friends; ++i) {
sum_diff += abs(addr[i] - center);
}
/* DEBUG */
printf("Number of friends: %d\n", no_friends);
printf(" Optimal: %f\n", (double)sum_house / (double)no_friends );
printf(" Real: %d\n", center);
printf(" Sum_Diff: %d\n", sum_diff);
/*
printf(" Addresses: ");
for ( int i = 0; i < no_friends; ++i) {
printf("%d ", addr[i]);
}
printf("\n");
*/
//printf("%d\n", sum);
}
return 0;
}
|
C
|
/*
* ADC_TEST_Q6.c
*
* Created: 17/04/2020 06:31:46 م
* Author : Abdel-Rahman
*Requirements :
-Select ADC1 as input channel - ADCSRA prescaler /128 - ADCSRA auto trigger mode
-polling -ADMUX right adjust( no left adjust)
-internal reference 2.56v
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <string.h>
void ADC_Init(){
//select A1 as input
DDRA &=~(1<<1);
//ADC1 as input | Internal reference
ADMUX=(1<<REFS1)|(1<<REFS0); //00001=ADC1 |reference 1100 =C
ADCSRA=(1<<ADATE)|(1<<ADPS0)|(ADPS1)|(ADPS2)|(1<<ADEN);
}
unsigned int ADC_Read(unsigned channel){
ADMUX=0xC0 |(channel&0x07);
//start conversion
ADCSRA|=(1<<ADSC);
//check flag -
while(!(ADCSRA&(1<<ADIF))); //infinite loop --POLLING 100%
//clear flag
ADCSRA|=(1<<ADIF);
//ADCL
unsigned int data = ADCL;
//ADCH
data|=ADCH<<8;
return data;
}
int main(void)
{
ADC_Init();
while (1)
{
char buffer[10]="";
unsigned int pot_value= ADC_Read(1); //POT
//equation from to celius
sprintf(buffer,"%d",pot_value);
// LCD_String(buffer);
}
}
|
C
|
#include<stdio.h>
int main()
{
int n,i,arr[105],x=arr[0],y=arr[0];
scanf("%d",&n);
printf("Enter the size of the Array:%d",n);
printf("\nEnter Array values: ");
for(i=0; i<n; i++)
{
scanf("%d",&arr[i]);
}
for(i=0; i<n; i++)
{
if(x<arr[i])
{
x=arr[i];
}
else
{
y=arr[i];
}
}
printf("Maximum element is: %d\n",x);
printf("Minimum element is: %d\n",y);
return 0;
}
|
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 sep_lli_entry_t {unsigned long physical_address; unsigned long block_size; } ;
struct sep_device {int dummy; } ;
struct page {int dummy; } ;
/* Variables and functions */
int ENOMEM ;
int /*<<< orphan*/ GFP_ATOMIC ;
unsigned long PAGE_MASK ;
unsigned long PAGE_SHIFT ;
unsigned long PAGE_SIZE ;
int /*<<< orphan*/ dbg (char*,...) ;
int /*<<< orphan*/ edbg (char*,...) ;
struct sep_lli_entry_t* kmalloc (int,int /*<<< orphan*/ ) ;
scalar_t__ virt_to_phys (unsigned long*) ;
__attribute__((used)) static int sep_lock_kernel_pages(struct sep_device *sep,
unsigned long kernel_virt_addr,
unsigned long data_size,
unsigned long *num_pages_ptr,
struct sep_lli_entry_t **lli_array_ptr,
struct page ***page_array_ptr)
{
int error = 0;
/* the the page of the end address of the user space buffer */
unsigned long end_page;
/* the page of the start address of the user space buffer */
unsigned long start_page;
/* the range in pages */
unsigned long num_pages;
struct sep_lli_entry_t *lli_array;
/* next kernel address to map */
unsigned long next_kernel_address;
unsigned long count;
dbg("SEP Driver:--------> sep_lock_kernel_pages start\n");
/* set start and end pages and num pages */
end_page = (kernel_virt_addr + data_size - 1) >> PAGE_SHIFT;
start_page = kernel_virt_addr >> PAGE_SHIFT;
num_pages = end_page - start_page + 1;
edbg("SEP Driver: kernel_virt_addr is %08lx\n", kernel_virt_addr);
edbg("SEP Driver: data_size is %lu\n", data_size);
edbg("SEP Driver: start_page is %lx\n", start_page);
edbg("SEP Driver: end_page is %lx\n", end_page);
edbg("SEP Driver: num_pages is %lu\n", num_pages);
lli_array = kmalloc(sizeof(struct sep_lli_entry_t) * num_pages, GFP_ATOMIC);
if (!lli_array) {
edbg("SEP Driver: kmalloc for lli_array failed\n");
error = -ENOMEM;
goto end_function;
}
/* set the start address of the first page - app data may start not at
the beginning of the page */
lli_array[0].physical_address = (unsigned long) virt_to_phys((unsigned long *) kernel_virt_addr);
/* check that not all the data is in the first page only */
if ((PAGE_SIZE - (kernel_virt_addr & (~PAGE_MASK))) >= data_size)
lli_array[0].block_size = data_size;
else
lli_array[0].block_size = PAGE_SIZE - (kernel_virt_addr & (~PAGE_MASK));
/* debug print */
dbg("lli_array[0].physical_address is %08lx, lli_array[0].block_size is %lu\n", lli_array[0].physical_address, lli_array[0].block_size);
/* advance the address to the start of the next page */
next_kernel_address = (kernel_virt_addr & PAGE_MASK) + PAGE_SIZE;
/* go from the second page to the prev before last */
for (count = 1; count < (num_pages - 1); count++) {
lli_array[count].physical_address = (unsigned long) virt_to_phys((unsigned long *) next_kernel_address);
lli_array[count].block_size = PAGE_SIZE;
edbg("lli_array[%lu].physical_address is %08lx, lli_array[%lu].block_size is %lu\n", count, lli_array[count].physical_address, count, lli_array[count].block_size);
next_kernel_address += PAGE_SIZE;
}
/* if more then 1 pages locked - then update for the last page size needed */
if (num_pages > 1) {
/* update the address of the last page */
lli_array[count].physical_address = (unsigned long) virt_to_phys((unsigned long *) next_kernel_address);
/* set the size of the last page */
lli_array[count].block_size = (kernel_virt_addr + data_size) & (~PAGE_MASK);
if (lli_array[count].block_size == 0) {
dbg("app_virt_addr is %08lx\n", kernel_virt_addr);
dbg("data_size is %lu\n", data_size);
while (1);
}
edbg("lli_array[%lu].physical_address is %08lx, lli_array[%lu].block_size is %lu\n", count, lli_array[count].physical_address, count, lli_array[count].block_size);
}
/* set output params */
*lli_array_ptr = lli_array;
*num_pages_ptr = num_pages;
*page_array_ptr = 0;
end_function:
dbg("SEP Driver:<-------- sep_lock_kernel_pages end\n");
return 0;
}
|
C
|
// IMplementation of prefix to postfiz using Stack (implemented using Stack)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _Stack
{
int top;
unsigned int capacity ;
char *array;
}Stack;
//Stack implementation
//Create a new stack
Stack * createStack(int capacity){
//imp
Stack *stack = (Stack*)malloc(sizeof(Stack));
if(!stack){
return NULL;
}
stack->top = -1;
stack->capacity = capacity;
stack->array = (char*)malloc(sizeof(char)*capacity);
//impr
if(!stack->array){
return NULL;
}
return stack;
}
//Check if Empty
int isEmpty(Stack *stack){
return (stack->top==-1);
}
//check if Full
int isFull(Stack *stack){
return (stack->top==stack->capacity);
}
char pop(Stack *stack){
if(isEmpty(stack)){
return ;
}
//printf("return %c \n",stack->array[stack->top]);
return (stack->array[stack->top--]);
}
char push(Stack *stack,char new_item){
if(isFull(stack)){
return ;
}
//printf("int push %c \n",new_item);
stack->array[++stack->top]=new_item;
}
char peek(Stack *stack){
if(isEmpty(stack)){
return ;
}
return (stack->array[stack->top]);
}
//Stack Implementation
int isOperand(char check){
if((check >= '0' && check <='9') || (check >= 'a' && check <='z') || (check >= 'A' && check <='Z'))
return 1;
else
return 0;
}
//set the precedence
//only supporting +,- ,*,/
int precedence(char check){
switch (check){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default :
return 0;
}
}
//print the next element
void nextGreater(int arr[],int size){
int i=0,next,temp;
Stack *stack = createStack(size);
//push the first element
push(stack,arr[i]);
i++;
while (i<size){
next = arr[i];
if(!isEmpty(stack)){
temp = pop(stack);
//printf("%d(temp) => %d (next)\n",temp,next);
while(next > temp){
printf("%d => %d (next)\n",temp,next);
if(isEmpty(stack)){
break;
}
temp = pop(stack);
}
if(next < temp)
{
push(stack,temp);
}
}
push(stack,next);
i++;
}
//remainder elements not having any greater
while(!isEmpty(stack)){
temp = pop(stack);
printf("%d => %d (next)\n",temp,-1);
}
}
//Implement prefix to post fix
int preToPost(char * exp){
int k,i;//counter for new postfix expr
//create the stack
Stack *stack = createStack(strlen(exp));
printf("old exp %s\n", exp);
if(!stack){
printf("NO stack\n");
return;
}
//check if the element is operator or operand then
//while(exp[i]!='\0'){
//for(i=0,k=-1;exp[i];++i){
k=-1;
for(i=0;i<strlen(exp);i++){
printf(" i => j %d=>%d\n",i,k );
if(isOperand(exp[i])){
//k++;
exp[++k]=exp[i];
}
else if (exp[i]=='('){
push(stack,exp[i]);
}
else if (exp[i]==')')
{
//if you find the ')' to pop and store it in expr(till '(s')
while( !isEmpty(stack) && peek(stack)!='(' ){
exp[++k]=pop(stack);
}
//*** imp
//if end reached and '(' not found
//if end and no '(' then issue with expression , no balance in ()
if(!isEmpty(stack) && peek(stack)!='('){
printf("Invalid expression\n");
return -1;
}
else
pop(stack);
}
else//operator encountered
{
//two conditions
//1) if no operator on stack
//2)
//check the stack for precedence
while(!isEmpty(stack) && precedence(exp[i])<= precedence(peek(stack))){
exp[++k] = pop(stack);
}
push(stack,exp[i]);
}
}
//left out experession value
while (!isEmpty(stack)){
exp[++k]=pop(stack);
}
exp[++k]='\0';
//vvimp to \o
//printf("Post %s\n",exp);
}
int main (){
printf("IMplementation of prefix to postfix and eval postfix\n");
char Str[]="a+b*(c^d-e)^(f+g*h)-i";
int i=0;
//*works fine
//int array[] = {1,3,23,8,5,20};
//nextGreater(array,sizeof(array)/sizeof(array[0]));
/*
Stack * stack = createStack(strlen(Str));
for (i=0;i<strlen(Str);i++){
//printf("push value %c\n",Str[i]);
push(stack,Str[i]);
}
for (i=0;i<strlen(Str);i++){
printf("%c",pop(stack));
}
printf("\n");
*/
printf("Pre %s\n",Str);
preToPost(Str);
printf("Post %s\n",Str);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "gmp.h"
#include "function.h"
#include "key.h"
/*
** Key();
**
*/
static unsigned long int seed = 1;
void key(key_gpq_t *key, mpz_t Ks, mpz_t Kp) {
//Cacul d'un nombre aléatoire entre 2 et p-2 (Ks)
mpz_t tmp;
gmp_randstate_t state;
mpz_init(tmp);
mpz_init(Ks);
gmp_randinit_mt(state);
gmp_randseed_ui(state, seed *rand());
seed += 1;
mpz_sub_ui(tmp, key->p, 4); // tmp = p - 4
mpz_urandomm(Ks, state, tmp);// 0 <= x <= p - 4
mpz_add_ui(Ks, Ks, 2); // 2 <= x <= p - 2
//Calcul de h = g^x(mod p) (Kp)
mpz_init(Kp);
ExpMod(Kp, key->g, Ks, key->p);
}
|
C
|
#include "timestep.h"
#include "settingsProgram.h"
void timestepInit(
timestep *const restrict step,
const float updateRate, const float renderRate,
const float timeSpeed
){
// Updates/renders per second.
step->updateRate = updateRate;
step->renderRate = renderRate;
// Seconds per update/render.
step->updateDelta = 1.f / updateRate;
// This is the time to interpolate for when
// we're rendering the scene. We set this
// value during the program loop.
step->renderDelta = 0.f;
// Updates/renders per millisecond.
step->updateTickrate = updateRate / 1000.f;
step->renderTickrate = renderRate / 1000.f;
// Milliseconds per update/render.
step->updateTime = 1000.f / updateRate;
step->renderTime = (renderRate <= 0.f) ? 0.f : 1000.f / renderRate;
// Controls spacing between updates
// independently to update logic.
timestepSetTimeSpeed(step, timeSpeed);
}
/*
** Change the program's speed to the value given by "timeSpeed".
** Note that this just controls the spacing between updates,
** and will not affect the logic performed during each update.
*/
void timestepSetTimeSpeed(timestep *const restrict step, const float timeSpeed){
// If "timeSpeed" is the percentage of ordinary speed, we can think
// of "timeScale" as how much to stretch out time. A value greater
// than '1' will stretch updates further apart, whereas a value
// between '0' and '1' will pull them closer together.
const float timeScale = 1.f / timeSpeed;
step->timeSpeed = timeSpeed;
step->updateTickrateScaled = timeScale * step->updateTickrate;
step->updateTimeScaled = timeScale * step->updateTime;
}
|
C
|
#include <stdio.h>
int main()
{
int a;
int result;
int temp;
int i;
while(scanf("%d", &a) != EOF)
{
result = 1;
for (i = 0; i < a; ++i)
{
scanf("%d",&temp);
if(temp % 2 == 1)
result = result * temp;
}
printf("%d\n", result);
}
return 0;
}
|
C
|
//633_Sum_of_Square_Numbers.h
//3ms 99.85%
/*
Total Accepted: 8.1k
Total Submissions: 25.7k
Instruction: LeetCode 633 - Sum of Square Numbers - [E]
Developer: lrushx
Process Time: Aug 14, 2017
*/
/*
Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a^2 + b^2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
*/
//inspired by Fermat's Conjecture
//return true if the number of each prime factor which can be written as p=4m+3 is even.
//once there is a prime factor p=4m+3 in odd times, return false
//example: 18 = 3*3*2, there are 2 times for the prime factor 3, return true(3^2+3^2)
//example: 27 = 3*3*3, there are 3 times for the prime factor 3, return false
bool judgeSquareSum(int c) {
int div = 3,t,sq = sqrt(c);
if ((c-3)%4 == 0) return false;
for (int i=2;i<=sq;i++){
if (c % i == 0){
if ((i-3) % 4 == 0){
t = 0;
while (c % i == 0){
t++;
c /= i;
}
if ((t & 1) == 1) return false;
}
else while (c % i == 0) c /= i;
if (c == 1) return true;
}
}
if ((c-3)%4 == 0) return false;
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.