Exemple #1
0
int main(int argc, char ** argv)
{
	struct stat buffer;
	int res;
	int i;
	
	if(argc == 1)
	{
		readDirContents(".");
	}
	else
	{
		for(i = 1; i<argc; ++i)
		{
			printf("%s\n", argv[i]);
			res = stat(argv[i], &buffer);
			if(res != -1)
			{
				if(S_ISREG(buffer.st_mode))
				{
					readFileContents(argv[i]);
				}
				else if(S_ISDIR(buffer.st_mode))
				{
					readDirContents(argv[i]);
				}
			}
		}
	}
	
}
Exemple #2
0
int HexReader::readBlockMeshDict(QTextStream *in)
{


    fileContents = readFileContents(in);

    //Read vertices
    getVertices();

    getBlocks();

    getBCs();

    getEdges();
    return 0;

}
int main() {
	srand(time(NULL));
	
	int outputType = 0;
	int inputType = 0;
	int wordsInStream = 0;
	
	ifstream inFile;
	ofstream outFile;
	char fileContents[MAXFILECONTENTSLENGTH];
	
	inputType = getInputType(inFile);
	
	outputType = getOutputType(outFile);
	
	//user selected to read from file
	if (inputType == 1) 
		readFileContents(inFile, fileContents);
	
	//user selected to read from keyboard
	if (inputType == 2)
		readKeyboardContents(fileContents);
	
	wordsInStream = countInputStreamWords(fileContents);
	
	//just send a 0 to start it
	convertEs(fileContents, 0, outFile);
	
	//replace(fileContents, "s ", "es");
	
	//user selected to output to a file
	/*if (outputType == 1)
		toFile(outFile, fileContents);
	
	//user selected to putput to the screen
	if (outputType == 2)
		toScreen(fileContents);*/
	
	inFile.close();
	outFile.close();
	
	return 0;
}
Exemple #4
0
void HTMLChatTheme::readTheme(QDir dir) {
    qDebug() << "reading theme from filesystem" << dir;

    isValid_ = false;

    if (!dir.cd("Contents/Resources/")) { //invalid dir
        return; //isValid == false;
    }

    setBaseHref(dir.path() + "/");

    incomingNextMessageTemplate.setContent(readFileContents(dir, "Incoming/Content.html"));

    if (dir.exists("Incoming/NextContent.html")) {
        incomingConsecutiveMessageTemplate.setContent(readFileContents(dir, "Incoming/NextContent.html"));
    }
    else {
        incomingConsecutiveMessageTemplate.setContent(incomingNextMessageTemplate.content());
    }

    // outgoing messages
    if (dir.exists("Outgoing/NextContent.html")) {
        outgoingConsecutiveMessageTemplate.setContent(readFileContents(dir, "Outgoing/NextContent.html"));
    }
    else {
        outgoingConsecutiveMessageTemplate.setContent(incomingConsecutiveMessageTemplate.content());
    }

    if (dir.exists("Outgoing/Content.html")) {
        outgoingNextMessageTemplate.setContent(readFileContents(dir, "Outgoing/Content.html"));
    }
    else {
        outgoingNextMessageTemplate.setContent(incomingNextMessageTemplate.content());
    }

    noOutgoingDir = !dir.exists("Outgoing/buddy_icon.png"); //some themes have empty Outgoing dir
    //we will be using Incoming avatar

    // status/event template
    fileTransferEventTemplate.setContent(readFileContents(dir, "Status.html"));
    systemEventTemplate = HTMLChatTemplate(fileTransferEventTemplate);
    moodEventTemplate = HTMLChatTemplate(fileTransferEventTemplate);
    tuneEventTemplate = HTMLChatTemplate(fileTransferEventTemplate);


    // action
    if (dir.exists("Incoming/Action.html")) {
        incomingEmoteEventTemplate.setContent(readFileContents(dir, "Incoming/Action.html"));
        incomingEmoteEventTemplate.setEmoteTemplate(true);
    }
    else {
        incomingEmoteEventTemplate.setContent(fileTransferEventTemplate.content());
    }

    if (dir.exists("Outgoing/Action.html")) {
        outgoingEmoteEventTemplate.setContent(readFileContents(dir, "Outgoing/Action.html"));
        incomingEmoteEventTemplate.setEmoteTemplate(true);
    }
    else {
        outgoingEmoteEventTemplate.setContent(fileTransferEventTemplate.content());
    }


    headerTemplate_.setContent(readFileContents(dir, "Header.html"));
    footerTemplate_.setContent(readFileContents(dir, "Footer.html"));

    isValid_ = true;

    //read Variants
    variants_.clear();

    if (!dir.cd("Variants/")) {
        qDebug() << "no Variants dir";
        return; //no variants
    }

    QStringList filters;
    filters << "*.css";

    QStringList variantFiles = dir.entryList(filters);
    QString variant;


    foreach(variant, variantFiles) {
        variants_.append(variant.left(variant.size() - 4));
    }
Exemple #5
0
void
handshake(int sockfd, SA *serv_addr, socklen_t serv_len, SA *cli_addr, socklen_t cli_len, char *filename, int max_sending_window_size)
{
	FILE *fd;
	char sendline[MAXLINE];
	char recvline[MAXLINE];
	int listen_sockfd = sockfd;
	int new_sockfd;
	int on = 1;
	struct sockaddr_in ss;
	int ss_len = sizeof(ss);
	int n;

	fd = fopen( filename, "r");
	
	getsockopt(listen_sockfd, SOL_SOCKET, SO_DONTROUTE, &on, sizeof(on));

	/* establishing new_sock */
	if((new_sockfd = socket( AF_INET, SOCK_DGRAM, 0)) == NULL)
        {
                printf("SERVER: socket error in handshake\n" );
                exit(1);
        }
	setsockopt(new_sockfd, SOL_SOCKET, SO_DONTROUTE | SO_REUSEADDR, &on, sizeof(on));
	Bind(new_sockfd, (SA *)serv_addr, sizeof(struct sockaddr_in ));
	
	/* getting ephemeral PORT */
	if( getsockname(new_sockfd, (SA *)&ss, &ss_len) < 0)
	{
		printf("SERVER: getsockname error \n");
		exit(1);
	}
#if(1)
	/* For Debug */
	int IPbuf[MAXLINE];
	inet_ntop( AF_INET, &(ss.sin_addr), IPbuf, MAXLINE);
	printf("SERVER: new_sockfd IP %s, port %d\n",IPbuf, ss.sin_port); 

#endif
	if(connect(new_sockfd, (SA *)cli_addr, cli_len) < 0)
        {
                printf("SERVER: connect error in handshake\n" );
                exit(1);
        }

	sprintf(sendline, "%d", ss.sin_port);
#if(0)

	ssize_t
	dg_send_recv(int fd, const void *outbuff, size_t outbytes,
                         void *inbuff, size_t inbytes,
                         const SA *destaddr, socklen_t destlen)


#else
	Sendto(listen_sockfd, sendline, 10, 0, cli_addr, cli_len);
	printf("SERVER: sending port num %d\n", ss.sin_port);

	n = recvfrom(new_sockfd, recvline, MAXLINE, 0, (SA *)cli_addr, &cli_len);
	recvline[15] = 0;
	printf("SERVER: receving ACK %s \n", recvline);
#endif
	close(listen_sockfd);	/* close listening socket */

	/* File data transfer */

	//fread(sendline, 1, 10, fd);
	
	//Sendto(new_sockfd, sendline, 10, 0, NULL, NULL);
	//printf("SERVER: sending file 10 bytes to client\n");
	//recvfrom(new_sockfd, recvline, MAXLINE, 0, (SA *)cli_addr, &cli_len);
	//printf("SERVER: Ack from client about PACKET 1\n");
	
	//while(1);
	int totalblocks = readFileContents(filename, max_sending_window_size);
	//printf("%d\n", totalblocks);
	sendFileContents(new_sockfd, totalblocks, max_sending_window_size);
}
//****************************************************************************
void CommandLineOptions::parseCollideCommands (const unsigned int argc, const char* const argv[], const unsigned int currentArg) {

	std::string currentArgumentValue;
	unsigned int argumentIndex = currentArg;

	if (argumentIndex >= static_cast<unsigned int> (argc)) {

		m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
		return;

	}

	currentArgumentValue = argv[argumentIndex];

	if (currentArgumentValue == CommandLineOptions::COMMAND_HELP) {

		// Help can only be requested if no other flags are given.
		// Because of this we can easily check if help is valid by
		// checking the number of passed arguments.
		if (argc == 3) {

			m_helpMode = true;

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}

	} else if (currentArgumentValue == CommandLineOptions::COMMAND_INPUT_FILE) {

		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_inputText.length () == 0) {

			// Load file.
			if (!readFileContents (argv[argumentIndex], m_inputText)) {

				m_errorCode = ErrorCode::FILE_READ_ERROR;
				return;

			}

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}

	} else if (currentArgumentValue == CommandLineOptions::COMMAND_OUTPUT_FILE) {

		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_outputFilename.length () == 0) {

			m_outputFilename = argv[argumentIndex];

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}

	} else if (currentArgumentValue == CommandLineOptions::COMMAND_MIN) {
	
		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_minLength == 0) {

			if (!parseStringAsUint (argv[argumentIndex], m_minLength)) {

				m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
				return;

			}		

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}
	
	} else if (currentArgumentValue == CommandLineOptions::COMMAND_MAX) {
	
		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_maxLength == 0) {

			if (!parseStringAsUint (argv[argumentIndex], m_maxLength)) {

				m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
				return;

			}		

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}
	
	} else if (currentArgumentValue == CommandLineOptions::COMMAND_THREAD_COUNT) {
	
		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_threadCount == std::thread::hardware_concurrency ()) {

			if (!parseStringAsUint (argv[argumentIndex], m_threadCount)) {

				m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
				return;

			}		

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}
	
	} else if (currentArgumentValue == CommandLineOptions::COMMAND_ALPHBET_FLAGS) {
	
		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_alphabet.length () == 0) {

			try {

				m_alphabet = CharacterSet (0);
				m_alphabet.generateFromStringSubsetFlags (argv[argumentIndex]);

			} catch (...) {

				m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
				return;

			}

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}	
	
	} else if (currentArgumentValue == CommandLineOptions::COMMAND_ALPHBET_FILE) {
	
		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_alphabet.length () == 0) {

			m_alphabet = CharacterSet (0);
			if (!m_alphabet.loadFromFile (argv[argumentIndex])) {

				m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
				return;

			}

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}
	
	} else if (currentArgumentValue == CommandLineOptions::COMMAND_ALPHBET_CHARS) {
	
		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_alphabet.length () == 0) {

			try {

				m_alphabet = CharacterSet (argv[argumentIndex]);

			} catch (...) {

				m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
				return;

			}

		} else {

			m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
			return;

		}
	
	} else if (m_inputText.length () == 0) {

		// If there is no input text then assume that this unknown
		// argument is a string of text as input.
		m_inputText = argv[argumentIndex];

	} else {

		m_errorCode = ErrorCode::COLLIDE_USAGE_ERROR;
		return;

	}

	argumentIndex++;
	if (argumentIndex < static_cast<unsigned int> (argc)) {

		parseCollideCommands (argc, argv, argumentIndex);
		return;

	}

	m_errorCode = ErrorCode::NONE;
	return;

}
//****************************************************************************
void CommandLineOptions::parseDigestCommands (const unsigned int argc, const char* const argv[], const unsigned int currentArg) {

	std::string currentArgumentValue;
	unsigned int argumentIndex = currentArg;

	if (argumentIndex >= static_cast<unsigned int> (argc)) {

		m_errorCode = ErrorCode::DIGEST_USAGE_ERROR;
		return;

	}

	currentArgumentValue = argv[argumentIndex];

	if (currentArgumentValue == CommandLineOptions::COMMAND_HELP) {

		// Help can only be requested if no other flags are given.
		// Because of this we can easily check if help is valid by
		// checking the number of passed arguments.
		if (argc == 3) {

			m_helpMode = true;

		} else {

			m_errorCode = ErrorCode::DIGEST_USAGE_ERROR;
			return;

		}

	} else if (currentArgumentValue == CommandLineOptions::COMMAND_INPUT_FILE) {

		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_inputText.length () == 0) {

			// Load file.
			if (!readFileContents (argv[argumentIndex], m_inputText)) {

				m_errorCode = ErrorCode::FILE_READ_ERROR;
				return;

			}

		} else {

			m_errorCode = ErrorCode::DIGEST_USAGE_ERROR;
			return;

		}

	} else if (currentArgumentValue == CommandLineOptions::COMMAND_OUTPUT_FILE) {

		if (!m_helpMode && ++argumentIndex < static_cast<unsigned int> (argc) && m_outputFilename.length () == 0) {

			m_outputFilename = argv[argumentIndex];

		} else {

			m_errorCode = ErrorCode::DIGEST_USAGE_ERROR;
			return;

		}

	} else if (m_inputText.length () == 0) {

		// If there is no input text then assume that this unknown
		// argument is a string of text as input.
		m_inputText = argv[argumentIndex];

	} else {

		m_errorCode = ErrorCode::DIGEST_USAGE_ERROR;
		return;

	}

	argumentIndex++;
	if (argumentIndex < static_cast<unsigned int> (argc)) {

		parseDigestCommands (argc, argv, argumentIndex);
		return;

	}

	m_errorCode = ErrorCode::NONE;
	return;

}
Exemple #8
0
/*
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?
*/
problem_result prob22(void) {
  char* contents = NULL;
  size_t fileSize = 0;
  char** names = NULL;
  size_t nameCount = 0;
  
  contents = readFileContents("names.txt", &fileSize);
  
  // Delimit
  char* pch = strchr(contents, ',');
  while (pch!=NULL) {
    nameCount++;
    *pch = '\0';
    pch=strchr(pch+1,',');
  }
  nameCount++;
  
  names = malloc(nameCount * sizeof(char*));
  
  // To Array
  char* currentNameStart = contents;
  char** activeName = names;
  for(int i = 0; i < nameCount; i++) {
    int nameLength = strlen(currentNameStart);
    
    currentNameStart[nameLength-1] = '\0';
    currentNameStart++;
    
    *activeName = currentNameStart;
  
    if(i < nameCount - 1) {
      currentNameStart += nameLength;
      activeName++;
    }
  }
  
  
  // Sort  
  strsort(names, nameCount);
  
  unsigned int nameScore = 0;
  unsigned long int totalScore = 0;
  
  for(int i = 0; i < nameCount; i++) {
    char* name = names[i];
    nameScore = 0;
    
    while(*name) {
      nameScore += (*name - 'A') + 1;
      name++;
    }
    
    totalScore += (nameScore * (i + 1));
  }
  
  
  free(names);
  free(contents);
  
  return totalScore;
}
terrama2::core::DataSetSeries terrama2::core::DataAccessorJsonCemaden::getSeries( const std::string& uri,
                                                                                  const Filter& filter,
                                                                                  DataSetPtr dataSet,
                                                                                  std::shared_ptr<terrama2::core::FileRemover> /*remover*/) const
{
  QString codestacao = QString::fromStdString(getCodePropertyName(dataSet));
  QString inputTimestampProperty = QString::fromStdString(getInputTimestampPropertyName(dataSet));
  std::string timestampProperty = getTimestampPropertyName(dataSet);
  QStringList staticData = QString::fromStdString(getStaticDataProperties(dataSet)).split(',');

  QString code = QString::fromStdString(getDCPCode(dataSet));

  auto dataSetType =  std::make_shared<te::da::DataSetType>(code.toStdString());
  dataSetType->add(new te::dt::DateTimeProperty(timestampProperty, te::dt::TIME_INSTANT_TZ, true));

  auto teDataSet = std::make_shared<te::mem::DataSet>(dataSetType.get());

  te::core::URI teUri(uri);
  std::string filePath = getFolderMask(dataSet) + "/" + getDataMask(dataSet);

  auto jsonStr = readFileContents(teUri.path()+filePath);
  QJsonDocument doc = QJsonDocument::fromJson(jsonStr.c_str());
  auto readingsArray = doc.object()["cemaden"].toArray();
  // iterate over readings
  // and populate the dataset
  for(auto reading : readingsArray)
  {
    auto obj = reading.toObject();
    //check if this is the DCP we want
    if(obj[codestacao].toString() != code)
      continue;

    auto timestampStr = obj[inputTimestampProperty].toString().toStdString();
    auto timestamp = terrama2::core::TimeUtils::stringToTimestamp(timestampStr, "%Y-%m-%d %H:%M:%S%F");
    // filter by timestamp
    if((filter.discardBefore && (*filter.discardBefore > *timestamp))
        || (filter.discardAfter && (*filter.discardAfter < *timestamp)))
        continue;

    // create new item
    auto item = std::unique_ptr<te::mem::DataSetItem>(new te::mem::DataSetItem(teDataSet.get()));
    // add item to the end of the dataset
    teDataSet->moveLast();
    teDataSet->add(item.get());
    // check if the item has data
    bool hasData = false;

    // add timestamp to dataset
    item->setDateTime(timestampProperty, static_cast<te::dt::TimeInstantTZ*>(timestamp->clone()));

    for(auto val = obj.begin(); val != obj.end(); ++val) {
      auto key = val.key();
      // ignore static data
      if(staticData.contains(key)
          || key == codestacao
          || key.toStdString() == timestampProperty)
        continue;

      // property name
      auto keyStr = key.toStdString();

      // check if the property is already registered in the dataset
      auto properties = dataSetType->getProperties();
      auto it = std::find_if(properties.cbegin(), properties.cend(), [&keyStr](te::dt::Property* property){ return property->getName() == keyStr; });
      if(it == properties.cend())
      {
        // update dataSetType
        te::dt::SimpleProperty* property = new te::dt::SimpleProperty(keyStr, te::dt::DOUBLE_TYPE, false);
        dataSetType->add(property);
        // update memory dataset structure
        teDataSet->add(keyStr, te::dt::DOUBLE_TYPE);
      }

      // add property value
      item->setDouble(keyStr, val.value().toDouble());
      hasData = true;
    }
    if(!hasData)
    {
      // remove the item if no data was inserted
      teDataSet->remove(item.get());
    }
    item.release();
  }

  terrama2::core::DataSetSeries serie;
  serie.dataSet = dataSet;
  serie.syncDataSet = std::make_shared<terrama2::core::SynchronizedDataSet>(teDataSet);
  serie.teDataSetType = dataSetType;

  return serie;
}