language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <glib.h> #include "../event_queue.h" void test_event_queue_init() { event_queue *eq = event_queue_init(); event_queue_execute(eq, G_MAXUINT); event_queue_free(eq); } typedef struct { guint current_time; guint total; } event_queue_test_struct; void queued(guint time, event_queue_test_struct *status) { g_assert(time <= status->current_time); status->total++; } void test_event_queue_random() { guint idx = 0; GRand* grand = g_rand_new_with_seed(g_test_rand_int()); event_queue *eq = event_queue_init(); event_queue_test_struct status = {0, 0}; for(; idx < 10000; idx++) { guint time = g_test_rand_int_range(5000, 10000); event_queue_enqueue(eq, time, (void (*)(guint, void *))queued, &status); } idx = 0; guint next = 0; while(next != G_MAXUINT) { status.current_time = next; next = event_queue_execute(eq, next); } g_assert(status.total == 10000); event_queue_free(eq); } //void event_queue_enqueue(event_queue *queue, guint time, void (*func)(void *), void *data); //guint event_queue_execute(event_queue *equeue, guint time); void test_event_queue() { g_test_add_func("/event_queue/init", test_event_queue_init); g_test_add_func("/event_queue/random", test_event_queue_random); }
C
#ifndef STRUCTS_H # define STRUCTS_H # include <stdlib.h> typedef char t_bool; typedef struct s_node { void *data; struct s_node *next; } t_node; typedef struct s_btree { void *data; struct s_btree *r; struct s_btree *l; } t_btree; typedef struct s_file { int fd; char *name; } t_file; typedef struct s_array { int *arr; int size; } t_array; typedef struct s_token { char *tok; //"cd" ";" char *type; //BUILTIN, ARG, SEP, "PIPE" size_t *len; int order; //...?? t_bool quoted; } t_token; /* ** -tokens: list of command tokens ["ls", "-la", "file"] ** - ** -ret return value of the command, ** if ret == ZERO AND sep == "&&" then stop executing. */ typedef struct s_command { char *cmd; t_node *tokens; t_bool ret; t_bool sep; } t_command; typedef struct s_input { char *line; size_t len; size_t i; } t_input; typedef struct s_env { int argc; char **argv; char **env_var; t_input *input; t_node *tokens; t_node *commands; //[, , , ], [, , , ] //char **builtins; } t_env; #endif
C
#include<stdio.h> int main(){ int n; scanf("%d",&n); while(n != 0){ unsigned long total = 0; while(n > 0){ total += n * n; --n; } printf("%lu\n", total); scanf("%d",&n); } return 0; }
C
#include <common.h> int main(int argc, char **argv) { if (argc != 3) errx(-1, "%s <old filename> <new filename>\n", argv[0]); char *old = argv[1]; char *new = argv[2]; int ret; if ((ret = rename(old, new)) < 0) err(ret, "rename"); return 0; }
C
#include <errno.h> #include <string.h> #include <stdlib.h> #include <util.h> #include <pat.ih> int thr_alloc(struct thread *thr[static 2]) { struct thread *ret; ret = calloc(1, sizeof *ret); if (!ret) return ENOMEM; thr[0] = ret; thr[1] = ret; return 0; } int thr_cmp(struct thread *lt, struct thread *rt) { size_t i; size_t min; ptrdiff_t cmp; if (!lt && !rt) return 0; if (!lt) return -1; if (!rt) return 1; min = umin(lt->nmat, rt->nmat); for (i = 0; i < min; ++i) { cmp = ucmp(lt->mat[i].off, rt->mat[i].off); if (cmp) return -cmp; cmp = ucmp(lt->mat[i].ext, rt->mat[i].ext); if (cmp) return cmp; } return 0; } int thr_init(struct thread *th, struct ins *prog) { th->ip = prog; th->nmat = 0; return 0; } void thr_fork(struct thread *dst, struct thread *src) { dst->ip = src->ip; dst->nmat = src->nmat; memcpy(dst->mat, src->mat, sizeof dst->mat); } void thr_free(struct thread *th) { struct thread *a; while (th) a = th, th = a->next, free(a); } void thr_mv(struct thread *dst[static 2], struct thread **src) { struct thread *tmp; tmp = src[0]; src[0] = src[0]->next; tmp->next = dst[0]; dst[0] = tmp; }
C
#include<stdio.h> int main(){ char* tab[5][5]={{"DUFOURD","BERTRAND","BOB","BOULANGER","JAMES"},{"pierre","marley","jean","loic","alex"},{"5 rue du pic","6 rue du coeur","7 rue du carreaux","8 rue du trèfle","9 rue de l'as"},{"18","12","15","14","16"},{"20","10","18","8","19"}}; int j=0; int i=0; for(i=0;i<5;i++){ for(j=0;j<5;j++) {printf("\n %s",tab[j][i]); }printf("\n"); } return(0); }
C
/** * See Copyright Notice in picrin.h */ #include "picrin.h" #include "picrin/dict.h" #include "picrin/cont.h" #include "picrin/pair.h" static int xh_value_hash(const void *key, void *data) { union { double f; int i; } u; pic_value val = *(pic_value *)key; int hash, vtype; UNUSED(data); vtype = pic_vtype(val); switch (vtype) { default: hash = 0; break; case PIC_VTYPE_SYMBOL: hash = pic_sym(val); break; case PIC_VTYPE_FLOAT: u.f = pic_float(val); hash = u.i; break; case PIC_VTYPE_INT: hash = pic_int(val); break; case PIC_VTYPE_HEAP: hash = (int)(intptr_t)pic_ptr(val); break; } return hash + vtype; } static int xh_value_equal(const void *key1, const void *key2, void *pic) { return pic_equal_p(pic, *(pic_value *)key1, *(pic_value *)key2); } static void xh_init_value(pic_state *pic, xhash *x) { xh_init_(x, sizeof(pic_value), sizeof(pic_value), xh_value_hash, xh_value_equal, pic); } static inline xh_entry * xh_get_value(xhash *x, pic_value key) { return xh_get_(x, &key); } static inline xh_entry * xh_put_value(xhash *x, pic_value key, void *val) { return xh_put_(x, &key, val); } static inline void xh_del_value(xhash *x, pic_value key) { xh_del_(x, &key); } struct pic_dict * pic_make_dict(pic_state *pic) { struct pic_dict *dict; dict = (struct pic_dict *)pic_obj_alloc(pic, sizeof(struct pic_dict), PIC_TT_DICT); xh_init_value(pic, &dict->hash); return dict; } pic_value pic_dict_ref(pic_state *pic, struct pic_dict *dict, pic_value key) { xh_entry *e; e = xh_get_value(&dict->hash, key); if (! e) { pic_errorf(pic, "element not found for a key: ~s", key); } return xh_val(e, pic_value); } void pic_dict_set(pic_state *pic, struct pic_dict *dict, pic_value key, pic_value val) { UNUSED(pic); xh_put_value(&dict->hash, key, &val); } size_t pic_dict_size(pic_state *pic, struct pic_dict *dict) { UNUSED(pic); return dict->hash.count; } bool pic_dict_has(pic_state *pic, struct pic_dict *dict, pic_value key) { UNUSED(pic); return xh_get_value(&dict->hash, key) != NULL; } void pic_dict_del(pic_state *pic, struct pic_dict *dict, pic_value key) { if (xh_get_value(&dict->hash, key) == NULL) { pic_errorf(pic, "no slot named ~s found in dictionary", key); } xh_del_value(&dict->hash, key); } static pic_value pic_dict_make_dictionary(pic_state *pic) { struct pic_dict *dict; pic_get_args(pic, ""); dict = pic_make_dict(pic); return pic_obj_value(dict); } static pic_value pic_dict_dictionary(pic_state *pic) { struct pic_dict *dict; pic_value *argv; size_t argc, i; pic_get_args(pic, "*", &argc, &argv); dict = pic_make_dict(pic); for (i = 0; i < argc; i += 2) { pic_dict_set(pic, dict, argv[i], argv[i+1]); } return pic_obj_value(dict); } static pic_value pic_dict_dictionary_p(pic_state *pic) { pic_value obj; pic_get_args(pic, "o", &obj); return pic_bool_value(pic_dict_p(obj)); } static pic_value pic_dict_dictionary_ref(pic_state *pic) { struct pic_dict *dict; pic_value key; pic_get_args(pic, "do", &dict, &key); if (pic_dict_has(pic, dict, key)) { return pic_values2(pic, pic_dict_ref(pic, dict, key), pic_true_value()); } else { return pic_values2(pic, pic_none_value(), pic_false_value()); } } static pic_value pic_dict_dictionary_set(pic_state *pic) { struct pic_dict *dict; pic_value key, val; pic_get_args(pic, "doo", &dict, &key, &val); pic_dict_set(pic, dict, key, val); return pic_none_value(); } static pic_value pic_dict_dictionary_del(pic_state *pic) { struct pic_dict *dict; pic_value key; pic_get_args(pic, "do", &dict, &key); pic_dict_del(pic, dict, key); return pic_none_value(); } static pic_value pic_dict_dictionary_size(pic_state *pic) { struct pic_dict *dict; pic_get_args(pic, "d", &dict); return pic_size_value(pic_dict_size(pic, dict)); } static pic_value pic_dict_dictionary_to_alist(pic_state *pic) { struct pic_dict *dict; pic_value item, alist = pic_nil_value(); xh_entry *it; pic_get_args(pic, "d", &dict); for (it = xh_begin(&dict->hash); it != NULL; it = xh_next(it)) { item = pic_cons(pic, xh_key(it, pic_value), xh_val(it, pic_value)); pic_push(pic, item, alist); } return pic_reverse(pic, alist); } static pic_value pic_dict_alist_to_dictionary(pic_state *pic) { struct pic_dict *dict; pic_value alist, e; pic_get_args(pic, "o", &alist); dict = pic_make_dict(pic); pic_for_each (e, pic_reverse(pic, alist)) { pic_dict_set(pic, dict, pic_car(pic, e), pic_cdr(pic, e)); } return pic_obj_value(dict); } static pic_value pic_dict_dictionary_to_plist(pic_state *pic) { struct pic_dict *dict; pic_value plist = pic_nil_value(); xh_entry *it; pic_get_args(pic, "d", &dict); for (it = xh_begin(&dict->hash); it != NULL; it = xh_next(it)) { pic_push(pic, xh_key(it, pic_value), plist); pic_push(pic, xh_val(it, pic_value), plist); } return pic_reverse(pic, plist); } static pic_value pic_dict_plist_to_dictionary(pic_state *pic) { struct pic_dict *dict; pic_value plist, e; pic_get_args(pic, "o", &plist); dict = pic_make_dict(pic); for (e = pic_reverse(pic, plist); ! pic_nil_p(e); e = pic_cddr(pic, e)) { pic_dict_set(pic, dict, pic_cadr(pic, e), pic_car(pic, e)); } return pic_obj_value(dict); } void pic_init_dict(pic_state *pic) { pic_defun(pic, "make-dictionary", pic_dict_make_dictionary); pic_defun(pic, "dictionary?", pic_dict_dictionary_p); pic_defun(pic, "dictionary", pic_dict_dictionary); pic_defun(pic, "dictionary-ref", pic_dict_dictionary_ref); pic_defun(pic, "dictionary-set!", pic_dict_dictionary_set); pic_defun(pic, "dictionary-delete!", pic_dict_dictionary_del); pic_defun(pic, "dictionary-size", pic_dict_dictionary_size); pic_defun(pic, "dictionary->alist", pic_dict_dictionary_to_alist); pic_defun(pic, "alist->dictionary", pic_dict_alist_to_dictionary); pic_defun(pic, "dictionary->plist", pic_dict_dictionary_to_plist); pic_defun(pic, "plist->dictionary", pic_dict_plist_to_dictionary); }
C
#include "ADC_Fun.h" #include "Delay_Fun.h" #include "intrins.h" #include "Stc_Math.h" /*---------------------------- Initial ADC sfr ----------------------------*/ void InitADC(unsigned char Port) { unsigned int i; P1ASF = Port; //Open 8 channels ADC function ADC_RES = 0; //Clear previous result ADC_CONTR = ADC_POWER | ADC_SPEEDLL; for(i=0;i<16;i++) //ADC power-on and delay 16ms { Delay1ms(); } } /*---------------------------- Get ADC result ----------------------------*/ unsigned char GetADCResult(unsigned char ch) { unsigned char I; //I = ADC_CONTR; ADC_CONTR = ADC_POWER | ADC_SPEEDLL| ch | ADC_START; //ADC_POWER | ADC_SPEEDLL | _nop_(); //Must wait before inquiry _nop_(); _nop_(); _nop_(); while (!(ADC_CONTR & ADC_FLAG));//Wait complete flag ADC_CONTR &= ~ADC_FLAG; //Close ADC I = ADC_RES; ADC_RES = 0; return I; //Return ADC result } /*---------------------------- Get Vin(1000) 8λ ȷС3λ ----------------------------*/ unsigned int Vin_8(unsigned char ADCResult,unsigned int VREF) { unsigned long Vin; EA = 0; //ʽVin = Vcc(5)*ADCResult/256 Vin = ((unsigned long)ADCResult*VREF*10)>>8; EA = 1; return (unsigned int)Vin; } /*---------------------------------------- Get Vin(1000) 8λ ȷС3λ ַ ---------------------------------------- void GetVinString(unsigned char ADCResult,unsigned char* VinString) { unsigned int Vin; unsigned char i; Vin = Vin_8(ADCResult,VREF); EA = 0; WordToStr(Vin,VinString,4); EA = 1; for(i=4;i>=2;i--) { VinString[i] = VinString[i-1]; } VinString[1] = '.'; } */
C
/************************************************************************* DCencoder.c Author: Josiah Snarr Date: April 17, 2015 clientProtocal.c contains the functions to control the client handling of incoming commands through RS232 *************************************************************************/ #include "derivative.h" #include "clientProtocal.h" #include "SCI.h" char static packBuff[BUFFER_SIZE]; int static index = 0; int static unsigned numPacket = 0; //Number of packets int static unsigned packOff[PACKET_COUNT]; //Packet offset //Get number of packets left int unsigned nbrPackets(void) { return numPacket; } //Get next packet char * nextPacket(void) { numPacket--; return packBuff + packOff[0]; } /************************************************************************* Author: Josiah Snarr Date: April 18, 2015 the sendPacket function sends a packet through RS232 to a host *************************************************************************/ void sendSinglePacket(char dataSend) { putcSCI('<'); putcSCI(dataSend); putcSCI('>'); } /************************************************************************* Author: Josiah Snarr Date: April 18, 2015 the sendPing function sends a ping through RS232 to a host *************************************************************************/ void sendPing(void) { sendSinglePacket('P'); } /************************************************************************* Author: Josiah Snarr Date: April 18, 2015 the sciReceive interrupt handles incomming data and places it into the bound buffer *************************************************************************/ interrupt VectorNumber_Vsci void sciReceive(void) { char static unsigned started = 0; char const newData = SCIDRL; if(IS_SET(SCISR1, SCISR1_RDRF_MASK)) //If received data { if(newData == FIRST_CHAR) //Check if start of packet { packBuff[index] = newData; started++; packOff[numPacket] = index++; } else if(newData == LAST_CHAR) { if(started > 0) //Otherwise garbage { //Full packet packBuff[index] = newData; numPacket++; started = 0; //Add charachter to separate packet packBuff[++index] = SPACER; index++; } } else //Non-edge of packet { if(started > 0) //Otherwise garbage { packBuff[index++] = newData; } } } }
C
//////////////////////////////////////////////////////////////////////////////// // vvprintf.c - printf-like backend // // Written by Rich Rademacher, UWaterloo/IQC // October 2018 //////////////////////////////////////////////////////////////////////////////// #include <types.h> #include <algorithm/vvprintf.h> #include <stdarg.h> /* * Lowercase hex table */ const s8 lower_hex_tab[] = "0123456789abcdef"; /* * uppercase hex table */ const s8 upper_hex_tab[] = "0123456789ABCDEF"; /* * decimal table */ const s8 dec_tab[] = "0123456789"; /* * power-of-tens table */ const s32 dec_pwr_table[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; #define LAST_DEC_PWR_IDX (sizeof(dec_pwr_table)/sizeof(dec_pwr_table[0]) - 1) /* * vvprintf() - printf backend * * vputc - handle to function that puts a single character * vp_state - state variable for vputc * fmt - null-termintated format specifier * ... - variable arg list */ s32 vvprintf( s32 (*vputc)(s8 c, void* state), void* vp_state, s8* fmt, ...) { s8 c; s32 result = 0; enum {IDLE, ESCAPE_1, ESCAPE_N} state = IDLE; s8 pad_char; s32 leading_pad, trailing_pad; s32 has_dot; s32 has_plus; s8* pvalue; s32 value; double dvalue; va_list ap; // start the variable argument list va_start(ap, fmt); while(1) { // get next format character c = *fmt++; // null termination if( 0 == c ) break; // not in escaped state? look for start of token if( IDLE == state ) { if('%' == c) { pad_char = ' '; leading_pad = 0; trailing_pad = 0; has_dot = 0; has_plus = 0; state = ESCAPE_1; } else { result += (*vputc)(c, vp_state); } } // first character of escape code else if( ESCAPE_1 == state ) { switch(c) { case ' ': pad_char = ' '; state = ESCAPE_N; break; case '0': pad_char = '0'; state = ESCAPE_N; break; case '.': has_dot = 1; state = ESCAPE_N; break; case '+': has_plus = 1; state = ESCAPE_N; break; case 'c': value = va_arg(ap, s8); result += (*vputc)((s8) value, vp_state); state = IDLE; break; case 's': pvalue = va_arg(ap, s8*); result += vvputs(vputc, vp_state, pvalue, leading_pad); state = IDLE; break; case 'x': value = va_arg(ap, s32); result += vvitoh(vputc, vp_state, value, leading_pad, pad_char, trailing_pad, lower_hex_tab); state = IDLE; break; case 'X': value = va_arg(ap, s32); result += vvitoh(vputc, vp_state, value, leading_pad, pad_char, trailing_pad, upper_hex_tab); state = IDLE; break; case 'i': value = va_arg(ap, s32); result += vvitoa(vputc, vp_state, value, has_plus, leading_pad, pad_char); state = IDLE; break; case 'e': dvalue = va_arg(ap, double); result += vvdtoa_e(vputc, vp_state, dvalue); state = IDLE; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': leading_pad = leading_pad*10 + (c - '0'); state = ESCAPE_N; break; default: state = IDLE; } } // first character of escape code else if( ESCAPE_N == state ) { switch(c) { case 'c': value = va_arg(ap, s8); result += (*vputc)((s8) value, vp_state); state = IDLE; break; case 's': pvalue = va_arg(ap, s8*); result += vvputs(vputc, vp_state, pvalue, leading_pad); state = IDLE; break; case 'x': value = va_arg(ap, s32); result += vvitoh(vputc, vp_state, value, leading_pad, pad_char, trailing_pad, lower_hex_tab); state = IDLE; break; case 'X': value = va_arg(ap, s32); result += vvitoh(vputc, vp_state, value, leading_pad, pad_char, trailing_pad, upper_hex_tab); state = IDLE; break; case 'i': value = va_arg(ap, s32); result += vvitoa(vputc, vp_state, value, has_plus, leading_pad, pad_char); state = IDLE; break; case 'e': dvalue = va_arg(ap, double); result += vvdtoa_e(vputc, vp_state, dvalue); state = IDLE; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': leading_pad = leading_pad*10 + (c - '0'); state = ESCAPE_N; break; default: state = IDLE; } } } return result; } /* * vvitoh() virtual ascii to hex converter * * vputc - putc function driver * vp_state - putc state variable * value - value to convert * leading_pad - minium number of digits leading * leading_char - character to pad leading with * trailing_pad - minimum number of digits to trail * table - encoding table to use (upper or lower case) * */ s32 vvitoh( s32 (*vputc)(s8, void*), void* vp_state, u32 value, s32 leading_pad, s8 leading_char, s32 trailing_pad, const s8* table) { s32 n; s8 c; s32 result = 0; s32 n_digits = 0; u32 p16 = 0x10000000; // get expected number of digits (special case for zero) if(0 == value) { n_digits = 1; } else { for(n_digits = 8; n_digits > 0; n_digits--) { if(value >= p16) break; p16 >>= 4; } } // do leading pad for(n=leading_pad; n > n_digits; n--) { result += (*vputc)( leading_char, vp_state ); } // do digits for(n=n_digits-1; n >= 0; n--) { c = table[ (value >> (n*4)) & 0xf ]; // get digits result += (*vputc)( c, vp_state ); // call putc() } // do trailing pad for(; result < trailing_pad; ) { result += (*vputc)(' ', vp_state); } return result; } /* * vvputs() - virtualizes the puts() function * * vputc - putc() driver * vp_state - state variable for putc() * str - string to put */ s32 vvputs( s32 (*vputc)(s8, void*), void* vp_state, s8* str, s32 leading_pad ) { s8 c; s32 result = 0; s32 len; s8* p = str; // pad leading if(leading_pad != 0) { // find string length for(p=str, len=leading_pad; '\0' != *p; p++) len--; // apply padding character (space) for(; len > 0; len--) result += (*vputc)(' ', vp_state); } // copy string p = str; while(1) { // get new character c = *p++; // null termination ends function if('\0' == c) return result; // place character result += (*vputc)(c, vp_state); } } /* * vvitoa() - integer to ascii * * vputc - putc() driver * vp_state - putc() state variable * value - value * plus_sign - mandatory plus sign * leading_pad - number of pad characters * pad_char - pad characters * */ s32 vvitoa(s32 (*vputc)(s8, void*), void* vp_state, s32 value, s32 plus_sign, s32 leading_pad, s8 pad_char) { s32 radix = LAST_DEC_PWR_IDX; s32 m; s32 result = 0; s32 n; s32 n_digits = 0; // pos/neg logic if( value < 0 ) { result += (*vputc)('-', vp_state); value = 0-value; n_digits++; } else if( plus_sign ) { result += (*vputc)('+', vp_state); n_digits++; } // calculate number of digits if( 0 == value ) { n_digits++; } else { for(radix=LAST_DEC_PWR_IDX; radix >=0; radix--) { if( value >= dec_pwr_table[ radix ] ) { n_digits += radix; break; } } } // do pad character for( ; leading_pad > n_digits; leading_pad-- ) { result += (*vputc)(pad_char, vp_state); } // print each power-of-10 digit if( 0 == value ) { result += (*vputc)('0', vp_state); } else { for( ; radix >= 0; radix-- ) { // find multiplicand at this radix m = value / dec_pwr_table[ radix ]; // printt multiplicand as ascii digit result += (*vputc)( dec_tab[m], vp_state ); // remainder is result of multiplication value -= m * dec_pwr_table[ radix ]; } } return result; } /* * vvdtoa_e() - double-precision to ascii in "e" format * */ s32 vvdtoa_e( s32 (*vputc)(s8, void*), void* vp_state, double value ) { union { double d; u32 u; struct { u32 mant: 23; s32 exp: 8; u32 sign: 1; } ieee; } dvalue; s32 result = 0; s8 exp; s32 mant; s32 n; s32 ipart; s32 fpart; s8 c; // decode ieee764 value dvalue.d = value; exp = dvalue.ieee.exp - 127; // normalize the signed mantissa if( 0 == dvalue.ieee.exp ) mant = dvalue.ieee.mant; // denormalized numbers have else mant = (1 << 24) + dvalue.ieee.mant; // add implicit "1" from IEEE standard // do sign if(dvalue.ieee.sign) result += (*vputc)('-', vp_state); // do integer portion ipart = (mant << exp ) >> 24; c = dec_tab[ ipart ]; result += (*vputc)( c, vp_state ); result += (*vputc)( '.', vp_state ); // do fractional part fpart = mant - ((c - '0') << 24); for(n=exp-24; n>0; n++) { } return result; }
C
#include <stdlib.h> #include <stdio.h> int main(void) { char *env_variable; env_variable = getenv("USER"); if (NULL!=env_variable) printf("USER: %s\n", env_variable); env_variable = getenv("SHELL"); if (NULL!=env_variable) printf("SHELL: %s\n", env_variable); env_variable = getenv("PATH"); if (NULL!=env_variable) printf("PATH: %s\n", env_variable); return 0; }
C
#include "daed_builtins.h" int main(void) { double T, a, b, N, p, V; double k; double res; T = DBETWEEN_WITH_ULP(300.0, 300.0); a = DBETWEEN_WITH_ULP(0.401, 0.401); b = DBETWEEN_WITH_ULP(42.7e-6, 42.7e-6); N = DBETWEEN_WITH_ULP(1000.0, 1000.0); p = DBETWEEN_WITH_ULP(3.5e7, 3.5e7); V = DBETWEEN_WITH_ULP(0.1, 0.5); k = 1.3806503e-23; SUBDIV_BEGIN(V, 20) res = (p + a * (N / V) * (N / V)) * (V - N * b) - k * N * T; SUBDIV_END DSENSITIVITY(res); return 0; }
C
// splitStr3.c // author: Sasha (Alexandre) Avreline, UBC BCS Tutor, Fall 2019 #include <stdio.h> #include <stdlib.h> #include <string.h> void split_str(char *input_str, char token, char ***components_addr) { int i = 0; char *input_str_copy = strdup(input_str); const char *token_string = (char[]){token, '\0'}; char **components = *components_addr; char *result = strtok(input_str_copy, token_string); while (result) { components[i] = strdup(result); components = realloc(components, (++i + 1) * sizeof(char *)); result = strtok(NULL, token_string); } components[i] = NULL; *components_addr = components; free(input_str_copy); } int main() { char *str = "www.example.com"; char token = '.'; char **components = malloc(sizeof(char *)); char ***components_addr = &components; split_str(str, token, components_addr); printf("Input string is %s\n", str); char **components_pnt = components; while (*components) printf("Component is %s\n", *components++); // free memory components = components_pnt; while (*components) free(*components++); free(components_pnt); }
C
#include <stddef.h> #include <string.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <libgen.h> extern char **environ; int main(int argc, char *argv[]) { char * pipfile; int pipfile_len; { char * dir; { /* argv[1] is the path to the script file */ char * s = realpath(argv[1], NULL); if (s == NULL) { perror("realpath"); exit(EXIT_FAILURE); } dir = dirname(s); free(s); } int max_depth; { char * s = getenv("PIPENV_MAX_DEPTH"); if (s != NULL) { max_depth = atoi(s); } else { max_depth = 3; } } while (true) { size_t dir_len = strlen(dir); char * buffer = malloc(dir_len + 9); memcpy(buffer, dir, dir_len); memcpy(buffer + dir_len, "/Pipfile", 9); if (access(buffer, F_OK) != -1) { pipfile = buffer; pipfile_len = dir_len + 8; break; } free(buffer); if (max_depth == 0) { // couldn't find Pipfile pipfile = NULL; pipfile_len = 0; break; } --max_depth; dir = dirname(dir); } } /* construct new_argv */ char **new_argv; { new_argv = malloc((argc + 4) * sizeof(char *)); char ** p = new_argv; *p++ = "/usr/bin/env"; if (pipfile != NULL) { *p++ = "pipenv"; *p++ = "run"; } *p++ = "python"; int i; for(i=1; i!=argc; ++i) { *p++ = argv[i]; } *p++ = NULL; } /* construct new_envp */ char **new_envp; { /* get length of environ */ int len; { char **p; for (p=environ, len=0; *p!=NULL; ++p, ++len) {} } new_envp = malloc((len+2) * sizeof(char*)); memcpy(new_envp, environ, (len+1) * sizeof(char*)); char **p = new_envp + len; if (pipfile != NULL) { char *e = malloc(16+pipfile_len); memcpy(e, "PIPENV_PIPFILE=", 15); memcpy(e+15, pipfile, pipfile_len+1); *p++ = e; } *p++ = NULL; } execve(new_argv[0], new_argv, new_envp); /* execvpe() only returns on error */ perror("execve"); exit(EXIT_FAILURE); }
C
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdlib.h> #include <unistd.h> #include <strings.h> #include <string.h> #include <math.h> #include <sys/time.h> void error(char *msg) { perror(msg); exit(0); } int main(int argc, char *argv[]) { int sockfd, portno, n, acknowledged; struct sockaddr_in serv_addr; struct hostent *server; int size = (int)pow(10,5); int longBufferLong, sliceLen; double timetick; int sizeData = 65536; unsigned char intStr[sizeof(int)]; unsigned char ackInt[sizeof(int)]; char buffer[size]; char data[size+sizeof(int)]; int longBuffer; if (argc < 3) { fprintf(stderr,"usage %s hostname port\n", argv[0]); exit(0); } portno = atoi(argv[2]); // create socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); // loockup ip address server = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } // fill struct bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); // connect socket if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); // initialize sending buffer bzero(buffer,size); for (int i=0; i<size-1;i++){ buffer[i] = 'a'; } longBufferLong = strlen(buffer); // prepare the data to send longBuffer = htonl(longBufferLong); // send the total size of the buffer n = write(sockfd,&longBuffer,sizeof(longBuffer)); if (n < 0) error("ERROR writing to socket"); int sent = 0; while (sent<longBufferLong){ intStr[0] = (sent>>24) & 0xFF; intStr[1] = (sent>>16) & 0xFF; intStr[2] = (sent>>8) & 0xFF; intStr[3] = sent & 0xFF; memcpy(data, intStr, sizeof(intStr)); memcpy(data+sizeof(intStr), buffer+sent, longBufferLong-sent); if(longBufferLong-sent >= sizeData){ n = write(sockfd,data,sizeData+sizeof(int)); }else{ n = write(sockfd,data,longBufferLong-sent+sizeof(int)); } if (n < 0) error("ERROR writing to socket"); n = read(sockfd, &ackInt, sizeof(int)); if (n < 0) error("ERROR receiving data"); acknowledged = (ackInt[0] << 24) | (ackInt[1] << 16) | (ackInt[2] << 8) | ackInt[3]; printf("ack %d\n", acknowledged); sent += acknowledged; printf("sent %d\n", sent); } return 0; }
C
/************************************************************************* > File Name: test.c > Author: > Mail: > Created Time: 2018年08月21日 星期二 16时14分35秒 ************************************************************************/ #include "../include/rsa.h" void creatRsa(int* e , int* n , int* bytes , int* d) { int p, q, phi; srand(time(NULL)); while(1) { p = randPrime(SINGLE_MAX); q = randPrime(SINGLE_MAX); *n = p * q; if(*n < 128) { printf("Modulus is less than 128, cannot encode single bytes. Trying again ... "); exit(-1); } else { break; } } if(*n >> 21) { *bytes = 3; } else if(*n >> 14) { *bytes = 2; } else { *bytes = 1; } phi = (p - 1) * (q - 1); *e = randExponent(phi, EXPONENT_MAX); *d = inverse(*e, phi); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "ptable.h" int main(int argc, char *argv[]) { extern int debug; int printall = 0; int opt; char *eep = NULL; char *profile = "eep.xml"; while ((opt = getopt(argc, argv, "ade:f:")) != EOF) { switch (opt) { case 'a': printall++; break; case 'd': debug++; break; case 'e': eep = optarg; break; case 'f': profile = optarg; break; default: /* '?' */ fprintf(stderr, "Usage: %s: [-a][-d][-e eep][-f eepfile]\n", argv[0]); exit(EXIT_FAILURE); break; } } //printf("optind=%d argc=%d\n", optind, argc); if (argv[optind] != NULL) { profile = argv[optind]; } if (!InitEep(profile)) { fprintf(stderr, "InitEep error\n"); exit(1); } if (printall) { PrintEepAll(); } else if (eep) { PrintEep(eep); } //_D printf("end.\n"); return 0; }
C
/* * Network console server * inf138575 * PUT NSK2018 */ #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdio.h> #define BUF_SIZE 1024 #define NUM_THREADS 5 //data structure which will be passed to thead struct thread_data_t { int desc_new; }; //pointer to funcion describing thread behavior void *ThreadBehavior(void *t_data) { struct thread_data_t *th_data = (struct thread_data_t*)t_data; //access to stucture's filds: (*th_data).field //sending to server section char buffer_local[BUF_SIZE]; while (fgets(buffer_local, BUF_SIZE, stdin) >0) //fget returns -1 when problem occurs write ((*th_data).desc_new, buffer_local, strlen(buffer_local)); //close thread pthread_exit(NULL); } //connection handler void handleConnection(int connection_socket_descriptor) { printf("Connecting...\n"); //result of creating a new thread int create_result = 0; //thread descriptor pthread_t thread1; //data which will be passed to thread struct thread_data_t t_data; t_data.desc_new = connection_socket_descriptor; create_result = pthread_create(&thread1, NULL, ThreadBehavior, (void *)&t_data); if (create_result){ printf("Error while creating thread, error code: %d\n", create_result); exit(-1); } //reading server replys section char buf[BUF_SIZE]; while(read(connection_socket_descriptor, buf, BUF_SIZE) >0) { buf[strlen(buf)] = '\0'; printf("%s", buf); fflush(stdout); memset(buf, 0, BUF_SIZE); } } int main (int argc, char *argv[]) { int connection_socket_descriptor; int connect_result; struct sockaddr_in server_address; struct hostent* server_host_entity; if (argc != 3) { fprintf(stderr, "Syntax error: %s server_name port_number\n", argv[0]); exit(1); } server_host_entity = gethostbyname(argv[1]); if (! server_host_entity) { fprintf(stderr, "%s: Could not reslove hostname.\n", argv[0]); exit(1); } connection_socket_descriptor = socket(PF_INET, SOCK_STREAM, 0); if (connection_socket_descriptor < 0) { fprintf(stderr, "%s: Could not create a new socket.\n", argv[0]); exit(1); } memset(&server_address, 0, sizeof(struct sockaddr)); server_address.sin_family = AF_INET; memcpy(&server_address.sin_addr.s_addr, server_host_entity->h_addr, server_host_entity->h_length); server_address.sin_port = htons(atoi(argv[2])); connect_result = connect(connection_socket_descriptor, (struct sockaddr*)&server_address, sizeof(struct sockaddr)); if (connect_result < 0) { fprintf(stderr, "%s: Could not make a connection with server: %s:%i.\n", argv[0], argv[1], atoi(argv[2])); exit(1); } handleConnection(connection_socket_descriptor); close(connection_socket_descriptor); printf("Connection closed\n"); return 0; }
C
/********************************************************************************* * Smith–Waterman algorithm * Purpose: Local alignment of nucleotide or protein sequences * Authors: Daniel Holanda, Hanoch Griner, Taynara Pinheiro * * Compilation: gcc omp_smithW.c -o omp_smithW -fopenmp -DDEBUG // debugging mode * gcc omp_smithW.c -O3 -o omp_smithW -fopenmp // production run * Execution: ./omp_smithW <number_of_col> <number_of_rows> * * Updated by C. Liao, Jan 2nd, 2019 *********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include <time.h> #include <assert.h> #include <stdbool.h> // C99 does not support the boolean data type #include "parameters.h" /*-------------------------------------------------------------------- * Text Tweaks */ #define RESET "\033[0m" #define BOLDRED "\033[1m\033[31m" /* Bold Red */ /* End of text tweaks */ /*-------------------------------------------------------------------- * Constants */ #define PATH -1 #define NONE 0 #define UP 1 #define LEFT 2 #define DIAGONAL 3 /* End of constants */ /*-------------------------------------------------------------------- * Helpers */ #define min(x, y) (((x) < (y)) ? (x) : (y)) #define max(a,b) ((a) > (b) ? a : b) // #define DEBUG /* End of Helpers */ /*-------------------------------------------------------------------- * Functions Prototypes */ void similarityScore(long long int i, long long int j, int* H, int* P, long long int* maxPos); // without omp critical: how to conditionalize it? void similarityScore2(long long int i, long long int j, int* H, int* P, long long int* maxPos); int matchMissmatchScore(long long int i, long long int j); void backtrack(int* P, long long int maxPos); void printMatrix(int* matrix); void printPredecessorMatrix(int* matrix); void generate(void); long long int nElement(long long int i); void calcFirstDiagElement(long long int i, long long int *si, long long int *sj); /* End of prototypes */ /*-------------------------------------------------------------------- * Global Variables */ bool useBuiltInData=true; //Defines size of strings to be compared long long int m = 8 ; //Columns - Size of string a long long int n = 9; //Lines - Size of string b // the generated scoring matrix's size is m++ and n++ later to have the first row/column as 0s. //Defines scores int matchScore = 3; int missmatchScore = -3; int gapScore = -2; //Strings over the Alphabet Sigma char *a, *b; /* End of global variables */ /*-------------------------------------------------------------------- * Function: main */ int main(int argc, char* argv[]) { // thread_count is no longer used int thread_count; if (argc==3) { m = strtoll(argv[1], NULL, 10); n = strtoll(argv[2], NULL, 10); useBuiltInData = false; } //#ifdef DEBUG if (useBuiltInData) printf ("Using built-in data for testing ..\n"); printf("Problem size: Matrix[%lld][%lld], FACTOR=%d CUTOFF=%d\n", n, m, FACTOR, CUTOFF); //#endif //Allocates a and b a = (char*) malloc(m * sizeof(char)); b = (char*) malloc(n * sizeof(char)); //Because now we have zeros m++; n++; //Allocates similarity matrix H int *H; H = (int *) calloc(m * n, sizeof(int)); //Allocates predecessor matrix P int *P; P = (int *)calloc(m * n, sizeof(int)); if (useBuiltInData) { //Uncomment this to test the sequence available at //http://vlab.amrita.edu/?sub=3&brch=274&sim=1433&cnt=1 // OBS: m=11 n=7 // a[0] = 'C'; // a[1] = 'G'; // a[2] = 'T'; // a[3] = 'G'; // a[4] = 'A'; // a[5] = 'A'; // a[6] = 'T'; // a[7] = 'T'; // a[8] = 'C'; // a[9] = 'A'; // a[10] = 'T'; // b[0] = 'G'; // b[1] = 'A'; // b[2] = 'C'; // b[3] = 'T'; // b[4] = 'T'; // b[5] = 'A'; // b[6] = 'C'; // https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm#Example // Using the wiki example to verify the results b[0] = 'G'; b[1] = 'G'; b[2] = 'T'; b[3] = 'T'; b[4] = 'G'; b[5] = 'A'; b[6] = 'C'; b[7] = 'T'; b[8] = 'A'; a[0] = 'T'; a[1] = 'G'; a[2] = 'T'; a[3] = 'T'; a[4] = 'A'; a[5] = 'C'; a[6] = 'G'; a[7] = 'G'; } else { //Gen random arrays a and b generate(); } //Start position for backtrack long long int maxPos = 0; //Calculates the similarity matrix long long int i, j; // The way to generate all wavefront is to go through the top edge elements // starting from the left top of the matrix, go to the bottom top -> down, then left->right // total top edge element count = dim1_size + dim2_size -1 //Because now we have zeros ((m-1) + (n-1) - 1) long long int nDiag = m + n - 3; #ifdef DEBUG printf("nDiag=%d\n", nDiag); printf("Number of wavefront lines and their first element positions:\n"); #endif #pragma omp parallel { #pragma omp master { thread_count = omp_get_num_threads(); printf ("Using %d out of max %d threads...", thread_count, omp_get_max_threads()); } } //Gets Initial time double initialTime = omp_get_wtime(); // #pragma omp parallel default(none) shared(H, P, maxPos, nDiag, j) private(i) { for (i = 1; i <= nDiag; ++i) // start from 1 since 0 is the boundary padding { long long int nEle, si, sj; nEle = nElement(i); calcFirstDiagElement(i, &si, &sj); if (nEle>=CUTOFF) { #pragma omp parallel for private(j) shared (nEle, si, sj, H, P, maxPos) for (j = 0; j < nEle; ++j) { // going upwards : anti-diagnol direction long long int ai = si - j ; // going up vertically long long int aj = sj + j; // going right in horizontal similarityScore(ai, aj, H, P, &maxPos); // a critical section is used inside } } else { // serial version, totally avoid parallel region creation. for (j = 0; j < nEle; ++j) { // going upwards : anti-diagnol direction long long int ai = si - j ; // going up vertically long long int aj = sj + j; // going right in horizontal similarityScore2(ai, aj, H, P, &maxPos); // a specialized version without a critical section used inside } } } // for end nDiag } // end omp parallel double finalTime = omp_get_wtime(); printf("\nElapsed time for scoring matrix computation: %f\n", finalTime - initialTime); initialTime = omp_get_wtime(); backtrack(P, maxPos); finalTime = omp_get_wtime(); //Gets backtrack time finalTime = omp_get_wtime(); printf("Elapsed time for backtracking: %f\n", finalTime - initialTime); if (useBuiltInData) { printf ("Verifying results using the builtinIn data: %s\n", (H[n*m-1]==7)?"true":"false"); assert (H[n*m-1]==7); } #ifdef DEBUG printf("\nSimilarity Matrix:\n"); printMatrix(H); printf("\nPredecessor Matrix:\n"); printPredecessorMatrix(P); #endif //Frees similarity matrixes free(H); free(P); //Frees input arrays free(a); free(b); return 0; } /* End of main */ /*-------------------------------------------------------------------- * Function: nElement * Purpose: Calculate the number of i-diagonal's elements * i value range 1 to nDiag. we inclulde the upper bound value. 0 is for the padded wavefront, which is ignored. */ long long int nElement(long long int i) { if (i < m && i < n) { // smaller than both directions //Number of elements in the diagonal is increasing return i; } else if (i < max(m, n)) { // smaller than only one direction //Number of elements in the diagonal is stable long int min = min(m, n); // the longer direction has the edge elements, the number is the smaller direction's size return min - 1; } else { //Number of elements in the diagonal is decreasing long int min = min(m, n); return 2 * min - i + llabs(m - n) - 2; } } /*-------------------------------------------------------------------- * Function: calcElement: expect valid i value is from 1 to nDiag. since the first one is 0 padding * Purpose: Calculate the position of (si, sj)-element * n rows, m columns: we sweep the matrix on the left edge then bottom edge to get the wavefront */ void calcFirstDiagElement(long long int i, long long int *si, long long int *sj) { // Calculate the first element of diagonal if (i < n) { // smaller than row count *si = i; *sj = 1; // start from the j==1 since j==0 is the padding } else { // now we sweep horizontally at the bottom of the matrix *si = n - 1; // i is fixed *sj = i - n + 2; // j position is the nDiag (id -n) +1 +1 // first +1 } } /* // understanding the calculation by an example n =6 // row m =2 // col padded scoring matrix n=7 m=3 0 1 2 ------- 0 x x x 1 x x x 2 x x x 3 x x x 4 x x x 5 x x x 6 x x x We should peel off top row and left column since they are the padding the remaining 6x2 sub matrix is what is interesting for us Now find the number of wavefront lines and their first element's position in the scoring matrix total diagnol frontwave = (n-1) + (m-1) -1 // submatrix row+column -1 We use the left most element in each wavefront line as its first element. Then we have the first elements like (1,1), (2,1) (3,1) .. (6,1) (6,2) */ /*-------------------------------------------------------------------- * Function: SimilarityScore * Purpose: Calculate value of scoring matrix element H(i,j) : the maximum Similarity-Score H(i,j) * int *P; the predecessor array,storing which of the three elements is picked with max value */ void similarityScore(long long int i, long long int j, int* H, int* P, long long int* maxPos) { int up, left, diag; //Stores index of element long long int index = m * i + j; //Get element above up = H[index - m] + gapScore; //Get element on the left left = H[index - 1] + gapScore; //Get element on the diagonal diag = H[index - m - 1] + matchMissmatchScore(i, j); //Calculates the maximum int max = NONE; int pred = NONE; /* === Matrix === * a[0] ... a[n] * b[0] * ... * b[n] * * generate 'a' from 'b', if '←' insert e '↑' remove * a=GAATTCA * b=GACTT-A * * generate 'b' from 'a', if '←' insert e '↑' remove * b=GACTT-A * a=GAATTCA */ if (diag > max) { //same letter ↖ max = diag; pred = DIAGONAL; } if (up > max) { //remove letter ↑ max = up; pred = UP; } if (left > max) { //insert letter ← max = left; pred = LEFT; } //Inserts the value in the similarity and predecessor matrixes H[index] = max; P[index] = pred; //Updates maximum score to be used as seed on backtrack #pragma omp critical if (max > H[*maxPos]) { *maxPos = index; } } /* End of similarityScore */ void similarityScore2(long long int i, long long int j, int* H, int* P, long long int* maxPos) { int up, left, diag; //Stores index of element long long int index = m * i + j; //Get element above up = H[index - m] + gapScore; //Get element on the left left = H[index - 1] + gapScore; //Get element on the diagonal diag = H[index - m - 1] + matchMissmatchScore(i, j); //Calculates the maximum int max = NONE; int pred = NONE; /* === Matrix === * a[0] ... a[n] * b[0] * ... * b[n] * * generate 'a' from 'b', if '←' insert e '↑' remove * a=GAATTCA * b=GACTT-A * * generate 'b' from 'a', if '←' insert e '↑' remove * b=GACTT-A * a=GAATTCA */ if (diag > max) { //same letter ↖ max = diag; pred = DIAGONAL; } if (up > max) { //remove letter ↑ max = up; pred = UP; } if (left > max) { //insert letter ← max = left; pred = LEFT; } //Inserts the value in the similarity and predecessor matrixes H[index] = max; P[index] = pred; //Updates maximum score to be used as seed on backtrack if (max > H[*maxPos]) { *maxPos = index; } } /* End of similarityScore2 */ /*-------------------------------------------------------------------- * Function: matchMissmatchScore * Purpose: Similarity function on the alphabet for match/missmatch */ int matchMissmatchScore(long long int i, long long int j) { if (a[j - 1] == b[i - 1]) return matchScore; else return missmatchScore; } /* End of matchMissmatchScore */ /*-------------------------------------------------------------------- * Function: backtrack * Purpose: Modify matrix to print, path change from value to PATH */ void backtrack(int* P, long long int maxPos) { //hold maxPos value long long int predPos; //backtrack from maxPos to startPos = 0 do { if (P[maxPos] == DIAGONAL) predPos = maxPos - m - 1; else if (P[maxPos] == UP) predPos = maxPos - m; else if (P[maxPos] == LEFT) predPos = maxPos - 1; P[maxPos] *= PATH; maxPos = predPos; } while (P[maxPos] != NONE); } /* End of backtrack */ /*-------------------------------------------------------------------- * Function: printMatrix * Purpose: Print Matrix */ void printMatrix(int* matrix) { long long int i, j; printf("-\t-\t"); for (j = 0; j < m-1; j++) { printf("%c\t", a[j]); } printf("\n-\t"); for (i = 0; i < n; i++) { //Lines for (j = 0; j < m; j++) { if (j==0 && i>0) printf("%c\t", b[i-1]); printf("%d\t", matrix[m * i + j]); } printf("\n"); } } /* End of printMatrix */ /*-------------------------------------------------------------------- * Function: printPredecessorMatrix * Purpose: Print predecessor matrix */ void printPredecessorMatrix(int* matrix) { long long int i, j, index; printf(" "); for (j = 0; j < m-1; j++) { printf("%c ", a[j]); } printf("\n "); for (i = 0; i < n; i++) { //Lines for (j = 0; j < m; j++) { if (j==0 && i>0) printf("%c ", b[i-1]); index = m * i + j; if (matrix[index] < 0) { printf(BOLDRED); if (matrix[index] == -UP) printf("↑ "); else if (matrix[index] == -LEFT) printf("← "); else if (matrix[index] == -DIAGONAL) printf("↖ "); else printf("- "); printf(RESET); } else { if (matrix[index] == UP) printf("↑ "); else if (matrix[index] == LEFT) printf("← "); else if (matrix[index] == DIAGONAL) printf("↖ "); else printf("- "); } } printf("\n"); } } /* End of printPredecessorMatrix */ /*-------------------------------------------------------------------- * Function: generate * Purpose: Generate arrays a and b */ void generate() { //Random seed srand(time(NULL)); //Generates the values of a long long int i; for (i = 0; i < m; i++) { int aux = rand() % 4; if (aux == 0) a[i] = 'A'; else if (aux == 2) a[i] = 'C'; else if (aux == 3) a[i] = 'G'; else a[i] = 'T'; } //Generates the values of b for (i = 0; i < n; i++) { int aux = rand() % 4; if (aux == 0) b[i] = 'A'; else if (aux == 2) b[i] = 'C'; else if (aux == 3) b[i] = 'G'; else b[i] = 'T'; } } /* End of generate */ /*-------------------------------------------------------------------- * External References: * http://vlab.amrita.edu/?sub=3&brch=274&sim=1433&cnt=1 * http://pt.slideshare.net/avrilcoghlan/the-smith-waterman-algorithm * http://baba.sourceforge.net/ */
C
#include<stdio.h> #include<string.h> void substring(char [], char[], int, int); int main() { char str[100]="hello"; char strnew[100],strnew1[100]; int len,i; //printf("%s",str); len=strlen(str); //printf("%d",len); for(i=1;i<len-1;i++) { substring(str, strnew, 1, i); printf("%s\n",strnew); } //for(i=len;i>0;--i) for (i = len; i>= 0;i--) { substring(str, strnew1, 1, i); printf("%s\n",strnew1); } return 0; } // C substring function definition void substring(char s[], char sub[], int p, int l) { int c = 0; while (c < l) { sub[c] = s[p+c-1]; c++; } sub[c] = '\0'; }
C
#include <stdbool.h> #include <math.h> bool is_prime(int num){ if(num <= 3) return num > 1; if(num % 2 == 0) return false; if(num % 3 == 0) return false; int i = 5; while(pow(i, 2) <= num){ if(num % i == 0) return false; i += 2; } return true; }
C
/* MERGESORT AUTORES: JIMÉNEZ DELGADO LUIS DIEGO SÁNCHEZ CASTRO AARÓN GAMALIEL SÁNCHEZ TIRADO CITLALI YASMÍN VERSIÓN 1.5 */ #include <time.h> #include <stdlib.h> #include <stdio.h> int *cal(int arreglo[], int tamano); void printArray(int arrTo[], int tam); void copyArray(int *arrTo, int *arrFrom, int tam); int main() { int tam = 25, i; int arreglo[tam]; srand(time(NULL)); for (i = 0; i < tam; ++i) { if (i % 2 == 0){ arreglo[i] = i; } else { arreglo[i] = -i + 2; } } printf("\a\n"); printArray(arreglo, tam); copyArray(arreglo, cal(arreglo, tam), tam); printf("\resultado\n"); printArray(arreglo, tam); return 0; } /* FUNCIÓN: printArray(int arrTo[], int tam) RECIBE: el arreglo de int a imprimir int arrTo[], el tamaño del arreglo int tam DEVUELVE: void; DESCRIPCIÓN: Funcion que recibe un arreglo de tamaño n, e imprime todos los valores en el separados por un / OBSERVACIONES: */ void printArray(int arrTo[], int tam) { int i = 0; for (i = 0; i < tam; ++i) { printf("%i \t", arrTo[i]); } printf("\n"); } /* FUNCIÓN: copyArray(int *arrTo, int *arrFrom, int tam) RECIBE: el arreglo al que se le van asignar los numeros int *arrTo, el arreglo del que se van asignar los numeros int *arrFrom, el tamaño del arreglo int tam DEVUELVE: void DESCRIPCIÓN: copia todos los elementos de un arreglo a otro */ void copyArray(int *arrTo, int *arrFrom, int tam) { int i = 0; for (i = 0; i < tam; ++i) { arrTo[i] = arrFrom[i]; } } /* FUNCIÓN: *cal(int arreglo[], int tamano) RECIBE: el arreglo a acmodar int arreglo[], el tamaño del arreglo int tamano DEVUELVE: un arreglo de tamño variable int * DESCRIPCIÓN: Realiza el proceso de ordenamiento merge por medio de recursividad */ int *cal(int arreglo[], int tamano) { printf("\n"); if (tamano != 1) { int i, j; int tamArr = tamano / 2; int tamArr2 = tamArr + (tamano % 2); int arr1[tamArr]; int arr2[tamArr2]; for (i = 0; i < (tamArr); ++i) { arr1[i] = arreglo[i]; arr2[i] = arreglo[tamArr + i]; } arr2[tamArr2 - 1] = arreglo[tamano - 1]; copyArray(&arr1, cal(arr1, tamArr), tamArr); copyArray(&arr2, cal(arr2, tamArr2), tamArr2); int res[tamano], k = 0; i = 0; j = 0; while (i <= tamArr && j <= tamArr2 && k < tamano) { if (i <= tamArr && arr1[i] < arr2[j]) { res[k] = arr1[i]; ++i; } else { if (j < tamArr2) { res[k] = arr2[j]; ++j; } else { res[k] = arr1[i]; ++i; } } ++k; } return res; } return arreglo; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "pa12.h" #ifndef INIT //head: the head of the singly linkedlist. //length: the length of the singly linkedlist. //This function will create and initialize the singly linkedlist with length=length, //The values of the nodes within the singly linkedlist will be the same as array indices. //For example, if the singly linkedlist length is 4, the values of the nodes will be 0 1 2 3 void init(struct node **head,int length) { struct node * temp = NULL; struct node * last = NULL; for(int i = 0; i<length; i++){ temp = malloc(sizeof(struct node)); temp->value = i; temp->next = NULL; if(*head == NULL){ *head = temp; } else{ last->next = temp; } last = temp; } last->next = *head; } /*struct node * temp = malloc(sizeof(struct node)); temp ->value = 0; temp->next = NULL; *head = temp; for(int i = 1; i<length; i++){ temp->next = malloc(sizeof(struct node)); temp = temp->next; temp->value = i; } temp->next = NULL; print(head);*/ /* while((*head) != NULL){ printf("%d, ", (*head)->value); *head = (*head)->next; }*/ #endif #ifndef PRINT //head: the head of the singly linkedlist. //This function will print the values of the nodes within the singly linkedlist. //For example, if the values of the nodes within the singly linkedlist are 1 5 6 8 9 10, this function will print 1,5,6,8,9,10 //Note: there is no extra comma nor at the beginning nor at the end. void print(struct node **head) { struct node * temp = *head; if(temp == temp->next){ printf("%d\n", temp->value); return; } /*int count = 1; temp = temp->next; while(temp !=(*head)){ temp = temp->next; count+=1; } temp = *head; for(int i = 0; i<count; i++){ printf("%d,", temp->value); temp = temp->next; } printf("%d\n", temp->value);*/ do{ printf("%d,", temp->value); temp = temp->next; }while((*head) != temp->next); printf("%d\n", temp->value); /*while(temp->next !=NULL){ printf("%d,", temp->value); temp = temp->next; } printf("%d\n", temp->value);*/ } #endif #ifndef JOSPI //head: the head of the singly linkedlist. //k : this variable will be used for counting if count = k, the element will be out. //p : this variable will be used for printing if the number of remaining elements/nodes is divisible by p (call the print function). //length: the length of the singly linkedlist. //This function will solve the josephus problem using the singly linkedlist. void josp(struct node ** head,int k,int p,int length) { struct node * rem = *head; struct node * temp = *head; //struct node * fix = *head; int count = length; int i; while(rem->next != rem){ for(i = 0; i<k; i++){ temp = rem; rem = rem->next; } temp -> next = rem -> next; if(rem == *head){ *head = rem->next; } free(rem); rem = temp->next; count = count -1; if(count % p == 0){ print(head); /*if((*head)->next->next != NULL){ print(head); } else{ print(&rem); }*/ } } *head = rem; } #endif #ifndef INITII //head: the head of the doubly linkedlist. //length: the length of the doubly linkedlist. //This function will create and initialize the doubly linkedlist with length=length, //The values of the nodes within the doubly linkedlist will be the same as array indices. //For example, if the doubly linkedlist length is 4, the values of the nodes will be 0 1 2 3 //NOTE: this is a doubly linkedlist you should assign the prev pointer for each node probably. //NOTE: head->prev is NULL as well as tail->next. void init2(struct dnode ** head,int length) { int i = 0; struct dnode * last = NULL; if(*head==NULL){ struct dnode * temp = malloc(sizeof(struct dnode)); temp->value = i; temp->next = temp->prev = temp; *head = temp; } for(i=1; i<length; i++){ last = (*head)->prev; struct dnode * new = malloc(sizeof(struct dnode)); new->value = i; new->next = *head; (*head)->prev = new; new->prev = last; last->next = new; } /*for(int i = length; i>=0; i--){ struct dnode * temp = malloc(sizeof(struct dnode)); temp->value = i; temp->next = *head; temp->prev = NULL; if((*head) !=NULL){ (*head)->prev = temp; } *head = temp; }*/ } #endif #ifndef PRINTII //head: the head of the doubly linkedlist. //This function will print the values of the nodes within the doubly linkedlist. //For example, if the values of the nodes within the doubly linkedlist are 1 5 6 8 9 10, this function will print 1,5,6,8,9,10 //Note: there is no extra comma nor at the beginning nor at the end. void print2(struct dnode ** head) { struct dnode * temp = *head; if(temp == NULL){ return; } if(temp->next == temp || temp->prev == temp){ printf("%d\n", temp->value); return; } do{ printf("%d,", temp->value); temp = temp->next; }while((*head)->prev != temp); printf("%d\n", temp->value); } #endif #ifndef JOSPII //head: the head of the doubly linkedlist. //k : this variable will be used for counting if count = k, the element will be out. //q : this variable will be used for flipping the direction. If while counting, the value of the node is divisible by q, //you will take the node out, flip the direction, and continue counting. //length: the length of the doubly linkedlist. //This function will solve the modified josephus problem using the doubly linkedlist. //NOTE: you should call the print2() function after any delete operation. void josp2(struct dnode **head, int k, int q,int length) { struct dnode * rem = *head; struct dnode * temp = *head; struct dnode * prevhead = NULL; // struct dnode * remhead = *head; bool flip = false; int count = 0; while(length !=1){ while(count != k){ if(flip == true){ prevhead = rem; rem = rem->prev; count+=1; if(rem->value % q == 0){ flip = !flip; if(rem == *head){ prevhead = (*head)->prev; *head = (*head)->next; prevhead->next = *head; (*head)->prev = prevhead; free(rem); length-=1; rem = prevhead; } else if(rem->next == *head){ prevhead->next = *head; (*head)->prev = prevhead; free(rem); length-=1; rem = prevhead; } else{ temp = rem->next; prevhead->next = temp; temp->prev = prevhead; free(rem); length-=1; rem = prevhead; } print2(head); } } if(flip == false){ prevhead = rem; rem = rem->next; count+=1; if(rem->value % q == 0){ flip = !flip; if(rem == *head){ prevhead = (*head)->prev; *head = (*head)->next; prevhead->next = *head; (*head)->prev = prevhead; free(rem); length-=1; rem = prevhead; } else if(rem->next == *head){ prevhead->next = *head; (*head)->prev = prevhead; free(rem); length-=1; rem = prevhead; } else{ temp = rem->next; prevhead->next = temp; temp->prev = prevhead; free(rem); length-=1; rem = prevhead; } print2(head); } } } if(rem->value % q == 0){ flip = !flip; } if(rem == *head){ prevhead = (*head)->prev; *head = (*head)->next; prevhead->next = *head; (*head)->prev = prevhead; free(rem); length-=1; rem = prevhead; } else if(rem->next == *head){ prevhead->next = *head; (*head)->prev = prevhead; free(rem); length-=1; rem = prevhead; } else{ temp = rem->next; prevhead->next = temp; temp->prev = prevhead; free(rem); length-=1; rem = prevhead; } print2(head); count = 0; } /* struct node * temp = *head; struct node * rem = *head; int len = length; int count = 0; bool flip = false; while(len != 1){ while(count != k){ temp = rem; rem = rem->next; while(rem->value % q == 0){ flip = !flip; if(rem->next !=NULL){ rem->next->prev = rem->prev; } if(rem->prev !=NULL){ rem->prev->next = rem->next; } if(rem == *head){ *head = rem->next; } free(rem); rem = temp->next; print(head); count+=1; }*/ } #endif
C
#include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<signal.h> struct node { int data; struct node *next; }*front=NULL,*rear=NULL; void insert(int value) { struct node *nu; nu=(struct node*)malloc(sizeof(struct node)); nu->data=value; if(front==NULL) front=rear=nu; else { rear->next=nu; rear=nu; } printf("success\n"); } void delete(void) { if(front==NULL) printf("queue is empty\n"); else { struct node *temp; temp=front; front=front->next; printf("\n deleted element %d \n",temp->data); free(temp); } } void display(void) { sleep(); struct node *temp=front; while(temp) { printf("%d",temp->data); temp=temp->next; } } int main() { int i,n; pthread_t t1; freopen("/home/patilkam/ipc/practice/database","r",stdout); for(i=2;i<5;i++) { scanf("%d",&n); insert(n); } //pthread_create(&t1,NULL,&display,NULL); //usleep(1); // signal(SIGINT,display); display(); for(i=2;i<5;i++) delete(); }
C
/* Alex Sluborski CIS 190 Lab 6 part 1 10/11/18 */ #include <stdio.h> #include <stdlib.h> //defines buffer #define BUFFER 256 //function declarations void digitCount(int *num,int *answer); void digitSum(int *num, int*answer); void largestDigit(int *num, int*answer); int main(){ char string[BUFFER]; // creates string of bugger int num; do{ printf("Enter a number greater than 0\n"); // input number greater than 0 fgets(string,BUFFER,stdin); // scanner num = atoi(string); // converts string to int }while (num < 1); // do while loop for checking negative values printf("Value entered: %d\n", num); int length; // count of digits variable digitCount(&num,&length); printf("Length of %d is: %d\n",num,length); // prints length int digSum; // sum variable digitSum(&num,&digSum); printf("sum of digits: %d\n",digSum); // prints sum int largest; // largest digit variable largestDigit(&num,&largest); printf("Largest digit: %d\n",largest); // prints largest digit return 0; } // function for length of number void digitCount(int *num, int *answer){ int a = *num; //creates temp var for num int count = 0; // counter variable while(a!=0) //while a does not equal zero { count++; //increments count a/=10; // divides by 10 (digits place) } *answer = count; } //function for sum of all digits void digitSum(int *num, int*answer){ int a = *num; int sum = 0; while(a!=0){ sum +=a%10; // sum modulus operator equation a /=10; // divides by digits place } *answer = sum; // gets sum } //function to find largest digit in number void largestDigit(int *num, int*answer){ int a =*num; int value = 0; while(a!=0) // while a does not equal 0 { int b = a %10; /// modulus equation if(b > value) // if b greater than value value = b; a/=10; // get digits place for b } *answer = value; // gets largest digit }
C
/* Напишете програма, която да генерира парола с малки букви (i), специални символи (j), големи букви (k) и цифри (l), ама разбъркано. Използвайте функции. */ #include <stdio.h> #include <stdlib.h> #include <time.h> char getSmallLetter(); char getCapitalLetter(); char getSymbol(); char getNumber(); int main(void){ srand((unsigned)time(0)); char (*funcPtr[4])() = {getSmallLetter, getCapitalLetter, getSymbol, getNumber}; int length, nSmall, nCapital, nNumbers, nSymbols, chance; printf("Enter password length:\n"); scanf("%d", &length); printf("How many small letters?\n"); scanf("%d", &nSmall); printf("How many capital letters?\n"); scanf("%d", &nCapital); printf("How many numbers?\n"); scanf("%d", &nNumbers); printf("How many symbols?\n"); scanf("%d", &nSymbols); char *password; password = (char *) malloc((length + 1)* sizeof(char)); char *passwordStart = password; while (nSmall != 0 || nCapital != 0 || nNumbers != 0 || nSymbols != 0){ chance = rand() % 4; if (chance == 0 && nSmall > 0){ *password++ = (*funcPtr[0])(); nSmall--; } else if (chance == 1 && nCapital > 0){ *password++ = (*funcPtr[1])(); nCapital--; } else if (chance == 2 && nSymbols > 0){ *password++ = (*funcPtr[2])(); nSymbols--; } else if (chance == 3 && nNumbers > 0){ *password++ = (*funcPtr[3])(); nNumbers--; } } *password = '\0'; printf("Your password is: %s\n", passwordStart); free(passwordStart); return 0; } char getSmallLetter(){ char a = (rand() % 26) + 'a'; return a; } char getCapitalLetter(){ char a = (rand() % 26) + 'A'; return a; } char getSymbol(){ int n = rand() % 8; char a; switch (n){ case 0: a = '@'; break; case 1: a = '#'; break; case 2: a = '$'; break; case 3: a = '%'; break; case 4: a = '!'; break; case 5: a = '^'; break; case 6: a = '&'; break; case 7: a = '*'; break; } return a; } char getNumber(){ char a = (rand() % 9) + '0'; return a; }
C
// Benchmarking the Memory Heirarchy // Using cpuid to find out cache sizes #include <stdio.h> #include <stdint.h> int main(){ // Use a loop to check all 4 levels int i; for(i=0;i<4;++i){ // inputting 4 into %eax gives us back cache parameters for a cache // level specified in %ecx (pg 267) // setting level to i int lvl = i; // reset a,b,c,d each iteration of the loop uint32_t a=0, b=0, c=0, d=0; __asm__( "movl $4, %%eax;" "movl %4, %%ecx;" "cpuid;" "movl %%eax, %0;" "movl %%ebx, %1;" "movl %%ecx, %2;" "movl %%edx, %3;" :"+r" (a), "+r" (b), "+r" (c), "+r" (d) :"r" (lvl) :"eax", "ebx", "ecx", "edx" ); // Cache level printf("Cache level: %d\n",lvl); // register ecx: Sets // Sets: ecx + 1 uint32_t sets = c; printf("Sets: %d\n",sets); // register ebx: Line size, Partitions, Ways of associativity. // use mod to grab specified number of bits // Line Size: ebx[11:0] + 1 uint32_t l_size = b & 0xfff; // Partitions: ebx[21:12] + 1 uint32_t parts = (b >> 12) & 0x3ff; // Ways of Associativity: ecx[31:22] + 1 uint32_t ways = (b >> 22) & 0x3ff; printf("Line Size: %d\nPartitions: %d\nWays of Associativity: %d\n",l_size,parts,ways); // Cachsize = (Ways + 1) * (Partitions + 1) * (Line_Size + 1) * (Sets + 1) uint64_t cache = (ways + 1) * (parts + 1) * (l_size + 1) * (sets + 1); printf("Cache Size: %llu\t",(long long unsigned)cache); cache = cache/1000; printf("which is %llu kb\n",(long long unsigned)cache); } return 0; }
C
#include<stdio.h> #include <stdlib.h> #include <time.h> int tails(void); void main(void) { int n,counter; int coin[2]= {0}; srand( time( NULL ) ); for(n=1; n<=100; n++) { coin[tails()]+=1; printf("%d ",tails()); } printf("\nHeads times:%d\nTails times:%d",coin[0],coin[1]); } int tails(void) { if(rand()%2==0) return 0; else return 1; } //srand( time( NULL ) );ܷѭ
C
/* Ӻ@20200809 */ /* negate.c -- ෴ */ int negate (int n) { return -n; }
C
#include <avr/io.h> #include <stdlib.h> #include <util/delay.h> #include <stdbool.h> #include "display.h" //map value of bit a to index b uint8_t col_b_map[8] = {0, 0, 0, 0, 2, 4, 0, 0}; uint8_t col_c_map[8] = {0, 0, 1, 0, 3, 6, 0, 0}; uint8_t row_c_map[8] = {2, 3, 0, 5, 0, 0, 0, 0}; uint8_t col_d_map[8] = {7, 0, 5, 0, 0, 8, 0, 0}; uint8_t row_d_map[8] = {0, 1, 0, 6, 4, 0, 8, 7}; uint8_t map_bit(uint8_t bits, int to, int from){ if(from != 0){ uint8_t bit = ((1 << (from-1)) & bits) >> (from-1); return bit << to; } else{ return 0; } } void draw_row(uint8_t col, int index){ uint8_t portb = 0; uint8_t portc = 0; uint8_t portd = 0; uint8_t row = 0b1 << index; col = ~col; for(int i = 0; i < 8; i++){ portb |= map_bit(col, i, col_b_map[i]); portc |= map_bit(col, i, col_c_map[i]); portd |= map_bit(col, i, col_d_map[i]); portc |= map_bit(row, i, row_c_map[i]); portd |= map_bit(row, i, row_d_map[i]); } PORTB = portb; PORTD = portd; PORTC = portc; } void draw(disp_t board){ for(int i= 0 ; i < DIM; i++){ draw_row(board[i], i); } } void set_pins(){ DDRD |= (1 << C8); DDRD |= (1 << R4); DDRD |= (1 << R6); DDRD |= (1 << C5); DDRD |= (1 << R1); DDRD |= (1 << C7); DDRD |= (1 << R7); DDRD |= (1 << R8); DDRC |= (1 << C6); DDRC |= (1 << C3); DDRC |= (1 << R5); DDRC |= (1 << C1); DDRC |= (1 << R3); DDRC |= (1 << R2); DDRB |= (1 << C2); DDRB |=(1 << C4); //INPUT DDRB &= ~(1 << PB1); DDRB &= ~(1 << PB2); } int get_cell(uint8_t* board, int x, int y){ return (board[y] >> ((8 - 1) - x)) & 0x1; } int bit_count(uint8_t bits){ bits = (bits & 0b01010101) + ((bits & 0b10101010) >> 1); bits = (bits & 0b00110011) + ((bits & 0b11001100) >> 2); return (bits & 0b00001111) + ((bits & 0b11110000) >> 4); } int get_row_count(uint8_t row, int x){ uint8_t pos = 0b10000000 >> x; uint8_t neighbors = (pos >> 1) | (pos << 1) | pos; return bit_count(neighbors & row); } void cell_on(disp_t board, int x, int y){ uint8_t cell_mask = (1 << ((DIM - 1) - x)); board[y] |= cell_mask; } void cell_toggle(disp_t board, int x, int y){ uint8_t cell_mask = (1 << ((DIM - 1) - x)); board[y] ^= cell_mask; } void cell_off(disp_t board, int x, int y){ uint8_t cell_mask = ~(1 << ((DIM - 1) - x)); board[y] &= cell_mask; } int diff_board(disp_t a, disp_t b){ int diff = 0; for(int i = 0; i < DIM; i++){ diff += bit_count(a[i]) - bit_count(b[i]); } return diff; } disp_t disp_new(){ set_pins(); disp_t disp = (disp_t) malloc(8*sizeof(disp_t)); return disp; } void disp_free(disp_t disp){ free(disp); } void delay_draw(disp_t disp, int delay){ for(int i = 0; i < delay; i++){ draw(disp); } } void screen_row_wipe(disp_t disp){ for(int i = 0; i < 8; i++){ disp[i] = disp[i] ^ 0xff; delay_draw(disp, 100); } } void screen_dissolve(disp_t disp){ uint8_t dissolved = 0; int next_row; while(dissolved != 0xff){ next_row = rand() % 8; disp[next_row] |= rand() % 256; if(disp[next_row] == 0xff){ dissolved |= 1 << next_row; } delay_draw(disp, 20); } } void screen_cell_wipe(disp_t disp){ for(int i = 0; i < DIM; i++){ for(int j = 0; j < DIM; j++){ cell_toggle(disp, i, j); delay_draw(disp, 10); } } } void screen_random_transition(disp_t disp){ int choice = rand() % 3; switch(choice){ case 0: screen_row_wipe(disp); break; case 1: screen_dissolve(disp); break; case 2: screen_cell_wipe(disp); break; } }
C
/* *************************************************************************** Tina Stahlstedt stahlstt@onid.oregonstate.edu CS362 - 400 Spring 2015 Assignment 3 Write unit tests for four functions (not card implementations or cardEffect) in dominion.c. Check these tests in as unittest1.c,unittest2.c, unittest3.c, and unittest4.c. Unit test for shuffle(). Because initializing the game sets player 0's hand, player 0 starts with a 5 card deck. Also, I am expecting that initialize game is working correctly. *************************************************************************** */ #include "dominion.h" #include "dominion_helpers.h" #include "interface.c" #include "rngs.h" #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> int testShuffle(int player, struct gameState *state) { printf("Before shuffle() on "); printDeck(player, state); shuffle(player, state); // deck should be noticeably different now printf("Deck is different after shuffle() on "); printDeck(player, state); return 0; } int main () { int i, play; int seed = 415789; int k[10] = {adventurer, baron, council_room, feast, gardens, great_hall, mine, remodel, smithy, village}; struct gameState game; play = initializeGame(MAX_PLAYERS, k, seed, &game); assert (play == 0); printf("Testing shuffle()...\n"); for(i = 0; i < MAX_PLAYERS; i++) { testShuffle(i, &game); } printf("End testing shuffle()...\n"); return 0; }
C
//#include "everything.h" #include "tab.h" /******************************************************************************* * COMPRESSOR DICTIONARY & FUNCTIONS * ****************************************************************************/ //structure that defines the dictionary typedef struct dict{ int dict_size; int symbols; ht_table table; }dictionary; /*function to initialize the dictionary, the arguments are: * dictionary to initialize, dimension, symbols * in the initialization ht_array points to an array of * SIZE entries */ void comp_dict_init(dictionary*, int, int); //add a word in the dictionary int comp_dict_add_word(int index, int father, unsigned int symbol, dictionary* d); //search a couple father child in the dictionary int comp_dict_search(int* father, unsigned int child, dictionary* D); //destroy the dictionary void comp_dict_suppress(dictionary* dict); /******************************************************************************* * DECOMPRESSOR DICTIONARY & FUNCTIONS * ****************************************************************************/ typedef struct dec_dict{ int size; //max dimension of dictionary int symbols; //symbols for initialization table tab; }dec_dictionary; //function to initialize the dictionary used by the decompressor void decomp_dict_init(dec_dictionary* d, int size, int symbols); //insertion in the decompressor dictionary void decomp_dict_insertion(int father, unsigned int symbol, dec_dictionary* d); //suppress the decompressor dictionary void decomp_dict_suppress(dec_dictionary* d); //returns how many positions there are in the rebuilt word int decomp_dict_reb_word(int index, int* vector, int* size, dec_dictionary* d);
C
#ifndef EMBER_PRINT_H #define EMBER_PRINT_H 1 #include <stdbool.h> #include <stdint.h> /** * @brief Prints a log message * @param category - Currently ignored as zcl categories do not map to chip categories. Defaults to kLogCategory_Progress * @param format - Format string to print * */ void emberAfPrint(int category, const char * format, ...); /** * @brief Prints a log followed by new line line * @param category - Currently ignored as zcl categories do not map to chip categories. Defaults to kLogCategory_Progress * @param format - Format string to print * */ void emberAfPrintln(int category, const char * format, ...); /** * @brief Prints a buffer * @param category - Currently ignored as zcl categories do not map to chip categories. Defaults to kLogCategory_Progress. * @param buffer - Buffer to print. * @param length - Length of buffer * @param withSpace - Pass in true if a space should be printed between each byte. * */ void emberAfPrintBuffer(int category, const uint8_t * buffer, uint16_t length, bool withSpace); #endif // EMBER_PRINT
C
/* * File: 6-size.c * Auth: Ewar James <ewaarjames@gmail.com> */ #include <stdio.h> /** * main - Prints "with proper grammar, but the outcome is a piece of art, * * Return: Always 0. */ int main(void) { printf("Size of a char: %i byte(s)\n", sizeof(char)); printf("Size of an int: %i byte(s)\n", sizeof(int)); printf("Size of a long int: %i byte(s)\n", sizeof(long)); printf("Size of a long long int: %i byte(s)\n", sizeof(long long)); printf("Size of a float: %i byte(s)\n", sizeof(float)); return (0); }
C
#include<stdio.h> int main() { int arr1[20], arr2[20], array_new[40], n1, n2, size, i; /*n1 size of first array (i.e. arr1[]), n2 size of second array(i.e. arr2[]), size is the total size of the new array (array_new[]) */ scanf("%d", &n1); //Get the size of first array from test data and store it in n1. for (i = 0; i < n1; i++) scanf("%d", &arr1[i]); //Accepts the values for first array scanf("%d", &n2); //Get the size of second array from test data and store it in n2. for (i = 0; i < n2; i++) scanf("%d", &arr2[i]); //Accepts the values for second array size = n1 +n2; int j = n1; for (i = 0 ;i < n1; i++) { array_new[i] = arr1[i]; } for (i = 0 ;j<size; i++,j++) { array_new[j] = arr2[i]; } //Printing after merging for (i = 0; i < size; i++) { printf("%d\n", array_new[i]); } }
C
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include "funciones.h" #define CANTIDAD 1000 int main() { //Declaracion de estructura. estructuraPersona persona[CANTIDAD]; //Se inicializa el array en 0. iniciarArrays(persona, CANTIDAD); //Se carga la estructura para probar las funciones. cargaDePrueba(persona, CANTIDAD); //contador. int i; //variable para funcionamiento del menu. int opcion; do { //llamada a la funcion del menu para mostrarlo. opcion = menu(); //se entra en el case de la opcion ingresada switch(opcion) { case 1: agregarPersona(persona, CANTIDAD);//Se ingresa una persona. break; case 2: borrarPersona(persona, CANTIDAD);//Ingresar dni de una persona para eliminarlo. break; case 3: imprimirPersonas(persona, CANTIDAD);//imprimir lista de personas ordenadas por Nombre. break; case 4: graficar(persona, CANTIDAD);//grafico de rangos de edades. break; } }while(opcion!=5); return 0; }
C
// O que esse algoritmo faz? #include <stdio.h> int main(){ while (1) { // 1!=0 printf("*"); } return 0; }
C
/*=======================================================================================================*/ /*======================================PROJETO 2 - IAED 2016/2017=======================================*/ /*===========================================Ricardo Velhinho============================================*/ /*=============================================GRUPO AL087===============================================*/ /*=======================================================================================================*/ /*=======================================================================================================*/ /*=============================================BIBLIOTECAS===============================================*/ /*=======================================================================================================*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "Item.h" #include "ST.h" static int contador=0; /* Permite a contagem de quantos nos existem */ /*=======================================================================================================*/ /*=============================================CONSTANTES================================================*/ /*=======================================================================================================*/ #define TAM 8 /* Tamanho limite de carateres para uma chave */ /*=======================================================================================================*/ /*================================================MAIN===================================================*/ /*=======================================================================================================*/ void altera_stock(Item t,int quantidade){ /* Funcao que altera o stock dependendo se a quantidade recebida vai ser superior ou inferior a 0 */ if (quantidade!=0){ t->stock+=quantidade; } if (t->stock<0){ t->stock=0; } return; } int main(){ int maior=-1,*maior_aux,quantidade, command ; char sign, maior_chave[TAM+1],mensagem[TAM+1],mensagem_a_remover[TAM+1],*msg=mensagem,*msg_r=mensagem_a_remover; link produtos; STinit(&produtos); /* Vai inicializar a arvore binaria */ maior_aux=&maior; while (1){ command = getchar(); switch(command){ case 'a': getchar(); /* livra se do primeiro espaco */ scanf("%s",msg); scanf("%c%d",&sign,&quantidade); if(sign=='-'){ quantidade=quantidade*-1; /* Caso o sinal seja '-' vai tornar a quantidade um valor negativo */ } Item t = STsearch(produtos,msg); /* Vai procurar na arvore pela chave correspondente */ if ( t == NULL && quantidade >= 0){ /* Caso nao encontre e a quantidade seja maior ou igual a 0 */ Item novo = newItem(mensagem,quantidade); STinsert(&produtos,novo); contador++; if ( (novo->stock > maior)|| (novo->stock==maior && strcmp(novo->chave,maior_chave)<0)){ maior = novo->stock; strcpy(maior_chave,novo->chave); } } else if ( t== NULL && quantidade < 0){ /* Caso nao encontre e o stock seja menor que 0 */ quantidade = 0; Item novo = newItem(mensagem,quantidade); STinsert(&produtos,novo); contador++; } else if (t!= NULL){ /* Caso encontre o produto */ altera_stock(t,quantidade); if ( quantidade>0){ /* Se a quantidade for maior que 0 vai apenas comparar com o maior stock */ if ( (t->stock > maior)|| (t->stock==maior && strcmp(t->chave,maior_chave)<0)){ maior = t->stock; strcpy(maior_chave,t->chave); } } else if (quantidade<0){ /* Se houver diminuicao de algum stock vai se percorrer a arvore para encontrar o maior */ maior=-1; traverse_procura_maior(produtos,maior_aux,maior_chave); } } break; case 'l': traverse(produtos); break; case 'm': if ( contador == 0) { /* Caso a arvore esteja vazia */ break; } else { printf("%s %d\n",maior_chave,*maior_aux); break; } case 'r': getchar(); scanf("%s",msg_r); Item no_a_remover = STsearch(produtos,msg_r); /* Verifica se esse no se encontra na arvore */ if ( no_a_remover != NULL){ /* Caso se encontre na arvore vai apagar dessa */ STdelete(&produtos,msg_r); if (strcmp(msg_r,maior_chave)==0 ){ /* Caso a chave seja igual a chave maior, vai percorrer a arvore a procura da nova chave maior */ maior=-1; traverse_procura_maior(produtos,maior_aux,maior_chave); } contador--; } break; case 'x': printf("%d\n",contador); /* Imprime a variavel global que conta o numero de nos existentes */ STfree(&produtos); /* Liberta todos os elementos da arvore */ return EXIT_SUCCESS; } } return EXIT_FAILURE; }
C
#pragma pack(1) struct Header{ int num; int index; }; struct PkgContent { char sex; int score; char address [100]; int age; }; struct Pkg { Header head; PkgContent content; }; int MySend(int iSock, char * pchBuf, size_t tLen){ int iThisSend; unsigned int iSended=0; if(tLen==0) return 0; while(iSended<tLen){ do{ iThisSend=send(iSock,pchBuf,tLen-iSended,0); }while( (iThisSend<0) && (errno==EINTR)); if(iThisSend<0){ return (iSended); } iSended+=iThisSend; pchBuf+=iThisSend; } return (tLen); } int MyRecv( int iSock, char * pchBuf, size_t tCount){ size_t tBytesRead=0; int iThisRead; while(tBytesRead<tCount){ do{ iThisRead= read(iSock, pchBuf,tCount-tBytesRead); }while( (iThisRead<0) && (errno==EINTR)); if(iThisRead < 0){ return (iThisRead); }else if(iThisRead==0) return (tBytesRead); tBytesRead+=iThisRead; pchBuf+=iThisRead; } }
C
#include"seqlist.h" //haha void TestPushBack(){ TEST_HEADER; SeqList seqlist; SeqListInit(&seqlist); SeqListPushBack(&seqlist,'a'); SeqListPushBack(&seqlist,'b'); SeqListPushBack(&seqlist,'c'); SeqListPushBack(&seqlist,'d'); SeqListPrintChar(&seqlist,"尾插元素"); } void TestSeqListErase(){ TEST_HEADER; SeqList seqlist; SeqListInit(&seqlist); SeqListPushBack(&seqlist,'a'); SeqListPushBack(&seqlist,'b'); SeqListPushBack(&seqlist,'c'); SeqListPushBack(&seqlist,'d'); SeqListErase(&seqlist,2); SeqListPrintChar(&seqlist,"删除c元素"); } void TestSeqListGet(){ TEST_HEADER; SeqList seqlist; SeqListInit(&seqlist); SeqListPushBack(&seqlist,'a'); SeqListPushBack(&seqlist,'b'); SeqListPushBack(&seqlist,'c'); SeqListPushBack(&seqlist,'d'); //SeqListSet测试函数 SeqListSet(&seqlist, 1,'x'); SeqListType value; int ret = SeqListGet(&seqlist, 1 ,&value); printf("ret expected 1,actual %d\n",ret); printf("value expected b,actual %c\n",value); } size_t TestSeqListFind(){ TEST_HEADER; SeqList seqlist; SeqListInit(&seqlist); SeqListPushBack(&seqlist,'a'); SeqListPushBack(&seqlist,'b'); SeqListPushBack(&seqlist,'c'); SeqListPushBack(&seqlist,'d'); size_t pos = SeqListFind(&seqlist,'c'); printf("c号元素是:%d\n",pos); } void TestSeqListRemoveAll(){ TEST_HEADER; SeqList seqlist; SeqListInit(&seqlist); SeqListPushBack(&seqlist,'a'); SeqListPushBack(&seqlist,'b'); SeqListPushBack(&seqlist,'a'); SeqListPushBack(&seqlist,'r'); SeqListRemoveAll(&seqlist,'a'); SeqListPrintChar(&seqlist,"删除所有a"); } void TestSeqListBubbleSort(){ TEST_HEADER; SeqList seqlist; SeqListInit(&seqlist); SeqListPushBack(&seqlist,'d'); SeqListPushBack(&seqlist,'c'); SeqListPushBack(&seqlist,'a'); SeqListPushBack(&seqlist,'b'); SeqListBubbleSort(&seqlist); SeqListPrintChar(&seqlist,"冒泡排序"); } int main(){ TestPushBack(); TestSeqListErase(); TestSeqListGet(); TestSeqListFind(); TestSeqListRemoveAll(); TestSeqListBubbleSort(); return 0; }
C
#include <stdarg.h> #include <string.h> #include "config.h" #include "console.h" #include "trace.h" #ifdef USE_TRACE static const struct { int ch; int flag; const char *name; const char *desc; } flaginfo[] = { /* Note: not necessarily in same order as DOTRACE flags */ { 'k', DOTRACE_KINSN, "kinsn", "Kernel-mode instructions" }, { 'u', DOTRACE_UINSN, "uinsn", "User-mode instructions" }, { 'j', DOTRACE_JUMP, "jump", "Jumps" }, { 't', DOTRACE_TLB, "tlb", "TLB operations" }, { 'x', DOTRACE_EXN, "exn", "Exceptions" }, { 'i', DOTRACE_IRQ, "irq", "Interrupts" }, { 'd', DOTRACE_DISK, "disk", "Disk activity" }, { 'n', DOTRACE_NET, "net", "Network activity" }, { 'e', DOTRACE_EMUFS, "emufs", "Emufs activity" }, { -1, -1, NULL, NULL } }; int g_traceflags[NDOTRACES]; static int set_traceflag(int ch) { int j, f; for (j=0; flaginfo[j].ch >= 0; j++) { if (flaginfo[j].ch == ch) { f = flaginfo[j].flag; g_traceflags[f] = !g_traceflags[f]; return 0; } } return -1; } int adjust_traceflag(int letter, int onoff) { int j, f; for (j=0; flaginfo[j].ch >= 0; j++) { if (flaginfo[j].ch == letter) { f = flaginfo[j].flag; g_traceflags[f] = onoff; return 0; } } return -1; } void set_traceflags(const char *letters) { int i; for (i=0; letters[i]; i++) { if (set_traceflag(letters[i])) { msg("Unknown trace flag %c", letters[i]); die(); } } } void print_traceflags(void) { int i, k=0; for (i=0; i<NDOTRACES; i++) { if (g_traceflags[i]) k++; } if (k==0) { return; } msgl("Tracing enabled:"); for (i=0; i<NDOTRACES; i++) { if (g_traceflags[i]) { msgl(" %s", flaginfo[i].name); } } msg(" "); } void print_traceflags_usage(void) { int i; size_t len; for (i=0; i<NDOTRACES; i++) { msgl(" %c %s", flaginfo[i].ch, flaginfo[i].name); len = strlen(flaginfo[i].name); if (len < 12) { msgl("%.*s", (int)(12-len), " "); } msg(" %s", flaginfo[i].desc); } } #endif /* USE_TRACE */
C
#include "demo.h" void timer_ini(void); extern unsigned char fd1[]; extern unsigned char fd2[]; extern unsigned char fd3[]; extern unsigned char fd4[]; /**************************************************************************** * 名 称:void timer_ini(void) * 功 能:定时器初始化函数 * 入口参数:无 * 出口参数:无 * 说 明: * 调用方法:无 ****************************************************************************/ void timer_ini(void) { //定时器是为了产生250K的更新频率, 也就是4us的定时 用于超声波的控制 TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; //允许TIM2的时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); //重新将Timer设置为缺省值 TIM_DeInit(TIM2); //采用内部时钟给TIM2提供时钟源 TIM_InternalClockConfig(TIM2); //预分频系数为36000-1,这样计数器时钟为72MHz/144 = 500KHz TIM_TimeBaseStructure.TIM_Prescaler = 144 - 1; //设置时钟分割 TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置计数器模式为向上计数模式 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //设置计数溢出大小,每计2个数就产生一个更新事件 TIM_TimeBaseStructure.TIM_Period = 2-1; //将配置应用到TIM2中 TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure); //清除溢出中断标志 TIM_ClearFlag(TIM2, TIM_FLAG_Update); //禁止ARR预装载缓冲器 TIM_ARRPreloadConfig(TIM2, DISABLE); //开启TIM2的中断 TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE); TIM_Cmd(TIM2,ENABLE); } /******************* (C) COPYRIGHT STM32 *****END OF FILE****/
C
/* Copyright 2017 The serverX Authors. All Rights Reserved. * Maintainer: Bytes Club (https://bytesclub.github.io)<bytes-club@googlegroups.com> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ==============================================================================*/ // Library Source File // parse.c // include header #include <serverX.h> /** * Parses a request-line, storing its absolute-path at abs_path * and its query string at query, both of which are assumed * to be at least of length LimitRequestLine + 1. */ bool parse(int cfd, const char* line, char* abs_path, char* query) { if (cfd == -1 || line == NULL) { return false; } else if (abs_path != NULL) { memset(abs_path, '\0', LimitRequestLine + 1); } else if (query != NULL) { memset(query, '\0', LimitRequestLine + 1); } unsigned int length = strlen(line); char toParse[length + 1]; strcpy(toParse, line); char *peek = strtok(toParse, " "); if (strcmp(peek, "GET")) { error(cfd, 405); return false; } peek = strtok(NULL, " "); if (*peek != '/') { error(cfd, 501); return false; } else if (strchr(peek, '\"')) { error(cfd, 400); return false; } strncpy(query, "", 1); char *q = strchr(peek, '?'); int n = 0; if (q != NULL) { n = strlen(q); strncpy(query, q + 1, n - 1); } int m = strlen(peek) - n; strncpy(abs_path, peek, m); peek = strtok(NULL, " "); if (strcmp(peek, "HTTP/1.1\r\n")) { error(cfd, 505); return false; } return true; }
C
// // Tile renderer, var width/height, 1->4bpp tiles, // recolored with transparency // //! \file chr4r_drawg_b1cts.c //! \author J Vijn //! \date 20070621 - 20070725 // /* === NOTES === * 20070725: Skipping rendering if raw == 0 helps. A lot. Also, there is more than one way to bitunpack and split between tiles. Which method is faster is very platform dependent. * 20070723: Prepping dst stuff inside the drawg and passing along to renc does NOT help (prolly due to Thumb). Try combining in asm manually. */ #include "tonc_memdef.h" #include "tonc_tte.h" // -------------------------------------------------------------------- // FUNCTIONS // -------------------------------------------------------------------- //! Render 1bpp fonts to 4bpp tiles void chr4r_drawg_b1cts(uint gid) { TTE_BASE_VARS(tc, font); TTE_CHAR_VARS(font, gid, u8, srcD, srcL, charW, charH); uint x= tc->cursorX, y= tc->cursorY; uint srcP= font->cellH, dstP= tc->dst.pitch/4; u32 *dstD= (u32*)(tc->dst.data + y/8*dstP + (y%8)*4 + x/8*32), *dstL; dstP= dstP/4 - 8; x %= 8; u32 lsl= 4*x, lsr= 32-4*x, right= x+charW; // Inner loop vars u32 px, pxmask, raw; u32 ink= tc->cattr[TTE_INK]; const u32 mask= 0x01010101; uint iy, iw; for(iw=0; iw<charW; iw += 8) // Loop over strips { dstL= dstD; dstD += 8; srcL= srcD; srcD += srcP; iy= charH; while(iy--) // Loop over scanlines { raw= *srcL++; if(raw) { raw |= raw<<12; raw |= raw<< 6; px = raw & mask<<1; raw &= mask; px = raw | px<<3; pxmask= px*15; px *= ink; // Write left tile: dstL[0] = (dstL[0] &~ (pxmask<<lsl) ) | (px<<lsl); // Write right tile (if any) if(right > 8) dstL[8]= (dstL[8] &~ (pxmask>>lsr) ) | (px>>lsr); } dstL++; if( ((u32)dstL)%32 == 0 ) dstL += dstP; } } } // EOF
C
#include <stdio.h> #define MAX 1000001 long long g[MAX]; int phi[MAX]; int main() { int i, j, n; for(i=2,phi[1]=1; i<MAX; i++) { if(!phi[i]) { phi[i] = i-1; for(j=(i<<1); j<MAX; j+=i) { if(!phi[j]) phi[j] = j; phi[j] = phi[j]/i*(i-1); } } } for(i=1; i<MAX; i++) for(j=2; i*j<MAX; j++) g[i*j] += i*phi[j]; for(i=2; i<MAX; i++) g[i] += g[i-1]; while(scanf("%d", &n)==1 && n) printf("%lld\n", g[n]); return 0; }
C
#include "logic.h" #include "main.h" #include "Developer/Src/dev_helper.h" #include "ProtoCommunication\Src\messages_proto.h" #include "Developer/Src/m_timer.h" //зависит от требуемого сигнала на входе управления двигателем и используется для установки минимальной и максимальной скважности. #define MIN_VALUE_ARR 230 #define MAX_VALUE_ARR 550 //999 //must be equal ARR * n, где 0 < n <= 1 #define MOTOR_DIAPASONE 180 //Градусов #define MIN_VALUE_POSITION 0 //минуты #define MAX_VALUE_POSITION (MOTOR_DIAPASONE * 60) //минуты //typedef enum{ // WAIT_START, // STARTING, // RUN, // //}RegulatorState_t; extern TIM_HandleTypeDef htim2; extern TIM_HandleTypeDef htim3; static Regulator_t r = {0}; static Timer_t timerDurationOn; static Timer_t timerPeriod; static Timer_t timerActiveTime; static Timer_t timerValveProcess; static Timer_t timerCorrection; volatile static uint32_t milliseconds = 0; volatile int32_t correctValue = 0; static uint8_t valveCurPos = 0; //100% - full open, 0% - full closed static uint8_t valveSetPos = 0; //100% - full open, 0% - full closed static uint32_t GetMilliseconds(void){ return milliseconds; } static void SetPositionByMinutes(uint16_t _minutes){ if(_minutes > MAX_VALUE_POSITION) _minutes = MAX_VALUE_POSITION; uint32_t precent = GetPrecentFromValue(_minutes, MAX_VALUE_POSITION); uint32_t val = MIN_VALUE_ARR + GetValueFromPrecent(precent, MAX_VALUE_ARR - MIN_VALUE_ARR); __HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_1, val); } //100% - full open, 0% - full closed static void SetPositionByPrecent(uint8_t _prec){ uint16_t min = r.set.angleOff > r.set.angleOn ? r.set.angleOn : r.set.angleOff; uint16_t max = r.set.angleOff > r.set.angleOn ? r.set.angleOff : r.set.angleOn; uint16_t maxArr = MIN_VALUE_ARR + (max * (MAX_VALUE_ARR - MIN_VALUE_ARR))/MAX_VALUE_POSITION; uint16_t minArr = MIN_VALUE_ARR + (min * (MAX_VALUE_ARR - MIN_VALUE_ARR))/MAX_VALUE_POSITION; uint32_t val = minArr + GetValueFromPrecent(_prec, maxArr - minArr); __HAL_TIM_SetCompare(&htim2, TIM_CHANNEL_1, val); } //установка позиции клапана в процентах //100% - full open, 0% - full closed static void SetValve(uint8_t _precent){ if(_precent > 100) _precent = 100; valveSetPos = _precent; } //полностью открыть static void OpenValve(void){ SetValve(100); } //полностью закрыть static void CloseValve(void){ SetValve(0); } static void Work(void){ if(Timer_IsElapsed(&timerActiveTime)) { CloseValve(); r.isActive = false; return; } if(Timer_IsElapsed(&timerDurationOn)){ CloseValve(); } if(Timer_IsElapsed(&timerPeriod)) { OpenValve(); Timer_Reset(&timerDurationOn); Timer_Restart(&timerPeriod); } } static void ValvePositionProcess(void){ if(valveCurPos != valveSetPos && Timer_IsElapsed(&timerValveProcess)){ if(valveCurPos > valveSetPos) valveCurPos--; else valveCurPos++; Timer_Reset(&timerValveProcess); SetPositionByPrecent(valveCurPos); // uint16_t range = r.set.angleOff > r.set.angleOn ? r.set.angleOff - r.set.angleOn : r.set.angleOn - r.set.angleOff; // uint16_t minutes = GetValueFromPrecent(valveCurPos, range); // uint16_t minimum = r.set.angleOff > r.set.angleOn ? r.set.angleOn : r.set.angleOff; // SetPosition(minimum + minutes); } } static void CorrectTime(void){ if(Timer_IsElapsed(&timerCorrection)){ correctValue = r.set.correctValue; Timer_Restart(&timerCorrection); } } void Logic_Process(void){ ValvePositionProcess(); if(!r.isActive) { if(r.set.isOpenWhenStopped) OpenValve(); else CloseValve(); return; }; Work(); CorrectTime(); } void Logic_Initialise(void){ Timer_Initialise(&timerDurationOn, GetMilliseconds); Timer_Initialise(&timerPeriod, GetMilliseconds); Timer_Initialise(&timerActiveTime, GetMilliseconds); Timer_Initialise(&timerValveProcess, GetMilliseconds); Timer_Initialise(&timerCorrection, GetMilliseconds); Timer_Start(&timerValveProcess, 2); HAL_TIM_Base_Start_IT(&htim3); HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1); } void Logic_IncrementTime(void){ milliseconds++; } int32_t Logic_GetCorrectValue(void){ return correctValue; } void Logic_CorrectTimeCmpltClbk(void){ correctValue = 0; } static void RestartTimers(void){ HAL_TIM_Base_Stop_IT(&htim3); __HAL_TIM_SetCounter(&htim3, 0); HAL_TIM_Base_Start_IT(&htim3); } void OnMessageStartReceived(ProtoTransportP pr, MsgStart_t* msg){ r.isActive = msg->isStart; if(r.isActive){ Timer_Start(&timerActiveTime, r.set.activeTime); Timer_Start(&timerCorrection, r.set.correctPer); } } void OnMessageSettingsReceived(ProtoTransportP pr, MsgSettings_t* msg){ if(msg->correctValue > -900 && msg->correctValue < 900) r.set.correctValue = msg->correctValue; else r.set.correctValue = 0; r.set.activeTime = msg->activeTime; r.set.cycleCount = msg->cycleCount; r.set.delayAfter = msg->delayAfter; r.set.delayBefore = msg->delayBefore; r.set.durationOn = msg->durationOn; r.set.period = msg->period; r.set.angleOn = msg->angleOn; r.set.angleOff = msg->angleOff; r.set.valveStepPer = msg->valveStepPer; r.set.correctPer = msg->correctPer; r.set.isOpenWhenStopped = msg->isOpenWhenStopped; Timer_Start(&timerValveProcess, r.set.valveStepPer); } void OnMessageSynchronizeReceived(ProtoTransportP pr, MsgSynchronize_t* msg){ RestartTimers(); OpenValve(); Timer_Start(&timerDurationOn, r.set.durationOn); Timer_Start(&timerPeriod, r.set.period); MsgSynchronize_t m = {.id = msg->id}; SendMes_Synchronize(pr, &m); } void OnMessageSetPositionReceived(ProtoTransportP pr, MsgSetPosition_t* msg){ SetPositionByMinutes(msg->position); }
C
#include "common.h" #include "device.h" #include "lcd.h" #include "rotenc.h" #include "process.h" #include "manualmode.h" #include "uart.h" #include "timer0.h" // // 基板上のボタン押下時の処理 // static void process_on_BUTTON_0() { } static void process_on_BUTTON_1() { } static void process_on_BUTTON_2() { // 手動モードに遷移 process_init(); } static void process_on_BUTTON_3() { // 手動モード時 if (main_mode == 0) { // 正転/反転の切替 reverse_on_manual_mode(); return; } } static void send_uart_command(unsigned char c) { // ボタン押下時に、UARTコマンドを送信する printf("%c\r\n", c); } static int process_on_button_press() { int ret = 1; // スイッチOnに対する処理を実行 if (BUTTON_0 == 1) { process_on_BUTTON_0(); send_uart_command('A'); } else if (BUTTON_1 == 1) { process_on_BUTTON_1(); send_uart_command('M'); } else if (BUTTON_2 == 1) { process_on_BUTTON_2(); send_uart_command('E'); } else if (BUTTON_3 == 1) { process_on_BUTTON_3(); send_uart_command('C'); } else { ret = 0; } return ret; } // // UARTリモコンコマンド受信時の処理 // static void process_on_uart_command(unsigned char c) { switch (c) { case 'A': // 自動運転実行 process_on_BUTTON_0(); break; case 'M': // モード変更実行 process_on_BUTTON_1(); break; case 'E': // キャンセル実行 process_on_BUTTON_2(); break; case 'C': // 正/逆転切替実行 process_on_BUTTON_3(); break; default: // 無効 break; } } // // 入力された文字列を数値に変換 // static unsigned char atouc(char *value) { char buff[8]; int i, n; // 入力された文字列を作業領域にセット memset(buff, 0, sizeof(buff)); for (i = 0; value[i] != 0; i++) { buff[i] = value[i]; } // 数値変換 n = atoi(buff); if (n < 0) { return 0; } else if (255 < n) { return 255; } return (unsigned char)n; } // // UARTに入力された内容を解析する // static void parse_uart_input() { unsigned char c; unsigned char *rc_buff = get_uart_recv_buff(); if (rc_buff == NULL) { return; } // 先頭が半角大文字以外の場合はスルー c = rc_buff[0]; if (c < 64 || 90 < c) { return; } switch (c) { case 'D': // デューティー比入力 c = atouc(&rc_buff[1]); if (rsw_counter_max < c) { c = rsw_counter_max; } rsw_counter_value = c; break; case 'A': // 自動運転実行(Auto drive) case 'M': // モード変更実行(Mode change) case 'E': // キャンセル実行(End) case 'C': // 正/逆転切替実行(direction Change) process_on_uart_command(c); break; default: // 無効 break; } } // // ボタン押下検知処理 // static unsigned long btn_push_prevent_cnt; // 割込みごとに処理(3.2768 ms) static void switch_prevent() { // カウンターが0の時は終了 if (0 == btn_push_prevent_cnt) { return; } // ボタン連続押下抑止カウンターを更新 btn_push_prevent_cnt-- ; } // イベントループ内の最後のステップで処理 static void switch_detection() { // カウンターが0でない時は終了 if (0 < btn_push_prevent_cnt) { return; } // スイッチ押下時の処理を実行 if (process_on_button_press() != 0) { // 押下抑止カウンターを設定(約1秒に設定) btn_push_prevent_cnt = 300; } else { btn_push_prevent_cnt = 0; } } // // センサー検知処理 // static unsigned char reducing_sensor_flg; static unsigned char stopping_sensor_flg; static void process_on_REDUCING_SENSOR() { } static void process_on_STOPPING_SENSOR() { } // 割込みごとに処理(3.2768 ms) static void sensor_detection() { // レイアウト制御デバイス以外の場合は処理しない if (devide_type != DEVTYP_LAYOUT) { return; } // センサーOnに対する処理を実行 if (REDUCING_SENSOR == 0) { reducing_sensor_flg++; // n回連続して検知にかかったらセンサーを踏んだと判定 if (5 == reducing_sensor_flg) { process_on_REDUCING_SENSOR(); } } else if (STOPPING_SENSOR == 0) { stopping_sensor_flg++; // n回連続して検知にかかったらセンサーを踏んだと判定 if (5 == stopping_sensor_flg) { process_on_STOPPING_SENSOR(); } } else { reducing_sensor_flg = 0; stopping_sensor_flg = 0; } } // 約 0.1 秒ごとに処理(3.2768ms × 30回) static void process_on_100m_second() { switch (main_mode) { case 0: // 手動運転モード時 process_on_manual_mode(); break; } } // 約 1.0 秒ごとに処理(3.2768ms × 305回) static void process_on_one_second() { switch (main_mode) { case 0: // 手動運転モード時 process_on_one_second_manual_mode(); break; } } // ロータリーエンコーダーの現在値変更時の処理 static void process_on_change_rotenc_val() { // 値が変更時、UARTコマンドを送信する printf("D%u\r\n", rsw_counter_value); } void process_init() { // 動作モードを設定 set_device_mode(); // ローカル変数の初期化 btn_push_prevent_cnt = 0; reducing_sensor_flg = 0; stopping_sensor_flg = 0; // モードを手動モードに設定 manual_mode_init(); } // // 主処理 // void process() { // UART入力を優先させる parse_uart_input(); // 割込みごとに処理(3.2768 ms) if (tmr0_toggle == 1) { // ロータリーエンコーダーによる検知処理 if (rotenc_detection() != 0) { process_on_change_rotenc_val(); } // スイッチ連続検知抑止 switch_prevent(); tmr0_toggle = 0; // センサー検知処理 sensor_detection(); } // 約 0.1 秒ごとに処理(3.2768ms × 30回) if (tmr0_total_cnt_100m > 30) { // カウンターを初期化 tmr0_total_cnt_100m = 0; // イベントごとの処理(モード/ステータス遷移)を行う process_on_100m_second(); } // 約 1.0 秒ごとに処理(3.2768ms × 305回) if (tmr0_total_cnt_1s > 305) { // カウンターを初期化 tmr0_total_cnt_1s = 0; // イベントごとの処理を行う process_on_one_second(); } // スイッチ検知処理 switch_detection(); }
C
/* Notes from mycodeschool videos - Function Pointers; Function pointers and callbacks function is a set of instructions. Function pointers store the starting address or the entry point of a block of memory containing instructions of a particular function */ #include <stdio.h> #include <stdlib.h> // stdlib.h is for the abs() function #include <math.h> // math.h is for qsort function int Add(int a, int b){ return a+b; } void printHello(){ printf("Hello!\n"); } void A(){ printf("Hello\n"); } void B(void (*ptr)()){ ptr(); } void BubbleSort(int a[], int size){ int temp; for(int i = 0; i < size; i++){ for(int j = 0; j < size-1; j++){ if(a[j] > a[j+1]){ temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } } } int ascending(int a, int b){ if(a > b) return 1; else return -1; } int descending(int a, int b){ if(a > b) return -1; else return 1; } int absoluteCompare(int a, int b){ if(abs(a) > abs(b)) return 1; else return -1; } void smartBubbleSort(int a[], int size, int (*compare)(int,int)){ /* callback function should compare two integers, should return 1 if first element is greater, 0 if elements are equal and -1 if second element is greater */ int temp; for(int i = 0; i < size; i++){ for(int j = 0; j < size-1; j++){ if(compare(a[j], a[j+1]) > 0 ){ temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } } } int qcompare(const void* a, const void* b){ int x = *((int*)a); // typecast to integer pointer (since it was void*) then dereference to get the value int y = *((int*)b); return x - y; } int main(){ // pointer to function tht // RETURN TYPE (*NAME OF F POINTER) (ARG TYPES) int (*p)(int, int); // INITIALIZE p = Add; // this works because the name of a function returns // the pointer to that function int c = (*p)(2,3); printf("%d\n", c); void (*h)(); h = printHello; (*h)(); /* function pointers are used when we want to pass functions as arguments to other functions */ void (*fp)() = A; B(fp); B(A); /* want to write a function that takes an array and sorts them in increasing order */ int arr[] = { -3,2,1,5,6,4,7}; BubbleSort(arr,7); for(int i = 0; i < 7; i++) printf("%d ", arr[i]); printf("\n"); /* what if we want to return the sorting in increasing order at times but also in decreasing order at times? */ /* we can write a smartBubbleSort method which takes in an extra parameter or flag to indicate the order which we want in the BubbleSort method, the order of sorting is determined by one point - the comparison between item[j] and item[j+1] we can calculate this part by using a function pointer */ printf("better sort\nAscending\n"); smartBubbleSort(arr, 7, ascending); for(int i = 0; i < 7; i++) printf("%d ", arr[i]); printf("\n"); printf("better sort\nDescending\n"); smartBubbleSort(arr, 7, descending); for(int i = 0; i < 7; i++) printf("%d ", arr[i]); printf("\n"); printf("better sort\nAbsolute\n"); smartBubbleSort(arr, 7, absoluteCompare); for(int i = 0; i < 7; i++) printf("%d ", arr[i]); printf("\n"); /* qsort can sort any array. You only have to specify the compare logic. qsort function takes an array, size of array, size of array data type and a pointer to a comparison function. the comparison function must take two const void pointers and returns an integer eg int qcompare(const void* a, const void* b) */ qsort(arr, 7, sizeof(int), qcompare); for(int i = 0; i < 7; i++) printf("%d ", arr[i]); printf("\n"); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<string.h> //ַ int cmp_str(const void *a,const void *b) { assert(a); assert(b); return strcmp(*(char **)a,*(char **)b); } void show(char **arr,int sz) { int i = 0; assert(arr); assert(sz); for (i = 0; i < sz; i++) { printf("%s ",arr[i]); } printf("\n"); } int main() { char *str[] = {"hello","kkkkkk","abfdm","aaaaaa"}; int sz = sizeof(str)/sizeof(str[0]); show(str,sz); qsort(str,sz,sizeof(str[0]),cmp_str); show(str,sz); system("pause"); return 0; }
C
#include <stdio.h> #define TABSTOP 4 int get_line(char storage[], int limit); int main(void) { return 0; } int get_line(char line[], int limit) { int i, c; for (i = 0; i < limit - 1 && (c == getchar()) != EOF && c != '\n' && c != '\0'; i++) line[i] = c; if (c == '\n') line[i++] = c; line[i] = '\0'; return i; }
C
/* Alumno: Vileriño,Silvio Curso:5to 2da Fecha: 11/5/09 */ #include <stdio.h> #include <stdlib.h> int esdivisibleportres(int); int main(){ int numero=0; system("clear"); printf("Ingrese Numero:"); scanf("%i",&numero); if (esdivisibleportres(numero)==0){ printf("\n%i Es Divisible por 3\n",numero); }else{ printf("\n%i NO es Divisible por 3\n",numero); } return(0); } int esdivisibleportres(int num){ static restos; if ((num/10)<10){ restos+=((num/10)+(num%10)); printf("\nFin,suma de los digitos= %i\n",restos); if((restos<10)){ if((restos==3)||(restos==6)||(restos==9)){ return(0); }else{ return(1); } }else{ num=restos; restos=0; return(esdivisibleportres(num)); } }else{ printf("\nDivision=%i , Resto=%i\n",(num/10),(num%10)); restos+=(num%10); return(esdivisibleportres(num/10)); } }
C
/* * usingmacro.c * * Created on: 2015. 5. 11. * Author: root */ #include <stdio.h> #define SIZE 100 int main(void) { printf("%d\n", 5 * SIZE); printf("%d\n", 3 * SIZE); printf("%d\n", 5 / SIZE); printf("%d\n", 7 * SIZE); printf("%d\n", 5 + SIZE); return 0; }
C
# include <stdio.h> # include <ctype.h> # define EOL '\n' void main() { char c[100]; int count=0; c[count]=getchar(); while(c[count] != EOL) { count++; c[count]=getchar(); putchar(c[count]); } int tag; tag=count; count=0; printf("\n"); printf(" The lowercase letters:\n"); while(count<=tag && c[count]>=65 && c[count]<=90 && isalpha(c[count])) { c[count]=c[count]+32; putchar(c[count]); count++; } printf("\nPlease enter a valid uppercase letter"); return; }
C
#include <stdlib.h> #include <stdio.h> /* * 置换(排列)输出 * */ void swap(char *left,char *right); void copy(char *left,char *right,int count); void perm(char * ,int,int,void (*handle)(char *,int)); void out(char *,int); int count = 0; int main(){ char list[]={'a','b','c','d'}; int count = (sizeof list)/ sizeof(char); // perm(list,0,count-1,out); } void perm(char list[],int left,int right,void (*handle)(char *,int)){ if(left==right){ handle(list,right); } int i; for (i = left; i <= right; ++i) { char tmp[right]; copy(tmp,list,right); swap(&tmp[left],&tmp[i]); perm(tmp,left+1,right,handle); } } // void out(char *list,int right){ int j; count++; printf("%d\t(",count); for (j=0;j<=right;j++){ printf("%c,",list[j]); } printf(")\n"); } // 交换 void swap(char *left,char *right){ char blank; blank = *left; *left = *right; *right = blank; } // void copy(char *left,char *right,int count){ int i; for (i=0;i<=count;i++){ left[i]=right[i]; } }
C
#ifndef CUSTOM_BOARD_H #define CUSTOM_BOARD_H /************************************************************ *----------------------custom_board.h------------------------- * ӵҪŷֲ io1Ϊ *------------------------------------------------------------- * λLEDx * LED1 P.18 LED5 P.17 LED9 P.22 * LED2 P.15 LED6 P.7 LED10 P.6 * LED3 P.14 LED7 P.8 LED11 P.9 * LED4 P.13 LED8 P.12 LED13 P.10 * LED12 P.11 * (LED13()LED12()Ӧ1λ) *-------------------------------------------------------------- * оƬ() * 6(bi--backward input) P.3 * 7(fi--forward input) P.2 *-------------------------------------------------------------- * (iic) * 4(iic_en) P.25 * 3(int) P.24 * 2(scl) P.0 * 1(sda) p.1 *--------------------------------------------------------------- * () * 1() P.4 *--------------------------------------------------------------- * UART(JK5) * 3(TX) P.29 * 4(RX) P.28 *************************************************************/ //LEDs #define LED_1 18 #define LED_2 15 #define LED_3 14 #define LED_4 13 #define LED_5 17 #define LED_6 7 #define LED_7 8 #define LED_8 12 #define LED_9 22 #define LED_10 6 #define LED_11 9 #define LED_12 11 #define LED_13 10 #define BSP_LED_0 LED_1 #define BSP_LED_1 LED_2 #define BSP_LED_2 LED_3 #define BSP_LED_3 LED_4 #define BSP_LED_4 LED_5 #define BSP_LED_5 LED_6 #define BSP_LED_6 LED_7 #define BSP_LED_7 LED_8 #define BSP_LED_8 LED_9 #define BSP_LED_9 LED_10 #define BSP_LED_10 LED_11 #define BSP_LED_11 LED_12 #define BSP_LED_12 LED_13 //beep #define BEEP_IN_PIN 4 #define LEDS_NUMBER 13 #define BSP_BUTTON_0_MASK (1<<BSP_BUTTON_0) #define LEDS_LIST { LED_1, LED_2, LED_3, LED_4, LED_5, LED_6, LED_7, LED_8, \ LED_9, LED_10, LED_11, LED_12, LED_13} #define BSP_LED_0_MASK (1<<LED_1) #define BSP_LED_1_MASK (1<<LED_2) #define BSP_LED_2_MASK (1<<LED_3) #define BSP_LED_3_MASK (1<<LED_4) #define BSP_LED_4_MASK (1<<LED_5) #define BSP_LED_5_MASK (1<<LED_6) #define BSP_LED_6_MASK (1<<LED_7) #define BSP_LED_7_MASK (1<<LED_8) #define BSP_LED_8_MASK (1<<LED_9) #define BSP_LED_9_MASK (1<<LED_10) #define BSP_LED_10_MASK (1<<LED_11) #define BSP_LED_11_MASK (1<<LED_12) #define BSP_LED_12_MASK (1<<LED_13) #define LEDS_MASK (BSP_LED_0_MASK | BSP_LED_1_MASK | BSP_LED_2_MASK |\ BSP_LED_3_MASK | BSP_LED_4_MASK | BSP_LED_5_MASK |\ BSP_LED_6_MASK | BSP_LED_7_MASK | BSP_LED_8_MASK |\ BSP_LED_9_MASK | BSP_LED_10_MASK | BSP_LED_11_MASK |\ BSP_LED_12_MASK ) /* all LEDs are lit when GPIO is low */ #define LEDS_INV_MASK LEDS_MASK //UART #define RX_PIN_NUMBER 28 #define TX_PIN_NUMBER 29 #define CTS_PIN_NUMBER 26 #define RTS_PIN_NUMBER 27 #define HWFC true //TOUCH-IIC #define TOUCH_IIC_EN_PIN 25 #define TOUCH_IIC_INT_PIN 24 #define TOUCH_IIC_SCL_PIN 0 #define TOUCH_IIC_SDA_PIN 1 //RTC-IIC #define RTC_IIC_SCL_PIN 0 #define RTC_IIC_SDA_PIN 1 //MOTO #define MOTO_FI 2 #define MOTO_BI 3 #endif
C
/* * File: main.h * Author: Chris Hajduk * * Created on October 15, 2013, 8:14 PM * * This file contains all GLOBAL constants needed for the code. * Avoiding adding stuff here unless you really need to. * */ #ifndef MAIN_H #define MAIN_H //Include Libraries #include <p33FJ256GP710A.h> #include <stdio.h> #include <stdlib.h> #include <math.h> //Define constants for global use in the code #define TRUE 1 #define FALSE 0 //Mathematical Constants #define PI 3.14159265 //Basic Mathematical Conversions #define deg2rad(DEG) ((DEG) * PI/180.0) #define rad2deg(RAD) ((RAD) * 180.0/PI) typedef enum{ waitingToStartTimer, drivingTimer, NUMBER_OF_TIMERS, } Timer; typedef enum{ waitingToStart, drivingForward, drivingBackward, turningRight, turningLeft, } MoveState; typedef enum{ phase1, phase2, phase3, test, } Task; typedef enum { false, true } boolean; #endif
C
#include <logging.h> #include <fstream> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; FILE* Logger::logger = NULL; void Logger::LogEvent(const char* event) { if(logger == NULL) { logger = fopen("logger","w"); } fprintf(logger,"%s",event); } void Logger::Finalize() { fclose(logger); } DataFlowException::DataFlowException(const char *type, const char *error) { //strcpy(this->msg,"(",type,"): ",error); sprintf(this->msg,"Throwing Exception (%s): %s\n",type,error); Logger::LogEvent(msg); }
C
#include<stdio.h> #include<string.h> void get_record() { printf("Enter record:"); char record[128] = ""; gets(record); } int main(int argc,char **argv) { get_record(); }
C
#include <stdio.h> int main(){ //2.4a int a, c; c = 1; c++; a = 2 * c; printf("%d True\n", a);//True //False 2.4b c = 1; a = 2 * c++; printf("%d False\n",a); //True 2.4c c = 1; c += 1; a = c + c; printf("%d True\n",a); //False 2.4d c = 1; a = c++ + c; printf("%d False\n",a); //True 2.4e c = 1; ++c; a = c + c; printf("%d True\n",a); //True 2.4f c = 1; a = ++ c + c; printf("%d True\n",a); //False 2.4j c = 1; a = c += 1 + c; printf("%d False\n",a); //True 2.4h c = 1; a = (c+=1)+c; printf("%d True\n",a); c = 5; c = c - 1/2; printf("%f",c); }
C
#include <stdio.h> main() { int a = 10, b; a >= 5 ? b = 100 : (b = 200); printf("%d\n", b); }
C
#include<stdio.h> void main() { int a,b,div,mod; printf("enter the values"); scanf("%d%d",&a,&b); mod=a%b; div=a/b; printf("%d\t",div); printf("%d\t",mod); }
C
#include "sctpArgs.h" void free_memory() { free(args); } static void address(char *address, int port, struct sockaddr_in *addr) { int r_4; // Try to match with IPv4 r_4 = inet_pton(AF_INET, address, &addr->sin_addr); // IPv4 unsuccessful, try with IPv6 if (r_4 <= 0) { printf("Cannot determine address family %s, please try again with a valid address.\n", address); fprintf(stderr, "Address resolution error\n"); free_memory(); exit(0); } else { addr->sin_family = AF_INET; addr->sin_port = htons(port); } } static void address6(char *address, int port, struct sockaddr_in6 *addr) { // Try to match with IPv4 int r_6 = inet_pton(AF_INET6, address, &addr->sin6_addr); // IPv6 error, exit if (r_6 <= 0) { printf("Cannot determine address family %s, please try again with a valid address.\n", address); fprintf(stderr, "Address resolution error\n"); free_memory(); exit(0); } else { addr->sin6_family = AF_INET6; addr->sin6_port = htons(port); } } static int get_addr_type(char *address) { struct in_addr inaddr; struct in6_addr in6addr; int r_4, r_6; // Try to match with IPv4 r_4 = inet_pton(AF_INET, address, &inaddr); // IPv4 unsuccessful, try with IPv6 if (r_4 <= 0) { // Try to match with IPv4 r_6 = inet_pton(AF_INET6, address, &in6addr); // IPv6 error, exit if (r_6 <= 0) { printf("Cannot determine address family %s, please try again with a valid address.\n", address); fprintf(stderr, "Address resolution error\n"); free_memory(); exit(0); } else { return AF_INET6; } } else { return AF_INET; } } static unsigned short port(const char *s) { char *end = 0; const long sl = strtol(s, &end, 10); if (end == s || '\0' != *end || ((LONG_MIN == sl || LONG_MAX == sl) && ERANGE == errno) || sl < 0 || sl > USHRT_MAX) { fprintf(stderr, "port should in in the range of 1-65536: %s\n", s); free_memory(); exit(1); return 1; } return (unsigned short)sl; } static void version(void) { fprintf(stderr, "sctp client version 0.0\n" "ITBA Protocolos de Comunicación 2020/1 -- Grupo 2\n" "AQUI VA LA LICENCIA\n"); } static void usage(const char *progname) { fprintf(stderr, "Usage: %s [OPTION]...\n" "\n" " -h Imprime la ayuda y termina.\n" " -L <conf addr> Dirección donde servirá el servicio de management.\n" " -P <conf port> Puerto entrante conexiones configuracion\n" " -v Imprime información sobre la versión versión y termina.\n" "\n", progname); free_memory(); exit(1); } // Variable for the options sctpClientArgs args; void parse_args(const int argc, char **argv) { args = malloc(sizeof(*args)); memset(args, 0, sizeof(*args)); args->mng_addr = "127.0.0.1"; args->mng_addr6 = "::1"; args->mng_port = 8080; memset(&args->mng_addr_info, 0, sizeof(args->mng_addr_info)); memset(&args->mng_addr_info6, 0, sizeof(args->mng_addr_info6)); int c; while (true) { c = getopt(argc, argv, "hL:P:v"); if (c == -1) break; switch (c) { case 'h': usage(argv[0]); break; case 'L': args->mng_addr = optarg; args->mng_family = get_addr_type(args->mng_addr); if (args->mng_family == AF_INET) { address(args->mng_addr, args->mng_port, &args->mng_addr_info); } else if (args->mng_family == AF_INET6) { address6(args->mng_addr, args->mng_port, &args->mng_addr_info6); } break; case 'P': args->mng_port = port(optarg); if (args->mng_family == AF_INET6) { args->mng_addr_info6.sin6_port = htons(args->mng_port); } else if (args->mng_family == AF_INET) { args->mng_addr_info.sin_port = htons(args->mng_port); } break; case 'v': version(); free_memory(); exit(0); break; default: fprintf(stderr, "unknown argument %d.\n", c); free_memory(); exit(1); } } if (optind < argc) { fprintf(stderr, "argument not accepted: "); while (optind < argc) { fprintf(stderr, "%s ", argv[optind++]); } fprintf(stderr, "\n"); free_memory(); exit(1); } }
C
#include<stdio.h> #include<ctype.h> #include<string.h> int main(int argc,char *argv[]) { int i; for (int i = argc; argc > 0; i--) { if (islower(argv[i])) { argv[i] = toupper(argv[i]); } else if (isupper(argv[i])) { argv[i] = toupper(argv[i]); } } }//!!!!
C
#include<stdio.h> #include<math.h> /* * main.c */ int main(void) { int N,k,n,i; float pi=3.1416,sumre=0,sumim=0,out_real[8]={0,0},out_imag[8]={0,0}; int x[32]; printf("Enter the length of sequence: "); scanf("%d", &N); printf("Enter the sequence: "); for(i=0;i<N;i++){ scanf("%d",&x[i]); } for(k=0;k<N;k++){ sumre=0; sumim=0; for(n=0;n<N;n++){ sumre=sumre+x[n]*cos(2*pi*k*n/N); sumim=sumim-x[n]*sin(2*pi*k*n/N); } out_real[k]=sumre; out_imag[k]=sumim; printf("x([%d])=\t%f\t+\t%fj\n",k,out_real[k],out_imag[k]); } return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int bigEndian() { short test = 0x0001; char* x = (char*) &test; //returns 0 if big endian, return 1 if little endian //big endian : 00 01 //little endian: 01 00 //return value: ^ return *x; } int main(int argc, char *argv[]){ if (strcmp (argv[0],"little") == 0) { exit(!bigEndian()); } else { exit(bigEndian()); } }
C
#include "ds/queue_array.h" void copy_value_to_node_float(Queue_Array* queue, void* value) { float* temp = (float*) queue->buffer[queue->rear]; *temp = *(float*) value; } void copy_value_to_node_double(Queue_Array* queue, void* value) { double* temp = (double*) queue->buffer[queue->rear]; *temp = *(double*) value; } void copy_value_to_node_long_double(Queue_Array* queue, void* value) { long double* temp = (long double*) queue->buffer[queue->rear]; *temp = *(long double*) value; }
C
#include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <pthread.h> #include <semaphore.h> /* Written by : Yunus Emre Ertunc Muhammed Enes Akturk */ int checkDigit(char temp[]){ int length = strlen(temp); int i = 0; for(i = 0 ; i < length; i++){ if(isdigit(temp[i])){ return 1; } } return 0; } int getAndCheckArguments(int argc , char *argv[], int *numPublisherType , int *numPublisherCount,int *numPackagerCount, int *numPublishingBook, int *numPackagerBook, int *bufferSize){ //argc -> girilen argüman sayısını veriyor if(argc != 10){ printf("Please check your arguments!\nPlease just write 0 , If you do not want to enter any threads!\n"); return -1; } int i = 0; for(i = 1 ; i < argc-1 ; i++){ int sc = -1; char temp[50]; strcpy(temp,argv[i]); if(strcmp(argv[i],"-n") == 0){sc = 0;} // if option is -n else if(strcmp(argv[i],"-b") == 0){sc = 1;} // if option is -b else if(strcmp(argv[i],"-s") == 0){sc = 2;} // // if option is -s else if(!checkDigit(temp)){ printf("Please check your arguments !\n"); return -1; } switch(sc){ case 0:{ // -n char temp1[10]; char temp2[10]; char temp3[10]; strcpy(temp1,argv[i+1]); strcpy(temp2,argv[i+2]); strcpy(temp3,argv[i+3]); //This part indicates that if(!(checkDigit(temp1) && checkDigit(temp2) && checkDigit(temp3))){ //you have to give 3 digit after -n option. printf("Please check your arguments !\n"); return -1; } *numPublisherType = atoi(argv[i+1]); // this is for publisher type threads *numPublisherCount = atoi(argv[i+2]); // this is for publisher type threads count *numPackagerCount = atoi(argv[i+3]); // this is for packager threads count break; } case 1:{ // -b char temp1[10]; strcpy(temp1,argv[i+1]); if(!(checkDigit(temp1))){ //This part indicates that you have to give 1 digit after -b option printf("Please check your arguments !\n"); return -1; } *numPublishingBook = atoi(argv[i+1]); // this indicates how many book each publisher thread can publish break; } case 2:{ // -s char temp1[10]; char temp2[10]; strcpy(temp1,argv[i+1]); strcpy(temp2,argv[i+2]); if(!(checkDigit(temp1) && checkDigit(temp2))){ printf("Please check your arguments !\n"); return -1; } *numPackagerBook = atoi(argv[i+1]); // this indicates how many book each packager thread can package *bufferSize = atoi(argv[i+2]); // this indicates buffer size break; } default: break; } } return 0; } //--------------------------------------------------// Program starts at that point //Global Variables int numPublisherType = -1; int numPublisherCount = -1; //in total, there will be numPublisherType * numPublisherCount threads. int numPackagerCount = -1; int numPublishingBook = -1; int numPackagerBook = -1; int bufferSize = -1; typedef struct args{ int type; int index; int bookCount; pthread_t pubThread[10000000]; }args; //publisher part struct publisherBufferList{ // this struct will hold books for each type int bookIndex; char bookName[50]; struct publisherBufferList *nextPtr; }; typedef struct publisherBufferList PublisherBufferList; typedef PublisherBufferList *PublisherBufferPtr; struct publisherTypeList{ // this struct will hold publisher type list int pType; int pIndex; int bufSize; // this is the buffer size for each type of publisher buffer int threadCount; sem_t semaphore_queue; sem_t semaphore_queue_packager; sem_t semaphore_pub_pack; int isLocked; pthread_t pubThread[10000000]; struct publisherBufferList *bufferPtr; // this will hold the buffer for corresponding type struct publisherTypeList *nextPtr; }; typedef struct publisherTypeList PublisherTypeList; typedef PublisherTypeList *PublisherTypePtr; //packager part struct packagerBufferList{ char bookName[50]; struct packagerBufferList *nextPtr; }; typedef struct packagerBufferList PackagerBufferList; typedef PackagerBufferList *PackagerBufferListPtr; struct packagerList{ int packIndex; int packSize; struct packagerBufferList *bufferPtr; // this will hold the buffer for corresponding packager struct packagerList *nextPtr; }; typedef struct packagerList PackagerList; typedef PackagerList *PackagerListPtr; // Insert to the publisher type list void insertPublisherType(PublisherTypePtr *sPtr,int pType,int pIndex,int bufSize,int threadCount){ PublisherTypePtr newPtr = malloc(sizeof(PublisherTypeList)); if(newPtr != NULL){ newPtr->pType = pType; newPtr->pIndex = pIndex; newPtr->bufSize = bufSize; newPtr->threadCount = threadCount; newPtr->isLocked = 0; sem_init(&(newPtr->semaphore_queue) , 0 , 1); sem_init(&(newPtr->semaphore_queue_packager), 0 , 1); sem_init(&(newPtr->semaphore_pub_pack) , 0 , 1); PublisherBufferPtr bufferStartPtr = NULL; newPtr->bufferPtr = bufferStartPtr; newPtr->nextPtr = NULL; PublisherTypePtr previousPtr = NULL; PublisherTypePtr currentPtr = *sPtr; while(currentPtr != NULL){ previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if(previousPtr == NULL){ newPtr->nextPtr = *sPtr; *sPtr = newPtr; } else{ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } } else{ printf("There is no memory available.\n"); } } // Insert to the publisher buffer list void insertPublisherBuffer(PublisherBufferPtr *sPtr,int bookIndex,char bookName[]){ PublisherBufferPtr newPtr = malloc(sizeof(PublisherBufferList)); if(newPtr != NULL){ newPtr->bookIndex = bookIndex; strcpy(newPtr->bookName,bookName); newPtr->nextPtr = NULL; PublisherBufferPtr previousPtr = NULL; PublisherBufferPtr currentPtr = *sPtr; while(currentPtr != NULL){ previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if(previousPtr == NULL){ newPtr->nextPtr = *sPtr; *sPtr = newPtr; } else{ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } } else{ printf("There is no memory available.\n"); } } // Insert to the packager list void insertPackagerList(PackagerListPtr *sPtr,int packIndex,int packSize, char bookName[]){ PackagerListPtr newPtr = malloc(sizeof(PackagerList)); if(newPtr != NULL){ newPtr->packIndex = packIndex; newPtr->packSize = packSize; newPtr->nextPtr = NULL; PackagerBufferListPtr pBufferPtr = NULL; newPtr->bufferPtr = NULL; PackagerListPtr previousPtr = NULL; PackagerListPtr currentPtr = *sPtr; while(currentPtr != NULL){ previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if(previousPtr == NULL){ newPtr->nextPtr = *sPtr; *sPtr = newPtr; } else{ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } } else{ printf("There is no memory available.\n"); } } void insertPackagerBufferList(PackagerBufferListPtr *sPtr , char bookName[]){ PackagerBufferListPtr newPtr = malloc(sizeof(PackagerBufferList)); if(newPtr != NULL){ strcpy(newPtr->bookName,bookName); newPtr->nextPtr = NULL; PackagerBufferListPtr previousPtr = NULL; PackagerBufferListPtr currentPtr = *sPtr; while(currentPtr != NULL){ previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if(previousPtr == NULL){ newPtr->nextPtr = *sPtr; *sPtr = newPtr; } else{ previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } } else{ printf("There is no memory available.\n"); } } int isEmptyType(PublisherTypePtr sPtr){return sPtr == NULL;} int isEmptyPackage(PackagerListPtr sPtr){return sPtr == NULL;} int isEmptyBuffer(PublisherBufferPtr sPtr){return sPtr == NULL;} void printPackagerList(PackagerListPtr currentPtr){ if(isEmptyPackage(currentPtr)){ puts("List is empty"); } else{ while(currentPtr != NULL){ printf("packIndex : %d packSize : %d\n",currentPtr->packIndex , currentPtr->packSize); currentPtr = currentPtr->nextPtr; } } } void printBufferList(PublisherBufferPtr currentPtr){ if(isEmptyBuffer(currentPtr)){ puts("List is empty"); } else{ while(currentPtr != NULL){ printf("Book Index : %d , Book Name : %s\n",currentPtr->bookIndex,currentPtr->bookName); currentPtr = currentPtr->nextPtr; } } } void printPubTypeList(PublisherTypePtr currentPtr){ if(isEmptyType(currentPtr)){ puts("List is empty"); } else{ while(currentPtr != NULL){ printf("pType : %d bufSize : %d\n",currentPtr->pType,currentPtr->bufSize); printBufferList(currentPtr->bufferPtr); currentPtr = currentPtr->nextPtr; } } } void initiliazeBuffer(PublisherTypePtr *sPtr , int typeIndex){ //This function creates all the nodes at the beginning of the program PublisherTypePtr tempPtr = *sPtr; while(tempPtr != NULL){ if(tempPtr->pType == typeIndex){ break; } tempPtr = tempPtr -> nextPtr; } int i = 0; for(i = 0; i < tempPtr->bufSize; i++){ insertPublisherBuffer(&(tempPtr->bufferPtr) , -1 , "" ); } } void initiliazePackagerBuffer(PackagerListPtr *sPtr, int index){ //This function creates all the nodes at the beginning of the program PackagerListPtr tempPtr = *sPtr; while(tempPtr != NULL){ if(tempPtr->packIndex == index){ break; } tempPtr = tempPtr->nextPtr; } int i=0 ; for(i=0 ; i<numPackagerBook ; i++){ insertPackagerBufferList(&(tempPtr->bufferPtr) , ""); } } //GLOBAL VARIABLES PublisherTypePtr publisherStartPtr = NULL; PackagerListPtr packagerStartPtr = NULL; int getPublishedBookSize(int type){ // this method will give us the number of books in the buffer PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ // bütün type listesini gezecek ve dogru type ı bulacak if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } if(tempPtr == NULL) return 0; PublisherBufferPtr tempBuffer = tempPtr->bufferPtr; int count = 0; while(tempBuffer != NULL){ if(tempBuffer->bookIndex != -1 && tempBuffer->bookIndex != -2){ //kitap isminin uzunlugundan node içinde kitap var mı yok mu anlayabilrz count++; } tempBuffer = tempBuffer->nextPtr; } return count; } int getNodeNumberInBuffer(int type){ //This function gives us the number of nodes in the buffer PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ // bütün type listesini gezecek ve dogru type ı bulacak if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } PublisherBufferPtr tempBuffer = tempPtr->bufferPtr; int count = 0; while(tempBuffer != NULL){ count++; tempBuffer = tempBuffer->nextPtr; } return count; } void resizeBuffer(int type){ //This function doubles the size of the buffer PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ // bütün type listesini gezecek ve dogru type ı bulacak if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } int previousSize = tempPtr->bufSize; tempPtr->bufSize = tempPtr->bufSize * 2; //size is doubled here int i = 0; for(i = 0 ; i < previousSize ; i++){ // bir önceki size kadar yeni node üretecek insertPublisherBuffer(&(tempPtr->bufferPtr) , -1 , "" ); //creating new nodes } } void insertToBuffer(int index , char bookName[], PublisherTypePtr *tempPtr ){ //This method puts book into the buffer PublisherBufferPtr tempBuffer = (*tempPtr)->bufferPtr; while(tempBuffer->bookIndex != -1 && tempBuffer->bookIndex != -2){ tempBuffer = tempBuffer->nextPtr; } tempBuffer->bookIndex = index; strcpy(tempBuffer->bookName,bookName); } void publishBook(int type, int bookIndex , int index){ // This function finds correct node and add books into its buffer PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ // bütün type listesini gezecek ve dogru type ı bulacak if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } char buf[12]; snprintf(buf, 12, "Book%d_%d", type ,tempPtr->pIndex+1); printf("Publisher %d of type %d \t%s is published and put into the buffer %d.\n",index,type , buf,type); insertToBuffer(tempPtr->pIndex+1,buf , &tempPtr); tempPtr->pIndex = tempPtr->pIndex + 1 ; } void *publisher(void *Args){ //This is the publisher thread's function struct args *pArgs = (struct args *)Args; int type = pArgs->type; int index = pArgs->index; PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(type == tempPtr->pType) break; tempPtr = tempPtr->nextPtr; } sem_wait(&(tempPtr->semaphore_queue)); //Locking this area sem_wait(&(tempPtr->semaphore_pub_pack)); int i; for(i = 1; i <= numPublishingBook; i++){ if(getPublishedBookSize(type) == getNodeNumberInBuffer(type) ){ printf("Publisher %d of type %d \tBuffer is full. Resizing the buffer.\n",index,type); resizeBuffer(type); } publishBook(type, i , index); if(i == numPublishingBook){ tempPtr->threadCount -= 1; printf("Publisher %d of type %d \tFinished publishing %d books. Exiting the system.\n",index,type,numPublishingBook); (tempPtr->pubThread)[index-1] = 0; } } sem_post(&(tempPtr->semaphore_pub_pack)); //unlocking part sem_post(&(tempPtr->semaphore_queue)); } void packageBook(int type, int index){ //This function is to package the book PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } PackagerListPtr packagerTempPtr = packagerStartPtr; while(packagerTempPtr != NULL){ if(packagerTempPtr->packIndex == index){ break; } packagerTempPtr = packagerTempPtr->nextPtr ; } PackagerBufferListPtr bufferPtr = packagerTempPtr->bufferPtr ; PublisherBufferPtr tempPublisherBuffer = tempPtr->bufferPtr; while(tempPublisherBuffer != NULL){ ///correct book if(tempPublisherBuffer->bookIndex != -1 && tempPublisherBuffer->bookIndex != -2){ break; } tempPublisherBuffer = tempPublisherBuffer->nextPtr; } while(bufferPtr != NULL){ ///correct place in the buffer if(strlen(bufferPtr->bookName) < 2){ break; } bufferPtr = bufferPtr->nextPtr; } if(tempPublisherBuffer == NULL) return; if(bufferPtr == NULL) return; printf("Packager %d \tPut %s into the package.\n",index,tempPublisherBuffer->bookName); strcpy(bufferPtr->bookName , tempPublisherBuffer->bookName); //adding book into buffer packagerTempPtr->packSize -= 1; strcpy(tempPublisherBuffer->bookName , ""); //Cleaning publisher buffer tempPublisherBuffer->bookIndex = -2; } int checkAllThreads(){ int control = 0 ; PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(tempPtr->threadCount > 0) control = 1 ; tempPtr = tempPtr->nextPtr; } if(control == 0) return 1 ; // if there is not any thread in the system , returns 1 else return 0 ; // else 0 } int checkPublisherThread(int type){ //Checks is there any thread of that type or not PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } if(tempPtr == NULL ) return 0; if(tempPtr->threadCount != 0) return 1; else return 0 ; } int checkPackageSize(int index){ //This function checks the package size of packager PackagerListPtr tempPtr = packagerStartPtr; while(tempPtr != NULL){ if(tempPtr->packIndex == index){ break; } tempPtr = tempPtr->nextPtr; } if(tempPtr->packSize == 0){ return 0; } else{ return 1; } } void printAndResetPackBuffer(int index){ // This function prints all books in the package and then reset package PackagerListPtr tempPtr = packagerStartPtr; while(tempPtr != NULL){ if(tempPtr->packIndex == index){ break; } tempPtr = tempPtr->nextPtr; } PackagerBufferListPtr bufferPtr = tempPtr->bufferPtr ; printf("Packager %d\tFinished preparing one package. The package contains: ",index); while(bufferPtr != NULL){ printf("%s " , bufferPtr->bookName); strcpy(bufferPtr->bookName,""); //silmek icin bufferPtr = bufferPtr->nextPtr; } printf("\n"); tempPtr->packSize = numPackagerBook; // } void waitThread(int type){ //This function is to wait thread PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } int i ; int rc; for(i = 0; i < numPublisherCount; i++ ){ if((tempPtr->pubThread)[i] == 0) continue; rc = pthread_join((tempPtr->pubThread)[i],NULL); if(rc == 0){ return; } } } void lockType(int type){ // This function locks the publisher type PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } if(tempPtr == NULL) return; sem_wait(&(tempPtr->semaphore_queue_packager)); } void unLockType(int type){ // This function unlocks the publisher type PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(tempPtr->pType == type){ break; } tempPtr = tempPtr->nextPtr; } if(tempPtr == NULL) return; sem_post(&(tempPtr->semaphore_queue_packager)); } int checkBooks(){ //checks is there any book or not PublisherTypePtr tempPtr = publisherStartPtr; int flag = 0; while(tempPtr != NULL){ if(getPublishedBookSize(tempPtr->pType) != 0){ flag = 1; break; } tempPtr = tempPtr->nextPtr; } return flag; } void printAndExit(int index){ // Prints all the books from its package then exit system int count = 0 ; PackagerListPtr tempPtr = packagerStartPtr; while(tempPtr != NULL){ if(tempPtr->packIndex == index){ break; } tempPtr = tempPtr->nextPtr; } PackagerBufferListPtr bufferPtr = tempPtr->bufferPtr ; int i ; for(i=0 ; i<numPackagerBook ; i++){ if(strlen(bufferPtr->bookName)>2){ count++; } bufferPtr = bufferPtr->nextPtr; } printf("Packager %d \tThere are no publishers left in the system.Only %d of %d number of books could be packaged.The package contains : ",index,count,numPackagerBook); bufferPtr = tempPtr->bufferPtr ; for(i=0 ; i<numPackagerBook ; i++){ if(strlen(bufferPtr->bookName)>2){ printf("%s ",bufferPtr->bookName); } bufferPtr = bufferPtr->nextPtr; } printf("Exiting the system.\n"); } sem_t semaphore_queue_packager; void *packager(void *Args){ // This function is packager thread's function struct args *pArgs = (struct args *)Args; int index = pArgs->index; while(1){ int randomType = rand() % numPublisherType + 1 ; lockType(randomType); // locking pub type node if(getPublishedBookSize(randomType) > 0){ packageBook(randomType,index); if(checkPackageSize(index) == 0){ printAndResetPackBuffer(index); } } else if(checkPublisherThread(randomType) == 1){ waitThread(randomType); packageBook(randomType,index); if(checkPackageSize(index) == 0){ printAndResetPackBuffer(index); } } else if(checkBooks() == 0 && checkAllThreads()){ printAndExit(index); unLockType(randomType); pthread_exit(NULL); } unLockType(randomType); // unlocking pub type node } } int main(int argc, char *argv[]){ //Argument Error handling if(getAndCheckArguments(argc,argv,&numPublisherType,&numPublisherCount,&numPackagerCount,&numPublishingBook,&numPackagerBook,&bufferSize) == -1){ return -1; } //toplam publisher thread sayısı belli oldugu için fix size array olusturulabilir pthread_t publishers[numPublisherType * numPublisherCount]; //packager sayısı bilindiğinden fix size array olusturulabilir pthread_t packagers[numPackagerCount]; sem_init (&semaphore_queue_packager,0,1); void * status; int rc; int i = 0; int j = 0; int pIndex = -1; for(i = 1; i <= numPublisherType; i++){ //Adding into publisher type list insertPublisherType(&publisherStartPtr , i , 0 , bufferSize,numPublisherCount); //type index bufsize initiliazeBuffer(&publisherStartPtr , i); // buffer nodes are initiliazed for(j = 1; j <= numPublisherCount; j++){ pIndex++; args *pArgs = (args*)malloc(sizeof(args)); //.............// pArgs->type = i; pArgs->index = j; pArgs->bookCount = numPublishingBook; rc = pthread_create(&(publishers[pIndex]),NULL,&publisher,(void *)pArgs); if(rc){ printf("ERROR\n"); } PublisherTypePtr tempPtr = publisherStartPtr; while(tempPtr != NULL){ if(tempPtr->pType == i){ break; } tempPtr = tempPtr->nextPtr; } (tempPtr->pubThread)[j - 1] = publishers[pIndex]; } } // printPubTypeList(publisherStartPtr); for(i = 0; i < numPackagerCount; i++){ //Adding into packager list insertPackagerList(&packagerStartPtr , i+1 , numPackagerBook , NULL); // index , size book name initiliazePackagerBuffer(&packagerStartPtr,i+1); args *pgArgs = (args*)malloc(sizeof(args)); //.............// pgArgs->type = -1; pgArgs->index = i+1; rc = pthread_create(&(packagers[i]),NULL,&packager,(void *)pgArgs); if(rc){ printf("ERRROOOOOOOOOR\n"); } } // printPackagerList(packagerStartPtr); //Waiting part pIndex = 0; for(i = 1; i <= numPublisherType; i++){ for(j = 1; j <= numPublisherCount; j++){ //rc = pthread_join(publishers[pIndex], &status); if (rc) { printf("ERROR; return code from pthread_join() is %d %d %d\n", rc, i , j); exit(-1); } // printf("Main: completed join with thread %ld having a status of %ld\n",pIndex,(long)status); pIndex++; } } for(i = 0; i < numPackagerCount;i++){ rc = pthread_join(packagers[i], &status); if (rc) { printf("ERROR; return code from pthread_join() is %d %d\n", rc, i ); exit(-1); } // printf("Main: completed join with thread %ld having a status of %ld\n",i,(long)status); } printf("Main: program completed. Exiting.\n"); pthread_exit(NULL); return 0; }
C
#include <stdio.h> #include <string.h> #include "Utilities.h" #include "MatricesUtilities.h" #define INFINITY 1000 typedef struct scoreMoves{ int row; int col; int isMove; int ori; double value; }MOVE; MOVE alphaBeta(char **board,int sizeBoard,int position[2][2],int walls[2],int depth,const int initialDepth,int maxPL,int maximizingPlayer,double alpha,double beta,int maximizer); extern int moves[12][7]; int playmove(char **board,int position[2][2],int sizeBoard,char **cmd) { int player=atoi(cmd[1]); int targetRow,targetCol,legal=0; char temp; int rows = 2* sizeBoard,columns = 4 * sizeBoard; char *tempCmd; temp = cmd[2][0]; tempCmd = &(cmd[2][1]); targetRow = atoi(tempCmd); if (temp >= 'A' && temp <= 'Z') temp += 'a' - 'A'; if (targetRow <= 0 || targetRow > rows / 2 || temp - 'a' < 0 || temp - 'a' >= columns / 4 ){ printf("? illegal move\n\n"); return 0; } targetRow = rows - (2*targetRow) + 1; targetCol = 4 *(temp - 'a') + 2; legal = check_Legal_Move(board,rows,columns,targetRow,targetCol,position[player][0],position[player][1]); if (legal){ simpleMove(board,player,rows,targetRow,targetCol,position); printf("=\n\n"); fflush(stdout); insertMove(player,0,targetRow,targetCol,-1); } else printf("? illegal move\n\n"); return 0; } void playwall(char **board,int sizeBoard,int walls[2],int position[2][2],char **cmd){ char temp; int targetRow,targetCol,legal,player; int rows = 2 * sizeBoard,columns = 4 * sizeBoard,wallOrientation; int **visited; char *tempCmd; player = atoi(cmd[1]); temp = cmd[2][0]; tempCmd = &(cmd[2][1]); targetRow = atoi(tempCmd); if (temp >= 'A' && temp <= 'Z') temp += 'a' - 'A'; targetRow = rows - (2*targetRow) + 1; targetCol = 4 *(temp - 'a') + 2; visited = createVisited(rows,columns); toLower(cmd[3]); if (cmd[3] != NULL && ((strcmp(cmd[3],"horizontal") == 0) || strcmp(cmd[3],"h") == 0)) wallOrientation = 1; else if (cmd[3] != NULL && strcmp(cmd[3],"vertical") == 0 || strcmp(cmd[3],"v") == 0) wallOrientation = 0; else{ printf("? illegal move\n\n"); fflush(stdout); return; } if (walls[player]>0){ legal = check_Legal_Wall(board,rows,columns,targetRow,targetCol,wallOrientation,walls[0]); if (legal) legal = tryWall(board,rows,columns,targetRow,targetCol,position,wallOrientation,0,visited,walls,rows-1); //black if (legal) legal = tryWall(board,rows,columns,targetRow,targetCol,position,wallOrientation,1,visited,walls,1); //white if (legal){ printf("=\n\n"); walls[player] -= 1; fflush(stdout); insertMove(player,1,targetRow,targetCol,wallOrientation); } else printf("? illegal move\n\n"); } else if (player != 1 && player != 0) printf("? wrong syntax\n\n"); else if (walls[player] == 0) printf("? illegal move\n\n"); freeVisited(visited,rows); } void genmove(char **board,int sizeBoard,int position[2][2],int walls[2],int depth,int maxPL,int maxPlayer){ MOVE bestMove; int rows = 2*sizeBoard; int columns = 4* sizeBoard; int winningRow,flag=0,i; double alpha,beta; const int initialDepth = depth; alpha = -INFINITY; beta = INFINITY; if (maxPL) winningRow = 1; else winningRow = 2*sizeBoard -1; /*Checks if there is an immediate move that makes the player win.If there is,there is no need to run alphaBeta.*/ for (i=0;i<12;i++){ if (moves[i][4] == 0){ if(position[maxPL][0] != moves[i][2] && position[maxPL][1] != moves[i][3] && (check_Legal_Move(board,rows,columns,position[maxPL][0] + moves[i][0],position[maxPL][1] + moves[i][1],position[maxPL][0],position[maxPL][1])) && position[maxPL][0] + moves[i][0] == winningRow ){ flag = 1; break; } } else if (moves[i][4] == 1){ if((position[maxPL][0]*moves[i][5] > moves[i][2]*moves[i][5])&&(position[maxPL][1]*moves[i][6] > moves[i][3]*moves[i][6])&& (check_Legal_Move(board,rows,columns,position[maxPL][0] + moves[i][0],position[maxPL][1] + moves[i][1],position[maxPL][0],position[maxPL][1])) && position[maxPL][0] + moves[i][0] == winningRow){ flag = 1; break; } } } if (flag == 1){ bestMove.isMove =1; bestMove.row = position[maxPL][0] + moves[i][0]; bestMove.col = position[maxPL][1] + moves[i][1]; } else bestMove = alphaBeta(board,sizeBoard,position,walls,depth,initialDepth,maxPL,1,alpha,beta,maxPL); if(bestMove.isMove == 1){ simpleMove(board,maxPL,rows,bestMove.row,bestMove.col,position); insertMove(maxPL,0,bestMove.row,bestMove.col,-1); printf("= %c%d\n\n",(position[maxPL][1]-2)/4 + 'a',(rows - position[maxPL][0] + 1)/2); fflush(stdout); } else if (bestMove.isMove == 0){ simpleWall(board,bestMove.ori,rows,bestMove.row,bestMove.col); insertMove(maxPL,1,bestMove.row,bestMove.col,bestMove.ori); if (bestMove.ori == 0){ printf("= %c%d vertical\n\n",(bestMove.col-2)/4 + 'a',(rows - bestMove.row + 1)/2); fflush(stdout); } else{ printf("= %c%d horizontal\n\n",(bestMove.col-2)/4 + 'a',(rows - bestMove.row + 1)/2); fflush(stdout); } walls[maxPL]--; } else printf("TO THE NOPEVILLE!!!! \n\n"); } int showboard(char **board,int size,int walls[2]) { int i,j,k,counter; counter = 1; for (i=0;i<8;i++) putchar(' '); putchar('A'); /*Printing Letters indicating columns.*/ for (i=0;i<7;i++) putchar(' '); for (j=0;j<2 *(4*size-2) -4 ;j++){ if (j % 8 == 0){ putchar('A' + counter); counter++; } else putchar(' '); } putchar('\n'); /*Ends here.*/ for (i=0;i<2*size +1 ;i++){ putchar(' '); putchar(' '); putchar(' '); for (j=0;j<4*size +1;j++){ if (j == 0 && i % 2 == 1){ /*Printing each line.*/ if ((2*size/2)-(i/2) < 10) printf("\b%d ",(2*size/2)-(i/2)); else printf("\b\b%d ",(2*size/2)-(i/2)); } else putchar(' '); printf("%c",board[i][j]); } putchar(' '); if (j == 4*size +1 && i % 2 == 1){ printf("%d",(2*size/2)-(i/2)); if (i==1) printf(" black walls: %d",walls[0]); if (i==3) printf(" white walls: %d",walls[1]); } putchar('\n'); } counter = 1; for (i=0;i<8;i++) putchar(' '); putchar('A'); for (i=0;i<7;i++) putchar(' '); for (j=0;j<2 * (4*size-2) -4;j++){ if (j % 8 == 0){ putchar('A' + counter); counter++; /*Printing letters once again.*/ } else putchar(' '); } putchar('\n'); return 0; }
C
#include <stdio.h> #include <pthread.h> #include <unistd.h> void *test_print(void *arg)//线程创建成功后会执行这个方法 { int i; for ( i = 0; i < 10; i++) { printf("cthread: test_print start--->i = %d\n", i); } return arg; } int main() { pthread_t main_tid; int err = pthread_create(&main_tid, NULL, test_print, NULL); //创建线程 if(err < 0) { printf("cthread: pthread_create-->error\n"); return -1; } //不会等test_print方法执行完,因为main方法跟test_print方法不在同一个线程 printf("cthread:it's main process.\n"); sleep(2); return 0; }
C
#include <stdio.h> #include <Windows.h> #include <conio.h> #define MAX_SCREEN_WIDTH 999 #define MAX_SCREEN_HEIGHT 999 #define KB_SPACE 0x20 COORD ConsoleSize = { 200, 50 }; int main(void) { HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleScreenBufferSize(hConsoleOutput, COORD{ MAX_SCREEN_WIDTH, MAX_SCREEN_HEIGHT }); SMALL_RECT ConsoleWindow = { 0, 0, ConsoleSize.X - 1, ConsoleSize.Y - 1 }; SetConsoleWindowInfo(hConsoleOutput, true, &ConsoleWindow); SetConsoleScreenBufferSize(hConsoleOutput, ConsoleSize); WORD colorValue[2] = { FOREGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_INTENSITY, BACKGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY }; int color = 0; int a = 0; while (1) { printf("%d", a); for (SHORT i = 48; i < ConsoleSize.Y; i++) for (SHORT j = 0; j < ConsoleSize.X; j++) { SetConsoleCursorPosition(hConsoleOutput, COORD{ j, i }); SetConsoleTextAttribute(hConsoleOutput, colorValue[color]); if (i == ConsoleSize.Y - 1 && j == ConsoleSize.X - 1) continue; if (j % 4 != 0) continue; else putchar(' '); } SetConsoleCursorPosition(hConsoleOutput, COORD{ 0, 0 }); SetConsoleTextAttribute(hConsoleOutput, FOREGROUND_INTENSITY); if (_kbhit()) { if (_getch() == KB_SPACE) { break; } } color = !color; a++; Sleep(50); } //SetConsoleCursorPosition J[\ʒuw return 0; }
C
/********************************************************* * Exemplo de passagem de parametro para Tasks na criação* * Por: Fábio Souza *********************************************************/ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #include "sdkconfig.h" /* Can use project configuration menu (idf.py menuconfig) to choose the GPIO to blink, or you can edit the following line and set a number here. */ #define BLINK_GPIO CONFIG_BLINK_GPIO #define LED1 2 #define LED2 5 /* Variáveis para Armazenar o handle das Tasks */ TaskHandle_t xTask1Handle, xTask2Handle, xTask3Handle; /* Protótipo das Tasks*/ void vTask1(void *pvParameters ); void vTask2(void *pvParameters ); int valor = 100; void app_main(void) { xTaskCreate( vTask1 /* função da task*/ , "Task1" /* Nome da Task */ , configMINIMAL_STACK_SIZE +1024 /* Stack Size */ , (void*)100 /* parametro passado para a task*/ , 1 /* Prioridade da task*/ , &xTask1Handle /* handle da task*/ ); xTaskCreate( vTask1 /* função da task*/ , "Task2" /* Nome da Task */ , configMINIMAL_STACK_SIZE +1024 /* Stack Size */ , (void*)500 /* parametro passado para a task*/ , 1 /* Prioridade da task*/ , NULL /* handle da task*/ ); xTaskCreate( vTask2 /* função da task*/ , "BLINK2" /* Nome da Task */ , configMINIMAL_STACK_SIZE + 1024 /* Stack Size,*/ , (void*)LED1 /* parametro passado para a task*/ , 2 /* Prioridade da task*/ , &xTask2Handle /* handle da task*/ ); xTaskCreate( vTask2 /* função da task*/ , "BLINK5" /* Nome da Task */ , configMINIMAL_STACK_SIZE + 1024 /* Stack Size,*/ , (void*)LED2 /* parametro passado para a task*/ , 2 /* Prioridade da task*/ , &xTask3Handle /* handle da task*/ ); } /* Task 1 - contador*/ void vTask1(void *pvParameters ) { int count = (int)pvParameters; while(1) { printf("Task %s: %d \n",__func__,count++); vTaskDelay(pdMS_TO_TICKS(500)); /* Delay de 1 segundos */ } } /* Task 2 - Imprime valor na serial*/ void vTask2(void *pvParameters ) { int pin = (int)pvParameters; /*lê o parametro passado*/ //gpio_reset_pin(pin); /* Set the GPIO as a push/pull output */ gpio_set_direction(pin, GPIO_MODE_OUTPUT); while(1) { /* Blink off (output low) */ printf("Turning off the LED %d\n",pin); gpio_set_level(pin, 0); vTaskDelay(1000 / portTICK_PERIOD_MS); /* Blink on (output high) */ printf("Turning on the LED %d\n",pin); gpio_set_level(pin, 1); vTaskDelay(1000 / portTICK_PERIOD_MS); } }
C
#include "stdio.h" #include "stdlib.h" int main() { char xyz[] = "648892"; long int num = atol (xyz); printf("num: %ld \n", num ); char xyz1 [] = "90.57"; float num1 = atof(xyz1); //%.2f print flot with two decimail number printf("num1: %.2f\n", num1); char xyz2 [] = "239.53425378998"; double num2 = atof(xyz2); //%.11f print float with 11 decimail number printf("num1: %.11f\n", num2); }
C
#include <stdio.h> #include <syscalls.h> int main(int argc, char *argv[], char *envp[]){ int ret = -1; if(argc>2) { char *s = argv[2]; int n = 0; ret = 0; while (*s) { if (*s >= '0' && *s <= '9') { n = n * 10 + (*s - '0'); s++; } else { ret = -1; break; } } if(ret == 0) { //ret = syscall1(SYSCALL_SLEEP, n); puts("I am sleeping\n"); ret = sleep(n); } } return ret; }
C
#include <stdio.h> #include <string.h> #include <snl_md5.h> static char *test[] = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", NULL }; static char *ret[] = { "d41d8cd98f00b204e9800998ecf8427e", "0cc175b9c0f1b6a831c399e269772661", "900150983cd24fb0d6963f7d28e17f72", "f96b697d7cb7938d525a2f31aaf161d0", "c3fcd3d76192e4007dfb496cca67e13b", "d174ab98d277d9f5a5611c2c9f419d9f", }; #define MD5_LENGTH 16 static char *pt(unsigned char *md); void md5_test(const char *src, size_t len, unsigned char digest[16]) { snl_md5_ctx_t ctx; snl_md5_init(&ctx); snl_md5_update(&ctx, (u_char *)src, len); snl_md5_final(&ctx, digest); } int main(int argc, char *argv[]) { int i, err = 0; char **p, **r, *t; unsigned char md[MD5_LENGTH]; p = test; r = ret; i = 1; while (*p != NULL) { md5_test(*p, strlen(*p), md); t = pt(md); if (strcmp(t, (char *)*r) != 0) { printf("error calculating MD5 on '%s'\n", *p); printf("got %s instead of %s\n", t, *r); err++; } else { printf("test %d ok\n", i); } i++; p++; r++; } return err; } static char *pt(unsigned char *md) { int i; static char buf[80]; for (i = 0; i < MD5_LENGTH; i++) { sprintf(&(buf[i * 2]), "%02x", md[i]); } return buf; }
C
#include <packet.h> #include <string.h> #include <cobs.h> #define PACKET_HEADER 0x00 #define HEADER_INDEX 0 #define COBS_INDEX 1 #define LENGTH_INDEX 2 #define TYPE_INDEX 3 //#define PRINTF_DEBUG void pkt_init(pkt_generic_t *packet) { memset(packet, 0, sizeof(pkt_generic_t)); } /* maybe only have it clear total_length bytes? */ void pkt_clear(pkt_generic_t *packet) { memset(packet, 0, sizeof(pkt_generic_t)); } /* piecewise read returns true when finished reading */ bool pkt_readByte(pkt_generic_t *packet, uint8_t input) { #ifdef PRINTF_DEBUG printf("%d:%x ", packet->index, input); #endif if ((packet->index == 0) && (input != PACKET_HEADER)) return false; packet->data[packet->index] = input; packet->index++; if ((packet->index > LENGTH_INDEX) && (packet->index >= packet->type_payload_length + PKT_HEADER_LENGTH)) { packet->index = 0; packet->total_length = packet->type_payload_length + PKT_HEADER_LENGTH; #ifdef PRINTF_DEBUG printf("\n"); #endif return true; } return false; } uint8_t *pkt_encodeBuffer(pkt_generic_t *packet) { cobs_encodeInPlace(packet->data, packet->total_length); return packet->data; } void pkt_decodePacket(pkt_generic_t *packet) { cobs_decodeInPlace(packet->data, packet->total_length); } bool pkt_decodeByteHandler( pkt_generic_t *packet, uint8_t input, pkt_handler_func_t callback) { bool retval = pkt_readByte(packet, input); if (retval) { pkt_decodePacket(packet); (*callback)(packet); pkt_clear(packet); } return retval; } /* piecewise read returns true when finished reading */ /* static bool pkt_readInputBe(pkt_generic_t *packet, sr_port_t port) { uint8_t input = 0; sr_ReadPort(port, &input, sizeof(input)); if ((packet->index == 0) && (input != PACKET_HEADER)) return false; packet->data[MAX_PACKET_LENGTH - 1 - packet->index] = input; packet->index++; if (packet->index >= MAX_PACKET_LENGTH) { packet->index = 0; return true; } return false; } */ void pkt_print(pkt_generic_t *packet) { #ifdef PRINTF_DEBUG printf("header: %x\n", packet->header_byte); printf("imu_ax: %d\n", packet->imu_ax); printf("imu_ay: %d\n", packet->imu_ay); printf("imu_az: %d\n", packet->imu_az); printf("imu_gx: %d\n", packet->imu_gx); printf("imu_gy: %d\n", packet->imu_gy); printf("imu_gz: %d\n", packet->imu_gz); #endif }
C
#ifndef _FUNCTIONS_WITH_QUEUE_H #define _FUNCTIONS_WITH_QUEUE_H #include "utilits.h" #include <stdlib.h> typedef struct my_struct1 { char c; struct my_struct1 *next; } q_elem; typedef struct my_struct2 { int quantity; q_elem *head, *tail; } Q; // q_elem* create_element(char c); // int Q_push(Q *Queue, q_elem *element); // ( ) q_elem Q_pop(Q *Queue); // void Q_clear(Q *Queue); #endif //_FUNCTIONS_WITH_QUEUE_H
C
#include <stdio.h> #include "common.h" void b_dump(void) { printf("in b, &entries = %p\n", &entries); for (int i = 0; i < ARRAY_LENGTH(entries); i++) { const struct table_entry *e = &entries[i]; printf("Entry %d is at %p = {key:%d, label:%s}\n", i, e, e->key, e->label); } }
C
/* * Reads an employee's number, his/her worked hours number in month and the * amount he received per hour. * Print the employee's number and salary that he/she will receive at end of * the month with two decimal places * ---------------------------------------------------------------------------*/ #define SALARY_CALCULATOR(x,y) ((x) * (y)) #include <stdio.h> /*----------------------------------------------------------------------------*/ typedef struct person { int id; int workedHourInMonth; double amountReceivedPerHour; double salary; } person; int main( ) { person employee; fscanf( stdin, "%i %i %lf", &employee.id, &employee.workedHourInMonth, &employee.amountReceivedPerHour); employee.salary = (double) SALARY_CALCULATOR( (double) employee.workedHourInMonth, (double) employee.amountReceivedPerHour); fprintf( stdout, "NUMBER = %i\n", employee.id ); fprintf( stdout, "SALARY = U$ %.2f\n", employee.salary); return 0; }
C
/*<html><pre> -<a href="qh-user_r.htm" >-------------------------------</a><a name="TOP">-</a> usermem_r.c user redefinable functions -- qh_exit, qh_free, and qh_malloc See README.txt. If you redefine one of these functions you must redefine all of them. If you recompile and load this file, then usermem.o will not be loaded from qhull.a or qhull.lib See libqhull_r.h for data structures, macros, and user-callable functions. See user_r.c for qhull-related, redefinable functions see user_r.h for user-definable constants See userprintf_r.c for qh_fprintf and userprintf_rbox_r.c for qh_fprintf_rbox Please report any errors that you fix to qhull@qhull.org */ #include "libqhull_r.h" #include <stdarg.h> #include <stdlib.h> /*-<a href="qh-user_r.htm#TOC" >-------------------------------</a><a name="qh_exit">-</a> qh_exit( exitcode ) exit program the exitcode must be 255 or less. Zero indicates success. Note: Exit status ('$?') in bash reports 256 as 0 notes: qh_exit() is called when qh_errexit() and longjmp() are not available. This is the only use of exit() in Qhull To replace qh_exit with 'throw', see libqhullcpp/usermem_r-cpp.cpp */ void qh_exit(int exitcode) { exit(exitcode); } /* exit */ /*-<a href="qh-user_r.htm#TOC" >-------------------------------</a><a name="qh_fprintf_stderr">-</a> qh_fprintf_stderr( msgcode, format, list of args ) fprintf to stderr with msgcode (non-zero) notes: qh_fprintf_stderr() is called when qh.ferr is not defined, usually due to an initialization error if msgcode is a MSG_ERROR (6000), caller should set qh.last_errcode (like qh_fprintf) or variable 'last_errcode' It is typically followed by qh_errexit(). Redefine this function to avoid using stderr Use qh_fprintf [userprintf_r.c] for normal printing */ void qh_fprintf_stderr(int msgcode, const char *fmt, ... ) { va_list args; va_start(args, fmt); if(msgcode) fprintf(stderr, "QH%.4d ", msgcode); vfprintf(stderr, fmt, args); va_end(args); } /* fprintf_stderr */ /*-<a href="qh-user_r.htm#TOC" >-------------------------------</a><a name="qh_free">-</a> qh_free(qh, mem ) free memory notes: same as free() No calls to qh_errexit() */ void qh_free(void *mem) { free(mem); } /* free */ /*-<a href="qh-user_r.htm#TOC" >-------------------------------</a><a name="qh_malloc">-</a> qh_malloc( mem ) allocate memory notes: same as malloc() */ void *qh_malloc(size_t size) { return malloc(size); } /* malloc */
C
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<netinet/ip.h> #include<arpa/inet.h> #include<sys/socket.h> #include<unistd.h> #define PORT 8080 #define IP_ADDR "127.0.0.1" int read_msg(int des) { struct sockaddr_in client; socklen_t client_size = sizeof(client); int number,readbytes; for(int i=0;i<100;i++) { readbytes = recvfrom(des,&number,sizeof(number),0,(struct sockaddr*)&client,&client_size); if(readbytes == -1) perror("readbytes"); if(number%3==0) printf("divisible by 3 : %d\n",number); } } int name_socket(int des) { struct in_addr network_address; if(inet_aton(IP_ADDR,&network_address) == -1) perror("inet_aton"); struct sockaddr_in server = { .sin_family = AF_INET, .sin_port = PORT, .sin_addr = network_address }; if(bind(des,(struct sockaddr*)&server,sizeof(server))==-1) perror("bind"); } int main(void) { int des = socket(AF_INET, SOCK_DGRAM, 0); if(des == -1) perror("des"); name_socket(des); read_msg(des); close(des); }
C
#include "mpi.h" #include <stdio.h> #include <stdlib.h> // utility functions int ** alloc_matrix(int n, int m); void init_matrix(int n, int m, int ** a); void print_matrix(int n, int m, int ** a); void init_unit_matrix(int n, int m, int **a); // matrix operations int ** prod_matrix(int n, int l, int m, int ** a, int ** b); int ** pseudoprod_matrix(int n, int l, int m, int ** a, int ** b); int ** trans_matrix(int n, int m, int ** a); // MPI functions int MPI_Prod_matrix(int n, int ** a, int ** b, int ** c, int root, MPI_Comm comm); int MPI_PseudoProd_matrix(int n, int ** a, int ** b, int ** c, int root, MPI_Comm comm); int MPI_Prod_column_matrix(int n, int ** a, int ** b, int ** c, int root, MPI_Comm comm); int main(int argc, char ** argv) { int size, rank, tag = 1, i, j, n = 1200, **a, **b, **c, **a1, **c1; double time; MPI_Status stat; MPI_Datatype rowtype; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Type_contiguous(n, MPI_INT, &rowtype); MPI_Type_commit(&rowtype); a = alloc_matrix(n, n); b = alloc_matrix(n, n); c = alloc_matrix(n, n); if (rank == 0) { // initialise the matrices init_matrix(n, n, a); init_matrix(n, n, b); } time = MPI_Wtime(); //MPI_Prod_matrix(n, a, b, c, 0, MPI_COMM_WORLD); MPI_PseudoProd_matrix(n, a, b, c, 0, MPI_COMM_WORLD); //MPI_Prod_column_matrix(n, a, b, c, 0, MPI_COMM_WORLD); time = MPI_Wtime() - time; printf("\nProcessor %d worked for %lf\n\n", rank, time); if (rank == 0) { // initialise the matrices printf("Matrix a:\n\n"); print_matrix(n, n, a); printf("\nMatrix b:\n\n"); print_matrix(n, n, b); printf("\nMatrix c:\n\n"); print_matrix(n, n, c); } MPI_Type_free(&rowtype); MPI_Finalize(); } int MPI_Prod_matrix(int n, int ** a, int ** b, int ** c, int root, MPI_Comm comm) { int rank, size; // get rank and size of comm MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); // alocate space for local_a and local_c int **local_a = alloc_matrix(n / size, n); int **local_c = alloc_matrix(n / size, n); // scatter a to local_a and bcast_b MPI_Scatter(a[0], n*n/size, MPI_INT, local_a[0], n*n/size, MPI_INT, root, comm); MPI_Bcast(b[0], n*n, MPI_INT, root, comm); // calculate local_c = local_a * b local_c = prod_matrix(n / size, n, n, local_a, b); //local_c = pseudoprod_matrix(n / size, n, n, local_a, trans_matrix(n,n,b)); // gather local_c MPI_Gather(local_c[0], n*n / size, MPI_INT, c[0], n*n / size, MPI_INT, root, comm); return MPI_SUCCESS; } int MPI_PseudoProd_matrix(int n, int ** a, int ** b, int ** c, int root, MPI_Comm comm) { int rank, size; // get rank and size of comm MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); // alocate space for local_a and local_c int **local_a = alloc_matrix(n / size, n); int **local_c = alloc_matrix(n / size, n); // scatter a to local_a and bcast_b MPI_Scatter(a[0], n*n / size, MPI_INT, local_a[0], n*n / size, MPI_INT, root, comm); MPI_Bcast(b[0], n*n, MPI_INT, root, comm); // calculate local_c = local_a * b //local_c = prod_matrix(n / size, n, n, local_a, b); local_c = pseudoprod_matrix(n / size, n, n, local_a, trans_matrix(n, n, b)); // gather local_c MPI_Gather(local_c[0], n*n / size, MPI_INT, c[0], n*n / size, MPI_INT, root, comm); return MPI_SUCCESS; } int MPI_Prod_column_matrix(int n, int ** a, int ** b, int ** c, int root, MPI_Comm comm) { int rank, size; // get rank and size of comm MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); // alocate space for local_a and local_c int **local_b = alloc_matrix(n, n/size); int **local_c = alloc_matrix(n, n/size); //create column datataType MPI_Datatype column; MPI_Type_vector(n, 1, n, MPI_INT, &column); MPI_Type_commit(&column); // scatter a to local_a and bcast_b MPI_Bcast(a[0], n, column, root, comm); MPI_Scatter(b[0], n / size, column, local_b[0], n / size, column, root, comm); //MPI_Bcast(b[0], n*n, MPI_INT, root, comm); // calculate local_c = local_a * b local_c = prod_matrix(n, n, n/size, a, local_b); //local_c = pseudoprod_matrix(n / size, n, n, local_a, trans_matrix(n, n, b)); // gather local_c MPI_Gather(local_c[0], n / size, column, c[0], n / size, column, root, comm); return MPI_SUCCESS; } /* The function alloc_matrix is to allocate dynamically a matrix of integers with n rows and m columns. The function arguments are; n - number of rows m - number of columns The function returns the double pointer representing the matrix. */ int ** alloc_matrix(int n, int m) { int i, j, **a, *aa; aa = (int *)calloc(n*m, sizeof(int)); a = (int **)calloc(n, sizeof(int*)); for (i = 0; i < n; i++)a[i] = aa + i * m; for (i = 0; i < n; i++)for (j = 0; j < m; j++)a[i][j] = 0; return a; } /* The function init_matrix is to initialize the matrix a with random integers. The function arguments are: n - number of rows m - number of columns a - the matrix */ void init_matrix(int n, int m, int ** a) { int i, j; for (i = 0; i < n; i++)for (j = 0; j < m; j++)a[i][j] = rand() % 10; } void init_unit_matrix(int n, int m, int ** a) { int i, j; for (i = 0; i < n; i++)for (j = 0; j < m; j++) if (i == j)a[i][j] = 1; else a[i][j] = 0; } /* The function print_matrix is to display the matrix a. The function arguments are: n - number of rows m - number of columns a - the matrix */ void print_matrix(int n, int m, int ** a) { int i, j; if (n <= 20) { printf("\n"); for (i = 0; i < n; i++) { for (j = 0; j < m; j++)printf("%d ", a[i][j]); printf("\n"); } } } /* The function prod_matrix is to multiply the matrices a and b. The function arguments are; n - number of rows of a l - number of columns of a // the matrix b must have l rows m - number of columns of b a - the first matrix b - the second matrix The function returns the double pointer representing the product matrix. */ int ** prod_matrix(int n, int l, int m, int ** a, int ** b) { int i, j, k, ** c; c = alloc_matrix(n, m); for (i = 0; i < n; i++)for (j = 0; j < m; j++) { c[i][j] = 0; for (k = 0; k < l; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } return c; } int ** pseudoprod_matrix(int n, int l, int m, int ** a, int ** b) { int i, j, k, ** c; c = alloc_matrix(n, m); for (i = 0; i < n; i++)for (j = 0; j < m; j++) { c[i][j] = 0; for (k = 0; k < l; k++) { c[i][j] = c[i][j] + a[i][k] * b[j][k]; } } return c; } int ** trans_matrix(int n, int m, int ** a) { int i, j; int ** b; b = alloc_matrix(m, n); for (j = 0; j < m; j++)for (i = 0; i < n; i++) { b[j][i] = a[i][j]; } return b; }
C
#define fxm_1 (u8)0x01 #define fxm_2 (u8)0x02 #define fxm_3 (u8)0x04 #define fxm_4 (u8)0x08 #define fxm_5 (u8)0x10 ////////////////////////0x20 #define fxm_acoustc (u8)0x40 #define fxm_dirty (u8)0x80 // For the Axe-FX Vol block, Log 20A means that the resistance is 20% at the halfway point in the travel. // If you put the knob at noon, the volume would be 20% of maximum (about -14 dB). // So, 0 = -INFdB, 63 = -14dB and 127 = 0dB // We adjust the scale by +6dB to define 0dB at 98 and +6dB at 127 #define volume_0dB 98 #define volume_6dB 127 #define gate_default 71 #define scene_count_max 11 struct amp { u8 gain; // amp gain (7-bit), if 0 then the default gain is used u8 fx; // bitfield for FX enable/disable, including clean/dirty/acoustic switch u8 volume; // volume (7-bit) represented where 0 = -inf, 98 = 0dB, 127 = +6dB u8 gate; // gate threshold (7-bit) represented where 0 = -76.0dB, 127 = -12.0dB, default should be 71 = -40.0dB aka 0x47 }; // amp state is 4 bytes: COMPILE_ASSERT(sizeof(struct amp) == 4); // Program v5 data structure loaded from / written to flash memory: struct program { // Name of the song: u8 name[20]; // AXE-FX program # to switch to (7 bit) u8 midi_program; // Tempo in bpm: u8 tempo; // Default gain setting for each amp: u8 default_gain[2]; // MIDI CC numbers for FX enable/disable for each amp: // TODO: this will be redundant per MIDI program. Better to move this out to a per-program storage instead of per-song. u8 fx_midi_cc[2][5]; // 34 bytes consumed up to this point. 128 - 34 = 94 bytes to spend on scene descriptors. u8 _padding[5]; u8 scene_count; // Scene descriptors (8 bytes each): struct scene_descriptor { // 2 amps (4 bytes each): struct amp amp[2]; } scene[scene_count_max]; }; // NOTE(jsd): Struct size must be a divisor of 64 to avoid crossing 64-byte boundaries in flash! // Struct sizes of 1, 2, 4, 8, 16, and 32 qualify. COMPILE_ASSERT(sizeof(struct program) == 128); // Set list entry struct set_entry { u8 program; }; #define max_set_length 127 // Set lists struct set_list { u8 count; // number of songs in set list // u8 d0, d1; // date of show (see DATES below) struct set_entry entries[max_set_length]; }; // DATES since 2014 are stored in 16 bits in the following form: (LSB on right) // yyyyyyym mmmddddd; // |||||||| |||||||| // |||||||| |||\++++ day of month [0..30] // |||||||\-+++----- month [0..11] // \++++++---------- year since 2014 [0..127] COMPILE_ASSERT(sizeof(struct set_list) == 128);
C
#include<stdio.h> int well_ordered(int num) { int a[3], count=0; for(int i=0; i<3; i++) { a[i]=num%10; num/=10; } for(int i=0; i<2; i++) if(a[i]<=a[i+1]) count=1; if(count==0) return 1; else return 0; } int main() { int check=0, flag=0; printf("The list of all well-ordered three digit numbers\n\n"); for(int i=100; i<1000; i++) { check=well_ordered(i); if(check==1) { printf("%d\n", i); flag++; } check=0; } printf("\nThe total number of well-ordered three digit numbers are: %d\n", flag); return 0; }
C
#include "list.h" #include <stdlib.h> #include <string.h> #include <stdio.h> struct node { char* value; // Node* next; // }; struct list { Node* head; Node* tail; }; Node* nodeInit() { Node* head = (Node*)malloc(sizeof(Node)); if (head == NULL) { perror("can`t create node"); return NULL; } head->next = NULL; head->value = NULL; return head; } void freeNode(Node* currentNode) { free(currentNode->value); free(currentNode); } List* createList() { List* newList = (List*)malloc(sizeof(List)); if (newList == NULL) { perror("List creation error"); return NULL; } newList->head = NULL; newList->tail = NULL; return newList; } int addString(List *list, char* newLine) { Node* newNode = NULL; if (list == NULL) { perror(" List is NULL"); return FIASCO; } newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { perror("can`t create newNode"); return FIASCO; } newNode->value = (char*)malloc((strlen(newLine) + 1) * sizeof(char)); if (newNode->value == NULL) { perror("can`t create newNode->value"); return FIASCO; } //strcpy(newNode->value, newLine); strncpy(newNode->value, newLine, strlen(newLine) + 1); //strcpy_s(newNode->value, strlen(newLine) + 1, newLine); newNode->next = NULL; if (list->head == NULL) { list->head = newNode; list->tail = newNode; } else { list->tail->next = newNode; list->tail = newNode; } return(SUCCESS); } void freememory(List* list) { if (list == NULL) { return; } Node* nxtNode = NULL; if (list->head == NULL) { free(list); return; } Node* curNode = list->head->next; while (curNode != NULL) { nxtNode = curNode->next; freeNode(curNode); curNode = nxtNode; } free(list->head); free(list); } void printList(List* list) { if (list == NULL) return; Node* i = list->head; for (Node* i = list->head; i != NULL; i = i->next) { puts(i->value); } }
C
#include <stdio.h> long long int N; int binarySearch(long long int arr[], int l, int r, int x) { int mid = l + (r - l) / 2; if (x <= arr[0]) { return 0; } if (x >= arr[N - 1]) { return N - 1; } if (r >= l) { // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not // present in array return mid; } void merge(long long int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort(long long int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } int main() { long long int Q, K, count; scanf("%lld %lld %lld", &N, &Q, &K); int i; long long int a[N], b[N]; long long int X, val; for (i = 0; i < N; i++) { scanf("%lld", &a[i]); b[i] = a[i]; } mergeSort(b, 0, N - 1); scanf("%d", &val); printf("index = %d\n", binarySearch(b, 0, N - 1, val)); }
C
#include <math.h> #include <stdlib.h> #include <stdio.h> //this function works in strong assumption of det(X) ne 0 double* jordan_main_throgh_matrix_1(double *X, double *y, int n){ int i = 0, j = 0, k = 0, i_max, j_max; int *ind; ind = malloc(n*sizeof(int)); for(i=0;i<n;i++) ind[i] = i; double *y_sup, *a; y_sup = malloc(n*sizeof(double)); a = malloc(n*sizeof(double)); double max_elem = 0, t; for(i=0;i<n;i++) { y_sup[i] = y[i]; } for(k=0;k<n;k++) { //Finding abs max elem for(i=k;i<n;i++) { for(j=k;j<n;j++) { if(fabs(X[i*n+j])>fabs(max_elem)) { max_elem = X[i*n+j]; i_max = i; j_max = j; } } } /*if(fabs(max_elem)<=10e-15) { return -1; }*/ max_elem = 0; //Replacing max_elem to k,k position //Replacing strings t = y_sup[k]; y_sup[k] = y_sup[i_max]; y_sup[i_max] = t; for(j=k;j<n;j++) { t = X[k*n+j]; X[k*n+j] = X[i_max*n+j]; X[i_max*n+j] = t; } //Replacing columns j = ind[k]; //Replacing columns leads to replacing solution indexes. Remember that ind[k] = ind[j_max]; ind[j_max] = j; for(i=0;i<n;i++){ t = X[i*n+k]; X[i*n+k] = X[i*n+j_max]; X[i*n+j_max] = t; } //Gaussian step //Making k,k elem eq 1, i.e. dividing k-th string by k,k elem t = X[k*n+k]; y_sup[k] /= t; for(j=k;j<n;j++) { X[k*n+j] /= t; } //Subtracting k-th string from those below, so that (k+1,k), ..., (n,k) elems would be eq to 0 for(i=k+1;i<n;i++) { t = X[i*n+k]; y_sup[i] -= y_sup[k]*t; for(j=k;j<n;j++) { X[i*n+j] -= X[k*n+j]*t; } } //Gaussian backward step //Subtracting k-th string from those above, so that (k-1,k), ..., (1,k) elems would be eq to 0 for(i=0;i<k;i++) { t = X[i*n+k]; y_sup[i] -= y_sup[k]*t; for(j=k;j<n;j++) { X[i*n+j] -= X[k*n+j]*t; } } } for(i=0;i<n;i++) a[ind[i]] = y_sup[i]; free(y_sup); free(ind); return a; free(a); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<string.h> int main() { char str[10]; int count = 3; printf("㹲Ļ\n"); while (count > 0) { printf("룺"); scanf("%s", &str); if (strcmp(str,"579579")==0) { printf("½ɹ\n"); break; } else { printf("\n"); count--; printf("%dλ\n", count); } } system("pause"); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> int main() { int fd = open("/root/sysprogs/cars.txt", O_RDWR | O_APPEND); if( fd == -1) { perror("No need to continue as we can't open the file\n"); return 1; } ssize_t tw1,tw2; const char *buf1 = "Jaguar\n"; const char *buf2 = "Tesla\n"; tw1 = write(fd,buf1,strlen(buf1)); if(tw1 == -1) { perror("Can't add Jaguar! \n"); } close(fd); tw2 = write(fd,buf2,strlen(buf2)); if(tw2 == -1) { perror("Can't add Tesla! \n"); } return 0; }
C
#include<stdlib.h> #include<stdio.h> int main() { int IntArray[100]; int IntNum,IntMoveSteps; int AuxiliarySpace; scanf("%d %d",&IntNum,&IntMoveSteps); if(IntNum>100||IntNum<1||IntMoveSteps<0) return 1; int i,j; for(i=0;i<IntNum;i++) { scanf("%d",&IntArray[i]); } for(i=1;i<=IntMoveSteps;i++) { AuxiliarySpace=IntArray[IntNum-1]; for(j=IntNum-1;j>=1;j--) { IntArray[j]=IntArray[j-1]; } IntArray[0]=AuxiliarySpace; } for(i=0;i<IntNum-1;i++) { printf("%d ",IntArray[i]); } printf("%d",IntArray[i]); return 0; }
C
/* * ===================================================================================== * * Filename: 111.c * * Description: 111 * * Version: 1.0 * Created: Sunday 30 June 2013 07:49:19 CST * Revision: none * Compiler: gcc * * Author: Zhang Dongsheng (mars), zhangdongsheng1224@gmail.com * Organization: HANGZHOU DIANZI UNIVERSITY * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> typedef struct node { struct node *lchild; char data; struct node *rchild; } bitnode, *bitree; bitree CreatTree() { char a; bitree new; scanf("%c", &a); if (a == '#') return NULL; else { new = (bitree)malloc(sizeof(bitnode)); new->data = a; new->lchild = CreatTree(); new->rchild = CreatTree(); } return new; } void PreorderTraverse(bitree bt) { if (bt != NULL) { printf("%c", bt->data); PreorderTraverse(bt->lchild); PreorderTraverse(bt->rchild); } } void InorderTraverse(bitree bt) { if (bt != NULL) { InorderTraverse(bt->lchild); printf("%c", bt->data); InorderTraverse(bt->rchild); } } void PostorderTraverse(bitree bt) { if (bt != NULL) { PostorderTraverse(bt->lchild); PostorderTraverse(bt->rchild); printf("%c", bt->data); } } int main() { bitree root; root = CreatTree(); printf("Preorder Traversal:\n"); PreorderTraverse(root); printf("\n"); printf("Inorder Traversal:\n"); InorderTraverse(root); printf("\n"); printf("Postorder Traversal:\n"); PostorderTraverse(root); printf("\n"); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int sha2_byte ; typedef int SHA512_CTX ; /* Variables and functions */ int /*<<< orphan*/ MEMSET_BZERO (int*,int) ; int SHA512_DIGEST_LENGTH ; int /*<<< orphan*/ SHA512_Final (int*,int*) ; int /*<<< orphan*/ assert (int /*<<< orphan*/ ) ; void** sha2_hex_digits ; char *SHA512_End(SHA512_CTX* context, char buffer[]) { sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; int i; /* Sanity check: */ assert(context != NULL); if (buffer != NULL) { SHA512_Final(digest, context); for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; } *buffer = 0; } else { MEMSET_BZERO(context, sizeof(*context)); } MEMSET_BZERO(digest, SHA512_DIGEST_LENGTH); return buffer; }
C
#include <stdio.h> #include <cs50.h> //#include <string.h> //#include <stdlib.h> //#include <ctype.h> int main(int argc, string argv[]) { //Проверка на количетво аргументов if (argc!=2) { printf("Usage: ./vigenere k\n"); return 1; } int messlen,keylen;//Длинна сообщения и длинна ключа string key = (argv[1]);//Иниц. ключ с 1-го аргумента //Иниц. длинну ключа и проверка аргумента на лишние символы, если лишние "схлоп" for(keylen=0;key[keylen]!='\0';keylen++) if (key[keylen]<65 || ( key[keylen]>65+26 && key[keylen]<97) || key[keylen]>97+26) { printf("Usage: ./vigenere k\n"); return 1; } // Иниц. сообщение через ввод пользователя string mess; do { printf("plaintext: "); mess=GetString(); for(messlen=0;mess[messlen]!='\0';messlen++); //printf("%i\n",l); } while(mess[0]==0 && messlen==0); //Сбор двух массивов (малые и большие буквы) символов char alf_m[52], alf_b[52]; for (int n=65;n<65+26;n++) { alf_b[n-65]=n,alf_b[n-65+26]=n; alf_m[n-65]=n+32,alf_m[n-65+26]=n+32; } //Вывод результата int offsetkey=0;// Иниц. смещщение индекса по ключу printf("ciphertext: "); for (int en=0;en<messlen;en++)// Перебор сообщения по символам { if ( key[offsetkey]<91)// Если символ ключа большой(заглавная буква) { key[offsetkey]+=32;// смещаем на малую } if (mess[en]>64 && mess[en]<91)//Если символ сообщения большой { printf("%c",alf_b[mess[en]-65+key[offsetkey]-97]);//Выводим из массива с большими символами } else if(mess[en]>96 && mess[en]<123)//Если малый { printf("%c",alf_m[mess[en]-97+key[offsetkey]-97]);// из масссива с малыми } else { printf("%c",mess[en]);//иначе не меняя offsetkey--;// минусуем чтобы не смещать ключ } offsetkey++;//смещаем ключ на 1 // Если ключ прошел круг, обнуляем if (offsetkey>=keylen) { offsetkey=0; } } printf("\n");//Снос return 0; }
C
#include<stdio.h> int factorial(int n) { int r; if (n==1) { return 1; } r=n*factorial(n-1 ) ; return (r ) ; } int main() { int n,res; printf("***********************************n" ) ; printf("tFactorial Recursivon" ) ; printf("***********************************n" ) ; printf("Dame un numero: " ) ; scanf("%d",&n ) ; res=factorial(n ) ; printf("El factorial de %d es: %d",n,res ) ; system ("pause"); return 0; }
C
/** * Cracking the Coding Interview Problem 8.1 * Designing the data structure for a generic deck of cards. * * FIRST we define a type 'Suit'. * THEN we define a class Card. * THEN we define a class Hand (representing one's hand of cards). */ // Defining a type 'Suit'. public enum Suit { // enum = a user-defined type Clubs(1), Diamonds(2), Spades(3), Hearts(4); private int value; // Setting the suit's value: private Suit(int v) { value = v; } public int getValue() { return value; } // Additional function: public static Suit getSuitFromValue(int value) { ... } } // Card = an abstract class because some methods do not make sense without // a game being played. public abstract class Card { // Whether or not card is available to be given out: private boolean available = true; protected int faceValue; protected Suit suit; public Card(int f, Suit s) { faceValue = f; suit = s; } // A Card's functions re: availability. public boolean isAvailable() { return available; } public void makeUnavailable() { available = false; } public void makeAvailable() { available = true; } } // A class representing your current hand of cards. public class Hand<T extends Card> { ArrayList<T> myCards = new ArrayList<T>(); // Obtaining the score of your deck: public int score() { int score = 0; // Add up all your cards' values. for (T card: cards) { score += card.value(); } return score; } // Adding a card to your deck: public void addCard(T card) { cards.add(card); } }
C
/******************************************************************************* * File Name: Move_Down.c * Version 1.90 * * Description: * This file contains API to enable firmware control of a Pins component. * * Note: * ******************************************************************************** * Copyright 2008-2012, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "cytypes.h" #include "Move_Down.h" #define SetP4PinDriveMode(shift, mode) \ do { \ Move_Down_PC = (Move_Down_PC & \ (uint32)(~(uint32)(Move_Down_DRIVE_MODE_IND_MASK << (Move_Down_DRIVE_MODE_BITS * (shift))))) | \ (uint32)((uint32)(mode) << (Move_Down_DRIVE_MODE_BITS * (shift))); \ } while (0) /******************************************************************************* * Function Name: Move_Down_Write ******************************************************************************** * * Summary: * Assign a new value to the digital port's data output register. * * Parameters: * prtValue: The value to be assigned to the Digital Port. * * Return: * None * *******************************************************************************/ void Move_Down_Write(uint8 value) { uint8 drVal = (uint8)(Move_Down_DR & (uint8)(~Move_Down_MASK)); drVal = (drVal | ((uint8)(value << Move_Down_SHIFT) & Move_Down_MASK)); Move_Down_DR = (uint32)drVal; } /******************************************************************************* * Function Name: Move_Down_SetDriveMode ******************************************************************************** * * Summary: * Change the drive mode on the pins of the port. * * Parameters: * mode: Change the pins to this drive mode. * * Return: * None * *******************************************************************************/ void Move_Down_SetDriveMode(uint8 mode) { SetP4PinDriveMode(Move_Down__0__SHIFT, mode); } /******************************************************************************* * Function Name: Move_Down_Read ******************************************************************************** * * Summary: * Read the current value on the pins of the Digital Port in right justified * form. * * Parameters: * None * * Return: * Returns the current value of the Digital Port as a right justified number * * Note: * Macro Move_Down_ReadPS calls this function. * *******************************************************************************/ uint8 Move_Down_Read(void) { return (uint8)((Move_Down_PS & Move_Down_MASK) >> Move_Down_SHIFT); } /******************************************************************************* * Function Name: Move_Down_ReadDataReg ******************************************************************************** * * Summary: * Read the current value assigned to a Digital Port's data output register * * Parameters: * None * * Return: * Returns the current value assigned to the Digital Port's data output register * *******************************************************************************/ uint8 Move_Down_ReadDataReg(void) { return (uint8)((Move_Down_DR & Move_Down_MASK) >> Move_Down_SHIFT); } /* If Interrupts Are Enabled for this Pins component */ #if defined(Move_Down_INTSTAT) /******************************************************************************* * Function Name: Move_Down_ClearInterrupt ******************************************************************************** * * Summary: * Clears any active interrupts attached to port and returns the value of the * interrupt status register. * * Parameters: * None * * Return: * Returns the value of the interrupt status register * *******************************************************************************/ uint8 Move_Down_ClearInterrupt(void) { uint8 maskedStatus = (uint8)(Move_Down_INTSTAT & Move_Down_MASK); Move_Down_INTSTAT = maskedStatus; return maskedStatus >> Move_Down_SHIFT; } #endif /* If Interrupts Are Enabled for this Pins component */ /* [] END OF FILE */
C
#include <stdio.h> void main() { int row, rows, a=1, i; scanf("%d", &rows); for(row=1;row<=rows;row++) { for(i=1;i<row;i++) { printf("%4d", a); a++; } puts(""); } }
C
#include <stdio.h> #include <stdlib.h> #include "address.h" #define ADDRESSFILE "addresses.txt" void saveAddresses(AddressPtr_t* node){ FILE *fp; fp = fopen(ADDRESSFILE, "w+"); // --- HEADER fprintf(fp, "Name,Vorname,Strasse,PLZ,Ort\n"); //evtl. Komma? while(*node != NULL){ fprintf(fp, "%s,", (*(*node)).firstname); fprintf(fp, "%s,", (*(*node)).name); fprintf(fp, "%s,", (*(*node)).street); fprintf(fp, "%s,", (*(*node)).streetNbr); fprintf(fp, "%s,", (*(*node)).zip); fprintf(fp, "%s\n", (*(*node)).city); node = &(*(*node)).next; //*node =, würde den Inhalt von node, also head, verändern! } fclose(fp); } void emptyAddressMemory(AddressPtr_t* node){ AddressPtr_t* isNode = node; int zaehler = 0; //alle Nodes durchzählen while(*isNode != NULL){ zaehler += 1; isNode = &(*(*isNode)).next; } //isNode wieder auf Head richten isNode = node; //Alle Addressen in ein Pointer-Array füllen AddressPtr_t* allAddresses[zaehler]; for(int i = 0; i < zaehler; i++){ allAddresses[i] = isNode; isNode = &(*(*isNode)).next; } //isNode wieder auf Head richten isNode = node; //Addressen rückwärts durchgehen und Speicher freigeben for(int i = (zaehler - 1); i >= 0; i--){ free((*(*(allAddresses[i]))).firstname); free((*(*(allAddresses[i]))).name); free((*(*(allAddresses[i]))).street); free((*(*(allAddresses[i]))).streetNbr); free((*(*(allAddresses[i]))).zip); free((*(*(allAddresses[i]))).city); free((*(*(allAddresses[i]))).next); } //Head freigeben free(*node); *node = NULL; //naja... TODO? } void getAddresses(AddressPtr_t* node){ //1. speicher der bisher eingegebenen Addressen freigeben emptyAddressMemory(node); //2. Speicher neu allozieren und einfüllen FILE *fp; fp = fopen(ADDRESSFILE, "r"); //Datei öffnen char tempBuffer[MAXBUFFERSIZE]; int tempCharCount = 0; char ch; int structData = 0; AddressPtr_t oldNode; //erste Structure allozieren *node = (AddressPtr_t)malloc(sizeof(Address_t)); ch = getc(fp); while(ch != '\n'){ //erste Zeile überspringen ch = getc(fp); } ch = getc(fp); while(ch != EOF){ while((ch != '\n') && (ch != ',')){ tempBuffer[tempCharCount] = ch; tempCharCount++; ch = getc(fp); } //wort (und evtl auch Zeile) abgeschlossen tempBuffer[tempCharCount] = '\0'; //Wort-Array abschliessen if((ch == ',') || (structData < 6)){ //Wort abgeschlossen //Wort entsprechend abspeichern switch(structData){ case FIRSTNAME: saveBuffer(&(*(*node)).firstname, tempBuffer, tempCharCount); structData++; break; case NAME: saveBuffer(&(*(*node)).name, tempBuffer, tempCharCount); structData++; break; case STREET: saveBuffer(&(*(*node)).street, tempBuffer, tempCharCount); structData++; break; case STREETNBR: saveBuffer(&(*(*node)).streetNbr, tempBuffer, tempCharCount); structData++; break; case ZIP: saveBuffer(&(*(*node)).zip, tempBuffer, tempCharCount); structData++; break; case CITY: saveBuffer(&(*(*node)).city, tempBuffer, tempCharCount); structData++; break; } //Wort fertig abgespeichert tempCharCount = 0; //Buffer zurücksetzen } if(ch == '\n'){ //Zeile abgeschlossen structData = 0; //switch zurücksetzen oldNode = *node; (*(*node)).next = (AddressPtr_t)malloc(sizeof(Address_t)); //Speicher für nächste Structure allozieren node = &(*(*node)).next; //node-Pointer neu zuweisen für nächsten Durchgang } ch = getc(fp); //nächsten Character, nach einem '\n' oder ',', abrufen } //EOF, letzte Allozierung wieder auflösen und NULL-Pointer zuweisen free((*oldNode).next); (*oldNode).next = NULL; fclose(fp); //Datei schliessen }
C
#include <stdio.h> #include <string.h> int main(){ char a[1001]; char b[1001]; scanf("%s\n", &a); scanf("%s\n", &b); int flag=0; int l = strlen(a); int ans; for(int i =0;i<l;i++){ if(tolower(a[i])==tolower(b[i])){ ans = 0; } else if(tolower(a[i])<tolower(b[i])){ ans = -1; break; } else{ ans = 1; break; } } printf("%d\n", ans); } //asadasdasd //asdwasdawd
C
/* * @lc app=leetcode id=1023 lang=c * * [1023] Camelcase Matching * * https://leetcode.com/problems/camelcase-matching/description/ * * algorithms * Medium (56.58%) * Total Accepted: 7.2K * Total Submissions: 12.7K * Testcase Example: '["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"]\n"FB"' * * A query word matches a given pattern if we can insert lowercase letters to * the pattern word so that it equals the query. (We may insert each character * at any position, and may insert 0 characters.) * * Given a list of queries, and a pattern, return an answer list of booleans, * where answer[i] is true if and only if queries[i] matches the pattern. * * * * Example 1: * * * Input: queries = * ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = * "FB" * Output: [true,false,true,true,false] * Explanation: * "FooBar" can be generated like this "F" + "oo" + "B" + "ar". * "FootBall" can be generated like this "F" + "oot" + "B" + "all". * "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". * * Example 2: * * * Input: queries = * ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = * "FoBa" * Output: [true,false,true,false,false] * Explanation: * "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". * "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". * * * Example 3: * * * Input: queries = * ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = * "FoBaT" * Output: [false,true,false,false,false] * Explanation: * "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + * "est". * * * * * Note: * * * 1 <= queries.length <= 100 * 1 <= queries[i].length <= 100 * 1 <= pattern.length <= 100 * All strings consists only of lower and upper case English letters. * */ /** * Note: The returned array must be malloced, assume caller calls free(). */ bool* camelMatch(char ** queries, int queriesSize, char * pattern, int* returnSize){ }
C
#include <kilolib.h> // Maximum of an 8-bit number (since we're using 1 byte of the message to send // the gradient value). #define GRADIENT_MAX 255 int own_gradient = GRADIENT_MAX; int received_gradient = 0; int new_message = 0; message_t message; void setup() { // If the ID is 42, the robot is the seed its gradient should be 0 rather // than GRADIENT_MAX. if (kilo_uid == 42) { own_gradient = 0; } // Compute the message. message.type = NORMAL; message.data[0] = own_gradient; message.crc = message_crc(&message); } void loop() { if (new_message == 1) { new_message = 0; if (own_gradient > received_gradient + 1) { own_gradient = received_gradient + 1; // Update the message whenever the gradient changes. message.type = NORMAL; message.data[0] = own_gradient; message.crc = message_crc(&message); } } // Set LED color based on gradient. if (own_gradient == 0) { set_color(RGB(1, 1, 1)); // White } else if (own_gradient == 1) { set_color(RGB(1, 0, 0)); // Red } else if (own_gradient == 2) { set_color(RGB(0, 1, 0)); // Green } else if (own_gradient == 3) { set_color(RGB(0, 0, 1)); // Blue } else if (own_gradient == 4) { set_color(RGB(1, 0, 1)); // Magenta } else if (own_gradient >= 5) { set_color(RGB(1, 1, 0)); // Yellow } } message_t *message_tx() { return &message; } void message_rx(message_t *m, distance_measurement_t *d) { new_message = 1; received_gradient = m->data[0]; } int main() { kilo_init(); kilo_message_rx = message_rx; kilo_message_tx = message_tx; kilo_start(setup, loop); return 0; }