language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* my_unset.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yyabumot <yyabumot@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/04 14:52:21 by yyabumot #+# #+# */
/* Updated: 2021/03/04 14:52:21 by yyabumot ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "env_ctrl.h"
#include "constants.h"
#include "exit_status.h"
#include "struct/env_list.h"
extern t_env_list *g_env_list;
static void put_invalid_env_key_error(char *key)
{
ft_putstr_fd("minishell: unset: \'", STD_ERR);
ft_putstr_fd(key, STD_ERR);
ft_putstr_fd("\': not a valid identifier\n", STD_ERR);
}
static void unset_env_node(t_env_list *delete_node)
{
delete_node->prev->next = delete_node->next;
delete_node->next->prev = delete_node->prev;
free_env_node(delete_node);
}
int my_unset(char **args)
{
int i;
int exit_status;
t_env_list *delete_node;
i = 1;
exit_status = SUCCEEDED;
while (args[i])
{
if (!is_valid_env_key(args[i]))
{
put_invalid_env_key_error(args[i]);
++i;
exit_status = GENERAL_ERRORS;
continue;
}
if ((delete_node = search_env_node(args[i])) == g_env_list)
{
++i;
continue;
}
unset_env_node(delete_node);
++i;
}
return (exit_status);
}
|
C
|
/*
bluepp
2014-06-02
2014-07-08
2014-08-07
2014-11-23
May the force be with me!
Problem: Binary Tree Postorder Traversal
Source: http://oj.leetcode.com/problems/binary-tree-postorder-traversal/
Notes:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
Solution: 1. Iterative way (stack). Time: O(n), Space: O(n).
2. Recursive solution. Time: O(n), Space: O(n).
3. Threaded tree (Morris). Time: O(n), Space: O(1).
for more detailed explanations:
http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html
*/
/* my version */
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
if (!root) return res;
stack<TreeNode*> s;
TreeNode *prev = NULL;
s.push(root);
while (!s.empty())
{
TreeNode *pCurr = s.top();
if (!prev || prev->left == pCurr|| prev->right == pCurr)
{
if (pCurr->left) s.push(pCurr->left);
else if(pCurr->right) s.push(pCurr->right);
}
else if (pCurr->left == prev)
{
if (pCurr->right) s.push(pCurr->right);
}
else
{
res.push_back(pCurr->val);
s.pop();
}
prev = pCurr;
}
return res;
}
/* ---------------------------------- */
/* Morris , 2015-07-24 */
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
TreeNode dump(0);
dump.left = root;
TreeNode *cur = &dump, *prev = NULL;
while (cur)
{
if (cur->left)
{
prev = cur->left;
while (prev->right != NULL && prev->right != cur)
prev = prev->right;
if (prev->right == NULL)
{
prev->right = cur;
cur = cur->left;
}
else
{
printReverse(cur->left, prev, res); // call print
prev->right = NULL;
cur = cur->right;
}
}
else
{
cur = cur->right;
}
}
return res;
}
void printReverse(TreeNode* from, TreeNode *to, vector<int>& res) // print the reversed tree nodes 'from' -> 'to'.
{
reverse(from, to);
TreeNode *p = to;
while (true)
{
res.push_back(p->val);
if (p == from)
break;
p = p->right;
}
reverse(to, from);
}
void reverse(TreeNode *from, TreeNode *to) // reverse the tree nodes 'from' -> 'to'.
{
if (from == to)
return;
TreeNode *x = from, *y = from->right, *z;
while (true)
{
z = y->right;
y->right = x;
x = y;
y = z;
if (x == to)
break;
}
}
/* ----------------------------- */
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
stack<TreeNode *> s;
TreeNode *pCurr = root, *prev = NULL;
while (pCurr || !s.empty())
{
if (pCurr)
{
s.push(pCurr);
pCurr = pCurr->left;
}
else
{
TreeNode *pTmp = s.top();
if (pTmp->right && prev != pTmp->right)
{
pCurr = pTmp->right;
}
else
{
res.push_back(pTmp->val);
s.pop();
prev = pTmp;
}
}
}
return res;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define UseAESedp // Tell AES.h to define things for AESedp.
#include "AES.h"
/* In comments below, {n} designates the Galois field element represented by
the byte n. See notes about Galois field multiplication in ReadMe.txt.
So 3+5 is addition of ordinary integers, and 3+5 == 8, while {3}+{5} is
addition in the field, and {3} + {5} = {3 XOR 5} = {6}.)
*/
// Define constants for languages.
typedef enum { C, IntelAssembly } Language;
/* LogBase3[i] will contain the base-three logarithm of i in the 256-element
Galois field defined by AES. That is, {3}**LogBase3[i] == {3}**i.
*/
static Byte LogBase3[256];
/* AntilogBase3[i] will contain {3}**i in the 256-element Galois field defined
by AES. It contains extra elements so that the antilog of a+b can be found
by looking up a+b directly, without having to reduce modulo the period, for
0 <= a, b < 255.
(254 is the greatest value we encounter. Each a or b we use is the
base-three logarithm of some element. As a primitive root, the powers of
three cycle through all non-zero elements of the field, of which there are
255, so the exponents cover 0 to 254 before the powers repeat.)
*/
static Byte AntilogBase3[254+254+1];
static void InitializeLogTables(void)
{
// log({1}) is zero, so start {p} (power) at {1} and l (logarithm) at 0.
Byte p = 1;
int l = 0;
do
{
// Record table entries.
LogBase3[p] = l;
AntilogBase3[l] = p;
/* Observe that {2}*{p} is {p << 1 ^ (a & 0x80 ? 0x1b : 0)}, per notes
in ReadMe.txt. We produce {3}*{p}:
{3}*{p}
= {1}*{p} + {2}*{p}
= {1}*{p} + {p << 1 ^ (a & 0x80 ? 0x1b : 0)}
= {p ^ p << 1 ^ (p & 0x80 ? 0x1b : 0)}.
*/
p ^= p << 1 ^ (p & 0x80 ? 0x1b : 0);
++l;
} while (p != 1); // Stop when we have gone around completely.
/* The antilogarithms are periodic with a period of 255, and we want to
look up elements as high as 254+254 (the largest that a sum of two
logarithms could be), so we replicate the table beyond the first
period.
*/
for (l = 255; l < 254+254; ++l)
AntilogBase3[l] = AntilogBase3[l-255];
}
/* MultiplyByte(Byte b, Byte c) returns {b}*{c}. It requires tables that must
be initialized before this routine is used.
*/
static Byte MultiplyByte(Byte b, Byte c)
{
// Calculate product by adding logarithms, but avoid logarithms of zero.
return b == 0 || c == 0 ? 0 : AntilogBase3[LogBase3[b] + LogBase3[c]];
}
// Return {0} if {b} is {0} and the multiplicative inverse of {b} otherwise.
static Byte InverseByte(Byte b)
{
return b == 0 ? 0 : AntilogBase3[255 - LogBase3[b]];
}
// Perform AES' SubBytes operation on a single byte.
static Byte SubByte(Byte b)
{
unsigned int r = InverseByte(b);
// Duplicate r as a proxy for a rotate operation.
r = r | r<<8;
// Apply the standard's affine transformation.
return r ^ r>>4 ^ r>>5 ^ r>>6 ^ r>>7 ^ 0x63;
}
// Define and populate tables for the SubBytes and InvSubBytes operations.
static Byte SubBytesTable[256];
static Byte InvSubBytesTable[256];
static void InitializeSubBytesTable(void)
{
for (int i = 0; i < 256; ++i)
SubBytesTable[i] = SubByte((Byte) i);
}
static void InitializeInvSubBytesTable(void)
{
for (int i = 0; i < 256; ++i)
InvSubBytesTable[SubByte((Byte) i)] = i;
}
/* Print tables for SubBytes function providing the output byte embedded in
various places in a word, so that the table entries can be used with
fewer byte manipulations.
*/
static void PrintSubBytesWordTable(Language language)
{
switch (language)
{
case C:
printf("\n\n"
"// SubBytes embedded in words tables.\n"
"const Word AESSubBytesWordTable[4][256] =\n"
"{\n");
for (int j = 0; j < 4; ++j)
{
printf("\t{\n");
for (int i = 0; i < 256; ++i)
printf("\t\t0x%08x,\n", SubBytesTable[i] << j*8);
printf("\t},\n");
}
printf("};\n");
break;
case IntelAssembly:
printf("\n\n"
"// SubBytes embedded in words tables.\n"
"\t.globl\t_AESSubBytesWordTable\n"
"\t.private_extern\t_AESSubBytesWordTable\n"
"\t.align\t2\n"
"_AESSubBytesWordTable:\n");
for (int j = 0; j < 4; ++j)
{
printf("\t// Table %d.\n", j);
for (int i = 0; i < 256; ++i)
printf("\t.long\t0x%08x\n", SubBytesTable[i] << j*8);
}
break;
}
}
/* Print tables for InvSubBytes function providing the output byte embedded in
various places in a word, so that the table entries can be used with
fewer byte manipulations.
*/
static void PrintInvSubBytesWordTable(Language language)
{
switch (language)
{
case C:
printf("\n\n"
"// InvSubBytes embedded in words tables.\n"
"const Word AESInvSubBytesWordTable[4][256] =\n"
"{\n");
for (int j = 0; j < 4; ++j)
{
printf("\t{\n");
for (int i = 0; i < 256; ++i)
printf("\t\t0x%08x,\n", InvSubBytesTable[i] << j*8);
printf("\t},\n");
}
printf("};\n");
break;
case IntelAssembly:
printf("\n\n"
"// InvSubBytes embedded in words tables.\n"
"\t.globl\t_AESInvSubBytesWordTable\n"
"\t.private_extern\t_AESInvSubBytesWordTable\n"
"\t.align\t2\n"
"_AESInvSubBytesWordTable:\n");
for (int j = 0; j < 4; ++j)
{
printf("\t// Table %d.\n", j);
for (int i = 0; i < 256; ++i)
printf("\t.long\t0x%08x\n", InvSubBytesTable[i] << j*8);
}
break;
}
}
// Print the round constants.
static void PrintRcon(Language language)
{
union { Byte c[4]; Word w; } t = { { 1, 0, 0, 0 } };
switch (language)
{
case C:
printf("\n\n"
"// Round constants.\n"
"const Byte AESRcon[] =\n"
"{\n"
"\t0,\t// Not used, included for indexing simplicity.\n");
for (int i = 1; i < MaxRcon; ++i)
{
printf("\t0x%02x,\n", t.w);
t.c[0] = MultiplyByte(0x2, t.c[0]);
}
printf("};\n");
break;
case IntelAssembly:
printf("\n\n"
"// Round constants.\n"
"\t.globl\t_AESRcon\n"
"\t.private_extern\t_AESRcon\n"
"_AESRcon:\n"
"\t.byte\t0\t// Not used, included for indexing simplicity.\n");
for (int i = 1; i < MaxRcon; ++i)
{
printf("\t.byte\t0x%02x\n", t.w);
t.c[0] = MultiplyByte(0x2, t.c[0]);
}
break;
}
}
// Print tables for the InvMixColumn operation.
static void PrintInvMixColumnTable(Language language)
{
Word T[4][256];
for (int i = 0; i < 256; ++i)
{
union { Byte b[4]; Word w; } c;
Byte s9 = MultiplyByte(0x9, i);
Byte sb = MultiplyByte(0xb, i);
Byte sd = MultiplyByte(0xd, i);
Byte se = MultiplyByte(0xe, i);
c.b[0] = se;
c.b[1] = s9;
c.b[2] = sd;
c.b[3] = sb;
T[0][i] = c.w;
c.b[0] = sb;
c.b[1] = se;
c.b[2] = s9;
c.b[3] = sd;
T[1][i] = c.w;
c.b[0] = sd;
c.b[1] = sb;
c.b[2] = se;
c.b[3] = s9;
T[2][i] = c.w;
c.b[0] = s9;
c.b[1] = sd;
c.b[2] = sb;
c.b[3] = se;
T[3][i] = c.w;
}
switch (language)
{
case C:
printf("\n\n"
"// Tables for InvMixColumn.\n"
"const Word AESInvMixColumnTable[4][256] =\n"
"{\n");
for (int i = 0; i < 4; ++i)
{
printf("\t{\n");
for (int j = 0; j < 256; ++j)
printf("\t\t0x%08x,\n", T[i][j]);
printf("\t},\n");
}
printf("};\n");
break;
case IntelAssembly:
printf("\n\n"
"// Tables for InvMixColumn.\n"
"\t.globl\t_AESInvMixColumnTable\n"
"\t.private_extern\t_AESInvMixColumnTable\n"
"\t.align\t2\n"
"_AESInvMixColumnTable:\n");
for (int i = 0; i < 4; ++i)
{
printf("\t// Table %d.\n", i);
for (int j = 0; j < 256; ++j)
printf("\t.long\t0x%08x\n", T[i][j]);
}
break;
}
}
/* Print the tables defined AES Proposal: Rijndael, amended, 9/04/2003,
section 5.2.1. These combine the MixColumn and SubBytes operations.
*/
static void PrintEncryptTable(Language language)
{
Word T[4][256];
for (int i = 0; i < 256; ++i)
{
union { Byte b[4]; Word w; } c;
Byte s1 = SubBytesTable[i];
Byte s2 = MultiplyByte(0x2, s1);
Byte s3 = s1 ^ s2;
c.b[0] = s2;
c.b[1] = s1;
c.b[2] = s1;
c.b[3] = s3;
T[0][i] = c.w;
c.b[0] = s3;
c.b[1] = s2;
//c.b[2] = s1;
c.b[3] = s1;
T[1][i] = c.w;
c.b[0] = s1;
c.b[1] = s3;
c.b[2] = s2;
//c.b[3] = s1;
T[2][i] = c.w;
//c.b[0] = s1;
c.b[1] = s1;
c.b[2] = s3;
c.b[3] = s2;
T[3][i] = c.w;
}
switch (language)
{
case C:
printf("\n\n"
"// Tables for main encryption iterations.\n"
"const Word AESEncryptTable[4][256] =\n"
"{\n");
for (int i = 0; i < 4; ++i)
{
printf("\t{\n");
for (int j = 0; j < 256; ++j)
printf("\t\t0x%08x,\n", T[i][j]);
printf("\t},\n");
}
printf("};\n");
break;
case IntelAssembly:
printf("\n\n"
"// Tables for main encryption iterations.\n"
"\t.globl\t_AESEncryptTable\n"
"\t.private_extern\t_AESEncryptTable\n"
"\t.align\t2\n"
"_AESEncryptTable:\n");
for (int i = 0; i < 4; ++i)
{
printf("\t// Table %d.\n", i);
for (int j = 0; j < 256; ++j)
printf("\t.long\t0x%08x\n", T[i][j]);
}
break;
}
}
/* Print the inverse tables. These correspond to the tables above, but for
decyrption. These combine the InvSubBytes and InvMixColumn operations.
*/
static void PrintDecryptTable(Language language)
{
Word T[4][256];
for (int i = 0; i < 256; ++i)
{
union { Byte b[4]; Word w; } c;
Byte si = InvSubBytesTable[i];
Byte s9 = MultiplyByte(0x9, si);
Byte sb = MultiplyByte(0xb, si);
Byte sd = MultiplyByte(0xd, si);
Byte se = MultiplyByte(0xe, si);
c.b[0] = se;
c.b[1] = s9;
c.b[2] = sd;
c.b[3] = sb;
T[0][i] = c.w;
c.b[0] = sb;
c.b[1] = se;
c.b[2] = s9;
c.b[3] = sd;
T[1][i] = c.w;
c.b[0] = sd;
c.b[1] = sb;
c.b[2] = se;
c.b[3] = s9;
T[2][i] = c.w;
c.b[0] = s9;
c.b[1] = sd;
c.b[2] = sb;
c.b[3] = se;
T[3][i] = c.w;
}
switch (language)
{
case C:
printf("\n\n"
"// Tables for main decryption iterations.\n"
"const Word AESDecryptTable[4][256] =\n"
"{\n");
for (int i = 0; i < 4; ++i)
{
printf("\t{\n");
for (int j = 0; j < 256; ++j)
printf("\t\t0x%08x,\n", T[i][j]);
printf("\t},\n");
}
printf("};\n");
break;
case IntelAssembly:
printf("\n\n"
"// Tables for main decryption iterations.\n"
"\t.globl\t_AESDecryptTable\n"
"\t.private_extern\t_AESDecryptTable\n"
"\t.align\t2\n"
"_AESDecryptTable:\n");
for (int i = 0; i < 4; ++i)
{
printf("\t// Table %d.\n", i);
for (int j = 0; j < 256; ++j)
printf("\t.long\t0x%08x\n", T[i][j]);
}
break;
}
}
static void Usage(const char *ProgramName)
{
fprintf(stderr,
"%s: This program must have exactly one argument, \"C\" to generate\n"
"C or \"Intel\" to generate GCC i386/x86_64 assembly.\n", ProgramName);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
if (argc != 2)
Usage(argv[0]);
Language language;
// Figure out which language to generate, C or Intel assembly.
if (0 == strcmp(argv[1], "C"))
language = C;
else if (0 == strcmp(argv[1], "Intel"))
language = IntelAssembly;
else
Usage(argv[0]);
printf("// This file was generated by " __FILE__ ".\n");
if (language == C)
printf("\n\n#include \"AES.h\"\n");
if (language == IntelAssembly)
printf("\n\n\t.const\n");
InitializeLogTables();
InitializeSubBytesTable();
InitializeInvSubBytesTable();
PrintRcon(language);
PrintInvMixColumnTable(language);
PrintEncryptTable(language);
PrintDecryptTable(language);
PrintSubBytesWordTable(language);
PrintInvSubBytesWordTable(language);
return 0;
}
|
C
|
i#include <stdio.h>
int main()
{
double a;
double b;
double MEDIA;
double aa ;
double bb;
scanf("%lf %lf",&a,&b);
aa = a * 3.5 ;
bb = b * 7.5;
MEDIA = (aa + bb) /11;
printf("MEDIA = %.5lf\n",MEDIA);
return 0;
}
|
C
|
#include <pthread.h>
#include "papi_test.h"
void *
pthread_main( void *arg )
{
( void ) arg;
int retval = PAPI_register_thread( );
if ( retval != PAPI_OK ) {
test_fail( __FILE__, __LINE__, "PAPI_register_thread", retval );
}
clockcore( );
retval = PAPI_unregister_thread( );
if ( retval != PAPI_OK ) {
test_fail( __FILE__, __LINE__, "PAPI_unregister_thread", retval );
}
return NULL;
}
int
main( int argc, char **argv )
{
pthread_t t1, t2, t3, t4;
pthread_attr_t attr;
int retval;
/* Set TESTS_QUIET variable */
tests_quiet( argc, argv );
if (( retval = PAPI_library_init( PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) {
test_fail( __FILE__, __LINE__, "PAPI_library_init", retval );
}
retval = PAPI_thread_init( ( unsigned long ( * )(void) ) (pthread_self) );
if ( retval != PAPI_OK ) {
if ( retval == PAPI_ECMP ) {
test_skip( __FILE__, __LINE__, "PAPI_thread_init", retval );
}
else {
test_fail( __FILE__, __LINE__, "PAPI_thread_init", retval );
}
}
if ( !TESTS_QUIET ) {
printf( "Test case: Clock latency and resolution.\n" );
printf( "Note: Virtual timers are proportional to # CPUs.\n" );
printf( "------------------------------------------------\n" );
}
pthread_attr_init( &attr );
#ifdef PTHREAD_CREATE_UNDETACHED
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_UNDETACHED );
#endif
#ifdef PTHREAD_SCOPE_SYSTEM
retval = pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM );
if ( retval != 0 ) {
test_skip( __FILE__, __LINE__, "pthread_attr_setscope", retval );
}
#endif
if (pthread_create( &t1, &attr, pthread_main, NULL )) {
test_fail(__FILE__, __LINE__, "cannot create thread", retval);
}
if (pthread_create( &t2, &attr, pthread_main, NULL )) {
test_fail(__FILE__, __LINE__, "cannot create thread", retval);
}
if (pthread_create( &t3, &attr, pthread_main, NULL )) {
test_fail(__FILE__, __LINE__, "cannot create thread", retval);
}
if (pthread_create( &t4, &attr, pthread_main, NULL )) {
test_fail(__FILE__, __LINE__, "cannot create thread", retval);
}
pthread_main( NULL );
pthread_join( t1, NULL );
pthread_join( t2, NULL );
pthread_join( t3, NULL );
pthread_join( t4, NULL );
test_pass( __FILE__, NULL, 0 );
exit( 0 );
}
|
C
|
// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "AVLNode.h"
int32_t avl_test_print(avlnode_ptr node, int32_t dep) {
if (!node) {
return 0;
}
if (node->left) {
avl_test_print(node->left,dep + 1);
}
if (node->right) {
avl_test_print(node->right,dep +1 );
}
printf("%d\n", node->key.size);
if (node->parent) {
printf("the paren is %d\n",node->parent->key.size);
}
return 1;
}
avlnode_ptr avl_test_search(avlnode_ptr node, str_t key){
if (!node) {
return NULL;
}
if (node->key.size == key.size) {
return node;
} else {
if (node->key.size < key.size) {
return avl_test_search(node->right, key);
} else {
return avl_test_search(node->left, key);
}
}
}
int32_t avl_test_remove_node(avlnode_ptr *node, avlnode_ptr node_new) {
if (!(*node)) {
printf("NO\n");
return -1;
}
printf("top is %d\n",(*node)->key.size);
if ((*node)->key.size < node_new->key.size) {
return avl_test_remove_node(&(*node)->right, node_new);
} else if ((*node)->key.size > node_new->key.size ) {
return avl_test_remove_node(&(*node)->left, node_new);
} else {
if (!(*node)->left && !(*node)->right) {
printf("No child\n");
avlnode_ptr last = (*node)->parent;
if (last && (last->left == *node)) {
last->left = NULL;
printf("left\n");
} else if (last) {
last->right = NULL;
printf("right\n");
}
avl_calc_hight(last);
//delete key
//delete page
//???????????
free((*node));
} else if ((*node)->left && (*node)->right) {
printf("All child\n");
avlnode_ptr mid1 = *node, mid2;
mid1 = mid1-> left;
while (mid1->right) {
mid1 = mid1->right;
}
//delete key
//delete page
//???????????
(*node)->key = mid1->key;
(*node)->page = mid1->page;
if (mid1 == (*node)->left) {
(*node)->left = mid1->left;
if (mid1->left) {
mid1->left->parent = *node;
}
avl_calc_hight(*node);
avl_rebalance(node);
} else {
if (mid1->left) {
mid1->left->parent = mid1->parent;
}
mid1->parent->right = mid1->left;
mid2 = mid1->parent;
mid1->key.ptr = NULL;
mid1->page = NULL;
free(mid1);
while (mid2 != (*node)) {
avl_calc_hight(mid2);
avl_rebalance(&mid2);
mid2 = mid2->parent;
}
avl_calc_hight(*node);
avl_rebalance(node);
}
} else if ((*node)->left) {
printf("left child\n");
avlnode_ptr mid1 = (*node)->left;
//delete key
//delete page
//???????????
(*node)->key = mid1->key;
(*node)->page = mid1->page;
(*node)->left = mid1->left;
(*node)->right = mid1->right;
avl_calc_hight(*node);
mid1->key.ptr = NULL;
mid1->page = NULL;
free(mid1);
} else if ((*node)->right) {
printf("right child\n");
avlnode_ptr mid1 = (*node)->right;
//delete key
//delete page
//???????????
(*node)->key = mid1->key;
(*node)->page = mid1->page;
(*node)->left = mid1->left;
(*node)->right = mid1->right;
avl_calc_hight(*node);
mid1->key.ptr = NULL;
mid1->page = NULL;
free(mid1);
}
}
avl_calc_hight(*node);
avl_rebalance(node);
return 1;
}
|
C
|
#include <stdio.h>
#include "machin_serial.c"
#define PI 3.14159265358979323846
int main(int argc, char const *argv[])
{
FILE *fp;
fp = fopen("./machin0_residual.txt", "w");
double pi_k = 0;
for (int k=1; k<=24; ++k) {
pi_k = machin0(pow(2,k));
double resi = fabs(PI - pi_k);
fprintf(fp, "n = %.0lf,\t\t\tresidual = %.15lf\n", pow(2,k), resi);
}
fclose(fp);
printf("Done writing to file\n");
}
|
C
|
/**
* @file icl_hash.c
*
* Dependency free hash table implementation.
*
* This simple hash table implementation should be easy to drop into
* any other peice of code, it does not depend on anything else :-)
*
* @author Jakub Kurzak
*/
/* $Id: icl_hash.c 2838 2011-11-22 04:25:02Z mfaverge $ */
/* $UTK_Copyright: $ */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "hash.h"
#include <limits.h>
#define BITS_IN_int ( sizeof(int) * CHAR_BIT )
#define THREE_QUARTERS ((int) ((BITS_IN_int * 3) / 4))
#define ONE_EIGHTH ((int) (BITS_IN_int / 8))
#define HIGH_BITS ( ~((unsigned int)(~0) >> ONE_EIGHTH ))
/**
* A simple string hash.
*
* An adaptation of Peter Weinberger's (PJW) generic hashing
* algorithm based on Allen Holub's version. Accepts a pointer
* to a datum to be hashed and returns an unsigned integer.
* From: Keith Seymour's proxy library code
*
* @param[in] key -- the string to be hashed
*
* @returns the hash index
*/
unsigned int
hash_pjw(void* key)
{
char *datum = (char *)key;
unsigned int hash_value, i;
if(!datum) return 0;
for (hash_value = 0; *datum; ++datum) {
hash_value = (hash_value << ONE_EIGHTH) + *datum;
if ((i = hash_value & HIGH_BITS) != 0)
hash_value = (hash_value ^ (i >> THREE_QUARTERS)) & ~HIGH_BITS;
}
return (hash_value);
}
int string_compare(void* a, void* b)
{
return (strcmp( (char*)a, (char*)b ) == 0);
}
int get_n_entries(icl_hash_t *t) {
return (t->nentries);
}
/**
* Create a new hash table.
*
* @param[in] nbuckets -- number of buckets to create
* @param[in] hash_function -- pointer to the hashing function to be used
* @param[in] hash_key_compare -- pointer to the hash key comparison function to be used
* @param[in] maxSize -- maximum memory that can be used from the hash table
* @param[in] maxFiles -- maximum number of files that can be stored on the hash table
*
* @returns pointer to new hash table.
*/
icl_hash_t *
icl_hash_create( int nbuckets, unsigned int (*hash_function)(void*), int (*hash_key_compare)(void*, void*), size_t maxSize, long maxFiles)
{
icl_hash_t *ht;
int i;
ht = (icl_hash_t*) malloc(sizeof(icl_hash_t));
if(!ht) return NULL;
ht->nentries = 0;
ht->buckets = (icl_entry_t**)malloc(nbuckets * sizeof(icl_entry_t*));
if(!ht->buckets) return NULL;
ht->nbuckets = nbuckets;
for(i=0;i<ht->nbuckets;i++)
ht->buckets[i] = NULL;
ht->hash_function = hash_function ? hash_function : hash_pjw;
ht->hash_key_compare = hash_key_compare ? hash_key_compare : string_compare;
ht->curr_size = 0;
if (pthread_mutex_init(&ht->tableLock, NULL) != 0) {
fprintf(stderr, "SERVER: Errore nell'inizializzazione della lock\n");
return NULL;
}
ht->max_size = maxSize;
ht->max_files = maxFiles;
return ht;
}
/**
* Search for an entry in a hash table.
*
* @param ht -- the hash table to be searched
* @param key -- the key of the item to search for
*
* @returns pointer to the data corresponding to the key.
* If the key was not found, returns NULL.
*/
void *
icl_hash_find(icl_hash_t *ht, void* key)
{
icl_entry_t* curr;
unsigned int hash_val;
if(!ht || !key) return NULL;
hash_val = (* ht->hash_function)(key) % ht->nbuckets;
for (curr=ht->buckets[hash_val]; curr != NULL; curr=curr->next)
if ( ht->hash_key_compare(curr->key, key))
return(curr->data);
return NULL;
}
/**
* Cerca un file nella tabella e ritorna la sua dimensione
*
* @param ht -- the hash table to be searched
* @param key -- the key of the item to search for
*
* @returns file's size.
* If the key was not found, returns -1.
*/
size_t
icl_hash_get_file_size(icl_hash_t *ht, void* key)
{
icl_entry_t* curr;
unsigned int hash_val;
if(!ht || !key) return -1;
hash_val = (* ht->hash_function)(key) % ht->nbuckets;
for (curr=ht->buckets[hash_val]; curr != NULL; curr=curr->next)
if ( ht->hash_key_compare(curr->key, key))
return(curr->fileSize);
return -1;
}
int
icl_hash_find_and_append(icl_hash_t *ht, void* key, void *data_to_append)
{
icl_entry_t* curr;
unsigned int hash_val;
if(!ht || !key) return -1;
if (!data_to_append) return -1;
hash_val = (* ht->hash_function)(key) % ht->nbuckets;
LOCK(&ht->tableLock);
for (curr=ht->buckets[hash_val]; curr != NULL; curr=curr->next)
if ( ht->hash_key_compare(curr->key, key)) {
free(curr->data); //Libero la vecchia memoria
curr->data = data_to_append; //Aggiorno il puntatore
}
UNLOCK(&ht->tableLock);
return 0;
}
size_t get_current_size (icl_hash_t *ht) {
return ht->curr_size;
}
/**
* Append something to an item in the hash table.
*
* @param ht -- the hash table
* @param key -- the key of the new item
* @param data -- pointer to the new item's data
*
* @returns pointer to the new item. Returns NULL on error.
*/
int append (icl_hash_t *ht, void *key, char *new_data, size_t size) {
if (!ht || !key) return -1;
if (!new_data) return -1;
char *data = (char*)icl_hash_find(ht, key);
if (!data) {
return -1;
}
size_t oldsize = strlen(data);
if (size > MAX_FILE_SIZE || oldsize + size > MAX_FILE_SIZE) {
fprintf(stderr, "SERVER: Errore - il contenuto da scrivere supera la memoria massima per un file\n");
return -1;
}
char *res = malloc(oldsize+size+1);
if (!res) {
fprintf(stderr, "SERVER: Errore nella malloc\n");
return -1;
}
memcpy(res, data, oldsize);
memcpy(res+oldsize, new_data, size+1);
if (icl_hash_find_and_append(ht, key, (void*)res) == 0) { //Se ho appeso con successo
/*Aggiorno la memoria lockando la hTable*/
LOCK(&ht->tableLock);
ht->curr_size = ht->curr_size + size;
UNLOCK(&ht->tableLock);
return 0;
}
return -1;
}
/**
* Insert an item into the hash table.
*
* @param ht -- the hash table
* @param key -- the key of the new item
* @param data -- pointer to the new item's data
* @param size -- the new data's size
* @returns pointer to the new item. Returns NULL on error.
*/
icl_entry_t *
icl_hash_insert(icl_hash_t *ht, void* key, void *data, size_t size)
{
icl_entry_t *curr;
unsigned int hash_val;
//size_t len_of_data = 0;
if(!ht || !key) return NULL;
/*if (data) {
len_of_data = strnlen((char*)data, MAX_FILE_SIZE);
}*/
/*Superata la memoria*/
if (size > ht->max_size) {
fprintf(stderr, "SERVER: Errore - file troppo grande per la memoria dello storage\n"); //Se il file è più grande della capienza massima della tabella, non lo inserisco
return NULL;
}
if (size > MAX_FILE_SIZE) {
fprintf(stderr, "SERVER: Errore - il contenuto da scrivere supera la memoria massima per un file\n");
return NULL;
}
hash_val = (* ht->hash_function)(key) % ht->nbuckets;
LOCK(&ht->tableLock);
for (curr=ht->buckets[hash_val]; curr != NULL; curr=curr->next)
if ( ht->hash_key_compare(curr->key, key))
return(NULL); /* key already exists */
/* if key was not found */
curr = (icl_entry_t*)malloc(sizeof(icl_entry_t));
if(!curr) return NULL;
curr->key = key;
curr->data = data;
curr->fileSize = size;
curr->next = ht->buckets[hash_val]; /* add at start */
ht->buckets[hash_val] = curr;
ht->nentries++;
ht->curr_size += size;
UNLOCK(&ht->tableLock);
return curr;
}
/**
* Free one hash table entry located by key (key and data are freed using functions).
*
* @param ht -- the hash table to be freed
* @param key -- the key of the new item
* @param free_key -- pointer to function that frees the key
* @param free_data -- pointer to function that frees the data
*
* @returns 0 on success, -1 on failure.
*/
int icl_hash_delete(icl_hash_t *ht, void* key, void (*free_key)(void*), void (*free_data)(void*))
{
icl_entry_t *curr, *prev;
unsigned int hash_val;
if(!ht || !key) return -1;
hash_val = (* ht->hash_function)(key) % ht->nbuckets;
prev = NULL;
LOCK(&ht->tableLock);
for (curr=ht->buckets[hash_val]; curr != NULL; ) {
if ( ht->hash_key_compare(curr->key, key)) {
if (prev == NULL) {
ht->buckets[hash_val] = curr->next;
} else {
prev->next = curr->next;
}
if (*free_key && curr->key) (*free_key)(curr->key);
if (*free_data && curr->data) {
size_t old_size = strlen((char*)curr->data); //Peso in byte del file che sto per eliminare
ht->curr_size = ht->curr_size - old_size; //Diminuisco l'attuale memoria utilizzata di 'old_size' byte
(*free_data)(curr->data);
}
ht->nentries--;
free(curr);
UNLOCK(&ht->tableLock);
return 0;
}
prev = curr;
curr = curr->next;
}
UNLOCK(&ht->tableLock);
return -1;
}
/**
* Free hash table structures (key and data are freed using functions).
*
* @param ht -- the hash table to be freed
* @param free_key -- pointer to function that frees the key
* @param free_data -- pointer to function that frees the data
*
* @returns 0 on success, -1 on failure.
*/
int
icl_hash_destroy(icl_hash_t *ht, void (*free_key)(void*), void (*free_data)(void*))
{
icl_entry_t *bucket, *curr, *next;
int i;
if(!ht) return -1;
for (i=0; i<ht->nbuckets; i++) {
bucket = ht->buckets[i];
for (curr=bucket; curr!=NULL; ) {
next=curr->next;
if (*free_key && curr->key) (*free_key)(curr->key);
if (*free_data && curr->data) {
(*free_data)(curr->data);
}
free(curr);
curr=next;
}
}
pthread_mutex_destroy(&ht->tableLock);
if(ht->buckets) free(ht->buckets);
if(ht) free(ht);
return 0;
}
/**
* Dump the hash table's contents to the given socket descriptor.
*
* @param connFd -- the socket descriptor
* @param ht -- the hash table to be dumped
* @param n_of_files -- the number of files to read
*
* @returns 0 on success, -1 on failure.
*/
int
icl_hash_dump(long connFd, icl_hash_t* ht, int n_of_files)
{
icl_entry_t *bucket, *curr;
int i;
server_reply server_rep;
memset(&server_rep, 0, sizeof(server_reply));
if(!ht) return -1;
int file_readed = 0;
for(i=0; i<ht->nbuckets; i++) {
if (file_readed == n_of_files) return 0; //Ho finito, esco
bucket = ht->buckets[i];
for(curr=bucket; curr!=NULL; ) {
if (file_readed == n_of_files) return 0; //Ho finito, esco
if(curr->key) {
strcpy(server_rep.pathname, (char*)curr->key);
memcpy(server_rep.data, curr->data, curr->fileSize+1);
server_rep.size = curr->fileSize; //Prendo la size del file
if (writen(connFd, &server_rep, sizeof(server_reply)) < 0) {
perror("writenDump");
return -1;
}
memset(&server_rep, 0, sizeof(server_reply));
file_readed++;
}
curr=curr->next;
}
}
return 0;
}
int
icl_hash_dump_2(FILE* stream, icl_hash_t* ht)
{
icl_entry_t *bucket, *curr;
int i;
if(!ht) return -1;
//fprintf(stream, "\n\nSERVER: File presenti al momento nello storage:\n");
for(i=0; i<ht->nbuckets; i++) {
bucket = ht->buckets[i];
for(curr=bucket; curr!=NULL; ) {
if(curr->key)
fprintf(stream, "%s\n", (char *)curr->key);
curr=curr->next;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <gtk/gtk.h>
#include <cairo.h>
// switch case wymagal zeby obiekty nie byly zmiennymi wiec zmienilem na #define
#define DROGA '#'
#define OSIEDLE 'O'
#define KOPALNIA 'K'
#define ELEKTROWNIA 'E'
#define LINIA 'T'
#define UNIWERSYTET 'U'
int width, height;
char map[100][100];
bool visited[100][100];
int workers[100][100]; // tablica obiektow ktore maja pracownikow lub ktore ich zapewniaja
int electricity[100][100]; // tablica obiektow ktore maja prad lub go rozprowadzaja
int active[100][100]; // tablica obiektow ktore maja wegiel lub go dostarczaja
bool pathExistsRec(int startX, int startY, char target, char roads, char start)
{
if (map[startX][startY] == target)
{
if (target == OSIEDLE) // szukanie pracownikow
{
if (!workers[startX][startY])
{
workers[startX][startY] = 1;
return true;
}
}
if (target == KOPALNIA) // szukanie wegla
{
if (!active[startX][startY]) // jezeli kopalnia nie dostarcza wegla
{
if (workers[startX][startY]) // jezeli kopalnia ma pracownikow
{
active[startX][startY] = 1;
return true;
}
}
}
if (target == ELEKTROWNIA) // szukanie elektrowni
{
if (electricity[startX][startY] < 5) // jezeli podlaczylo sie mniej niz 5 obiektow
{
if (workers[startX][startY]) // jezeli elektrownia ma pracownikow
{
if (active[startX][startY]) // jezeli elektrownia ma wegiel
{
electricity[startX][startY]++;
return true;
}
}
}
}
}
if (visited[startX][startY])
{
return false;
}
if (map[startX][startY] != roads && map[startX][startY] != start)
{
return false;
}
visited[startX][startY] = true;
if (startX > 0) // lewo
{
if (pathExistsRec(startX - 1, startY, target, roads, start))
return true;
}
if (startX < width - 1) // prawo
{
if (pathExistsRec(startX + 1, startY, target, roads, start))
return true;
}
if (startY > 0) // gora
{
if (pathExistsRec(startX, startY - 1, target, roads, start))
return true;
}
if (startY < height - 1) // dol
{
if (pathExistsRec(startX, startY + 1, target, roads, start))
return true;
}
//visited[startX][startY] = false;
return false;
}
bool pathExists(int startX, int startY, char target, char roads, char start)
{
for (int i = 0; i < 100; i++)
{
for (int e = 0; e < 100; e++)
{
visited[i][e] = false;
}
}
return pathExistsRec(startX, startY, target, roads, start);
}
void findWorkers(int x, int y, char start)
{
if (pathExists(x, y, OSIEDLE, DROGA, start))
{
workers[x][y] = 1;
}
}
void findMine(int x, int y)
{
if (pathExists(x, y, KOPALNIA, DROGA, ELEKTROWNIA))
{
active[x][y] = 1;
}
}
void findElectricity(int x, int y, char start)
{
if (pathExists(x, y, ELEKTROWNIA, LINIA, start))
{
electricity[x][y] = 1;
}
}
void draw(GtkWidget* window, GdkPixbuf* pix, int x, int y)
{
cairo_t *cr;
cr = gdk_cairo_create (gtk_widget_get_window(window));
gdk_cairo_set_source_pixbuf(cr, pix, 32 * y, 32 * x);
cairo_paint(cr);
cairo_destroy (cr);
}
static gboolean on_window_draw(GtkWidget *window, GdkEvent *event, gpointer data)
{
(void)event; (void)data;
GdkPixbuf *pix;
GError *err = NULL;
for (int i = 0; i < height; i++)
{
for (int e = 0; e < width; e++)
{
switch (map[e][i])
{
case UNIWERSYTET:
{
if (workers[e][i] && electricity[e][i])
pix = gdk_pixbuf_new_from_file("pictures/university.png", &err);
else
pix = gdk_pixbuf_new_from_file("pictures/university2.png", &err);
break;
}
case ELEKTROWNIA:
{
if (workers[e][i] && active[e][i])
pix = gdk_pixbuf_new_from_file("pictures/pplant.png", &err);
else
pix = gdk_pixbuf_new_from_file("pictures/pplant2.png", &err);
break;
}
case KOPALNIA:
{
if (workers[e][i])
pix = gdk_pixbuf_new_from_file("pictures/mine.png", &err);
else
pix = gdk_pixbuf_new_from_file("pictures/mine2.png", &err);
break;
}
case OSIEDLE:
{
if (electricity[e][i])
pix = gdk_pixbuf_new_from_file("pictures/house.png", &err);
else
pix = gdk_pixbuf_new_from_file("pictures/house2.png", &err);
break;
}
case LINIA:
{
pix = gdk_pixbuf_new_from_file("pictures/pline.png", &err);
break;
}
case DROGA:
{
pix = gdk_pixbuf_new_from_file("pictures/road.png", &err);
break;
}
case '.':
{
pix = gdk_pixbuf_new_from_file("pictures/empty.png", &err);
break;
}
default:
{
pix = gdk_pixbuf_new_from_file("pictures/tree.png", &err);
break;
}
}
draw(window, pix, i, e);
}
}
/*
if(err)
{
printf("Error : %s\n", err->message);
g_error_free(err);
return FALSE;
}
*/
}
int main(int argc, char* argv[])
{
scanf("%i%i", &width, &height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
scanf(" %c", &map[x][y]);
active[x][y] = 0;
workers[x][y] = 0;
electricity[x][y] = 0;
}
}
/*
UWAGA UWAGA
UWAGA
Algorytm nie przydziala pracownikow optymalnie, wiec mozliwe jest ze beda oni we wszystkich
budynkach oprocz kopalni, przez co cale miasto i tak nie bedzie mialo pradu
(ale przynajmniej bezrobocie bedzie niskie)
*/
for (int i = 0; i < width; i++) // przyporzadkowywanie pracownikow
{
for (int e = 0; e < height; e++)
{
if (map[i][e] == ELEKTROWNIA) // wiem ze to mogl byc jeden if ale nie chce mi sie teraz tego zmieniac :(
findWorkers(i, e, ELEKTROWNIA);
else if (map[i][e] == KOPALNIA)
findWorkers(i, e, KOPALNIA);
else if (map[i][e] == UNIWERSYTET)
findWorkers(i, e, UNIWERSYTET);
}
}
for (int i = 0; i < width; i++) // przyporzadkowywanie kopalni do elektrowni
{
for (int e = 0; e < height; e++)
{
if (map[i][e] == ELEKTROWNIA)
findMine(i, e);
}
}
for (int i = 0; i < width; i++) // rozprowadzanie pradu z elektrowni do innych obiektow
{
for (int e = 0; e < height; e++)
{
if (map[i][e] == UNIWERSYTET || map[i][e] == OSIEDLE)
findElectricity(i, e, map[i][e]);
}
}
printf("\n\n================DZIALAJACE====================\n\n");
for (int i = 0; i < height; i++)
{
for (int e = 0; e < width; e++)
{
switch (map[e][i])
{
case UNIWERSYTET:
if (workers[e][i] && electricity[e][i])
printf("U");
else
printf("u");
break;
case ELEKTROWNIA:
if (workers[e][i] && active[e][i])
printf("E");
else
printf("e");
break;
case KOPALNIA:
if (workers[e][i])
printf("K");
else
printf("k");
break;
case OSIEDLE:
if (electricity[e][i])
printf("O"); // osiedle jest aktywne kiedy ma prad, niekoniecznie kiedy jest praca
else
printf("o");
break;
default:
printf("%c",map[e][i]);
break;
}
}
printf("\n");
}
/*
printf("\n\n================ELEKTRYCZNOSC=================\n\n");
for (int i = 0; i < height; i++)
{
for (int e = 0; e < width; e++)
{
printf("%d",electricity[e][i]);
}
printf("\n");
}
printf("\n\n================PRACOWNICY====================\n\n");
for (int i = 0; i < height; i++)
{
for (int e = 0; e < width; e++)
{
printf("%d",workers[e][i]);
}
printf("\n");
}
printf("\n\n================WEGIEL=======================#\n\n");
for (int i = 0; i < height; i++)
{
for (int e = 0; e < width; e++)
{
printf("%d",active[e][i]);
}
printf("\n");
}
*/
// WYSWIETLANIE W GTK+ 3.0
GtkWidget *window;
GtkWidget *canvas;
gtk_init (&argc , &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 32 * width, 32 * height);
gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit) , NULL);
canvas = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER (window), canvas);
g_signal_connect (canvas, "draw", (GCallback) on_window_draw, NULL);
gtk_widget_set_app_paintable(canvas, TRUE);
gtk_widget_show_all (window);
gtk_main ();
return 0;
}
|
C
|
#include "minishell.h"
void ft_free(void **ptr)
{
free(*ptr);
*ptr = NULL;
}
int check_symbols(char *str)
{
int i;
if (!ft_isalpha(str[0]) && str[0] != '_')
return (1);
i = 1;
while (str[i] && str[i] != '=')
{
if (str[i] == '+' && str[i + 1] == '=')
return (2);
if (!ft_isalnum(str[i]) && str[i] != '_')
return (1);
i++;
}
return (0);
}
t_list_env *strdup_list(t_list_env **src)
{
t_list_env *new;
t_list_env *tmp;
t_list_env *node;
tmp = *src;
new = NULL;
while (tmp)
{
node = envlistnew1(tmp->name, tmp->content, tmp->has_equal);
env_lst_addback(&new, node);
tmp = tmp->next;
}
return (new);
}
static void get_new_root(t_list_env **node, t_list_env **new_root)
{
(*node)->next = (*new_root);
(*new_root) = (*node);
}
t_list_env *sort_list(t_list_env *src)
{
t_list_env *root;
t_list_env *new_root;
t_list_env *node;
t_list_env *current;
root = strdup_list(&src);
new_root = NULL;
while (root)
{
node = root;
root = root->next;
if (!new_root || ft_strcmp(node->name, new_root->name) < 0)
get_new_root(&node, &new_root);
else
{
current = new_root;
while (current->next && \
ft_strcmp(node->name, current->next->name) >= 0)
current = current->next;
node->next = current->next;
current->next = node;
}
}
return (new_root);
}
|
C
|
#include <stdio.h>
int main() {
int n;
printf("Enter a number to see if it is prime:");
scanf("%d", &n);
int isPrime = 1;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
isPrime = 0;
printf("%d is divisible by %d\n", n, i);
break;
}
}
if (isPrime && n != 1) {
printf("Is a prime!\n");
}
else {
printf("Not a prime!\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define STDIN 0 // file descriptor for standard input
int main(void) {
fd_set rfds;
struct timeval tv;
int retval;
char buf[255];
int len;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
//we must turn on the interested bits (by calling FD_SET) each time we call select.
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
while(1){
retval = select(STDIN+1, &rfds, NULL, NULL, &tv);
/* Don’t rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval){
fgets(buf, sizeof(buf), stdin);
len = strlen(buf) - 1;
if (buf[len] == '\n'){
buf[len] = '\0';
}
if(strcmp(buf, "quit") == 0){
printf("exit\n");
exit(EXIT_FAILURE);
}else{
printf("'%s' was read from stdin.\n", buf);
}
}else{
printf("No data within five seconds.\n");
exit(EXIT_FAILURE);
}
}
return 0;
}
|
C
|
/* socket_tcp_client.c
A client enters textline to server and also receive echo back message
Server is handled as thread with epoll
Compiling and Execution
$ gcc -o exec_c socket_tcp_client.c -Wall -
$ ./exec_c localhost 5000
or
$ ./exec_c 192.168.1.46 5000
There can be several clients from different termials.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#define BUF_SIZE 256
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockTCPfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server; // old the way.
char buffer[BUF_SIZE];
char buffer_sent[BUF_SIZE];
char buffer_recv[BUF_SIZE];
int clientId, len;
char str_id[15];
struct timeval tv;
struct tm* ptm;
char time_string[35];
n = 1; // in order to go to the 1st while loop
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockTCPfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockTCPfd < 0) {
error("ERROR opening socket");
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
memset((char *) &serv_addr, 0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy((char *)&serv_addr.sin_addr.s_addr,(char *)server->h_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockTCPfd,(struct sockaddr *)&serv_addr,
sizeof(serv_addr)) < 0) {
error("ERROR connecting");
}
srand(time(0));
clientId = rand() % 100; // clientID 01-99
sprintf(str_id, "client%02d:", clientId);
while (n > 0) {
printf("Please enter the text from %s ", str_id);
bzero( buffer_sent, BUF_SIZE);
bzero( buffer_recv, BUF_SIZE);
/* Obtain the time of day, and convert it to a tm struct. */
gettimeofday (&tv, NULL);
ptm = localtime (&tv.tv_sec);
strftime (time_string, sizeof (time_string),
"%Y-%m-%d %H:%M:%S", ptm);
/* Add client ID and time stamp */
strcpy(buffer_sent, str_id);
strcat(buffer_sent, time_string);
strcat(buffer_sent, " ");
/* get order */
len = BUF_SIZE-strlen(buffer_sent);
memset(buffer,0,len);
fgets(buffer,len,stdin);
strcat(buffer_sent, buffer);
n = write(sockTCPfd,buffer_sent,strlen(buffer_sent));
if (n < 0) {
error("ERROR writing to socket");
}
n = read(sockTCPfd,buffer_recv, BUF_SIZE);
if (n > 0) {
printf("***Echo from Server***: %s",buffer_recv);
}
else {
printf("nothing to read");
}
}
return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putnbr_hexa_fd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: olgerret <olgerret@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/24 07:39:10 by olgerret #+# #+# */
/* Updated: 2021/07/24 07:39:34 by olgerret ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static void ten_to_sixteen_up(unsigned long n, int fd, int *counter)
{
if (n == 10)
ft_putchar_counter_fd('A', fd, counter);
else if (n == 11)
ft_putchar_counter_fd('B', fd, counter);
else if (n == 12)
ft_putchar_counter_fd('C', fd, counter);
else if (n == 13)
ft_putchar_counter_fd('D', fd, counter);
else if (n == 14)
ft_putchar_counter_fd('E', fd, counter);
else if (n == 15)
ft_putchar_counter_fd('F', fd, counter);
}
static void ten_to_sixteen_low(unsigned long n, int fd, int *counter)
{
if (n == 10)
ft_putchar_counter_fd('a', fd, counter);
else if (n == 11)
ft_putchar_counter_fd('b', fd, counter);
else if (n == 12)
ft_putchar_counter_fd('c', fd, counter);
else if (n == 13)
ft_putchar_counter_fd('d', fd, counter);
else if (n == 14)
ft_putchar_counter_fd('e', fd, counter);
else if (n == 15)
ft_putchar_counter_fd('f', fd, counter);
}
void ft_putnbr_hexa_fd(unsigned long n, int fd, int up, int *counter)
{
if (n >= 0 && n <= 9)
{
n += '0';
ft_putchar_counter_fd(n, fd, counter);
}
else if (n >= 10 && n < 16 && up == 0)
ten_to_sixteen_low(n, fd, counter);
else if (n >= 10 && n < 16 && up == 1)
ten_to_sixteen_up(n, fd, counter);
else
{
ft_putnbr_hexa_fd(n / 16, fd, up, counter);
ft_putnbr_hexa_fd(n % 16, fd, up, counter);
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define bucketSize 512
void bktInput(int a,int b)
{
if(a>bucketSize)
printf("\n\t\tBucket overflow");
else {
while(a>b){
printf("\n%d bytes outputed.",b);
a-=b;
}
if (a>0) printf("\n\t\tLast %d" ,a);
printf("\tbytes sent\t");
printf("\n\t\tBucket output successful\n");
}
}
void main() {
int op, pktSize;
printf("Enter output rate : ");
scanf("%d",&op);
int i;
for(i=1;i<=5;i++){
pktSize = rand() % 600;
printf("\nPacket no %d",i);
printf("\tPacket size = %d",pktSize);
bktInput(pktSize,op);
}
}
|
C
|
//
// main.c
// HeAtom
//
// Created by Mitchell Miller on 3/23/12.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double bohrRadius = .5291772083; //angstroms
double Pi = 3.141592653589793;
double E = 2.718281828459045;
double eCharge = 14.39964439;
double Z = 2;
int numberOfLoops = 10000000;
double oneSState(double x,double y,double z){
double funcValue;
double exp = 0;
double radius = sqrt(x*x+y*y+z*z);
exp = -2*Z*radius/bohrRadius;
funcValue = pow(E,exp);
return(funcValue);
}
double twoSState(double x,double y,double z){
double funcValue;
double exp;
double coef;
double expTerm;
double radius = sqrt(x*x+y*y+z*z);
coef = pow(1. - 0.5*Z*radius/bohrRadius,2);
exp = -Z*radius/bohrRadius;
expTerm = pow(E,exp);
funcValue = coef*expTerm;
return(funcValue);
}
double twoPState(double x,double y,double z){
double funcValue;
double exp;
double coef;
double expTerm;
double radius = sqrt(x*x+y*y+z*z);
exp = -2*Z*radius/bohrRadius;
coef = radius*radius;
expTerm = pow(E,exp);
funcValue = coef*expTerm;
return(funcValue);
}
double K1s2sIntegral(double x1,double y1,double z1,double x2,double y2,double z2){
double funcValue;
double coef;
double exp;
double radius1 = sqrt(x1*x1+y1*y1+z1*z1);
double radius2 = sqrt(x2*x2+y2*y2+z2*z2);
coef = (1-(.5)*Z*radius2/bohrRadius)*(1-(.5)*Z*radius1/bohrRadius);
exp = -Z*(radius1+radius2)* (3/ (2*bohrRadius));
funcValue = coef*pow(E,exp);
return(funcValue);
}
double K1s2pR(double x,double y,double z){
double funcValue;
double exp;
double radius = sqrt(x*x+y*y+z*z);
exp = -(3*Z*radius/(2*bohrRadius));
funcValue = z*pow(E,exp);
return(funcValue);
}
double repulsion(double x1,double y1,double z1,double x2,double y2,double z2){
double funcValue;
double radius = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
funcValue = 1 / fabs(radius);
return(funcValue);
}
double J1S2S(double low, double high){
double funcValue=0;
int counter;
double x1=0;
double x2=0;
double y1=0;
double y2=0;
double z1=0;
double z2=0;
double oneS=0;
double twoS=0;
double repul=0;
double width = high - low;
double coef1S = pow((Z / bohrRadius),3) / Pi;
double coef2S = pow((Z / bohrRadius),3) / (8*Pi);
for(counter=0;counter<numberOfLoops;counter++){
x1 = (drand48() - 0.5) * width;
y1 = (drand48() - 0.5) * width;
z1 = (drand48() - 0.5) * width;
x2 = (drand48() - 0.5) * width;
y2 = (drand48() - 0.5) * width;
z2 = (drand48() - 0.5) * width;
oneS = fabs(oneSState(x1, y1, z1));
twoS = fabs(twoSState(x2, y2, z2));
repul = repulsion(x1, y1, z1, x2, y2, z2);
funcValue += oneS * twoS * repul;
}
funcValue /= numberOfLoops;
funcValue *= coef1S*coef2S*eCharge*pow(width,6);
return(funcValue);
}
double K1S2S(double low, double high){
double funcValue=0;
int counter;
double x1=0;
double x2=0;
double y1=0;
double y2=0;
double z1=0;
double z2=0;
double repul;
double kInteg;
double zBohr = Z / bohrRadius;
double coef1S = (1 / (8*pow(Pi,2)))*pow(zBohr,6);
double width = high - low;
for(counter=0;counter<numberOfLoops;counter++){
x1 = (drand48() - 0.5) * width;
y1 = (drand48() - 0.5) * width;
z1 = (drand48() - 0.5) * width;
x2 = (drand48() - 0.5) * width;
y2 = (drand48() - 0.5) * width;
z2 = (drand48() - 0.5) * width;
kInteg = K1s2sIntegral(x1,y1,z1,x2,y2,z2);
repul = repulsion(x1, y1, z1, x2, y2, z2);
funcValue += kInteg*repul;
}
funcValue = funcValue / numberOfLoops;
funcValue = funcValue * eCharge*pow(width,6)*coef1S;
return(funcValue);
}
double J1S2P(double low, double high){
double funcValue=0;
int counter;
double width = high - low;
double x1=0;
double x2=0;
double y1=0;
double y2=0;
double z1=0;
double z2=0;
double zBohr = Z / bohrRadius;
double repul=0;
double oneS=0;
double twoP=0;
double coef1S = pow(zBohr,3) / Pi;
double coef2P = (1 / (64*pow(Pi,2)))*pow(zBohr,8);
for(counter=0;counter<numberOfLoops;counter++){
x1 = (drand48() - 0.5) * width;
y1 = (drand48() - 0.5) * width;
z1 = (drand48() - 0.5) * width;
x2 = (drand48() - 0.5) * width;
y2 = (drand48() - 0.5) * width;
z2 = (drand48() - 0.5) * width;
oneS = oneSState(x1, y1, z1);
twoP = twoPState(x2, y2, z2);
repul = repulsion(x1, y1, z1, x2, y2, z2);
funcValue += oneS*twoP*repul;
}
funcValue = funcValue / numberOfLoops;
funcValue = funcValue * coef1S*coef2P*eCharge*pow(width,6); // May need to add 'coef1S' here
return(funcValue);
}
double K1S2P(double low, double high){
double funcValue=0;
int counter;
double width = high - low;
double x1=0;
double x2=0;
double y1=0;
double y2=0;
double z1=0;
double z2=0;
double zBohr = Z / bohrRadius;
double repul;
double r1;
double r2;
double coef2P = (1 / (32*pow(Pi,2)))*pow(zBohr,8);
for(counter=0;counter<numberOfLoops;counter++){
x1 = (drand48() - 0.5) * width;
y1 = (drand48() - 0.5) * width;
z1 = (drand48() - 0.5) * width;
x2 = (drand48() - 0.5) * width;
y2 = (drand48() - 0.5) * width;
z2 = (drand48() - 0.5) * width;
r1 = K1s2pR(x1, y1, z1);
r2 = K1s2pR(x2, y2, z2);
repul = repulsion(x1, y1, z1, x2, y2, z2);
funcValue += r1*r2*repul;
}
funcValue = funcValue / numberOfLoops;
funcValue = funcValue * eCharge*pow(width,6)*coef2P;
return(funcValue);
}
int main ()
{
double lower = -5;
double upper = 5;
double j1s2s=0;
double k1s2s=0;
double j1s2p=0;
double k1s2p=0;
int counter;
int loops=1000;
FILE *outfile;
outfile = fopen("HeAtom.dat","w");
srand48( time(NULL));
for(counter=0;counter<loops;counter++){
printf("Begin Loop\t");
j1s2s += J1S2S(lower, upper);
j1s2p += J1S2P(lower, upper);
k1s2s += K1S2S(lower, upper);
k1s2p += K1S2P(lower, upper);
printf("Loop %i Complete\n",counter);
}
j1s2s = j1s2s / loops;
j1s2p = j1s2p / loops;
k1s2s = k1s2s / loops;
k1s2p = k1s2p / loops;
printf("J1S2S = %lf\n",j1s2s);
printf("K1S2S = %lf\n",k1s2s);
printf("J1S2P = %lf\n",j1s2p);
printf("K1S2P = %lf\n",k1s2p);
fclose(outfile);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rotation.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: grass-kw <grass-kw@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/04/19 15:30:03 by grass-kw #+# #+# */
/* Updated: 2016/07/20 10:35:05 by grass-kw ### ########.fr */
/* */
/* ************************************************************************** */
#include "rt_v1.h"
static void rotation_x(t_vector3d *a, double angle)
{
double tmp_x;
double tmp_y;
double tmp_z;
if (angle != ZERO)
{
tmp_x = a->x;
tmp_y = (cos(angle) * a->y) + (-sin(angle) * a->z);
tmp_z = (sin(angle) * a->y) + (cos(angle) * a->z);
a->x = tmp_x;
a->y = tmp_y;
a->z = tmp_z;
}
}
static void rotation_y(t_vector3d *a, double angle)
{
double tmp_x;
double tmp_y;
double tmp_z;
if (angle != ZERO)
{
tmp_x = (cos(angle) * a->x) + (sin(angle) * a->z);
tmp_y = a->y;
tmp_z = (-sin(angle) * a->x) + (cos(angle) * a->z);
a->x = tmp_x;
a->y = tmp_y;
a->z = tmp_z;
}
}
static void rotation_z(t_vector3d *a, double angle)
{
double tmp_x;
double tmp_y;
double tmp_z;
if (angle != ZERO)
{
tmp_x = cos(angle) * a->x - sin(angle) * a->y;
tmp_y = sin(angle) * a->x + cos(angle) * a->y;
tmp_z = a->z;
a->x = tmp_x;
a->y = tmp_y;
a->z = tmp_z;
}
}
void rotation(t_vector3d *a, t_vector3d angle)
{
rotation_x(a, angle.x);
rotation_y(a, angle.y);
rotation_z(a, angle.z);
}
|
C
|
#include "spi.h"
void SPI_MasterInit(void)
{
/* Set MOSI and SCK output, all others input */
DDRB = (1<<DDB2)|(1<<DDB1);
//enable OE
DDRE |= _BV(PE4);
//enable pour LE
DDRE |= _BV(PE5);
// enable port SS
DDRB |= _BV(PB0);
/* Enable SPI, Master, set clock rate fck/16, enable interuption*/
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);//|(0 << SPIE);
}
void SPI_MasterTransmit(uint8_t cData)
{
/* Start transmission */
SPDR = cData;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)));
}
// allume les LED à partir d'un chiffre décimal
void allumeLed(uint16_t chiffre)
{
uint8_t trame1= chiffre>>8;
uint8_t trame2 = chiffre;
PORTE |= _BV(PE4);
PORTE &=~ _BV(PE5);
SPI_MasterTransmit(trame1);
SPI_MasterTransmit(trame2);
PORTE |= _BV(PE5);
PORTE &=~ _BV(PE4);
}
|
C
|
#ifndef __LINKLIST_H__
#define __LINKLIST_H__
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int DataType;//charģάԴ룩
typedef struct Node
{
DataType data;
struct Node* next;
}Node;
void PushBack(Node** pphead, DataType x);//ppheadӦΪָ
void PopBack(Node** pphead);
void PushFront(Node** pphead, DataType x);
void PopFront(Node** pphead);
Node* Find(Node* phead,DataType x);
void PrintList(Node* phead);
#endif __LINKLIST_H__
|
C
|
/**
* @file test.c
*
* A test driver.
*/
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "logger.h"
#include "allocator.h"
/**
* A test driver.
*
* @param void
*/
int main(void){
// //test 3
// char* str0 = malloc(100);
// char* str1 = malloc(100);
// char* str2 = malloc(16);
// char* str3 = malloc(100);
// char* str4 = malloc(100);
// free(str1);
// free(str3);
// char* str5 = malloc(16);
// char* str6 = malloc(4096);
// print_memory();
//char* str1 =
// char* str2 = malloc(10);
// char* str3 = malloc(5000);
// print_memory();
// char* str0 = malloc(8);
// free(str0);
// char* str1 = malloc(120);
// char* str2 = malloc(16);
// char* str3 = malloc(776);
// char* str4 = malloc(112);
// char* str5 = malloc(1336);
// char* str6 = malloc(216);
// char* str7 = malloc(432);
// char* mid = malloc(8);
// char* str8 = malloc(1);
// char *str1 = malloc(100);
// char *str2 = calloc(17, 16);
//print memory is allocating memory
print_memory();
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "../incs/libasm.h"
int main(int ac, char **av)
{
int ret = 0;
if (ac == 2)
{
char copy[ft_strlen(av[1])];
char copy2[ft_strlen(av[1])];
printf("\nSTRLEN TEST-----\n");
printf("ft=%lu\n", ft_strlen(av[1]));
printf("rl=%lu\n", strlen(av[1]));
printf("\nSTRCPY TEST-----\n");
printf("ft=%s\n", ft_strcpy(copy, av[1]));
printf("rl=%s\n", strcpy(copy2, av[1]));
printf("\nSTRDUP TEST-----\n");
printf("ft_av[1]_dup=%s\n", ft_strdup(av[1]));
printf("rl_av[1]_dup=%s\n", strdup(av[1]));
printf("\nWRITE TEST-----STDIN\n");
errno = 0;
printf("\nft(%lu)\n", ft_write(1, av[1], ft_strlen(av[1])));
printf("my_error=%s\n", (strerror(errno)));
errno = 0;
printf("\nrl(%lu)\n", write(1, av[1], ft_strlen(av[1])));
printf("rl_error=%s\n", (strerror(errno)));
printf("\nWRITE TEST-----FILE----Check files in directory\n");
errno = 0;
printf("\nft(%lu)\n", ft_write(open("write_ft.txt", (O_RDWR | O_CREAT), 0666), av[1], ft_strlen(av[1])));
printf("my_error=%s\n", (strerror(errno)));
errno = 0;
printf("\nrl(%lu)\n", write(open("write_rl.txt", (O_RDWR | O_CREAT), 0666), av[1], ft_strlen(av[1])));
printf("rl_error=%s\n", (strerror(errno)));
printf("\nWRITE TEST-----BAD_FD\n");
errno = 0;
printf("\nft(%lu)\n", ft_write(-1, av[1], ft_strlen(av[1])));
printf("my_error=%s\n", (strerror(errno)));
errno = 0;
printf("\nrl(%lu)\n", write(-1, av[1], ft_strlen(av[1])));
printf("rl_error=%s\n", (strerror(errno)));
}
if (ac == 3)
{
char buff[4096 + 1];
int fd = open(av[1], O_RDONLY);
int fd2 = open(av[2], O_RDONLY);
printf("\nSTRCMP TEST-----\n");
printf("ft=%d\n", ft_strcmp(av[1], av[2]));
printf("rl=%d\n", strcmp(av[1], av[2]));
printf("\nREAD TEST-----\n");
errno = 0;
ret = ft_read(fd, buff, 4096);
buff[ret] = '\0';
printf("ft=(%d)| buffer=%s\n-----------------\n", ret, buff);
printf("my_error=%s\n", (strerror(errno)));
errno = 0;
ret = read(fd2, buff, 4096);
buff[ret] = '\0';
printf("rl=(%d)| buffer=%s\n", ret, buff);
printf("rl_error=%s\n", (strerror(errno)));
close(fd);
close(fd2);
}
return (0);
}
|
C
|
/*
A simple example for dangling pointer.
*/
#include <stdio.h>
#include <stdlib.h>
int main(){
char* data = (char *)malloc(32); // Assuming that the 9th char is critical...
data[8] = 'L';
printf("data buffer at address %x\n", data);
/* ...
* some complex program code here
* ...
*/
free(data); //the data buffer could be accidentially freed.
/* ...
* some complex program code here
* ...
*/
/* Here, the memory allocator could allocate the same space for the data buffer.
* Whether this will happen depends on multiple factors (allocation algorithm,
* the size of the buffer, etc.). For example, if you set the input buffer with
* size 64, this might not happen because the allocator will use a new chunk
* instead of reusing the old one.
*/
char* input = (char *)malloc(64);
printf("input buffer at address %x\n", input);
/* Assuming that the attacker can control the input. Now, the attacker can
* type aaaaaaaaS to write char 'S' to the critical space.
*/
scanf("%s", input);
/* The dangling pointer is used here to do a critical operation.
* Note that this bug might not be hard to find because it will
* almost never trigger a crash.
*/
if(data[8] == 'S'){
printf("Pwn!\n"); // This is the goal of the attacker
}else{
printf("Pew!\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int big(int a, int b) {
if (a > b) {
return a;
}
return b;
}
void work(int * data, int * max, int * visited, int current, int count) {
if (data[data[current]] == current) {
max[current] = big(max[current], count);
return ;
}
if (visited[current]) {
max[current] = big(max[current], count - visited[current]);
return;
}
visited[current] = count;
work(data, max, visited, data[current], count + 1);
visited[current] = 0;
return;
}
int main() {
int p_max;
int p_count;
int n_max;
int n_cycle;
int ans;
int pairs;
int * data = (int *)malloc(1000 * sizeof(int));
int * max = (int *)malloc(1000 * sizeof(int));
int * visited = (int *)malloc(1000 * sizeof(int));
scanf("%d\n", &p_max);
p_count = 0;
while (p_count < p_max) {
p_count ++;
printf("Case #%d: ", p_count);
scanf("%d\n", &n_max);
n_cycle = 0;
while (n_cycle < n_max) {
scanf("%d", &data[n_cycle]);
data[n_cycle] --;
n_cycle ++;
}
n_cycle = 0;
while (n_cycle < n_max) {
max[n_cycle] = 0;
visited[n_cycle] = 0;
n_cycle ++;
}
n_cycle = 0;
while (n_cycle < n_max) {
work(data, max, visited, n_cycle, 1);
n_cycle ++;
}
ans = -1;
n_cycle = 0;
pairs = 0;
while (n_cycle < n_max) {
if (data[data[n_cycle]] == n_cycle) {
pairs = pairs + max[n_cycle];
}
ans = big(ans, max[n_cycle]);
n_cycle ++;
}
ans = big(ans, pairs);
printf("%d", ans);
printf("\n");
}
}
|
C
|
#include "../include/sock_help.h"
void *get_in_addr(struct sockaddr *sa)
{
if(sa->sa_family == AF_INET)
return &(((struct sockaddr_in *) sa)->sin_addr);
else
return &(((struct sockaddr_in6 *) sa)->sin6_addr);
}
int get_tcp_socket(const char *port, char *hostname, char flags)
{
int fd = 0;
int rv = 0;
#ifdef __linux__
int yes = 1;
#elif _WIN32
char yes = 1;
#endif
#ifdef __linux__
char addr_str[INET6_ADDRSTRLEN];
#endif
struct addrinfo hints;
struct addrinfo *address_list;
struct addrinfo *p = NULL;
#ifdef _WIN32
WSADATA wsaData;
unsigned long mode = 1;
#endif
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if(hostname == NULL) {
hints.ai_flags = AI_PASSIVE;
}
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0) {
fprintf(stderr, "WSAStartup failed.\n");
return -1;
}
#endif
printf("PORT %s\n", port);
if((rv = getaddrinfo(hostname, "2222", &hints, &address_list)) != 0) {
#ifdef __linux__
fprintf(stderr, "Error: getaddrinfo failed with status: %s\n",
gai_strerror(rv));
#elif _WIN32
fprintf(stderr, "Error: getaddrinfo failed with status: %d\n",
rv);
#endif
return -1;
}
for(p = address_list; p != NULL; p = p->ai_next) {
#ifdef __linux__
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *) p->ai_addr),
addr_str, sizeof(addr_str));
printf("get_tcp_socket: Trying to connect to %s...\n", addr_str);
#endif
if((fd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
fprintf(stderr, "Error: socket() failed with status: "
"%s\n", strerror(errno));
continue;
}
if((flags & SOCKET_REUS) && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) != 0) {
fprintf(stderr, "Error: setsockopt() failed with status: "
"%s\n", strerror(errno));
return -1;
}
if((flags & SOCKET_BIND) && bind(fd, p->ai_addr, p->ai_addrlen) == -1) {
fprintf(stderr, "Error: bind() failed with status: "
"%s\n", strerror(errno));
#ifdef __linux__
close(fd);
#elif _WIN32
closesocket(fd);
#endif
continue;
}
if((flags & SOCKET_CONN) && connect(fd, p->ai_addr, p->ai_addrlen) == -1) {
fprintf(stderr, "Error: connect() failed with status: "
"%s\n", strerror(errno));
#ifdef __linux__
close(fd);
#elif _WIN32
closesocket(fd);
#endif
continue;
}
#ifdef __linux__
if((flags & SOCKET_NOBL) && fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
fprintf(stderr, "Error: fcntl() failed with status: "
"%s\n", strerror(errno));
close(fd);
continue;
}
#elif _WIN32
if((flags & SOCKET_NOBL) && ioctlsocket(fd, FIONBIO, &mode) != 0) {
fprintf(stderr, "Error: fcntl() failed with status: "
"%s\n", strerror(errno));
closesocket(fd);
continue;
}
#endif
break;
}
if(p == NULL) {
fprintf(stderr, "Error: failed to bind to any socket\n");
return -1;
}
freeaddrinfo(address_list);
printf("get_tcp_socket: Connected!\n");
return fd;
}
/*
int poor_send(const int socket, const char *message){
struct poorIRC_message msg;
msg.len = strlen(message) + 1;
printf("len sent: %d\nlen originally: %d", msg.len, strlen(message)+1);
if(0 == msg.len - 1)
return -1; you have to actually send something
else if (POORIRC_MSG_MAX_LEN < msg.len){
return -1; too much
}
else{
if (-1 == send(socket, (char *)&(msg.len), sizeof(msg.len), 0)){
return -1; error with sending
}
strncpy(msg.body,message, msg.len);
}
Sleep(1000);
if(-1 == (send(socket, (char *)&(msg.body), msg.len, 0))) {
return -1; /* error with sending actual message
}
printf("orginal: %s\nlength: %c\nsent: %s", message,msg.len, msg.body);
return 0;
}
int poor_recv(const int socket, struct poorIRC_message_srv *rsp ){
if(-1 == (recv(socket, (char *)&(rsp->len), sizeof(rsp->len), 0))) {
return -1;
}
printf("received lenght: %d\n",rsp->len);
if(-1 == (recv(socket, (char *)&rsp->body, rsp->len, 0))) {
return -1;
}
printf("received string: %s\n", rsp->body );
return 0;
}
*/
#ifdef __linux__
void modify_tcp_socket(int fd, char flags)
{
int yes = 1;
if((flags & SOCKET_REUS) && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) != 0) {
fprintf(stderr, "Error: setsockopt() failed with status: "
"%s\n", strerror(errno));
}
if((flags & SOCKET_NOBL) && fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
fprintf(stderr, "Error: fcntl() failed with status: "
"%s\n", strerror(errno));
}
}
#endif
|
C
|
/**
* Write a program to print a histogram of the frequencies of different
* characters in its input.
*/
#include <stdio.h>
#define MAXLEN 100
int main(int argc, char const *argv[])
{
char c;
int most_occuring = 0, ind = 0, count = 0, k = 0;
char input[MAXLEN];
int word_freq[MAXLEN];
bool signal = false;
while((c = getchar()) != EOF)
{
input[ind] = c;
++ind;
}
//printf("%d", ind);
// for(int ind2 = 0; ind2 < ind-1; ind2++)
// {
// printf("%c", input[ind2]);
// }
for(int i = 0; i < ind-1; i++)
{
count = 0;
signal = false; //for deciding whether the charater is already done or not, if that characters freq
// is already calculated then we will skip it.
for(int j = 0; j < ind-1; j++)
{
if((input[i] == input[j]) && (j > i))
{
count++;
}
if((input[i] == input[j]) && j < i)
{
signal = true;
}
}
if(!signal)
{
word_freq[k] = count+1;
++k;
}
}
// for(int ind = 0; ind < k; ind++)
// {
// printf("%d", word_freq[ind]);
// }
//Histogram printing...
for(int i = (ind-1); i > 0; i--)
{
for(int j = 0; j < k; j++)
{
if(i <= word_freq[j])
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
return 0;
}
|
C
|
/*maximum and minimum of three numbers using ternary condition
input:
10 6 17
output:
max:17 min:6
*/
#include<stdio.h>
int main(){
int a,b,c;
int max,min;
scanf("%d %d %d",&a,&b,&c);
max=(a>b&&a>c)?a:b>c?b:c;
min=(a<b&&a<c)?a:b<c?b:c;
printf("max:%d min:%d",max,min);
}
|
C
|
#include<stdio.h>
#include"grpengine.h"
void clear_screen()
{
//ȭ 尡 ʿ
//system("cls");
COORD Coor = { 0, 0 };
DWORD dw;
FillConsoleOutputCharacter
(GetStdHandle(STD_OUTPUT_HANDLE), ' ', 80 * 42, Coor, &dw);
}
void sleeped(int mil_second)
{
//clock();// ð
int result;
result = mil_second + clock();
while (result>clock());
}
void set_color(unsigned short color)
{
//WORD
/*
1.Ķ(ο) 2.() 3.û() 4.
//5.ũ 6.Ȳ 7.̺ 8.ȸ
9.Ķ() 10. 11.û 12. 13.ũ 14. 15.
*/
SetConsoleTextAttribute
(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void gotoxy(int x, int y)
{
//api setconsoleCursorposition // Ŀ ġ Ѵ.
//win32 api > ϴ .
//win32 > ˰̳
//HANDLE // α Ҽ ִ ּҳ ڷ
COORD CurPos = { x, y }; //ǥ
//ܼâ Ŀ ġ ٲ۴.
SetConsoleCursorPosition
(GetStdHandle(STD_OUTPUT_HANDLE), CurPos);
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "v1beta1_custom_resource_validation.h"
v1beta1_custom_resource_validation_t *v1beta1_custom_resource_validation_create(
v1beta1_json_schema_props_t *openAPIV3Schema
) {
v1beta1_custom_resource_validation_t *v1beta1_custom_resource_validation_local_var = malloc(sizeof(v1beta1_custom_resource_validation_t));
if (!v1beta1_custom_resource_validation_local_var) {
return NULL;
}
v1beta1_custom_resource_validation_local_var->openAPIV3Schema = openAPIV3Schema;
return v1beta1_custom_resource_validation_local_var;
}
void v1beta1_custom_resource_validation_free(v1beta1_custom_resource_validation_t *v1beta1_custom_resource_validation) {
listEntry_t *listEntry;
v1beta1_json_schema_props_free(v1beta1_custom_resource_validation->openAPIV3Schema);
free(v1beta1_custom_resource_validation);
}
cJSON *v1beta1_custom_resource_validation_convertToJSON(v1beta1_custom_resource_validation_t *v1beta1_custom_resource_validation) {
cJSON *item = cJSON_CreateObject();
// v1beta1_custom_resource_validation->openAPIV3Schema
if(v1beta1_custom_resource_validation->openAPIV3Schema) {
cJSON *openAPIV3Schema_local_JSON = v1beta1_json_schema_props_convertToJSON(v1beta1_custom_resource_validation->openAPIV3Schema);
if(openAPIV3Schema_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "openAPIV3Schema", openAPIV3Schema_local_JSON);
if(item->child == NULL) {
goto fail;
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
v1beta1_custom_resource_validation_t *v1beta1_custom_resource_validation_parseFromJSON(cJSON *v1beta1_custom_resource_validationJSON){
v1beta1_custom_resource_validation_t *v1beta1_custom_resource_validation_local_var = NULL;
// v1beta1_custom_resource_validation->openAPIV3Schema
cJSON *openAPIV3Schema = cJSON_GetObjectItemCaseSensitive(v1beta1_custom_resource_validationJSON, "openAPIV3Schema");
v1beta1_json_schema_props_t *openAPIV3Schema_local_nonprim = NULL;
if (openAPIV3Schema) {
openAPIV3Schema_local_nonprim = v1beta1_json_schema_props_parseFromJSON(openAPIV3Schema); //nonprimitive
}
v1beta1_custom_resource_validation_local_var = v1beta1_custom_resource_validation_create (
openAPIV3Schema ? openAPIV3Schema_local_nonprim : NULL
);
return v1beta1_custom_resource_validation_local_var;
end:
return NULL;
}
|
C
|
#include "log.h"
#include "wrapper.h"
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <string.h>
#include <sys/mman.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>
static const char* dir_name = "../log";
//static pthread_mutex_t* mutex;
static FILE* FP;
static struct tm* cur_time;
/*
* EFFECTS: init log file
* Assign value to static global variable FP
* ERRORS: -1 for init error
*/
int initLog()
{
mkdir(dir_name, 0777);
if (setFilePointer() == -1) {
return -1;
}
//initMutex();
return regularCleanLog();
}
/*
* EFFECTS: periodically clean expired logs
* ERRORS: -1 for error
*/
int regularCleanLog()
{
struct itimerval tick;
memset(&tick, 0, sizeof(tick));
tick.it_value.tv_sec = 1;
tick.it_interval.tv_sec = 24 * 60 * 60 * 1000;
if (setitimer(ITIMER_REAL, &tick, NULL) < 0)
return -1;
return 0;
}
/*
* EFFECTS: init mutex in a shared memory
* Assign value to static global variable mutex
*/
//void initMutex()
//{
// mutex = (pthread_mutex_t*) Mmap(NULL, sizeof(pthread_mutex_t),
// PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
// pthread_mutexattr_t attr;
// pthread_mutexattr_init(&attr);
// pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);
// pthread_mutex_init(mutex, &attr);
//}
/*
* EFFECTS: return filename according to current date
* Assign value to static global variable cur_time
*/
char* getFileName() {
time_t now = time(NULL);
cur_time = localtime(&now);
char time_str[MAXLINE];
strftime(time_str, MAXLINE, "%F", cur_time);
char* file_name = (char*) malloc(sizeof(char) * MAXLINE);
sprintf(file_name, "%s/%s-proxy.log", dir_name, time_str);
return file_name;
}
/*
* EFFECTS: assign value to static global variable FP
* ERRORS: -1 for init error
*/
int setFilePointer()
{
char* file_name = getFileName();
if ((FP = fopen(file_name,"a")) == NULL)
{
fprintf(stderr, "fail to open or create log file");
free(file_name);
return -1;
}
free(file_name);
return 0;
}
/*
* EFFECTS: write formatted log to file
*/
void Log(enum LOG_TYPE type, const char* func_name, const char* msg)
{
char log_type[MAXWORD];
switch(type)
{
case Error:
strcpy(log_type, "ERROR");
break;
case Debug:
strcpy(log_type, "DEBUG");
break;
default:
strcpy(log_type, "INFO");
}
char time_str[MAXLINE];
time_t now = time(NULL);
struct tm* local = localtime(&now);
strftime(time_str, MAXLINE, "%a %d %b %Y %H:%M:%S %Z", local);
//pthread_mutex_lock(mutex);
if (local->tm_mday != cur_time->tm_mday)
setFilePointer();
fprintf(FP, "[%s], <%s>, %s: %s\n", log_type, func_name, time_str, msg);
// Flush after write!!!!
fflush(FP);
//pthread_mutex_unlock(mutex);
}
|
C
|
#include <stdio.h>
main()
{
int a=10;
int b=20;
swapv(a,b);
printf("a=%d\n",a);
printf("b=%d\n",b);
}
swapv(int x,int y)
{
int t;
t = x;
x = y;
y = t;
printf("x=%d\n",x);
printf("y=%d\n",y);
}
|
C
|
/*
Meno: Matus Brandys
Datum: 4.12.2016
Simulujte nasledujucu situaciu.
Vo vyvhodnej Europe, v malej dedinke prepukla epidemia a nakazilo sa 10 ludi. Sedem z nich maju len mensiu nemoc na traja ludia maju vazne problemi. Aby sa nakazilo este viac ludi, tak sa vlada rozhodla tychto 10 ludi prestahovat do vedlasej dedinky, kde uz nikto dlhsie nebyval. Tito ludia musia kazdy den chodit na zdravotne stredisko v pravidelnych intervaloch (lahko chori v simulacii 3s a takzko chori 2.5s), kde ordinuje jeden doktor. Osetrenie jedneho pacienta trva urcity cas (lahko choreho v simulacii 0.5s a tazko choreho 1) a potom moze ist domov. Cela simulacia trva 20s.
1. Doplnte do programu pocitadlo pocitajuce, kolko krat boli vysetreni pacienti s velkymi ocherenim a tiez pocitadlo ratajucem kolko krat boli vysetreni pacienti len sa malou nemocou.
2. Zabezpecte, aby do miestnosti k lekarovi mohli vojst maximalne dvaja lahko postihnuti pacienti, a ak v cakarni caka pacient z vaznym postihnutim, tak lekar dovysetruje pritimnich pacientov v miestnosti a pacient z vaznym postinutim ma prednst pred ostatnymi. Pocet pacientov v miestnosti s vaznym ochorenim mozu byt aj 3 ale vysetruje sa iba jeden.
3. Osetrite v programe spravne ukoncenie simulacie po uplynuti stanoveneho casu, tak ze ti pacienti co su este v cakarni, tyc doktor dovysetruje.
Poznamky:
- na synchronizaciu je mozne pouzit mutexy, podmienene premenne alebo semafory
- nespoliehajte sa na uvedene casy, simulacia by mala fungovat aj s inymi casmi
- build (console): gcc epidemia.c -o epidemia -lpthread
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
// signal na zastavenie simulacie
pthread_mutex_t mutex_stoj = PTHREAD_MUTEX_INITIALIZER;
int stoj = 0;
//pthread_cond_t chram_z = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_tazko_chori = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_lahko_chori = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_vysetrenie = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_t;
pthread_cond_t cond_l;
int count_tazko_chori = 0;
int count_lahko_chori = 0;
int count_vsetci = 0;
int pritomni_t = 0;
int pritomni_l = 0;
// lahko chori ide domov
void volno_lahko_chory(int i) {
printf("lahko chory pacient %d je doma\n", i);
sleep(3);
}
void vysetrenie_lahko_choreho(int i) {
//lahko chori moznu do miestnosti vstupit aj dvaja ak tam nie je tazko chori
pthread_mutex_lock(&mutex_vysetrenie);
printf("%d lahko chory sa dostavil pred miestnost\n", i);
while(pritomni_t != 0 || pritomni_l >= 2)
pthread_cond_wait(&cond_l, &mutex_vysetrenie);
pritomni_l++;
printf("%d lahko chory bude vstupovat do miestnostnosti\n", i);
pthread_mutex_unlock(&mutex_vysetrenie);
//kriticka oblast == miestnost == lahko chori vysetrovat iba po 1
pthread_mutex_lock(&mutex_lahko_chori);
printf("vysetrenie %d lahko choreho\n", i);
sleep(0.5); //samotne vysetrenie v miestnosti u dkotora
count_lahko_chori++;
count_vsetci++;
pthread_mutex_unlock(&mutex_lahko_chori);
pthread_mutex_lock(&mutex_vysetrenie);
pritomni_l--; //opusta miestnost dokora
printf("lahko chory %d opustuje miestnostnost\n", i);
pthread_cond_broadcast(&cond_t);
pthread_cond_broadcast(&cond_l); //potrebne na ukoncenie na konci !!!!!
pthread_mutex_unlock(&mutex_vysetrenie);
}
void *lahka_choroba( void *ptr ) {
int i = (int*)ptr;
// pokial nie je zastaveny
pthread_mutex_lock(&mutex_stoj);
while(!stoj) {
pthread_mutex_unlock(&mutex_stoj);
vysetrenie_lahko_choreho(i);
volno_lahko_chory(i);
pthread_mutex_lock(&mutex_stoj);
}
pthread_mutex_unlock(&mutex_stoj);
return NULL;
}
// tazko chori ide domov
void volno_tazko_chory(int i) {
printf("tazko chory pacient %d je doma\n", i);
sleep(5);
}
void vysetrenie_tazko_choreho(int i) {
//tazko chori vstupuje do miestnosti iba jeden a ma prednost pred lahko chorimi, ale musi pockat kym sa lahko chori dovysetruje
pthread_mutex_lock(&mutex_vysetrenie);
pritomni_t++;
printf("%d tazko chory sa dostavil pred miestnost\n", i);
while(pritomni_l != 0)
pthread_cond_wait(&cond_t, &mutex_vysetrenie);
printf("%d tazko chory bude vstupovat do miestnostnosti\n", i);
pthread_mutex_unlock(&mutex_vysetrenie);
//kriticka oblast == miestnost == tazko chori vysetrovat iba po 1
pthread_mutex_lock(&mutex_tazko_chori);
printf("vysetrenie %d tazko choreho\n", i);
sleep(1); //samotne vysetrenie v miestnosti u dkotora
count_tazko_chori++;
count_vsetci++;
pthread_mutex_unlock(&mutex_tazko_chori);
pthread_mutex_lock(&mutex_vysetrenie);
pritomni_t--; //opusta miestnost dokora
printf("tazko chory %d opustuje miestnostnost\n", i);
pthread_cond_broadcast(&cond_l);
pthread_mutex_unlock(&mutex_vysetrenie);
}
void *vazna_choroba( void *ptr ) {
int i = (int*)ptr;
// pokial nie je zastaveny
pthread_mutex_lock(&mutex_stoj);
while(!stoj) {
pthread_mutex_unlock(&mutex_stoj);
vysetrenie_tazko_choreho(i);
volno_tazko_chory(i);
pthread_mutex_lock(&mutex_stoj);
}
pthread_mutex_unlock(&mutex_stoj);
return NULL;
}
int main(void) {
int i;
pthread_t vazne_chori[3];
pthread_t lahko_chori[7];
for (i=0;i<3;i++) pthread_create( &vazne_chori[i], NULL, &vazna_choroba,(void*)i);
for (i=0;i<7;i++) pthread_create( &lahko_chori[i], NULL, &lahka_choroba, (void*)i);
sleep(20);
pthread_mutex_lock(&mutex_stoj);
stoj = 1;
pthread_cond_broadcast(&cond_l);
pthread_cond_broadcast(&cond_t);
pthread_mutex_unlock(&mutex_stoj);
for (i=0;i<3;i++) pthread_join( vazne_chori[i], NULL);
for (i=0;i<7;i++) pthread_join( lahko_chori[i], NULL);
printf("pocet vysetreni tazko chorych: %d, lahko_chorich: %d, vsetkych: %d\n ", count_tazko_chori, count_lahko_chori, count_vsetci);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
// c function must return
int FindGreatestSumOfSubArray(int* array, int arrayLen ) {
// write code here
int f = array[0];
int s = array[0];
int re = array[0];
for (int i = 1; i < arrayLen; i ++){
s += array[i];
printf("%d ", s);
if (s > array[i]){
f = s;
} else {
f = array[i];
s = array[i];
}
if (s > re){ re = s; }
}
return re;
}
int main()
{
int num[] = {2,8,1,5,9}; // this is array, don't need to assign size
FindGreatestSumOfSubArray(num, 5);
return 0;
}
|
C
|
#include "ft_malloc.h"
void *realloc(void *ptr, size_t size)
{
t_allocinfo *zone;
t_allocinfo *next;
t_allocinfo *next_tmp;
size_t tmp_size;
zone = ptr - STRUCTSIZE;
if (exists(zone))
return (NULL);
if (zone->size >= size + STRUCTSIZE * 2)
zone = split_zone(zone, size);
else
{
next = (void *)malloc(size) - 16;
next_tmp = next->next;
tmp_size = next->size;
ft_memcpy(next, zone, zone->size - 16);
next->size = tmp_size;
next->next = next_tmp;
zone->is_free = 1;
zone = next;
}
return ((void*)zone + 16);
}
t_allocinfo *split_zone(t_allocinfo *actual, size_t size)
{
t_allocinfo new;
new.size = actual->size - (size + STRUCTSIZE);
new.next = actual->next;
new.is_free = 1;
actual->size = size + STRUCTSIZE;
actual->next = (void*)actual + actual->size;
ft_memcpy(actual->next, &new, STRUCTSIZE);
return (actual);
}
int exists(t_allocinfo *map)
{
t_allocinfo *reel;
reel = g_pages.tiny;
while (reel != NULL)
{
if (reel == map)
return (0);
reel = reel->next;
}
reel = g_pages.small;
while (reel != NULL)
{
if (reel == map)
return (0);
reel = reel->next;
}
reel = g_pages.large;
while (reel != NULL)
{
if (reel == map)
return (0);
reel = reel->next;
}
return (1);
}
|
C
|
#include <stdio.h>
#include <omp.h>
#define N 1000000
int a[N];
int main(){
// initialize the array
for(int i=0; i<N; ++i){
a[i] = 0.2 * i;
}
int sum = 0;
double seq_time, par_time;
double t1 = omp_get_wtime();
// sequential implementation
for(int i=0; i<N; ++i){
sum += a[i];
}
seq_time = omp_get_wtime() - t1;
printf("sequential sum: %d\n", sum);
printf("sequential time: %lf\n", par_time);
sum = 0;
t1 = omp_get_wtime();
// parallel implementation
#pragma omp parallel for reduction(+:sum)
for(int i=0; i<N; ++i){
sum += a[i];
}
par_time = omp_get_wtime() - t1;
printf("parallel sum: %d\n", sum);
printf("parallel time: %lf\n", par_time);
return 0;
}
|
C
|
//A dictionary
//data is the contents of the dictionary (not including definitions)
//so dict.data[0] should be a string containting the first word in the dictionary, and so on.
//size is the number of words in the dictionary.
typedef struct{
char** data;
int size;
} dictionary;
//reads a dictionary line by line from filename into the data structure.
//aborts if the file is not opened.
void dict_open(char* filename, dictionary* dict){
//open the file, make sure it works
FILE* f=fopen(filename,"r");
if (f==NULL){
fprintf(stderr,"File %s not opened properly\n",filename);
exit(1);
}
//Start small-ish, grow as needed.
long int dict_capacity=1000;
dict->data=malloc(dict_capacity*sizeof(char*));
//how many are filled?
int dict_filled=0;
//a buffer to read into
char word[1000];
int wordlen;
//Start reading from file. Keep reading as long as results make sense.
while (fgets(word,1000,f)!=NULL){
wordlen=strlen(word);
//strip the newline if it is there:
if (word[wordlen-1]=='\n'){
word[wordlen-1]='\0';
}
//if the dictionary is currently full, expand it.
if (dict_filled==dict_capacity-1){
dict_capacity=dict_capacity*2;
dict->data=realloc(dict->data,dict_capacity*sizeof(char*));
}
//malloc room for the word -- I bet this is real slow, but good on memory.
dict->data[dict_filled]=malloc((wordlen+1)*sizeof(char));
//copy the word into dictionary.
strcpy(dict->data[dict_filled],word);
//increment len
dict_filled++;
}
//Finish
dict->size=dict_filled;
fclose(f);
}
//checks to see if word is in the supplied dictionary.
//if it is, the return value is a non-negative integer indicating the position of the word in the dictionary.
//if it is not, returns -1.
//
//*ASSUMES THAT dict.data IS SORTED IN ALPHABETICAL ORDER!
int dict_lookup(char* word, dictionary* dict){
//will hold the index of word in dict, if word exists in dict.
int targ_idx=-1;
//upper and lower bounds for binary search.
int l=0;
int u=dict->size-1;
int m;
if (strcmp(word, dict->data[l])==0){
targ_idx=l;
}
if (strcmp(word,dict->data[u])==0){
targ_idx=u;
}
int r;
while (targ_idx==-1 && u-l>1){
m=(l+u)/2;
//get the result of alphabetic comparison of the target word and the m'th word in the dictionary.
r=strcmp(word,dict->data[m]);
//found!
if (r==0){
targ_idx=m;
}
//update l and u accordingly.
else if (r<0){
u=m;
}
else{
l=m;
}
}
return targ_idx;
}
|
C
|
#include <stdio.h>
// 1. Է
void main(){
int dan;
int i=9;
printf(" Էϼ: ");
scanf("%d", &dan);
while (i > 0){
printf("%d x %d = %d \n", dan, i, dan * i);
i--;
}
}
|
C
|
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int i;
for(i = 0; i < 4; i++) {
pid_t pid = fork();
if(pid < 0) {
printf("Error");
exit(1);
} else if (pid == 0) {
printf("Child (%d): %d\n", i + 1, getpid());
exit(0);
} else {
wait(NULL);
}
}
}
|
C
|
#include <esp8266.h>
#include <serled.h>
static ETSTimer serledTimer;
static uint8_t serledPin;
static void ICACHE_FLASH_ATTR setSerled(int on) {
// LED is active-low
if (on) {
gpio_output_set(0, (1<<serledPin), (1<<serledPin), 0);
} else {
gpio_output_set((1<<serledPin), 0, (1<<serledPin), 0);
}
}
static void ICACHE_FLASH_ATTR serledTimerCb(void *v) {
setSerled(0);
}
void ICACHE_FLASH_ATTR serledFlash(int duration) {
setSerled(1);
os_timer_disarm(&serledTimer);
os_timer_setfn(&serledTimer, serledTimerCb, NULL);
os_timer_arm(&serledTimer, duration, 0);
}
void ICACHE_FLASH_ATTR serledInit(uint8_t pin) {
serledPin = pin;
makeGpio(pin);
gpio_output_set(0, 0, (1<<pin), 0);
serledFlash(1000); // turn it on for 1 second
}
// Make a pin be GPIO, i.e. set the mux so the pin has the gpio function
void ICACHE_FLASH_ATTR makeGpio(uint8_t pin) {
uint32_t addr;
uint8_t func = 3;
switch (pin) {
case 0:
addr = PERIPHS_IO_MUX_GPIO0_U;
func = 0;
break;
case 1:
addr = PERIPHS_IO_MUX_U0TXD_U;
break;
case 2:
addr = PERIPHS_IO_MUX_GPIO2_U;
func = 0;
break;
case 3:
addr = PERIPHS_IO_MUX_U0RXD_U;
break;
case 4:
addr = PERIPHS_IO_MUX_GPIO4_U;
func = 0;
break;
case 5:
addr = PERIPHS_IO_MUX_GPIO5_U;
func = 0;
break;
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
addr = PERIPHS_IO_MUX_SD_CMD_U - 4 * (11-pin);
break;
case 12:
case 13:
case 14:
case 15:
addr = PERIPHS_IO_MUX_MTDO_U - 4 * (15-pin);
break;
default:
return;
}
PIN_FUNC_SELECT(addr, func);
}
|
C
|
#include<stdio.h>
#define F_LOW 0 //------------------------------
#define F_MAX 250 //-----SYMBOLIC CONSTANTS-------
#define STEP 25 //------------------------------
int main()
{
typedef float REAL;
REAL f, c;
f = F_LOW;
printf("Fahrenheit | Celsius\n\n");
//----------------------------------------------
//STAY IN LOOP AND CONVERT FAHRENHEIT TO CELSIUS
//---------------------------------------------
while(f <= F_MAX)
{
c = (f - 32.0)/1.8;
printf("\t%5.1f | %7.2f\n", f, c);
f += STEP;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void printByArray(int(*pArr)[3], int len1, int len2)
{
for (int i = 0; i < len1; ++i) {
for (int j = 0; j < len2; ++j) {
//printf("%d ", *(*(pArr + i) +j));
printf("%d ", pArr[i][j]);
}
}
printf("\n");
}
void test01()
{
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
printByArray(arr, 3, 3);
//int arr[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
//int arr[][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
//对于二维数组,同一维数组一样,除了sizeof 和取地址以外,那么数组名就是指向数组首元素的指针
//int(*pArray)[3] = arr;
printf("%d\n", arr[2][1]);
printf("*(*(arr + 2) +1) = %d\n", *(*(arr + 2) +1));
}
int main(int argc, char *argv[])
{
test01();
return 0;
}
|
C
|
/*
Created on 04/2015
Author: guidefloripa
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
*/
#include <stdio.h>
#include <string.h>
int next_permutation(int* arr, int len)
{
int i, j, temp;
i = len - 1;
while (i>0 && arr[i-1]>arr[i]) {
i--;
}
if (i==0) return 0;
j = len - 1;
while (arr[j] <= arr[i-1]) {
j--;
}
temp = arr[i-1];
arr[i-1] = arr[j];
arr[j] = temp;
j = len -1;
while (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
return 1;
}
int main(int argc, char** argv)
{
int numbers[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int s = sizeof(numbers)/sizeof(numbers[0]);
int i = 0;
do {
i++;
if (i == 1000000) break;
} while (next_permutation(numbers, s));
fprintf(stderr, "[Problem 24] ");
for (i = 0; i<s; i++) {
fprintf(stderr, "%d", numbers[i]);
}
fprintf(stderr, "\n");
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int parcela1, parcela2;
printf("Digite a primeira parcela: ");
scanf("%d", &parcela1);
printf("Digite a segunda parcela: ");
scanf("%d", &parcela2);
int soma = parcela1 + parcela2;
printf("%d + %d = %d\n", parcela1, parcela2, soma);
return 0;
}
|
C
|
#include <stdio.h>
void next(int *a, int n) {
int j = n - 1;
int temp;
while (a[j] > a[j + 1]) j--;
int k = n;
while (a[j] > a[k]) k--;
temp = a[j];
a[j] = a[k];
a[k] = temp;
int r = n;
int s = j+1;
while (r > s) {
temp = a[r];
a[r] = a[s];
a[s] = temp;
r--;
s++;
}
}
int main() {
int num[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, i;
for (i = 2; i <= 1000000; i++) next(num, 9);
for (i = 0; i < 10; i++) printf("%d",num[i]);
printf("\n");
return 0;
}
|
C
|
//mapping table data structure is used to store the correspondence between threads and core. author:hh
typedef struct processor{
int logical_id;
int physical_id;
}Proc;
typedef struct index{
int proc_no;
int thread_no;
}Index;
////mapping function: returns the cpu number bound to the thread in same core author:hh
int mapping(int proc_num,int thread_num,int t_no){
Index* index=(Index*)malloc(thread_num*sizeof(Index));
int tnum=0,cnum=0;
while(tnum<thread_num){
index[tnum].thread_no=tnum;
index[tnum].proc_no=cnum;
tnum++;
cnum++;
if(cnum>=proc_num){
cnum=0;
}
}
return index[t_no].proc_no;
}
//mapping function in different core
int mapping_diff_core(int proc_num,int thread_num,int t_no){
Index* index=(Index*)malloc(thread_num*sizeof(Index));
int tnum=0,cnum=0;
while(tnum<thread_num){
index[tnum].thread_no=tnum;
index[tnum].proc_no=cnum;
tnum++;
cnum=cnum+2;
if(cnum>=proc_num){
cnum=1;
}
}
return index[t_no].proc_no;
}
//read config file
/*char* read_file(char * filename){
FILE *fp=fopen(filename, "r+");
char buf[1024];
if (fp != (FILE *)NULL)
{
while(fgets(buf, sizeof(buf), fp)){
printf("%s",buf);
}
fclose(fp);
}
return buf;
}*/
|
C
|
/*
'global shared int i = 0
main:
spawn thread_1
spawn thread_2
join all threads (wait for them to finish)
print i
thread_1:
do 1_000_000 times:
i++
thread_2:
do 1_000_000 times:
i--
*/
#include <pthread.h>
#include <stdio.h>
int i = 0; //Husk i og ikke j
void minus(){
for (int j = 0; j< 1000000;j++){
i--;
//printf("minus gives: %i\n", i);
}
}
void plus(){
for (int j = 0; j< 1000000;j++){
i++;
//printf("plus gives: %i\n", i);
}
}
int main(){
pthread_t mThread;
pthread_t pThread;
pthread_create(&pThread, NULL, plus, NULL);
pthread_create(&mThread, NULL, minus, NULL);
pthread_join(pThread, NULL);
pthread_join(mThread, NULL);
printf("done gives: %i\n", i);
return 0;
}
|
C
|
/*
* 链表反转
*/
#include <stdio.h>
#include <stdlib.h>
#define LEN 5
typedef struct NUMS {
int num;
struct NUMS *p_next;
}N;
N* create_linklist( int *a, int n ){
N *p_head;
N *p_node;
p_head = ( N* )malloc( sizeof( N ) );
if( !p_head ) return NULL;
p_head->num = a[0];
p_head->p_next = NULL;
p_node = p_head;
int i = 1;
for( i = 1 ; i < n ; i++ ){
N* p = ( N* )malloc( sizeof( N ) );
if( !p ) break;
p->num = a[i];
p->p_next = NULL;
p_node->p_next = p;
p_node = p;
}
return p_head;
}
void print_linklist( N* p_head ) {
N* p_node = p_head;
while( p_node != NULL ){
printf( "%d\n", p_node->num );
p_node = p_node->p_next;
}
}
N* invert_linklist( N* p_head ) {
N* p_mid = NULL; //head前面的节点
N* p_last = NULL; //mid前面的节点
while( p_head != NULL ) {
p_last = p_mid;
p_mid = p_head;
p_head = p_head->p_next;
p_mid->p_next = p_last;
}
return p_mid;
}
void free_linklist( N* p_head ) {
N* p_node;
while( p_head != NULL ) {
p_node = p_head;
p_head = p_head->p_next;
free( p_node );
}
p_node = NULL;
}
int main( void ) {
int arr[LEN] = { 10, 20, 30, 40, 50 };
N* p_head = create_linklist( arr, LEN );
printf( "反转前\n" );
print_linklist( p_head );
printf( "反转后\n" );
p_head = invert_linklist( p_head );
print_linklist( p_head );
free_linklist( p_head );
return 0;
}
|
C
|
#include <stdio.h>
int main ()
{
int marks;
char grade;
scanf ("%d",&marks);
if (marks >= 80){
grade = 'A+';
printf ("your grade is %c\n",grade);
}
else if (marks >= 70){
grade ='A';
printf ("your grade is %c\n",grade);
}
else if (marks >= 60){
grade = 'B';
printf (" your grade is %c\n", grade);
}
else if (marks >= 50){
grade = 'C';
printf ("your grade is %c\n", grade);
}
else if (marks >= 40){
grade ='d';
printf ("your grade is %c\n",grade);
}
else {
printf ("your grade is F\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
float Floating(float x){
float y;
y = x/(1 + fabsf(x));
return y;
}
int main(){
printf("Input x:\n");
float x;
scanf("%f",&x);
printf("%f\n", Floating(x));
}
|
C
|
void arpcache_insert(u32 ip4, u8 mac[ETH_ALEN])
{
// check is there has been one item with given ipv4 addr, if yes, replace it
int i = 0;
int flag = 0;
for (i = 0; i < MAX_ARP_SIZE; i += 1) {
if(arpcache.entries[i].ip4 == ip4) {
flag = 1;
memcpy(arpcache.entries[i].mac, mac, ETH_ALEN);
arpcache.entries[i].valid = 1;
time(&arpcache.entries[i].added);
}
}
if(flag == 0) {
// if no, create one, put it in the first place, FIFO
struct arp_cache_entry *entry = (struct arp_cache_entry *)malloc(sizeof(struct arp_cache_entry));
entry->ip4 = ip4;
memcpy(entry->mac, mac, ETH_ALEN);
time(&entry->added);
entry->valid = 1;
for (i = MAX_ARP_SIZE - 1; i >= 0; i -= 1) {
arpcache.entries[i] = arpcache.entries[i - 1];
}
arpcache.entries[0] = *entry;
}
struct arp_req *req = NULL;
struct cached_pkt *pkt = NULL;
list_for_each_entry(req, &arpcache.req_list, list) {
if(req->ip4 == ip4) {
pkt = NULL;
list_for_each_entry(pkt, &req->cached_packets, list) {
struct ether_header * eh = (struct ether_header *)(pkt->packet);
memcpy(eh->ether_dhost, mac, ETH_ALEN);
iface_send_packet(req->iface, pkt->packet, pkt->len);
list_delete_entry(&pkt->list);
}
list_delete_entry(&req->list);
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
FILE *f;
char input[1000];
int t, i=0;
f=fopen("input.txt", "r");
fseek(f, 0, SEEK_END);
t=ftell(f);
fseek(f,0,SEEK_SET);
while(!feof(f)){
fscanf(f, "%c", &input[i]);
i++;
}
input[i-1]='\0';
printf("%s", input);
}
|
C
|
/*
* AF_INET
* This designates the address format that goes with the Internet namespace
* 网络编程 -- 客户端
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc, char const *argv[])
{
int server_fd;
char buf[100] = {0};
struct sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
/* inet_addr 将字符串转换为int型数据 */
serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serveraddr.sin_port = htons(8080);
//建立socket
server_fd = socket(AF_INET,SOCK_STREAM,0);
if(server_fd == -1){
perror("socket error");
exit(-1);
}
//连接
if(connect(server_fd,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) == -1){
perror("connect error");
exit(-1);
}
//读取服务器端发送的信息
read(server_fd,buf,100);
printf("get message = %s\n",buf);
close(server_fd);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int i = 0;
for(i = 0; i < 729; ++i)
{
printf("%i\n", i);
}
printf("The value of i is %i\n", i);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "ArrayEmployees.h"
#define cant 1000
int menuOpcion_getNumero(int opcion, char* mensaje, char* mensajeErrorUno)
{
system("cls");
printf("Bienvenido al Menu, que desea realizar?");
printf("\n\n 1. Dar Alta Empleado.");
printf("\n 2. Modificar legajo.");
printf("\n 3. Dar Baja Empleado.");
printf("\n 4. Informes.");
printf("\n 5. Salir.");
printf(mensaje);
fflush(stdin);
scanf("%d", &opcion);
while(opcion > 5 || opcion < 1)
{
printf(mensajeErrorUno);
printf("\n\n Por favor ingrese otro numero: ");
fflush(stdin);
scanf("%d", &opcion);
}
return opcion;
}
void init(eEmpleado empleado[], int cantidad)
{
int i;
for(i = 0; i < cantidad; i++)
{
empleado[i].isEmpty = 1;
}
}
int obtenerEspacioLibre(eEmpleado empleado[], int cantidad)
{
int i, retorno = -1;
for(i = 0; i < cantidad; i++)
{
if(empleado[i].isEmpty == 1)
{
retorno = i;
break;
}
}
return retorno;
}
void alta(eEmpleado empleado[], int cantidad)
{
int index;
index = obtenerEspacioLibre(empleado, cantidad);
if(index != -1)
{
empleado[index].id = cargaId();
system("cls");
printf("Ingrese el Apellido: ");
fflush(stdin);
fgets(empleado[index].apellido, sizeof(empleado[index].apellido)-2, stdin);
cantidad = strlen(empleado[index].apellido);
empleado[index].apellido[cantidad-1] = '\0';
empleado[index].apellido[0] = toupper(empleado[index].apellido[0]);
printf("\nIngrese el Nombre: ");
fgets(empleado[index].nombre, sizeof(empleado[index].nombre)-2, stdin);
cantidad = strlen(empleado[index].nombre);
empleado[index].nombre[cantidad-1] = '\0';
empleado[index].nombre[0] = toupper(empleado[index].nombre[0]);
printf("\nSectores ");
printf("\n1.RRHH");
printf("\n2.Administracion");
printf("\n3.Fabrica");
printf("\n4.Ventas");
printf("\n5.Tesoreria");
printf("\n\nIndique el Sector: ");
scanf("%d", &empleado[index].sector);
printf("\nIngrese el Salario: ");
scanf("%f", &empleado[index].salario);
empleado[index].isEmpty = 0;
}
}
void baja(eEmpleado empleado[], int cantidad)
{
int i;
int idAux;
char respuesta;
int flag = 0;
system("cls");
printf("Ingrese el ID del empleado: ");
fflush(stdin);
scanf("%d", &idAux);
for(i = 0; i < cantidad; i++)
{
if(idAux == empleado[i].id)
{
flag = 1;
printf("Apellido: %s \t Nombre: %s \t Sector: %d", empleado[i].apellido, empleado[i].nombre, empleado[i].sector);
printf("\n\n Desea eliminar el registro? S/N: ");
fflush(stdin);
scanf("%c", &respuesta);
while(respuesta != 's' && respuesta != 'n')
{
printf("Error ingrese S o N");
scanf("%c", &respuesta);
}
if(respuesta == 's')
{
empleado[i].isEmpty = 1;
printf("El registro fue eliminado.");
system("pause");
break;
}
else
{
printf("El registro no fue eliminado.");
system("pause");
break;
}
}
}
if(flag == 0)
{
printf("Dato inexistente...");
system("pause");
}
}
void orden(int cantidad)
{
eEmpleado empleado[cantidad], empAux;
int i, j;
for(i = 0; i < cantidad; i++){
for(j = i+1; j < cantidad; j++)
{
if(strcmp(empleado[i].apellido, empleado[j].apellido) > 0)
{
empAux = empleado[i];
empleado[i] = empleado[j];
empleado[j] = empAux;
}
else if(strcmp(empleado[i].apellido, empleado[j].apellido) == 0 && strcmp(empleado[i].nombre, empleado[j].nombre) > 0)
{
empAux = empleado[i];
empleado[i] = empleado[j];
empleado[j] = empAux;
}
}
}
}
static int cargaId(void)
{
static int carga = 0;
return carga++;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** str_to_word_array.c
** File description:
** create tab string
*/
#include "../header.h"
char *select_word(char *wrd, char *str, int end, int start)
{
int i = 0;
while (start != end) {
wrd[i] = str[start];
i = i + 1;
start = start + 1;
}
wrd[i] = '\0';
return (wrd);
}
char *push_the_word(char *str, int word, char c)
{
char *wrd;
int i = 0;
int j = 0;
while (j != word) {
if (str[i] == c || str[i] == '\t') {
while (str[i] == c || str[i] == '\t') {
i = i + 1;
}
if (str[i] != '\n')
j = j + 1;
} else
i = i + 1;
}
j = i;
while (str[i] != c && str[i] != '\t' && str[i] != '\n') {
i = i + 1;
}
wrd = malloc(sizeof(char)*(i + 1));
return (select_word(wrd, str, i, j));
}
void worder(char **str_tab, char *str, int word, char c)
{
int i = 0;
while (i != word) {
str_tab[i] = push_the_word(str, i, c);
i = i + 1;
}
str_tab[i] = NULL;
}
char **str_to_word_array(char *str, char c)
{
char **str_tab = NULL;
int i = 0;
int word = 1;
while (str[i] != '\0') {
if (str[i] == c || str[i] == '\t') {
while (str[i] == c || str[i] == '\t') {
i = i + 1;
}
if (str[i] != '\n')
word = word + 1;
} else
i = i + 1;
}
str_tab = malloc(sizeof(char *)*(word + 1));
worder(str_tab, str, word, c);
return (str_tab);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lista.h"
#include "operacoes.h"
void menu(){
int op=-1, i;
system("clear");
printf("#######################################\n");
printf(" CALCULADORA - BIG INT \n");
printf("#######################################\n\n");
printf("1 - ADIÇÃO\n");
printf("2 - COMPARAÇÃO\n");
printf("3 - QUADRADO\n");
printf("4 - MULTIPLICAÇÃO\n");
printf("5 - MDC\n");
printf("6 - FATORIAL\n");
printf("7 - EXPONENCIAÇÃO\n");
printf("8 - MÓDULO\n");
printf("0 - SAIR\n\n");
printf("- > ");
scanf("%d", &op);
if(op==0) exit(0);
char *ch1 = (char*)malloc(sizeof(char));
char *ch2 = (char*)malloc(sizeof(char));
switch(op){
case 1: system("clear");
printf("#######################################\n");
printf(" SOMA \n");
printf("#######################################\n\n");
Lista* parcela1 = cria();
Lista* parcela2 = cria();
printf("Digite a primeira parcela: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
parcela1 = lerNumero(parcela1, ch1[i]);
}
printf("Digite a segunda parcela: ");
scanf("%s", ch2);
for(i=0; i<strlen(ch2); i++){
parcela2 = lerNumero(parcela2, ch2[i]);
}
parcela1 = removeZeroInicio(parcela1);
parcela2 = removeZeroInicio(parcela2);
printf("\nResultado = ");
imprime(adicao(parcela1, parcela2));
printf("\n\n");
libera(parcela1); libera(parcela2);
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 2: system("clear");
printf("#######################################\n");
printf(" COMPARAÇÃO \n");
printf("#######################################\n\n");
Lista* numero1 = cria();
Lista* numero2 = cria();
printf("Digite o primeiro número: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
numero1 = lerNumero(numero1, ch1[i]);
}
printf("Digite o segundo número: ");
scanf("%s", ch2);
for(i=0; i<strlen(ch2); i++){
numero2 = lerNumero(numero2, ch2[i]);
}
numero1 = removeZeroInicio(numero1);
numero2 = removeZeroInicio(numero2);
printf("\n");
if(compara(numero1, numero2)==-1){
printf("O primeiro número é menor que o segundo.\n");
}
else
if(compara(numero1, numero2)==1){
printf("O primeiro número é maior que o segundo.\n");
}
else
if(compara(numero1, numero2)==0){
printf("Os números são iguais.\n");
}
libera(numero1); libera(numero2);
printf("\n");
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 3: system("clear");
printf("#######################################\n");
printf(" QUADRADO \n");
printf("#######################################\n\n");
Lista* numeroQuad = cria();
printf("Digite um número: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
numeroQuad = lerNumero(numeroQuad, ch1[i]);
}
numeroQuad = removeZeroInicio(numeroQuad);
printf("\nResultado = ");
imprime(quadrado(numeroQuad));
printf("\n\n");
libera(numeroQuad);
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 4: system("clear");
printf("#######################################\n");
printf(" MULTIPLICAÇÃO \n");
printf("#######################################\n\n");
Lista* fator1 = cria();
Lista* fator2 = cria();
printf("Digite o primeiro fator: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
fator1 = lerNumero(fator1, ch1[i]);
}
printf("Digite o segundo fator: ");
scanf("%s", ch2);
for(i=0; i<strlen(ch2); i++){
fator2 = lerNumero(fator2, ch2[i]);
}
fator1 = removeZeroInicio(fator1);
fator2 = removeZeroInicio(fator2);
printf("\nResultado = ");
imprime(produto(fator1, fator2));
printf("\n\n");
libera(fator1); libera(fator2);
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 5: system("clear");
printf("#######################################\n");
printf(" MDC \n");
printf("#######################################\n\n");
Lista* numero1Mdc = cria();
Lista* numero2Mdc = cria();
printf("Digite o primeiro número: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
numero1Mdc = lerNumero(numero1Mdc, ch1[i]);
}
printf("Digite o segundo número: ");
scanf("%s", ch2);
for(i=0; i<strlen(ch2); i++){
numero2Mdc = lerNumero(numero2Mdc, ch2[i]);
}
numero1Mdc = removeZeroInicio(numero1Mdc);
numero2Mdc = removeZeroInicio(numero2Mdc);
printf("\nResultado = ");
imprime(mdc(numero1Mdc, numero2Mdc));
printf("\n\n");
libera(numero1Mdc); libera(numero2Mdc);
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 6: system("clear");
printf("#######################################\n");
printf(" FATORIAL \n");
printf("#######################################\n\n");
Lista* numeroFat = cria();
printf("Digite um número: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
numeroFat = lerNumero(numeroFat, ch1[i]);
}
numeroFat = removeZeroInicio(numeroFat);
printf("\nResultado = ");
imprime(fatorial(numeroFat));
printf("\n\n");
libera(numeroFat);
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 7: system("clear");
printf("#######################################\n");
printf(" EXPONENCIAÇÃO \n");
printf("#######################################\n\n");
Lista* base = cria();
Lista* expoente = cria();
printf("Digite a base: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
base = lerNumero(base, ch1[i]);
}
printf("Digite o expoente: ");
scanf("%s", ch2);
for(i=0; i<strlen(ch2); i++){
expoente = lerNumero(expoente, ch2[i]);
}
base = removeZeroInicio(base);
expoente = removeZeroInicio(expoente);
printf("\nResultado = ");
imprime(expo(base, expoente));
printf("\n\n");
libera(base); libera(expoente);
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 8: system("clear");
printf("#######################################\n");
printf(" MÓDULO \n");
printf("#######################################\n\n");
Lista *divisor = cria();
Lista *dividendo = cria();
printf("Digite o dividendo: ");
scanf("%s", ch1);
for(i=0; i<strlen(ch1); i++){
dividendo = lerNumero(dividendo, ch1[i]);
}
printf("Digite o divisor: ");
scanf("%s", ch2);
for(i=0; i<strlen(ch2); i++){
divisor = lerNumero(divisor, ch2[i]);
}
dividendo = removeZeroInicio(dividendo);
divisor = removeZeroInicio(divisor);
printf("\nResultado = ");
imprime(modulo(dividendo,divisor));
libera(divisor); libera(dividendo);
printf("\n\n");
printf("RETORNAR? 0-NÃO | 1-SIM: ");
scanf("%d", &op);
if(op==0){
free(ch1); free(ch2); exit(0);
}
menu();
case 0: free(ch1); free(ch2); exit(0);
default: menu();
}
}
Lista* lerNumero(Lista* l, char ch){
l = insereFinal(l, ch);
return l;
}
Lista* adicao(Lista* lA, Lista* lB){
No* auxLA = acessaFim(lA), *auxLB = acessaFim(lB);
Lista* result = cria();
int carry = 0;
if(lA == NULL){
return lB;
}
else
if(lB == NULL){
return lA;
}
while(auxLA!=NULL && auxLB!=NULL){
int digA = acessaDigito(auxLA) + carry;
int digB = acessaDigito(auxLB);
int soma = digA + digB;
if(soma >= 10){
result = insereInicio(result, converteChar(soma%10));
carry = 1;
}
else{
result = insereInicio(result, converteChar(soma));
carry = 0;
}
auxLA = acessaAnt(auxLA);
auxLB = acessaAnt(auxLB);
}
if(auxLA!=NULL && auxLB==NULL){
while(auxLA!=NULL){
int soma = acessaDigito(auxLA) + carry;
if(soma >= 10){
result = insereInicio(result, converteChar(soma%10));
carry = 1;
}
else{
result = insereInicio(result, converteChar(soma));
carry = 0;
}
auxLA = acessaAnt(auxLA);
}
}
if(auxLA==NULL && auxLB!=NULL){
while(auxLB!=NULL){
int soma = acessaDigito(auxLB) + carry;
if(soma >= 10){
result = insereInicio(result, converteChar(soma%10));
carry = 1;
}
else{
result = insereInicio(result, converteChar(soma));
carry = 0;
}
auxLB = acessaAnt(auxLB);
}
}
if(carry == 1){
result = insereInicio(result, converteChar(1));
}
return result;
}
int compara(Lista* lA, Lista* lB){
No* auxLA = acessaNo(lA);
No* auxLB = acessaNo(lB);
if(contaDigitos(lA) < contaDigitos(lB)){
return -1;
}
else
if(contaDigitos(lA) > contaDigitos(lB)){
return 1;
}
while(auxLA!=NULL && auxLB!=NULL){
if(acessaDigito(auxLA) < acessaDigito(auxLB)){
return -1;
}
if(acessaDigito(auxLA) > acessaDigito(auxLB)){
return 1;
}
auxLA = acessaProx(auxLA);
auxLB = acessaProx(auxLB);
}
}
Lista* quadrado(Lista* l){
return produto(l, l);
}
Lista* produto(Lista* lA, Lista* lB){
Lista* result1 = cria(), *result2 = cria();
No* auxLB = acessaFim(lB);
int y=0, i;
result1 = insereFinal(result1, '0');
result2 = insereFinal(result2, '0');
while(auxLB!=NULL){
for(i=0; i<acessaDigito(auxLB); i++){
result1 = adicao(result1, lA);
}
if(y>0){
for(i=0; i<y; i++){
result1 = insereFinal(result1, '0');
}
}
y++;
result2 = adicao(result1, result2);
result1 = cria();
result1 = insereFinal(result1, '0');
auxLB = acessaAnt(auxLB);
}
return result2;
}
Lista* mdc(Lista* lA, Lista* lB){
Lista* zero = cria();
zero = insereFinal(zero, '0');
if(compara(lA,lB) == 0){
return lB;
}
if(compara(zero,lB) == 0 || compara(zero,lA) == 0){
return NULL;
}
Lista* resto1;
Lista* resto2;
Lista* mdc = cria();
mdc = insereFinal(mdc, '0');
if(compara(lA,lB)==1){
mdc = adicao(lB, mdc);
resto1 = modulo(lA, mdc);
resto2 = modulo(lB, mdc);
while(compara(resto1, zero) != 0 || compara(resto2, zero) != 0){
mdc = subtrai(mdc);
resto1 = modulo(lA, mdc);
resto2 = modulo(lB, mdc);
}
return mdc;
}
else{
mdc = adicao(lA, mdc);
resto1 = modulo(lA, mdc);
resto2 = modulo(lB, mdc);
while(compara(resto1, zero) != 0 || compara(resto2, zero) != 0){
mdc = subtrai(mdc);
resto1 = modulo(lA, mdc);
resto2 = modulo(lB, mdc);
}
return mdc;
}
}
Lista* fatorial(Lista* l){
Lista* result = cria(), *zero = cria();
zero = insereFinal(zero, '0');
result = insereFinal(result, '0');
result = adicao(result, l);
if(compara(zero, l) == 0){
Lista * aux = cria();
aux = insereFinal(aux, '1');
return aux;
}
l = subtrai(l);
while(l != NULL){
if(compara(zero, l) == 0){
break;
}
else{
result = produto(result, l);
l = subtrai(l);
}
}
return result;
}
Lista* expo(Lista* lA, Lista* lB){
Lista *zero = cria(), *result = cria();
zero = insereFinal(zero, '0');
result = insereFinal(result, '1');
while(compara(zero, lB) != 0){
result = produto(result,lA);
lB = subtrai(lB);
}
return result;
}
Lista* modulo(Lista* lA, Lista* lB){
Lista* result = cria();
result = insereFinal(result, '0');
int x = 0, i;
if(compara(result,lB)==0){
return NULL;
}
while(compara(result, lA) != 0 && compara(result, lA) != 1){
result = adicao(result, lB);
x++;
}
if(compara(result,lA) == 0){
result = cria();
result = insereFinal(result,'0');
return result;
}
else{
result = cria();
result = insereFinal(result,'0');
for(i=1; i<x; i++){
result = adicao(result,lB);
}
x = 0;
while(compara(result, lA) != 0){
lA = subtrai(lA);
x++;
}
if(x > 9){
result = cria();
while(x>0){
result = insereInicio(result,converteChar(x%10));
x = x/10;
}
}
else{
result = cria();
result = insereFinal(result,converteChar(x));
}
return result;
}
}
Lista* subtrai(Lista* l){
No *aux = acessaFim(l);
Lista *novo = cria();
int x;
while(aux!=NULL){
if(acessaDigito(aux) == 0){
novo = insereInicio(novo, '9');
}
else{
x = acessaDigito(aux) -1;
novo = insereInicio(novo, converteChar(x));
break;
}
aux = acessaAnt(aux);
}
aux = acessaAnt(aux);
while(aux!= NULL){
x = acessaDigito(aux);
novo = insereInicio(novo, converteChar(x));
aux = acessaAnt(aux);
}
novo = removeZeroInicio(novo);
return novo;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<stdbool.h>
#include<err.h>
#include<errno.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<signal.h>
#define MAXLINE 1008
#define HEADER 8
char filename[20];
char *filedata;
static void sig_alrm(int);
int readfile(void);
void dg_cli(int, struct sockaddr*, socklen_t);
int ATOI(char*, int);
int main(int argc, char *argv[]){
if(argc != 4)
err(1, "[Usage] sender1 <server IP> <Server Port> <File name>\n");
int sockfd;
struct sockaddr_in server;
strcpy(filename, argv[3]);
if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
err(2, "[Error] Failed in creating socket\n");
bzero(&server, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, argv[1], &server.sin_addr);
dg_cli(sockfd, (struct sockaddr *)&server, sizeof(server));
return 0;
}
void dg_cli(int sockfd, struct sockaddr* server, socklen_t len){
int current_ack, n;
int usecond = 10000;
int filelen = readfile();
char sendline[MAXLINE];
char recvline[HEADER+1];
bool ok_to_send;
//Step 1, sending file name
current_ack = 0;
memset(sendline, 0, sizeof(sendline));
strcpy(sendline, "00000000");
strcat(sendline, filename);
signal(SIGALRM, sig_alrm);
siginterrupt(SIGALRM, 1);
ok_to_send = true;
while(1){
if(ok_to_send){
int temp = sendto(sockfd, sendline, strlen(sendline), 0, server, len);
printf("%d data sent\n", temp);
}
ualarm(usecond, 0);
if((n = recvfrom(sockfd, recvline, sizeof(recvline), 0, NULL, NULL)) < 0){
if(errno == EINTR){
printf("[Timeout] Resending filename datagram\n");
if(usecond < 500000)
usecond += 10000;
ok_to_send = true;
}
else
err(4, "[Error] Recvfrom has error\n");
}
else{
recvline[8] = '\n';
if(current_ack == atoi(recvline)){
ualarm(0, 0);
printf("[Success] Filename Ack received\n");
if(usecond >= 20000)
usecond -= 10000;
current_ack++;
break;
}
else
ok_to_send = false;
}
}
//step 2, sending file data
bool end = false;
int i = 0;
int current_read;
while(!end){
memset(sendline, 0, sizeof(sendline));
memset(recvline, 0, sizeof(recvline));
char num[HEADER];
memset(num, 0, sizeof(num));
sprintf(num, "%d", current_ack);
strcpy(sendline, num);
current_read = i;
for(; i < filelen; i++){
if((i-current_read) >= (MAXLINE-HEADER))
break;
sendline[i-current_read+HEADER] = filedata[i];
}
if(i == filelen)
end = true;
ok_to_send = true;
while(1){
sendto(sockfd, sendline, (i-current_read+HEADER), 0, server, len);
memset(recvline, 0, sizeof(recvline));
ualarm(usecond, 0);
if((n = recvfrom(sockfd, recvline, sizeof(recvline), 0, NULL, NULL)) < 0){
if(errno == EINTR){
printf("[Timeout] Resending Packet %d\n", current_ack);
if(usecond < 500000)
usecond += 10000;
ok_to_send = true;
}
else
err(4, "[Error] Recvfrom has error\n");
}
else{
recvline[8] = '\n';
if(current_ack == atoi(recvline)){
ualarm(0, 0);
printf("[Success] Packet %d ack received\n", current_ack);
if(usecond >= 20000)
usecond -= 10000;
break;
current_ack++;
}
else
ok_to_send = false;
}
}
current_ack++;
}
//step 3, sending end packet
current_ack = 99999999;
strcpy(sendline, "99999999");
ok_to_send = true;
while(1){
sendto(sockfd, sendline, strlen(sendline), 0, server, len);
memset(recvline, 0, sizeof(recvline));
ualarm(usecond, 0);
if((n = recvfrom(sockfd, recvline, sizeof(recvline), 0, NULL, NULL)) < 0){
if(errno == EINTR){
printf("[Timeout] Resending end packet\n");
if(usecond < 500000)
usecond += 10000;
ok_to_send = true;
}
else
err(4, "[Error] Recvfrom has error\n");
}
else{
recvline[8] = '\n';
if(current_ack == atoi(recvline)){
ualarm(0, 0);
printf("[Success] End packet ack received\n");
if(usecond >= 20000)
usecond -= 10000;
break;
}
else
ok_to_send = false;
}
}
printf("[Complete] All data has sent\n");
return;
}
int readfile(void){
FILE *ifile;
if((ifile = fopen(filename, "r")) == NULL)
err(3, "[Error] Failed in opening the file\n");
int n;
fseek(ifile, 0, SEEK_END);
n = ftell(ifile);
fseek(ifile, 0, SEEK_SET);
filedata = malloc(n * sizeof(char));
fread(filedata, n, 1, ifile);
return n;
}
static void sig_alrm(int signo){
return;
}
|
C
|
/* elem.c */
/* Returns TRUE if the first argument is a */
/* member of the array (the second argument). */
/* Otherwise, returns FALSE. */
/* This code is released to the public domain. */
/* "Share and enjoy...." ;) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
/* Define the length of the array */
#define LEN 5
/* Function to find if a value is a member */
/* of an array. */
/* Returns 1 if it is, and 0 if it is not. */
int elem(int val, int myarray[LEN])
{
int i;
int retval=0;
for(i=0; i<LEN; i++)
{
if (myarray[i] == val) {
retval += 1; break; }
}
return retval;
}
/* The function to show if an element is NOT in the array. */
/* Returns 1 if it is NOT, and 0 if it IS. */
int notelem(int val, int myarray[LEN])
{
return !elem(val, myarray);
}
int main(void)
{
/* Declare arrays and fill them with data. */
int myarray[LEN] = {2, 3, 5, 7, 11} ;
int myarray2[LEN] = {4, 6, 8, 10, 12};
/* Test to see if an element is in the array. */
printf("Result is %d \n", elem(5, myarray) );
/* Test to see if an element is in the array. */
printf("Result is %d \n", elem(5, myarray2) );
/* Test to see if an element is NOT in the array. */
printf("Result is %d \n", notelem(5, myarray) );
/* Test to see if an element is NOT in the array. */
printf("Result is %d \n", notelem(5, myarray2) );
return 0 ;
}
|
C
|
#include <stdio.h>
#include <string.h>
#define SIZE 64
void reverse_name(char *name);
int main(void)
{
char name[SIZE + 1];
printf("Enter First Name and Last Name: ");
fgets(name, sizeof(name), stdin);
reverse_name(name);
puts(name);
return 0;
}
void reverse_name(char *name)
{
/* char first[SIZE / 2], last[SIZE / 2]; */
/* sscanf(name, " %s %s", first, last); */
/* sprintf(name, "%s, %c.", last, first[0]); */
char first, *p = name;
int len;
while (*p && *p == ' ') p++; /* find first non-space character */
first = *p;
while (*p && *p != ' ') p++; /* find word boundary: first space after first p */
while (*p && *p == ' ') p++; /* find start of last */
for (len = 0; p[len] != '\n' && p[len] && p[len] != ' '; len++);
sprintf(name, "%.*s, %c.", len, p, first);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Mapping.h"
#include "Debug.h"
#include "Comm.h"
// FIXME: find a better place for this
Mapping* Mapping_create(int dim, int levels, int order, const Tuple *flat_size, const Tuple* tiling, const Dist *dist, size_t scalar_size)
{
return Mapping_create_impl(-1, 0, dim, levels, order, flat_size, tiling, dist, scalar_size, NULL);
}
Mapping* Mapping_create_with_pid(int pid, int dim, int levels, int order, const Tuple *flat_size, const Tuple* tiling, const Dist *dist, size_t scalar_size)
{
return Mapping_create_impl(pid, 0, dim, levels, order, flat_size, tiling, dist, scalar_size, NULL);
}
Mapping* Mapping_create_with_ptr(int dim, int levels, int order, const Tuple *flat_size, const Tuple* tiling, const Dist *dist, size_t scalar_size, void* prealloc)
{
return Mapping_create_impl(-1, 0, dim, levels, order, flat_size, tiling, dist, scalar_size, NULL);
}
// When prealloc != NULL, the memory space is preallocated and this function will only calculate
// the pointer to the first element for each tile
Mapping* Mapping_create_impl(int pid, int owner_only, int dim, int levels, int order, const Tuple *flat_size, const Tuple* tiling, const Dist *dist, size_t scalar_size, void* prealloc)
{
int i = 0;
int num_tiles;
//int mem_space_used = 0;
ASSERT(scalar_size > 0);
// get number of leaf tiles
if(tiling)
num_tiles = Tuple_count_elements(tiling, tiling->height);
else
num_tiles = 1;
DBG(5, "Mapping_create(): allocate memory space for %d tiles\n", num_tiles);
// allocate space for metadata
Mapping *m = (Mapping*) Alloc_acquire_block(sizeof(Mapping));
if(!owner_only)
m->map_blocks = (void**) Alloc_acquire_block(num_tiles*sizeof(void*));
else
m->map_blocks = NULL;
m->owners = (int*) Alloc_acquire_block(num_tiles*sizeof(int));
DBG(5, "Mapping_create(): create an integer pointer array for blocks\n");
m->order = order;
m->dist = *dist;
m->num_blocks = num_tiles;
m->scalar_size = scalar_size;
DBG(5, "Mapping_create(): allocate blocks for leaf tile\n");
#if 0
if(num_tiles > 1)
#endif
{
// Allocate data blocks
Tuple iter[levels-1]; // the number of tuples in tiling array is (levels-1) tuples
Tuple_iterator_begin(dim, levels-1, iter);
Tuple tile_size;
Tuple_init_zero(&tile_size, dim); // Create a temporary tuple for computations
if(order == ORDER_TILE) {
ASSERT(prealloc == NULL);
for(i=0;i<num_tiles;i++)
{
int owner = (pid == -1) ? (-1):(Dist_get_pid(dist, iter, tiling));
if(!owner_only) {
Tuple_get_leaf_tile_size(flat_size, tiling, iter, &tile_size);
size_t block_size = scalar_size * Tuple_product(&tile_size);
DBG(5, "Mapping_create(): allocate %zd bytes for leaf tile %d\n", block_size, i);
if((pid == -1) || (owner == pid)) // owner of the tile // Dist_get_pid applied to the first level tiling for distribution
m->map_blocks[i] = Alloc_acquire_block(block_size);
else
m->map_blocks[i] = NULL;
}
m->owners[i] = owner;
if(num_tiles >1) Tuple_iterator_next(tiling, iter);
}
} else { // ROW- or COL-major layout
void* ptr;
ASSERT(!owner_only);
if(prealloc == NULL) {
// 1. only one thread allocates a big block
int num_elems = Tuple_product(flat_size);
size_t total_size = scalar_size * num_elems; // NOTICE: for dense HTA only
if(pid == 0 || pid == -1)
ptr = Alloc_acquire_block(total_size);
// 2. broadcast the pointer to the block allocated to all threads
if(pid != -1) // communicate to fetch base pointer to the block for SPMD mode
comm_bcast(pid, 0, &ptr, sizeof(void*));
} else {
ptr = prealloc;
}
// 3. evaluate and set pointers for leaf tiles
Tuple nd_offset;
nd_offset.height = 1;
// iterate through the leaf tiles and get their logical index
for(i=0;i<num_tiles;i++) {
int owner = (pid == -1) ? (-1):(Dist_get_pid(dist, iter, tiling));
Tuple_get_tile_start_offset(flat_size, tiling, iter, &nd_offset);
// use the logical index to evaluate the location of the first element in the physical memory
int offset = Tuple_nd_to_1d_index_by_order(order, &nd_offset, flat_size);
m->map_blocks[i] = ptr + scalar_size * offset;
m->owners[i] = owner;
if(num_tiles > 1) Tuple_iterator_next(tiling, iter);
}
}
}
//DBG(5, "Mapping_create(): total memory space allocated = %d\n", mem_space_used);
return m;
}
void Mapping_destroy(Mapping *m)
{
if(m->map_blocks)
Alloc_free_block(m->map_blocks);
Alloc_free_block(m->owners);
Alloc_free_block(m);
}
void Mapping_print(Mapping *m)
{
printf("Mapping structure:\n");
printf("order: %d\n", m->order);
Dist_print(&m->dist);
printf("scalar_size: %zd\n", m->scalar_size);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
void first_cmd(int argc, char **argv);
//function for handle command-line arguments
void first_cmd(int argc, char **argv){
pid_t k;
int status;
char* buf[100];
int count = 0;
memset(buf, '\0', sizeof(char*) * 100);
//check if there is a command-line argument
if(argc == 2){
//split the commands into tokens with whitespace
char *pch;
pch = strtok(argv[1]," ");
while (pch != NULL)
{
buf[count] = pch;
pch = strtok(NULL," ");
count++;
}
//execute
k = fork();
if (k==0) {
if(execvp(buf[0],buf) == -1)exit(1);
}
else {
waitpid(k, &status, 0);
}
}
}
int main(int argc, char **argv)
{
pid_t k;
char buf[100];
int status;
int len;
//deal with command-line arguments
first_cmd(argc, argv);
//below is the same as simsh.c
while(1) {
// print prompt
fprintf(stdout,"[%d]$ ",getpid());
// read command from stdin
fgets(buf, 100, stdin);
len = strlen(buf);
if(len == 1) // only return key pressed
continue;
buf[len-1] = '\0';
k = fork();
if (k==0) {
// child code
if(execlp(buf,buf,NULL) == -1) // if execution failed, terminate child
exit(1);
}
else {
// parent code
waitpid(k, &status, 0);
}
}
}
|
C
|
//program to do all experimental actions on c (basic actions)
// Author:Ajay Shinde Date : 11/01/2019
#include<stdio.h>
int main(){
// int a = b = 3 =4;
//
// int a,b;
// a = b = 4= 4;
printf("%d",12345/10);
return 0;
}
|
C
|
#include<stdio.h>
void bonjour(char * name)
{
printf("Boujour %s\n",name);
}
|
C
|
/* testfork1.c
* Simple program to test the fork system call.
*/
#include "syscall.h"
void test1(){
Write("test1\n", 6, ConsoleOutput);
Exit(0);
}
void test2(){
Write("test2\n", 6, ConsoleOutput);
Exit(0);
}
int main() {
Fork(test1);
Fork(test2);
}
|
C
|
#include "struct.h"
/* Get file size */
uint64_t fgetsize(int fd) {
struct stat info;
if (fstat(fd, &info) != 0) {
perror("fstat() error\n");
exit(1);
}
return info.st_size;
}
/* Get file width for mal_site1, mal_site2 */
int getwidth(const char *buf) {
int i = 0;
while (buf[i++] != '\1');
return i;
}
/* strcmp for bsearch */
int _strcmp(const void *a, const void *b) {
return strcmp(a, b);
}
/* Get get, host */
#define NETFILTER_IP_INDEX 44
bool gethost(char *data, struct http *http) {
uint8_t *p;
struct ip *ip;
struct tcp *tcp;
/* ip */
ip = (struct ip *)((uint8_t *)data + NETFILTER_IP_INDEX);
if (ip->ver != IPV4_VERSION) return false;
if (ip->pro != PROTOCOL_TCP) return false;
if (ntohs(ip->len_t) <= 40) return false;
/* tcp */
tcp = (struct tcp *)((uint8_t *)ip + ip->len_h * 4);
/* http: get */
p = (uint8_t *)tcp + tcp->off * 4;
if (*(uint32_t *)p != STRING_GET) return false;
while (*p++ != '\r');
if (*p++ != '\n') return false;
/* http: host */
http->host = p += 6;
while (*p != '\r') p++;
*p = '\0';
return true;
}
|
C
|
#include "sort.h"
/**
* selection_sort - sorting by selection
* @array: array
* @size: size
*/
void selection_sort(int *array, size_t size)
{
size_t i = 0, j, pivote;
int aux;
if (array && size > 1)
{
while (i < size - 1)
{
pivote = i;
j = i + 1;
while (j < size)
{
if (array[pivote] > array[j])
{
pivote = j;
}
j++;
}
if (i != pivote)
{
aux = array[i];
array[i] = array[pivote];
array[pivote] = aux;
print_array(array, size);
}
i++;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* fp;
fp = fopen("./output/rkdsp.bin", "rb");
if(fp){
fseek(fp, 0, SEEK_END);
int len = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char* buf = (unsigned char*) malloc(len);
if (fread(buf, len, 1, fp) == 1){//ok
FILE* fw;
fw = fopen("./output/rkdsp_fw.h", "w");
if (!fw){
printf("error @ open file ./output/rkdsp_fw.h\n");
}
else{
fprintf(fw, "static const uint8_t dsp_fw[] = {");
for(int i = 0; i < len; i++){
if(!(i&7)){
fprintf(fw, "\n");
}
fprintf(fw, " 0x%02x,", buf[i]);
}
fprintf(fw, "\n};\n");
fclose(fw);
}
}
else{
printf("error @ read file %s\n", "./output/rkdsp.bin");
}
fclose(fp);
}
return 0;
}
|
C
|
#ifndef DEBUG_H
#include "debug.h"
#endif
char errore[24];
void error(char message[], int err)
{
sprintf(errore, "[ERROR : %s]:%s,message:%s\n",processSign, strerror(err), message);
printf("%s",errore);
cleaner();
perror(errore);
exit(err);
}
int debug(const char *__restrict__ message, ...)
{
char formatted[128];
va_list args;
if (isDebug)
{
va_start(args, message);
vsnprintf(formatted, sizeof(formatted), message, args);
printf("[Debug %s]: %s\n", processSign, formatted);
va_end(args);
bzero(formatted, sizeof(formatted));
fflush(stdout);
return 1;
}
else
{
return 0;
}
}
void logg(const char *__restrict__ message, ...)
{
float actime;
char logformatted[128];
va_list args;
actime = (double)clock() / 1000;
va_start(args, message);
vsnprintf(logformatted, sizeof(logformatted), message, args);
if (verbosity > 0)
{
printf("[LOG : %s -> %f]%s\n", processSign, (float)actime, logformatted);
}
va_end(args);
bzero(logformatted, sizeof(logformatted));
fflush(stdout);
}
|
C
|
#include "include.h"
#include "img_control.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "timer.h"
#include "beep.h"
/**********************************************************************************
* ƣvoid show_photo()
* ˵ͼ
* ˵f==1 ӥͷĶֵʽf==0Ҷģʽ
* أ
* ʱ䣺2014-6-17 wuwenqi
* ע
**********************************************************************************/
void show_photo(int f)
{
uart_putchar(UART0,0x01); //ͼͷ
uart_putchar(UART0,0xFE); //ͼͷ
int i,j;
if(f==1){//ֵģʽ
for(i=0;i<ROW*COLUMN/8;i++){
uart_putchar(UART0,Picbuff[i]);
}
}
else{//Ҷģʽ
for(i=0;i<ROW;i++){
for(j=0;j<COLUMN;j++){
uart_putchar(UART0,img[i][j]);
}
}
}
uart_putchar(UART0,0xFE); //ͼͷ
uart_putchar(UART0,0x01); //ͼͷ
}
/**********************************************************************************
* ƣvoid image_process()
* ˵ͼ
* ˵
* أ
* ʱ䣺2014-6-17 wuwenqi
* ע
**********************************************************************************/
void copyImgBuffer(){
u8 i,j;
for(i=0;i<ROW;i++){
for(j=0;j<COLUMN;j++){
img[i][j]=img_origin[i][j];
}
}
};
void image_process()
{
//buffer(img_origin)еͼcopyimgҪ
copyImgBuffer();
//TODO
//дԼĴ㷨,Ŀǻst_ekҲǶƫι
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
/*3) Escribe un programa en el que se cargue una matriz de 15 filas con números enteros
aleatorios entre 100 y 999. Cada fila se cargará en FORMA DINAMICA. La cantidad de
columnas estará dada por un número aleatorio entre [5, 15]. Mostrar por pantalla la
matriz
a) Luego determinar para cada fila cuántos números son pares.
b) Por último, generar un nuevo vector dinámico de 15 elementos con la cantidad
de pares por fila obtenidos en el punto anterior.
c) Subir los cambios al repositorio remoto.*/
const int fila = 15;
const int DIM2 = 5;
void funcion_par (int *matriz, int columna, int *vector)
{
int *aux = matriz, contador = 0, i=0, j=0;
for (i =0; i <fila ; i++)
{
for (j=0; j < columna; j++)
{
if ((int) *(matriz + i *columna + j) %2 == 0)
{
contador++;
}
}
*(vector +i) = contador;
printf("la cantidad de numeros pares en la fila %d son: %d \n", i+1, *(vector +i));
contador =0;
}
}
int main ()
{
int i, j, columna, pares;
srand(time(NULL));
columna = rand()% (15 -5 +1) + 5;
int *PunteroMatriz = (int *) malloc (sizeof (int) * fila * columna);
int *PunteroVector = (int *) malloc (sizeof (int) * 15);
printf("cantidad de columanas: %d \n", columna);
printf("cantidad de fila %d\n", fila);
for (i =0; i < fila ; i++)
{
for (j = 0; j < columna ; j++)
{
*(PunteroMatriz + i *columna + j) = 100 + rand () % (999+1-100);
printf(" %d ", *(PunteroMatriz + i * columna + j));
}
printf("\n");
}
funcion_par(PunteroMatriz, columna, PunteroVector);
getchar ();
return 0;
}
|
C
|
/****************************************************************************************
* NAME: SOUMITRI CHATTOPADHYAY
* ROLL: 001911001083
* SUBJECT: COMPUTER NETWORKS LABORATORY (UG-2, SEM-2)
* ASSIGNMENT: CO-3 Assignment 3(a) - Go-Back-N Acknowledgement Protocol - Sender
****************************************************************************************/
/****************************************************************************************
* COMPILATION: gcc gobackn_acksender.c -o ack_sender
* EXECUTION: ./ack_sender
***************************************************************************************/
/* header files */
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#define PORT 9999
#define MAX 1024
#define MAX_SEQ 3
typedef unsigned int seq_nr;
typedef struct
{
char data[MAX];
} packet;
typedef enum
{
data,
ack,
nak
} frame_kind;
typedef struct
{
frame_kind kind;
seq_nr seq;
seq_nr ack;
packet info;
} frame;
typedef enum
{
false,
true
} bool;
typedef enum
{
frame_arrival,
time_out
} event_type;
typedef struct
{
event_type type;
} event;
char buff[4096];
static int i = 1;
void inc(seq_nr *val)
{
seq_nr x = *val;
*val = (x + 1) % (1 + MAX_SEQ);
}
bool between(seq_nr a, seq_nr b, seq_nr c)
{
if (((a <= b) && b < c) || ((c < a) && (a <= b)) || ((b < c) && (c < a)))
return true;
else
return false;
}
void waitForEvent(int sockfd, event_type *event)
{
memset(buff, 0, sizeof(buff));
read(sockfd, buff, 4096);
if (strlen(buff) == 0)
{
*event = time_out;
}
else
*event = frame_arrival;
}
void getData(packet *p)
{
char num[50];
strcpy(num, "This is packet #");
sprintf(num + 16, "%d", i);
strcpy(p->data, num);
i++;
}
void makeFrame(seq_nr frame_nr, seq_nr frame_expected, packet buffer[], frame *f)
{
f->info = buffer[frame_nr];
f->seq = frame_nr;
f->ack = (frame_expected + MAX_SEQ) % (MAX_SEQ + 1);
//f->kind = ack;
}
void sendFrame(int sockfd, frame *f)
{
memset(buff, 0, sizeof(buff));
frame *fr = (frame *)buff;
fr->kind = f->kind;
fr->seq = f->seq;
fr->ack = f->ack;
fr->info = f->info;
printf("Sending frame...\n");
printf("%s\n", fr->info.data);
write(sockfd, buff, sizeof(buff));
}
void receiveFrame(frame *f)
{
printf("Received acknowledgement...\n");
frame *fr = (frame *)buff;
f->ack = fr->ack;
f->info = fr->info;
f->kind = fr->kind;
f->seq = fr->seq;
}
int randn()
{
srand(time(0));
return rand() % 10 + 1;
}
void extractData(frame *f, packet *p)
{
*p = f->info;
}
void deliverData(packet *p)
{
printf("Received data : %s\n", p->data);
}
void sender(int sockfd)
{
seq_nr next_frame_to_send = 0;
seq_nr ack_expected = 0;
frame r, s;
packet buffer[MAX_SEQ + 1];
seq_nr nbuffered = 0;
seq_nr itr;
event_type event;
int pos = -1, count = 0;
// getData(&buffer[0]);
// getData(&buffer[1]);
// getData(&buffer[2]);
// getData(&buffer[3]);
while (count < 9)
{
if (nbuffered < MAX_SEQ)
{
getData(&buffer[next_frame_to_send]);
nbuffered++;
}
int x = randn();
if (x <= 3)
{
memset(buff, 0, sizeof(buff));
write(sockfd, buff, sizeof(buff));
}
else
{
makeFrame(next_frame_to_send, 0, buffer, &s);
sendFrame(sockfd, &s);
}
inc(&next_frame_to_send);
waitForEvent(sockfd, &event);
if (event == frame_arrival)
{
receiveFrame(&r);
while (between(ack_expected, r.ack, next_frame_to_send))
{
nbuffered--;
//pos = inc(pos);
inc(&ack_expected);
count++;
//printf("#######%d#####\n",ack_expected);
}
}
else
{
sleep(3);
printf("Timed out!! Resending...\n");
next_frame_to_send = ack_expected;
for (itr = 1; itr <= nbuffered; itr++)
{
makeFrame(next_frame_to_send, 0, buffer, &s);
sendFrame(sockfd, &s);
inc(&next_frame_to_send);
}
}
}
}
int main()
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
sender(sock);
close(sock);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <libssh/libssh.h>
#include <libssh/priv.h>
#include <errno.h>
#define AUTHOR "Jonathan Sarba<jsarba@petrobrasenergia.com>"
#define PROGRAM "fssh"
#define VERSION "v0.2"
#define MAX_COM 2048
#define MAX_PASS 16
#define _PATH_TTY "/dev/tty"
extern char *optarg;
extern int optind, optopt;
void usage(char *prgname)
{
printf("%s %s (c) 2005 by %s\n\nUsage: %s [options] [hostname] [filename]\n",
PROGRAM, VERSION, AUTHOR, prgname);
printf("Options:\n"
" -l user : log in as user\n"
" -p port : connect to port\n");
exit(-1);
}
int echoing(void)
{
int infd;
static int atom = 0;
static struct termios oterm, nterm;
if ( (infd = open(_PATH_TTY, O_RDWR)) == -1 )
infd = (int )stdin;
if ( atom == 1 )
{
(void )tcsetattr(infd, TCSAFLUSH, &oterm);
return atom = 0;
}
if ( tcgetattr(infd, &oterm) == -1 )
return atom;
nterm = oterm;
nterm.c_lflag &= ~(ECHO|ICANON);
if ( tcsetattr(infd, TCSAFLUSH, &nterm) == -1 )
return atom;
return atom = 1;
}
int GetPass(char *pass)
{
unsigned int p;
int y;
while(1)
{
y=0;
memset(pass, 0x0, MAX_PASS);
(void )echoing();
while ( (p = getc(stdin)) )
{
if (p == 0xa || p == 0xd) break;
if (y < MAX_PASS && p != EOF) memcpy(pass+y, (char *)&p, 1);
y++;
}
(void )echoing();
if ( strlen(pass) > 0 && strlen(pass) < MAX_PASS )
return 1;
else
return 0;
}
}
char *GetLastArg(int argc, char **argv)
{
static int index = 0;
int opt;
while ( (opt=getopt(argc, argv, "")) != -1 )
{
switch(opt)
{
default:
usage(argv[0]);
}
}
if ( optind < argc )
return argv[(optind++)+(index++)];
else
return NULL;
}
int handshake(SSH_SESSION *session)
{
int state;
char hash[MD5_DIGEST_LEN];
state = ssh_is_server_known(session);
switch(state)
{
case SSH_SERVER_KNOWN_OK:
break;
case SSH_SERVER_KNOWN_CHANGED:
printf("[!] Host key for server changed: server's one is now:\n");
(void )ssh_get_pubkey_hash(session, hash);
(void )ssh_print_hexa("Public key hash", hash, MD5_DIGEST_LEN);
return 0;
case SSH_SERVER_FOUND_OTHER:
printf("[!] The host key for this server was not found but an other type of key exists.\n"
" An attacker might change the default server key to confuse your client\n"
" into thinking the key does not exist\n");
return 0;
case SSH_SERVER_NOT_KNOWN:
printf("[!] The server is unknown. We'll trust this key\n");
(void )ssh_get_pubkey_hash(session, hash);
(void )ssh_print_hexa("Public key hash", hash, MD5_DIGEST_LEN);
printf("[!] This new key will be written on disk for further usage.\n");
if ( ssh_write_knownhost(session) < 0 )
return 0;
break;
case SSH_SERVER_ERROR:
return 0;
}
return 1;
}
int authentication(SSH_SESSION *session)
{
SSH_OPTIONS *opt = session->options;
char *password;
char *issue;
int auth = 0;
// try private/public keys first
auth = ssh_userauth_autopubkey(session);
/* no quiero el banner
if ( (issue = ssh_get_issue_banner(session)) )
printf("%s", issue);
*/
switch(auth)
{
case SSH_AUTH_DENIED:
// printf("Error: no key matched\n");
case SSH_AUTH_ERROR:
case SSH_AUTH_PARTIAL:
// printf("Error: some key matched but you still have to give an other mean of authentication\n");
if ( (password = (char *)calloc(MAX_PASS+1, sizeof(char))) == NULL)
return 0;
printf("%s@%s's password: ", opt->username, opt->host);
if ( !GetPass(password) )
printf("\n[!] Dont use authentication without strong password\n");
if ( ssh_userauth_password(session, NULL, password) != SSH_AUTH_SUCCESS )
{
memset(password, 0x0, MAX_PASS);
free(password);
printf("\n[!] %s\n", ssh_get_error(session));
return 0;
}
memset(password, 0x0, MAX_PASS);
free(password);
case SSH_AUTH_SUCCESS:
printf("\n[*] Authentication success [%s on %s]\n", opt->username, opt->host);
break;
}
return 1;
}
int Send_Command(SSH_SESSION *session, char *cmd)
{
CHANNEL *channel = NULL;
BUFFER *buf = buffer_new();
struct timeval timeout;
char ptr[10];
fd_set fds;
int p, ret;
if ( (channel = channel_open_session(session)) == NULL )
return 0;
if ( channel_request_pty(channel) != 0 )
return 0;
if ( channel_request_exec(channel, cmd) != 0 )
return 0;
while(channel)
{
CHANNEL *chans[] = { channel, NULL } ;
CHANNEL *ochans[2];
(void )echoing();
do
{
FD_ZERO(&fds);
FD_SET(0, &fds);
timeout.tv_sec = 2;
timeout.tv_usec = 0;
ret = ssh_select(chans, ochans, 0+1, &fds, &timeout);
} while ( ret == SSH_EINTR );
if ( FD_ISSET(0, &fds) )
{
p = read(0, ptr, 10);
if ( p ) channel_write(channel, ptr, p);
}
(void )echoing();
if ( ochans[0] )
{
while ( channel_poll(ochans[0], 0) )
{
p = channel_read(ochans[0], buf, 0, 0);
if ( p ) write(1, buffer_get(buf), p);
}
while ( channel_poll(ochans[0], 1) )
{
p = channel_read(ochans[0], buf, 0, 1);
if ( p ) write(2, buffer_get(buf), p);
}
}
if ( !channel_is_open(channel) )
{
channel_free(channel);
channel = NULL;
}
}
buffer_free(buf);
return 1;
}
int main(int argc, char **argv)
{
FILE *fd;
SSH_OPTIONS *options;
SSH_SESSION *sessions;
const char *hostname;
const char *filename;
char cmd[MAX_COM];
options = ssh_getopt(&argc, argv);
if ( !options )
{
printf("[!] %s\n", ssh_get_error(NULL));
usage(argv[0]);
}
if ( (hostname = GetLastArg(argc, argv)) == NULL )
usage(argv[0]);
if ( (filename = GetLastArg(argc, argv)) == NULL )
usage(argv[0]);
if ( (fd = fopen(filename, "r")) == NULL )
{
perror("[!]");
return -1;
}
options_set_host(options, hostname);
if ( (sessions = ssh_connect(options)) == NULL )
{
printf("[!] %s\n", ssh_get_error(NULL));
return (fd) ? fclose(fd) : 0 ;
}
if ( !handshake(sessions) )
{
printf("[!] %s\n", ssh_get_error(NULL));
(void )ssh_disconnect(sessions);
if ( fd ) fclose(fd);
exit(-1);
}
if ( !authentication(sessions) )
{
(void )ssh_disconnect(sessions);
if ( fd ) fclose(fd);
exit(-1);
}
while ( fgets(cmd, MAX_COM-1, fd ) )
{
cmd[strlen(cmd)-1] = '\0';
if ( strlen(cmd) < 2 || strncmp(cmd, "#", 1) == 0 ) continue;
if ( strncmp(cmd, "<", 1) == 0 )
{
printf("%s\n", cmd);
continue;
}
if ( !Send_Command(sessions, cmd) )
printf("[!] %s\n", ssh_get_error(NULL));
}
printf("[*] Disconnected\n");
(void )ssh_disconnect(sessions);
if ( fd ) fclose(fd);
exit(0);
}
|
C
|
/** AST handling for expression nodes: Literals, Variables, etc.
* @file
*
* This source file is part of the Cone Programming Language C compiler
* See Copyright Notice in conec.h
*/
#include "../ast/ast.h"
#include "../shared/memory.h"
#include "../parser/lexer.h"
#include "../ast/nametbl.h"
// Create a new function signature node
FnSigAstNode *newFnSigNode() {
FnSigAstNode *sig;
newAstNode(sig, FnSigAstNode, FnSig);
sig->methods = newNodes(1); // probably share these across all fnsigs
sig->subtypes = newNodes(1); // ditto
sig->parms = newInodes(8);
sig->rettype = voidType;
sig->vtype = NULL;
return sig;
}
// Serialize the AST for a function signature
void fnSigPrint(FnSigAstNode *sig) {
SymNode *nodesp;
uint32_t cnt;
astFprint("fn(");
for (inodesFor(sig->parms, cnt, nodesp)) {
astPrintNode((AstNode*)nodesp->node);
if (cnt > 1)
astFprint(", ");
}
astFprint(") ");
astPrintNode(sig->rettype);
}
// Traverse the function signature tree
void fnSigPass(PassState *pstate, FnSigAstNode *sig) {
SymNode *nodesp;
uint32_t cnt;
for (inodesFor(sig->parms, cnt, nodesp))
astPass(pstate, (AstNode*)nodesp->node);
astPass(pstate, sig->rettype);
}
// Compare two function signatures to see if they are equivalent
int fnSigEqual(FnSigAstNode *node1, FnSigAstNode *node2) {
SymNode *nodes1p, *nodes2p;
int16_t cnt;
// Return types and number of parameters must match
if (!typeIsSame(node1->rettype, node2->rettype)
|| node1->parms->used != node2->parms->used)
return 0;
// Every parameter's type must also match
nodes2p = &inodesGet(node2->parms, 0);
for (inodesFor(node1->parms, cnt, nodes1p)) {
if (!typeIsSame((AstNode*)nodes1p->node, (AstNode*)nodes2p->node))
return 0;
nodes2p++;
}
return 1;
}
// Will the function call (caller) be able to call the 'to' function
// Return 0 if not. 1 if perfect match. 2+ for imperfect matches
int fnSigMatchesCall(FnSigAstNode *to, FnCallAstNode *caller) {
int matchsum = 1;
// Too many arguments is not a match
if (caller->parms->used > to->parms->used)
return 0;
// Every parameter's type must also match
SymNode *tonodesp;
AstNode **callnodesp;
int16_t cnt;
tonodesp = &inodesGet(to->parms, 0);
for (nodesFor(caller->parms, cnt, callnodesp)) {
int match;
switch (match = typeMatches(((TypedAstNode *)tonodesp->node)->vtype, ((TypedAstNode*)*callnodesp)->vtype)) {
case 0: return 0;
case 1: break;
default: matchsum += match;
}
tonodesp++;
}
// Match fails if not enough arguments & method has no default values on parms
if (caller->parms->used != to->parms->used
&& ((NameDclAstNode *)tonodesp)->value==NULL)
return 0;
// It is a match; return how perfect a match it is
return matchsum;
}
|
C
|
#include <math.h>
#include "myLib.h"
#include "sprites.h"
typedef struct {
const u16* image;
u8 x;
u8 y;
u8 alive;
} BRICK;
typedef struct {
double x;
double y;
double speed;
s16 direction;
double dx;
double dy;
u8 alive;
} BALL;
typedef struct {
s16 x;
s16 y;
s16 speed;
u8 lives;
} PLAYER;
// globals
u16 *videoBuffer = (u16*)0x6000000;
BRICK brickgrid[BRICKGRID_SIZE];
BALL ball;
PLAYER player;
// ====================================================================
int main()
{
REG_DISPCNT = MODE3 | BG2_ENABLE;
// game starts at the splash screen
splash_screen();
while(TRUE) {
while (KEY_DOWN_NOW(BUTTON_SELECT));
// wait for SCANLINECOUNTER to be at vsync to avoid tearing
wait_for_vsync();
// restart after losing life
if (ball.alive == FALSE && ball.y > 180) {
// clear the previous player and ball sprites
draw_background(ball.x, ball.y, background_green, BALL1_WIDTH, BALL1_HEIGHT);
draw_background(player.x, player.y, background_green, PLAYER1_WIDTH, PLAYER1_HEIGHT);
--player.lives;
if (player.lives > 0)
new_life();
else
game_over_screen();
}
// first thing to do in a new frame is to redraw the background at
// the previous frame's positions of the player and ball
draw_background(ball.x, ball.y, background_green, BALL1_WIDTH, BALL1_HEIGHT);
draw_background(player.x, player.y, background_green, PLAYER1_WIDTH, PLAYER1_HEIGHT);
// check position of the ball of ball relative to the bricks
s8 row_ball_top = BRICK_ROW(ball.y);
s8 row_ball_bot = BRICK_ROW(ball.y + BALL1_HEIGHT);
// =========== check collisions b/w ball and bricks ===========
if (ball.y >= 20 - BALL1_HEIGHT && row_ball_top <= 5) {
s8 col_ball_left = BRICK_COL(ball.x);
s8 col_ball_right = BRICK_COL(ball.x + BALL1_WIDTH);
// limit col-ball_right to 8 to prevent killing brick on the next row
if (col_ball_right > 8)
col_ball_right = 8;
s8 killed_a_brick = FALSE;
// if the ball hits the side of a brick
if (kill_brick(row_ball_top*9 + col_ball_left)
|| kill_brick(row_ball_bot*9 + col_ball_left)) {
killed_a_brick = TRUE;
// if the ball hits the bottom/top of a brick
}
if (kill_brick(row_ball_top*9 + col_ball_right)
|| kill_brick(row_ball_bot*9 + col_ball_right)) {
killed_a_brick = TRUE;
}
if (killed_a_brick) {
if (col_ball_left == col_ball_right) {
ball.dy = -ball.dy;
} else {
if (row_ball_bot == row_ball_top) {
ball.dx = -ball.dx;
} else {
ball.dx = -ball.dx;
ball.dy = -ball.dy;
}
}
}
}
// ============================================================
// update the player and ball positions
player.x = player.x + player.speed * player_direction();
ball.x = (ball.x + ball.dx);
ball.y = (ball.y + ball.dy);
// have the ball stick to the player if it hasn't been launched
if (ball.speed == 0) {
ball.x = player.x + (0.6*PLAYER1_WIDTH);
}
// ================ check if ball is in bounds ================
if (ball.y < UPPER_BOUND) {
ball.y = UPPER_BOUND;
ball.dy = -ball.dy;
}
if (ball.y > player.y - BALL1_HEIGHT && ball.alive) {
if (check_paddle_collision()) {
// get the new angle of direction of the ball, after hitting the paddle
ball.direction = new_ball_direction();
// update the x and y velociies of the ball
ball.dx = ball.speed * cos(RAD(ball.direction));
ball.dy = ball.speed * sin(RAD(ball.direction));
ball.y = player.y - BALL1_HEIGHT;
}
// else: stop checking this. Lose a life.
}
// if the ball is in a row of bricks, redraw the entire row
// (optimize this to be more efficient later)
draw_brick_row(row_ball_top);
if (row_ball_bot != row_ball_top) draw_brick_row(row_ball_bot);
if (ball.x > RIGHT_BOUND - BALL1_WIDTH) {
ball.x = RIGHT_BOUND - BALL1_WIDTH;
ball.dx = -ball.dx;
}
if (ball.x < LEFT_BOUND) {
ball.x = LEFT_BOUND;
ball.dx = -ball.dx;
}
if (player.x > (RIGHT_BOUND - PLAYER1_WIDTH)) {
player.x = (RIGHT_BOUND - PLAYER1_WIDTH);
}
if (player.x < LEFT_BOUND) {
player.x = LEFT_BOUND;
}
// ============================================================
//draw the player
draw_no_corners(player.x, player.y, player1, PLAYER1_WIDTH, PLAYER1_HEIGHT);
// draw the ball
draw_no_corners((s16) ball.x, (s16) ball.y, ball1, BALL1_WIDTH, BALL1_HEIGHT);
// launch the ball off the paddle
if (KEY_DOWN_NOW(BUTTON_A))
launch_ball();
// reset back to the splash screen if select is pressed
if (KEY_DOWN_NOW(BUTTON_SELECT))
splash_screen();
}
}
inline void splash_screen()
{
draw(0, 0, splash, 240, 160);
while (KEY_DOWN_NOW(BUTTON_SELECT));
while (!KEY_DOWN_NOW(BUTTON_SELECT));
// once select is pressed, start the game
init_game_values();
init_brick_array();
draw(0, 0, black, 240, 160);
// draw the entire background.
draw(40, 0, background_green, 160, 160);
// draw all the blocks
for (int i = 0; i < BRICKGRID_SIZE; i++) {
if(brickgrid[i].alive) draw(brickgrid[i].x, brickgrid[i].y, brickgrid[i].image, BLOCK_BLUE_WIDTH, BLOCK_BLUE_HEIGHT);
}
}
inline void game_over_screen() {
draw(0, 0, game_over, 240, 160);
while (KEY_DOWN_NOW(BUTTON_SELECT));
while (!KEY_DOWN_NOW(BUTTON_SELECT));
splash_screen();
}
inline void init_game_values()
{
player.x = 120 - (0.5 * PLAYER1_WIDTH);
player.lives = 1;
new_life();
}
inline void new_life()
{
player.y = 150;
player.speed = 1;
ball.x = player.x + (0.6*PLAYER1_WIDTH);
ball.speed = 0;
ball.direction = -50;
ball.dx = 0;
ball.dy = 0;
ball.y = player.y - BALL1_HEIGHT;
ball.alive = TRUE;
}
inline void init_brick_array()
{
for (int i = 0; i < BRICKGRID_SIZE; i++) {
brickgrid[i].image = block_blue;
// x values: 48 + 16*i
brickgrid[i].x = LEFT_BOUND + 1 + (BLOCK_BLUE_WIDTH*(i%9));
// y values: 20 + 8*i
brickgrid[i].y = 20 + (BLOCK_BLUE_HEIGHT*(i/9));
brickgrid[i].alive = TRUE;
}
}
inline void launch_ball()
{
if (ball.speed == 0) {
ball.speed = 3;
ball.dx = ball.speed * cos(RAD(ball.direction));
ball.dy = ball.speed * sin(RAD(ball.direction));
}
}
void wait_for_vsync()
{
while (SCANLINECOUNTER >= 160);
while (SCANLINECOUNTER < 160);
}
inline void dma_cpy(u16* dst, const volatile u16* src, u32 count, u8 fixed_src)
{
DMA[3].cnt = 0;
DMA[3].src = src;
DMA[3].dst = dst;
if (fixed_src) count = count | DMA_SOURCE_FIXED;
DMA[3].cnt = count | DMA_ON;
}
inline void draw(volatile s16 x, volatile s16 y, const volatile u16* image, u8 width, u8 height)
{
for (int i = y; i < y + height; i++) {
dma_cpy(videoBuffer + OFFSET(i ,x), image + (i-y)*width, width, 0);
}
}
inline void draw_background(volatile s16 x, volatile s16 y, const volatile u16* image, u8 width, u8 height)
{
for (int i = y; i < y + height; i++) {
dma_cpy(videoBuffer + OFFSET(i ,x), image + (i * 160 + x) - 40, width, 0);
}
}
inline void draw_no_corners(volatile s16 x, volatile s16 y, const volatile u16* image, u8 width, u8 height)
{
// copy the first row, without the left and right corner.
dma_cpy(videoBuffer + 1 + OFFSET(y ,x), image + 1, width-2, 0);
// copy the middle rows of the image normally
for (int i = 1; i < height-1; i++) {
dma_cpy(videoBuffer + OFFSET(i + y ,x), image + i*width, width, 0);
}
// copy the last row, without the left or right corner.
dma_cpy(videoBuffer + 1 + OFFSET(height-1 + y ,x), image + 1 + (height-1)*width, width-2, 0);
}
inline void draw_brick_row(s8 row_number)
{
if (row_number < 0 || row_number > BRICKGRID_SIZE/9 - 1) return;
for (int i = 9*row_number; i < 9*row_number+9; i++)
{
if(brickgrid[i].alive)
draw(brickgrid[i].x, brickgrid[i].y, brickgrid[i].image, BLOCK_BLUE_WIDTH, BLOCK_BLUE_HEIGHT);
else
draw_background(brickgrid[i].x, brickgrid[i].y, background_green, BLOCK_BLUE_WIDTH, BLOCK_BLUE_HEIGHT);
}
}
// returns true if there was a living brick at the passed in index.
inline u8 kill_brick(s8 index)
{
if (index < 54) {
if (brickgrid[index].alive) {
brickgrid[index].alive = FALSE;
return TRUE;
}
}
return FALSE;
}
inline s8 player_direction()
{
return (KEY_DOWN_NOW(BUTTON_LEFT) ? -2 : KEY_DOWN_NOW(BUTTON_RIGHT) ? 2 : 0);
}
inline s8 check_paddle_collision()
{
if (ball.x < player.x + PLAYER1_WIDTH && ball.x + BALL1_WIDTH > player.x)
return 1;
ball.alive = 0;
return 0;
}
// left edge of the paddle produces a -75 degree angle of ball movement,
// right edge of the paddle produces a 75 degree angle of ball movement.
inline s16 new_ball_direction()
{
return (-165 + (150 * (ball.x - (player.x - BALL1_WIDTH)) / (PLAYER1_WIDTH + BALL1_WIDTH)));
}
|
C
|
#include <stdio.h>
#include <math.h>
int A[200000];
long long B[200000];
int Dp[200000][20];
void SetRMQ(long long *array, int n)
{
int i, j, k;
for(i = 0; i < n; ++i) {
Dp[i][0] = i;
}
k = log(n) / log(2);
for(j = 1; j <= k; ++j) {
for(i = 0; i + (1 << j) - 1 < n; ++i) {
if(array[Dp[i][j - 1]] > array[Dp[i + (1 << (j - 1))][j - 1]]) {
Dp[i][j] = Dp[i][j - 1];
continue;
}
if(array[Dp[i][j - 1]] == array[Dp[i + (1 << (j - 1))][j - 1]]) {
Dp[i][j] = Dp[i][j - 1] < Dp[i + (1 << (j - 1))][j - 1] ?
Dp[i][j - 1] : Dp[i + (1 << (j - 1))][j - 1];
continue;
}
if(array[Dp[i][j - 1]] < array[Dp[i + (1 << (j - 1))][j - 1]]) {
Dp[i][j] = Dp[i + (1 << (j - 1))][j - 1];
}
}
}
}
int GetRMQ(long long *array, int a, int b)
{
int k = log(b - a + 1) / log(2);
if(array[Dp[a][k]] > array[Dp[b - (1 << k) + 1][k]]) {
return Dp[a][k];
}
if(array[Dp[a][k]] < array[Dp[b - (1 << k) + 1][k]]) {
return Dp[b - (1 << k) + 1][k];
} else {
return Dp[a][k] < Dp[b - (1 << k) + 1][k] ?
Dp[a][k] : Dp[b - (1 << k) + 1][k];
}
}
int main()
{
int N, K, i, L;
scanf("%d %d", &N, &K);
for(i = 0; i < N; ++i) {
scanf("%d", &A[i]);
}
B[0] = 0;
for(i = 0; i < K; ++i) {
B[0] += A[i];
}
for(i = 1; i + K <= N; ++i) {
B[i] = B[i - 1] - A[i - 1] + A[i + K - 1];
}
SetRMQ(B, N - K + 1);
long long Max = 0;
int MinA, MinB;
for(i = 0; i + K <= N - K; ++i) {
int cura = i;
int curb = GetRMQ(B, i + K, N - K);
if(B[cura] + B[curb] > Max) {
Max = B[i] + B[curb];
MinA = cura;
MinB = curb;
} else if(B[cura] + B[curb] == Max) {
if((cura < MinA) || (cura == MinA && curb < MinB)) {
MinA = cura;
MinB = curb;
}
}
}
printf("%d %d\n", MinA + 1, MinB + 1);
return 0;
}
|
C
|
#include "holberton.h"
/**
* print_alphabet_x10 - display alphabet x10
* Return: void
*/
void print_alphabet_x10(void)
{
char alp;
int i;
for (i = 0; i <= 9; i++)
{
alp = 'a';
while (alp <= 'z')
{
_putchar(alp);
alp++;
}
_putchar('\n');
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* small.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aalves <aalves@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/22 09:06:16 by aalves #+# #+# */
/* Updated: 2019/01/23 07:28:04 by aalves ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "malloc.h"
t_arena_header *find_small(uint16_t size)
{
t_arena_header *small;
if ((small = match_header_var(unused_small_space, &size)))
return (small);
else
{
small = get_new_header();
return (init_arena_header(small, T_SMALL));
}
}
size_t unused_small_space(t_arena_header *header, void *size)
{
uint16_t i;
if (!(header->type == T_SMALL))
return (0);
i = 0;
while (i < 4)
{
if (!header->arena.small.size[i] &&
*(uint16_t*)size <= available_space_at_index(header, i))
return (1);
i++;
}
return (0);
}
uint16_t available_space_at_index(t_arena_header *header, uint16_t index)
{
uint16_t i;
uint16_t j;
i = index + 1;
j = index ? index - 1 : 0;
while (j > 0 && !header->arena.small.size[j])
j--;
while (i < 4)
{
if (header->arena.small.offset[i])
return (header->arena.small.offset[i] -
(header->arena.small.offset[j] + header->arena.small.size[j]));
i++;
}
return ((uint16_t)g_manager.page_size -
(header->arena.small.offset[j] + header->arena.small.size[j]));
}
void *set_small_alloc(t_arena_header *header, uint16_t size)
{
uint16_t i;
uint16_t prev;
i = 0;
while (header->arena.small.size[i] || size > available_space_at_index(header, i))
i++;
prev = i ? i - 1 : 0;
while (prev > 0 && !header->arena.small.size[prev])
prev--;
header->arena.small.offset[i] = header->arena.small.size[prev] ?
header->arena.small.offset[prev] + header->arena.small.size[prev] : 0;
header->arena.small.size[i] = size;
header->used = 1;
return ((uint8_t*)header->loc + header->arena.small.offset[i]);
}
void print_small_alloc(t_arena_header *header)
{
uint16_t i;
if (!(header->type == T_SMALL) || !header->used)
return;
i = 0;
ft_putstr("SMALL : ");
print_addr(header->loc);
ft_putstr("\n");
while (i < 4)
{
if (header->arena.small.size[i])
{
print_addr((void*)((size_t)header->loc + header->arena.small.offset[i]));
ft_putstr(" - ");
print_addr((void*)((size_t)header->loc + header->arena.small.offset[i] +
header->arena.small.size[i]));
ft_putstr(" : ");
ft_putstr(ft_static_ulltoa(header->arena.small.size[i]));
ft_putstr(" octets\n");
}
i++;
}
}
|
C
|
#include "scc.h"
//calculates number of edges in each scc
int process_traversed(t_vect *edgs)
{
int num = 0;
qsort(edgs->tab, edgs->used, sizeof(int), cmp_int);
for (int i = 0; i < edgs->used; i++)
if (i == 0 || edgs->tab[i] != edgs->tab[i-1])
num++;
free(edgs->tab);
free(edgs);
return num;
}
t_component *init_component()
{
t_component *new = (t_component*)malloc(sizeof(t_component));
t_vect *l = (t_vect*)malloc(sizeof(t_vect));
init_vector(l);
new->vrx_nb = 0;
new->edg_nb = 0;
new->list = l;
return (new);
}
void fill_component(int x, t_graph *g, t_component *new, int cycl)
{
t_stack *stk = (t_stack*)malloc(sizeof(t_stack));
t_vect *edgs = (t_vect*)malloc(sizeof(t_vect));
init_vector(edgs);
stk->size = 0;
int tag;
int top;
int cnt = 0;
push(stk,x);
g->visited[x] = cycl;
while (stk->size > 0)
{
tag = 0;
top = stk->top->val;
for (int i = 0; i < g->rev_adj[top].used; i++)
{
if (g->visited[g->rev_adj[top].tab[i]] == 0)
{
g->visited[g->rev_adj[top].tab[i]] = cycl;
push(stk, g->rev_adj[top].tab[i]);
tag = 1;
}
else if (g->visited[g->rev_adj[top].tab[i]] == cycl)
push_back(edgs, g->vertx * top + g->rev_adj[top].tab[i]);
}
if (!tag)
{
new->vrx_nb++;
push_back(new->list,top);
pop(stk);
}
}
new->edg_nb = process_traversed(edgs);
free(stk);
}
void classify_component(t_component *c)
{
if (c->edg_nb > c->vrx_nb)
c->type = 2;
else if (c->edg_nb == 0)
c->type = 0;
else
c->type = 1;
}
void add_component(t_graph *g, t_component *c)
{
if (g->head == NULL)
{
g->head = c;
g->tail = c;
c->next = NULL;
}
else
{
g->tail->next = c;
c->next = NULL;
g->tail = c;
}
}
void get_component(t_graph *g, int src, int cycl)
{
t_component *new = init_component();
fill_component(src,g,new, cycl);
classify_component(new);
add_component(g, new);
}
|
C
|
/*
Escreva um programa que leia informações de livros presentes no arquivo bestsellers.cvs,
organize-os na forma de um array de structs, e imprima uma tabela com o nome e autor dos livros.
o arquivo possui um livro por linha, com cada campo separado por vírgulas, sendo os campos
nome, autor, idioma, data, vendas
use scanf para ler estas informações.
fscanf(arquivo, "padrão de formatação com i% %s", &inteiro, &str);
fscanf lê do arquivo em questão informações seguindo o formato especificado, colocando-as
nas variáveis cujos endereços você passar. lembrando que pode usar &variavél para representar
o endereço delas.
lembre que struct é algo parecido com classes e objetos. você define um struct como se definisse uma classe,
depois pode criar N objetos dela.
struct person {
char[50] name;
int age;
} #cria a estrutura de structs chamados person - as variáveis/propriedades que ficam dentro dele
struct person Alline; #declara uma variável com nome Alline cujo tipo é o struct person
quando você declara um struct, ele não "tem" nada. ele é só um modelo, você nunca vai lidar com ele diretamente.
depois de ter a declaração de um struct, daí você cria uma variável específica, do tipo struct, seguindo aquele modelo, e usa como quiser.
*/
#include <stdio.h>
#include <stdlib.h>
int qtd(char nomearquivo[])
{
FILE *books2;
int cont=0;
char lala[100];
books2=fopen(nomearquivo, "r");
while (fgets(lala, 100, books2) != NULL)
{
cont++;
}
fclose(books2);
return cont;
}
void main()
{
FILE *books;
// esta é uma declaração do modelo/classe de structs, chamado Livro.
// não pode usar diretamente; não é uma variável.
struct Livro
{
char nome[40];
char autor[40];
char linguagem[20];
int ano;
int vendas;
};
books=fopen("bestsellers.csv", "r");
// declaração de duas variáveis - chamadas Tale e She, do tipo struct, que seguem o modelo Livro.
struct Livro Tale, She;
// aqui as duas primeiras linhas do arquivo são lidas e colocadas em respectivos structs.
fscanf(books, "%[^;]; %[^;]; %[^;]; %i; %i", Tale.nome, Tale.autor, Tale.linguagem, &Tale.ano, &Tale.vendas);
fscanf(books, "%[^;]; %[^;]; %[^;]; %i; %i", She.nome, She.autor, She.linguagem, &She.ano, &She.vendas);
// um array de structs do tipo Livro.
// um array de structs funciona como demais arrays, no sentido de que cada posição
// é uma variável completamente separada.
// livros[0].nome = "Tale"; livros[1].nome = "She";
struct Livro livros[14];
// sabendo que arrays de structs se comportam assim (ou seja, como qualquer outro array),
// podemos criar loops com eles.
for(i = 0; i < 13; i++){
fscanf(books, "%[^ ]; %[^;]; %[^;]; %i; %i",
books[i].nome, books[i].autor, books[i].linguagem, &books[i].ano, &books[i].vendas
);
}
fclose(books);
}
for(i = 0; i < 10; i++){
fscanf(nov, "%13[^/]%f", Pagamentos[i].matricula, &Pagamentos[i].horas);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void swap(int * n1, int * n2)
{
int tmp = *n1;
*n1 = *n2;
*n2 = tmp;
}
void quick_sort( int *tab, int left, int right )
{
int i = left, j = right;
int x = tab[( left + right ) / 2 ];
do
{
while( tab[ i ] < x )
i++;
while( tab[ j ] > x )
j--;
if( i <= j )
{
swap( &tab[ i ], &tab[ j ] );
i++;
j--;
}
} while( i <= j );
if( right > i ) quick_sort( tab, i, right );
if( left < j ) quick_sort( tab, left, j );
}
int main()
{
int tab_1[10] = {10, 2, 23, 2, 21, 1, 8, 6, 4, 2};
quick_sort(tab_1, 0, 9);
for(int i = 0; i < 10; i++) printf("%d, ", tab_1[i]);
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
double cotacao, aliquota, valorproduto, valorfrete;
double valortotal, importacao, finalicms, icms, impostos, totalpagar;
scanf("%lf %lf %lf %lf", &cotacao, &aliquota, &valorproduto, &valorfrete);
valorproduto = valorproduto * cotacao;
valorfrete = valorfrete * cotacao;
valortotal = valorproduto + valorfrete;
aliquota = aliquota/100;
if(valorproduto >= (2500.00*cotacao))
{
importacao = valorproduto * 0.6;
finalicms = (valorproduto + importacao)/(1-aliquota);
}
else{
importacao = valortotal * 0.6;
finalicms = (valortotal + importacao)/(1-aliquota);
}
icms = finalicms*aliquota;
impostos = icms + importacao;
totalpagar = valortotal + impostos;
printf("%.2lf\n", cotacao);
printf("%.2lf\n", valorproduto);
printf("%.2lf\n", valorfrete);
printf("%.2lf\n", valortotal);
printf("%.2lf\n", importacao);
printf("%.2lf\n", icms);
printf("%.2lf\n", impostos);
printf("%.2lf\n", totalpagar);
if(valorproduto >= (2500.00*cotacao))
{
printf("Impostos calculados sem o frete\n");
}
else{
printf("Impostos calculados com o frete\n");
}
return 0;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#define EMPTY_QUEUE_ERROR -999999
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXLEN 100
/*29
3. ݴʻHuffman ¾ ѹͽѹ
love is love, this commandment is always said by Marbury, which means that one person always love any other person.
Ҫͳһ¸ʵĴƵ,,õÿʵHuffman,ٸݸľ((ظ))ζӦı
*/
/*
ʾα桰01ıʡռ䣿
01001011ַ鱣Ҫ8ֽڣ
öƱʾΪ0100 1011һַK(ASCIIΪ7575ĶΪ 01001011)ɱʾ롣
λѹΪַ
*/
/*Ϊ˽ѹ,ҪдתΪʮ,ԱתΪASCII,̶ͨputchar()ASCII뽫ѹݱ*/
/*෴,Ϊʵֽ,ַĸַASCIIתΪ01봮*/
//HuffmanĴ洢ṹ
#define n 15 //ҶĿ
#define m 2*n-1 //н
#define ZIP_bits 7 //ѹλ
/*ʵֵľ̬˫ݽṹ*/
/*HuffmanĻ(㱾ȨԼ/ϵ*/
typedef struct //(Ҷӽڵ)
{
float weight; //ȨֵȨֵ(ֵ)
int lchild, rchild, parent; //ҺӼ˫ָ
}HTNode;
/*HuffmanĽṹ(ڵ͵),ֻ(Ȩ)Ҷӽڵ*/
typedef HTNode HuffmanTree[m]; //HuffmanTree/*(Ҳ)ԪĿHuffmanĽm*/
/*HuffumanĸĸӱϢ*/
typedef struct
{
char str[MAXLEN]; //洢ַ
char bits[n + 1]; // λ(0,1)
}CodeNode;
/*huffman Ϣ*/
typedef CodeNode HuffmanCode[n];/*(Ҳ)ԪĿHuffmanҶӽڵĿn*/
int To_letter(char* str_01)
{
int len = strlen(str_01);
int sum = 0;
for (int i = len-1; i >= 0; i--)
{
sum = sum + (int)str_01[i] * pow(2, len - 1 - i);
}
return sum;
}
int To_char_Ascii_7bit(char* str_01)
{
int sum = 0;
for (int i = 0; i < ZIP_bits; i++)
{
//sum = sum + (int)(*(str_01 + i)) * pow(2, 7 - i);
sum = sum + (*(str_01 + i)-48) * pow(2, ZIP_bits-1 - i);
}
return sum;
}
void InitHuffmanTree(HuffmanTree T); //ʼHuffman
void InputWeight(HuffmanTree T); //Ȩֵ
void SelectMin(HuffmanTree T, int i, int* p1, int* p2);
/*huffman*/
void main()/*㹻ߵĻ,ַ()ı̳ȿԳ1*/
{
/*ڲ:*/
/*ǵ!!!1*/
void CreateHuffmanTree(HuffmanTree T); //:Huffmanĺ
void CharSetHuffmanEncoding(HuffmanTree T, HuffmanCode H); //:ڵĹ,ڲHеĺ.
/*Huffman͵ı(ʼǽ͵)*/
HuffmanTree T;
HuffmanCode H;
CreateHuffmanTree(T);/*main()кȺϵ,ǰĺÿܶԺõĺ
Ӱʼݽṹ/ݽṹ..Աĵÿȷ*/
CharSetHuffmanEncoding(T, H);
}
/*ͼ(ʾ):
* 700->713->715
*/
void CreateHuffmanTree(HuffmanTree T)//main()_1(Huffman,Ϻ)
{ //HuffmanT[m-1]Ϊ
int i, p1, p2;
InitHuffmanTree(T); //Tʼ
InputWeight(T); //ҶȨֵT[0..n-1]weight
for (i = n; i < m; i++) /*n-1κϲ½δT[i];n->mЩڵǷҶӽڵ(ڹǴnҶ)ǵȨֵ
Ҷӽڵϲõ,֮ҲɳΪϲĶ,T(ÿϲһ,TеĽͻһ:(һ½,ɽ)
Ȼ𱣴Ϣ H еĽ㲻ᱻɾ*/
{
SelectMin(T, i - 1, &p1, &p2);
//T[0..i-1]ѡ ȨС 㣬ŷֱΪp1p2
T[p1].parent = T[p2].parent = i;/*iǵǰTһһλ,൱ڰp1p2ҽӵô*/
/*СȨʹСȨҹϵ*/
T[i].lchild = p1; //СȨĸ ½
T[i].rchild = p2; //СȨĸ ½Һ
/*½T[i].parent ʱȻڱInitHuffmanʼNULL(ij½T[i].parentûб(ΪNULL)T[i]Huffmanܸ*/
T[i].weight = T[p1].weight + T[p2].weight;/*½Ȩֵ*/
}
}
void InitHuffmanTree(HuffmanTree T)/*ʼHuffman*/
{
int i;
for (i = 0; i < m; i++)/*Huffmanнλöгʼ( m = 2n-1)*/
{
T[i].weight = 0;
T[i].lchild = T[i].rchild = T[i].parent = NULL;/*ϵ()ָ붼ʼΪNULL: (void*)0 */
}
}
void InputWeight(HuffmanTree T)//Ȩֵ(nҶӽڵ)
{
int i;
for (i = 0; i < n; i++)/*nǰĺ궨,ֵΪ5,(ȻôдNȽϺ)*/
{
printf("%dȨֵ", i + 1);
scanf("%f", &T[i].weight);/*Ȩ дTǰn*/
}
}
/*T[0..i]ѡ δϲ ȨС (ЩҶӽڵ㶼һ,ҶӱǸ)ŷֱΪp1p2(üӴ,Ա㱣Ľ)*/
void SelectMin(HuffmanTree T,
int i,/*ɨ/жϵķΧ:iΪ(0~i)(ΪЧʵĸӲ(ͬʱҲDZҪ)*/
int* p1, /*С*/
int* p2)/*С*/ //T[0..i-1]ѡ ȨС 㣬ŷֱΪp1p2(üӴ,Ա㱣Ľ)
{
//TѡȨСĸ
int j;
float min1,/*С*/
min2;/*С*/
min1 = min2 = -1;
for (j = 0; j <= i; j++)/*0iȡüҶӽڵ*/
/*T[j]δϲ,T[j].parentDZֳʼNULL*/
if (T[j].parent == NULL)/*T[j].parent != NULL,˵֮ǰѾںϲ(,ôTоͲٲϲ,ҲͲɸеСȨ*/
{
/*min1*/
if (T[j].weight < min1 /*ȵǰΪֹСȨС,T[j]µСȨڵ.*/
|| min1 == -1)/*Ϊ˿һж,нڵȨΪȽ*/
{
if (min1 != -1)/*min1֮ǰѱ.ͱҪmin2p2,ȻҲԲж,һgeng'xin.*/
{
/*min1*p1ǰ,ݸƵmin2*p2*/
min2 = min1;
*p2 = *p1;
}
/*min1*p1*/
min1 = T[j].weight;
*p1 = j;
}
else
if (T[j].weight < min2 || min2 == -1)
{
min2 = T[j].weight;
*p2 = j;
}
}
}
/*ռַ,˳ȡ.*/
void CharSetHuffmanEncoding(HuffmanTree T, HuffmanCode H)/*main()_2()*/
{ //HuffmanT HuffmanH
int c,/*childλ*/
p,/*parentλ.*/
i; //cpֱָʾ T() Ӻ˫λ
char cd[n + 1]; //ʱű/*һλ:cd[n]ַ'\0'.ȷַHuffmanijȲᳬn
int start; //ָʾcdеʼλ
cd[n] = '\0'; //
printf("뵥ַ\n");
//getchar();/*Ӧʱ֮ǰµĻ.(ȻͲҪgetchar()ķֵ)*/
/*ֱӿfor()(ǰͷĸſ),;ʶĻͣ漴ɿ(жʱעҲʾ.*/
for (i = 0; i < n; i++) // ҶT[i] ı
{
scanf("%s", H[i].str); //ҶT[i]Ӧĵ
start = n; //ʼλ ijֵ
c = i;/*ʼΪi*/ // ҶT[i] ʼ /*(yin'wei)ΪҶӽڵ,ȻҪ ''
while ((p = T[c].parent) != NULL)/*//ֱ ݵT[c] Ϊֹ;ռ0,1ַ봮.ڵĸڵָΪNULL
(Ȼ,϶dzʼnҶӽڵ,;ϲ½ڵ(ЩҶӽڵֻλ,ûнڵı?).*/
{ //T[c]T[p]ӣɴ0ɴ1
cd[--start] = (T[p].lchild == c) ? '0' : '1';/*ռַǴӺǰд,˳ŶȾͿԻôӸڵ㵽Ҷӽڵı.
(start=n;λñд'\0',Ҫǰһλд(--start)
(Ȼ̱ǣͷֿ(),Һstartָʾ↑ʼȡַ,
ǰͷѾcd[n]ʼΪ'\0'*/
c = p; ///*ΪԾ,cֱi.*/
}
/*ҶӽڵϢH.*/
strcpy(H[i].bits, &cd[start]); //Ʊλ(д뵽ӦҶӽʽ)
/*ѹ*/
/*ַռ*/
;
}/*ڵϵͽڵϢѽ*/
/*ӡ:*/
for (i = 0; i < n; i++)/*ڵȨͽڵƵ ԵȺϵһһӦ.*/
printf("%dַ%sıΪ%s\n", i + 1, H[i].str, H[i].bits);
/*Ľڵ,εزұ,ռ*/
printf("Ľڵ,εزұ,ռ:\n");
char temp[MAXLEN];
char collect_encode[2 * MAXLEN];
collect_encode[0] = '\0';
while (scanf("%s", temp) != EOF)
{
for (int i = 0; i < n; i++)
{
if (!strcmp(temp, H[i].str))
{
strcat(collect_encode, H[i].bits);
break;
}
}
}
/*ռر߸ֽӳ䵽һַ(˸ػеӡ),ռַӡ*/
printf("ռı߸ֽӳ䵽һַ(˸ػеӡ),ռַӡ:\n");
//int i = 0;
for ( i = 0; i < strlen(collect_encode); i += ZIP_bits)
{
putchar(To_char_Ascii_7bit(&collect_encode[i]));
printf("|");
}
putchar(To_letter(&collect_encode[i - ZIP_bits]));
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#define MAX_THREADS 3
char WORDS[3] = "ABC";
void *do_thread_stuff(void *i){
int index = (int) i;
char *letter = malloc(sizeof(char) + 1);
letter[0] = WORDS[index];
unsigned short int sleep_time = rand() % 10 + 1;
sleep(sleep_time);
pthread_exit((void*) letter);
}
int main(void){
pthread_t pthread_id[MAX_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int i;
for(i=0; i < MAX_THREADS; i++){
printf("Thread number %d\n", i);
pthread_create(&pthread_id[i],
&attr,
&do_thread_stuff,
(void *)i);
}
printf("Returning text: \n");
for(i=0; i < MAX_THREADS; i++){
char *character = malloc(sizeof(char) + 1);
pthread_join(pthread_id[i], (void *) &character);
printf("%s\n", character);
}
printf("\n");
pthread_exit(NULL);
}
|
C
|
#include<stdio.h>
main()
{
int i=2,n=8,c;
for(i=2;i<n;i++)
{
c=n%i;
if(c==0)
{
printf("%d n is not a prime number\n",n);
if (c!=0)
continue;
}
if(i==n)
printf("%d n is a prime number\n",n);
if(i<n)
printf("%d n is not a prime number\n",n);
}
}
|
C
|
#ifndef HASH_H
#define HASH_H
#include <stdbool.h>
#include <stddef.h>
typedef struct hash hash_t;
// A implementar
bool hash_guardar(hash_t* hash, const char* clave, void* dato);
hash_t* hash_crear();
bool hash_pertenece(const hash_t* hash, const char* clave);
void* hash_borrar(hash_t* hash, const char* clave);
void* hash_obtener(const hash_t* hash, const char* clave);
size_t hash_cantidad(const hash_t* hash);
// Se asume que Barbara se encarga de los datos, por simplicidad del ejercicio
void hash_destruir(hash_t* hash);
#endif
|
C
|
// Copyright 2016-2019 Coffee Stain Studios. All Rights Reserved.
#pragma once
/**
* A collection of unit conversions to make code more readable.
*/
struct FUnits
{
/** Distance */
static FORCEINLINE float CmToM( float cm ) { return cm / 100.0f; }
static FORCEINLINE float MToCm( float m ) { return m * 100.0f; }
/** Area and Volume */
static FORCEINLINE float M2ToCm2( float m2 ) { return m2 * 100.f * 100.f; }
static FORCEINLINE float Cm2ToM2( float cm2 ) { return cm2 / ( 100.f * 100.f ); }
/** Speed */
static FORCEINLINE float KmHToCmS( float kmH ) { return kmH * 100000.f / 3600.f; }
static FORCEINLINE float CmSToKmH( float cmS ) { return cmS * 3600.f / 100000.f; }
/** Forces */
static FORCEINLINE float kNToN( float kN ) { return kN * 1000.0f; }
static FORCEINLINE float NTokN( float kN ) { return kN / 1000.0f; }
/** Radians to a grade in percent. */
static FORCEINLINE float RadiansToGrade( float rad )
{
const float clamped = FMath::Min( FMath::Abs( rad ), PI / 4.0f );
return FMath::Tan( clamped ) * 100.0f;
}
/** Volume */
static FORCEINLINE float LiterToM3( float liter ) { return liter * 1000.f; }
static FORCEINLINE float M3ToLiter( float m3 ) { return m3 / 1000.f; }
};
|
C
|
//
// main.c
// PlayingWithC
//
// Created by Jonathan Pappas on 5/11/21.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
// insert code here...
printf("Hello, World!\n");
int count = 1;
for(int i=0;i<1000000000;i++) {
for(int j=0;j<1000000000;j++) {
for(int l=0;l<1000000000;l++) {
for(int m=0;m<1000000000;m++) {
count++;
}
}
}
}
printf("%d", count);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
float sum = 0.0f, corr = 0.0f; /* corrective value for rounding error */
for (int i = 0; i < 10000; i++) {
float y = (i + 1) - corr; /* add the correction to specific item */
float t = sum + y; /* bits might be lost */
corr = (t - sum) - y; /* recover lost bits */
sum = t;
}
printf("Sum: %f\n", sum);
return 0;
}
|
C
|
/* 求置换的循环节,polya原理 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXN 1000
int gcd(int a,int b){
return b?gcd(b,a%b):a;
}
/* perm[0..n-1]为0..n-1的一个置换(排列)
* 返回置换最小周期,num返回循环节个数
*/
int polya(int* perm,int n,int* num){
int i,j,p=0,v[MAXN]={0},ret=1;
for(*num=i=0;i<n;i++)
if(!v[i]){
for(*num++,j=0,p=i;!v[p=perm[p]];j++)
v[p]=1;
ret*=j/gcd(ret,j);
}
return ret;
}
int main(void)
{
int perm[5]={1,2,3,4,5},num,ret;
ret = polya(perm,5,&num);
printf("ret:%d num:%d\n",ret,num);
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int a[10],i,j;
for(i=0;i<10;i++){
scanf("%d",&a[i]);
}
for(i=1;i<10;i++){//n-1
//iʱa[0]a[n-i-1]һȽ
for(j=1;j<11-i;j++){
if(a[j-1]>a[j]){//ߵ
int temp = a[j-1];
a[j-1]=a[j];
a[j]=temp;
}
}
}
for(i=0;i<10;i++){
printf("%d\n",a[i]);
}
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 */
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
struct TYPE_3__ {int next; int count; int /*<<< orphan*/ * tids; } ;
typedef TYPE_1__ corrupt_items ;
typedef int /*<<< orphan*/ ItemPointerData ;
typedef int /*<<< orphan*/ * ItemPointer ;
/* Variables and functions */
int /*<<< orphan*/ * repalloc (int /*<<< orphan*/ *,int) ;
__attribute__((used)) static void
record_corrupt_item(corrupt_items *items, ItemPointer tid)
{
/* enlarge output array if needed. */
if (items->next >= items->count)
{
items->count *= 2;
items->tids = repalloc(items->tids,
items->count * sizeof(ItemPointerData));
}
/* and add the new item */
items->tids[items->next++] = *tid;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b;
printf("/nenter the two numbers");
scanf("%d%d",&a,&b);
printf("\n a=%d\nb=%d");
a=a^b;
b=a^b;
a=a^b;
printf("/n after swapping")
printf("/n a-%d/nb=%d);
getch();
return 0;
}
|
C
|
#include<gtk/gtk.h>
#include<stdlib.h>
GtkWidget *window;
GtkWidget *table;// 和ios相比,是多出来的,ios没有这种界面布局控件。
GtkWidget *label;
GtkWidget *entry;
GtkWidget *button;
char text[50];
void
on_clicked(GtkWidget *widget,gpointer data)
{
// 获取文本框的内容,并将其复制到text字符数组中
strcpy(text,gtk_entry_get_text(GTK_ENTRY(entry)));
printf("输入的字符串是:%s\n",text);
}
int
main(int argc,char *argv[])
{
gtk_init(&argc,&argv);// 初始化图形显示环境。
// 窗口
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),
g_locale_to_utf8("文本框的使用",-1,NULL,NULL,NULL)
);
// g_locale_to_utf8()支持中文字符显示。
// 表格:3行2列,单元格大小会根据单元格中的控件大小自动调整。
table = gtk_table_new(3,2,FALSE);
// 标签
label = gtk_label_new(
g_locale_to_utf8("请在这里输入文本:",-1,NULL,NULL,NULL));
// 文本框
entry = gtk_entry_new_with_max_length(50);
// 按钮
button = gtk_button_new_with_label(
g_locale_to_utf8("提交",-1,NULL,NULL,NULL));
// 将表格添加到窗口中,因为表格也是一个控件,自然要添加到容器中。
gtk_container_add(GTK_CONTAINER(window),table);
// 类似于controller的self.view
// 将3个元件添加到表格相应的位置中。
gtk_table_attach(GTK_TABLE(table),label,0,1,0,1,
(GtkAttachOptions)(0),(GtkAttachOptions)(0),10,10);
gtk_table_attach(GTK_TABLE(table),entry,0,2,1,2,
(GtkAttachOptions)(0),(GtkAttachOptions)(0),10,10);
gtk_table_attach(GTK_TABLE(table),button,1,2,2,3,
(GtkAttachOptions)(0),(GtkAttachOptions)(0),10,10);
// 显示窗口中的所有元件
gtk_widget_show_all(window);
//为提交按钮添加回调函数
g_signal_connect(G_OBJECT(button),"clicked"
,G_CALLBACK(on_clicked),window);
//直接引用g_signal_connect宏,退出
g_signal_connect(G_OBJECT(window),"delete_event"
,G_CALLBACK(gtk_main_quit),NULL);
// 消息主循环
gtk_main();
return 0;
}
/*
g_signal_connect()
在点击“提交”按钮时,产生来相应的信号。
系统自动调用相应的信号处理函数。
*/
|
C
|
//
#include "TFile.h"
#include "TTree.h"
#include "TH1F.h"
#include "CMSAna/HHToBBGG/interface/HHToBBGGEventTree.hh"
#include "CMSAna/Utils/interface/SimpleTable.h"
//--------------------------------------------------------------------------------------------------
// Get Total Number of Events in the sample
//--------------------------------------------------------------------------------------------------
Double_t getNormalizationWeight(string filename, string datasetName) {
// Get Normalization Weight Factor
//Get Number of Events in the Sample
TFile *file = new TFile(filename.c_str(),"READ");
if (!file) {
cout << "Could not open file " << filename << endl;
return 0;
}
//TDirectory *dir = (TDirectory*)file->FindObjectAny("AnaFwkMod");
//if (!dir) {
// cout << "Could not find directory AnaFwkMod"
// << " in file " << filename << endl;
// delete file;
// return 0;
//}
TH1F *hist = (TH1F*) file->Get("NEvents");
if (!hist) {
cout << "Could not find histogram hDAllEvents in directory AnaFwkMod"
<< " in file " << filename << endl;
//delete dir;
file->Close();
delete file;
return 0;
}
Double_t NEvents = hist->Integral();
cout << "Original events in the sample: " << NEvents << endl;
//Get CrossSection
cmsana::SimpleTable xstab("$CMSSW_BASE/src/CMSAna/HHToBBGG/data/xs.dat");
Double_t CrossSection = xstab.Get(datasetName.c_str());
Double_t Weight = CrossSection / NEvents;
// weight for data is always 1 (-1 to make a trick for fakes)
if(CrossSection < 0) Weight = -1.0;
cout << "Cross Section = " << CrossSection << " for dataset " << datasetName << "\n";
cout << "Events get weight: " << Weight << "\n";
//delete dir;
file->Close();
delete file;
return Weight;
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void NormalizeNtuple(const string InputFilename,
const string datasetName,
const string OutputFilename) {
cmsana::HHToBBGGEventTree event;
event.LoadTree(InputFilename.c_str());
event.InitTree();
Double_t normalizationWeight = getNormalizationWeight(InputFilename, datasetName);
//*************************************************************************************************
//Create new normalized tree
//*************************************************************************************************
TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
outputFile->cd();
TTree *normalizedTree = event.tree_->CloneTree(0);
cout << "Events in the ntuple: " << event.tree_->GetEntries() << endl;
for (int n=0;n<event.tree_->GetEntries();n++) {
event.tree_->GetEntry(n);
if (normalizationWeight < 0){
event.weight = event.weight * 1.0;
} else {
event.weight = event.weight * normalizationWeight * 1.0;
}
normalizedTree->Fill();
}
normalizedTree->Write();
outputFile->Close();
}
|
C
|
#include "header.h"
#include <math.h>
#include <string.h>
char *getXor(char *a, char *b)
{
char *res = strdup("000000");
for (int i = 0; i < 6; i++)
{
if (a[i] != b[i])
res[i] = '1';
else
res[i] = '0';
}
return (res);
}
int toInt(char *bits)
{
int num = 0;
int p = 0;
int size = strlen(bits);
for (int i = 0; i < 6; i++)
{
p = bits[size - 1 - i] - '0';
num += pow(2,i) * p;
}
return (num);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m,n,t,i,cif,p,j,bd;
scanf("%d%d%d" , &m ,&n ,&t); /**t=broj na deliteli*/
for(i=m;i<=n;i++)
{
p=i;
bd=0;
for(j=1;j<=p;j++)
{
if(p%j==0)
++bd;
}
if(bd==t)
printf("%d\n" , i);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int num,num1 = 0,num2=1,cont=1,fibo;
printf("Ingrese el valor del termino que desea saber la serie de fibonacci: ");
scanf("%i",&num);
while(num<=0){
printf("Error. Ingrese un numero entero positivo: ");
scanf("%i",&num);
}
while(cont<=num){
fibo = num1 + num2;
printf("%i \n",fibo);
num1 = num2;
num2 = fibo;
cont = cont +1;
}
printf("el valor del termino de fibonacci es %i\n",fibo);
system("PAUSE");
return 0;
}
|
C
|
/** finalfuncts.c
* ===========================================================
* Name: Trinity Abdulkhalik, 12/3/2020
* Section:T1A
* Project: Hangman
* Purpose: Display understanding of overarching course concepts
* ===========================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <errno.h>
void intializeGame(char* wordRead){//This function opens the file, scans for a word in accordance with the randomly generated index.
int index = 0;
FILE* inFile = fopen("dictionary.txt", "r");
if(inFile == NULL){
printf("Error creating data file: %s.\n", strerror(errno));
exit(1);
}
index = rand() % getNumLines();//This randomly generates the index.
for(int i =0; i <= index; i++){
fscanf(inFile, " %s ", wordRead);
}
fclose(inFile);
wordRead = (char *) realloc(wordRead, strlen(wordRead));//This reallocates the appropriate amount of memory after the word is selected.
}
int getNumLines(){//This generates the number of lines in the .txt file that feeds into the calculation for the randomized index.
int numLines = 0;
char temp[50];
FILE* inFile = fopen("dictionary.txt", "r");
while(!feof(inFile)){
fscanf(inFile, " %s ", temp);
numLines++;
}
return numLines;
}
int updateWord(char* word, char* blanks, char characterInput){//This function replaces the appropriate blank with the appropriate letter.
int wordLength = strlen(word);
int correctlyGuessed;
int guessLeft = 6;
for (int i = 0; i < wordLength; i++){//This iterates through the word to check if a letter matches at a certain space.
if (characterInput == word [i]){
blanks[i] = characterInput;//This statement causes the letter input to replace the appropriate blank if there is a matching letter.
correctlyGuessed ++;
}
else{
guessLeft--;//This decreases the amount of guesses left and leads into the amount of limbs no the hangman pole are drawn.
}
}
return correctlyGuessed;
return guessLeft;
}
void drawHangman(int incorrectGuess){//This draws the hangman in accordance with the number of guesses left for the user.
char* hangman[7][100]={ // This is a 2D array. There is one to specify the platform and another one for the string of characters.
" |=====|\n"
" |\n"
" |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" | |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" -| |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" -|- |\n"
" |\n"
" ===\n",
" |=====|\n"
" O |\n"
" -|- |\n"
" | |\n"
" ===\n",
" |=====|\n"
" O |\n"
" -|- |\n"
" | | |\n"
" ===\n"
};
switch (incorrectGuess){//This switch case prints the appropriate hangman structure for the attempts left.
case 7:
printf("\n\n%s\n", hangman[0][0]);
break;
case 6:
printf("\n\n%s\n", hangman[1][0]);
break;
case 5:
printf("\n\n%s\n", hangman[2][0]);
break;
case 4:
printf("\n\n%s\n", hangman[3][0]);
break;
case 3:
printf("\n\n%s\n", hangman[4][0]);
break;
case 2:
printf("\n\n%s\n", hangman[5][0]);
break;
case 1:
printf("\n\n%s\n", hangman[6][0]);
break;
}
}
void checkWinner(int guessLeft, char* wordChoice, char* blankPhrase, char characterCollect){//This function checks whether the hangman is complete or if the blanks are correctly filled.
int i = rand() % getNumLines();
if (guessLeft > 0){//This is supposed to update the word and hangman structure in accordance with the guesses left for the user as long as the guesses are at a value greater than zero.
updateWord(wordChoice, blankPhrase, characterCollect);
drawHangman(guessLeft);
printf("Winner! Would you like to play again?\n");//This is the victory message.
}
else{//This else statement draws the hangman fully with all body parts if the guesses are at 0 and the word has not been filled appropriately.
drawHangman(1);
printf("Unfortunately, you lost. The correct word was %s, Would you like to play again?\n", wordChoice[i]);//This is a losing message.
}
}
int endGame(){//This function asks the player if they wish to replay and scans for a value. If the player wishes to replay, this function resets the game by calling the main function which calls the intiailized functions.
char val = 'a';
printf("Replay?")?
scanf("%d", val);
if (val == 1){
return main();
}
return 0;
}
|
C
|
#include <ft_printf.h>
#define BUFF_SIZE 4096
#include <string.h>
#include <unistd.h>
static char buffer[BUFF_SIZE];
static size_t size = 0;
static size_t total = 0;
static void bufferize_too_long_char(const char c, size_t len)
{
memset(buffer + size, c, TAB_SIZE(buffer) - size);
len -= TAB_SIZE(buffer) - size;
write(1, buffer, TAB_SIZE(buffer));
if (len > TAB_SIZE(buffer))
{
memset(buffer, c, TAB_SIZE(buffer));
while (len > TAB_SIZE(buffer))
{
write(1, buffer, len);
len -= TAB_SIZE(buffer);
}
size = len;
}
else
{
size = len;
memset(buffer, c, size);
}
}
void bufferize_char(const char c, size_t len, char flush)
{
total += len;
if (size + len > TAB_SIZE(buffer))
bufferize_too_long_char(c, len);
else
{
memset(buffer + size, c, len);
size += len;
}
if (flush && size)
{
write(1, buffer, size);
size = 0;
}
}
static void bufferize_too_long(const char *str, size_t len)
{
size_t add;
if (size + len > TAB_SIZE(buffer) * 2)
{
write(1, buffer, size);
write(1, str, len);
}
else
{
add = TAB_SIZE(buffer) - size;
memcpy(buffer + size, str, add);
write(1, buffer, TAB_SIZE(buffer));
size = len - add;
memcpy(buffer, str + add, size);
}
}
void bufferize(const char *str, size_t len, char flush)
{
total += len;
if (size + len > TAB_SIZE(buffer))
bufferize_too_long(str, len);
else
{
memcpy(buffer + size, str, len);
size += len;
}
if (flush && size)
{
write(1, buffer, size);
size = 0;
}
}
size_t get_total(e_instruction instruction)
{
const size_t ret = total;
if (instruction == RESET)
total = 0;
return (ret);
}
|
C
|
#include <stdio.h>
main (int argc, char *argv[]) {
int i;
printf("There were %d things on the command line\n",argc);
printf("They were:\n");
i = 0;
while (i < argc) {
printf("argv[%d] is %s\n",i,argv[i]);
i++;
}
}
|
C
|
#include <stdio.h>
void main()
{
int n, i, res, m, arr[50], sum = 0;
int size = 0, b[50];
printf("How many number you want to enter ?\n");
res=scanf("%d", &n);
if( n == 0 || n ==1 || n>10 || (res!=1) )
printf("Not right size of array");
else
{
printf("Enter %d Numbers :", n);
for (i = 0; i < n; i++)
{
m=scanf("%d", &arr[i]);
if(m!=1)
printf("Error");
else
{
sum = sum + arr[i];
}
int average = sum / n;
for (i = 0; i < n; i++)
if (arr[i] > average)
{
b[size] = arr[i];
size++;
}
printf("New array: ");
for (i = 0; i < size; i++)
printf("%d ", b[i]);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.