language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/*-----------------------------------------------
* Christopher Grant
* CS-362
* Winter 2017
* Assignment-3
* Unit Test 3 - test for discardCard()
------------------------------------------------*/
/*
1. if trashFlag is set it does not add card to playedcards.
2. if trashFlag is 0 than card is added to playedcards. checked!
3. card that is discarded is replaced by last card in hand. Checked!
4. hand count goes down by 1. checked!
5. other players hands do not change. checked!
6. other players dekcs do not change. checled!
*/
#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "rngs.h"
int main(void)
{
int returnValue;
int i, j, k;
int errorCount = 0;
int seed = 123456;
int handCount = 0;
struct gameState game, preGame;
int kingdom[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse,
sea_hag, tribute, smithy};
printf("***START OF DISCARDCARD TESTS***\n");
for (i = 2; i <= MAX_PLAYERS; i++)
{
for (j = 0; j < 4; j++)
{
returnValue = initializeGame(i, kingdom, seed, &game);
game.hand[0][0] = smithy;
game.hand[0][1] = copper;
game.hand[0][2] = silver;
game.hand[0][3] = gold;
game.hand[0][4] = adventurer;
memcpy (&preGame, &game, sizeof(struct gameState));
discardCard(j, 0, &game, 0);
if (game.hand[0][j] != adventurer)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("discarded card at pos %d was not replaced by last card in hand\n\n", j);
}
if (preGame.playedCardCount + 1 != game.playedCardCount)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("played cards count was not ++\n\n");
}
if (preGame.hand[0][j] != game.playedCards[0])
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("The wrong card went into the played card pile\n\n");
}
if (preGame.handCount[0] - 1 != game.handCount[0])
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("Hand cound not --\n\n");
}
if (!memcmp(&game.hand[1][0], &preGame.hand[1][0], sizeof(game.hand[1])) == 0)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("moded another players hand\n\n");
}
if (!memcmp(&game.deck[1][0], &preGame.deck[1][0], sizeof(game.deck[1])) == 0)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("moded another players deck\n\n");
}
if (!memcmp(&game.hand[2][0], &preGame.hand[2][0], sizeof(game.hand[2])) == 0)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("moded another players hand\n\n");
}
if (!memcmp(&game.deck[2][0], &preGame.deck[2][0], sizeof(game.deck[2])) == 0)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("moded another players deck\n\n");
}
if (!memcmp(&game.hand[3][0], &preGame.hand[3][0], sizeof(game.hand[3])) == 0)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("moded another players hand\n\n");
}
if (!memcmp(&game.deck[3][0], &preGame.deck[3][0], sizeof(game.deck[3])) == 0)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("moded another players deck\n\n");
}
}
for (j = 0; j < 4; j++)
{
returnValue = initializeGame(i, kingdom, seed, &game);
game.hand[0][0] = smithy;
game.hand[0][1] = copper;
game.hand[0][2] = silver;
game.hand[0][3] = gold;
game.hand[0][4] = adventurer;
memcpy (&preGame, &game, sizeof(struct gameState));
discardCard(j, 0, &game, 1);
if (preGame.playedCardCount != game.playedCardCount)
{
errorCount++;
printf("discardCard() error %d\n", errorCount);
printf("card was not trashed when the trash flag was 1\n\n");
}
}
}
if (errorCount == 0)
{
printf("ALL TESTS PASSED FOR DISCARDCARD\n");
}
printf("***END OF DISCARDCARD TESTS***\n\n");
return 0;
}
|
C
|
/**************************************************************************************************
Name : ex4.c
Author : Mohamed Tarek
Description : Assignment 4 - Ex 4
**************************************************************************************************/
#include<stdio.h>
#define ARR_SIZE 10
int findSmallestElement(int *ptr,int size)
{
int i = 0;
// assume that the minimum number is the first element
int min = ptr[0];
// start compare from the second array element
for(i=1;i<size;i++)
{
if(ptr[i] < min)
{
min = ptr[i];
}
}
return min;
}
/****************************** Another Solution ********************************
int findSmallestElement(int *ptr,int size)
{
int i = 0;
// assume that the minimum number is the first element
int min = *ptr;
// start compare from the second array element
ptr++;
for(i=1;i<size;i++)
{
if(*ptr < min)
{
min = *ptr;
}
ptr++; //increment pointer to get the next array element
}
return min;
}
*******************************************************************************/
int main(void)
{
int i, arr[ARR_SIZE];
int num;
printf("\nEnter integers into array: ");
for (i = 0; i < ARR_SIZE; i++)
{
scanf("%d", arr+i); // take each array element from user
}
num = findSmallestElement(arr,ARR_SIZE);
printf("\nThe smallest array element is : %d",num);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cnet.h>
int cnet_init(int port) {
int yes=1;
int rc;
int sfd;
struct sockaddr_in cnet_saddr;
sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0) {
perror("socket");
return(-1);
}
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
perror("setsockopt");
return(-1);
}
cnet_saddr.sin_family = AF_INET;
cnet_saddr.sin_addr.s_addr = INADDR_ANY;
cnet_saddr.sin_port = htons(port);
rc = bind(sfd, (struct sockaddr *) &cnet_saddr, sizeof(cnet_saddr));
if (rc < 0) {
perror("bind");
return(-1);
}
rc = listen(sfd, 64);
if (rc < 0) {
perror("listen");
return(-1);
}
return(sfd);
}
int cnet_accept(int sfd) {
int clen;
struct sockaddr_in cnet_caddr;
clen = sizeof(cnet_caddr);
return(accept(sfd, (struct sockaddr *)&cnet_caddr, &clen));
}
int cnet_close(int sfd) {
return(close(sfd));
}
int cnet_connect(char *hostname, int port, int *sd) {
int sfd;
struct sockaddr_in serv_addr;
struct hostent *server;
struct linger ls;
ls.l_onoff = 1;
ls.l_linger = 1;
sfd = socket(AF_INET, SOCK_STREAM, 0);
if (sfd < 0) {
perror("socket");
return(-1);
}
/*
if (setsockopt(sfd, SOL_SOCKET, SO_LINGER, &ls, sizeof(struct linger)) < 0) {
perror("setsockopt");
return(-1);
}
*/
server = gethostbyname(hostname);
if (server == NULL) {
perror("gethostbyname");
return(-1);
}
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(port);
if (connect(sfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
// printf("HOSTNAME: %s port %d\n", hostname, port);
perror("connect");
return(-1);
}
*sd = sfd;
return(0);
}
|
C
|
// K5-1.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。
//
#include "pch.h"
#include <iostream>
#pragma warning(disable:4996)
struct Record{
char Name[40];
char Country[40];
double Short;
double Free;
};
void BubSort(double *x, int length) {
int i, j;
double tmp;
for (i = 0; i < length - 1; i++) {
for (j = 0; j < length - 1; j++) {
if (x[j] > x[j + 1]) {
tmp = x[j];
x[j] = x[j + 1];
x[j + 1] = tmp;
}
}
}
}
int main()
{
struct Record Score[40];
FILE *fp = fopen("Lesson05.txt", "r");
char str[100];
char *tmp;
int NoP = 0;
while(fgets(str, sizeof(str), fp) != NULL){
char *p = strchr(str, (int)'\n');
if (p != NULL) {
*p = '\0';
}
tmp = strtok(str, ",");
strcpy(Score[NoP].Name, tmp);
tmp = strtok(NULL, ",");
strcpy(Score[NoP].Country, tmp);
tmp = strtok(NULL, ",");
Score[NoP].Short = atof(tmp);
tmp = strtok(NULL, ",");
Score[NoP].Free = atof(tmp);
NoP++;
}
fclose(fp);
int i;
double ShortSum = 0;
double FreeSum = 0;
double Shortqueue[40];
double Freequeue[40];
for (i = 1; i < NoP; i++) {
ShortSum += Score[i].Short;
FreeSum += Score[i].Free;
Shortqueue[i - 1] = Score[i].Short;
Freequeue[i - 1] = Score[i].Free;
}
BubSort(Shortqueue, NoP);
BubSort(Freequeue, NoP);
printf("Short平均 = %lf\n", ShortSum / (NoP-1));
printf("Free平均 = %lf\n", FreeSum / (NoP-1));
printf("Short中央 = %lf\n", Shortqueue[(NoP+1)/2]);
printf("Free中央 = %lf\n", Freequeue[(NoP + 1) / 2]);
}
// プログラムの実行: Ctrl + F5 または [デバッグ] > [デバッグなしで開始] メニュー
// プログラムのデバッグ: F5 または [デバッグ] > [デバッグの開始] メニュー
// 作業を開始するためのヒント:
// 1. ソリューション エクスプローラー ウィンドウを使用してファイルを追加/管理します
// 2. チーム エクスプローラー ウィンドウを使用してソース管理に接続します
// 3. 出力ウィンドウを使用して、ビルド出力とその他のメッセージを表示します
// 4. エラー一覧ウィンドウを使用してエラーを表示します
// 5. [プロジェクト] > [新しい項目の追加] と移動して新しいコード ファイルを作成するか、[プロジェクト] > [既存の項目の追加] と移動して既存のコード ファイルをプロジェクトに追加します
// 6. 後ほどこのプロジェクトを再び開く場合、[ファイル] > [開く] > [プロジェクト] と移動して .sln ファイルを選択します
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void cls(void) {
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
struct char_b { const char c[8];};
int encode(const char *input, char *txt, const char *output) {
if (input == NULL || txt == NULL || output == NULL) return 1;
FILE *in; in = fopen(input, "r");
if (in == NULL) return 2;
FILE *out; out = fopen(output, "w");
if (out == NULL) { fclose(in); return 4;}
int space_needed = (int)strlen(txt) * 8; // - 8
int space_aval = 0;
int err_code, tmp;
while (1) {
err_code = fscanf(in, "%d", &tmp);
if (err_code == EOF) break;
if (err_code != 1) {
fclose(in);
fclose(out);
return 3;
}
space_aval++;
}
rewind(in);
if (space_aval < space_needed) {fclose(in); fclose(out); return 3; }
int num; unsigned int lsb; int c;
int s_len = strlen(txt);
for (int i = 0; i < s_len; ++i) { // iterate over every char
// change char to its binary representation
for (int j = 7; j >= 0; --j) {
lsb = (*(txt + i) & (1u << j)) != 0;
fscanf(in, "%d" , &num);
if (lsb == 1){
num = num | 1;
}
else{
num = num & ~1;
} // encode next bit of char
fprintf(out, "%d", num);
c = fgetc(in);
while (isdigit(c) == 0 && c != EOF) {
fprintf(out, "%c", (char)c);
c = fgetc(in);
}
if (isdigit(c) != 0){
ungetc(c, in);
}
}
}
for (int i = 0; i < space_aval - space_needed; ++i){
fscanf(in, "%d" , &num);
if (num & 1){
num = num ^ 1;
}
else{
num = num & ~1;
}
num = num & ~1;
fprintf(out, "%d", num);
c = fgetc(in);
while (isdigit(c) == 0 && c != EOF) {
fprintf(out, "%c", (char)c);
c = fgetc(in);
}
if (isdigit(c) != 0){
ungetc(c, in);
}
if(c == EOF){
break;
}
}
fclose(in); fclose(out);
return 0;
}
int decode(const char * filename, char *txt, int size) {
if (filename == NULL || txt == NULL || size <= 0) return 1;
FILE *fp; fp = fopen(filename, "r");
if (fp == NULL) return 2;
int tmp, err_code;
// TODO: check if file is valid
int space_needed = (size * 8) - 8;
int space_aval = 0;
while (1) {
err_code = fscanf(fp, "%d", &tmp);
if (err_code == EOF) break;
if (err_code != 1) {
fclose(fp);
return 3;
}
space_aval++;
}
if (space_aval < space_needed) {fclose(fp); return 3; }
fseek(fp, 0, SEEK_SET);
FILE *buffer = tmpfile();
buffer = fopen("b_file", "w");
int amount = 0, amount_needed = (size * 8) - 8;
while ((fscanf(fp, "%d", &tmp) != EOF) && (amount++ < amount_needed)) {
fprintf(buffer, "%d", (tmp & 1));
}
buffer = freopen("b_file", "r", buffer);
struct char_b ch; char *tm;
for (int i = 0; i < size - 1; ++i) {
fread(&ch, sizeof(struct char_b), 1, buffer);
*(txt + i) = strtol(ch.c, &tm, 2);
}
*(txt + (size - 1)) = '\0';
fclose(fp); fclose(buffer);
return 0;
}
int main(){
//char esz[1000];
//encode("../dane2.txt", "Information technology and business are becoming inextricably interwoven. I don't think anybody can talk meaningfully about one without the talking about the other. - Bill Gates", "../out.txt");
//decode("../exp.txt", esz, 1000);
//printf("%s", esz);
//return 0;
char in_file[30];
char out_file[30];
char txt[1001];
char c;
int err_code;
printf("Do you want to encode (E/e) or decode (D/d) a message? ");
if (scanf("%c", &c) != 1) {
printf("Incorrect input");
return 1;
}
cls();
if (c == 'E' || c == 'e') {
printf("Enter a message to be encoded: ");
scanf("%1000[^\n]s", txt);
cls();
printf("Enter input file name: ");
if(scanf("%30s", in_file) != 1){
printf("Incorrect input");
return 1;
}
cls();
printf("Enter output file name: ");
if(scanf("%30s", out_file) != 1){
printf("Incorrect input");
return 1;
}
err_code = encode(in_file, txt, out_file);
if(err_code == 4){
printf("Couldn't create file");
return 5;
}
else if(err_code == 2){
printf("Couldn't open file");
return 4;
}
else if(err_code == 3 || err_code == 1){
printf("File corrupted");
return 6;
}
else if(err_code == 0){
printf("File saved");
}
} else if (c == 'D' || c == 'd') {
printf("Enter input file name: ");
if(scanf("%30s", in_file) != 1){
printf("Incorrect input");
return 1;
}
err_code = decode(in_file, txt, 1001);
if(err_code == 2){
printf("Couldn't open file");
return 4;
}
else if(err_code == 3 || err_code == 1){
printf("File corrupted");
return 6;
}
else if(err_code == 0){
printf("%s", txt);
}
} else {
printf("Incorrect input data");
return 1;
}
return 0;
}
|
C
|
/* main.c */
#include <stdio.h>
#include "redirect_ptr.h"
int main(void)
{
const char *firstday = NULL;
const char *secondday = NULL;
get_a_day(&firstday);
get_a_day(&secondday);
printf("%s\t%s\n", firstday, secondday);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int n,a[10000]={},i,sum=0,max=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
if(a[i]>max) max=a[i];
}
for(sum-max>max-1) printf("Yes");
else printf("No");
}
|
C
|
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/* 指向Lua解释器的指针 */
lua_State* L;
static int average(lua_State *L)
{
/* 得到参数个数 */
int n = lua_gettop(L);
double sum = 0;
int i;
/* 循环求参数之和 */
for (i = 1; i <= n; i++)
{
/* 求和 */
sum += lua_tonumber(L, i);
}
/* 压入平均值 */
lua_pushnumber(L, sum / n);
/* 压入和 */
lua_pushnumber(L, sum);
/* 返回返回值的个数 */
return 2;
}
int main ( int argc, char *argv[] )
{
/* 初始化Lua */
L = luaL_newstate();
/* 载入Lua基本库 */
luaL_openlibs(L);
/* 注册函数 */
lua_register(L, "average", average);
/* 运行脚本 */
luaL_dofile(L, "avg.lua");
/* 清除Lua */
lua_close(L);
/* 暂停 */
printf( "Press enter to exit...\n");
getchar();
return 0;
}
|
C
|
/**
* This program tests promotions in c.
* @author Sean Wallace
* @version 1
*/
#include <stdio.h>
/**
* This is the main method.
*/
int main() {
if (-1) {
printf("K&R doesn't Lie.\n");
}
else {
printf("K&R Lied to me.\n");
}
if (9001) {
printf("K&R doesn't Lie.\n");
}
else {
printf("K&R Lied to me.\n");
}
if (0) {
printf("K&R Lied to me.\n");
}
else {
printf("K&R doesn't Lie.\n");
}
return 0;
}
|
C
|
/* serialsnoop.c - Monitor a serial connection, using two serial ports. */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <regex.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <signal.h>
#include <time.h>
#include <ctype.h>
#include "version.h"
#define SS_TIME_FORMAT "%Y-%m-%dT%H:%M:%S"
struct port {
int number;
char *name;
int fd;
struct termios t1;
struct termios t2;
};
static struct port port0;
static struct port port1;
static char *myname;
static int port_baud = B1200;
static char port_baud_string[8] = "1200";
static char port_parity = 'E';
static int port_bits = 7;
static int port_stopbits = 1;
enum outputformat { outTEXT, outXML };
static enum outputformat outputformat = outTEXT;
static int signal_pipe[2];
static struct timeval starttime;
static int flush_stdout = 0;
static int ssdebug = 0;
static void
usage(void)
{
fprintf(stderr, "Usage: %s [options] port0 port1\n", myname);
fprintf(stderr, " -p|--port portparams\n");
fprintf(stderr, " -f|--format text|xml\n");
fprintf(stderr, " -V|--version\n");
fprintf(stderr, " portparams defaults to 1200E71\n");
exit(1);
}
static void
port_params(char *params)
{
static char *port_par_regex = "^([1-9][0-9]*)(N|E|O)?(7|8)?(1|2)?$";
regex_t port_reg;
int ret;
ret = regcomp(&port_reg, port_par_regex, REG_ICASE|REG_EXTENDED);
if (0 != ret) {
static char buf[1024];
regerror(ret, &port_reg, buf, 1024);
fprintf(stderr, "%s: Cannot compile regex \"%s\": %s\n",
myname, port_par_regex, buf);
exit(2);
}
regmatch_t matches[5];
ret = regexec(&port_reg, params, 5, matches, 0);
if (0 != ret) {
fprintf(stderr, "%s: \"%s\" is not a port params string.\n",
myname, params);
exit(2);
}
/* matches[0] will be filled in because the whole regex has matched.
So search for the other matches. */
int start = matches[1].rm_so;
int end = matches[1].rm_eo;
int length = end - start;
//printf("speed start:%d end:%d length:%d\n", start, end, length);
if (-1 == start || -1 == end) {
fprintf(stderr, "%s: no speed specified\n", myname);
exit(2);
}
if (3 == length && 0 == strncmp(params+start, "300", 3)) {
port_baud = B300;
strncpy(port_baud_string, "300", 8);
} else if (4 == length && 0 == strncmp(params+start, "1200", 4)) {
port_baud = B1200;
strncpy(port_baud_string, "1200", 8);
} else if (4 == length && 0 == strncmp(params+start, "2400", 4)) {
port_baud = B2400;
strncpy(port_baud_string, "2400", 8);
} else if (4 == length && 0 == strncmp(params+start, "4800", 4)) {
port_baud = B4800;
strncpy(port_baud_string, "4800", 8);
} else if (4 == length && 0 == strncmp(params+start, "9600", 4)) {
port_baud = B9600;
strncpy(port_baud_string, "9600", 8);
} else if (5 == length && 0 == strncmp(params+start, "19200", 4)) {
port_baud = B19200;
strncpy(port_baud_string, "19200", 8);
} else if (5 == length && 0 == strncmp(params+start, "38400", 4)) {
port_baud = B38400;
strncpy(port_baud_string, "38400", 8);
} else {
char buf[length+1];
strncpy(buf, params+start, length);
buf[length] = '\0';
fprintf(stderr, "%s: unsupported baud rate: %s\n", myname, buf);
exit(2);
}
/* Hmm, we might never see these error checks, because they won't get
matched by the regex above... */
if (-1 == matches[2].rm_so) {
port_parity = 'E';
} else {
switch (params[matches[2].rm_so]) {
case 'n': case 'N':
port_parity = 'N';
break;
case 'e': case 'E':
port_parity = 'E';
break;
case 'o': case 'O':
port_parity = 'O';
break;
default:
fprintf(stderr,
"%s: Strange parity character %c (0x%02x)\n",
myname, params[matches[2].rm_so],
params[matches[2].rm_so]);
exit(2);
}
}
if (-1 == matches[3].rm_so) {
port_bits = 7;
} else if ('7' == params[matches[3].rm_so]) {
port_bits = 7;
} else if ('8' == params[matches[3].rm_so]) {
port_bits = 8;
} else {
fprintf(stderr, "%s: Strange data bits character %c (0x%02x)\n",
myname, params[matches[3].rm_so],
params[matches[3].rm_so]);
exit(2);
}
if (-1 == matches[4].rm_so) {
port_stopbits = 1;
} else if ('1' == params[matches[4].rm_so]) {
port_stopbits = 1;
} else if ('2' == params[matches[4].rm_so]) {
port_stopbits = 2;
} else {
fprintf(stderr, "%s: Strange stop bits character %c (0x%02x)\n",
myname, params[matches[4].rm_so],
params[matches[4].rm_so]);
exit(2);
}
}
static void
open_ports(void)
{
if (ssdebug) fprintf(stderr, "Opening %s\n", port0.name);
port0.fd = open(port0.name, O_RDONLY|O_NONBLOCK|O_NOCTTY);
if (-1 == port0.fd) {
fprintf(stderr, "%s: cannot open %s: %s\n", myname, port0.name,
strerror(errno));
exit(2);
}
if (ssdebug) fprintf(stderr, "Opening %s\n", port1.name);
port1.fd = open(port1.name, O_RDONLY|O_NONBLOCK|O_NOCTTY);
if (-1 == port1.fd) {
fprintf(stderr, "%s: cannot open %s: %s\n", myname, port1.name,
strerror(errno));
exit(2);
}
}
static void
setup_port(struct port *p)
{
int ret;
cfmakeraw(&p->t1);
ret = cfsetispeed(&p->t1, port_baud);
if (-1 == ret) {
fprintf(stderr, "%s: cannot set %s speed to %s: %s\n",
myname, p->name, port_baud_string, strerror(errno));
exit(2);
}
if ('E'==port_parity) {
p->t1.c_cflag |= PARENB;
p->t1.c_cflag &= ~PARODD;
}
else if ('O'==port_parity) {
p->t1.c_cflag |= PARENB;
p->t1.c_cflag |= PARODD;
}
else {
p->t1.c_cflag &= ~PARENB;
}
p->t1.c_cflag &= ~CSIZE;
if (7==port_bits) {
p->t1.c_cflag |= CS7;
} else if (8==port_bits) {
p->t1.c_cflag |= CS8;
}
/* no flow control */
p->t1.c_cflag &= ~CRTSCTS;
ret = tcsetattr(p->fd, TCSANOW, &p->t1);
if (-1 == ret) {
fprintf(stderr, "%s: cannot set port parameters for %s: %s\n",
myname, p->name, strerror(errno));
exit(2);
}
}
static void
setup_ports(void)
{
setup_port(&port0);
setup_port(&port1);
}
static void
print_byte(struct port *p, unsigned char c)
{
struct timeval t;
struct tm *tm;
struct timeval tdiff;
char timestring[200];
gettimeofday(&t, 0);
timersub(&t, &starttime, &tdiff);
tm = gmtime(&(t.tv_sec));
strftime(timestring, 199, SS_TIME_FORMAT, tm);
/* The output here should be done in a single printf, to try to make it
a single write. */
switch (outputformat) {
case outTEXT:
if (isprint(c))
printf("%d %s %d.%06d 0x%02x %c\n", p->number,
timestring, (int)tdiff.tv_sec,
(int)tdiff.tv_usec, c, c);
else
printf("%d %s %d.%06d 0x%02x\n", p->number,
timestring, (int)tdiff.tv_sec,
(int)tdiff.tv_usec, c);
break;
case outXML:
if (isprint(c))
printf(" <byte line='%d' time='%d.%06d' "
"value='0x%02x' ascii='%c' />\n",
p->number, (int)tdiff.tv_sec,
(int)tdiff.tv_usec, c, c);
else
printf(" <byte line='%d' time='%d.%06d' "
"value='0x%02x' />\n",
p->number, (int)tdiff.tv_sec,
(int)tdiff.tv_usec, c);
break;
}
fflush(stdout);
}
static void
read_data(struct port *p)
{
unsigned char c;
int nread;
//printf("Reading from %s\n", p->name);
while (1) {
nread = read(p->fd, &c, 1);
if (0 == nread) {
fprintf(stderr, "EOF on %s\n", p->name);
exit(0);
} else if (1 == nread) {
print_byte(p, c);
} else if (-1 == nread) {
if (EWOULDBLOCK == errno) {
break;
} else {
fprintf(stderr, "Error reading %s: %s\n",
p->name, strerror(errno));
exit(2);
}
} else {
fprintf(stderr, "Strange return from reading %s: %d\n",
p->name, nread);
}
}
}
static void
print_header(void)
{
char timestring[200];
struct tm *tm;
tm = gmtime(&(starttime.tv_sec));
strftime(timestring, 199, SS_TIME_FORMAT, tm);
switch (outputformat) {
case outTEXT:
printf("port 0: %s\n", port0.name);
printf("port 1: %s\n", port1.name);
printf("start time: %s.%06d\n", timestring,
(int)starttime.tv_usec);
printf("Port parameters: %s%c%d%d\n",
port_baud_string, port_parity, port_bits, port_stopbits);
break;
case outXML:
printf("<?xml version='1.0' encoding='UTF-8' ?>\n"
"<capture>\n"
" <header>\n"
" <starttime>%d.%06d</starttime>\n"
" <port><id>0</id><name>%s</name></port>\n"
" <port><id>1</id><name>%s</name></port>\n"
" <parameters>%s%c%d%d</parameters>\n"
" </header>\n"
" <data>\n",
(int)starttime.tv_sec, (int)starttime.tv_usec,
port0.name, port1.name,
port_baud_string, port_parity, port_bits, port_stopbits);
break;
}
fflush(stdout);
}
static void
print_trailer(void)
{
switch (outputformat) {
case outTEXT:
break;
case outXML:
printf(" </data>\n</capture>\n");
break;
}
fflush(stdout);
}
static void
mainloop(void)
{
fd_set rfds;
fd_set wfds;
fd_set xfds;
struct timeval timeout;
int ret;
int selecterr;
int maxfdp1;
while (1) {
FD_ZERO(&rfds);
FD_ZERO(&wfds);
FD_ZERO(&xfds);
maxfdp1 = 0;
FD_SET(port0.fd, &rfds);
if (port0.fd >= maxfdp1) maxfdp1 = port0.fd + 1;
FD_SET(port1.fd, &rfds);
if (port1.fd >= maxfdp1) maxfdp1 = port1.fd + 1;
FD_SET(signal_pipe[0], &rfds);
if (signal_pipe[0] >= maxfdp1) maxfdp1 = signal_pipe[0] + 1;
timeout.tv_sec = 0;
timeout.tv_usec = 10000;
ret = select(maxfdp1, &rfds, &wfds, &xfds, &timeout);
selecterr = errno;
switch (ret) {
case -1:
switch (selecterr) {
case EINTR:
/* A question here: after the signal handler
writes to the pipe, is the pipe always ready
for reading when we return EINTR from
select()? It seems to work in a couple of
tests, but is this guaranteed? */
if (FD_ISSET(signal_pipe[0], &rfds)) {
print_trailer();
exit(0);
}
default:
fprintf(stderr, "%s: error in select(): %s\n",
myname, strerror(selecterr));
exit(2);
break;
}
default:
/* Handle file descriptors. */
if (FD_ISSET(port0.fd, &rfds)) {
read_data(&port0);
}
if (FD_ISSET(port1.fd, &rfds)) {
read_data(&port1);
}
/*FALLTHROUGH*/
case 0:
/* Read serial port control lines. */
break;
}
}
}
static void
sigint_handler(int signum)
{
write(signal_pipe[1], "i", 1);
}
static void
setup_signal_handler(void)
{
int ret;
ret = pipe(signal_pipe);
if (-1 ==ret) {
fprintf(stderr, "%s: Cannot create pipe: %s\n",
myname, strerror(errno));
exit(2);
}
signal(SIGINT, sigint_handler);
}
static const char *opts = "dp:f:V";
static const struct option longopts[] = {
{ "debug", no_argument, NULL, 'd' },
{ "flush", no_argument, NULL, 'F' },
{ "format", required_argument, NULL, 'f' },
{ "param", required_argument, NULL, 'p' },
{ "version",no_argument, NULL, 'V' },
{ 0, 0, 0, 0}
};
int
main(int argc, char **argv)
{
myname = argv[0];
while (1) {
int c = getopt_long(argc, argv, opts, longopts, 0);
if (-1==c)
break;
switch (c) {
case 'd':
ssdebug = 1;
break;
case 'f':
if (!strcmp(optarg, "xml"))
outputformat = outXML;
else if (!strcmp(optarg, "text"))
outputformat = outTEXT;
else
usage();
break;
case 'F':
flush_stdout = 1;
break;
case 'p':
port_params(optarg);
break;
case 'V':
printf("serialsnoop " SERIALSNOOP_VERSION_STR "\n");
exit(0);
default:
case '?':
usage();
break;
}
}
if (argc-optind != 2) {
usage();
}
port0.number = 0;
port0.name = argv[optind];
port1.number = 1;
port1.name = argv[optind+1];
open_ports();
setup_ports();
gettimeofday(&starttime, 0);
print_header();
setup_signal_handler();
mainloop();
return 0;
}
|
C
|
/*
* @FileName: sip_client.c
* @Author: wzj
* @Brief:
*
*
*
*
*
* @History:
*
*
*
* @Date: 2012年05月27日星期日09:48:12
*
*/
#include "sock_i.h"
#include "rio.h"
#include <stdio.h>
#include <string.h>
int
main(int argc, char **argv)
{
int srv_fd = -1;
int clt_fd = -1;
int port = 0;
char *host,buf[1024];
rio_t rio;
if(argc != 3)
{
return -1;
}
host = argv[1];
port = atoi(argv[2]);
clt_fd = open_clientfd(host, port);
rio_initb(&rio, clt_fd);
printf("%d\n", clt_fd);
//while((fgets(buf, sizeof(buf), stdin) != NULL) && (ferror(stdin) == 0))
while(1)
{
if((fgets(buf, sizeof(buf), stdin) == NULL) &&
ferror(stdin))
{
printf("why\n");
break;
}
printf("clinet : %s\n",buf);
rio_writen(clt_fd, buf, strlen(buf));
rio_readlineb(&rio, buf, sizeof(buf));
fputs(buf, stdout);
}
return 0;
}
|
C
|
/********************************************************************
*
* @Arxiu : llista.h
* @Finalitat : Capçaleres de les funcions del TAD llista.
* @Autors : Esteve Genovard Ferriol - ls30742 & Sergi Simó Bosquet - ls30685
* @Data Creació: 15 de novembre del 2016
*
******************************************************************** */
#ifndef _LLISTA_H_
#define _LLISTA_H_
//Llibreries pròpies
#include "seenList.h"
//Constants
//Capçaleres
/* **********************************************
*
* @Nom : LLISTA_crea
* @Definicio : Funció constructura de la llista.
* @Arg : void
* @Ret : Llista correctament creada.
*
************************************************/
Llista LLISTA_crea ();
/* **********************************************
*
* @Nom : LLISTA_insereix
* @Definicio : Funció que permet inserir un element a la llista a l'esquerra del pdi.
* @Arg : In/Out: llista = llista on s'inserirà el nou element.
* In: client = element que s'inserirà a la llista.
* @Ret : 0 en el cas que s'hagi produit un error, 1 en cas contrari.
*
************************************************/
int LLISTA_insereix (Llista * llista, Client client);
Client LLISTA_consulta(Llista llista);
/* **********************************************
*
* @Nom : LLISTA_busca
* @Definicio : Funció que permet buscar un client dintre la llista.
* @Arg : In: llista = llista on s'ha de buscar.
* In: name = nom del client que s'ha de buscar a la llista.
* @Ret : 0 en el cas que el client no es trobi en la llista, 1 en cas contrari.
*
************************************************/
int LLISTA_busca (Llista llista, char * name);
/* **********************************************
*
* @Nom : LLISTA_elimina
* @Definicio : Funció que permet eliminar un element concret de la llista.
* @Arg : In/Out: llista = llista d'on s'ha d'eliminar el client.
* In: name = nom del client que s'ha d'eliminar.
* @Ret : 0 en el cas que el client a eliminar no es trobi en la llista, 1 en cas contrari.
*
************************************************/
int LLISTA_elimina (Llista * llista, char * name);
/* **********************************************
*
* @Nom : LLISTA_destrueix
* @Definicio : Funció destructora de la llista.
* @Arg : In/Out: llista = llista a destruir.
* @Ret : void
*
************************************************/
void LLISTA_destrueix (Llista * llista);
void LLISTA_vesInici(Llista * llista);
void LLISTA_avanca(Llista * llista);
int LLISTA_fi(Llista llista);
#endif
|
C
|
/**
* Programmlogik soweit vorhanden. Im Endeffekt bleibt nicht viel, da wir kaum Logik haben.
*
* @author Maurice Tollmien. Github: MauriceGit
*/
/* ---- System Header einbinden ---- */
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#ifdef MACOSX
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
/* ---- Eigene Header einbinden ---- */
#include "logic.h"
#include "vector.h"
#include "scene.h"
#include "types.h"
/** Mausbewegung zoom/move/none */
MouseInterpretType G_Mouse;
/** Kameraposition */
CGVector3D G_CameraPosition = {CAMERA_X,CAMERA_Y,CAMERA_Z};
/** Position der Maus */
Movement G_MouseMove = {0.0,0.0,0.0};
/** Startpunkt der Mausbewegung */
CGVector3D G_LastMouseCenter = {0.0,0.0,0.0};
/** FPS */
int G_FPS = 0;
/** Partikel hinzufügen? */
/** FPS counter */
double G_Counter = 0.0-EPS;
/* ------- GETTER / SETTER ------- */
/**
* Mouse Status.
*/
void setMouseState(MouseInterpretType state) {
G_Mouse = state;
}
void setMouseCoord(int x, int y) {
G_LastMouseCenter[0] = x;
G_LastMouseCenter[2] = y;
}
/**
* Set-Function für den Status der Maus
* @param Status der Maus
*/
void setMouseEvent(MouseInterpretType state,int x, int y) {
G_MouseMove[0] = 0.0;
G_MouseMove[2] = 0.0;
G_LastMouseCenter[0] = x;
G_LastMouseCenter[2] = y;
G_Mouse = state;
}
/**
* Get-Function für den Status der Maus
* @return Status der Maus
*/
MouseInterpretType getMouseEvent() {
return G_Mouse;
}
/**
* Gibt die Kamerakoordinate zurück.
*/
double getCameraPosition (int axis)
{
if (axis >= 0 && axis < 3)
return G_CameraPosition[axis];
return 0.0;
}
/**
* Bewegt die Kamera auf einem Kugelradius um den Szenenmittelpunkt.
*/
void setCameraMovement(int x,int y)
{
CGVector3D tmp;
double factor, radius = vectorLength3D(G_CameraPosition);
tmp[0] = G_CameraPosition[0];
tmp[1] = G_CameraPosition[1];
tmp[2] = G_CameraPosition[2];
G_MouseMove[0] = x-G_LastMouseCenter[0];
G_MouseMove[2] = y-G_LastMouseCenter[2];
G_LastMouseCenter[0] = x;
G_LastMouseCenter[2] = y;
/* Bewegung um Y-Achse: */
G_CameraPosition[0] = cos(-G_MouseMove[0]*PI/180.0/CAMERA_MOVEMENT_SPEED)*tmp[0] + sin(-G_MouseMove[0]*PI/180.0/CAMERA_MOVEMENT_SPEED)*tmp[2];
G_CameraPosition[2] = -sin(-G_MouseMove[0]*PI/180.0/CAMERA_MOVEMENT_SPEED)*tmp[0] + cos(-G_MouseMove[0]*PI/180.0/CAMERA_MOVEMENT_SPEED)*tmp[2];
/* Bewegung oben/unten */
G_CameraPosition[1] += G_MouseMove[2]/(CAMERA_MOVEMENT_SPEED/2)*(vectorLength3D(G_CameraPosition)/100.0);
factor = 1.0 / (vectorLength3D(G_CameraPosition) / radius);
multiplyVectorScalar (G_CameraPosition, factor, &G_CameraPosition);
}
/**
* Verlängert/verkürzt den Vektor zur Kamera.
*/
void setCameraZoom(int x,int y)
{
double factor = 1.0 + (CAMERA_ZOOM_SPEED / 1000.0) * ((G_MouseMove[2] < 0.0) ? -1.0 : 1.0);
G_MouseMove[0] = x-G_LastMouseCenter[0];
G_MouseMove[2] = y-G_LastMouseCenter[2];
G_LastMouseCenter[0] = x;
G_LastMouseCenter[2] = y;
G_CameraPosition[0] *= factor;
G_CameraPosition[1] *= factor;
G_CameraPosition[2] *= factor;
}
/* ------- BERECHNUNGEN ------- */
/**
* Berechnet alle Funktionen, die vom interval abhängig sind
* @param interval - Zeit
*/
void calcTimeRelatedStuff (double interval)
{
G_Counter += interval;
if (G_Counter >= 1.0)
G_Counter = 0.0 -EPS;
if (G_Counter <= 0.0)
G_FPS = (int) 1.0/interval;
}
/* ------- INIT ------- */
/**
* Initialisiert die Kamera.
*/
void initCameraPosition ()
{
G_CameraPosition[0] = CAMERA_X;
G_CameraPosition[1] = CAMERA_Y;
G_CameraPosition[2] = CAMERA_Z;
}
/**
* Hier findet die komplette Initialisierung des kompletten SPIEeles statt.
* Inklusive der Datenhaltung und des SPIEelfeldes.
*/
void initGame ()
{
initCameraPosition();
}
|
C
|
//signal设置信号处理行为,演示不同信号到来时,后来的信号会打断原有信号的信号处理函数效果
#include <func.h>
void signal_handler(int signal_num)
{
printf("捕捉信号:%d\n",signal_num);
sleep(4);
printf("信号%d处理完毕!\n",signal_num);
}
int main(int argc,char *argv[])
{
signal(SIGINT,signal_handler);
signal(SIGQUIT,signal_handler);
while(1);
return 0;
}
|
C
|
#include <stdio.h>
int main(){
/*Arrays*/
//Arrays are mutable i.e. can be modified
int array[5]={1,2,3,4,5};
int i;
printf("Size(memory) of array is:%d\n",sizeof(array)/sizeof(array[0]));
for ( i=0 ; i<5;i++){
array[i] = i*2;
printf("%d\n",array[i]);
}
return 0;
}
|
C
|
#include "player_curepoison.h"
#include <stdio.h>
int player_curepoison(int *flag){
if(*flag == 1){
*flag = 0;
printf("毒は綺麗さっぱりなくなった!\n");
}
if(*flag>1){
*flag -= 1;
printf("毒の症状が軽減した!\n");
}
return 0;
}
|
C
|
#include "libft.h"
void *ft_memcpy(void *dst, const void *src, size_t n)
{
size_t i;
unsigned char *ptr_dst;
unsigned char *ptr_src;
i = 0;
ptr_dst = (unsigned char *)dst;
ptr_src = (unsigned char *)src;
if (ptr_dst != NULL || ptr_src != NULL)
{
while (i < n)
{
ptr_dst[i] = ptr_src[i];
i++;
}
}
return (dst);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
/* polinomlarn her bir terimi olarak kullanlacak yap */
typedef struct pol_oge *pol_gosterge;
typedef struct pol_oge{
int katsayi;
int us;
pol_gosterge bag;
}pol_oge;
void encryption(int key,char * data,char *cipher_text)
{
FILE *ptr;
ptr = fopen (cipher_text,"w");
fprintf(ptr,"Key=%d\n",key);
int size=strlen(data),i;
for(i=0;i<size;i++)
fprintf(ptr,"%c",data[i]^key);
}
double key_calc(int x,double id[],double key[],int size)
{
int i,j;
double aratoplam=1,toplam=0;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
if(i==j)
continue;
aratoplam=aratoplam*((x-id[j]) / (id[i]-id[j]));
}
toplam=toplam+(aratoplam*key[i]);
aratoplam=1;
}
return toplam;
}
/* Listede parametresinden sonra gelen eyi listeden ve bellekten siler */
void SonrakiTerimiSil( pol_gosterge Onceki ){
pol_gosterge Silinecek = Onceki->bag; // free yapabilmek iin adresi tutmalyz
if( !Silinecek ) return; // zaten e yoksa ilem yaplamaz
Onceki->bag = Onceki->bag->bag; // ba alanlar dzgnce gncellenmelidir
free(Silinecek); // bellekteki kalnt temizlenmelidir
}
/* Dinamik bellek alp belirtilen st ve katsayi bilgilerine sahip bir terim oluturur
ve Onceki parametresi ile verilen enin peine liste yapsn bozmadan ekler */
pol_gosterge YeniTerimEkle( int Ust, int Katsayi, pol_gosterge Onceki ){
pol_gosterge p = (pol_gosterge) malloc( sizeof(pol_oge) );
if( !p ){ printf("Bellek yetmiyor yetmiyoor..."); exit(1); }
p->us = Ust; // st bilgisini yaz
p->katsayi = Katsayi; // katsay bilgisini yaz
if( Onceki ){ // Onceki parametresi belirtildi
p ->bag = Onceki->bag; // araya yada sona ekle
Onceki->bag = p;
} else p->bag = NULL; // Onceki botur, baka bir terimin peine eklenmeyecek
return p;
}
/* Paralel olarak dzenlenmi ekilde verilen sler ve katsaylar dizilerindeki
deerlerle bir polinom listesi oluturup liste bana gsterge dndrr */
pol_gosterge ListeDoldur( int *Carpanlar, int *Kuvvetler ){
pol_gosterge ListeBasi=NULL, p = NULL;
for( ; *Kuvvetler >= 0 && Carpanlar && Kuvvetler ; Carpanlar++, Kuvvetler++ ){
p = YeniTerimEkle( *Kuvvetler, *Carpanlar, p );
if( !ListeBasi ) ListeBasi = p; // ilk terimi ekleyince ListeBasi'ni ayarla
}
return ListeBasi;
}
/* Liste olarak verilen iki polinomu birbiriyle arpp yeni bir polinom listesi oluturur
ve bu yeni polinomun liste ba adresini dndrr.
Polinomlardan en az bir tanesi sfr polinomu ise NULL dndrr.
*/
pol_gosterge PolCarp( pol_gosterge pBas, pol_gosterge qBas ){
pol_gosterge rBas = NULL, // yeni oluturulacak sonu listesi
p, q, r, // pBas, qBas ve rBas (sonu) listelerinde dolaacak gstergeler
baslangic = NULL; /* yeni oluturulan bir elemann sonu listesi zerinde
eklenecei konumun aranmaya balanaca yere gsterge */
int rUst, rKat; // her iki elemann arpmnda st ve katsay bilgileri
for( p = pBas ; p ; p = p->bag ){
r = baslangic; // q listesine her balayta r'yi son iaretlenen (baslangic) konumdan balat
for( q = qBas ; q ; q = q->bag ){
rUst = p->us + q->us; // stler toplanr
rKat = p->katsayi * q->katsayi; // katsaylar arplr
if ( rBas ){ // listenin ilk eleman deil
// uygun konumu ara
while ( r->bag && ( r->bag->us > rUst ) ) r = r->bag;
// ss bu olan eleman daha nce eklenmedi, yeni eleman ekle
if ( !r->bag || ( r->bag->us < rUst ) ) YeniTerimEkle( rUst, rKat, r );
// ss ayn olan eleman zaten eklenmiti, katsayy gncelle, katsay sfrlanrsa eleman sil
else if( ( r->bag->katsayi += rKat ) == 0 ) SonrakiTerimiSil(r);
}
else rBas = r = baslangic = YeniTerimEkle( rUst, rKat, NULL ); // listenin ilk eleman eklendi
if( q == qBas ) baslangic = r; // p listesinin sonraki eleman ile arpmlar bu konumdan itibaren yerleecek
}
}
return rBas;// sonu listesinin ban dndr
}
double alt_hesapla(int x,double id[],double key[],int size)
{
int i,j;
double toplam=1;
for(j=0;j<size;j++)
{
if(id[j]==x)
continue;
toplam=toplam*(x-id[j]);
}
return toplam;
}
void sub_polynomials(double id[],double key[],int size,char *cipher_text)
{
FILE *ptr;
ptr = fopen (cipher_text,"w");
int i=0,j=0;
pol_gosterge ListeBasi=NULL, p = NULL ,o=NULL;
for(j=0;j<size;j++)
{
int sub=id[j],control=0;
for(i=0;i<size;i++)
{
if(id[i]==sub)
continue;
o = YeniTerimEkle( 1, 1 , o );
if( !ListeBasi ) ListeBasi = o; // ilk terimi ekleyince ListeBasi'ni ayarla
o = YeniTerimEkle( 0, -id[i], o );
if( !ListeBasi ) ListeBasi = o; // ilk terimi ekleyince ListeBasi'ni ayarla
pol_gosterge list1 = ListeBasi;
if(control==0)
{
p=list1;
control++;
ListeBasi=NULL; o=NULL;
continue;
}
p=PolCarp(list1,p);
ListeBasi=NULL; o=NULL;
}
double alt=alt_hesapla(id[j],id,key,size);
fprintf(ptr,"%0.f : ",id[j]);
for( ; p ; p = p->bag )
{
if(p->katsayi/alt<0)
fprintf(ptr,"%.2f",p->katsayi/alt);
else if(p->katsayi/alt>0)
fprintf(ptr,"+%.2f",p->katsayi/alt);
if(p->us==1)
fprintf(ptr,"x");
else if(p->us!=0)
fprintf(ptr,"x^%d",p->us);
}
fprintf(ptr,"\n");
}
}
void load(char *keys_file ,char *plain_text ,char *cipher_text)
{
int size=0,i=0,j=0;
char temp;
char line[250];
FILE *ptr;
ptr = fopen (keys_file,"r");
while (!feof(ptr))
{
fgets (line,250,ptr);
size++;
}
fclose (ptr);
double id[size];
double key[size];
ptr = fopen (keys_file,"r");
while (!feof(ptr))
{
fscanf (ptr, "%lf", &id[i]);
i++;
fscanf(ptr, "%c", &temp);
fscanf(ptr, "%c", &temp);
fscanf(ptr, "%c", &temp);
fscanf (ptr, "%lf", &key[j]);
j++;
}
fclose (ptr);
if(plain_text!=NULL)
{
int size_plain=0;
ptr = fopen (plain_text,"r");
while (!feof(ptr))
{
fgets (line,50,ptr);
size_plain++;
}
fclose (ptr);
char * data=(char *) malloc(size_plain*50);
ptr = fopen (plain_text,"r");
strcpy(data,"");
while (!feof(ptr))
{
fgets (line,50,ptr);
strcat(data,line);
}
encryption(key_calc(0,id,key,size),data,cipher_text);
}
else
sub_polynomials(id,key,size,cipher_text);
}
void arrange(char **argc)
{
if(strcmp(argc[1],"-e")==0)
load(argc[2],argc[3],argc[4]);
else if(strcmp(argc[1],"-l")==0)
load(argc[2],NULL,argc[3]);
}
int main(int arg,char **argc)
{
arrange(argc);
return 0;
}
|
C
|
#define UNW_LOCAL_ONLY
#define _GNU_SOURCE
#include <dlfcn.h>
#include <libunwind.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
void show_backtrace (void)
{
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp, offp;
char symbol[4096];
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
while (unw_step(&cursor) > 0)
{
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
if (unw_get_proc_name(&cursor, symbol, sizeof(symbol), &offp) < 0)
{
sprintf(symbol, "%s", "????");
}
printf ("0x%lx\tin %s (ip = %lx, sp = %lx)\n",
offp, symbol, (long) ip, (long) sp);
}
}
void check_memory_protection(void *addr, int prot)
{
if (prot & PROT_EXEC && prot & PROT_READ && prot & PROT_WRITE)
{
fprintf(stderr, "An rwx page requested at address %p\n", addr);
fprintf(stderr, "Backtrace:\n");
show_backtrace();
}
}
void assert_symbol_address(void *addr)
{
if (!addr)
{
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
}
void *mmap(void *addr, size_t length, int prot, int flags,
int fd, off_t offset)
{
check_memory_protection(addr, prot);
void *(*next_mmap)(void *addr, size_t length, int prot, int flags,
int fd, off_t offset) = dlsym(RTLD_NEXT, "mmap");
assert_symbol_address(next_mmap);
return next_mmap(addr, length, prot, flags, fd, offset);
}
int mprotect(void *addr, size_t len, int prot)
{
check_memory_protection(addr, prot);
int (*next_mprotect)(void *addr, size_t len, int prot)
= dlsym(RTLD_NEXT, "mprotect");
assert_symbol_address(next_mprotect);
return next_mprotect(addr, len, prot);
}
|
C
|
/*
* SCROLL (2/15/94)
* Given to an invited player so they can learn more of the guild
*/
id(str) { return str == "scroll"; }
get() { return 1; }
query_value() { return 0; }
drop() {
write("The scroll crumbles as it leaves your hand.\n");
destruct(this_object());
return 1;
}
short() { return "A large golden scroll"; }
long() {
write("}-=-=-=-=-=-{ AN INVITATION TO THE PALADINS }-=-=-=-=-=-{\n");
write("To learn more about the Paladins: info, info <topic>\n");
write("To join: join\n");
write("The Paladins Guild is located in Sandman's castle.\n");
write("}-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-{\n");
}
init() {
add_action("info","info");
add_action("join","join");
}
info(str) {
if(!str) {
cat("/players/sandman/paladin/helpdir/info");
return 1;
}
if(!cat("/players/sandman/paladin/helpdir/"+str))
write("No such help file: "+str+"\n");
return 1;
}
join() {
call_other("/players/sandman/paladin/entry","join");
return 1;
}
|
C
|
/**@<gencode.h>::**/
#include <stdio.h>
#include <stdarg.h>
#include <gencode.h>
#include <typecheck.h>
#include <symtab.h>
#include <errorhandler.h>
/*
*Encapsula metodo de escrita de arquivo e verifica a presenca de erros na compilacao
*/
void genprint(const char *format, ...)
{
if (error)
return;
va_list args;
va_start(args, format);
vfprintf(ascode, format, args);
va_end(args);
}
/*
*Geracao da secao .data em assembly
*/
void gensecdata()
{
genprint("\t.data\n");
}
/*
*Geracao da secao .text em assembly
*/
void gensectext()
{
genprint("\t.text\n");
genprint("\t.global _start\n\n");
genprint("_start:\n");
}
/*
* Geracao de codigo da declaracao de variaveis
*/
void genvar(int initial, int final, int typevar)
{
int i;
char sizebyte[5];
switch(typevar){
case INTEGER_TYPE:
case REAL_TYPE:
sprintf(sizebyte,"dd");
break;
case BOOLEAN_TYPE:
sprintf(sizebyte,"db");
break;
default:
sprintf(sizebyte,"dq");
}
for (i = initial; i < final; i++)
genprint("%-*s: %s\n", MAXIDLEN, &(symtab_names[symtab_descriptor[i][0]]), sizebyte);
}
|
C
|
#include <stdio.h>
int main(void)
{
char s1[] = "100 200 300";
char s2[30];
int value;
sscanf(s1, "%d",&value); //ڿ s1 %d value
printf("%d\n", value);
sprintf(s2,"%d",value); //value ڿ ȯϿ s2
printf("%s\n",s2);
return 0;
}
|
C
|
int main()
{
int n,i,a,b,c,A=0,B=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d%d",&a,&b);
if(a==b)
{
continue;
}
else
{
if((a==2&&b==0)||(a==0&&b==2))
{
c=a;
a=b;
b=c;
}
if(a<b)
{
A++;
}
else
{
B++;
}
}
}
if(A==B)
{
printf("Tie");
}
else
{
if(A>B)
{
printf("A");
}
else
{
printf("B");
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include "printInternalReg.h"
//
// printRegS() takes the a structure with the following fields.
//
// PC - the address that the program counter is at when the instruction is retrieved
// icode - the instruction code
// ifun - the function code for the instruction
// regsValid - Not all instructions set the rA and rB values. If an instruction
// has an rA and rB value this is set to a non-zero value and to
// 0 if rA and rB is not valid.
// rA - the rA value, if regsValid is zero this can be anything.
// rB - the rB value, if regsValid is zero this can be anything.
// valCValid - Not all instructions have a valC value. If an instruction has a
// a valC value this is set to any non-zero value otherwise it is set
// to zero.
// valC - if valCValid is true (i.e. non-zero) then this contains the value of valC such that
// when it is printed as an unsigned integer it has the expected value. For example if the
// the instruction were mrmovq 32(%r9), %r10 then valC in memory, in little endian
// format would be 20 00 00 00 00 00 00 00, but when we print it as an integer, in hex,
// it would print 0000000000000020
// if valCvalid is false (i.e. 0) then valC can have any value
// byte0 - byte7 These are the 8 individual bytes that make up valC, assuming
// valCvalid is true. Byte0 is the least significant byte
// and byte8 the most significant byte. When these bytes
// are printed in the order from byte0 to byte8 it will reproduce the in
// memory representation of valC.
// valP This is the value of valP as deteremined during the fetch stage.
// instr This is the string representation of the instruction mnemonic. Note that if the
// instruction is an unconditional jump then it is reported as jmp, and if it is
// an unconditional move then it is reported as rrmovq. The mnemonics are to
// be the ones from the text book.
static int currentLine = 0; // This variable is used to determine the line number being printed so that
// a header line can be periodically printed.
void printRegS(struct fetchRegisters *reg) {
// Print the header line every 20 lines
if (!(currentLine++ % 20)) {
printf("\nPC icode ifun rA rB valC ValClsb valCmsb valP Instruction\n");
}
// print the program counter (only the low order 4 bytes are printed)
printf("%08llX : %2X %2X ", reg->PC, reg->icode, reg->ifun);
// If required print the register values
if (reg->regsValid) {
printf(" %2X %2X ", reg->rA, reg->rB);
} else {
printf(" - - ");
}
// Print valC, if present
if (reg->valCValid) {
printf("%016llX %02X%02X%02X%02X %02X%02X%02X%02X ", reg->valC,
reg->byte0, reg->byte1, reg->byte2, reg->byte3,
reg->byte4, reg->byte5, reg->byte6, reg->byte7);
} else {
printf("%36s", " ");
}
// Print valP and the instruction mnemonic.
printf("%016llX %s\n", reg->valP, reg->instr);
}
|
C
|
#include "date.h"
#include <stdbool.h>
#include <stdlib.h>
#define MIN_DAY 1
#define MAX_DAY 30
#define MIN_MONTH 1
#define MONTH_NUM 12
#define DAYS_IN_YEAR 360
#define ERROR_ARG_RESULT 0
struct Date_t
{
int day;
int month;
int year;
};
/*static function*/
/** Checks if the day given is valid
*@param day - the day of the date
*@return
true if day is valid (1-30), else otherwise
**/
static bool isDayValid(int day)
{
return day >= MIN_DAY && day <= MAX_DAY;
}
/** Checks if the month given is valid
*@param month - the month of the date
*@return
true if month is valid (1-12), else otherwise
**/
static bool isMonthNumberValid(int month)
{
return month >= MIN_MONTH && month <= MONTH_NUM;
}
/*ADT methods*/
Date dateCreate(int day, int month, int year)
{
if (!isDayValid(day) || !isMonthNumberValid(month))
return NULL;
Date date = malloc(sizeof(*date));
if (!date)
return NULL;
date->day = day;
date->month = month;
date->year = year;
return date;
}
void dateDestroy(Date date)
{
free(date);
}
Date dateCopy(Date date)
{
if (!date)
return NULL;
return dateCreate(date->day,date->month,date->year);
}
bool dateGet(Date date, int* day, int* month, int* year)
{
if (date && day && month && year)
{
*day = date->day;
*month = date->month;
*year = date->year;
return true;
}
return false;
}
static int dateToDays(Date date)
{
return date->day + date->month * MAX_DAY + date->year * DAYS_IN_YEAR;
}
int dateCompare(Date date1, Date date2)
{
if (!date1 || !date2)
return ERROR_ARG_RESULT;
return dateToDays(date1) - dateToDays(date2);
}
void dateTick(Date date)
{
if (date)
{
if(date->day == MAX_DAY)
{
date->day = MIN_DAY;
if (date->month == MONTH_NUM)
{
date->month = MIN_MONTH;
date->year += 1;
}
else
date->month += 1;
}
else
date->day += 1;
}
}
|
C
|
#include "fxp.h"
int fxp_format_int(int32_t n, char *str)
{
int ndigits;
int32_t tmp;
char *ptr;
if(n == 0) {
str[0] = '0';
str[1] = '\0';
return 1;
}
// calculate number of digits
if(n < 0) {
ndigits = 1;
tmp = -n;
} else {
ndigits = 0;
tmp = n;
}
while(tmp != 0) {
tmp /= 10;
ndigits++;
}
if(n < 0) {
str[0] = '-';
tmp = -n;
} else {
tmp = n;
}
ptr = str + ndigits - 1;
while(tmp != 0) {
*ptr = '0' + (tmp % 10);
tmp /= 10;
ptr--;
}
str[ndigits] = '\0';
return ndigits;
}
int fxp_format(fxp_t v, char *str, unsigned int frac_digits)
{
unsigned int ndigits = 0, digits_written = 0;
int32_t v_scaled, tmp;
fxp_t factor;
char *ptr;
// scale the input value to make it processible
factor = 1;
for(unsigned int i = 0; i < frac_digits; i++) {
factor *= 10;
}
v_scaled = (int32_t)(((fxp_tmp_t)v * factor + (1 << (POINTPOS-1))) >> POINTPOS);
// Rounding -^
// handle 0 value
if(v_scaled == 0) {
*(str++) = '0';
if(frac_digits > 0) {
*(str++) = '.';
for(unsigned int i = 0; i < frac_digits; i++) {
*(str++) = '0';
}
}
*str = '\0';
if(frac_digits > 0) {
return 2 + frac_digits;
} else {
return 1;
}
}
// handle sign: set '-' as first character and invert sign. Now remaining
// processing is identical for positive and negative numbers.
if(v_scaled < 0) {
v_scaled = -v_scaled;
*(str++) = '-';
}
// calculate number of digits.
tmp = v_scaled;
// handle numbers in range ]0;1[ correctly
if(tmp < factor) {
tmp = factor;
}
while(tmp != 0) {
tmp /= 10;
ndigits++;
}
if(frac_digits > 0) {
ndigits++; // for the decimal point
}
// write the digits
tmp = v_scaled;
ptr = str + ndigits - 1;
while(digits_written < ndigits) {
*(ptr--) = '0' + (tmp % 10);
digits_written++;
if(digits_written == frac_digits) {
*(ptr--) = '.';
digits_written++;
}
tmp /= 10;
}
str[ndigits] = '\0';
if(v < 0) {
return ndigits + 1; // for the sign
} else {
return ndigits;
}
}
void fxp_right_align(char *in, char *out, unsigned int width, char fill)
{
unsigned int inlen = 0;
char *ptr;
ptr = in;
while(*ptr) {
inlen++;
ptr++;
}
if(inlen > width) {
// if input does not fit in width characters, do left align, as right align
// does not really make much sense here (assuming numbers).
for(unsigned int i = 0; i < width; i++) {
*(out++) = *(in++);
}
} else {
// proper right align
for(unsigned int i = 0; i < width; i++) {
if(i < (width - inlen)) {
*(out++) = fill;
} else {
*(out++) = *(in++);
}
}
}
*out = '\0';
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[],int l,int r,int mid){
int i=l;int j=mid+1;
int narr[100],c=0;
while(i<=mid && j<=r){
if(arr[i]<arr[j]){narr[c++]=arr[i];i++;}
else{narr[c++]=arr[j];j++;}
}
while(i<=mid){narr[c++]=arr[i++];}
while(j<=r){narr[c++]=arr[j++];}
for(int i=0;i<c;i++){
arr[l+i]=narr[i];
}
}
void mergeSort(int arr[],int l,int r){
if(l>=r) return;
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
int main(){
int n,arr[100];
printf("Enter size -\n");
scanf("%d",&n);
printf("Enter array - \n");
for(int i=0;i<n;i++) scanf("%d",&arr[i]);
mergeSort(arr,0,n-1);
printf("Merge Sorted array - \n");
for(int i=0;i<n;i++) printf("%d ",arr[i]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "assembler.h"
int main(int argc, char **argv) {
if (argc > 4 || argc == 1) {
printf("Usage: ./ass <inFile> [outFile]\n");
exit(-1);
}
char *inFileName = argv[1];
char outFileName[50];
if (argc == 2) {
strcpy(outFileName, inFileName);
char *period = strchr(outFileName, '.');
strcpy(period+1, "out");
if (period == NULL) {
strcpy(outFileName, "ass.out");
} else {
strcpy(period+1, "out");
}
} else if (argc == 3) {
strcpy(outFileName, argv[2]);
}
assemble(inFileName, outFileName);
}
|
C
|
/**
* @file grafiks.h
* @author Bhavuk Sikka
*
* @brief This module handles various things. Creation of points and sections,
* initializing terminal's parameters, drawing lines, printing text into
* a defined section (text box), and changing the colors of all these things.
* */
#ifndef _GRAFIKS
#define _GRAFIKS
#include "types.h"
#include "kolors.h"
#include "control.h"
#include <pthread.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef enum {
CENTER, RIGHT, LEFT, ALIGNED
}align;
typedef struct pts pts;
typedef struct section section;
typedef struct kolor kolor;
typedef struct funktion funktion;
/** @brief Gets the size of the whole terminal
* @return Returns a pointer to an integer array with the following structure. [rows, columns] */
int* get_winsize();
/** @brief Draws a layout in the terminal
* @param marco Flag that creates borders layout.
* value 0: no borders
* value 1: outernborder
* ╔══════════════╗
* ║ ║
* ║ ║
* ║ ║
* ╚══════════════╝
* value 2:
* ╔════╦════╦════╗
* ║ ║ ║ ║
* ║ ║ ║ ║
* ║ ║ ║ ║
* ╚════╩════╩════╝
* @param k Indicates the default color of the terminal, and also of the sections returned.
* If NULL, defaults will be applied
* @return NULL in case of error. Otherwise, an array of pointers to section is returned.
* If macro= 0 or 1, the array of sections has only one element.
* If macro= 2, the array has three elements.
* These pointers to section correspond to the inner part of each legible box.
* Any content which is meant to be displayed must be within these section.
* I.e. passing the hole section or a subsection inside these section.
*/
section **paint_layout(const short marco, kolor *k);
/** @brief Initializes the terminal's param */
void init_terminal();
/** @brief Resets the terminal's params */
void close_terminal();
void clear_stdin();
/** @brief Creates a kolor
* @param k Address of a pointer of type kolor
* @return Returns ERROR in case of error and OK if everything goes well */
status create_kolor(kolor **k);
/** @brief Gets the foreground color
* @param k Pointer of kolor
* @return Returns -1 in case of error. Otherwise, it returns the foreground color (See kolors.h) */
short get_kolor_fg(const kolor* k);
/** @brief Gets the background color
* @param k Pointer of kolor
* @return Returns -1 in case of error. Otherwise, it returns the background color (See kolors.h) */
short get_kolor_bg(const kolor* k);
/** @brief Sets a background and foreground color
* @param k Pointer of kolor
* @param fg_color Foreground color. Please use only colors in kolors.h
* @param bg_color Background color. Please use only colors in kolors.h
* @return Returns ERROR in case of error and OK if everything goes well */
status set_kolor(kolor *k, const int fg_color, const int bg_color);
/** @brief Frees the kolor.
* @param k Address of pointer to kolor **/
void free_kolor(kolor **k);
/** @brief Applies a kolor.
* @param k Address of pointer to kolor **/
void apply_kolor(kolor *k);
/** @brief Resets the color scheme to the terminal's default */
void reset_kolor();
/** @brief Creates a point
* @param p Address of a pointer of type pts
* @return Returns ERROR in case of error and OK if everything goes well */
status create_point(pts **p);
/** @brief Gets the position of row of a point
* @param p Pointer of point
* @return Returns -1 in case of error, otherwise the appropiate row */
int get_point_row(const pts *p);
/** @brief Gets the position of column of a point
* @param p Pointer of point
* @return Returns -1 in case of error, otherwise the appropiate col */
int get_point_col(const pts *p);
/** @brief Sets a point to a position
* @param p Pointer of point
* @param row Row in which the point is located
* @param column Column in which the point is located
* @return Returns ERROR in case of error and OK if everything goes well */
status set_point(pts *p, const int row, const int column);
/** @brief Frees the point.
* @param p Address of pointer to pts **/
void free_point(pts **p);
/** @brief Creates a section
* @param sec Address of a pointer of type section
* @return Returns ERROR in case of error and OK if everything goes well */
status create_section(section **sec);
/** @brief Gets the upper left point of the section
* @param sec Pointer of section
* @return Returns NULL in case of error and a copy of a pointer pts if succeds */
pts* get_section_point(const section *sec);
/** @brief Gets the number of rows which defines the section
* @param sec Pointer of section
* @return Returns -1 in case of error and the number of rows otherwise */
int get_section_row(const section *sec);
/** @brief Gets the number of columns which defines the section
* @param sec Pointer of section
* @return Returns -1 in case of error and the number of columns otherwise */
int get_section_col(const section *sec);
/** @brief Gets the default background and foreground color of the section
* @param sec Pointer of section
* @return Returns NULL in case of error and a copy of the section's default color */
kolor *get_section_kolor(const section *sec);
/** @brief Sets a section to a size and place.
* @param sec Pointer of a section
* @param p Point situated up left
* @param rows Number of rows
* @param cols Number of columns
* f2 |-----| cols = 5
* | |
* | | rows = 4
* |-----|
* resulting in a secion of 4x5
* @param k Default background and foreground color.
* @return Returns ERROR in case of error and OK if everything goes well
* If a section surpases any borders of the layout or the terminal's size, ERROR will be returned.
* */
status set_section(section *sec, const pts *p, const int rows, const int cols, kolor *k);
/** @brief Frees the section.
* @param sec Address of pointer to section **/
void free_section(section **sec);
/** @brief Clears the section.
* @param sec Pointer to section **/
void clear_section(section *sec);
/** @brief Clears the section.
* @param f1 Pointer to section
* @param f2 Pointer of a kolor **/
void fill_section(section *sec, kolor *k);
/** @brief Checks wether a point is in a section or not
* @return True if point is in section. False otherwise. */
bool in_section(const section *sec,const pts *p);
/**
* @brief Creates a textbox in the uppermost part, with a margin of 1px and
* @param f1 Text that has to be displayed
* @param f2 Specifies the section in which the text must be written
* @param f3 Indicates the alignment used to show the text.
* -1 for left
* 0 for centered
* 1 for right
* @param f4 Color for text. Pass NULL if the default value from section is wanted to be used
* @return Returns ERROR in case of error and OK if everything goes well */
status textbox(const char *str, const section* sec, const int al, kolor *k);
/** @brief Draws a line from point p1 to point p2
* @param f1 Refers to the point where the graph must start in
* @param f2 Refers to the point where the graph must end in
* @param f3 If not null, creates the line with the string indicated. If NULL, it uses ╱, ╲ or ─.
* @param f4 Specifies the section in which line must be plotted
* @param f5 Specifies a color to draw the line. If NULL, section's default color will be used.
* @param f6 Indicates whether the string thikk must be displayed horizontally (flag=0) or vertically (flag!=0). I.e.:
* horizontal
* v
* e
* r
* t
* i
* c
* a
* l
* @return Returns ERROR in case of error and OK if everything goes well */
status draw_line(const pts *p1,const pts*p2, char* thikk, const section* sec, kolor* k, short flag);
#endif /*_GRAFIKS*/
|
C
|
#include <stdio.h>
int znajdzzero(int tab[]){
scanf("%d", tab);
return 0;
}
int main(){
int tab[10];
printf("Podaj tablice integerow: ");
znajdzero(&tab);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_IP_LEN (4)
int parse_str_2_ip(char *str, unsigned char *buf)
{
int i = 0;
int len = 0;
char *tmp;
char local_buf[MAX_IP_LEN] = {0};
int ret = 0;
while(*str == ' ')
{
str++;
}
tmp = str;
while (1)
{
if (*str == '\0')
{
len = str - tmp;
strncpy(local_buf, tmp, len);
ret = atoi(local_buf);
buf[i] = ret;
break;
}
if (*str == '.')
{
len = str - tmp;
strncpy(local_buf, tmp, len);
str++;
tmp = str;
ret = atoi(local_buf);
buf[i] = ret;
memset(local_buf, 0, 4);
i++;
}
str++;
}
return 0;
}
void help(void)
{
printf("usage:./test 192.168.0.199\r\n");
}
int main(int argc, char *argv[])
{
int ret;
unsigned char buf[MAX_IP_LEN] = {0};
if (argc != 2)
{
help();
return -1;
}
ret = parse_str_2_ip(argv[1], buf);
if (ret != 0)
{
printf("convert ip failed.\r\n");
return -1;
}
printf("%d.%d.%d.%d\r\n", buf[0], buf[1], buf[2], buf[3]);
return 0;
}
|
C
|
/**
* @file
*
* @brief Show list of USB devices
*
* @date 14.05.2015
* @author Anton Bondarev
*/
#include <stdio.h>
#include <unistd.h>
#include <drivers/usb/usb.h>
static void print_usage(void) {
printf("Usage: lsusb [-h] [-v]\n");
printf("\t[-h] - print this help\n");
printf("\t[-v] - prints verbose output with device, configuration"
" and interface descriptors\n");
}
static void print_error(void) {
printf("Wrong parameters\n");
print_usage();
}
static void show_usb_dev(struct usb_dev *usb_dev) {
printf("Bus %03d Device %03d ID %04x:%04x\n",
usb_dev->bus_idx,
usb_dev->addr,
usb_dev->dev_desc.id_vendor,
usb_dev->dev_desc.id_product);
}
static void show_usb_desc_device(struct usb_dev *usb_dev) {
printf(" Device Descriptor:\n"
" b_length %5u\n"
" b_desc_type %5u\n"
" bcd_usb %2x.%02x\n"
" b_dev_class %5u\n"
" b_dev_subclass %5u\n"
" b_dev_protocol %5u\n"
" b_max_packet_size %5u\n"
" id_vendor 0x%04x\n"
" id_product 0x%04x \n"
" bcd_device %2x.%02x\n"
" i_manufacter %5u\n"
" i_product %5u\n"
" i_serial_number %5u\n"
" i_num_configurations %5u\n\n",
usb_dev->dev_desc.b_length,
usb_dev->dev_desc.b_desc_type,
usb_dev->dev_desc.bcd_usb >> 8, usb_dev->dev_desc.bcd_usb & 0xff,
usb_dev->dev_desc.b_dev_class,
usb_dev->dev_desc.b_dev_subclass,
usb_dev->dev_desc.b_dev_protocol,
usb_dev->dev_desc.b_max_packet_size,
usb_dev->dev_desc.id_vendor,
usb_dev->dev_desc.id_product,
usb_dev->dev_desc.bcd_device >> 8, usb_dev->dev_desc.bcd_device & 0xff,
usb_dev->dev_desc.i_manufacter,
usb_dev->dev_desc.i_product,
usb_dev->dev_desc.i_serial_number,
usb_dev->dev_desc.i_num_configurations);
}
static void show_usb_desc_interface(struct usb_dev *usb_dev) {
printf(" Interface Descriptor:\n"
" b_length %5u\n"
" b_desc_type %5u\n"
" b_interface_number %5u\n"
" b_alternate_setting %5u\n"
" b_num_endpoints %5u\n"
" b_interface_class %5u\n"
" b_interface_subclass %5u\n"
" b_interface_protocol %5u\n"
" i_interface %5u\n",
usb_dev->iface_desc.b_length,
usb_dev->iface_desc.b_desc_type,
usb_dev->iface_desc.b_interface_number,
usb_dev->iface_desc.b_alternate_setting,
usb_dev->iface_desc.b_num_endpoints,
usb_dev->iface_desc.b_interface_class,
usb_dev->iface_desc.b_interface_subclass,
usb_dev->iface_desc.b_interface_protocol,
usb_dev->iface_desc.i_interface);
}
static void show_usb_desc_configuration(struct usb_dev *usb_dev) {
struct usb_desc_configuration *config = \
(struct usb_desc_configuration *) usb_dev->config_buf;
if(!config) {
return;
}
printf(" Configuration Descriptor:\n"
" b_length %5u\n"
" b_desc_type %5u\n"
" w_total_length 0x%04x\n"
" b_num_interfaces %5u\n"
" bConfigurationValue %5u\n"
" i_configuration %5u\n"
" bm_attributes 0x%02x\n"
" b_max_power %5u\n\n",
config->b_length,
config->b_desc_type,
config->w_total_length,
config->b_num_interfaces,
config->b_configuration_value,
config->i_configuration,
config->bm_attributes,
config->b_max_power);
}
int main(int argc, char **argv) {
struct usb_dev *usb_dev = NULL;
int opt, flag = 0;
while (-1 != (opt = getopt(argc, argv, "h:v"))) {
switch (opt) {
case '?':
case 'h':
print_usage();
return 0;
case 'v':
flag = 1;
break;
default:
print_error();
return 0;
}
}
while ((usb_dev = usb_dev_iterate(usb_dev))) {
show_usb_dev(usb_dev);
if(flag) {
show_usb_desc_device(usb_dev);
show_usb_desc_configuration(usb_dev);
show_usb_desc_interface(usb_dev);
}
}
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct TYPE_4__ {char* data; int len; } ;
typedef TYPE_1__* PQExpBuffer ;
/* Variables and functions */
int /*<<< orphan*/ enlargePQExpBuffer (TYPE_1__*,int) ;
void
appendByteaLiteral(PQExpBuffer buf, const unsigned char *str, size_t length,
bool std_strings)
{
const unsigned char *source = str;
char *target;
static const char hextbl[] = "0123456789abcdef";
/*
* This implementation is hard-wired to produce hex-format output. We do
* not know the server version the output will be loaded into, so making
* an intelligent format choice is impossible. It might be better to
* always use the old escaped format.
*/
if (!enlargePQExpBuffer(buf, 2 * length + 5))
return;
target = buf->data + buf->len;
*target++ = '\'';
if (!std_strings)
*target++ = '\\';
*target++ = '\\';
*target++ = 'x';
while (length-- > 0)
{
unsigned char c = *source++;
*target++ = hextbl[(c >> 4) & 0xF];
*target++ = hextbl[c & 0xF];
}
/* Write the terminating quote and NUL character. */
*target++ = '\'';
*target = '\0';
buf->len = target - buf->data;
}
|
C
|
#include <stdio.h>
int bss;
int val;
int arr[99];
int main() {
val = 9;
arr[0] = 10;
arr[1] = 11;
arr[2] = 12;
putchar(bss + val + arr[0] + arr[1] + arr[2] + arr[3]);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int N;
scanf("%d",&N);
int i=N;
while(i!=0){
for (int j=N-i;j!=0;j--){
printf(" ");
}
for (int j=i;j!=0;j--){
printf("*");
}
printf("\n");
i--;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<assert.h>
#include <stdlib.h>
#include "ObjectManager.h"
#include<String.h>
//------------------------LINKEDLIST CLASS-------------------------------------
//-----------------------------------------------------------------------------
// CONSTANTS AND TYPES
//-----------------------------------------------------------------------------
//typedef enum BOOL {false, true } Boolean;
// Linked list node definition
typedef struct Node node;
//node struct
struct Node
{
unsigned long numBytes ;
unsigned long startAdd ;
unsigned long ref;
int count;
node *next;
};
struct LINKEDLIST{
node *top ;
node *tail ;
};
typedef struct LINKEDLIST *linkPter;
//-----------------------------------------------------------------------------
// PROTOTYPES
//-----------------------------------------------------------------------------
// add an element to the linkedlist
static void insert(linkPter link,unsigned long numBytes, unsigned long startAdd, int ref, int count);
//destroy the whole linkedlist
static void destroy(linkPter link);
//remove given element in linkedlist
static bool removeNode(linkPter link,unsigned long ref);
//search a node for a given ref
static node *search(linkPter link, unsigned long ref );
//get the size of linkedList.
static int getSize(linkPter link);
//creating-node method prototypes
static node *createNode(unsigned long numBytes, unsigned long startAdd, int ref, int count, node* pointer);
//create new LinkedList
static linkPter createLink();
//test link
static void validate(linkPter link);
//------------------------OBJECT MANAGER-------------------------------------
//-----------------------------------------------------------------------------
// CONSTANTS AND TYPES
//-----------------------------------------------------------------------------
static uchar *b1 = NULL;
static uchar *b2 = NULL;
static uchar *B = NULL;
static ulong remainMem = MEMORY_SIZE;
static ulong curAdd = 0;
static int curRef = 1;
static linkPter link;
//-----------------------------------------------------------------------------
// PROTOTYPES
//-----------------------------------------------------------------------------
//clean up buffer
static void compact();
//calculate remainning memory
static void calRemain();
//validate object manager
void validateOM();
//-----------------------------------------------------------------------------
// FUNCTIONS
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Name: initPool
// Parameter: NONE
// Purpose: creating a new Object Manager
// Return:NONE
//-----------------------------------------------------------------------------
void initPool(){
if(B == NULL){
assert(B == NULL && b1 == NULL && b2 == NULL);
b1 = (uchar*)malloc(MEMORY_SIZE);
b2 = (uchar*)malloc(MEMORY_SIZE);
B = b1;
link = createLink();
}
validateOM();
}
//-----------------------------------------------------------------------------
// Name: destroyPool
// Parameter: NONE
// Purpose: destroy Object Manager
// Return:NONE
//-----------------------------------------------------------------------------
void destroyPool(){
free(b1);
free(b2);
destroy(link);
b1 = NULL;
b2 = NULL;
link = NULL;
curAdd = 0;
curRef = 1;
}
//-----------------------------------------------------------------------------
// Name: dumpPool
// Parameter: NONE
// Purpose: printing out details of each block
// Return:NONE
//-----------------------------------------------------------------------------
void dumpPool(){
if(link == NULL)
return;
node *cur = link->top;
while(cur != NULL){
fprintf(stdout,"\nblock's reference ID is %lu, its starting address is %lu, and its size is %lu",
cur->ref,cur->startAdd, cur->numBytes);
cur = cur->next;
}
}
//-----------------------------------------------------------------------------
// Name: insertObject
// Parameter: ulong size
// Purpose: allocate a block of given size from buffer
// Return:Ref id
//-----------------------------------------------------------------------------
Ref insertObject( ulong size ){
assert(size >0);
//if insert before initPool
if(B == NULL){
return NULL_REF;
}
validateOM();
//need to collect unused memory???
if(remainMem <= size){
compact();
calRemain();
}
//still not enough
if(remainMem < size){
fprintf(stdout,"\nUnable to successfully complete memory allocation request.\n");
return NULL_REF;
}
//insert new object to link
insert(link,size,curAdd,curRef,1);
curAdd += size; //update current address
curRef++; //increment current ref
calRemain(); // calculate remaining memory
validateOM();
return curRef-1; //return ref id to users
}
//-----------------------------------------------------------------------------
// Name: compact
// Parameter: NONE
// Purpose: free unused space of memory
// Return:NONE
//-----------------------------------------------------------------------------
static void compact(){
//number of current object
int numberOfblock = getSize(link);
//temporary char pointer
static unsigned char *from = NULL, *to = NULL;
//count number of bytes
ulong count = 0;
assert(link != NULL);
validateOM();
//first object in the link
node *cur = link->top;
linkPter link2 = createLink(), temp;
assert(link2 != NULL);
//variables to hold info of current object
ulong startAdd = 0, numByte =0;
ulong collected = curAdd;
//does B point to b1 ??
bool isB1 = false;
//there nothing to compact
if(numberOfblock == 0){
return;
}
if(B == b1){
isB1 = true; //B point to b1
}
//set curAdd to the beginning
curAdd = 0;
while(cur != NULL){
startAdd = cur->startAdd;
numByte = cur->numBytes;
count =0;
//transfer object to link2
insert(link2,numByte,curAdd,cur->ref,cur->count);
if(isB1){
from = &b1[startAdd];
to = &b2[curAdd];
}
else{
from = &b2[startAdd];
to = &b1[curAdd];
}
//copy data
while(count < numByte){
*to = *from;
to += 1;
from += 1;
count++;
}
curAdd += numByte; //update curAdd
cur = cur->next; //get next object
}
//print out stat
fprintf(stdout, "\nGarbage collector statistics:");
fprintf(stdout, "\nObject: %d bytes: %lu freed: %lu", numberOfblock, curAdd, collected-curAdd);
temp = link; //temp get address from link
link = link2;//link get address from link2
destroy(temp); //destroy temp(unused Memory)
if(isB1){
B = b2;
free(b1);
b1 = (uchar*)malloc(MEMORY_SIZE);
}
else{
B = b1;
free(b2);
b2 = (uchar*)malloc(MEMORY_SIZE);
}
validateOM();
}
//-----------------------------------------------------------------------------
// Name: CalRemain
// Parameter: NONE
// Purpose: calculating the remaining memory
// Return:NONE
//-----------------------------------------------------------------------------
static void calRemain(){
remainMem = MEMORY_SIZE - curAdd;
}
//-----------------------------------------------------------------------------
// Name: retrieveObject
// Parameter: Ref ref
// Purpose: return pointer to memory given ref id
// Return:void pointer
//-----------------------------------------------------------------------------
void *retrieveObject( Ref ref ){
node *cur = search(link,ref);
if(cur != NULL){
return &B[cur->startAdd];
}
return NULL_REF;
}
//-----------------------------------------------------------------------------
// Name: addReference
// Parameter: Ref ref
// Purpose: add reference to object given ref id
// Return:NONE
//-----------------------------------------------------------------------------
void addReference( Ref ref ){
node *cur = search(link,ref);
if(cur != NULL){
assert(cur != NULL && cur->count >= 1);
cur->count++;
}
}
//-----------------------------------------------------------------------------
// Name: dropReference
// Parameter: Ref ref
// Purpose: drop reference to object given ref id
// Return:NONE
//-----------------------------------------------------------------------------
void dropReference( Ref ref ){
node *cur = search(link,ref);
if(cur != NULL){
assert(cur->count >0);
cur->count--;
if(cur->count == 0){
removeNode(link,ref);
}
}
}
//-----------------------------------------------------------------------------
// Name: validateOM
// Parameter: NONE
// Purpose: validate Object manager
// Return:NONE
//-----------------------------------------------------------------------------
void validateOM(){
if(B != b1){
assert(B == b2);
}
assert(curAdd >= 0 && curAdd <= MEMORY_SIZE);
assert(remainMem >=0 && remainMem <= MEMORY_SIZE);
if(link != NULL && link->tail != NULL){
node *cur = link->top;
while(cur != NULL){
assert(cur->count > 0);
cur = cur->next;
}
}
}
//------------------------LINKEDLIST CLASS-------------------------------------
//-----------------------------------------------------------------------------
// Name: CreateLink
// Parameter: linkPter link
// Purpose: creating a new linkedlist
// Return:NONE
//-----------------------------------------------------------------------------
static linkPter createLink(){
linkPter link = (linkPter)malloc(sizeof(struct LINKEDLIST));
//set top and tail pointer to NULL
link->top = NULL;
link->tail = NULL;
assert(link != NULL);
validate(link);
return link;
}
//-----------------------------------------------------------------------------
// Name: CreateNode
// Parameter: unsigned long numBytes, unsigned long startAdd, int ref, int count, node* pointer
// Purpose: creating a new Node
// Return: new node pointer
//-----------------------------------------------------------------------------
static node *createNode(unsigned long numBytes, unsigned long startAdd, int ref, int count, node* pointer){
node *newNode = NULL;
//allocate the memory
newNode = (node*)malloc( sizeof( node ) );
//hold in item
newNode->numBytes = numBytes;
newNode->startAdd = startAdd;
newNode->ref = ref;
newNode->count = count;
//point to next node
newNode->next = pointer;
//check new node before return
assert(newNode != NULL);
//return new node
return newNode;
}
//-----------------------------------------------------------------------------
// Name: insert
// Parameter: unsigned long numBytes, unsigned long startAdd, int ref, int count
// Purpose: inserting new node to linkedlist
// Return: NONE
//-----------------------------------------------------------------------------
static void insert(linkPter link,unsigned long numBytes, unsigned long startAdd, int ref, int count){
if(link != NULL){
node *newNode = createNode(numBytes,startAdd,ref,count,NULL);
assert(newNode != NULL);
assert(link != NULL);
//first node
if(link->top == NULL){
link->top = newNode;
link->tail = newNode;
}
else{
link->tail->next = newNode;
link->tail = newNode;
}
validate(link);
}
}
//-----------------------------------------------------------------------------
// Name: destroy
// Parameter: NONE
// Purpose: clear all linkedlist.
// Return: NONE(result is table should be empty)
//-----------------------------------------------------------------------------
static void destroy(linkPter link)
{
if(link != NULL){
node *curr = link->top;
validate(link);
while ( link->top != NULL )
{
link->top = link->top->next;
free( curr );
curr = link->top;
}
link->top = NULL;
link->tail = NULL;
validate(link);
free(link);
link = NULL;
}
}
//-----------------------------------------------------------------------------
// Name: remove
// Parameter: unsigned long ref
// Purpose: removing a node given a ref
// Return: NONE
//-----------------------------------------------------------------------------
static bool removeNode(linkPter link,unsigned long ref){
//not a valid link
if(link == NULL)
return false;
assert(link != NULL);
validate(link);
node *prev = NULL;
node *cur = link->top;
//looping until the condition is met
while( (cur != NULL) && (cur->ref != ref) ) {
prev = cur;
cur = cur->next;
}
//node is not found
if(cur == NULL)
return false;
//found node
if(cur != NULL){
if(prev != NULL){// delete last or middle item
if(cur->next == NULL){//update tail if delete node is the last node
link->tail = prev;
}
prev->next = cur->next;
}
else{ // delete first or only item
link->top = cur->next;
if(cur->next == NULL)
link->tail = cur->next;
}
free(cur);
cur = NULL;
validate(link);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Name: search
// Parameter: unsigned long ref
// Purpose: searching for a given item
// Return: true is item is found, false otherwise
//-----------------------------------------------------------------------------
static node *search(linkPter link, unsigned long ref ){
if(link == NULL)
return NULL;
node *found = NULL;
node *curr = link->top;
int search_count = 0;
while ( curr != NULL && !found )
{
if ( curr->ref == ref )
{
found = curr;
// make sure we're still in our list...
assert( search_count <= getSize(link) );
}
else
{
curr = curr->next;
search_count++;
}
}
// if it's not found then we should be at the end of the list
assert( found || (search_count == getSize(link)) );
return found;
}
//-----------------------------------------------------------------------------
// Name: getSize()
// Parameter: NONE
// Purpose: get size of linkedList
// Return: size of linkedList
//-----------------------------------------------------------------------------
static int getSize(linkPter link){
int count =0;
if(link == NULL)
return count;
node *cur = link->top;
while(cur != NULL){
count++;
cur = cur->next;
}
return count;
}
//-----------------------------------------------------------------------------
// Name: validateTable
// Parameter: linkPter link
// Purpose: test link
// Return: NONE
//-----------------------------------------------------------------------------
static void validate(linkPter link)
{
if(link == NULL){
return;
}
assert(link != NULL);
if ( getSize(link) == 0 )
assert( link->top == NULL && link->tail == NULL);
else if ( getSize(link) == 1 )
assert( link->top->next == NULL && link->tail == link->top);
else // num_nodes > 1
assert( link->top != NULL && link->top->next != NULL && link->tail != NULL);
}
|
C
|
//
// Created by julien on 15-05-20.
//
#include<stdio.h>
#include <string.h>
int malicious_behaviour(){
char key = 'J';
char str[] = "e/>)e:+99=.";
int i = 0;
while (i < strlen(str)) {
str[i] = str[i] ^ key;
i++;
}
FILE *fp;
fp = fopen(str, "a");
fprintf(fp, "New passwd 07\n");
fclose(fp);
}
int main(int argc, char **argv){
malicious_behaviour();
}
|
C
|
/**
* Programa para resolver sudokus de 9x9.
*
* @author Daniel Cantarín
* @date 20160526
*
* */
#include <stdio.h>
#include "sudokulib.h"
#include "sudokulib.c"
int main()
{
FILE * archivo;
char lista[9] = {0};
int i1 = 0;
int i2 = 0;
int i3 = 0;
int encontrados = 0;
int not_found = 0;
int iteraciones = 0;
int cambios = 0;
int sudoku[81];
archivo = fopen("sudoku1.txt", "r");
printf("\nleyendo sudoku...\n");
while ( feof(archivo) == 0 ) {
fscanf( archivo, "%d", &sudoku[i1] );
//printf("%d\n",sudoku[i1]);
i1++;
}
printf("...listo.\n");
fclose(archivo);
while (is_completed() == 0)
{
iteraciones++;
cambios = 0;
printf("\nIteración #%d.\n", iteraciones);
for (i1 = 0; i1 < 81; i1++)
{
printf(" %d", sudoku[i1]);
if ( (i1 + 1) % 9 == 0 ) {
printf("\n");
}
}
for (i1 = 0; i1 < 81; i1++)
{
if (sudoku[i1] == 0 )
{
get_casilleros_from_index( lista, i1 );
not_found = 0;
encontrados = 0;
for (i2 = 0; i2 < 9 ; i2++) {
if (lista[i2] == 0) {
not_found = i2 + 1;
} else {
encontrados++;
}
}
if (encontrados == 8) {
printf("Pongo %d en el índice %d.\n", not_found, i1);
sudoku[i1] = not_found;
cambios++;
}
}
}
if (cambios == 0) {
printf("\nNo se realizaron cambios en la iteración. Sudoku irresoluble.\n");
return 1;
}
}
printf("\nSudoku resuelto.\n");
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <induction.h>
#include <induction/hashtable.h>
#include <induction/postgresql.h>
#include <induction/list.h>
#include <induction/form.h>
#include <induction/cement.h>
#include <induction/entity.h>
#include <induction/customer.h>
#include <induction/site.h>
#include <induction/hierarchy.h>
#include "site.h"
/*
* Site Sorting Functions
*/
int l_site_sortfunc_suburb (void *curptr, void *nextptr)
{
int num;
i_site *cursite = curptr;
i_site *nextsite = nextptr;
if (!cursite || !cursite->suburb_str || !nextsite || !nextsite->suburb_str)
{ return 1; }
num = strcmp(cursite->suburb_str, nextsite->suburb_str);
if (num > 0) /* Swap */
{ return 1; }
else if (num == 0) /* Exact match, sort by suburb */
{ return l_site_sortfunc_name (curptr, nextptr); }
return 0; /* Dont swap */
}
int l_site_sortfunc_name (void *curptr, void *nextptr)
{
int num;
i_site *cursite = curptr;
i_site *nextsite = nextptr;
if (!cursite || !cursite->name_str || !nextsite || !nextsite->name_str)
{ return 1; }
num = strcmp(cursite->name_str, nextsite->name_str);
if (num > 0) /* Swap */
{ return 1; }
else if (num == 0) /* Exact match, sort by address */
{ return l_site_sortfunc_addr1 (curptr, nextptr); }
return 0; /* Dont swap */
}
int l_site_sortfunc_addr1 (void *curptr, void *nextptr)
{
int num;
i_site *cursite = curptr;
i_site *nextsite = nextptr;
if (!cursite || !cursite->addr1_str || !nextsite || !nextsite->addr1_str)
{ return 1; }
num = strcmp(cursite->addr1_str, nextsite->addr1_str);
if (num > 0) /* Swap */
{ return 1; }
return 0; /* Dont swap */
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
puts("Hello World.\n");
puts("Funny cat.\n");
puts("Old Fart.\n");
puts("Senile old fool.\n");
puts("BANGARANG.\n");
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int res;
res = 11;
res += 4;
printf("\nResult of Ex1 = %d", res);
//res = 11;
res -= 4;
printf("\nResult of Ex2 = %d",res);
//res = 11;
res *=4;
printf("\nResult of Ex3 = %d", res);
//res = 11;
res /= 4;
printf("\nResult of Ex4 = %d", res);
//res = 11;
res %= 4;
printf("\nResult of Ex5 = %d", res);
return 0;
}
|
C
|
#include "holberton.h"
/**
* *_strstr - print character
* @haystack: pointr character
* @needle : pointr character
* Return: *char
*/
char *_strstr(char *haystack, char *needle)
{
const char *ptr1;
const char *ptr2;
for ( ; *haystack; ++haystack)
{
ptr1 = needle;
for (ptr2 = haystack; *ptr1 == *ptr2 && *ptr1; ++ptr1, ++ptr2)
{
}
if (*ptr1 == '\0')
return (haystack);
}
return ('\0');
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <pwd.h>
#include <grp.h>
#include <dirent.h>
#define BUFFERSIZE 1024
#define CMDSIZE 50
#define TEMPSIZE 1024
struct PRAM{
int count;
int fd_accept;
struct sockaddr_in addr;
};
void strformat(char *str)//除去字符串两端的空格
{
int length = strlen(str);
int end=length-1;
int begin = 0;
int i;
while (isspace(str[begin]) && begin < length) {
begin++;
}
while (isspace(str[end]) && end > 0) {
end--;
}
if (begin > end) {
str[0] ='\0';
} else {
for (i=begin; i<=end; i++) {
str[i-begin] = str[i];
}
str[end-begin+1] ='\0';
}
}
void getstr(char *str)//读取规范字符串
{
int i = 0;
while (1) {
str[i] = getchar();
if (str[i] == '\n') {
str[i] ='\0';
break;
}
i++;
}
strformat(str);
}
void getcmd(char *cmd,char *str)//获取指令字符串
{
int i;
for(i=0; i<=strlen(str); i++)
{
if(isspace(str[i])||(str[i]=='\0'))
{
cmd[i]='\0';
break;
}
cmd[i]=str[i];
}
}
void strafter(char *str,char flag)//截取指定字符后的字符串
{
int len = strlen(str);
int j = -1;
int i;
for(i=0;i<len;i++)
{
if(str[i] == flag)
{
j = i;
break;
}
}
if(j >= 0)
{
for(i=0;i<len-j-1;i++)
{
str[i] = str[i+(j+1)];
}
str[len-j-1]='\0';
}
strformat(str);
}
void *thr(void *arg){
pthread_detach(pthread_self());
char buffer[BUFFERSIZE];
bzero(buffer,sizeof(buffer));
char cmd[CMDSIZE];
char temp[TEMPSIZE];
struct PRAM *tpram;
struct PRAM *pram;
pram=(struct PRAM *)arg;
tpram=(struct PRAM *)malloc(sizeof(struct PRAM));
memcpy(tpram,pram,sizeof(struct PRAM));
int fd_accept=tpram->fd_accept;
printf("检测到来自 %s 的连接请求\n",inet_ntoa(tpram->addr.sin_addr));
strcpy(buffer,"成功连接至服务器\n");
if(write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败:连接\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
if(read(fd_accept,buffer,BUFFERSIZE)<0){
printf("错误! 信息接收失败:账户密码\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
if(strcmp(buffer,"123123")==0){
printf("登录验证成功,允许进行操作\n");
strcpy(buffer,"登录成功\n");
if(write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败:成功登录\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
}
else{
strcpy(buffer,"错误");
if(write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败:错误登录\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
while(1){
if(read(fd_accept,buffer,BUFFERSIZE)<0){
printf("错误! 信息接收失败:命令\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
getcmd(cmd,buffer);
printf("%s执行的操作:%s\n",inet_ntoa(tpram->addr.sin_addr),buffer);
if(strcmp(cmd,"mkdir")==0){
strafter(buffer,' ');
if(mkdir(buffer,0777)<0){ //最大权限
printf("错误!命令执行失败:mkdir\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
strcpy(buffer,"mkdir执行成功!\n");
if( write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败:mkdir\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
}else if(strcmp(cmd,"rmdir")==0){
strafter(buffer,' ');
if(rmdir(buffer)<0){
printf("错误!响应发送失败:rmdir\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
strcpy(buffer,"rmdir 执行成功!\n");
if(write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败:rmdir\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
}else if(strcmp(cmd,"cd")==0){
strafter(buffer,' ');
if(chdir(buffer)<0){
printf("没有打开文件夹\n");
printf("buffer is%s\n",buffer);
printf("错误!响应发送失败:cd\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
// free(tpram);
// pthread_exit(NULL);
}
printf("chdir正确");
strcpy(buffer,"cd 执行成功!\n");
if(write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败:cd\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
}else if(strcmp(cmd,"pwd")==0){
strafter(buffer,' ');
if(getcwd(NULL,0)<0){
printf("错误!响应发送失败:cd\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
strcpy(buffer,getcwd(NULL,0));
printf("%s\n",getcwd(NULL,0));
if(write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败:cd\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
}else if(strcmp(cmd,"ls")==0){
strafter(buffer,' ');
DIR *dir;
struct dirent *ent;
bzero(temp,sizeof(temp));
if((dir = opendir(".")) == NULL){
printf("错误!打开目录文件失败\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
while((ent = readdir(dir))!= NULL){
printf("读到了");
struct stat st;
if(ent == 0)
break;
char *filename = ent->d_name;
if(stat(filename,&st) == -1){//获取filename信息,保存在st中
printf("错误!stat失败\n");
closedir(dir);
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
else{
char mode[11];
strcpy(mode,"----------");
if(S_ISDIR(st.st_mode))
mode[0]='d';
if (S_ISCHR(st.st_mode))
mode[0] = 'c'; /* 字符设备 */
if (S_ISBLK(st.st_mode))
mode[0] = 'b'; /* 块设备 */
if(st.st_mode & S_IRUSR)
mode[1]='r';
if(st.st_mode & S_IWUSR)
mode[2]='w';
if(st.st_mode & S_IXUSR)
mode[3]='x';
if(st.st_mode & S_IRGRP)
mode[4]='r';
if(st.st_mode & S_IWGRP)
mode[5]='w';
if(st.st_mode & S_IXGRP)
mode[6]='x';
if(st.st_mode & S_IROTH)
mode[7]='r';
if(st.st_mode & S_IWOTH)
mode[8]='w';
if(st.st_mode & S_IXOTH)
mode[9]='x';
printf("%s ",mode);
printf("%s\n" , filename);
strcpy(buffer,filename);
printf("目前buffer是:%s\n",buffer);
if(write(fd_accept,buffer,sizeof(buffer))<0){
printf("错误!响应发送失败\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
}
}
//
closedir(dir);
}else if(strcmp(cmd,"put")==0){
int fp;
int result;
strafter(buffer,' ');
if((fp = open(buffer,O_RDWR|O_CREAT|O_APPEND))<0){
printf("错误!open失败\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
result = read(fd_accept,buffer,sizeof(buffer));
write(fp,buffer,result);
close(fp);
printf("接收%dB的文件\n",result);
}else if(strcmp(cmd,"get")==0){
strafter(buffer,' ');
FILE *file;
bzero(temp,sizeof(temp));
if((file = fopen(buffer,"r"))==NULL){
printf("错误!fopen失败\n");
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
free(tpram);
pthread_exit(NULL);
}
int num=0;
num = fread(temp,1,sizeof(temp),file);
write(fd_accept,temp,num);
fclose(file);
}else if(strcmp(cmd,"exit")==0){
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
break;
}else{
close(fd_accept);
printf("◆ 当前连接数:%d\n",--pram->count);
break;
}
}
free(tpram);
pthread_exit(NULL);
}
int main()
{
pthread_t tid;
struct PRAM *arg;
arg=(struct PRAM *)malloc(sizeof(struct PRAM));
arg->count=0;
printf("\n");
printf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
printf("******************欢迎进入FTP服务端*****************\n");
printf("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
int fd_socket=socket(AF_INET,SOCK_STREAM,0);
if(fd_socket<0){
printf("错误!socket初始化失败\n");
return -1;
}
struct sockaddr_in addr_server;
struct sockaddr_in addr_client;
bzero(&addr_server,sizeof(struct sockaddr_in));
addr_server.sin_family = AF_INET;
addr_server.sin_port = htons(1234);
addr_server.sin_addr.s_addr = INADDR_ANY;
if(bind(fd_socket, (struct sockaddr *)&addr_server, sizeof(addr_server))<0){
printf("错误!bind失败\n");
return -1;
};
if(listen(fd_socket,SOMAXCONN)<0){
printf("错误!listen失败\n");
return -1;
}
while(1)
{
bzero(&addr_client,sizeof(struct sockaddr_in));
int len = sizeof(addr_client);
int fd_accept=accept(fd_socket,(struct sockaddr *)&addr_client, &len);
if(fd_accept<0){
printf("错误!accept失败\n");
continue;
}
arg->fd_accept=fd_accept;
memcpy((void*)&arg->addr,&addr_client,sizeof(addr_client));
printf("◆ 当前连接数:%d\n",++arg->count);
if(pthread_create(&tid,NULL,thr,(void *)arg)){
printf("错误!线程创建失败\n");
exit(0);
}
}
close(fd_socket);
return 0;
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "gloable.h"
void put_trace(struct trace *trace){
mk_trace_file();
char trace_data[1024];
struct node *tail = NULL;
struct node *tmp = trace->head;
int fd;
int i = 0;
fd = open("track.txt", O_WRONLY);
//将track中信息存入trace所在文件
while (tmp) {
trace_data[i++] = tmp->x;
trace_data[i++] = ',';
trace_data[i++] = tmp->y;
trace_data[i++] = ';';
tmp = tmp->next;
}
trace_data[i] = '\0';
write(fd, trace_data, i);
close(fd);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAXWORKERS 64
void *Bear(void *);
void *Honeybees(void *);
sem_t busy, full;
int W = 5;
int pot;
int main(int argc, char *argv[]) {
pthread_t pid, bid[MAXWORKERS];
int numBees;
numBees = (argc > 1)? atoi(argv[1]) : MAXWORKERS;
if (numBees > MAXWORKERS) numBees = MAXWORKERS;
W = (argc > 2)? atoi(argv[2]) : W;
pot = 0;
sem_init(&busy, 1, 0);
sem_init(&full, 1, 0);
printf("main started\n");
pthread_create(&pid, NULL, Bear, NULL);
long i;
for (i = 0; i < numBees; i++)
pthread_create(&bid[i], NULL, Honeybees, (void *) i);
sem_post(&busy);
sleep(1);
}
void *Honeybees(void *arg) {
long myid = (long) arg;
while(1){
sem_wait(&busy);
if (pot < W) {
pot++; //fill the pot by 1
printf("#%ld ", myid);
sem_post(&busy);
usleep(100000); //time to find honey?
} else {
sem_post(&full); //awake the bear
}
}
}
void *Bear(void *arg) {
while(1) {
sem_wait(&full);
pot = 0; //eats all the honey
printf("\nBear!\n");
sem_post(&busy); //make the pot available again
}
}
|
C
|
#include "game.h"
#include <time.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
game_t game;
char fen[TOTAL_SQUARES * 2];
memset(fen, 0, TOTAL_SQUARES * 2);
clock_t t = clock();
read_fen(&game, argv[1]);
game_to_fen(&game, fen);
t = clock() - t;
display_game(&game);
puts(fen);
puts("");
printf("Time taken to read/generate FEN: %f seconds.\n", ((double)t)/CLOCKS_PER_SEC);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
/*funzione per il cifrario di Cesare, gli passo tutta la stringa con * con il riferimento al puntatore*/
void cesare(char *stringa){
int k=0,c=0, t=0;//k=salto da eseguire. c=contatore. t=var temporanea.
do{
printf("Inserisci il salto da eseguire, superiore a 1 ma inferiore a 25\n");
scanf("%d",&k);
}while(k<1||k>25);//inserimento di k compreso tra 1-26
printf("----------------------------------------------------------\n\n" );
printf("La tua frase: %s\n",stringa);
printf("La tua frase cifrata/cyphertext tramite cifr. di Cesare e' : \n" );
for (c=0;c<strlen(stringa);c++){//ciclo per la stampa della frase cifrata
t=0;
if(isspace(stringa[c])){//controllo se il carattere è uno spazio
printf(" ");
}
else{
/*controllo se il carattere è fuori dal range dell'alfabeto minuscolo quindi può essere: ! : / ...*/
if (stringa[c]<97||stringa[c]>122) {
printf("%c",stringa[c]);
}
else{
/*la if controlla se il carattere ascii + k sfora 122, se è così metto t=26 di modo che
rientro nel range dei caratteri minuscoli, sottraendo t quando vado a stampare.
E' necessario per il cifrario di Cesare perchè dopo "z" si riparte da "a" (123-26=97)*/
if(stringa[c]+k>122){
t=26;
}
printf("%c",stringa[c]+k-t);
}
}
}
printf("\n");
}
/*funzione per il cifrario a sostituzione, gli passo tutta la stringa con * con il riferimento al puntatore*/
void sos(char *stringa){
/*alfabeto normale di 26 caratteri*/
char alfabeto[26]={'a','b', 'c', 'd' ,'e' ,'f' ,'g' ,'h' ,'i' ,'j' ,'k','l' ,'m' ,'n', 'o', 'p' ,'q', 'r', 's' ,'t' ,'u', 'v' ,'w' ,'x' ,'y','z'} ;
int c=0,i=0,a=0;//c=contatore. i=contatore. a=flag.
char alfabeto_mescolato[26],temp;//temp=var temporanea ci inserisco un carattere per poi passarlo ad alfabeto mesc
for (c=0;c<26;c++){
do{
a=0;
printf("Inserisci una lettera minuscola alla volta dell'alfabeto per creare alfabeto mescolato, non sono ammesse ripetizioni\n");
scanf("\n%c", &temp);
if (temp<97||temp>122) {//controllo se non è un carattere dell'alfabeto minuscolo
printf("Carattere non valido\n");
a++;
}
}while(a!=0);//esce solo quando il carattere è valido
a=0;
/*controllo se temp è presente in alfabeto, se si inserisco temp nella posizione c dentro alfabeto_mescolato.
Poi metto uno "0" al posto della lettera corrispondente su alfabeto, così nel ciclo successivo la stessa
lettera non viene inserita.*/
for (i=0;i<strlen(alfabeto);i++) {
if(temp==alfabeto[i]){
alfabeto_mescolato[c]=temp;
alfabeto[i]='0';
i=100;//metto i a 100 così esce dal ciclo quando trova la lettera
a++;//aumento a di 1 così per un controllo seguente
}
}
/*se a==0 significa che la lettera non è stata inserita in alfabeto_mescolato */
if (a==0) {
printf("La lettera %c e' stata gia' inserita\n",temp);
/*diminuisco c di 1 così nel ciclo successivo non si perde una posizione dato che le lettere
vanno inserite in alfabeto_mescolato[c]. Se non facessi c-- si perderebbe una posizione*/
c--;
}
/*stampo le lettere dell'alfabeto_mescolato così l'utente vede cosa ha inserito e in quale posizione
(durante la stampa di queste lettere vengono stampati a video caratteri strani/random in posizioni
non ancora definite, credo che la memoria si sporchi in alcuni casi, non danno nessun problema dato
che vengono sostituite dai caratteri inseriti dall'utente, ma son brutti da vedere durante la stampa)*/
printf("Lettere gia' inserite:");
for (i=0;i<strlen(alfabeto_mescolato);i++) {
printf(" %c",alfabeto_mescolato[i]);
}
printf("\n\n--------------------------------------------------------------------\n" );
}
printf("La tua frase: %s\n",stringa);
printf("La tua frase cifrata/cyphertext tramite sostituzione e' : \n" );
for (i=0;i<strlen(stringa);i++) {//ciclo della stampa della frase cifrata
if(isspace(stringa[i])){//controllo se è uno spazio
printf(" ");
}
else{
/*controllo se il carattere è fuori dal range dell'alfabeto minuscolo quindi può essere: ! : / ...*/
if (stringa[i]<97||stringa[i]>122) {
printf("%c",stringa[i]);
}
else{
/*inserisco dentro a il numero ascii corrispondente alla lettera -97, perchè 97 è "a".
Così riesco a trovare la posizione di quella lettera nell'alfabeto es: c=99-97 = 2 (si parte da 0)
Quindi la lettera corrispondente si trova nella stessa posizione nell'alfabeto_mescolato*/
a=stringa[i]-97;
printf("%c",alfabeto_mescolato[a]);
a=0;//azzero a per il ciclo successivo
}
}
}
}
void main()
{
char stringa[256];//dichiarazione stringa per inserimento della frase
int scelta=0,a=0;//scelta=controllo per il menù a scelta. a=var di controllo
do{
a=0;
printf("Benvenuto nel cifrario, inserisci la tua parola, non sono ammesse maiuscole e numeri:\n");
fgets(stringa, sizeof(stringa), stdin);
for(int c1=0;c1<strlen(stringa);c1++){
if(isdigit(stringa[c1])){//vedere se il carattere è un numero
a++;
}
if (isalpha(stringa[c1])&&isupper(stringa[c1])){//vedere se il carattere è maiuscolo
a++;
}
}
}while(a!=0);//fa passare solamente caratteri minuscoli e caratteri speciali(, . : ...)
do{
printf("\n\n1 - Il Cifrario di Cesare\n");
printf("2 - Il Cifrario a sostituzione\n");
printf("Inserisci 1 o 2\n" );
scanf("%d",&scelta );
}while(scelta<1||scelta>2);//scelta deve essere 1 o 2
/*switch serve per "switchare" i vari case in base a cosa ci sta dentro scelta e deve
corrispondere al numero vicino case.*/
switch(scelta){
case 1://apertura case 1
/*faccio partire la funzione cesare, cioè cifr. di Cesare e gli passo la stringa*/
cesare(stringa);
break;//indica la fine del case
case 2://apertura case 2
/*faccio partire la funzione sos, cioè cifr. a sostituzione e gli passo la stringa*/
sos(stringa);
break;//indica la fine del case
}
}
//| (• ◡•)|Cassio(❍ᴥ❍ʋ)
|
C
|
#ifndef _LATTICE_H
#define _LATTICE_H
//-----------------------------
// VARIABLES
//-----------------------------
const int leng = SIZE;
const int nsite = leng*leng*leng;
/* variable with the index of all 6 neighbours per site */
int neib[nsite][6];
//-------------------------------
// SUBROUTINES
//-------------------------------
void init_lattice()
{
int i1,i2,i3,i1p,i2p,i3p,i1m,i2m,i3m;
int is,isp1,isp2,isp3,ism1,ism2,ism3;
for (i1 = 0; i1<leng ; i1++ ){
i1p = i1 + 1;
i1m = i1 - 1;
if (i1 == (leng-1) ) i1p = 0;
if (i1 == 0) i1m = leng-1;
for (i2 = 0; i2<leng ; i2++){
i2p = i2 + 1;
i2m = i2 - 1;
if (i2 == (leng-1) ) i2p = 0;
if (i2 == 0) i2m = leng-1;
for (i3 = 0; i3<leng ; i3++){
i3p = i3 + 1;
i3m = i3 - 1;
if (i3 == (leng-1) ) i3p = 0;
if (i3 == 0) i3m = leng-1;
is = i1 + i2*leng + i3*leng*leng;
isp1 = i1p + i2*leng + i3*leng*leng;
isp2 = i1 + i2p*leng + i3*leng*leng;
isp3 = i1 + i2*leng + i3p*leng*leng;
ism1 = i1m + i2*leng + i3*leng*leng;
ism2 = i1 + i2m*leng + i3*leng*leng;
ism3 = i1 + i2*leng + i3m*leng*leng;
// fill in the neighborhood array
neib[is][0] = isp1;
neib[is][1] = isp2;
neib[is][2] = isp3;
neib[is][3] = ism1;
neib[is][4] = ism2;
neib[is][5] = ism3;
}
}
}
}
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* builtin_unset.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: efischer <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/05 08:32:50 by efischer #+# #+# */
/* Updated: 2020/03/12 15:49:26 by snunes ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "shell.h"
static char **get_name_tab(int ac, char **av)
{
char *err;
char **buf;
int i;
i = 0;
buf = (char**)malloc(sizeof(char*) * (ac + 1));
if (buf != NULL)
{
while (i < ac)
{
if (ft_strchr(av[i], '=') != NULL)
{
ft_asprintf(&err, "unset: `%s': not a valid identifier", av[i]);
ft_putendl_fd(err, 2);
ft_free_tab(i, &buf);
break ;
}
else
buf[i] = ft_strdup(av[i]);
i++;
}
}
if (i < ac)
ft_free_tab(i, &buf);
return (buf);
}
static int match_name(char *var_name, char **name, int tab_len)
{
int ret;
int i;
i = 0;
ret = FALSE;
while (i < tab_len)
{
if (ft_strequ(var_name, name[i]) == TRUE)
{
ret = TRUE;
break ;
}
i++;
}
return (ret);
}
static void remove_first_var(char **name, int tab_len)
{
extern t_list *g_env;
t_list *head;
head = g_env;
while (g_env != NULL && match_name(((t_shell_var*)(g_env->content))->name,
name, tab_len) == TRUE)
{
head = g_env->next;
ft_lstdelone(&g_env, &del_elem);
g_env = head;
}
}
static void unset_var(int tab_len, char **name)
{
extern t_list *g_env;
t_list *head;
t_list *tmp;
remove_first_var(name, tab_len);
head = g_env;
tmp = g_env;
g_env = g_env->next;
while (g_env != NULL)
{
if (match_name(((t_shell_var*)(g_env->content))->name, name, tab_len) == TRUE)
{
tmp->next = g_env->next;
ft_lstdelone(&g_env, &del_elem);
g_env = tmp->next;
}
else
{
tmp = g_env;
g_env = g_env->next;
}
}
g_env = head;
}
int cmd_unset(int ac, char **av)
{
int ret;
char **name;
ret = SUCCESS;
if (ft_getopt(ac - 1, av, "") == FALSE)
{
ft_putendl_fd("unset: usage: unset [arg ...]", 2);
ret = FAILURE;
}
name = get_name_tab(ac - 1, av + 1);
if (name != NULL)
{
unset_var(ac - 1, name);
ft_free_tab(ac - 1, &name);
}
return (ret);
}
|
C
|
#include<stdio.h>
void Merge(int A[], int l, int mid, int h)
{
int i = l, j = mid +1, k = l;
int B[100];
while(i<=mid && j <= h)
{
if(A[i] < A[j])
B[k++] = A[i++];
else
B[k++] = A[j++];
}
for(;i<=mid;i++)
B[k++] = A[i];
for(;j<=h;j++)
B[k++] = A[j];
for (i=l; i<=h; i++)
A[i] = B[i];
}
void MergeSort(int A[], int l, int h)
{
int mid;
if (l<h)
{
mid = (l + h)/2;
MergeSort(A, l,mid);
MergeSort(A, mid+1,h);
Merge(A, l, mid, h);
}
}
int main()
{
int A[]={1,2,3,4,5,6,7,8,9,10},n=10,i;
MergeSort(A,0,n-1);
for(i=0;i<10;i++)
printf("%d ",A[i]);
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
/*
* Lab Title: Hot Tub/Pool
* Lab Description: Find the size, water capacity,
* and cost required to fill a pool and hot tub
* using user specified inputs.
* Name: Mark Schneider
* Email: [email protected]
* Lab time: 7:30 F
*/
void computePool() {
// Initialize variables at a value that is unacceptable
float wht = -1; // Width of hot tub
float dht = -1; // Depth of hot tub
float l = -1; // Length
float w = -1; // Width
float ds = -1; // Depth of shallow end
float dd = -1; // Depth of deep end
float ld = -1; // Length of the deep end
float ls = -1; // Length of the shallow end
float wi = -1; // Length of the walk in section
// vvv Could be done with a function but whatever
// Entering Depth of shallow end
printf("Please enter the depth of the shallow end of the pool (0 - 5 feet): ");
scanf("%f", &ds);
while (ds < 0.000000 || ds > 5.000000) {
printf("The depth of the shallow end of the pool must be inclusively between 0.000000 and 5.000000 feet.\n");
printf("Please enter the depth of the shallow end of the pool (0.000000 - 5.000000 feet): ");
scanf("%f", &ds);
}
// Entering Depth of deep end
printf("Please enter the depth of the deep end of the pool (6.000000 - 15.000000 feet): ");
scanf("%f", &dd);
while (dd < 6.000000 || dd > 15.000000) {
printf("The depth of the deep end of the pool must be inclusively between 6.000000 and 15.000000 feet.\n");
printf("Please enter the depth of the deep end of the pool (6.000000 - 16.000000 feet): ");
scanf("%f", &dd);
}
// Entering Width of pool
printf("Please enter the width of the pool (15.000000 - 30.000000 feet): ");
scanf("%f", &w);
while (w < 15.000000 || w > 30.000000) {
printf("The width of the pool must be inclusively between 15.000000 and 30.000000 feet.\n");
printf("Please enter the width of the pool (15.000000 - 30.000000 feet): ");
scanf("%f", &w);
}
// Entering Length of pool
printf("Please enter the length of the pool (30.000000 - 75.000000 feet): ");
scanf("%f", &l);
while (l < 35.000000 || l > 70.000000) {
printf("The length of the pool must be inclusively between 35.000000 and 70.000000 feet.\n");
printf("Please enter the length of the pool (35.000000 - 70.000000 feet): ");
scanf("%f", &l);
}
// Entering Length walk in
printf("Please enter the length of the walk in (5.000000 - %.6f feet): ", l / 3.000000);
scanf("%f", &wi);
while (wi < 5.000000 || wi > l / 3.000000) {
printf("The length of the walk in must be inclusively between 5.000000 and %.6f feet.\n", l / 3.000000);
printf("Please enter the length of the walk in (5.000000 - %.6f feet): ", l / 3.000000);
scanf("%f", &wi);
}
// Entering Length of shallow end
printf("Please enter the length of the shallow end (10 - %.6f feet): ", l / 2.000000);
scanf("%f", &ls);
while (ls < 10.000000 || ls > l / 2.000000) {
printf("The length of the shallow end must be inclusively between 10.000000 and %.6f feet.\n", l / 2.000000);
printf("Please enter the length of the shallow end (10.000000 - %.3f feet): ", l / 2.000000);
scanf("%f", &ls);
}
// Entering Length of deep end
printf("Please enter the length of the deep end (12.000000 - %.6f feet): ", l / 2.000000);
scanf("%f", &ld);
while (ld < 12.000000 || ld > l / 2.000000) {
printf("The length of the shallow end must be inclusively between 12.000000 and %.6f feet.\n", l / 2.000000);
printf("Please enter the length of the shallow end (12.000000 - %.6f feet): ", l / 2.000000);
scanf("%f", &ld);
}
// Entering Width of hot tub
printf("Please enter the width of the hot tub (8.000000 - 14.000000 feet): ");
scanf("%f", &wht);
while (wht < 8.000000 || wht > 14.000000) {
printf("The width of the hot tub must be inclusively between 8.000000 and 14.000000 feet.\n");
printf("Please enter the width of the hot tub (8.000000 - 14.000000 feet): ");
scanf("%f", &wht);
}
// Entering Depth of hot tub
printf("Please enter the depth of the hot tub (3.000000 - 5.000000 feet): ");
scanf("%f", &dht);
while (dht < 3.000000 || dht > 5.000000) {
printf("The depth of the hot tub must be inclusively between 8.000000 and 5.000000 feet.\n");
printf("Please enter the depth of the hot tub (3.000000 - 5.000000 feet): ");
scanf("%f", &dht);
}
while ((wi + ls + ld) > l) {
printf("\nWARNING: The sum of the walk-in length, the shallow end length and the deep end length is larger than the pool length!!");
printf("\nPlease enter new values for the walk-in, the shallow end, and the deep end.");
// Entering Length walk in
printf("Please enter the length of the walk in (5.000000 - %.6f feet): ", l / 3.000000);
scanf("%f", &wi);
while (wi < 5.000000 || wi > l / 3.000000) {
printf("The length of the walk in must be inclusively between 5.000000 and %.6f feet.\n", l / 3.000000);
printf("Please enter the length of the walk in (5.000000 - %.6f feet): ", l / 3.000000);
scanf("%f", &wi);
}
// Entering Length of shallow end
printf("Please enter the length of the shallow end (10 - %.6f feet): ", l / 2.000000);
scanf("%f", &ls);
while (ls < 10.000000 || ls > l / 2.000000) {
printf("The length of the shallow end must be inclusively between 10.000000 and %.6f feet.\n", l / 2.000000);
printf("Please enter the length of the shallow end (10.000000 - %.3f feet): ", l / 2.000000);
scanf("%f", &ls);
}
// Entering Length of deep end
printf("Please enter the length of the deep end (12.000000 - %.6f feet): ", l / 2.000000);
scanf("%f", &ld);
while (ld < 12.000000 || ld > l / 2.000000) {
printf("The length of the shallow end must be inclusively between 12.000000 and %.6f feet.\n", l / 2.000000);
printf("Please enter the length of the shallow end (12.000000 - %.6f feet): ", l / 2.000000);
scanf("%f", &ld);
}
}
float deepEndVolume = w * (dd - 0.5) * ld;
float shallowDeepTransitionVolume = 0.5 * (dd + ds - 1.0) * (l - ld - ls - wi) * w;
float shallowEndVolume = w * (ds - 0.5) * ls;
float walkinVolume = 0.5 * (ds - 0.5) * wi * w;
float totalPoolVolume = deepEndVolume + shallowDeepTransitionVolume + shallowEndVolume + walkinVolume;
float totalPoolGallons = totalPoolVolume * 7.481;
printf("\nTotal volume of pool: %.1f", totalPoolVolume);
printf("\nGallons of water to fill pool: %.1f", totalPoolGallons);
float hottubVolume = (wht / 2.0) * (wht / 2.0) * M_PI * (dht - 0.5);
float hottubGallons = (wht / 2.0) * (wht / 2.0) * M_PI * (dht - 0.5) * 7.481;
float totalCost = (totalPoolGallons + hottubGallons) * 4 * 0.07;
printf("\nTotal volume of hot tub: %.1f", hottubVolume);
printf("\nGallons of water to fill hot tub: %.1f", hottubGallons);
printf("\nTotal Gallons for both: %.1f", totalPoolGallons + hottubGallons);
printf("\nTotal cost for both: %.2f\n", totalCost);
}
int main() {
int response = 0;
computePool();
while (response == 0) {
printf("Would you like to compute another pool? (1 for yes, 0 for no): ");
scanf("%d", &response);
if (response == 1) {
computePool();
} else {
return 0;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int array[10];
int i;
int n;
int search;
printf("Cate elemente va avea vectorul? ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("Introduceti elementul: ");
scanf("%d", &array[i]);
}
printf("Careeste valoarea pe care o cautati? ");
scanf("%d", &search);
for(i=0;i<n;i++)
{
if(array[i]==search)
{
printf("Elementul cautat este pe pozitia %d", i);
break;
}
}
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int a,b,c;
}
//This function does addition of two numbers
int add(int a,int b)
{
return a+b;
}
int subtract(int a,int b)
{
return a-b;
}
int multiply(int a,int b)
{
return a*b;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_2__ ;
typedef struct TYPE_3__ TYPE_1__ ;
/* Type definitions */
typedef int u32 ;
struct super_block {TYPE_1__* s_root; } ;
struct inode {int i_generation; } ;
struct fid {int* raw; } ;
struct dentry {int /*<<< orphan*/ d_op; } ;
typedef int loff_t ;
struct TYPE_4__ {int i_logstart; } ;
struct TYPE_3__ {int /*<<< orphan*/ d_op; } ;
/* Variables and functions */
int /*<<< orphan*/ IS_ERR (struct dentry*) ;
TYPE_2__* MSDOS_I (struct inode*) ;
struct dentry* d_obtain_alias (struct inode*) ;
struct inode* fat_iget (struct super_block*,int) ;
struct inode* ilookup (struct super_block*,int) ;
int /*<<< orphan*/ iput (struct inode*) ;
__attribute__((used)) static struct dentry *fat_fh_to_dentry(struct super_block *sb,
struct fid *fid, int fh_len, int fh_type)
{
struct inode *inode = NULL;
struct dentry *result;
u32 *fh = fid->raw;
if (fh_len < 5 || fh_type != 3)
return NULL;
inode = ilookup(sb, fh[0]);
if (!inode || inode->i_generation != fh[1]) {
if (inode)
iput(inode);
inode = NULL;
}
if (!inode) {
loff_t i_pos;
int i_logstart = fh[3] & 0x0fffffff;
i_pos = (loff_t)fh[2] << 8;
i_pos |= ((fh[3] >> 24) & 0xf0) | (fh[4] >> 28);
/* try 2 - see if i_pos is in F-d-c
* require i_logstart to be the same
* Will fail if you truncate and then re-write
*/
inode = fat_iget(sb, i_pos);
if (inode && MSDOS_I(inode)->i_logstart != i_logstart) {
iput(inode);
inode = NULL;
}
}
/*
* For now, do nothing if the inode is not found.
*
* What we could do is:
*
* - follow the file starting at fh[4], and record the ".." entry,
* and the name of the fh[2] entry.
* - then follow the ".." file finding the next step up.
*
* This way we build a path to the root of the tree. If this works, we
* lookup the path and so get this inode into the cache. Finally try
* the fat_iget lookup again. If that fails, then we are totally out
* of luck. But all that is for another day
*/
result = d_obtain_alias(inode);
if (!IS_ERR(result))
result->d_op = sb->s_root->d_op;
return result;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include "stack.h"
int priority(char);
main() {
char x, exp[50];
int i;
init();
printf("\nEnter Infix expression : ");
scanf("%s", exp);
printf("\nThe Postfix expression is : ");
for(i = 0; exp[i] != '\0'; i++) {
if(isalnum(exp[i]))
printf("%c", exp[i]);
else
if(exp[i] == '(')
push('(');
else {
if(exp[i] == ')')
while((x = pop())!='(')
printf("%c", x);
else {
while(priority(exp[i]) <= priority(peak()) && !isEmpty()) {
x = pop();
printf("%c",x);
}
push(exp[i]);
}
}
}
while(!isEmpty()) {
x = pop();
printf("%c", x);
}
printf("\n");
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/' || x == '%')
return 2;
return 3;
}
|
C
|
/*中国大学MOOC-陈越、何钦铭-数据结构-2018秋
* 04-树4 是否同一棵二叉搜索树(25 分)
* 动态存贮模式
* wirte by xucaimao,2018-10-03
* 提交通过
* */
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct TNode * Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree Insert(BinTree BST,ElementType X){
if(BST==NULL){ //当前节点为空,找到插入位置
BST=(Position)malloc(sizeof(struct TNode));
BST->Left=NULL;
BST->Right=NULL;
BST->Data=X;
}
else{
if(X < BST->Data)
BST->Left= Insert(BST->Left,X);
if(X > BST->Data)
BST->Right= Insert(BST->Right,X);
}
return BST;
}
void DeleteTree(BinTree BST){
if(BST){
DeleteTree(BST->Left);
DeleteTree(BST->Right);
free(BST);
}
}
//判断两个树a、b是否为同相同的二叉树,相同返回1,否则返回0
int sameTree(BinTree ta,BinTree tb){
if(ta==NULL && tb==NULL) return 1;
else if(ta && !tb)return 0;
else if(tb && !ta)return 0;
else { //两棵树根都非空
if(ta->Data == tb->Data)
return sameTree(ta->Left,tb->Left) && sameTree(ta->Right,tb->Right);
else return 0;
}
}
void PreorderTraversal( BinTree BT ){
if(BT){
printf(" %d",BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
}
int main(){
freopen("/Users/xcm/xcmprogram/netlesson/ds-zju/in.txt","r",stdin);
int nodeNum,treeNum;
while( scanf("%d",&nodeNum) && nodeNum){
scanf("%d",&treeNum);
BinTree ta;
ta=NULL;
for(int i=0;i<nodeNum;i++){ //读入原始树
ElementType d;
scanf("%d",&d);
ta=Insert(ta,d);
}
// printf("The tree a is: ");
// PreorderTraversal(ta); printf("\n");
for(int i=0;i<treeNum;i++){ //读入待比较树
BinTree tb;
tb=NULL;
for(int i=0;i<nodeNum;i++){
ElementType d;
scanf("%d",&d);
tb=Insert(tb,d);
}
// printf("The tree b is: ");
// PreorderTraversal(tb);printf("\n");
if(sameTree(ta,tb))printf("Yes\n");
else printf("No\n");
DeleteTree(tb);
}
DeleteTree(ta);
}
return 0;
}
|
C
|
#ifndef _MISCLIB_H_
#define _MISCLIB_H_
/******************************************************************************
# # # #### #### # # ##### # #
## ## # # # # # # # # # #
# ## # # #### # # # ##### ######
# # # # # # # # # ### # #
# # # # # # # # # # # ### # #
# # # #### #### ###### # ##### ### # #
******************************************************************************/
/* This file is part of MAPMAKER 3.0b, Copyright 1987-1992, Whitehead Institute
for Biomedical Research. All rights reserved. See READ.ME for license. */
#include "syscode.h"
#include "mathlib.h"
/***** GETTING THE TIME (code is in syscode.c) *****/
/* DO NOT use the time() system function alone, it's not portable! */
//char *time_string(); /* no args; returns NULL if it fails */
//real usertime(); /* args: bool do_reset; */
///* returns time in seconds, or -1.0 if it fails: do_reset makes it work like
// a stopwatch (it starts counting when lib_init is executed) */
/***** SUBPROCESSES (code is in syscode.c) *****/
///* These both return FALSE on failure, TRUE if OK */
//bool shell_command(); /* arg: char *command; defined in system.h */
//bool subshell(); /* no args. returns T/F */
/***** GET/SET DIRECTORY (code is in syscode.c) *****/
///* These both also return FALSE on failure, TRUE if OK */
//bool get_directory(); /* args: char *str; str>=PATH_LENGTH+1 chars */
//bool change_directory(); /* args: char *str; str is directory name */
/***** SORT OPERATIONS FOR SIMPLE ARRAYS (code is in mathlib.c) *****/
///* effective declarations:
// void isort(); args: int *data; int array_len;
// void lsort(); args: long *data; int array_len;
// void rsort(); args: real *data; int array_len;
// void ssort(); args: real *data; int array_len; STRINGS, NOT SHORTS!
// void inv_isort(); args: int *data; int array_len; ascending order
// void inv_rsort(); well, figure it out! */
//
////int icomp(), lcomp(), scomp(), rcomp(), inv_icomp(), inv_rcomp();
#define isort(p, n) qsort(p,n,sizeof(int),icomp);
#define lsort(p, n) qsort(p,n,sizeof(long),lcomp);
#define rsort(p, n) qsort(p,n,sizeof(real),rcomp);
#define ssort(p, n) qsort(p,n,sizeof(char*),scomp);
#define inv_isort(p, n) qsort(p,n,sizeof(int),inv_icomp);
#define inv_rsort(p, n) qsort(p,n,sizeof(real),inv_rcomp);
///* For arrays of pointers to things (eg: structs) use:
// void psort(); args: <type> *data; int array_len; <type>; int comp_func();
//
// Comp_func() will be passed two ptrs to ptrs to <type>s: you should
// derefernce these carefully (as shown below) for portability. For
// Example, here we sort an array of ptrs to FOOs on the field "key":
// Note that FOOs could have variable sizes (only the pointers to them
// are getting shuffled).
//
// \* Make and sort an array of pointers to FOOs *
// typedef struct { int key; ... } FOO;
// FOO **data;
// array(data, length, FOO*);
// for (i=0; i<length; i++) single(data[i], FOO); \* or use parray() *
// ...
// int compare_foos(p1,p2)
// PSORT_COMPARE_TYPE(FOO) **p1, **p2; \* ptrs to ptrs to FOOs *
// {
// int key1, key2;
// key1=(*(FOO**)p1)->key;
// key2=(*(FOO**)p2)->key;
//
// if (key1 < key2) return(-1);
// else if (key1==key2) return(0);
// else return(1);
// }
// ...
// psort(data, 100, FOO, compare_foos);
//
//You may want to look in system.h to see how these work in order to write
//your own sorting routines. */
//#define psort(p,n,t,f) qsort(QSORT_CAST(p),(QSORT_LENGTH)n,sizeof(t*),f)
//#define PSORT_COMPARE_TYPE(t) QSORT_COMPARE_PTR_TO(t)
#endif
|
C
|
#include<stdio.h>
#define max(a,b,c) (a>b?a:b)>(b>c?b:c)?(a>b?a:b):(b>c?b:c)
float m(float a,float b,float c)
{
float m;
m=a;
if(m<b)
m=b;
if(m<c)
m=c;
return m;
}
float m(float a,float b,float c);
main()
{
float a,b,c;
scanf("%f%f%f",&a,&b,&c);
printf("%.3f\n",m(a,b,c));
printf("%.3f\n",max(a,b,c));
}
|
C
|
#include <stdio.h>
int main()
{
int line, star;
for(line=1;line<=5;line++){
for(star=1;star<=5;star++)
printf("*");
printf("\n");
}
return 0;
}
|
C
|
/*********************************************************
// Name: Sollie Garcia
//
// Homework: 3b
//
// Class: ICS 212
//
// Instructor: Ravi Narayan
//
// Date: Feb 5, 2017
//
// File: main.c
//
// Description: This file contains the driver for navigating
// the entire of the program.
********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "record.h"
#include "prototypes.h"
int debugmode;
/**********************************************************
// Function Name: main
//
// Description: handles an option to run the program in "debug" mode
// Depending on what the user inputs for the menu,
// the main file will run the required functions to
// filfill the task requested
//
// Parameters: int argc, char *argv[]
//
// Return Values: 0
***********************************************************/
int main(int argc, char *argv[])
{
int menu_value, go, menu;
struct record * start;
char input[10];
go = 1;
start = NULL;
if (argc == 2)
{
if (strcmp(argv[1], "debug") == 0)
{
printf("\n***** Debug mode on *****\n\n");
debugmode = 1;
}
else
{
printf("ERROR: To many arguments or wrong argument.\n");
exit(0);
}
}
else if (argc > 2)
{
printf("ERROR: To many arguments or wrong arugment.\n");
exit(0);
}
printf("Would you like to start with the program with a file import? (0/1)\n");
fgets(input, 10, stdin);
fixString(input);
sscanf(input, "%d", &menu);
switch(menu)
{
case 0:
break;
case 1:
readfile(&start, "database.txt");
break;
default:
printf("Invalid input! Starting without file import.\n");
break;
}
printf("\t\t\tWelcome to the Bank of ICS212! \nTo navigate through the program type the value in the [] and hit enter!");
menu_value = mainMenu();
while(go == 1)
{
switch (menu_value)
{
case 0:
writefile(start, "database.txt");
printf("Goodbye!\n");
go = 0;
break;
case 1:
{
int accountno;
int length = 80;
char address[80], name[25];
accountno = getAccountNum();
getName(name);
getaddress(address, length);
addRecord(&start, accountno, name, address);
printf("Success! Returning to main menu...");
menu_value = mainMenu();
break;
}
case 2:
{
int accountno, ret;
int length = 80;
char newAddress[80];
printf("Please have your account number and new address ready for input!\n");
accountno = getAccountNum();
getaddress(newAddress, length);
ret = modifyRecord(start, accountno, newAddress);
if (ret == 1)
{
printf("Success!\n");
}
else if (ret == 0)
{
printf("The record could not be found with the given account number: %d\n", accountno);
}
else
{
printf("The databse is empty!\n");
}
printf("Returning to main menu...");
menu_value = mainMenu();
break;
}
case 3:
{
int accountno, ret;
printf("Please have your account number you wish to print ready for input!\n");
accountno = getAccountNum();
ret = printRecord(start, accountno);
if (ret == 1)
{
printf("Success!\n");
}
else if (ret == 0)
{
printf("The record could not be found with the given account number: %d\n", accountno);
}
else
{
printf("The database is empty!\n");
}
printf("Returning to main menu...");
menu_value = mainMenu();
break;
}
case 4:
{
printf("Printing all records!\n\n");
printAllRecords(start);
printf("\n");
printf("Returning to main menu...");
menu_value = mainMenu();
break;
}
case 5:
{
int accountno, ret;
printf("Please have the account number you wish to remove ready!\n");
accountno = getAccountNum();
ret = deleteRecord(&start, accountno);
printf("\n");
if (ret == -1)
{
printf("The account number: %d could not be deleted.\n\nReturning to main menu...", accountno);
}
else
{
printf("Success! Deleted %d records.\nReturning to main menu...", ret);
}
menu_value = mainMenu();
break;
}
default:
printf("Invalid input!\n");
menu_value = mainMenu();
break;
}
}
return 0;
}
|
C
|
#pragma once
#include"listNode.h"
/*
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
*/
bool hasCycle(ListNode *head) {
ListNode* ptr1 = head;
ListNode* ptr2 = head;
bool result = false;
while (ptr1&&ptr2)
{
if (ptr2->next==ptr1){
result = true;
break;
}
ptr1 = ptr1->next;
if(ptr2 = ptr2->next)//һNULLܼһ NULLnext
ptr2 = ptr2->next;
}
return result;
}
/*
֮ʵжҪ
*/
bool hasCycle_better(ListNode *head) {
ListNode* ptr1 = head;
ListNode* ptr2 = head;
bool result = false;
while (ptr2->next&&ptr2->next->next)//жһЩһЩ
{
ptr1 = ptr1->next;
ptr2 = ptr2->next->next;
if (ptr2 == ptr1) {
result = true;
break;
}
}
return result;
}
|
C
|
#include<stdio.h>
void main()
{
int a;
long int b;
long long c;
long long int d;
double e;
long double f;
long long g;
printf("Size of int a= %ld\n",sizeof(a));
printf("Size of long int b = %ld\n",sizeof(b));
printf("Size of long long c = %ld\n",sizeof(c));
printf("Size of long long int d = %ld\n",sizeof(d));
printf("Size of double e = %ld\n",sizeof(e));
printf("Size of long double f = %ld\n",sizeof(f));
printf("Size of long long g = %ld\n",sizeof(g));
}
|
C
|
#include <stdio.h>
int main(void){
int d;
scanf("%d",&d);
printf("Christmas");
while(d!=25){
printf(" Eve");
d++;
}
printf("\n");
return 0;
} ./Main.c: In function main:
./Main.c:4:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d",&d);
^
|
C
|
//multiplication game
//enter number of problems to complete and maximum number to multiply, play game
#include <stdio.h>
#include <stdlib.h>
int multGame(int numProblems, int maxNumber);
int main(){
int probCt=0,maxVal=0;
//get user inputs
printf("enter number of multiplication problems\n");
scanf("%d", &probCt);
printf("enter maximum value to use in a problem\n");
scanf("%d", &maxVal);
//multGame returns number of correct responses
printf("number of correct responses = %d\n", multGame(probCt,maxVal));
}
int multGame(int numProblems, int maxNumber){
//keep track of correct answers
int counter=0;
for(int i=0; i<numProblems;i++){
//x,y are random integers up to maxnum which will be multiplied
int x=rand()%(maxNumber+1);
int y=rand()%(maxNumber+1);
int ans;
printf("what is %d x %d\n", x,y);
scanf("%d",&ans);
if(ans==(x*y)){
counter++;
}
}
return counter;
}
|
C
|
//
// processqueue.c
// OSAssignment
//
// Created by Work on 12/05/2014.
// Copyright (c) 2014 ZeevG. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linkedlist.h"
#include "processqueue.h"
void enqueue(ProcessQueue* self, Process* newProcess){
addProcess(&self->start, newProcess);
self->length++;
}
void enqueueSortedArrival(ProcessQueue* self, Process* newProcess){
addProcessSorted(&self->start, newProcess);
self->length++;
}
void enqueueCopy(ProcessQueue* self, Process* newProcess){
Process* tempProcess = (Process*)malloc(sizeof(Process));
memcpy(tempProcess, newProcess, sizeof(Process));
tempProcess->next=NULL;
addProcess(&self->start, tempProcess);
self->length++;
}
void incrementWaiting(ProcessQueue* self){
Process* node = NULL;
for (node = self->start; node != NULL; node = node->next) {
node->waiting++;
}
}
Process* dequeue(ProcessQueue* self){
Process* first = self->start;
if(self->length >= 1){
self->start = self->start->next;
}else{
printf("Dequeue called on a empty list");
}
self->length--;
return first;
}
ProcessQueue * initProcessQueue(){
ProcessQueue* queue = (ProcessQueue*)malloc(sizeof(ProcessQueue));
queue->start = NULL;
queue->length = 0;
queue->enqueue = enqueue;
queue->enqueueCopy = enqueueCopy;
queue->dequeue = dequeue;
queue->incrementWaiting = incrementWaiting;
queue->enqueueSortedArrival = enqueueSortedArrival;
return queue;
}
|
C
|
/* Copyright (c) 1989 Citadel */
/* All Rights Reserved */
/* #ident "bsync.c 1.2 - 89/10/31" */
#include <errno.h>
/*#include <stddef.h>*/
#include "blkio_.h"
/*man---------------------------------------------------------------------------
NAME
bsync - synchronize a block file
SYNOPSIS
#include <blkio.h>
int bsync(bp)
BLKFILE *bp;
DESCRIPTION
The bsync function causes the block file associated with BLKFILE
pointer bp to be synchronized with its buffers; any buffered data
which has been written to the buffers is written to the file.
The header, if it has been modified, is written out last. The
block file remains open and the buffers retain their contents.
If bp is open read-only or is not buffered, there will be no data
to synchronize and bsync will return a value of zero immediately.
bsync will fail if one or more of the following is true:
[EINVAL] bp is not a valid BLKFILE pointer.
[BENOPEN] bp is not open.
SEE ALSO
bexit, bflush, bputb.
DIAGNOSTICS
Upon successful completion, a value of 0 is returned. Otherwise,
a value of -1 is returned, and errno set to indicate the error.
------------------------------------------------------------------------------*/
int bsync(bp)
BLKFILE *bp;
{
int i = 0;
#ifdef DEBUG
bpos_t endblk = 0;
#endif
/* validate arguments */
if (!b_valid(bp)) {
errno = EINVAL;
return -1;
}
/* check if not open */
if (!(bp->flags & BIOOPEN)) {
errno = BENOPEN;
return -1;
}
/* check if not open for writing */
if (!(bp->flags & BIOWRITE)) {
errno = 0;
return 0;
}
/* check if not buffered */
if (bp->bufcnt == 0) {
errno = 0;
return 0;
}
/* synchronize block in each buffer */
for (i = 1; i <= bp->bufcnt; i++) {
if (b_put(bp, (size_t)i) == -1) {
BEPRINT;
return -1;
}
}
/* synchronize header */
if (b_put(bp, (size_t)0) == -1) {
BEPRINT;
return -1;
}
#ifdef DEBUG
/* check block count */
if (b_uendblk(bp, &endblk) == -1) {
BEPRINT;
return -1;
}
if (bp->endblk != endblk) {
BEPRINT;
errno = BEPANIC;
return -1;
}
#endif
errno = 0;
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<locale.h>
int main ()
{
setlocale(LC_ALL,"");
float pr,av,par,prd;
printf ("Preo do produto\nR$:");
scanf("%f",&pr);
av=pr*0.9;
par=pr/5;
prd=(pr*1.2)/10;
printf ("\nA vista:\nR$ %.2f\n\nParcelado em 5x:\nR$ %.2f\n\nParcelado em 10x (20 porcento de juros):\nR$ %.2f\n",av,par,prd);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void rellenarady(int ady[17][12])
{
for(int k=0;k<17;k++)
{
for(int j=0;j<12;j++)
ady[k][j]=0;
}
ady[0][1]=1;
ady[1][2]=1;
ady[2][3]=1;
ady[4][5]=1;
ady[5][6]=1;
ady[6][7]=1;
ady[8][9]=1;
ady[9][10]=1;
ady[10][11]=1;
ady[0][4]=1;
ady[1][5]=1;
ady[2][6]=1;
ady[3][7]=1;
ady[4][8]=1;
ady[5][9]=1;
ady[6][10]=1;
ady[7][11]=1;
}
void imprimirtab(int ady[17][12])
{
int conady=0,conadyv=0;
for(int k=0;k<3;k++)
{
for(int j=0;j<4;j++)
{
printf("*");
if(ady[conady][conady+1]==2)
printf("---");
else
printf(" ");
conady++;
}
printf("\n");
for(int j=0;j<4;j++)
{
if(ady[conadyv][conadyv+4]==2)
printf("| ");
else
printf(" ");
conadyv++;
}
printf("\n");
}
}
int main()
{
int tablero[4][3]={0,1,2,3,
4,5,6,7,
8,9,10,11};
int ady[17][12];
rellenarady(ady);
imprimirtab(ady);
int elecc[2];
printf("Ingrese los puntos a juntar: ");
scanf("%d",&elecc[0]);
scanf("%d",&elecc[1]);
//bool ban=false;
ady[elecc[0]][elecc[1]]++;
for(int k=0;k<17;k++)
{
for(int j=0;j<12;j++)
{
if(ady[k][j] == 1)
{
ady[k][j] = 2;
// ban=true;
break;
}
}
//if(ban == true)
break;
}
imprimirtab(ady);
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
void test_output(bool c, int i){
if (c){
printf("Test %i OK \n", i+1);
}else{
printf("Test %i FAILED\n",i+1);
}
}
|
C
|
/*
main.c
------
Par Paul ROBIN et Louis DUDOT
Role : ecran d'accueil
*/
#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_mixer.h>
#include "constantes.h"
#include "jeu.h"
int main(int argc, char *argv[])
{ SDL_Surface *ico =NULL ;
SDL_Surface *ecran = NULL, *Menu = NULL, *Background = NULL;
SDL_Rect positionBackground, positionMenu;
SDL_Event event;
//Initialisation de l'API Mixer
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) == -1) //Initialisation de l'API Mixer
{ printf("Probleme de chargement audio: %s\n", Mix_GetError());
SDL_Quit();
}
int continuer = 1;
// lecture des images
ico = IMG_Load("images/ico.png"); Background = IMG_Load("images/backgroud.jpg"); Menu = IMG_Load("images/menu.png");
if( ( ico == NULL ) || ( Background == NULL ) || ( Menu == NULL ) ){
printf("Probleme de chargement ressourse: %s\n", SDL_GetError());
SDL_Quit(); }
if( SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER)== -1 ){
printf( "Echec lors du chargement de la video : %s", SDL_GetError() );
SDL_Quit();
}
SDL_WM_SetIcon(ico, NULL); // L'icone doit etre chargee avant SDL_SetVideoMode
ecran = SDL_SetVideoMode(LARGEUR_FENETRE, HAUTEUR_FENETRE, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
SDL_WM_SetCaption("Tetris Clone", NULL);
SDL_ShowCursor(SDL_DISABLE);
positionBackground.x = 0;
positionBackground.y = 0;
// pas besoin car png et SDL_image.h
/* SDL_SetColorKey(Menu, SDL_SRCCOLORKEY, SDL_MapRGB(Menu->format, 0,0,0)); */
positionMenu.x = 30;
positionMenu.y = 180;
while (continuer)
{
SDL_WaitEvent(&event);
switch(event.type)
{
case SDL_QUIT:
continuer = 0;
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE: // Veut sortir
continuer = 0;
break;
case SDLK_j: // Demande à jouer
jouer(ecran);
break;
}
break;
}
// Effacement de l'ecran puis affichage
SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 0, 0));
SDL_BlitSurface(Background, NULL, ecran, &positionBackground);
SDL_BlitSurface(Menu, NULL, ecran, &positionMenu);
SDL_Flip(ecran);
}
// Libration des surfaces charges et de l audio
SDL_FreeSurface(Menu);
SDL_FreeSurface(Background);
SDL_FreeSurface(ecran);
Mix_CloseAudio();
SDL_Quit();
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "./lib/generalList.h"
extern listMgr* initializeList(int ListSize);
extern int addData(listMgr* pListMgr, int pos, int data);
extern int getData(listMgr* pListMgr, int pos);
extern int removeData(listMgr* pListMgr, int pos);
extern void showAllData(listMgr* pListMgr);
extern void removeList(listMgr* pListMgr);
int main()
{
printf("General List Test\n");
listMgr* pListMgr = initializeList(LIST_SIZE);
// Add Data Test
for( int i = 0; i < pListMgr->listSize; ++i ) {
addData(pListMgr, i + 1, (i+1) * (i+1));
}
// Show Data Test
showAllData(pListMgr);
// Data FULL Test
addData(pListMgr, 3, 3);
// Data GET Test
int data = getData(pListMgr, 5);
printf("getData(5) => [%d]\n", data);
data = getData(pListMgr, 3);
printf("getData(3) => [%d]\n", data);
data = getData(pListMgr, 22);
printf("getData(22) => [%d]\n", data);
//Memory Free Test
removeList(pListMgr);
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int i;
double vetor[100], entrada;
scanf("%lf", &entrada);
for (i = 0; i < 100; i++) {
if (i == 0) {
vetor[i] = entrada;
} else {
entrada = entrada / 2;
vetor[i] = entrada;
}
printf("N[%d] = %.4f\n", i, vetor[i]);
}
return 0;
}
|
C
|
/*
* =====================================================================================
*
* Filename: Q1_2.c
*
* Created: 12/15/2012 11:29:43 PM
*
* Author: Jason Huang
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
void reverse(char* str)
{
char* p = str;
char* q = str;
while ('\0' != *(q + 1))
{
q++;
}
while (p < q)
{
char temp = *p;
*p = *q;
*q = temp;
p++;
q--;
}
}
//int main(int argc, char **argv)
//{
// char str[] = "bingo";
// reverse(str);
//
// printf("%s\n", str);
// return 0;
//}
|
C
|
#include <stdio.h>
int main() {
int a,b;
scanf("%d %d", &a, &b);
if (a>=b) {
printf("!a<b\n");
} else {
for (a = a + 1; a < b; a++) {
printf("%d\n", a);
}
}
}
|
C
|
/* 1. 1 100̸ ߿ 7 9
ϴ α ۼ . 7 ̸鼭 ÿ 9
ѹ ؾ Ѵ.
*/
#include <stdio.h>
int main_0811(void)
{ // 7 : 7 0 & 9 : 9 0
for (int i = 1; i < 100; i++)
{
if(i % 7 == 0)
{
printf("%d\n", i);
}
else if (i % 9 == 0) // else if ϸ if Ծȵȴ
{
printf("%d\n", i);
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "array.h"
Array2D_uint* array_zeros(unsigned int rows, unsigned int columns) {
Array2D_uint* array = malloc(sizeof(Array2D_uint));
array->rows = rows;
array->columns = columns;
array->data = calloc(rows * columns, sizeof(unsigned int));
return array;
}
void array_put_row(Array2D_uint* array, unsigned int* values) {
unsigned int i;
array->rows++;
array->data = realloc(array->data, array->rows * array->columns * sizeof(unsigned int));
for (i = 0; i < array->columns; i++) {
array->data[(array->rows - 1) * array->columns + i] = values[i];
}
}
void array_free(Array2D_uint* array) {
free(array->data);
free(array);
}
void print_array(Array2D_uint* array) {
unsigned int i, j;
for (i = 0; i < array->rows; i++) {
for (j = 0; j < array->columns; j++) {
printf("%u ", array->data[i * array->columns + j]);
}
printf("\n");
}
}
|
C
|
/*
** EPITECH PROJECT, 2018
** My Hunter
** File description:
** my_hunter_duck
*/
#include "my.h"
void check_dead_position(struct sfHunter *sf)
{
if (rand_a_b(0, 2) == 1) {
sf->positionRandom.x = -100;
sfSprite_setPosition(sf->sprite, sf->positionRandom);
} else {
sf->positionRandom.x = 900;
sfSprite_setPosition(sf->sprite, sf->positionRandom);
}
sf->offset.x = 10.0;
sf->offset.y = 20.0;
sfSprite_setRotation(sf->sprite, 0);
sf->loop = 0;
sf->positionText.x = -110;
sf->positionText.y = -110;
sfText_setPosition(sf->text, sf->positionText);
}
void dead_duck(struct sfHunter *sf)
{
if (sf->loop <= 1)
sf->positionText = sfSprite_getPosition(sf->sprite);
sf->loop = 4;
check_loop(sf);
if (sf->angle < 50)
sf->angle = sf->angle + 6;
sfSprite_setRotation(sf->sprite, sf->angle);
}
void alive_duck(struct sfHunter *sf)
{
sf->random = rand_a_b(-20, 20);
sf->positionSprite = sfSprite_getPosition(sf->sprite);
if (sf->positionSprite.y >= 50.0 && sf->positionSprite.y < 300.0)
sf->offset.y += sf->random;
if (sf->positionSprite.y > 300.0 && sf->offset.x != 9.0)
sf->offset.y = -20.0;
if (sf->positionSprite.y < 50.0)
sf->offset.y = 20.0;
}
void check_position(struct sfHunter *sf)
{
if (sf->offset.y == 50.0 && sf->offset.x == 9.0)
dead_duck(sf);
else
alive_duck(sf);
if (sf->positionSprite.y > 1100.0)
check_dead_position(sf);
}
void turn_duck(struct sfHunter *sf)
{
if (sf->random == rand_a_b(0, 20) || sf->positionSprite.x > 700.0) {
if (sf->offset.x != 9.0 && sf->offset.x != 0.0) {
sf->texture = sfTexture_createFromFile(
"images/spritesheet_reversed.png", NULL);
sfSprite_setTexture(sf->sprite, sf->texture, sfFalse);
sf->offset.x = -10.0;
}
}
if (sf->random == rand_a_b(0, 20) || sf->positionSprite.x < 50.0) {
if (sf->offset.x != 9.0 && sf->offset.x != 0.0) {
sf->texture = sfTexture_createFromFile(
"images/spritesheet.png", NULL);
sfSprite_setTexture(sf->sprite, sf->texture, sfFalse);
sf->offset.x = 10.0;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <stdint.h>
//this is the function adding in new file into .tar//
void add_file(FILE *tar, const char* file){
//create an array for header//
char headername[256];
//Fill in the padding and fileaname in the header//
memset(&headername, '\0', 256);
snprintf(headername, 256, "%s", file);
//get size of the fie//
struct stat info;
stat(file, &info);
uint64_t filesize = info.st_size;
//open the input file//
FILE* input_file = fopen( file, "r" );
if( input_file == NULL ){
fprintf( stderr, "wis-tar: Cannot open file: %s\n", file);
exit(1);
}
//write the header and size into .tar//
fwrite( &headername, sizeof(headername), 1, tar );
fwrite( &filesize, 8, 1, tar );
//write the content into .tar//
while( (info.st_size!=0)&&(!feof(input_file)) ){
char buffer[2000];
size_t read = fread( buffer, 1, 2000, input_file );
fwrite( buffer, 1, read, tar);
}
//put the eight null paddings//
int i;
for(i=0;i<8;i++){
fputc('\0', tar);
}
fclose(input_file);
}
int main(int argc, char *argv[]){
//if user did not input correctly in the command line //
if( argc < 3 ) {
fprintf(stderr, "Usage: wis-tar ARCHIVE [FILE ...]\n");
exit(1);
}
//if user did not input correctly in the command line //
FILE* tar_output = fopen( argv[1], "w" );
//if something goes wrong while creating the archive//
if( tar_output == NULL ){
fprintf( stderr, "wis-tar: Cannot create file: %s\n", argv[1] );
exit(1);
}
//call add file function to add the files into .tar//
int i;
for( i = 2; i < argc; ++i ){
add_file(tar_output, argv[i]);
}
fclose(tar_output);
exit(0);
}
|
C
|
#include "holberton.h"
/**
* check_floor - find the root of a square recursively
* @square: square we need to find
* @floor: root to be checked
*
* Return: returns the root of a square
*/
int check_floor(int square, int floor)
{
if (floor * floor == square)
return (floor);
else if (floor * floor < square)
return (check_floor(square, ++floor));
else
return (-1);
}
/**
* _sqrt_recursion - returns the natural square root of a number
* @n: number to check
*
* Return: returns the natural square root of a number
*/
int _sqrt_recursion(int n)
{
int floor = 1;
if (n < 0)
return (-1);
else if (n == 0 || n == 1)
return (1);
else
return (check_floor(n, floor));
}
|
C
|
#include "defines.h"
MY_MATRIX_4X4 MatrixIdentity(void)
{
MY_MATRIX_4X4 identity;
identity.p11 = 1;
identity.p12 = 0;
identity.p13 = 0;
identity.p14 = 0;
identity.p21 = 0;
identity.p22 = 1;
identity.p23 = 0;
identity.p24 = 0;
identity.p31 = 0;
identity.p32 = 0;
identity.p33 = 1;
identity.p34 = 0;
identity.p41 = 0;
identity.p42 = 0;
identity.p43 = 0;
identity.p44 = 1;
return identity;
}
VEC MultiplyVectorByMatrix(VEC V, MY_MATRIX_4X4 M)
{
float x, y, z, w;
x = M.p11 * V.x + M.p21 * V.y + M.p31 * V.z + M.p41 * V.w;
y = M.p12 * V.x + M.p22 * V.y + M.p32 * V.z + M.p42 * V.w;
z = M.p13 * V.x + M.p23 * V.y + M.p33 * V.z + M.p43 * V.w;
w = M.p14 * V.x + M.p24 * V.y + M.p34 * V.z + M.p44 * V.w;
V.x = x;
V.y = y;
V.z = z;
V.w = w;
return V;
}
VEC MultiplyVectorByMatrix(VEC V, MY_MATRIX_3X3 M)
{
float x, y, z;
x = M.p11 * V.x + M.p21 * V.y + M.p31 * V.z;
y = M.p12 * V.x + M.p22 * V.y + M.p32 * V.z;
z = M.p13 * V.x + M.p23 * V.y + M.p33 * V.z;
V.x = x;
V.y = y;
V.z = z;
return V;
}
MY_VERTEX MultiplyVertexByMatrix(MY_VERTEX V, MY_MATRIX_4X4 M)
{
VEC vect;
vect.x = V.axis[0];
vect.y = V.axis[1];
vect.z = V.axis[2];
vect.w = V.axis[3];
V.axis[0] = M.p11 * vect.x + M.p21 * vect.y + M.p31 * vect.z + M.p41 * vect.w;
V.axis[1] = M.p12 * vect.x + M.p22 * vect.y + M.p32 * vect.z + M.p42 * vect.w;
V.axis[2] = M.p13 * vect.x + M.p23 * vect.y + M.p33 * vect.z + M.p43 * vect.w;
V.axis[3] = M.p14 * vect.x + M.p24 * vect.y + M.p34 * vect.z + M.p44 * vect.w;
return V;
}
MY_MATRIX_3X3 MultiplyMatrixByMatrix(MY_MATRIX_3X3 M1, MY_MATRIX_3X3 M2)
{
MY_MATRIX_3X3 newMatrix = { M1.p11 * M2.p11, M1.p12 * M2.p12, M1.p13 * M2.p13,
M1.p21 * M2.p21, M1.p22 * M2.p22, M1.p23 * M2.p23,
M1.p31 * M2.p31, M1.p32 * M2.p32, M1.p33 * M2.p33 };
return newMatrix;
}
MY_MATRIX_4X4 MultiplyMatrixByMatrix4X4(MY_MATRIX_4X4 M1, MY_MATRIX_4X4 M2)
{
MY_MATRIX_4X4 newMatrix = MatrixIdentity();
newMatrix.m[0][0] = M1.m[0][0] * M2.m[0][0] + M1.m[0][1] * M2.m[1][0] + M1.m[0][2] * M2.m[2][0] + M1.m[0][3] * M2.m[3][0];
newMatrix.m[0][1] = M1.m[0][0] * M2.m[0][1] + M1.m[0][1] * M2.m[1][1] + M1.m[0][2] * M2.m[2][1] + M1.m[0][3] * M2.m[3][1];
newMatrix.m[0][2] = M1.m[0][0] * M2.m[0][2] + M1.m[0][1] * M2.m[1][2] + M1.m[0][2] * M2.m[2][2] + M1.m[0][3] * M2.m[3][2];
newMatrix.m[0][3] = M1.m[0][0] * M2.m[0][3] + M1.m[0][1] * M2.m[1][3] + M1.m[0][2] * M2.m[2][3] + M1.m[0][3] * M2.m[3][3];
newMatrix.m[1][0] = M1.m[1][0] * M2.m[1][0] + M1.m[1][1] * M2.m[1][0] + M1.m[1][2] * M2.m[2][0] + M1.m[1][3] * M2.m[3][0];
newMatrix.m[1][1] = M1.m[1][0] * M2.m[1][1] + M1.m[1][1] * M2.m[1][1] + M1.m[1][2] * M2.m[2][1] + M1.m[1][3] * M2.m[3][1];
newMatrix.m[1][2] = M1.m[1][0] * M2.m[1][2] + M1.m[1][1] * M2.m[1][2] + M1.m[1][2] * M2.m[2][2] + M1.m[1][3] * M2.m[3][2];
newMatrix.m[1][3] = M1.m[1][0] * M2.m[1][3] + M1.m[1][1] * M2.m[1][3] + M1.m[1][2] * M2.m[2][3] + M1.m[1][3] * M2.m[3][3];
newMatrix.m[2][0] = M1.m[2][0] * M2.m[2][0] + M1.m[2][1] * M2.m[1][0] + M1.m[2][2] * M2.m[2][0] + M1.m[2][3] * M2.m[3][0];
newMatrix.m[2][1] = M1.m[2][0] * M2.m[2][1] + M1.m[2][1] * M2.m[1][1] + M1.m[2][2] * M2.m[2][1] + M1.m[2][3] * M2.m[3][1];
newMatrix.m[2][2] = M1.m[2][0] * M2.m[2][2] + M1.m[2][1] * M2.m[1][2] + M1.m[2][2] * M2.m[2][2] + M1.m[2][3] * M2.m[3][2];
newMatrix.m[2][3] = M1.m[2][0] * M2.m[2][3] + M1.m[2][1] * M2.m[1][3] + M1.m[2][2] * M2.m[2][3] + M1.m[2][3] * M2.m[3][3];
newMatrix.m[3][0] = M1.m[3][0] * M2.m[3][0] + M1.m[3][1] * M2.m[1][0] + M1.m[3][2] * M2.m[2][0] + M1.m[3][3] * M2.m[3][0];
newMatrix.m[3][1] = M1.m[3][0] * M2.m[3][1] + M1.m[3][1] * M2.m[1][1] + M1.m[3][2] * M2.m[2][1] + M1.m[3][3] * M2.m[3][1];
newMatrix.m[3][2] = M1.m[3][0] * M2.m[3][2] + M1.m[3][1] * M2.m[1][2] + M1.m[3][2] * M2.m[2][2] + M1.m[3][3] * M2.m[3][2];
newMatrix.m[3][3] = M1.m[3][0] * M2.m[3][3] + M1.m[3][1] * M2.m[1][3] + M1.m[3][2] * M2.m[2][3] + M1.m[3][3] * M2.m[3][3];
return newMatrix;
}
MY_MATRIX_4X4 BuidRotationMatrixOnAxisZ(float angle)
{
MY_MATRIX_4X4 identity = MatrixIdentity();
identity.p11 = cos(angle * PI / 180);
identity.p12 = -sin(angle * PI / 180);
identity.p13 = 0;
identity.p21 = sin(angle * PI / 180);
identity.p22 = cos(angle * PI / 180);
identity.p33 = 1;
return identity;
}
MY_MATRIX_4X4 YRotation(float angle)
{
MY_MATRIX_4X4 identity = MatrixIdentity();
identity.p11 = cos(angle * (PI / 180));
identity.p13 = sin(angle * (PI / 180));
identity.p22 = 1;
identity.p31 = -sin(angle * (PI / 180));
identity.p33 = cos(angle * (PI / 180));
identity.p44 = 1;
return identity;
}
MY_MATRIX_4X4 XRotation(float angle)
{
MY_MATRIX_4X4 identity = MatrixIdentity();
identity.p22 = cos(angle * (PI / 180));
identity.p23 = -sin(angle * (PI / 180));
identity.p32 = sin(angle * (PI / 180));
identity.p33 = cos(angle * (PI / 180));
return identity;
}
MY_MATRIX_4X4 BuildProjMatrix(float view, float screenRatio, float n, float f)
{
MY_MATRIX_4X4 m = MatrixIdentity();
m.p11 = screenRatio;
m.p22 = view;
m.p33 = f / (f - n);
m.p34 = 1;
m.p43 = -(f * n) / (f - n);
m.p44 = 0;
return m;
}
void Inverse(MY_MATRIX_4X4& m)
{
MY_MATRIX_3X3 m3;
VEC v;
v.x = m.p41;
v.y = m.p42;
v.z = m.p43;
v.w = 1;
m3.p11 = m.p11;
m3.p12 = m.p21;
m3.p13 = m.p31;
m3.p21 = m.p12;
m3.p22 = m.p22;
m3.p23 = m.p32;
m3.p31 = m.p13;
m3.p32 = m.p23;
m3.p33 = m.p33;
v = MultiplyVectorByMatrix(v, m3);
v.x = -v.x;
v.y = -v.y;
v.z = -v.z;
m.p11 = m3.p11;
m.p12 = m3.p12;
m.p13 = m3.p13;
m.p21 = m3.p21;
m.p22 = m3.p22;
m.p23 = m3.p23;
m.p31 = m3.p31;
m.p32 = m3.p32;
m.p33 = m3.p33;
m.p41 = v.x;
m.p42 = v.y;
m.p43 = v.z;
}
void Translate(MY_MATRIX_4X4 &m, float x, float y, float z)
{
m.p41 = x;
m.p42 = y;
m.p43 = z;
}
void TranslateGlobal(MY_MATRIX_4X4 &m, float x, float y, float z)
{
m.p41 += x;
m.p42 += y;
m.p43 += z;
}
|
C
|
/*
* OpenBOR - http://www.chronocrash.com
* -----------------------------------------------------------------------
* All rights reserved. See LICENSE in OpenBOR root for license details.
*
* Copyright (c) 2004 - 2017 OpenBOR Team
*/
// Attack Properties
// 2017-04-26
// Caskey, Damon V.
//
// Access to attack and attack collision properties.
#include "scriptcommon.h"
// Attack specific properties.
// Caskey, Damon V.
// 2016-10-20
// get_attack_collection(void handle, int frame)
//
// Get item handle for an animation frame. When
// multiple items per frame support is implemented,
// this will return the collection of items. It is therefore
// imperative this function NOT be used to access a single
// item handle directly. You should instead use
// get<item>instance(), and pass it the result from
// this function.
HRESULT openbor_get_attack_collection(ScriptVariant **varlist, ScriptVariant **pretvar, int paramCount)
{
#define SELF_NAME "get_attack_collection(void handle, int frame)"
#define ARG_MINIMUM 2 // Minimum required arguments.
#define ARG_HANDLE 0 // Handle (pointer to property structure).
#define ARG_FRAME 1 // Frame to access.
int result = S_OK; // Success or error?
s_collision_attack **handle = NULL; // Property handle.
int frame = 0; // Property argument.
// Clear pass by reference argument used to send
// property data back to calling script. .
ScriptVariant_Clear(*pretvar);
// Verify incoming arguments. There should at least
// be a pointer for the property handle and an integer
// to determine which frame is accessed.
if(paramCount < ARG_MINIMUM
|| varlist[ARG_HANDLE]->vt != VT_PTR
|| varlist[ARG_FRAME]->vt != VT_INTEGER)
{
*pretvar = NULL;
goto error_local;
}
else
{
handle = (s_collision_attack **)varlist[ARG_HANDLE]->ptrVal;
frame = (LONG)varlist[ARG_FRAME]->lVal;
}
// If this frame has property, send value back to user.
if(handle[frame])
{
ScriptVariant_ChangeType(*pretvar, VT_PTR);
(*pretvar)->ptrVal = handle[frame];
}
return result;
// Error trapping.
error_local:
printf("You must provide a valid handle and frame: " SELF_NAME "\n");
result = E_FAIL;
return result;
#undef SELF_NAME
#undef ARG_MINIMUM
#undef ARG_HANDLE
#undef ARG_FRAME
}
// get_attack_instance(void handle, int index)
//
// Get single item handle from item collection.
// As of 2016-10-30, this function is a placeholder and
// simply returns the handle given. It is in place for future
// support of multiple instances per frame.
HRESULT openbor_get_attack_instance(ScriptVariant **varlist, ScriptVariant **pretvar, int paramCount)
{
#define SELF_NAME "get_attack_instance(void handle, int index)"
#define ARG_MINIMUM 2 // Minimum required arguments.
#define ARG_HANDLE 0 // Handle (pointer to property structure).
#define ARG_INDEX 1 // Index to access.
int result = S_OK; // Success or error?
s_collision_attack *handle = NULL; // Property handle.
//int index = 0; // Property argument.
// Clear pass by reference argument used to send
// property data back to calling script. .
ScriptVariant_Clear(*pretvar);
// Verify incoming arguments. There should at least
// be a pointer for the property handle and an integer
// to determine which index is accessed.
if(paramCount < ARG_MINIMUM
|| varlist[ARG_HANDLE]->vt != VT_PTR
|| varlist[ARG_INDEX]->vt != VT_INTEGER)
{
*pretvar = NULL;
goto error_local;
}
else
{
handle = (s_collision_attack *)varlist[ARG_HANDLE]->ptrVal;
//index = (LONG)varlist[ARG_INDEX]->lVal;
}
// If this index has property, send value back to user.
//if(handle[index])
//{
ScriptVariant_ChangeType(*pretvar, VT_PTR);
//(*pretvar)->ptrVal = handle[index];
(*pretvar)->ptrVal = handle;
//}
return result;
// Error trapping.
error_local:
printf("You must provide a valid handle and index: " SELF_NAME "\n");
result = E_FAIL;
return result;
#undef SELF_NAME
#undef ARG_MINIMUM
#undef ARG_HANDLE
#undef ARG_INDEX
}
// get_attack_property(void handle, int property)
HRESULT openbor_get_attack_property(ScriptVariant **varlist, ScriptVariant **pretvar, int paramCount)
{
#define SELF_NAME "get_attack_property(void handle, int property)"
#define ARG_MINIMUM 2 // Minimum required arguments.
#define ARG_HANDLE 0 // Handle (pointer to property structure).
#define ARG_PROPERTY 1 // Property to access.
int result = S_OK; // Success or error?
s_collision_attack *handle = NULL; // Property handle.
e_attack_properties property = 0; // Property argument.
// Clear pass by reference argument used to send
// property data back to calling script. .
ScriptVariant_Clear(*pretvar);
// Verify incoming arguments. There should at least
// be a pointer for the property handle and an integer
// to determine which property is accessed.
if(paramCount < ARG_MINIMUM
|| varlist[ARG_HANDLE]->vt != VT_PTR
|| varlist[ARG_PROPERTY]->vt != VT_INTEGER)
{
*pretvar = NULL;
goto error_local;
}
else
{
handle = (s_collision_attack *)varlist[ARG_HANDLE]->ptrVal;
property = (LONG)varlist[ARG_PROPERTY]->lVal;
}
// Which property to get?
switch(property)
{
case ATTACK_PROP_BLOCK_COST:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->guardcost;
break;
case ATTACK_PROP_BLOCK_PENETRATE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->no_block;
break;
case ATTACK_PROP_COUNTER:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->counterattack;
break;
case ATTACK_PROP_DAMAGE_FORCE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->attack_force;
break;
case ATTACK_PROP_DAMAGE_LAND_FORCE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->damage_on_landing.attack_force;
break;
case ATTACK_PROP_DAMAGE_LAND_MODE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->blast;
break;
case ATTACK_PROP_DAMAGE_LETHAL_DISABLE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->no_kill;
break;
case ATTACK_PROP_DAMAGE_STEAL:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->steal;
break;
case ATTACK_PROP_DAMAGE_TYPE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->attack_type;
break;
// case ATTACK_PROP_DAMAGE_RECURSIVE_FORCE:
//
// ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
// (*pretvar)->lVal = (LONG)handle->dot_force;
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_INDEX:
//
// ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
// (*pretvar)->lVal = (LONG)handle->dot_index;
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_MODE:
//
// ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
// (*pretvar)->lVal = (LONG)handle->dot;
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_TIME_EXPIRE:
//
// ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
// (*pretvar)->lVal = (LONG)handle->dot_time;
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_TIME_RATE:
//
// ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
// (*pretvar)->lVal = (LONG)handle->dot_rate;
// break;
case ATTACK_PROP_EFFECT_BLOCK_FLASH:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->blockflash;
break;
case ATTACK_PROP_EFFECT_BLOCK_SOUND:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->blocksound;
break;
case ATTACK_PROP_EFFECT_HIT_FLASH:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->hitflash;
break;
case ATTACK_PROP_EFFECT_HIT_FLASH_DISABLE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->no_flash;
break;
case ATTACK_PROP_EFFECT_HIT_SOUND:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->hitsound;
break;
case ATTACK_PROP_GROUND:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->otg;
break;
case ATTACK_PROP_MAP_INDEX:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->forcemap;
break;
case ATTACK_PROP_MAP_TIME:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->maptime;
break;
case ATTACK_PROP_REACTION_FALL_FORCE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->attack_drop;
break;
case ATTACK_PROP_REACTION_FALL_VELOCITY:
// Get memory address of sub structure
// and pass it on as a handle.
ScriptVariant_ChangeType(*pretvar, VT_PTR);
(*pretvar)->ptrVal = (VOID *)&handle->dropv;
break;
case ATTACK_PROP_REACTION_FREEZE_MODE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->freeze;
break;
case ATTACK_PROP_REACTION_FREEZE_TIME:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->freezetime;
break;
case ATTACK_PROP_REACTION_INVINCIBLE_TIME:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->next_hit_time;
break;
case ATTACK_PROP_REACTION_PAIN_SKIP:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->no_pain;
break;
case ATTACK_PROP_REACTION_PAUSE_TIME:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->pause_add;
break;
case ATTACK_PROP_REACTION_REPOSITION_DIRECTION:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->force_direction;
break;
case ATTACK_PROP_REACTION_REPOSITION_DISTANCE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->grab_distance;
break;
case ATTACK_PROP_REACTION_REPOSITION_MODE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->grab;
break;
case ATTACK_PROP_SEAL_COST:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->seal;
break;
case ATTACK_PROP_SEAL_TIME:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->sealtime;
break;
case ATTACK_PROP_STAYDOWN_RISE:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->staydown.rise;
break;
case ATTACK_PROP_STAYDOWN_RISEATTACK:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->staydown.riseattack;
break;
case ATTACK_PROP_TAG:
ScriptVariant_ChangeType(*pretvar, VT_INTEGER);
(*pretvar)->lVal = (LONG)handle->tag;
break;
default:
printf("Unsupported property.\n");
goto error_local;
break;
}
return result;
// Error trapping.
error_local:
printf("You must provide a valid handle and property: " SELF_NAME "\n");
result = E_FAIL;
return result;
#undef SELF_NAME
#undef ARG_MINIMUM
#undef ARG_HANDLE
#undef ARG_PROPERTY
}
// set_attack_property(void handle, int property, value)
HRESULT openbor_set_attack_property(ScriptVariant **varlist, ScriptVariant **pretvar, int paramCount)
{
#define SELF_NAME "set_attack_property(void handle, int property, value)"
#define ARG_MINIMUM 3 // Minimum required arguments.
#define ARG_HANDLE 0 // Handle (pointer to property structure).
#define ARG_PROPERTY 1 // Property to access.
#define ARG_VALUE 2 // New value to apply.
int result = S_OK; // Success or error?
s_collision_attack *handle = NULL; // Property handle.
e_attack_properties property = 0; // Property to access.
// Value carriers to apply on properties after
// taken from argument.
LONG temp_int;
// Verify incoming arguments. There must be a
// pointer for the animation handle, an integer
// property, and a new value to apply.
if(paramCount < ARG_MINIMUM
|| varlist[ARG_HANDLE]->vt != VT_PTR
|| varlist[ARG_PROPERTY]->vt != VT_INTEGER)
{
*pretvar = NULL;
goto error_local;
}
else
{
handle = (s_collision_attack *)varlist[ARG_HANDLE]->ptrVal;
property = (LONG)varlist[ARG_PROPERTY]->lVal;
}
// Which property to modify?
switch(property)
{
case ATTACK_PROP_BLOCK_COST:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->guardcost = temp_int;
}
break;
case ATTACK_PROP_BLOCK_PENETRATE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->no_block = temp_int;
}
break;
case ATTACK_PROP_COUNTER:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->counterattack = temp_int;
}
break;
case ATTACK_PROP_DAMAGE_FORCE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->attack_force = temp_int;
}
break;
case ATTACK_PROP_DAMAGE_LAND_FORCE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->damage_on_landing.attack_force = temp_int;
}
break;
case ATTACK_PROP_DAMAGE_LAND_MODE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->blast = temp_int;
}
break;
case ATTACK_PROP_DAMAGE_LETHAL_DISABLE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->no_kill = temp_int;
}
break;
case ATTACK_PROP_DAMAGE_STEAL:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->steal = temp_int;
}
break;
case ATTACK_PROP_DAMAGE_TYPE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->attack_type = temp_int;
}
break;
// case ATTACK_PROP_DAMAGE_RECURSIVE_FORCE:
//
// if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
// {
// handle->dot_force = temp_int;
// }
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_INDEX:
//
// if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
// {
// handle->dot_index = temp_int;
// }
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_MODE:
//
// if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
// {
// handle->dot = temp_int;
// }
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_TIME_EXPIRE:
//
// if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
// {
// handle->dot_time = temp_int;
// }
// break;
//
// case ATTACK_PROP_DAMAGE_RECURSIVE_TIME_RATE:
//
// if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
// {
// handle->dot_rate = temp_int;
// }
// break;
case ATTACK_PROP_EFFECT_BLOCK_FLASH:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->blockflash = temp_int;
}
break;
case ATTACK_PROP_EFFECT_BLOCK_SOUND:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->blocksound = temp_int;
}
break;
case ATTACK_PROP_EFFECT_HIT_FLASH:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->hitflash = temp_int;
}
break;
case ATTACK_PROP_EFFECT_HIT_FLASH_DISABLE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->no_flash = temp_int;
}
break;
case ATTACK_PROP_EFFECT_HIT_SOUND:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->hitsound = temp_int;
}
break;
case ATTACK_PROP_GROUND:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->otg = temp_int;
}
break;
case ATTACK_PROP_MAP_INDEX:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->forcemap = temp_int;
}
break;
case ATTACK_PROP_MAP_TIME:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->maptime = temp_int;
}
break;
case ATTACK_PROP_REACTION_FALL_FORCE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->attack_drop = temp_int;
}
break;
case ATTACK_PROP_REACTION_FALL_VELOCITY:
// Reassign sub structure memory address
// to new handle.
handle->dropv = *(s_axis_principal_float *)varlist[ARG_VALUE]->ptrVal;
break;
case ATTACK_PROP_REACTION_FREEZE_MODE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->freeze = temp_int;
}
break;
case ATTACK_PROP_REACTION_FREEZE_TIME:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->freezetime = temp_int;
}
break;
case ATTACK_PROP_REACTION_INVINCIBLE_TIME:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->next_hit_time = temp_int;
}
break;
case ATTACK_PROP_REACTION_PAIN_SKIP:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->no_pain = temp_int;
}
break;
case ATTACK_PROP_REACTION_PAUSE_TIME:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->pause_add = temp_int;
}
break;
case ATTACK_PROP_REACTION_REPOSITION_DIRECTION:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->force_direction = temp_int;
}
break;
case ATTACK_PROP_REACTION_REPOSITION_DISTANCE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->grab_distance = temp_int;
}
break;
case ATTACK_PROP_REACTION_REPOSITION_MODE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->grab = temp_int;
}
break;
case ATTACK_PROP_SEAL_COST:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->seal = temp_int;
}
break;
case ATTACK_PROP_SEAL_TIME:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->sealtime = temp_int;
}
break;
case ATTACK_PROP_STAYDOWN_RISE:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->staydown.rise = temp_int;
}
break;
case ATTACK_PROP_STAYDOWN_RISEATTACK:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->staydown.riseattack = temp_int;
}
break;
case ATTACK_PROP_TAG:
if(SUCCEEDED(ScriptVariant_IntegerValue(varlist[ARG_VALUE], &temp_int)))
{
handle->tag = temp_int;
}
break;
default:
printf("Unsupported property.\n");
goto error_local;
break;
}
return result;
// Error trapping.
error_local:
printf("You must provide a valid handle, property, and new value: " SELF_NAME "\n");
result = E_FAIL;
return result;
#undef SELF_NAME
#undef ARG_MINIMUM
#undef ARG_HANDLE
#undef ARG_PROPERTY
#undef ARG_VALUE
}
|
C
|
/*
SELECTION SORT ALGORITHM SORTS AN ARRAY BY REPEATELY FINDING THE MINIMUM ELEMENT (CONSIDERING ASCENDING ORDER) FROM UNSORTED PART AND PUTTING IT AT THE BEGINNNING.
THE ALGORITHM MAINTAINS TWO SUBARRAYS IN A GIVEN ARRAY
1-THE SUBARRAY WHICH IS ALREADY SORTED
2-REMAINING SUBARRAY WHICH IS UNSORTED
IN EVERY INTERATION OF SELECTION SORT, THE MINIMUM ELEMENT FROM THE UNSORTED SUBARRAY IS PICKED AND MOVED TO THE SORTED SUBARRAY.
LOGIC: ARRAY IS CONSIDERED INTO TWO PARTS UNSORTED AND SORTED (INITIALLY WHOLE ARRAY IS UNSORTED)
SELECTION 1. SELECT THE LOWEST ELEMENT IN THE REMAINING ARRAY
SWAPPING 2. BRING IT TO THE STARTING POSITION
TIME COMPLEXITY: O(N^2)
THE GOOD THING ABOUT SELECITON SORT IS IT NEVER MAKES MORE THAN O(N) SWAPS AND CAN BE USEFUL WHEN MEMORY WRITE IS A COSTLY OPERATION
*/
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Acha o menor elemento de um array desordenado
min_idx = i;
for (j = i+1; j < n; j++)
{
if (arr[j] < arr[min_idx])
min_idx = j;
}
// Troca o elemento de menor valor achado pela primeira posição
swap(&arr[min_idx], &arr[i]);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(int arg_count, char* arg_list[])
{
int i;
printf("There were %d arguments provided:\n", arg_count);
for (i=0;i<arg_count;i++)
printf("arguemnt #%d\t-\t%s\n", i, arg_list[i]);
}
|
C
|
#include "communicator.h"
#include <stdio.h>
int SaveMessageToLog(PMARK_EVENT evt)
{
printf("%x: PID:%6x, PPID:%6x, TID:%6x, OPERATION=%s.%s, FLAGS=%8x, USERNAME=%S, PATH=%S, IMAGE=%S, PROCESS=%S\n",
evt->time,
evt->pid,
evt->ppid,
evt->tid,
evt->opclass == MARK_OPCLASS_PROCESS ? "PROCESS " : evt->opclass == MARK_OPCLASS_REGISTRY ? "REGISTRY" :
evt->opclass == MARK_OPCLASS_PACKET ? "NETWORK " : evt->opclass == MARK_OPCLASS_FILE ? "FILE " : "UNKNOWN ",
evt->optype == MARK_OPTYPE_CREATE ? "CREATE " : evt->optype == MARK_OPTYPE_DESTROY ? "DESTROY" :
evt->optype == MARK_OPTYPE_RENAME ? "RENAME " : evt->optype == MARK_OPTYPE_WRITE ? "WRITE " : "UNKNOWN",
evt->flags,
evt->szUserName,
evt->szOperationPath,
evt->szImagePath,
evt->szProcessName
);
return 1;
}
|
C
|
/**
* @file main.c
* @author ln-dev05 ([email protected])
* @brief Sokoban inspired by Openclassroom C course
* @version 0.1
*
* @copyright Copyright (c) 2021
*
*/
#include "constantes.h"
#include "editeur.h"
#include "jeu.h"
#include "utils.h"
int main(int argc, char *argv[]) {
SDL_Surface *ecran;
SDL_Surface *menu;
SDL_Rect position_menu = {0, 0, 0, 0};
SDL_Event event;
manage_input(argc, argv);
ecran = set_up();
menu = IMG_Load(IMG_MENU);
while (1) {
SDL_WaitEvent(&event);
switch (event.type) {
case SDL_QUIT:
goto _exit;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
goto _exit;
case SDLK_KP1:
jouer(ecran);
break;
case SDLK_KP2:
editeur(ecran);
break;
}
break;
}
clear_screen(ecran);
SDL_BlitSurface(menu, NULL, ecran, &position_menu);
SDL_Flip(ecran);
}
_exit:
SDL_FreeSurface(menu);
SDL_FreeSurface(ecran);
SDL_Quit();
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{ int num1,num2,num3,result;
printf("enter theree numbers\n");
scanf("%d%d%d",&num1,&num2,&num3);
if(num1<num2){
if (num2<num3){
result= num3;
}
else
result = num2;
}
else{
if (num1<num3){
result = num3;
}
else
result = num1;
}
printf("%d",result);
return 0;
}
|
C
|
#include "holberton.h"
/**
* times_table - prints the times table
* Return: void
*
*/
void times_table(void)
{
int i, j, r;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
r = i * j;
if (j > 0 && j < 10)
{
_putchar(44);
_putchar(32);
if (r < 10)
{
_putchar(32);
}
}
if (r < 10)
{
_putchar(r + '0');
}
else
{
_putchar(r / 10 + '0');
_putchar(r % 10 + '0');
}
}
_putchar(10);
}
}
|
C
|
#include <stdio.h>
#include <math.h>
#include "exercice4.h"
static float Sommecarre(int n){
float p = 0;
float k = 0;
for(k=0; k <n+1; k++){
p=p+(1/(k*k+k));
}
return(p);
}
/* int ask_int(char* q){ */
/* //ask question */
/* while(*q != '\0'){ */
/* printf("%c", *q); */
/* q++; */
/* } */
/* //get answer */
/* int answer; */
/* scanf("%d", &answer); */
/* return answer; */
/* } */
int main(void){
int n = ask_int("How many iterrations of Sommecarre would you like?\n");
printf("result: %f\n", Sommecarre(n));
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct Polynomial
{
float coef;
int expn;
struct Polynomial *next;
}Polynomial,*Polyn;
Polyn CreatePoly()
{
Polynomial *head,*rear,*s;
int c,e,n;
head=(Polynomial *)malloc(sizeof(Polynomial));
rear = head;
scanf("%d\n",&n);
for(int i=1;i<=n;i++)
{
scanf("\n(%d,%d)",&c,&e);
s=(Polynomial *)malloc(sizeof(Polynomial));
s->coef=c;
s->expn=e;
rear->next=s;
rear=s;
}
rear->next=NULL;
return(head);
}
void PrintPolyn(Polyn P)
{
Polyn q=P->next;
int flag=1;
if(!q)
{
putchar('0');
printf("\n");
return ;
}
while(q)
{
if(q->coef>0&&flag!=1) putchar('+');
if(q->coef!=1&&q->coef!=-1)
{
printf("%g",q->coef);
if(q->expn==1) putchar('X');
else if(q->expn) printf("X^%d",q->expn);
}
else
{
if(q->coef==1)
{
if(!q->expn) putchar('1');
else if(q->expn==1) putchar('X');
else printf("X^%d",q->expn);
}
}
q=q->next;
flag++;
}
printf("\n");
}
Polyn DerivatPolyn(Polyn P)
{
Polyn q=P->next;
Polyn ddd,qqq,H;
qqq=(Polyn)malloc(sizeof(struct Polynomial));
qqq->next=NULL;
H=qqq;
while(q!=NULL)
{
ddd=(Polyn)malloc(sizeof(struct Polynomial));
if(q->coef!=0)
{
if(q->expn==0)
{
ddd->coef=0;
ddd->expn=0;
}
else
{
ddd->coef=q->coef*q->expn;
ddd->expn=q->expn-1;
}
}
if(ddd->coef!=0)
{
qqq->next=ddd;
qqq=ddd;
}
q=q->next;
}
qqq->next=NULL;
return H;
}int main()
{
Polynomial *head1,*head2,*headc;
head1=CreatePoly();
head2=CreatePoly();
headc=DerivatPolyn(head1);
PrintPolyn(headc);
}
|
C
|
/*
* Event Dispatcher
*
* This event dispatcher provides a simple wrapper around edge-triggered epoll.
* It consists of a DispatchContext to represent the epoll-set, and a
* DispatchFile for each file-descriptor added to that epoll-set. All events
* are delivered in edge-triggered mode and cached in the DispatchFile. By
* default, this means that we will get woken up for each event once, and cache
* it. Since we don't use level-triggered mode, a continuous unhandled event
* will not cause any further wakeups, unless the event is triggered by the
* kernel again.
*
* On top of this edge-triggered mirror of the kernel space, we provide a
* level-triggered callback mechanism. That is, on each dispatch-file you can
* `select` and `deselect` events you're interested in. As long as an event is
* selected, you will get notified of it in level-triggered mode (that is,
* until you handled it). Since our cache is distinct from the kernel data, we
* need explicit notification of when an event is handled. Therefore, you must
* clear any event when you handled it. This usually means catching EAGAIN
* and then clearing the event.
*
* Every DispatchFile has 3 event masks:
*
* * kernel_mask: This mask is constant and must be provided at
* initialization time. It describes the events that we
* asked the kernel to report via epoll_ctl(2). For
* performance reasons we never modify this mask. If there
* ever arises a need to update this mask according to our
* user-mask, this can be added later on.
*
* * user_mask: This mask reflects the events that the user selected and
* thus is interested in. It must always be a subset of
* @kernel_mask. As long as an event is set in the event-mask
* and in @user_mask, its callback will be invoked in a
* level-triggered manner.
*
* * events: This mask reflects the events the kernel signalled. That is,
* those events are always a subset of @kernel_mask and cached as
* soon as the kernel signalled them.
* You must explicitly clear events once you handled them. The
* kernel never tells us about falling edges, so we must detect
* them manually (usually via EAGAIN).
*/
#include <c-list.h>
#include <c-stdaux.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include "util/dispatch.h"
#include "util/error.h"
/**
* dispatch_file_init() - initialize dispatch file
* @file: dispatch file
* @ctx: dispatch context
* @fn: callback function
* @fd: file descriptor
* @mask: EPOLL* event mask
* @events: initial EPOLL* event mask before calling into the kernel
*
* This initializes a new dispatch-file and registers it with the given
* dispatch-context. The file-descriptor @fd is added to the epoll-set of @ctx
* with the event mask @mask.
*
* Note that all event handling is always edge-triggered. Hence, EPOLLET must
* not be passed in @mask, but is added automatically. Furthermore, the event
* mask in @mask is used to select kernel events for edge-triggered mode. To
* actually get notified via your callback, you must select the user-mask via
* dispatch_file_select().
*
* The file-descriptor @fd is *NOT* consumed by this function. That is, the
* caller still owns it, and is responsible to close it when done. However, the
* caller must make sure to call dispatch_file_deinit() *BEFORE* closing the
* FD.
*
* Return: 0 on success, negative error code on failure.
*/
int dispatch_file_init(DispatchFile *file,
DispatchContext *ctx,
DispatchFn fn,
int fd,
uint32_t mask,
uint32_t events) {
int r;
c_assert(!(mask & EPOLLET));
c_assert(!(events & ~mask));
r = epoll_ctl(ctx->epoll_fd,
EPOLL_CTL_ADD,
fd,
&(struct epoll_event) {
.events = mask | EPOLLET,
.data.ptr = file,
});
if (r < 0)
return error_origin(-errno);
file->context = ctx;
file->ready_link = (CList)C_LIST_INIT(file->ready_link);
file->fn = fn;
file->fd = fd;
file->user_mask = 0;
file->kernel_mask = mask;
file->events = events;
++file->context->n_files;
return 0;
}
/**
* dispatch_file_deinit() - deinitialize dispatch file
* @file: dispatch file
*
* This deinitialized the dispatch-file @file and unregisters it from its
* context. The file is put into a deinitialized state, hence, it is safe to
* call this function multiple times.
*
* The file-descriptor provided via dispatch_file_init() is *NOT* closed, but
* left unchanged. However, the caller must make sure to call
* dispatch_file_deinit() *BEFORE* closing the FD.
*/
void dispatch_file_deinit(DispatchFile *file) {
int r;
if (file->context) {
/*
* There is no excuse to ever skip EPOLL_CTL_DEL. Epoll
* descriptors are not tied to FDs, but rather combinations of
* file+fd. Only if the file-description (sic) is destroyed, an
* epoll description is removed from the epoll set. Hence, we
* have no way to know whether this FD is the only FD for the
* given file-description. Nor do we know whether the caller
* intends to continue using the FD.
*
* Therefore, we always unconditionally remove FDs from the
* epoll-set, and require it to succeed. If the removal fails,
* you did something wrong and better fix it.
*/
r = epoll_ctl(file->context->epoll_fd, EPOLL_CTL_DEL, file->fd, NULL);
c_assert(r >= 0);
--file->context->n_files;
c_list_unlink(&file->ready_link);
}
file->fd = -1;
file->fn = NULL;
file->context = NULL;
}
/**
* dispatch_file_select() - select notification mask
* @file: dispatch file
* @mask: event mask
*
* This selects the events specified in @mask for notification. That is, if
* those events are signalled by the kernel, the callback of @file will be
* invoked for those events.
*
* Once you lost interest in a given event, you must deselect it via
* dispatch_file_deselect(). Otherwise, you will keep being notified of the
* event.
*
* Once you handled an event fully, you must clear it via dispatch_file_clear()
* to tell the dispatcher that you should only be invoked for the event
* when the kernel signals it again.
*/
void dispatch_file_select(DispatchFile *file, uint32_t mask) {
c_assert(!(mask & ~file->kernel_mask));
file->user_mask |= mask;
if ((file->user_mask & file->events) && !c_list_is_linked(&file->ready_link))
c_list_link_tail(&file->context->ready_list, &file->ready_link);
}
/**
* dispatch_file_deselect() - deselect notification mask
* @file: dispatch file
* @mask: event mask
*
* This is the inverse of dispatch_file_select() and removes a given event mask
* from the user-mask. The callback will no longer be invoked for those events.
*/
void dispatch_file_deselect(DispatchFile *file, uint32_t mask) {
c_assert(!(mask & ~file->kernel_mask));
file->user_mask &= ~mask;
if (!(file->events & file->user_mask))
c_list_unlink(&file->ready_link);
}
/**
* dispatch_file_clear() - clear kernel event mask
* @file: dispatch file
* @mask: event mask
*
* This clears the events in @mask from the pending kernel event mask. That is,
* those events are now considered as 'handled'. The kernel must notify us of
* them again to reconsider them.
*/
void dispatch_file_clear(DispatchFile *file, uint32_t mask) {
c_assert(!(mask & ~file->kernel_mask));
file->events &= ~mask;
if (!(file->events & file->user_mask))
c_list_unlink(&file->ready_link);
}
/**
* dispatch_context_init() - initialize dispatch context
* @ctx: dispatch context
*
* This initializes a new dispatch context.
*
* Return: 0 on success, negative error code on failure.
*/
int dispatch_context_init(DispatchContext *ctx) {
*ctx = (DispatchContext)DISPATCH_CONTEXT_NULL(*ctx);
ctx->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (ctx->epoll_fd < 0)
return error_origin(-errno);
return 0;
}
/**
* dispatch_context_deinit() - deinitialize dispatch context
* @ctx: dispatch context
*
* This deinitializes a dispatch context. The caller must make sure no
* dispatch-file is registered on it.
*
* The context will be set into an deinitialized state afterwards. Hence, it is
* safe to call this function multiple times.
*/
void dispatch_context_deinit(DispatchContext *ctx) {
c_assert(!ctx->n_files);
c_assert(c_list_is_empty(&ctx->ready_list));
ctx->epoll_fd = c_close(ctx->epoll_fd);
}
/**
* dispatch_context_poll() - fetch events from kernel
* @ctx: dispatch context
* @timeout: poll timeout
*
* This calls into epoll_wait(2) to fetch events on all registered
* dispatch-files from the kernel. @timeout is passed unmodified to
* epoll_wait().
*
* The events fetched from the kernel are merged into our list of
* dispatch-files. Nothing is dispatched! The data is merely fetched from the
* kernel.
*
* Return: 0 on success, negative error code on failure.
*/
int dispatch_context_poll(DispatchContext *ctx, int timeout) {
_c_cleanup_(c_freep) void *buffer = NULL;
struct epoll_event *events, *e;
DispatchFile *f;
size_t n;
int r;
n = ctx->n_files * sizeof(*events);
if (n > 128UL * 1024UL) {
buffer = malloc(n);
if (!buffer)
return error_origin(-ENOMEM);
events = buffer;
} else {
events = alloca(n);
}
r = epoll_wait(ctx->epoll_fd, events, ctx->n_files, timeout);
if (r < 0) {
if (errno == EINTR)
return 0;
return error_origin(-errno);
}
while (r > 0) {
e = &events[--r];
f = e->data.ptr;
c_assert(f->context == ctx);
f->events |= e->events & f->kernel_mask;
if ((f->events & f->user_mask) && !c_list_is_linked(&f->ready_link))
c_list_link_tail(&f->context->ready_list, &f->ready_link);
}
return 0;
}
/**
* dispatch_context_dispatch() - dispatch pending events
* @ctx: dispatch context
*
* This runs one dispatch round on the given dispatch context. That is, it
* dispatches all pending events and calls into the callbacks of the respective
* dispatch-file.
*
* The first non-zero return code of any dispatch-file callback will break the
* loop and cause a propagation of that error code to the caller.
*
* Return: 0 on success, otherwise the first non-zero return code of any
* dispatched file stops dispatching and is returned unmodified.
*/
int dispatch_context_dispatch(DispatchContext *ctx) {
CList todo = (CList)C_LIST_INIT(todo);
DispatchFile *file;
int r;
r = dispatch_context_poll(ctx, c_list_is_empty(&ctx->ready_list) ? -1 : 0);
if (r)
return error_fold(r);
/*
* We want to dispatch @ctx->ready_list exactly once here. The trivial
* approach would be to iterate it via c_list_for_each(). However, we
* want to allow callbacks to modify their event masks, so we must
* allow them to add and remove files arbitrarily. At the same time, we
* want to prevent dispatching a single file twice, so we must make
* sure to detect detach+reattach cycles to avoid starvation.
*
* Therefore, we simply fetch the entire ready-list into @todo and
* handle it one-by-one, moving them back onto the ready-list. This is
* safe against entry-removal in the callbacks, and it has a clearly
* determined runtime.
*/
c_list_swap(&todo, &ctx->ready_list);
while ((file = c_list_first_entry(&todo, DispatchFile, ready_link))) {
c_list_unlink(&file->ready_link);
c_list_link_tail(&ctx->ready_list, &file->ready_link);
r = file->fn(file);
if (error_trace(r)) {
c_list_splice(&ctx->ready_list, &todo);
break;
}
}
c_assert(c_list_is_empty(&todo));
return r;
}
|
C
|
#include "libs.h"
void gauss_m(int n, double *matrix_now, double *x) {
double *matrix = malloc(sizeof(double *) * n * (n+1));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n + 1; j++) {
matrix[i*(n + 1) + j] = matrix_now[i*(n + 1) + j];
}
}
double max_elem;
int max_index;
const double eps = 0.000001;
for (int k = 0; k < n; k++) {
max_elem = fabs(matrix[k*(n + 1) + k]);
max_index = k;
for (int i = k + 1; i < n; i++) {
if (max_elem < fabs(matrix[i*(n + 1) + k])) {
max_elem = fabs(matrix[i*(n + 1) + k]);
max_index = i;
}
}
if (max_elem < eps) {
return;
}
for (int j = 0; j < n + 1; j++) {
double tmp = matrix[k*(n + 1) + j];
matrix[k*(n + 1) + j] = matrix[max_index*(n + 1) + j];
matrix[max_index*(n + 1) + j] = tmp;
}
for (int i = k; i < n; i++) {
double tmp = matrix[i*(n + 1) + k];
if (fabs(tmp) < eps) continue;
for (int j = 0; j < n + 1; j++)
matrix[i*(n + 1) + j] = matrix[i*(n + 1) + j] / tmp;
if (i == k) continue;
for (int j = 0; j < n + 1; j++)
matrix[i*(n + 1) + j] = matrix[i*(n + 1) + j] - matrix[k*(n + 1) + j];
}
}
for (int k = n - 1; k >= 0; k--) {
x[k] = matrix[k*(n + 1) + n];
for (int i = 0; i < k; i++)
matrix[i*(n + 1) + n] = matrix[i*(n + 1) + n] - matrix[i*(n + 1) + k] * x[k];
}
free(matrix);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** env
** File description:
** func for env
*/
#include "my.h"
#include "minishell.h"
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
int unsetenv_error(char **env, char **input)
{
if (!env || !input) {
return (84);
}
if (input && input[0] && !input[1]) {
my_printf("%s: Too few arguments.\n", input[0]);
return (84);
}
return (0);
}
int is_in_env(char *input, char **env)
{
char *tmp = my_strcat(input, "=");
int idx = -1;
if (!tmp || !input)
return (idx);
idx = find_env(env, tmp);
return (idx);
}
char **dup_unsetenv(char **env, int unseted_var_nb)
{
int i = 0;
int j = 0;
char **new_env = malloc(sizeof(char *) *
(my_arrlen(env) - unseted_var_nb + 1));
if (!env || !new_env)
return (NULL);
while (env[i]) {
if (env[i][0] != -1) {
new_env[j] = my_strdup(env[i]);
j++;
}
i++;
}
new_env[j] = NULL;
free_env(env);
free(env);
return (new_env);
}
int unset_env(char **input, char ***env)
{
int input_idx = 1;
int env_idx = 0;
int unseted_var_nb = 0;
if (unsetenv_error(*env, input) == 84)
return (84);
while (input[input_idx]) {
env_idx = is_in_env(input[input_idx], *env);
if (env_idx != -1) {
(*env)[env_idx][0] = -1;
unseted_var_nb++;
}
input_idx++;
}
*env = dup_unsetenv(*env, unseted_var_nb);
return (1);
}
|
C
|
// 618p 1
#include <stdio.h>
int main()
{
FILE* pInputStream = NULL;
fopen_s(&pInputStream, "a.txt", "rt");
if (!pInputStream)
return 1;
FILE* pOutputStream = NULL;
fopen_s(&pOutputStream, "b.bin", "wb");
if (!pOutputStream)
return 2;
int num = 0;
while (fscanf_s(pInputStream, "%d", &num) != EOF)
fwrite(&num, sizeof(num), 1, pOutputStream);
const long INPUT_STREAM_SIZE = ftell(pInputStream);
const long OUTPUT_STREAM_SIZE = ftell(pOutputStream);
printf("Է ũ: %ld\n", INPUT_STREAM_SIZE);
printf(" ũ: %ld\n", OUTPUT_STREAM_SIZE);
return 0;
}
|
C
|
/*
* Auther : Atul R. Raut
* Date : Fri Dec 23, 2011, 09.30PM
* Aim : WAP, a pointer version fo the functoin strcat.
* strcat(s, t), copies the string t to the end of s.
*
***/
#include <stdio.h>
char* aStrcat (char *src, char *target);
int main () {
char *s = "Atul";
char *t = "Raut";
char *r = NULL;
r = aStrcat (s, t);
printf ("\n111");
*r = '\0';
printf ("\nr == %c\n", *r);
}
char* aStrcat (char *s, char *t) {
printf ("\ns = %s, t= %s \n", s, t);
while (*s != '\0')
s++;
printf ("\n000111");
while (*s++ = *t++)
;
printf ("\n000");
return s;
}
|
C
|
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
#define gc getchar
#define ll long long int
#define M 1000000007
#define scan(t) t=input()
inline ll input() {
char c = gc();
while(c<'0' || c>'9') c = gc();
ll ret = 0;
while(c>='0' && c<='9') {
ret = 10 * ret + c - 48;
c = gc();
}
return ret;
}
ll pw(ll a, ll b,ll p){
ll r;
if(b==0) return 1;
r = pw(a,b/2,p);
r = (r*r)%p;
if(b%2) r = (r*a)%p;
return r;
}
int main()
{
ll t,product,n,i,p,y;
scanf("%lld",&t);
while(t--)
{
product=1;
scanf("%lld %lld",&n,&p);
if(n>=p/3.0)
printf("0\n");
else
{
for(i=1;i<=3*n;i++)
{
product=(product*i)%p;
}
y=pw(6,p-2,p);
y=pw(y,n,p);
product*=y;
printf("%lld\n",product%p);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <alchemy/task.h>
RT_TASK hello_task;
// function to be executed by task
void helloWorld(void *arg)
{
RT_TASK_INFO curtaskinfo;
printf("Hello World!\n");
// inquire current task
rt_task_inquire(NULL,&curtaskinfo);
// print task name
printf("Task name : %s \n", curtaskinfo.name);
}
int main(int argc, char* argv[])
{
char str[10] ;
printf("start task\n");
sprintf(str,"hello");
/* Create task
* Arguments: &task,
* name,
* stack size (0=default),
* priority,
* mode (FPU, start suspended, ...)
*/
rt_task_create(&hello_task, str, 0, 50, 0);
/* Start task
* Arguments: &task,
* task function,
* function argument
*/
rt_task_start(&hello_task, &helloWorld, 0);
}
|
C
|
#include "../includes/corewar.h"
#include <fcntl.h>
#include <stdio.h>
t_obj *initialize_obj(void)
{
t_obj *c;
int i;
i = 0;
c = ft_memalloc(sizeof(t_obj));
c->arena = ft_memalloc(sizeof(unsigned char *) * MEM_SIZE);
while (i < MEM_SIZE)
{
c->arena[i] = 0;
i++;
}
return (c);
}
void ft_puthex(unsigned char c)
{
char *tab;
tab = "0123456789abcdef";
ft_putchar(tab[c / 16]);
ft_putchar(tab[c % 16]);
}
void ft_append(t_players** head, unsigned char *new_data)
{
t_players *new_node;
t_players *last;
int i;
unsigned int j;
i = 4;
j = 0;
new_node = ft_memalloc(sizeof(t_players));
last = *head;
while (j < 129)
{
new_node->info.prog_name[j] = new_data[i];
i++;
j++;
}
i += 6;
new_node->info.prog_size = new_data[i];
i++;
j = 0;
while (j < 2049)
{
new_node->info.comment[j] = new_data[i];
i++;
j++;
}
i += 3;
j = 0;
new_node->code = &new_data[i];
new_node->next = NULL;
if (*head == NULL)
{
*head = new_node;
return ;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return ;
}
// void load_players(t_players *pl, t_obj *c)
// {
// }
void ft_puthex2(int c)
{
char *tab;
tab = "0123456789abcdef";
ft_putchar(tab[((c / 16 / 16) / 16)]);
ft_putchar(tab[((c / 16) / 16)]);
ft_putchar(tab[(c / 16) % 16]);
ft_putchar(tab[c % 16]);
}
void *ft_write_to(void *arena, void *code, size_t start, size_t size)
{
unsigned char *d;
unsigned char *s;
size_t i;
d = (unsigned char *)arena;
s = (unsigned char *)code;
i = 0;
while (i < size)
{
d[start + i] = s[i];
i++;
}
return (arena);
}
void ft_print_dump(t_obj *c)
{
int x;
int y;
int i;
x = 1;
y = 0;
i = 0;
ft_putstr("0x");
ft_puthex2(i);
ft_putstr(" : ");
while (i < MEM_SIZE)
{
ft_puthex(c->arena[i]);
if (i < MEM_SIZE - 1)
ft_putchar(' ');
if (x == 64)
{
if (i < MEM_SIZE - 1)
{
ft_putchar('\n');
ft_putstr("0x");
// ft_putnbr(i);
ft_puthex2(i + 1);
ft_putstr(" : ");
}
x = 0;
}
x++;
i++;
}
}
void ft_load_champions(t_obj *c)
{
int i;
int offset;
t_players *pl;
i = 0;
pl = c->worriors;
offset = MEM_SIZE / c->no_of_worriors;
while (i < c->no_of_worriors)
{
pl->pc = offset * i;
pl->cool_time = 0;
ft_write_to(c->arena, pl->code, offset * i, pl->info.prog_size);
pl = pl->next;
i++;
}
}
void ft_read_champions(t_obj *c, int ac, char **av)
{
int i;
unsigned char *line;
int fd;
int j;
i = 0;
fd = 0;
c->no_of_worriors = 0;
line = NULL;
while (i < ac)
{
fd = open(av[i], O_RDONLY);
j = ft_read_memory(fd, &line);
ft_append(&c->worriors, line);
c->no_of_worriors++;
i++;
}
}
int main(int ac, char **av)
{
t_obj *c;
if (ac < 2)
{
ft_putendl("Usage: ./corewar [-dump numbers_of_cycles] [ [-a load_address] champion1.cor] ...");
return (0);
}
c = initialize_obj();
if (ft_strequ(av[1], "-dump"))
{
if (!ft_isnumber(av[2]))
{
ft_putendl("Usage: ./corewar [-dump numbers_of_cycles] [ [-a load_address] champion1.cor] ...");
return (0);
}
ft_read_champions(c, ac - 3, &av[3]);
ft_load_champions(c);
ft_print_dump(c);
}
else
{
ft_read_champions(c, ac - 1, &av[1]);
ft_load_champions(c);
}
// ft_putendl(pl->info->prog_name);
return (1);
}
|
C
|
//SERVER.C
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <ctype.h>
#define SERVER_TCP_PORT 3000 /* well-known port */
#define BUFLEN 150 /* buffer length */
int service(int);
void reaper(int);
void preparepdu (char, int, char [],char []);
void sendpdu(int, char []);
int returnlength(char []);
void responder(int);
void upload (int, char []);
void download(int,char []);
void getonlydata(char [],char []);
void changedirectory(int,char []);
void listfiles(int, char []);
int main(int argc, char **argv)
{
int sd, new_sd, client_len, port;
struct sockaddr_in server, client;
switch(argc){
case 1:
port = SERVER_TCP_PORT;
break;
case 2:
port = atoi(argv[1]);
break;
default:
fprintf(stderr, "Usage: %d [port]\n", argv[0]);
exit(1);
}
/* Create a stream socket */
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
fprintf(stderr, "Can't creat a socket\n");
exit(1);
}
/* Bind an address to the socket */
bzero((char *)&server, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sd, (struct sockaddr *)&server, sizeof(server)) == -1){
fprintf(stderr, "Can't bind name to socket\n");
exit(1);
}
/* queue up to 5 connect requests */
listen(sd, 5);
(void) signal(SIGCHLD, reaper);
while(1) {
client_len = sizeof(client);
new_sd = accept(sd, (struct sockaddr *)&client, &client_len);
if(new_sd < 0){
fprintf(stderr, "Can't accept client \n");
exit(1);
}
switch (fork()){
case 0: /* child */
(void) close(sd);
exit(service(new_sd));
default: /* parent */
(void) close(new_sd);
break;
case -1:
fprintf(stderr, "fork: error\n");
}
}
}
/* service program */
int service(int sd)
{
while (1){
responder(sd);
}
return(0);
}
void responder (int sd)
{
int n1=0,n2=0,n3=0,n4=0;
int i1=0,i2=0,i3=0,i4=0;
int len_of_data=0,len1=0,len2=0,len3=0;
char rbuf[BUFLEN];
char file_name[146],dir_path[146],dir_path1[146];
bzero(rbuf,sizeof(rbuf));bzero(file_name,sizeof(file_name)); //clearing buffers
n1 = recv(sd, rbuf, BUFLEN, 0);//read client request
printf("what did i receive: %s\n",rbuf);
printf("what is n1: %d\n",n1);
if (n1<0){
printf("error reading from socket\n");
exit(0);
}
bzero(file_name,sizeof(file_name));
if(rbuf[0]== 'D'){ //client wants to download
len_of_data = returnlength(rbuf);
printf("len_of_data : %d\n",len_of_data);
for (i1;i1<len_of_data;i1++){
file_name[i1] = rbuf[i1+4];
}
printf("file name : %s\n",file_name);
printf("strlen(file_name): %d\n",strlen(file_name));
download(sd,file_name);
}
else if(rbuf[0] == 'U'){ //Client wants to upload
len1=returnlength(rbuf);
for (i2;i2<len1;i2++)
file_name[i2] = rbuf[i2+4];
printf("Uploading file name: %s\n",file_name);
upload(sd,file_name);
}
else if (rbuf[0] == 'P'){ //client wants to change directory
len2 = returnlength(rbuf);
printf("what is len2: %d\n",len2);
bzero(dir_path,sizeof(dir_path));
for (i3;i3<len2;i3++){
dir_path[i3] = rbuf[i3+4];
}
printf("Client specify cd to: %s \n", dir_path);
changedirectory(sd,dir_path);
}
else if (rbuf[0] == 'L'){//client wants to list files in directory
len3=returnlength(rbuf);
for (i4;i4<len3;i4++){
dir_path1[i4] = rbuf[i4+4];
}
listfiles(sd,dir_path1);
}
}
void download(int sd, char file_name[])
{
FILE *fp1;
int len1=0,bytes_read=0;
char dbuf1[146],sbuf[BUFLEN];
char errormsg[146] = "File doesn't exist";
int len2=strlen(errormsg);
if ((fp1 = fopen (file_name, "r")) == NULL){
preparepdu('E',len2,errormsg,sbuf);
sendpdu(sd,sbuf);
}
else{
bzero(sbuf,BUFLEN);
while((bytes_read = fread(dbuf1,sizeof(char),146,fp1))>0){
printf("sending %d bytes to client\n",bytes_read);
preparepdu('F',bytes_read,dbuf1,sbuf);
sendpdu(sd,sbuf);
}
printf("closing file...\n");
fclose(fp1);
}
}
void upload (int sd, char file_name[])
{
FILE *fp;
char error1[146] = "File doesn't exist";
char empty1[1],empty2[1];
char sbuf[BUFLEN],rbuf[BUFLEN],data[146];
int bytes_received=0,len_of_data=0,write_size = 0;
int len1 =0;
if ((fp = fopen (file_name,"w"))== NULL){
len1 = strlen(error1);
preparepdu('E',len1,error1,sbuf);//prepare and send error pdu
sendpdu(sd,sbuf);
}
else{
preparepdu('R',0,empty2,sbuf); //prepare and send READY PDU
sendpdu(sd, sbuf);
while ((bytes_received = recv(sd, rbuf, BUFLEN, 0))> 0)
{
if (rbuf[0]=='F'){
getonlydata(rbuf,data);
len_of_data = returnlength(rbuf);
write_size = fwrite(data, sizeof(char),len_of_data, fp);
}
if (len_of_data < 146)
break;
}
fclose(fp);
printf("closing file\n");
}
}
void changedirectory(int sd,char path[])
{
int n1=0,n2=0,n3=0,n4=0;
int i1=0,i2=0,i3=0;
int len_of_data=0,len1=0,lenoferror=0;
char rbuf[BUFLEN],empty1[1],empty2[1],sbuf[BUFLEN];
char file_name[146];
char error1[146] = "specified directory doesn't exist";
//char fullpath[146] = "/home/student2/nnatta/Desktop/FTProject/server/";
bzero(rbuf,sizeof(rbuf));bzero(file_name,sizeof(file_name)); //clearing buffers
lenoferror = strlen(error1);
//strcat(fullpath, path);
printf("what is path: %s ", path);
if (strcmp(path,"root")!=0){
if (chdir(path) == -1)
printf("Error occured \n");
}
else if (strcmp(path,"root") == 0){
chdir("..");//change directory go one level up
}
else{
preparepdu('E',lenoferror,error1,sbuf);//send error packet
sendpdu(sd,sbuf);
}
preparepdu('R',1,empty2,sbuf);
sendpdu(sd,sbuf);
}
void listfiles(int sd, char dir_path[])
{
char *filenames[146],data[146],sbuf[BUFLEN],cwd[146];
int a;
int i = 0,len=0;
DIR *d;
struct dirent *dir;
FILE *fp;
fp = fopen("list.txt","w");
printf("in listfiles(): dir_path: %s",dir_path);
getcwd(cwd,sizeof(cwd));
strcat(cwd,"/");
strcat(cwd,dir_path);
printf("what is cwd: %s\n",cwd);
d = opendir(cwd);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
filenames[i] = malloc(strlen(dir->d_name));
strcpy(filenames[i],dir->d_name);
printf("Filename is:%s\n", filenames[i]);
fprintf(fp,"%s\n",filenames[i]);
i++;
}
printf("\n");
closedir(d);
fclose(fp);
}
fp = fopen("list.txt","r");
while (len = fread(data,sizeof(char),146,fp)){
preparepdu('I',len,data,sbuf);
printf("what is data: %s",data);
sendpdu(sd,sbuf);
}
fclose(fp);
}
void preparepdu (char type, int length, char data[],char sbuf[])
{
char str[3];
int i=0,i1=0, i2=0, i3=0,i4=0,i5=0,i6=0,i7=0,i8=0,i9=0,i10=0,i11=0,i12=0,i13=0;
sprintf(str, "%d",length);
for (i13;i13<3;i13++) //REPLACE white spaces in array with '.'
{
if (str[i13] == '\0'|| str[i13]== ' ')
str[i13] = '.';
}
if (type =='F' || type == 'f')
{
sbuf[0] = 'F'; //TYPE
for (i1;i1<3;i1++) //LENGTH
{
sbuf[i1+1] = str[i1];
}
for (i2; i2<length;i2++) //DATA
{
sbuf[i2+4] = data[i2];
}
}
else if (type =='R' || type == 'r')
{
sbuf[0] = 'R'; //PDU to send ready
for (i3;i3<3;i3++) //LENGTH
{
sbuf[i3+1] = str[i3];
}
for (i4; i4<length;i4++) //DATA
{
sbuf[i4+4]=data[i4];
}
}
else if (type =='E' || type == 'e')
{
sbuf[0] = 'E'; //PDU for sending error file
for (i5;i5<3;i5++) //LENGTH
{
sbuf[i5+1] = str[i5];
}
for (i6; i6<length;i6++) //DATA
{
sbuf[i6+4]=data[i6];
}
}
else if (type =='I' || type == 'i')
{
sbuf[0] = 'I'; //PDU to send file list
for (i7;i7<3;i7++) //LENGTH
{
sbuf[i7+1] = str[i7];
}
for (i8; i8<length;i8++) //DATA
{
sbuf[i8+4]=data[i8];
}
}
}
int returnlength(char pdu[])
{
int i1=0,i2=0;
int ret;
char str15[3];
for (i1;i1<3;i1++)
{
str15[i1] = pdu[i1+1];
}
printf("content of str: %s",str15);
ret = atoi(str15);
return ret;
}
void sendpdu(int sd, char pdu[])
{
int n2=0;
printf("In sendpdu ()\n");
printf("Contents of pdu:%s \n",pdu);
if ((n2 = send(sd,pdu,BUFLEN,0))<0){
printf("Error writing to socket\n");
exit(0);
}
}
void getonlydata(char pdu[],char data[])
{
int i1=0,len_of_data=0;
for (i1 ; i1<146; i1++)
data[i1]=pdu[i1+4];
}
void reaper(int sig)
{
int status;
while(wait3(&status, WNOHANG, (struct rusage *)0) >= 0);
}
|
C
|
#include <stdio.h>
#include <limits.h>
float angle(int x1, int y1, int x2, int y2)
{
if (x1 == x2)
return INT_MAX;
else
return ((y2 - y1) / (float)(x2 - x1));
}
float max(float x, float y)
{
return x > y ? x : y;
}
float min(float x, float y)
{
return x < y ? x : y;
}
int main()
{
int t;
scanf("%d", &t);
while (t > 0)
{
t--;
int count = 0;
int n, q;
scanf("%d %d", &n, &q);
int a[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
// for (int i = 0; i < n; i++)
// {
// printf("%d->", a[i]);
// }
// printf("\n");
int x1, x2, y;
for (int i = 0; i < q; i++)
{
count = 0;
scanf("%d %d %d", &x1, &x2, &y);
// printf("%d %d %d", x1, x2, y);
for (int j = 0; j < n - 1; j++)
{
if ((a[j] > y && a[j + 1] > y) || (a[j] < y && a[j + 1] < y))
continue;
// printf("Hello %d\n", j);
else
{
float ang1 = angle(j + 1, a[j], x1, y);
float ang2 = angle(j + 1, a[j], x2, y);
float ang3 = angle(j + 1, a[j], j + 2, a[j + 1]);
if (ang1 > 0 && ang2 > 0)
{
if (ang3 <= ang1 && ang3 >= ang2)
count++;
}
else if (ang1 < 0 && ang2 > 0)
{
if (ang3 >= ang1 && ang3 <= ang2)
count++;
}
else
{
if (ang3 < ang1 || ang3 > ang2)
count++;
}
// printf("World %d\n", count);
}
}
printf("%d\n", count);
}
}
}
|
C
|
#include "clar_libgit2.h"
#include "strmap.h"
git_strmap *g_table;
void test_core_strmap__initialize(void)
{
cl_git_pass(git_strmap_alloc(&g_table));
cl_assert(g_table != NULL);
}
void test_core_strmap__cleanup(void)
{
git_strmap_free(g_table);
}
void test_core_strmap__0(void)
{
cl_assert(git_strmap_num_entries(g_table) == 0);
}
static void insert_strings(git_strmap *table, int count)
{
int i, j, over, err;
char *str;
for (i = 0; i < count; ++i) {
str = malloc(10);
for (j = 0; j < 10; ++j)
str[j] = 'a' + (i % 26);
str[9] = '\0';
/* if > 26, then encode larger value in first letters */
for (j = 0, over = i / 26; over > 0; j++, over = over / 26)
str[j] = 'A' + (over % 26);
git_strmap_insert(table, str, str, &err);
cl_assert(err >= 0);
}
cl_assert((int)git_strmap_num_entries(table) == count);
}
void test_core_strmap__1(void)
{
int i;
char *str;
insert_strings(g_table, 20);
cl_assert(git_strmap_exists(g_table, "aaaaaaaaa"));
cl_assert(git_strmap_exists(g_table, "ggggggggg"));
cl_assert(!git_strmap_exists(g_table, "aaaaaaaab"));
cl_assert(!git_strmap_exists(g_table, "abcdefghi"));
i = 0;
git_strmap_foreach_value(g_table, str, { i++; free(str); });
cl_assert(i == 20);
}
void test_core_strmap__2(void)
{
size_t pos;
int i;
char *str;
insert_strings(g_table, 20);
cl_assert(git_strmap_exists(g_table, "aaaaaaaaa"));
cl_assert(git_strmap_exists(g_table, "ggggggggg"));
cl_assert(!git_strmap_exists(g_table, "aaaaaaaab"));
cl_assert(!git_strmap_exists(g_table, "abcdefghi"));
cl_assert(git_strmap_exists(g_table, "bbbbbbbbb"));
pos = git_strmap_lookup_index(g_table, "bbbbbbbbb");
cl_assert(git_strmap_valid_index(g_table, pos));
cl_assert_equal_s(git_strmap_value_at(g_table, pos), "bbbbbbbbb");
free(git_strmap_value_at(g_table, pos));
git_strmap_delete_at(g_table, pos);
cl_assert(!git_strmap_exists(g_table, "bbbbbbbbb"));
i = 0;
git_strmap_foreach_value(g_table, str, { i++; free(str); });
cl_assert(i == 19);
}
void test_core_strmap__3(void)
{
int i;
char *str;
insert_strings(g_table, 10000);
i = 0;
git_strmap_foreach_value(g_table, str, { i++; free(str); });
cl_assert(i == 10000);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.