Example #1
0
//---------------------------------------------------------------------------
static bool encodeFilter(DictionarySegment& dict,DifferentialIndex* diffIndex,const SPARQLParser::PatternGroup& group,const SPARQLParser::Filter& input,QueryGraph::Filter& output)
   // Encode an element for the query graph
{
   switch (input.type) {
      case SPARQLParser::Filter::Or: return encodeBinaryFilter(QueryGraph::Filter::Or,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::And: return encodeBinaryFilter(QueryGraph::Filter::And,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Equal: return encodeBinaryFilter(QueryGraph::Filter::Equal,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::NotEqual: return encodeBinaryFilter(QueryGraph::Filter::NotEqual,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Less: return encodeBinaryFilter(QueryGraph::Filter::Less,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::LessOrEqual: return encodeBinaryFilter(QueryGraph::Filter::LessOrEqual,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Greater: return encodeBinaryFilter(QueryGraph::Filter::Greater,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::GreaterOrEqual: return encodeBinaryFilter(QueryGraph::Filter::GreaterOrEqual,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Plus: return encodeBinaryFilter(QueryGraph::Filter::Plus,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Minus: return encodeBinaryFilter(QueryGraph::Filter::Minus,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Mul: return encodeBinaryFilter(QueryGraph::Filter::Mul,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Div: return encodeBinaryFilter(QueryGraph::Filter::Div,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Not: return encodeUnaryFilter(QueryGraph::Filter::Not,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::UnaryPlus: return encodeUnaryFilter(QueryGraph::Filter::UnaryPlus,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::UnaryMinus: return encodeUnaryFilter(QueryGraph::Filter::UnaryMinus,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Literal: {
         SPARQLParser::Element e;
         e.type=SPARQLParser::Element::Literal;
         e.subType=static_cast<SPARQLParser::Element::SubType>(input.valueArg);
         e.subTypeValue=input.valueType;
         e.value=input.value;
         unsigned id; bool constant;
         if (encode(dict,diffIndex,e,id,constant)) {
            output.type=QueryGraph::Filter::Literal;
            output.id=id;
            output.value=input.value;
         } else {
            output.type=QueryGraph::Filter::Literal;
            output.id=~0u;
            output.value=input.value;
         }
         } return true;
      case SPARQLParser::Filter::Variable:
         if (binds(group,input.valueArg)) {
            output.type=QueryGraph::Filter::Variable;
            output.id=input.valueArg;
         } else {
            output.type=QueryGraph::Filter::Null;
         }
         return true;
      case SPARQLParser::Filter::IRI: {
         SPARQLParser::Element e;
         e.type=SPARQLParser::Element::IRI;
         e.subType=static_cast<SPARQLParser::Element::SubType>(input.valueArg);
         e.subTypeValue=input.valueType;
         e.value=input.value;
         unsigned id; bool constant;
         if (encode(dict,diffIndex,e,id,constant)) {
            output.type=QueryGraph::Filter::IRI;
            output.id=id;
            output.value=input.value;
         } else {
            output.type=QueryGraph::Filter::IRI;
            output.id=~0u;
            output.value=input.value;
         }
         } return true;
      case SPARQLParser::Filter::Function:
         if (input.arg1->value==tableFunctionId)
            throw SemanticAnalysis::SemanticException(std::string("<")+tableFunctionId+"> calls must be placed in seperate filter clauses");
         return encodeBinaryFilter(QueryGraph::Filter::Function,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::ArgumentList: return encodeBinaryFilter(QueryGraph::Filter::ArgumentList,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_str: return encodeUnaryFilter(QueryGraph::Filter::Builtin_str,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_lang: return encodeUnaryFilter(QueryGraph::Filter::Builtin_lang,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_langmatches: return encodeBinaryFilter(QueryGraph::Filter::Builtin_langmatches,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_datatype: return encodeUnaryFilter(QueryGraph::Filter::Builtin_datatype,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_bound: return encodeUnaryFilter(QueryGraph::Filter::Builtin_bound,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_sameterm: return encodeBinaryFilter(QueryGraph::Filter::Builtin_sameterm,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_isiri: return encodeUnaryFilter(QueryGraph::Filter::Builtin_isiri,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_isblank: return encodeUnaryFilter(QueryGraph::Filter::Builtin_isblank,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_isliteral: return encodeUnaryFilter(QueryGraph::Filter::Builtin_isliteral,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_regex: return encodeTernaryFilter(QueryGraph::Filter::Builtin_regex,dict,diffIndex,group,input,output);
      case SPARQLParser::Filter::Builtin_in: return encodeBinaryFilter(QueryGraph::Filter::Builtin_in,dict,diffIndex,group,input,output);
   }
   return false; // XXX cannot happen
}
Vector<char> IndexMetaDataKey::encodeMaxKey(int64_t databaseId, int64_t objectStoreId)
{
    return encode(databaseId, objectStoreId, INT64_MAX, 255);
}
Vector<char> ExistsEntryKey::encode(int64_t databaseId, int64_t objectStoreId, const IDBKey& userKey)
{
    return encode(databaseId, objectStoreId, encodeIDBKey(userKey));
}
Example #4
0
std::string
MidiDevice::toXmlString() const
{
    std::stringstream midiDevice;

    midiDevice << "    <device id=\""  << m_id 
               << "\" name=\""         << m_name 
               << "\" direction=\""    << (m_direction == Play ?
                                           "play" : "record")
               << "\" variation=\""    << (m_variationType == VariationFromLSB ?
                                           "LSB" :
                                           m_variationType == VariationFromMSB ?
                                           "MSB" : "")
               << "\" connection=\""   << encode(m_connection)
               << "\" type=\"midi\">"  << std::endl << std::endl;

    midiDevice << "        <librarian name=\"" << encode(m_librarian.first)
               << "\" email=\"" << encode(m_librarian.second)
               << "\"/>" << std::endl;

    if (m_metronome)
    {
        // Write out the metronome - watch the MidiBytes
        // when using the stringstream
        //
        midiDevice << "        <metronome "
                   << "instrument=\"" << m_metronome->getInstrument() << "\" "
                   << "barpitch=\"" << (int)m_metronome->getBarPitch() << "\" "
                   << "beatpitch=\"" << (int)m_metronome->getBeatPitch() << "\" "
                   << "subbeatpitch=\"" << (int)m_metronome->getSubBeatPitch() << "\" "
                   << "depth=\"" << (int)m_metronome->getDepth() << "\" "
                   << "barvelocity=\"" << (int)m_metronome->getBarVelocity() << "\" "
                   << "beatvelocity=\"" << (int)m_metronome->getBeatVelocity() << "\" "
                   << "subbeatvelocity=\"" << (int)m_metronome->getSubBeatVelocity() 
                   << "\"/>"
                   << std::endl << std::endl;
    }

    // and now bank information
    //
    BankList::const_iterator it;
    InstrumentList::const_iterator iit;
    ProgramList::const_iterator pt;

    for (it = m_bankList.begin(); it != m_bankList.end(); ++it)
    {
        midiDevice << "        <bank "
                   << "name=\"" << encode(it->getName()) << "\" "
                   << "percussion=\"" << (it->isPercussion() ? "true" : "false") << "\" "
                   << "msb=\"" << (int)it->getMSB() << "\" "
                   << "lsb=\"" << (int)it->getLSB() << "\">"
                   << std::endl;

        // Not terribly efficient
        //
        for (pt = m_programList.begin(); pt != m_programList.end(); ++pt)
        {
            if (pt->getBank().partialCompare(*it))
            {
                midiDevice << "            <program "
                           << "id=\"" << (int)pt->getProgram() << "\" "
                           << "name=\"" << encode(pt->getName()) << "\" ";
                if (!pt->getKeyMapping().empty()) {
                    midiDevice << "keymapping=\"" 
                               << encode(pt->getKeyMapping()) << "\" ";
                }
                midiDevice << "/>" << std::endl;
            }
        }

        midiDevice << "        </bank>" << std::endl << std::endl;
    }

    // Now controllers (before Instruments, which can depend on 
    // Controller colours)
    //
    midiDevice << "        <controls>" << std::endl;
    ControlList::const_iterator cIt;
    for (cIt = m_controlList.begin(); cIt != m_controlList.end() ; ++cIt)
        midiDevice << cIt->toXmlString();
    midiDevice << "        </controls>" << std::endl << std::endl;

    // Add instruments
    //
    for (iit = m_instruments.begin(); iit != m_instruments.end(); ++iit)
        midiDevice << (*iit)->toXmlString();

    KeyMappingList::const_iterator kit;

    for (kit = m_keyMappingList.begin(); kit != m_keyMappingList.end(); ++kit)
    {
        midiDevice << "        <keymapping "
                   << "name=\"" << encode(kit->getName()) << "\">\n";

        for (MidiKeyMapping::KeyNameMap::const_iterator nmi =
                 kit->getMap().begin(); nmi != kit->getMap().end(); ++nmi) {
            midiDevice << "          <key number=\"" << (int)nmi->first
                       << "\" name=\"" << encode(nmi->second) << "\"/>\n";
        }

        midiDevice << "        </keymapping>\n";
    }

    midiDevice << "    </device>" << std::endl;

    return midiDevice.str();
}
Example #5
0
int CLiveParser::GetOnePacket(char *pData, J_StreamHeader &streamHeader)
{
	WLock(m_rwLocker);
	if (m_dateType == J_VideoMjpeg)
	{
		if (m_nDataSize < (int)sizeof(int))
		{
			streamHeader.dataLen = 0;
			RWUnlock(m_rwLocker);
			return J_NOT_COMPLATE;
		}

		int nOffset = 0;
		int nLen = *((int *)(m_pDataBuff));
		nOffset += sizeof(int);
		memcpy(pData, m_pDataBuff + nOffset, nLen);
		nOffset += nLen;
		memmove(m_pDataBuff, m_pDataBuff + nOffset, m_nDataSize - nOffset);
		m_nDataSize -= nOffset;

		streamHeader.timeStamp = CTime::Instance()->GetLocalTime(0);
		streamHeader.dataLen = nLen;
		streamHeader.frameType = J_VideoIFrame;
	}
	else
	{
		int iDataLen = 640 * 480;
		if (m_nDataSize < iDataLen * 2)
		{
			streamHeader.dataLen = 0;
			RWUnlock(m_rwLocker);
			return J_NOT_COMPLATE;
		}

		streamHeader.timeStamp = CTime::Instance()->GetLocalTime(0);
		int nOffset = 0;
		YUV422To420((uint8_t *)m_pDataBuff, m_pPicIn->img.plane[0], m_pPicIn->img.plane[1], m_pPicIn->img.plane[2], 640, 480);
		nOffset = iDataLen * 2;

		m_pPicIn->i_pts = 0;//streamHeader.timeStamp * 90;
		//m_pPicIn->i_dts = streamHeader.timeStamp * 90;
		//++g_uiPTSFactor;
		encode(m_pX264Handle, m_pPicIn, m_pPicOut);
		memmove(m_pDataBuff, m_pDataBuff + nOffset, m_nDataSize - nOffset);
		m_nDataSize -= nOffset;

		nOffset = 0;
		for (int i = 0; i < m_iNal; ++i)
		{
			/*static FILE *fp = NULL;
			if (fp == NULL)
				fp = fopen("test.h264", "wb+");
			fwrite(m_pNals[i].p_payload, 1, m_pNals[i].i_payload, fp);*/

			memcpy(pData + nOffset, m_pNals[i].p_payload, m_pNals[i].i_payload);
			nOffset += m_pNals[i].i_payload;
		}

		streamHeader.dataLen = nOffset;
		streamHeader.frameType = J_VideoIFrame;
	}

	RWUnlock(m_rwLocker);
	return J_OK;
}
Example #6
0
void main()
{
   char szName[80];
   unsigned char szHolder[500], nSpaceCount = 0, nHighestVal = 0, nTot = 0;
   long lPos = 0, lToSkip;

   randomize();
   printf("Enter Sysop name   >");
   gets(szName);

   if ( strlen(szName) < 3 )
      exit(0);

   for ( short n = 0; n < strlen(szName); n++ )
      {
      if ( szName[n] == ' ' )
         nSpaceCount++;
      if ( szName[n] > nHighestVal )
         nHighestVal = szName[n];
      nTot += szName[n]/2;
      }

   szHolder[lPos++] = encode(strlen(szName), 0);
   szHolder[lPos++] = encode(nSpaceCount, 1);
   szHolder[lPos++] = encode(szName[2], 2);
   szHolder[lPos++] = encode(szName[strlen(szName)-1], 3);
   szHolder[lPos++] = encode(nHighestVal, 4);
   szHolder[lPos++] = encode(strlen(szName), 5);
   szHolder[lPos++] = encode(nTot, 6);
   
   strrev(szName);
   
   for ( short n = 0; n < strlen(szName); n++ )
      {
      szHolder[lPos] = encode(szName[n], lPos);
      lPos++;
      szHolder[lPos] = random(204) + 50;
      lToSkip = szHolder[lPos] / 50;
      szHolder[lPos] = ~szHolder[lPos];
      lPos++;

      unsigned char nSum = 7;
      for ( short k = 0; k < lToSkip; k++ )
         {
         szHolder[lPos] = random(250);
         nSum += szHolder[lPos]/6;
         lPos++;
         }
      szHolder[lPos++] = nSum;
      }

   fstream myFile;
   myFile.open("e:\\ttreg.dat", ios::binary | ios::out | ios::trunc );
   myFile.write(szHolder, lPos);
   myFile.close();

   myFile.open("e:\\doors\\trivia\\regs.log", ios::out | ios::app);
   myFile.write(strrev(szName), strlen(szName));
   char szText[120], szFullDate[12];
   _strdate(szFullDate);
   sprintf(szText, "\n  Registered on %s\n", szFullDate);
   myFile.write(szText, strlen(szText));
   sprintf(szText, "  File size: %ld\n  First ten bytes: ", lPos);
   for ( short n = 0; n < 10; n++ )
      {
      sprintf(szFullDate, "%u ", szHolder[n]);
      strcat(szText, szFullDate);
      }
   strcat(szText, "\n\n");
   myFile.write(szText, strlen(szText));
   printf("\nFile created and logged.\n");

   char szCheckName[80];
   short nStatus = getRegName(szCheckName, szHolder, lPos);
   printf("  -> Reg status: %d; %s.\n\n", nStatus, szCheckName);
}
Example #7
0
void URI::setQuery(const std::string& query)
{
	_query.clear();
	encode(query, RESERVED_QUERY, _query);
}
Example #8
0
int main(int argc, char **argv) {

	int i, j, count = 0, encode_result_length, first_num, second_num, elecount, rows, personal_number = DEFAULT_PERSONAL_NUMBER, c;
	int date_len, verbose = 0, keyphrase_len;
	char t;

	int *date = DEFAULT_DATE;
	date_len = 6;
	int *random_ig = DEFAULT_RANDOM;


	/*Initialize the pointers that we'll need later */
	int *temp, *first_app_res, *assign_res, *header_checker, *first, *second;
	int *encode_result, *transpose_select, *new_header, *chain_res, *append_res, *sub_result;
	int **pseudo_random, **transpose_res, **second_num_trans, **final_res, **inter_trans, **message_matrix;

	char *key_phrase = DEFAULT_KEYPHRASE;
	keyphrase_len = strlen(key_phrase);
	
	char *message = DEFAULT_MESSAGE;


	while ((c = getopt_long(argc, argv, "d:p:k:m:v", longopts, NULL)) != -1)
        	switch (c) {
			case 'd':
				date_len = strlen(optarg);
				date = malloc(sizeof(int) * date_len);
				i = 0;
				while(i < strlen(optarg)) {
					t = optarg[i];
					if(t == 0) {
						fprintf (stderr, "--date must be in the form DDMMYYYY.\n");
						return -1;
					}
					date[i++] = atoi(&t);
				}

			break;

		        case 'p':
				personal_number = atoi(optarg);

				if(personal_number > 16) {
					fprintf (stderr, "--personal must be < 16 strictly.\n");
					return -1;
				}
		        break;
	
			case 'k':
				key_phrase = optarg;
				if(strlen(key_phrase) < 20) fprintf (stderr, "--personal must be < 16 strictly.\n");
				if(strlen(key_phrase) % 2 != 0) fprintf (stderr, "--personal must be divisible by two.\n");
				keyphrase_len = strlen(key_phrase);
			break;

			case 'm':
				message = optarg;
			break;

			case 'v':
				verbose = 1;
			break;

	                case '?':
             			if (optopt == 'k' || optopt == 'm' || optopt == 'd' || optopt == 'p')
					fprintf (stderr, "Option -%c requires an argument.\n", optopt);
			        else if (isprint (optopt))
					fprintf (stderr, "Unknown option `-%c'.\n", optopt);
             			else
			                fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
                                return -1;
			default:
				abort();
				return -1;
        }



	sub_result = modular_subtraction_digit(random_ig, date, 5);

	if(verbose == 1) {

		printf("\n1. Subtraction result:\n");

		for(i = 0; i < 5; i++) 
			printf("%d ", sub_result[i]);

		printf("\n \n");

	}

	first = assign_char(key_phrase, 0, keyphrase_len / 2, 65); 
	second = assign_char(key_phrase, keyphrase_len / 2, 10, 65); 


	if(verbose == 1) {

		printf("2. First character assigned result:\n");

		for(i = 0; i < keyphrase_len / 2; i++) 
			printf("%d ", first[i]);

		printf("\n\n");


		printf("3. Second character assigned result:\n");

		for(i = 0; i < keyphrase_len / 2; i++) 
			printf("%d ", second[i]);

		printf("\n\n");

	}

	chain_res = chain_addition(sub_result, 5);

	if(verbose == 1) {

		printf("4. Chain addition result for the subtraction performed earlier:\n");

		for(i = 0; i < 5; i++) 
			printf("%d ", chain_res[i]);

		printf("\n\n");

	}

	append_res = join(sub_result, 5, chain_res, 5);

	if(verbose == 1) {

		printf("5. Joining both 1 and 4, we get:\n");

		for(i = 0; i < 10; i++) 
			printf("%d ", append_res[i]);

		printf("\n\n");

	}
	
	free(sub_result);
	free(chain_res);
	
	first_app_res = modular_addition_digit(first, append_res, 10);

	if(verbose == 1) {

		printf("6. Adding 2 and 5 modularly, we get:\n");

		for(i = 0; i < 10; i++) 
			printf("%d ", first_app_res[i]);

		printf("\n\n");

	}	

	assign_res = map_change(second, first_app_res, 10);

	if(verbose == 1) {

		printf("7. Mapping 6 according to 3, we get:\n");

		for(i = 0; i < 10; i++) 
			printf("%d ", assign_res[i]);

		printf("\n\n");

	}	


	free(first_app_res);
	
	pseudo_random = malloc(sizeof(int*) * 5);

	temp = assign_res;
	for(i = 0; i < 5; i++) {
		temp=chain_addition(temp,10);
		pseudo_random[i]=temp;
	}

	if(verbose == 1) {

		printf("8. Performing chain addition on 7, we get:\n");

		for(i = 0; i < 5; i++) {
			for(j = 0; j <10; j++) {
				printf("%d ", pseudo_random[i][j]);
			}
			printf("\n");
		}

		printf("\n");
	}
	

	header_checker = assign_int(pseudo_random[4], 0, 10);

	if(verbose == 1) {

		printf("8. The header for our checkerboard that we use is:\n");

		for(i = 0; i < 10; i++) {
			printf("%d ", header_checker[i]);
		}

		printf("\n\n");
	}

	encode_result = encode(message, header_checker, strlen(message));

	encode_result_length = get_encode_message_length(encode_result);

	if(verbose == 1) {

		printf("8. The encoded message is:\n");

		for(i = 0; i < encode_result_length; i++) {
			printf("%d ", encode_result[i]);
		}

		printf("\n\n");

		printf("9. The message's length is: %d\n", encode_result_length);

		printf("\n\n");

	}

	first_num = personal_number + pseudo_random[4][8];
	second_num = personal_number + pseudo_random[4][9];

	if(verbose == 1) {

		printf("10. The first and second number are: %d %d\n", first_num, second_num);

		printf("\n\n");

	}
	
	transpose_res = transpose(assign_res, pseudo_random, 10, 5);

	if(verbose == 1) {

		printf("11. The transpose of 8 wrt 7 is:\n");

		for(i = 0; i < 10; i++) {
			for(j = 0; j < 5; j++) 
				printf("%d ", transpose_res[i][j]);
			printf("\n");
		}

		printf("\n\n");

	}
	
	free(temp);
	
	transpose_select = malloc(sizeof(int) * (first_num + second_num));

	for(i = 0; i < 10; i++) {
		for(j = 0; j < 5; j++) {
			transpose_select[count++] = transpose_res[i][j];
			if (count == (first_num + second_num)) break;
		}
			if (count == (first_num + second_num)) break;
	}


	if(verbose == 1) {

		printf("12. The %d elements of 11 are:\n", first_num + second_num);

		for(i = 0; i < first_num + second_num; i++) {
			printf("%d ", transpose_select[i]);
		}

		printf("\n\n");

	}
	
	message_matrix = get_matrix(encode_result, encode_result_length, first_num);
	free(encode_result);

	elecount = encode_result_length + ((5 - (encode_result_length % 5)) % 5);
	rows = elecount / first_num;
	if(encode_result_length % first_num !=  0) rows =rows + 1;


	if(verbose == 1) {

		printf("13. Our message in 8 as a matrix is:\n");

		for(i = 0; i < rows; i++) {
			for(j = 0; j < first_num; j++) 
				printf("%d ", message_matrix[i][j]);
			printf("\n");
		}

		printf("\n\n");

	}
	

	
	inter_trans = transpose(transpose_select, message_matrix, first_num, rows);

	if(verbose == 1) {

		printf("14. Transpose of 13 using the first %d elements of 12 is:\n", first_num);

		for(i = 0; i < first_num; i++) {
			for(j = 0; j < rows; j++) 
				printf("%d ", inter_trans[i][j]);
			printf("\n");
		}

		printf("\n\n");

	}

	new_header = copy(transpose_select, first_num, first_num + second_num);

	if(verbose == 1) {

		printf("15. The last %d elements of 12 are:\n", second_num);

		for(i = first_num; i < first_num + second_num; i++) {
			printf("%d ", transpose_select[i]);
		}

		printf("\n\n");

	}

	second_num_trans = get_matrix_filled(inter_trans, first_num, rows, elecount, new_header, second_num);


	rows = elecount / second_num;
	if(encode_result_length % second_num !=  0) rows =rows + 1;

	if(verbose == 1) {

		printf("14. Filling in the matrix using the %d elements of 15 is:\n", second_num);

		for(i = 0; i < rows; i++) {
			for(j = 0; j < second_num; j++) 
				printf("%d ", second_num_trans[i][j]);
			printf("\n");
		}

		printf("\n\n");

	}


	final_res = transpose(new_header, second_num_trans, second_num, rows);
	free(new_header);
	
	elecount = 1;

	date[date_len - 1] = (date[date_len - 1] == 0) ? 10: date[date_len - 1];

	if(verbose == 1) {

		printf("16. The result is:\n");

	}
	
	for(i = 0; i < second_num; i++) {
		for(j = 0; j < rows; j++) {
			if(final_res[i][j] != -1) {
				printf("%d ", final_res[i][j]); 
				elecount++;	
				if(((elecount) % date[date_len - 1]) == 0) {
					elecount = 1; 
					printf("\n");
				}				
			}
		}
	}

	printf("\n");

	return 0;
}
Example #9
0
std::string encoder::encode() {
    std::string s;
    encode(s);
    return s;
}
Example #10
0
/**
 *
 * Will compute ktuple scores and store in tmat
 * Following values will be set: tmat[i][j], where
 * istart <= i <iend
 * and
 * jstart <= j < jend
 * i.e. zero-offset
 * tmat data members have to be preallocated
 *
 * if ktuple_param_t *aln_param == NULL defaults will be used
 */
void
KTuplePairDist(symmatrix_t *tmat, mseq_t *mseq,
               int istart, int iend,
               int jstart, int jend,
               ktuple_param_t *param_override,
               progress_t *prProgress, 
               unsigned long int *ulStepNo, unsigned long int ulTotalStepNo)
{
    /* this first group of variables were previously static
       and hence un-parallelisable */
    char **seq_array;
    int maxsf;
    int **accum;
    int max_aln_length;
    /* divide score with length of smallest sequence */
    int *zza, *zzb, *zzc, *zzd;
    int private_step_no = 0;

    int i, j, dsr;
    double calc_score;
    int max_res_code = -1;

    int max_seq_len;
    int *seqlen_array;
    /* progress_t *prProgress; */
    /* int uStepNo, uTotalStepNo; */
    ktuple_param_t aln_param = default_protein_param;
    bool bPrintCR = (rLog.iLogLevelEnabled<=LOG_VERBOSE) ? FALSE : TRUE;


    if(prProgress == NULL) {
        NewProgress(&prProgress, LogGetFP(&rLog, LOG_INFO), 
                    "Ktuple-distance calculation progress", bPrintCR);
    }

    /* conversion to old style data types follows
     *
     */

    seqlen_array = (int*) CKMALLOC((mseq->nseqs+1) * sizeof(int));
    for (i=0; i<mseq->nseqs; i++) {
        seqlen_array[i+1] = mseq->sqinfo[i].len;
    }

    /* setup alignment parameters
     */
    if (SEQTYPE_PROTEIN == mseq->seqtype) {
        DNAFLAG = FALSE;
        max_res_code = strlen(AMINO_ACID_CODES)-2;
        aln_param = default_protein_param;

    } else if (SEQTYPE_RNA == mseq->seqtype || SEQTYPE_DNA == mseq->seqtype) {
        DNAFLAG = TRUE;
        max_res_code = strlen(NUCLEIC_ACID_CODES)-2;
        aln_param = default_dna_param;

    } else {
        Log(&rLog, LOG_FATAL, "Internal error in %s: Unknown sequence type.", __FUNCTION__);
    }

    if (NULL!=param_override) {
        aln_param.ktup = param_override->ktup;
        aln_param.wind_gap = param_override->wind_gap;
        aln_param.signif = param_override->signif;
        aln_param.window = param_override->window;
    }

    /*LOG_DEBUG("DNAFLAG = %d max_res_code = %d", DNAFLAG, max_res_code);*/

    /* convert mseq to clustal's old-style int encoded sequences (unit-offset)
     */
    max_aln_length = 0;
    max_seq_len = 0;
    seq_array =  (char **) CKMALLOC((mseq->nseqs+1) * sizeof(char *));
    seq_array[0] = NULL;
    /* FIXME check that non of the seqs is smaller than ktup (?).
     * Otherwise segfault occurs
     */
    for (i=0; i<mseq->nseqs; i++) {
        seq_array[i+1] = (char *) CKMALLOC((seqlen_array[i+1]+2) * sizeof (char));;
    }
    for (i=0; i<mseq->nseqs; i++) {
        /*LOG_DEBUG("calling encode with seq_array[%d+1] len=%d and seq=%s",
          i, seqlen_array[i+1], mseq->seq[i]);*/
        if (TRUE == DNAFLAG) {
            encode(&(mseq->seq[i][-1]), seq_array[i+1],
                   seqlen_array[i+1], NUCLEIC_ACID_CODES);
        } else  {
            encode(&(mseq->seq[i][-1]), seq_array[i+1],
                   seqlen_array[i+1], AMINO_ACID_CODES);
        }

        if (seqlen_array[i+1]>max_seq_len) {
            max_seq_len = seqlen_array[i+1];
        }
    }
    max_aln_length = max_seq_len * 2;
    /* see sequence.c in old source */

    /* FIXME: short sequences can cause seg-fault 
     * because max_aln_length can get shorter 
     * than (max_res_code+1)^k 
     * FS, r222->r223 */
    max_aln_length = max_aln_length > pow((max_res_code+1), aln_param.ktup)+1 ? 
        max_aln_length : pow((max_res_code+1), aln_param.ktup)+1;

    /*
     *
     * conversion to old style clustal done (in no time) */


    accum = (int **) CKCALLOC(5, sizeof (int *));
    for (i=0;i<5;i++) {
        accum[i] = (int *) CKCALLOC((2*max_aln_length+1), sizeof(int));
    }
    zza = (int *) CKCALLOC( (max_aln_length+1), sizeof(int));
    zzb = (int *) CKCALLOC( (max_aln_length+1), sizeof(int));
    zzc = (int *) CKCALLOC( (max_aln_length+1), sizeof(int));
    zzd = (int *) CKCALLOC( (max_aln_length+1), sizeof(int));

    /* estimation of total number of steps (if istart and jstart are
     * both 0) (now handled in the calling routine)
     */
    /* uTotalStepNo = iend*jend - iend*iend/2 + iend/2;
    uStepNo = 0; */
    /*LOG_DEBUG("istart=%d iend=%d jstart=%d jend=%d", istart, iend, jstart, jend);*/

    for (i=istart+1; i<=iend; ++i) {
        /* by definition a sequence compared to itself should give
           a score of 0. AW */
        SymMatrixSetValue(tmat, i-1, i-1, 0.0);
        make_ptrs(zza, zzc, i, seqlen_array[i], aln_param.ktup, max_res_code, seq_array);

#ifdef HAVE_OPENMP
        #pragma omp critical(ktuple)
#endif
        {
            ProgressLog(prProgress, *ulStepNo, ulTotalStepNo, FALSE);
        }

        for (j=MAX(i+1, jstart+1); j<=jend; ++j) {
            (*ulStepNo)++;
            private_step_no++;
            /*LOG_DEBUG("comparing pair %d:%d", i, j);*/

            make_ptrs(zzb, zzd, j, seqlen_array[j], aln_param.ktup, max_res_code, seq_array);
            pair_align(i, seqlen_array[i], seqlen_array[j], max_res_code, &aln_param,
                seq_array, &maxsf, accum, max_aln_length, zza, zzb, zzc, zzd);

            if (!maxsf) {
                calc_score=0.0;
            } else {
                calc_score=(double)accum[0][maxsf];
                if (percent) {
                    dsr=(seqlen_array[i]<seqlen_array[j]) ?
                        seqlen_array[i] : seqlen_array[j];
                    calc_score = (calc_score/(double)dsr) * 100.0;
                }
            }

            /* printf("%d %d %d\n", i-1, j-1, (100.0 - calc_score)/100.0); */
            SymMatrixSetValue(tmat, i-1, j-1, (100.0 - calc_score)/100.0);

            /* the function allows you not to compute the full matrix.
             * here we explicitely make the resulting matrix a
             * rectangle, i.e. we always set full rows. in other
             * words, if we don't complete the full matrix then we
             * don't have a full symmetry. so only use the defined
             * symmetric part. AW
             */
            /*LOG_DEBUG("setting %d : %d = %f", j, i, tmat[i][j]);*/
            /* not needed anymore since we use symmatrix_t
               if (j<=iend) {
               tmat[j][i] = tmat[i][j];
               }
            */
#ifdef HAVE_OPENMP
            #pragma omp critical(ktuple)
#endif
            {
                Log(&rLog, LOG_DEBUG, "K-tuple distance for sequence pair %d:%d = %lg",
                    i, j, SymMatrixGetValue(tmat, i-1, j-1));
            }
        }
    }
    /*
      Log(&rLog, LOG_FORCED_DEBUG, "uTotalStepNo=%d for istart=%d iend=%d jstart=%d jend=%d", uStepNo, istart, iend, jstart, jend);
      Log(&rLog, LOG_FORCED_DEBUG, "Fabian = %d", iend*jend - iend*iend/2 + iend/2);
    */

/*    printf("\n\n%d\t%d\t%d\t%d\n\n", omp_get_thread_num(), uStepNo, istart, iend); */

    for (i=0;i<5;i++) {
        CKFREE(accum[i]);
    }
    CKFREE(accum);

#ifdef HAVE_OPENMP
    #pragma omp critical(ktuple)
#if 0
    {
    printf("steps: %d\n", private_step_no);
    }
#endif
#endif

    CKFREE(zza);
    CKFREE(zzb);
    CKFREE(zzc);
    CKFREE(zzd);

    free(seqlen_array);

    for (i=1; i<=mseq->nseqs; i++) {
        CKFREE(seq_array[i]);
    }
    CKFREE(seq_array);
}
Example #11
0
unsigned long * compress_site_patterns_diploid(char ** sequence,
                                               const unsigned int * map,
                                               int count,
                                               int * length,
                                               unsigned int ** wptr,
                                               int attrib)
{
  int i,j;
  char * memptr;
  char ** column;
  unsigned int * weight;
  unsigned long * mapping;
  unsigned char ** jc69_invmaps = NULL;

  unsigned char charmap[ASCII_SIZE];
  unsigned char inv_charmap[ASCII_SIZE];

  /* check that at least one sequence is given */
  if (!count) return NULL;

  /* a map must be given */
  if (!map) return NULL;

  /* a zero can never be used as a state */
  if (map[0]) return NULL;

  /* if map states are out of the BYTE range, remap */
  if (findmax(map) >= ASCII_SIZE)
  {
    remap_range(map,charmap);

    /* for now only DNA with pll_map_nt */
    assert(0);
  }
  else
  {
    for (i = 0; i < ASCII_SIZE; ++i)
      charmap[i] = (unsigned char)(map[i]);
  }

  /* create inverse charmap to decode states back to characters when
     compression is finished */
  for (i = 0; i < ASCII_SIZE; ++i)
    if (map[i])
      inv_charmap[charmap[i]] = (unsigned char)i;

  /* encode sequences using charmap */
  encode(sequence,charmap,count,*length);

  /* allocate memory for columns */
  column = (char **)xmalloc((size_t)(*length)*sizeof(char *));

  /* allocate memory for the alignment */
  memptr = column[0] = (char *)xmalloc((size_t)(*length) *
                                       (size_t)(count+1) *
                                       sizeof(char));

  /* map memory to each column */
  for (i = 1; i < *length; ++i)
    column[i] = column[i-1] + (count+1);

  /* allocate space for weight vector */
  weight = (unsigned int *)xmalloc((size_t)(*length)*sizeof(unsigned int));

  /* allocate space for mapping vector */
  mapping = (unsigned long *)xmalloc((size_t)(*length)*sizeof(unsigned long));

  /* split alignment into columns instead of rows */
  for (i = 0; i < (*length); ++i)
  {
    for (j = 0; j < count; ++j)
      column[i][j] = sequence[j][i];
    column[i][j] = 0;
  }

  /* allocate space for storing original indices (before sorting sites) */
  int * oi = (int *)xmalloc(*length * sizeof(int));
  for (i = 0; i < *length; ++i)
    oi[i] = i;

    /* do the jc69 now */
  if (attrib == COMPRESS_JC69)
    jc69_invmaps = encode_jc69(column,*length,count);

  /* sort the columns and keep original indices */
  ssort1(column, *length, 0, oi);

  /*first site in uncompressed alignment maps to first site in compressed */
  int compressed_length = 1;
  size_t ref = 0;
  mapping[0] = 0;
  weight[ref] = 1;

  /* find all unique columns and set their mappings A2->A3 */
  int * compressed_oi = (int *)xmalloc(*length * sizeof(int));

  compressed_oi[0] = oi[0];
  for (i = 1; i < *length; ++i)
  {
    if (strcmp(column[i],column[i-1]))
    {
      column[ref+1] = column[i];
      compressed_oi[ref+1] = oi[i];
      ++ref;
      ++compressed_length;
      weight[ref] = 1;
    }
    else
      weight[ref]++;

    /* map original index i in uncompressed alignment to index in compressed */
    mapping[oi[i]] = ref;
  }

  /* decode the jc69 encoding */
  if (attrib == COMPRESS_JC69)
  {
    for (i=0; i < compressed_length; ++i)
    {
      unsigned char * sitemap = jc69_invmaps[compressed_oi[i]];
      if (sitemap)
        for (j=0; j < count; ++j)
          column[i][j] = sitemap[(unsigned int)column[i][j]];
    }
    for (i = 0; i < *length; ++i)
      if (jc69_invmaps[i])
        free(jc69_invmaps[i]);
    free(jc69_invmaps);
  }

  /* copy the unique columns over the original sequences */
  for (i = 0; i < compressed_length; ++i)
    for (j = 0; j < count; ++j)
      sequence[j][i] = column[i][j];

  /* add terminating zero */
  for (j = 0; j < count; ++j)
    sequence[j][compressed_length] = 0;

  /* deallocate memory */
  free(memptr);
  free(column);


  /* adjust weight vector size to compressed length */
  unsigned int * mem = (unsigned int *)xmalloc((size_t)compressed_length *
                                               sizeof(unsigned int));
  if (mem)
  {
    /* copy weights */
    for (i = 0; i < compressed_length; ++i)
      mem[i] = weight[i];

    /* free and re-point */
    free(weight);
    weight = mem;
  }
  *wptr = weight;

  /* update length */
  *length = compressed_length;

  /* decode sequences using inv_charmap */
  encode(sequence,inv_charmap,count,compressed_length);

  free(oi);
  free(compressed_oi);

  return mapping;
}
Example #12
0
int
main(int argc, char **argv)
{
    SECStatus rv;
    int retval = -1;
    CERTCertDBHandle *certHandle = NULL;
    CERTCertificate *caCert = NULL, *cert = NULL;
    CERTOCSPCertID *cid = NULL;
    PLArenaPool *arena = NULL;
    PRTime now = PR_Now();
    
    SECItem *encoded = NULL;
    CERTOCSPResponse *decoded = NULL;
    SECStatus statusDecoded;

    SECItem *encodedRev = NULL;
    CERTOCSPResponse *decodedRev = NULL;
    SECStatus statusDecodedRev;
    
    SECItem *encodedFail = NULL;
    CERTOCSPResponse *decodedFail = NULL;
    SECStatus statusDecodedFail;

    CERTCertificate *obtainedSignerCert = NULL;

    if (argc != 4 && argc != 6) {
        return Usage();
    }

    if (argc == 6) {
        if (!strcmp(argv[4], "-p")) {
            pwdata.source = PW_PLAINTEXT;
            pwdata.data = PORT_Strdup(argv[5]);
        }
        else if (!strcmp(argv[4], "-f")) {
            pwdata.source = PW_FROMFILE;
            pwdata.data = PORT_Strdup(argv[5]);
        }
        else
            return Usage();
    }

    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    /*rv = NSS_Init(SECU_ConfigDirectory(NULL));*/
    rv = NSS_Init(argv[1]);
    if (rv != SECSuccess) {
	SECU_PrintPRandOSError(argv[0]);
	goto loser;
    }

    PK11_SetPasswordFunc(SECU_GetModulePassword);

    certHandle = CERT_GetDefaultCertDB();
    if (!certHandle)
	goto loser;

    if (!getCaAndSubjectCert(certHandle, argv[2], argv[3], &caCert, &cert))
        goto loser;

    cid = CERT_CreateOCSPCertID(cert, now);

    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    encoded = encode(arena, cid, caCert);
    PORT_Assert(encoded);
    decoded = CERT_DecodeOCSPResponse(encoded);
    statusDecoded = CERT_GetOCSPResponseStatus(decoded);
    PORT_Assert(statusDecoded == SECSuccess);

    statusDecoded = CERT_VerifyOCSPResponseSignature(decoded, certHandle, &pwdata,
                                                &obtainedSignerCert, caCert);
    PORT_Assert(statusDecoded == SECSuccess);
    statusDecoded = CERT_GetOCSPStatusForCertID(certHandle, decoded, cid,
                                                obtainedSignerCert, now);
    PORT_Assert(statusDecoded == SECSuccess);
    CERT_DestroyCertificate(obtainedSignerCert);

    encodedRev = encodeRevoked(arena, cid, caCert);
    PORT_Assert(encodedRev);
    decodedRev = CERT_DecodeOCSPResponse(encodedRev);
    statusDecodedRev = CERT_GetOCSPResponseStatus(decodedRev);
    PORT_Assert(statusDecodedRev == SECSuccess);

    statusDecodedRev = CERT_VerifyOCSPResponseSignature(decodedRev, certHandle, &pwdata,
                                                        &obtainedSignerCert, caCert);
    PORT_Assert(statusDecodedRev == SECSuccess);
    statusDecodedRev = CERT_GetOCSPStatusForCertID(certHandle, decodedRev, cid,
                                                   obtainedSignerCert, now);
    PORT_Assert(statusDecodedRev == SECFailure);
    PORT_Assert(PORT_GetError() == SEC_ERROR_REVOKED_CERTIFICATE);
    CERT_DestroyCertificate(obtainedSignerCert);
    
    encodedFail = CERT_CreateEncodedOCSPErrorResponse(
        arena, SEC_ERROR_OCSP_TRY_SERVER_LATER);
    PORT_Assert(encodedFail);
    decodedFail = CERT_DecodeOCSPResponse(encodedFail);
    statusDecodedFail = CERT_GetOCSPResponseStatus(decodedFail);
    PORT_Assert(statusDecodedFail == SECFailure);
    PORT_Assert(PORT_GetError() == SEC_ERROR_OCSP_TRY_SERVER_LATER);

    retval = 0;
loser:
    if (retval != 0)
        SECU_PrintError(argv[0], "tests failed");
    
    if (cid)
        CERT_DestroyOCSPCertID(cid);
    if (cert)
        CERT_DestroyCertificate(cert);
    if (caCert)
        CERT_DestroyCertificate(caCert);
    if (arena)
        PORT_FreeArena(arena, PR_FALSE);
    if (decoded)
        CERT_DestroyOCSPResponse(decoded);
    if (decodedRev)
        CERT_DestroyOCSPResponse(decodedRev);
    if (decodedFail)
        CERT_DestroyOCSPResponse(decodedFail);
    if (pwdata.data) {
        PORT_Free(pwdata.data);
    }
    
    if (NSS_Shutdown() != SECSuccess) {
        SECU_PrintError(argv[0], "NSS shutdown:");
        if (retval == 0)
            retval = -2;
    }

    return retval;
}
Example #13
0
int main(int argc, char* argv[]){
	if (argc < 2){
		fprintf(stderr,"No se especifico ningun comando\n");
		return 1;
	}
	TParseArg* args;
	char *output = NULL;
	char *input = NULL;
	int* res = NULL;
	FILE* inFile;
	FILE* outFile;

	// Creo el parseador de argumentos
	args = ParseArg_new(6);
	// Agrego los argumentos a parsear, si uso valores por defecto como NULL con tama~no 0,
	// estoy haciendo qe sean obligatorios los argumentos
	ParseArg_addArg(args, NULL, 'h', "help", NULL, 0);
	ParseArg_addArg(args, NULL, 'v', "version", NULL, 0);
	ParseArg_addArg(args, NULL, 'e', "encode", NULL, 0);
	ParseArg_addArg(args, NULL, 'd', "decode", NULL, 0);
	ParseArg_addArg(args, &ParseArg_parseStr, 'o', "output", NULL, 0);
	ParseArg_addArg(args, &ParseArg_parseStr, 'i', "input", NULL, 0);
	ParseArg_parse(args, argc, argv);

	if(ParseArg_getArg(args, 'h')){
		usage();
		ParseArg_delete(args);
		return 0;
	}

	if(ParseArg_getArg(args, 'v')){
		version(argv[0]);
		ParseArg_delete(args);
		return 0;
	}
	input = (char*) ParseArg_getArg(args, 'i');
	output = (char*) ParseArg_getArg(args, 'o');

	if(input == NULL){
		inFile = stdin;
	}else{
		inFile = fopen(input, "r");
		if(!inFile){
			free(input);
			ParseArg_delete(args);
			return 1;
		}
	}

	if(output == NULL){
		outFile = stdout;
	}else{
		outFile = fopen(output, "wb");
		if(!outFile){
			free(output);
			ParseArg_delete(args);
			return 1;
		}
	}

	if(ParseArg_getArg(args, 'e')){
		encode(inFile,outFile);
		ParseArg_delete(args);
		return 0;
	}

	if(ParseArg_getArg(args, 'd')){
		decode(inFile,outFile);
		ParseArg_delete(args);
		return 0;
	}


	if( !(ParseArg_getArg(args,'e')) || !(ParseArg_getArg(args,'d')) || !(ParseArg_getArg(args,'h')) || !(ParseArg_getArg(args,'v'))){
		perror("No se especifico un comando valido");
		return 1;
	}

	
	if(outFile != stdout)
		fclose(outFile);

	if(inFile != stdin)
		fclose(inFile);

	free(res);
	free(output);
	free(input);
	ParseArg_delete(args);

	return 0;
}
Example #14
0
//---------------------------------------------------------------------------
static bool transformSubquery(DictionarySegment& dict,DifferentialIndex* diffIndex,const SPARQLParser::PatternGroup& group,QueryGraph::SubQuery& output)
   // Transform a subquery
{
   // Encode all patterns
   for (std::vector<SPARQLParser::Pattern>::const_iterator iter=group.patterns.begin(),limit=group.patterns.end();iter!=limit;++iter) {
      // Encode the entries
      QueryGraph::Node node;
      if ((!encode(dict,diffIndex,(*iter).subject,node.subject,node.constSubject))||
          (!encode(dict,diffIndex,(*iter).predicate,node.predicate,node.constPredicate))||
          (!encode(dict,diffIndex,(*iter).object,node.object,node.constObject))) {
         // A constant could not be resolved. This will produce an empty result
         return false;
      }
      output.nodes.push_back(node);
   }

   // Encode the filter conditions
   for (std::vector<SPARQLParser::Filter>::const_iterator iter=group.filters.begin(),limit=group.filters.end();iter!=limit;++iter) {
      if (((*iter).type==SPARQLParser::Filter::Function)&&((*iter).arg1->value==tableFunctionId)) {
         encodeTableFunction(group,*iter,output);
         continue;
      }
      if (!encodeFilter(dict,diffIndex,group,*iter,output)) {
         // The filter variable is not bound. This will produce an empty result
         return false;
      }
   }

   // Encode all optional parts
   for (std::vector<SPARQLParser::PatternGroup>::const_iterator iter=group.optional.begin(),limit=group.optional.end();iter!=limit;++iter) {
      QueryGraph::SubQuery subQuery;
      if (!transformSubquery(dict,diffIndex,*iter,subQuery)) {
         // Known to produce an empty result, skip it
         continue;
      }
      output.optional.push_back(subQuery);
   }

   // Encode all union parts
   for (std::vector<std::vector<SPARQLParser::PatternGroup> >::const_iterator iter=group.unions.begin(),limit=group.unions.end();iter!=limit;++iter) {
      std::vector<QueryGraph::SubQuery> unionParts;
      for (std::vector<SPARQLParser::PatternGroup>::const_iterator iter2=(*iter).begin(),limit2=(*iter).end();iter2!=limit2;++iter2) {
         QueryGraph::SubQuery subQuery;
         if (!transformSubquery(dict,diffIndex,*iter2,subQuery)) {
            // Known to produce an empty result, skip it
            continue;
         }
         unionParts.push_back(subQuery);
      }
      // Empty union?
      if (unionParts.empty())
         return false;
      output.unions.push_back(unionParts);
   }

   // Encode all gjoin parts - Hancel y Giuseppe
   for (std::vector<std::vector<SPARQLParser::PatternGroup> >::const_iterator iter=group.gjoins.begin(),limit=group.gjoins.end();iter!=limit;++iter) {
      std::vector<QueryGraph::SubQuery> gjoinParts;
      for (std::vector<SPARQLParser::PatternGroup>::const_iterator iter2=(*iter).begin(),limit2=(*iter).end();iter2!=limit2;++iter2) {
         QueryGraph::SubQuery subQuery;
         if (!transformSubquery(dict,diffIndex,*iter2,subQuery)) {
            // Known to produce an empty result, skip it
            continue;
         }
         gjoinParts.push_back(subQuery);
      }
      // Empty gjoin?
      if (gjoinParts.empty())
         return false;
      output.gjoins.push_back(gjoinParts);
   }

   return true;
}
Example #15
0
static int foreach(struct dbengine *db,
                   const char *prefix, size_t prefixlen,
                   foreach_p *goodp,
                   foreach_cb *cb, void *rock,
                   struct txn **mytid)
{
    int r = CYRUSDB_OK;
    int offset;
    unsigned long len;
    const char *p, *pend;
    const char *dataend;

    /* for use inside the loop, but we need the values to be retained
     * from loop to loop */
    struct buf keybuf = BUF_INITIALIZER;
    int dontmove = 0;

    /* For when we have a transaction running */
    struct buf savebuf = BUF_INITIALIZER;

    /* for the local iteration so that the db can change out from under us */
    const char *dbbase = NULL;
    size_t dblen = 0;
    int dbfd = -1;

    struct buf prefixbuf = BUF_INITIALIZER;

    r = starttxn_or_refetch(db, mytid);
    if (r) return r;

    if (!mytid) {
        /* No transaction, use the fast method to avoid stomping on our
         * memory map if changes happen */
        dbfd = dup(db->fd);
        if(dbfd == -1) return CYRUSDB_IOERROR;

        map_refresh(dbfd, 1, &dbbase, &dblen, db->size, db->fname, 0);

        /* drop our read lock on the file, since we don't really care
         * if it gets replaced out from under us, our mmap stays on the
         * old version */
        lock_unlock(db->fd, db->fname);
    }
    else {
        /* use the same variables as in the no transaction case, just to
         * get things set up */
        dbbase = db->base;
        dblen = db->len;
    }

    if (prefix) {
        encode(prefix, prefixlen, &prefixbuf);
        offset = bsearch_mem_mbox(prefixbuf.s, dbbase, db->size, 0, &len);
    }
    else {
        offset = 0;
    }

    p = dbbase + offset;
    pend = dbbase + db->size;

    while (p < pend) {
        if (!dontmove) {
            GETENTRY(p)
        }
        else dontmove = 0;

        /* does it still match prefix? */
        if (keybuf.len < (size_t) prefixbuf.len) break;
        if (prefixbuf.len && memcmp(keybuf.s, prefixbuf.s, prefixbuf.len)) break;

        if (!goodp || goodp(rock, keybuf.s, keybuf.len, DATA(db), DATALEN(db))) {
            unsigned long ino = db->ino;
            unsigned long sz = db->size;

            if(mytid) {
                /* transaction present, this means we do the slow way */
                buf_copy(&savebuf, &keybuf);
            }

            /* make callback */
            r = cb(rock, keybuf.s, keybuf.len, DATA(db), DATALEN(db));
            if (r) break;

            if (mytid) {
                /* reposition? (we made a change) */
                if (!(ino == db->ino && sz == db->size)) {
                    /* something changed in the file; reseek */
                    buf_cstring(&savebuf);
                    offset = bsearch_mem_mbox(savebuf.s, db->base, db->size,
                                              0, &len);
                    p = db->base + offset;

                    GETENTRY(p);

                    /* 'key' might not equal 'savebuf'.  if it's different,
                       we want to stay where we are.  if it's the same, we
                       should move on to the next one */
                    if (!buf_cmp(&savebuf, &keybuf)) {
                        p = dataend + 1;
                    }
                    else {
                        /* 'savebuf' got deleted, so we're now pointing at the
                           right thing */
                        dontmove = 1;
                    }
                }
            }
        }

        p = dataend + 1;
    }

    if (!mytid) {
        /* cleanup the fast method */
        map_free(&dbbase, &dblen);
        close(dbfd);
    }

    buf_free(&savebuf);
    buf_free(&keybuf);
    buf_free(&prefixbuf);
    return r;
}
Example #16
0
 void checksum(unsigned short n) { encode(2, 3, n); }
Example #17
0
static int mystore(struct dbengine *db,
                   const char *key, size_t keylen,
                   const char *data, size_t datalen,
                   struct txn **mytid, int overwrite)
{
    int r = 0;
    char fnamebuf[1024];
    int offset;
    unsigned long len;
    const char *lockfailaction;
    int writefd;
    struct iovec iov[10];
    int niov;
    struct stat sbuf;
    struct buf keybuf = BUF_INITIALIZER;
    struct buf databuf = BUF_INITIALIZER;

    /* lock file, if needed */
    if (!mytid || !*mytid) {
        r = lock_reopen(db->fd, db->fname, &sbuf, &lockfailaction);
        if (r < 0) {
            syslog(LOG_ERR, "IOERROR: %s %s: %m", lockfailaction, db->fname);
            return CYRUSDB_IOERROR;
        }

        if (sbuf.st_ino != db->ino) {
            db->ino = sbuf.st_ino;
            map_free(&db->base, &db->len);
            map_refresh(db->fd, 0, &db->base, &db->len,
                        sbuf.st_size, db->fname, 0);
            db->size = sbuf.st_size;
        }

        if (mytid) {
            *mytid = new_txn();
        }
    }

    encode(key, keylen, &keybuf);

    /* find entry, if it exists */
    offset = bsearch_mem_mbox(keybuf.s, db->base, db->size, 0, &len);

    /* overwrite? */
    if (len && !overwrite) {
        if (mytid) abort_txn(db, *mytid);
        buf_free(&keybuf);
        buf_free(&databuf);
        return CYRUSDB_EXISTS;
    }

    /* write new file */
    if (mytid && (*mytid)->fnamenew) {
        strlcpy(fnamebuf, (*mytid)->fnamenew, sizeof(fnamebuf));
    } else {
        strlcpy(fnamebuf, db->fname, sizeof(fnamebuf));
        strlcat(fnamebuf, ".NEW", sizeof(fnamebuf));
    }

    unlink(fnamebuf);
    r = writefd = open(fnamebuf, O_RDWR | O_CREAT, 0666);
    if (r < 0) {
        syslog(LOG_ERR, "opening %s for writing failed: %m", fnamebuf);
        if (mytid) abort_txn(db, *mytid);
        buf_free(&keybuf);
        buf_free(&databuf);
        return CYRUSDB_IOERROR;
    }

    niov = 0;
    if (offset) {
        WRITEV_ADD_TO_IOVEC(iov, niov, (char *) db->base, offset);
    }

    if (data) {
        /* new entry */
        encode(data, datalen, &databuf);
        WRITEV_ADD_TO_IOVEC(iov, niov, keybuf.s, keybuf.len);
        WRITEV_ADD_TO_IOVEC(iov, niov, "\t", 1);
        WRITEV_ADD_TO_IOVEC(iov, niov, databuf.s, databuf.len);
        WRITEV_ADD_TO_IOVEC(iov, niov, "\n", 1);
    }

    if (db->size - (offset + len) > 0) {
        WRITEV_ADD_TO_IOVEC(iov, niov, (char *) db->base + offset + len,
                            db->size - (offset + len));
    }

    /* do the write */
    r = retry_writev(writefd, iov, niov);
    if (r == -1) {
        syslog(LOG_ERR, "IOERROR: writing %s: %m", fnamebuf);
        close(writefd);
        if (mytid) abort_txn(db, *mytid);
        buf_free(&keybuf);
        buf_free(&databuf);
        return CYRUSDB_IOERROR;
    }
    r = 0;

    if (mytid) {
        /* setup so further accesses will be against fname.NEW */
        if (fstat(writefd, &sbuf) == -1) {
            /* xxx ? */
        }

        if (!(*mytid)->fnamenew) (*mytid)->fnamenew = xstrdup(fnamebuf);
        if ((*mytid)->fd) close((*mytid)->fd);
        (*mytid)->fd = writefd;
        map_free(&db->base, &db->len);
        map_refresh(writefd, 0, &db->base, &db->len, sbuf.st_size,
                    fnamebuf, 0);
        db->size = sbuf.st_size;
    } else {
        /* commit immediately */
        if (fsync(writefd) ||
            fstat(writefd, &sbuf) == -1 ||
            rename(fnamebuf, db->fname) == -1) {
            syslog(LOG_ERR, "IOERROR: writing %s: %m", fnamebuf);
            close(writefd);
            buf_free(&keybuf);
            buf_free(&databuf);
            return CYRUSDB_IOERROR;
        }

        close(db->fd);
        db->fd = writefd;

        /* release lock */
        r = lock_unlock(db->fd, db->fname);
        if (r == -1) {
            syslog(LOG_ERR, "IOERROR: unlocking db %s: %m", db->fname);
            r = CYRUSDB_IOERROR;
        }

        db->ino = sbuf.st_ino;
        map_free(&db->base, &db->len);
        map_refresh(writefd, 0, &db->base, &db->len, sbuf.st_size,
            db->fname, 0);
        db->size = sbuf.st_size;
    }

    buf_free(&keybuf);
    buf_free(&databuf);

    return r;
}
Example #18
0
 void identifier(unsigned short n) { encode(4, 5, n); }
Example #19
0
inline void
invoke_reuse_incomplete(uint32_t symbols, uint32_t symbol_size)
{

    bool do_complete;

    typename Encoder::factory encoder_factory(symbols, symbol_size);
    typename Decoder::factory decoder_factory(symbols, symbol_size);

    // Use factory a lot of times
    for (uint32_t i = 0; i < 100; ++i)
    {
        // Build coders
        auto encoder = encoder_factory.build();
        auto decoder = decoder_factory.build();

        // Prepare buffers
        std::vector<uint8_t> payload(encoder->payload_size());
        std::vector<uint8_t> data_in(encoder->block_size());

        // Fill with random data
        for (auto &e: data_in)
            e = rand() % 256;

        // Put data in encoder
        encoder->set_symbols(sak::storage(data_in));

        if (rand() % 100 > 90)
        {
            do_complete = false;
        }
        else
        {
            do_complete = true;
        }

        // Start encoding/decoding
        while (!decoder->is_complete())
        {
            encoder->encode(&payload[0]);

            // Loose a packet with probability
            if (rand() % 100 > 90)
                continue;

            decoder->decode(&payload[0]);

            // Stop decoding after a while with probability
            if (!do_complete && decoder->rank() == symbols - 2)
                break;
        }

        // Check if completed decoders are correct
        if (decoder->is_complete())
        {
            std::vector<uint8_t> data_out(decoder->block_size());
            decoder->copy_symbols(sak::storage(data_out));

            ASSERT_TRUE(sak::equal(sak::storage(data_out),
                                   sak::storage(data_in)));
        }
    }

}
Example #20
0
 void sequence_number(unsigned short n) { encode(6, 7, n); }
Example #21
0
const string& url_coder::to_string() const
{
    encode(*buf_);
    return *buf_;
}
Example #22
0
/*
    @function main
*/
int main()
{
    /*test pq*/
    struct tnode* p=NULL;
    struct tnode* lc,*rc;
    float freq[]={0.01,0.04,0.05,0.11,0.19,0.20,0.4};
    int   NCHAR=7; /*number of characters*/
    int i=0;
    const char *CODE_FILE="code.txt";
    const char *OUT_FILE="encoded.txt";
    FILE* fout=NULL;
	/*zero out code*/
    memset(code,0,sizeof(code));

	/*testing queue*/
    pq_insert(talloc('a', 0.1));
    pq_insert(talloc('b', 0.2));
    pq_insert(talloc('c', 0.15));
    pq_insert(talloc('g', 0.3));
    pq_insert(talloc('x', 0.002));
    		
    /*making sure it pops in the right order*/
	puts("making sure it pops in the right order");
	while((p=pq_pop()))
    {
	printf("iam free \n");

	if(p != NULL)
	{
            free(p);
	}
	
    }
	
    qhead=NULL;
    /*initialize with freq*/
    for(i=0;i<NCHAR;i++)
    {
        pq_insert(talloc('a'+i,freq[i]));
    } 
    /*build tree*/
    for(i=0;i<NCHAR-1;i++)
    {
        lc=pq_pop();
        
        rc=pq_pop();
        
        /*create parent*/
        p=talloc(0,lc->freq+rc->freq);
        /*set parent link*/
        lc->parent=rc->parent=p;
        /*set child link*/
        p->right=rc; p->left=lc;
		/*make it non-leaf*/
		p->isleaf=0;
        /*add the new node to the queue*/
        pq_insert(p);
    }
    /*get root*/
     root=pq_pop();
	/*build code*/
	generate_code(root,0);
	/*output code*/
	puts("code:");
	fout=fopen(CODE_FILE,"w");
	dump_code(stdout);
	dump_code(fout);
	fclose(fout);

	/*encode a sample string*/
	puts("orginal:abba cafe bad");
	fout=fopen(OUT_FILE,"w");
	encode("abba cafe bad",stdout);
	encode("abba cafe bad",fout);
	fclose(fout);

	free(root);
	free(lc);
	free(rc);
	return 0;


}
Example #23
0
File: uri.cpp Project: zmij/restbed
 string Uri::encode( const string& value )
 {
     return encode( Bytes( value.begin( ), value.end( ) ) );
 }
/* Interaction of the child process with the client */
void Talk_to_client ( int cfd )
{
	int status;
   	int nbytes;
   	int src_addr, dest_addr;
   	Msg send_msg;
   	Msg recv_msg;
   	PubKey clientPublicKey;

   	dest_addr = inet_addr("127.0.0.1");
   	src_addr = inet_addr(DEFAULT_SERVER);
 
	while (1) 
   	{
		/* Receive response from client */
		nbytes = recv(cfd, &recv_msg, sizeof(Msg), 0);

		if (nbytes == -1) 
		{
			fprintf(stderr, "*** Server error: unable to receive\n");
			return;
		}
		switch ( recv_msg.hdr.opcode ) 
		{
			
         case PUBKEY : /* Public Key Message */
				printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
				printf("Message:: with opcode %d (PUBKEY) received from source (%d)\n", recv_msg.hdr.opcode, recv_msg.hdr.src_addr);  
				printf("Received public key\n");
				printf("Pub Key n : %ld\t", recv_msg.pubkey.n);
				printf("Pub Key e : %ld\n" , recv_msg.pubkey.e);
				
            //assign the values to the client Public Key structure
				clientPublicKey.e = recv_msg.pubkey.e;
				clientPublicKey.n = recv_msg.pubkey.n;
				break;

         case REQ: /* Request file message */
				printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
				printf("Message:: with opcode %d (REQ) received from source (%d)\n", recv_msg.hdr.opcode, recv_msg.hdr.src_addr);
            printf("Requested file name : \"%s\"", recv_msg.data);

				FILE *fp;
				fp = fopen(recv_msg.data, "r");
				if(fp == NULL)
				{
					printf("File is not present...\n");
					printf("Sending DISCONNECT message to the client\n");
					send_msg.hdr.opcode = DISCONNECT;
           		send_msg.hdr.src_addr = src_addr;
           		send_msg.hdr.dest_addr = dest_addr;
           		send_msg.status = FAIL;
           		memset(send_msg.data, '\0', MAX_LEN);
              		memset(send_msg.sha1, '\0', MAX_LEN);
					send_msg.pubkey.e = 0;
					send_msg.pubkey.n = 0;
					status = send(cfd, &send_msg, sizeof(Msg), 0);
					if (status == -1) 
					{
						fprintf(stderr, "*** Client error: unable to send\n");
						return;
					}
					exit(0);
				}
				else
				{
					printf("Requested file found on server...\nStarting the encryption...\n");
					long int blockSize = 16, counter = 0, intermediateNumber, flag = 0, j;
					char c, encryptedData[MAX_LEN], intermediateString[MAX_LEN], orgData[MAX_LEN];
					unsigned char hash[SHA_DIGEST_LENGTH];
               memset(encryptedData, '\0', sizeof encryptedData);
               memset(orgData, '\0', sizeof orgData);
               memset(hash, '\0', sizeof hash);
					while((c = fgetc(fp)) != EOF)
					{
						if(counter == blockSize)
						{
							//Generate the hash for the original data and send encrypted data to the client
							printf("++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
                     printf("Encrypted data : %s\n", encryptedData);
                     printf("original data : %s\n", orgData);

                     SHA1(orgData, sizeof(orgData) - 1, hash);

							printf("SHA1 -> ");
							for(j = 0; j < SHA_DIGEST_LENGTH; j++)
							  printf("%u", hash[j]);

							//Send the data to client
							printf("\nSending data...\n");
							send_msg.hdr.opcode = REP;
           				send_msg.hdr.src_addr = src_addr;
           				send_msg.hdr.dest_addr = dest_addr;
           				send_msg.status = SUCCESS;
           				//copy the data 
           				strcpy(send_msg.data, encryptedData);
           				//copy the sha1
           				for(j = 0; j < SHA_DIGEST_LENGTH; j++)
           					send_msg.sha1[j] = hash[j];
							send_msg.pubkey.e = 0;
							send_msg.pubkey.n = 0;
							status = send(cfd, &send_msg, sizeof(Msg), 0);
							if (status == -1) 
							{
								fprintf(stderr, "*** Client error: unable to send\n");
								return;
							}
							//data sent
							counter = 0;
							memset(encryptedData, '\0', sizeof encryptedData);
							memset(orgData, '\0', sizeof orgData);
                     memset(hash, '\0', sizeof hash);
							flag = 1;
						}
						orgData[counter] = c;
						intermediateNumber = EncryptionAlgorithm(encode(c), recv_msg.pubkey);
						
                  int i = 0;
						//Convert the number to the string here
						while(intermediateNumber != 0)
						{
							intermediateString[i++] = intermediateNumber % 10 + '0';
							intermediateNumber /= 10;
						}
						intermediateString[i] = '\0';
						reverse_string(intermediateString);
						strcat(encryptedData, intermediateString);

						strcat(encryptedData, ",");

						flag = 0;
						counter++;
					}

					if(flag == 0)  // means the data is formed less than the block size
					{
                  printf("Encrypted data : %s\n", encryptedData);
                  printf("Original data : %s\n", orgData );
						SHA1(orgData, sizeof(orgData) - 1, hash);
						printf("SHA1\n");
						for(j = 0; j < SHA_DIGEST_LENGTH; j++)
						   printf("%u", hash[j]);
						//Sending the data
						printf("Sending data...\n");
						send_msg.hdr.opcode = REP;
       				send_msg.hdr.src_addr = src_addr;
       				send_msg.hdr.dest_addr = dest_addr;
       				send_msg.status = SUCCESS;
       				//copy the data 
       				strcpy(send_msg.data, encryptedData);
       				//copy the sha1
       				for(j = 0; j < SHA_DIGEST_LENGTH; j++)
       					send_msg.sha1[j] = hash[j];
						send_msg.pubkey.e = 0;
						send_msg.pubkey.n = 0;
						status = send(cfd, &send_msg, sizeof(Msg), 0);
						if (status == -1) 
						{
							fprintf(stderr, "*** Client error: unable to send\n");
							return;
						}
               }

					//  File data transferred completely
               //    Send the DISCONNECT message to the client and close
					printf("Sending REQCOMM message to the client\n");
					send_msg.hdr.opcode = REQCOM;
           		send_msg.hdr.src_addr = src_addr;
           		send_msg.hdr.dest_addr = dest_addr;
           		send_msg.status = SUCCESS;
           		memset(send_msg.data, '\0', MAX_LEN);
           		memset(send_msg.sha1, '\0', MAX_LEN);
					send_msg.pubkey.e = 0;
					send_msg.pubkey.n = 0;
					status = send(cfd, &send_msg, sizeof(Msg), 0);
					if (status == -1) 
					{
						fprintf(stderr, "*** Client error: unable to send\n");
						return;
					}
					fclose(fp);
				}
				break;

			case DISCONNECT:
				printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
				printf("Message:: with opcode %d (DISCONNECT) received from source (%d)\n", recv_msg.hdr.opcode, recv_msg.hdr.src_addr);
				printf("Exiting...\n");
				exit(0);

			default: 
				printf("message received with opcode: %d\n", recv_msg.hdr.opcode);
				exit(0);  
		}
 	}
}
Vector<char> ObjectStoreMetaDataKey::encodeMaxKey(int64_t databaseId)
{
    return encode(databaseId, INT64_MAX, INT64_MAX);
}
int main ()
{
    std::cout << "\n--- Testing the decode function of Eurobalise Telegram with N_ITER packets." << std::endl;
    std::vector<uint8_t> raw_stream(1000);
    Bitstream stream;
    Bitstream_Init(&stream, &(raw_stream[0]), raw_stream.size(), 73);

    uint32_t init_pos = stream.bitpos;

    // TelegramHeader header = create_TelegramHeader_TrainToTrack();
    std::cout << " Encoding Telegram Header: " << header << std::endl;
    TelegramHeader header = create_TelegramHeader_TrackToTrain();
    encode(stream, header);

    Temporary_Speed_Restriction a = create_Temporary_Speed_Restriction();
    {
        std::cout << "    Encoding packet " << a << std::endl;
        encode(stream, a.header);
        encode(stream, a.core);
    }

    Adhesion_Factor b = create_Adhesion_Factor();
    {
        std::cout << "    Encoding packet " << b << std::endl;
        encode(stream, b.header);
        encode(stream, b.core);
    }

    Infill_location_reference c = create_Infill_location_reference(1);
    {
        std::cout << "    Encoding packet " << c << std::endl;
        encode(stream, c.header);
        encode(stream, c.core);
    }

    Infill_location_reference d = create_Infill_location_reference(0);
    {
        std::cout << "    Encoding packet " << d << std::endl;
        encode(stream, d.header);
        encode(stream, d.core);
    }

    Gradient_Profile e = create_Gradient_Profile();
    {
        std::cout << "    Encoding packet " << e << std::endl;
        encode(stream, e.header);
        encode(stream, e.core);
    }

    End_of_Information f;
    {
        std::cout << "    Encoding packet " << f << std::endl;
        encode(stream, f.header);
        encode(stream, f.core);
    }

    stream.bitpos = init_pos;

    EurobaliseTelegram telegram;

    std::cout << " Decoding Eurobalise Telegram." << std::endl;
    telegram.decode(stream);

    std::cout << " Decoder Output: " << telegram << std::endl;

    assert(telegram.header == header);

    assert_equal(a, telegram.packets[0]);
    assert_equal(b, telegram.packets[1]);
    assert_equal(c, telegram.packets[2]);

    std::cout << " Test successful." << std::endl;

    return EXIT_SUCCESS;
}
Vector<char> IndexFreeListKey::encodeMaxKey(int64_t databaseId, int64_t objectStoreId)
{
    return encode(databaseId, objectStoreId, INT64_MAX);
}
Example #28
0
int Roll::to_int() const {
  int data[7] = { 0, n_1, n_2, n_3, n_4, n_5, n_6 };
  for (int i = 1; i < 7; ++i) data[i] = data[i-1] + data[i] + 1;
  return encode(10,5,data+1);
}
Vector<char> IndexDataKey::encode(int64_t databaseId, int64_t objectStoreId, int64_t indexId, const IDBKey& userKey)
{
    return encode(databaseId, objectStoreId, indexId, encodeIDBKey(userKey), minIDBKey());
}
Example #30
0
int station(const char * stationURL) {
	char url[512] = { 0 }, * encodedURL = NULL, ** response, name[512], * completeURL;
	unsigned i = 0, retval = !0, regular = !0;
	const char * fmt;	
	const char * types[4] = {"play", "preview", "track", "playlist"};

	delayquit = 0;

	if(playfork && haskey(& rc, "delay-change")) {
		if(nextstation) {
			/*
			  Cancel station change if url is empty or equal to the current
			  station.
			*/
			free(nextstation);
			nextstation = NULL;

			if(!strlen(stationURL) || !strcmp(stationURL, current_station)) {
				puts("Station change cancelled.");
				return 0;
			}
		}

		/* Do nothing if the station is already played. */
		else if(current_station && !strcmp(current_station, stationURL)) {
			return 0;
		}

		/* Do nothing if the station URL is empty. */
		else if(!strlen(stationURL)) {
			return 0;
		}

		puts("\rDelayed.");
		nextstation = strdup(stationURL);

		return 0;
	}

	/* Do nothing if the station is already played. */
	else if(current_station && !strcmp(current_station, stationURL)) {
		return 0;
	}

	freelist(& playlist);

	if(!haskey(& data, "session")) {
		fputs("Not authenticated, yet.\n", stderr);
		return 0;
	}

	if(!strncmp(HTTP_STATION_PREFIX, stationURL, strlen(HTTP_STATION_PREFIX))) {
		stationURL += strlen(HTTP_STATION_PREFIX);
	}

	if(!stationURL || !strlen(stationURL))
		return 0;

	if(!strncasecmp(stationURL, "lastfm://", 9)) {
		completeURL = strdup(stationURL);
		stationURL += 9;
	}
	else {
		int size = strlen(stationURL) + 10;
		completeURL = malloc(size);
		snprintf(completeURL, size, "lastfm://%s", stationURL);
	}

	/* Check if it's a static playlist of tracks or track previews. */
	for(i = 0; i < 4; ++i)
		if(!strncasecmp(types[i], stationURL, strlen(types[i]))) {
			regular = 0;
			break;
		}

	/*
	   If this is not a special "one-time" stream, it's a regular radio
	   station and we request it using the good old /adjust.php URL.
	   If it's not a regular stream, the reply of this request already is
	   a XSPF playlist we have to parse.
   */
	if(regular) {
		fmt = "http://ws.audioscrobbler.com/radio/adjust.php?session=%s&url=%s";
	}
	else {
		fmt =
			"http://ws.audioscrobbler.com/1.0/webclient/getresourceplaylist.php"
			"?sk=%s&url=%s&desktop=1";
	}

	encode(completeURL, & encodedURL);
	snprintf(url, sizeof(url), fmt, value(& data, "session"), encodedURL);

	free(encodedURL);
	free(completeURL);

	if(!(response = fetch(url, NULL, NULL, NULL)))
		return 0;

	if(regular) {
		for(i = 0; response[i]; ++i) {
			char status[64] = { 0 };

			if(sscanf(response[i], "response=%63[^\r\n]", status) > 0)
				if(!strncmp(status, "FAILED", 6))
					retval = 0;

			if(sscanf(response[i], "stationname=%127[^\r\n]", name) > 0) {
				if(playlist.title != NULL)
					free(playlist.title);

				decode(name, & playlist.title);
				unhtml(playlist.title);
			}
		}

		purge(response);
		response = NULL;

		if(!retval) {
			printf("Sorry, couldn't set station to %s.\n", stationURL);
			return 0;
		}

		expand(& playlist);
	}
	else {
		char * xml = join(response, 0);

		response = NULL;

		freelist(& playlist);

		if(!parsexspf(& playlist, xml))
			retval = 0;

		free(xml);
	}

	enable(CHANGED);
	histapp(stationURL);

	if(current_station)
		free(current_station);

	current_station = strdup(stationURL);
	assert(current_station != NULL);

	if(retval && playfork) {
		enable(INTERRUPTED);
		kill(playfork, SIGUSR1);
	}

	return retval;
}