/*!
    Client side method call that converts an argument of type to its corresponding value as a
    valid type supported by the QtDBus type system.

    Supports conversion from a QVariant, QList, QMap, QHash, and custom user-defined types.
*/
QVariant ObjectEndPoint::toDBusVariant(const QByteArray& typeName, const QVariant& arg)
{
    QVariant dbusVariant = arg;

    int type = QMetaType::type(typeName);
    if (type == QMetaType::QVariant) {
        // Wrap QVariants in a QDBusVariant
        QDBusVariant replacement(arg);
        dbusVariant = QVariant::fromValue(replacement);
    } else if (type >= QMetaType::User) {
        // Wrap custom types in a QDBusVariant of the type name and
        // a buffer of its variant-wrapped data
        QByteArray buffer;
        QDataStream stream(&buffer, QIODevice::ReadWrite | QIODevice::Append);
        stream << arg;

        QServiceUserTypeDBus customType;
        customType.typeName = typeName;
        customType.variantBuffer = buffer;

        QDBusVariant replacement(QVariant::fromValue(customType));
        dbusVariant = QVariant::fromValue(replacement);
    }

    return dbusVariant;
}
Example #2
0
void KReplaceDialog::slotOk()
{
    // If regex and backrefs are enabled, do a sanity check.
    if(m_regExp->isChecked() && m_backRef->isChecked())
    {
        QRegExp r(pattern());
        int caps = r.numCaptures();
        QRegExp check(QString("((?:\\\\)+)(\\d+)"));
        int p = 0;
        QString rep = replacement();
        while((p = check.search(rep, p)) > -1)
        {
            if(check.cap(1).length() % 2 && check.cap(2).toInt() > caps)
            {
                KMessageBox::information(
                    this, i18n("Your replacement string is referencing a capture greater than '\\%1', ").arg(caps)
                              + (caps ? i18n("but your pattern only defines 1 capture.", "but your pattern only defines %n captures.", caps)
                                      : i18n("but your pattern defines no captures."))
                              + i18n("\nPlease correct."));
                return; // abort OKing
            }
            p += check.matchedLength();
        }
    }

    KFindDialog::slotOk();
    m_replace->addToHistory(replacement());
}
Example #3
0
//--------------------------------------------------------------------------------------------------------------------//
//Afairese tis perites parenthesis apo ena dentro
parenthesis * simplify(parenthesis * input)
{
    int i=0;
    parenthesis ** kids=input->subparenthesis;
    parenthesis * temporal;
    char * temp=(char*) malloc(MAX);
    if(temp== NULL)
    {
            fprintf(stderr, "out of memory\n");
            return NULL;
    }
    if((input->kids)==1)
    {
        strcpy(temp,kids[0]->content);
        wrapwithparenthesis(temp);
        if(!strcmp(temp,input->content))
        {
            replacement(input->content,input->content, kids[0]->content);
            temporal=addpar(input->content,input->parent,NULL,input->num,input->depth);
            removetree(input);
            free(input);
        }
        else
        {
            return input;
        }
        temporal=simplify(temporal);
        free(temp);
        return temporal;
    }
    else if ((input->kids)>1)
    {
        for(i=0;i<input->kids;i++)
        {
            strcpy(temp,(kids[i]->content));
            kids[i]= simplify(kids[i]);
            replacement(input->content,temp, kids[i]->content);
            temporal=addpar(input->content,input->parent,NULL,input->num,input->depth);
            removetree(input);
            free(input);
            input=temporal;
            kids=input->subparenthesis;
        }
        free(temp);
    }
    else
    {
            free(temp);
            return  input;
    }
    return  input;
}
static void NativeConverter_setCallbackDecode(JNIEnv* env, jclass, jlong address,
        jint onMalformedInput, jint onUnmappableInput, jstring javaReplacement) {
    UConverter* cnv = toUConverter(address);
    if (cnv == NULL) {
        maybeThrowIcuException(env, "toConverter", U_ILLEGAL_ARGUMENT_ERROR);
        return;
    }

    UConverterToUCallback oldCallback;
    const void* oldCallbackContext;
    ucnv_getToUCallBack(cnv, &oldCallback, &oldCallbackContext);

    DecoderCallbackContext* callbackContext = const_cast<DecoderCallbackContext*>(
            reinterpret_cast<const DecoderCallbackContext*>(oldCallbackContext));
    if (callbackContext == NULL) {
        callbackContext = new DecoderCallbackContext;
    }

    callbackContext->onMalformedInput = getToUCallback(onMalformedInput);
    callbackContext->onUnmappableInput = getToUCallback(onUnmappableInput);

    ScopedStringChars replacement(env, javaReplacement);
    if (replacement.get() == NULL) {
        maybeThrowIcuException(env, "replacement", U_ILLEGAL_ARGUMENT_ERROR);
        return;
    }
    u_strncpy(callbackContext->replacementChars, replacement.get(), replacement.size());
    callbackContext->replacementCharCount = replacement.size();

    UErrorCode errorCode = U_ZERO_ERROR;
    ucnv_setToUCallBack(cnv, CHARSET_DECODER_CALLBACK, callbackContext, NULL, NULL, &errorCode);
    maybeThrowIcuException(env, "ucnv_setToUCallBack", errorCode);
}
Example #5
0
int myFunction(int arg1, int arg2)
{
  int intermediate = arg1 + arg2;
  int anotherVal = arg1*arg2;
  int functionVal = replacement();
  return intermediate + anotherVal + functionVal;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int ModifiedLambertProjectionArray::eraseTuples(QVector<size_t>& idxs)
{
  int err = 0;

  // If nothing is to be erased just return
  if(idxs.size() == 0)
  {
    return 0;
  }

  if (static_cast<size_t>(idxs.size()) >= getNumberOfTuples() )
  {
    resize(0);
    return 0;
  }

  // Sanity Check the Indices in the vector to make sure we are not trying to remove any indices that are
  // off the end of the array and return an error code.
  for(QVector<size_t>::size_type i = 0; i < idxs.size(); ++i)
  {
    if (idxs[i] >= static_cast<size_t>(m_ModifiedLambertProjectionArray.size()))
    {
      return -100;
    }
  }


  QVector<ModifiedLambertProjection::Pointer> replacement(m_ModifiedLambertProjectionArray.size() - idxs.size());
  qint32 idxsIndex = 0;
  size_t rIdx = 0;
  size_t count = static_cast<size_t>(m_ModifiedLambertProjectionArray.size());
  for(size_t dIdx = 0; dIdx < count; ++dIdx)
  {
    if (dIdx != idxs[idxsIndex])
    {
      replacement[rIdx] = m_ModifiedLambertProjectionArray[dIdx];
      ++rIdx;
    }
    else
    {
      ++idxsIndex;
      if (idxsIndex == idxs.size() )
      {
        idxsIndex--;
      }
    }
  }
  m_ModifiedLambertProjectionArray = replacement;
  return err;
}
Example #7
0
  void XML_Element::set_string(const String &s) {
    if(!good()) {
      std::cerr << "Bad XML_Element_c attempted set_string(...)\n";
      throw XML_Element_Ungood();
    }

    TiXmlNode * const node = first_child();

    if(!node)
      m_handle.ToNode()->LinkEndChild(new TiXmlText(s.c_str()));
    else if(node->ToText()) {
      TiXmlText replacement(s.c_str());
      m_handle.ToNode()->ReplaceChild(node, replacement);
    }
    else {
      std::cerr << "XML_Element_c attempted set_string(...) on non-leaf node\n";
      throw XML_Element_Nonleaf();
    }
  }
    /**
     * @brief Removes Tuples from the Array. If the size of the vector is Zero nothing is done. If the size of the
     * vector is greater than or Equal to the number of Tuples then the Array is Resized to Zero. If there are
     * indices that are larger than the size of the original (before erasing operations) then an error code (-100) is
     * returned from the program.
     * @param idxs The indices to remove
     * @return error code.
     */
    virtual int EraseTuples(std::vector<size_t> &idxs)
    {
      int err = 0;
            // If nothing is to be erased just return
      if(idxs.size() == 0)
      {
        return 0;
      }

      if (idxs.size() >= GetNumberOfTuples() )
      {
        Resize(0);
        return 0;
      }

      // Sanity Check the Indices in the vector to make sure we are not trying to remove any indices that are
      // off the end of the array and return an error code.
      for(std::vector<size_t>::size_type i = 0; i < idxs.size(); ++i)
      {
        if (idxs[i] >= _data.size()) { return -100; }
      }


      std::vector<SharedVectorType> replacement(_data.size() - idxs.size());
      size_t idxsIndex = 0;
      size_t rIdx = 0;
      for(size_t dIdx = 0; dIdx < _data.size(); ++dIdx)
      {
        if (dIdx != idxs[idxsIndex])
        {
          replacement[rIdx] = _data[dIdx];
          ++rIdx;
        }
        else
        {
          ++idxsIndex;
          if (idxsIndex == idxs.size() ) { idxsIndex--;}
        }
      }
      _data = replacement;
      return err;
    }
Example #9
0
bool CLReplacePattern(const wxString& in, const wxString& pattern, const wxString& replaceWith, wxString &outStr)
{
	int where = pattern.Find(wxT("%0"));
	if(where != wxNOT_FOUND) {
		wxString replacement(replaceWith);

		// a patterened expression
		wxString searchFor = pattern.BeforeFirst(wxT('('));
		where = in.Find(searchFor);
		if(where == wxNOT_FOUND) {
			return false;
		}

		wxString      initList;
		wxArrayString initListArr;
		if(PPToken::readInitList(in, searchFor.Length() + where, initList, initListArr) == false)
			return false;

		outStr = in;
		// update the 'replacement' with the actual values ( replace %0..%n)
		for(size_t i=0; i<initListArr.size(); i++) {
			wxString placeHolder;
			placeHolder << wxT("%") << i;
			replacement.Replace(placeHolder, initListArr.Item(i));
		}

		outStr.Remove(where, searchFor.Length() + initList.Length());
		outStr.insert(where, replacement);
		return true;

	} else {
		if(in.Find(pattern) == wxNOT_FOUND) {
			return false;
		}
		// simple replacement
		outStr = ReplaceWord(in, pattern, replaceWith);
		return outStr != in;
	}
}
QgsStringReplacementCollection QgsSubstitutionListWidget::substitutions() const
{
  QList< QgsStringReplacement > result;
  for ( int i = 0; i < mTableSubstitutions->rowCount(); ++i )
  {
    if ( !mTableSubstitutions->item( i, 0 ) )
      continue;

    if ( mTableSubstitutions->item( i, 0 )->text().isEmpty() )
      continue;

    QCheckBox *chkCaseSensitive = qobject_cast<QCheckBox *>( mTableSubstitutions->cellWidget( i, 2 ) );
    QCheckBox *chkWholeWord = qobject_cast<QCheckBox *>( mTableSubstitutions->cellWidget( i, 3 ) );

    QgsStringReplacement replacement( mTableSubstitutions->item( i, 0 )->text(),
                                      mTableSubstitutions->item( i, 1 )->text(),
                                      chkCaseSensitive->isChecked(),
                                      chkWholeWord->isChecked() );
    result << replacement;
  }
  return QgsStringReplacementCollection( result );
}
Command *parser(char *path, int *size_com, int *num_str, int *err)
{
	Command *commands;
	Label *labels;
	int point_com = 0, point_lbl = 0;
	FILE *input;
	*num_str = 0;
	input = fopen(path, "r");
	commands = (Command *)malloc(sizeof(Command) * SIZE_COMMAND);
	labels = (Label *)malloc(sizeof(Label) * SIZE_LABEL);
	while(!feof(input))
	{
		char str[SIZE_STRING], *lexeme;
		int point_str = 0;
		str[0] = 0;
		++(*num_str);
		if ((point_com - 1) % SIZE_COMMAND == 0)
			commands = (Command *)realloc(commands, sizeof(Command) * (point_com + SIZE_COMMAND));
                if ((point_lbl - 1) % SIZE_LABEL == 0)
			labels = (Label *)realloc(labels, sizeof(Label) * (point_lbl + SIZE_LABEL));
		fgets(str, SIZE_STRING - 1, input);
		lexeme = read_word(str, &point_str, err);
		if (*err != 0)
		{
			clean_arrays(commands, point_com, labels, point_lbl);	
			return NULL;
		}
		commands[point_com].opcode = is_command(lexeme);
		if (commands[point_com].opcode == LDC) 
			commands[point_com].number = read_number(str, &point_str, err);
		else if ((commands[point_com].opcode == LD) || (commands[point_com].opcode == ST))
			commands[point_com].address = read_address(str, &point_str, err);
		else if ((commands[point_com].opcode == BR) || (commands[point_com].opcode == JMP))
		{
			commands[point_com].label = read_word(str, &point_str, err);
			if (*err == 1) *err = 5;
			if (*err == 0)
			{
				if (is_command(commands[point_com].label) == LBL)
					put_in_array(labels, &point_lbl, commands[point_com].label, -1, *num_str, err);	
				else *err = 5; 
			}
		}
		else if (commands[point_com].opcode == LBL)
		{
			while ((str[point_str] == ' ') || (str[point_str] == 9)) ++point_str;
			if (str[point_str++] == ':')
				put_in_array(labels, &point_lbl, lexeme, point_com, *num_str, err);
			else *err = 6;
		}
		if (*err != 0)
		{
			clean_arrays(commands, point_com + 1, labels, point_lbl);
			return NULL;
		}
		while ((str[point_str] == ' ') || (str[point_str] == 9)) ++point_str;
		if ((str[point_str] != ';') && (str[point_str] != 0) && (str[point_str] != '\n'))
		{
			*err = 8;
			clean_arrays(commands, point_com + 1, labels, point_lbl);
			return NULL;
		}
		if ((commands[point_com].opcode != LBL) && (commands[point_com].opcode != NUL)) 
		{
			commands[point_com].num_str = *num_str;
			++point_com;
		}
	}  
	replacement(commands, point_com, labels, point_lbl, num_str, err);
	if (*err != 0)
	{
		clean_arrays(commands, point_com, labels, point_lbl);
		return NULL;
	}	
	else 
	{
		*size_com = point_com;
		return commands;
	}	
}
Example #12
0
  Symbol* Converter::primitive_convert(STATE, Object* source, String* target,
                                       Fixnum* offset, Fixnum* size, Fixnum* options) {
    String* src = 0;

    if(!source->nil_p()) {
      if(!(src = try_as<String>(source))) {
        return force_as<Symbol>(Primitives::failure());
      }
    }

    OnStack<3> os(state, source, src, target);

    const unsigned char* source_ptr = 0;
    const unsigned char* source_end = 0;

    native_int byte_offset = offset->to_native();
    native_int byte_size = size->to_native();

  retry:

    if(!converter_) {
      size_t num_converters = converters()->size();

      converter_ = rb_econv_alloc(num_converters);

      for(size_t i = 0; i < num_converters; i++) {
        Transcoding* transcoding = as<Transcoding>(converters()->get(state, i));
        rb_transcoder* tr = transcoding->get_transcoder();

        if(rb_econv_add_transcoder_at(converter_, tr, i) == -1) {
          rb_econv_free(converter_);
          converter_ = NULL;
          return force_as<Symbol>(Primitives::failure());
        }
      }
    }

    /* It would be nice to have a heuristic that avoids having to reconvert
     * after growing the destination buffer. This is complicated, however, as
     * a converter may contain more than one transcoder. So, the heuristic
     * would need to be transitive. This requires getting the encoding objects
     * for every stage of the converter to check the min/max byte values.
     */
    if(byte_size == -1) {
      byte_size = src ? src->byte_size() : 4096;
    }

    int flags = converter_->flags = options->to_native();

    if(!replacement()->nil_p()) {
      native_int byte_size = replacement()->byte_size();
      char* buf = (char*)XMALLOC(byte_size + 1);
      strncpy(buf, replacement()->c_str(state), byte_size + 1);
      converter_->replacement_str = (const unsigned char*)buf;
      converter_->replacement_len = replacement()->byte_size();

      String* name = replacement()->encoding()->name();
      byte_size = name->byte_size();
      buf = (char*)XMALLOC(byte_size + 1);
      strncpy(buf, name->c_str(state), byte_size + 1);
      converter_->replacement_enc = (const char*)buf;
      converter_->replacement_allocated = 1;

      size_t num_converters = replacement_converters()->size();
      rb_econv_alloc_replacement_converters(converter_, num_converters / 2);

      for(size_t i = 0, k = 0; i < num_converters; k++, i += 2) {
        rb_econv_replacement_converters* repl_converter;
        repl_converter = converter_->replacement_converters + k;

        name = as<String>(replacement_converters()->get(state, i));
        byte_size = name->byte_size();
        buf = (char*)XMALLOC(byte_size + 1);
        strncpy(buf, name->c_str(state), byte_size + 1);
        repl_converter->destination_encoding_name = (const char*)buf;

        Array* trs = as<Array>(replacement_converters()->get(state, i + 1));
        size_t num_transcoders = trs->size();

        repl_converter->num_transcoders = num_transcoders;
        repl_converter->transcoders = ALLOC_N(rb_transcoder*, num_transcoders);

        for(size_t j = 0; j < num_transcoders; j++) {
          Transcoding* transcoding = as<Transcoding>(trs->get(state, j));
          rb_transcoder* tr = transcoding->get_transcoder();

          repl_converter->transcoders[j] = tr;
        }
      }
    }
Example #13
0
  Symbol* Converter::primitive_convert(STATE, Object* source, String* target,
                                       Fixnum* offset, Fixnum* size, Fixnum* options) {
    String* src = 0;

    if(!source->nil_p()) {
      if(!(src = try_as<String>(source))) {
        return force_as<Symbol>(Primitives::failure());
      }
    }

    if(!converter_) {
      size_t num_converters = converters()->size();

      converter_ = rb_econv_alloc(num_converters);

      for(size_t i = 0; i < num_converters; i++) {
        Transcoding* transcoding = as<Transcoding>(converters()->get(state, i));
        rb_transcoder* tr = transcoding->get_transcoder();

        if(rb_econv_add_transcoder_at(converter_, tr, i) == -1) {
          rb_econv_free(converter_);
          converter_ = NULL;
          return force_as<Symbol>(Primitives::failure());
        }
      }
    }

    if(!replacement()->nil_p()) {
      native_int byte_size = replacement()->byte_size();
      char* buf = (char*)XMALLOC(byte_size + 1);
      strncpy(buf, replacement()->c_str(state), byte_size + 1);
      converter_->replacement_str = (const unsigned char*)buf;
      converter_->replacement_len = replacement()->byte_size();

      String* name = replacement()->encoding()->name();
      byte_size = name->byte_size();
      buf = (char*)XMALLOC(byte_size + 1);
      strncpy(buf, name->c_str(state), byte_size + 1);
      converter_->replacement_enc = (const char*)buf;
      converter_->replacement_allocated = 1;

      size_t num_converters = replacement_converters()->size();
      rb_econv_alloc_replacement_converters(converter_, num_converters / 2);

      for(size_t i = 0, k = 0; i < num_converters; k++, i += 2) {
        rb_econv_replacement_converters* repl_converter;
        repl_converter = converter_->replacement_converters + k;

        name = as<String>(replacement_converters()->get(state, i));
        byte_size = name->byte_size();
        buf = (char*)XMALLOC(byte_size + 1);
        strncpy(buf, name->c_str(state), byte_size + 1);
        repl_converter->destination_encoding_name = (const char*)buf;

        Array* trs = as<Array>(replacement_converters()->get(state, i + 1));
        size_t num_transcoders = trs->size();

        repl_converter->num_transcoders = num_transcoders;
        repl_converter->transcoders = ALLOC_N(rb_transcoder*, num_transcoders);

        for(size_t j = 0; j < num_transcoders; j++) {
          Transcoding* transcoding = as<Transcoding>(trs->get(state, j));
          rb_transcoder* tr = transcoding->get_transcoder();

          repl_converter->transcoders[j] = tr;
        }
      }
    }
bool SkSVGPaint::flush(SkSVGParser& parser, bool isFlushable, bool isDef) {
    SkSVGPaint current;
    SkSVGPaint* walking = parser.fHead;
    int index;
    while (walking != NULL) {
        for (index = kInitial + 1; index < kTerminal; index++) {
            SkString* lastAttr = (*walking)[index];
            if (lastAttr->size() == 0)
                continue;
            if (current[index]->size() > 0)
                continue;
            current[index]->set(*lastAttr);
        }
        walking = walking->fNext;
    }
    bool paintChanged = false;
    SkSVGPaint& lastState = parser.fLastFlush;
    if (isFlushable == false) {
        if (isDef == true) {
            if (current.f_mask.size() > 0 && current.f_mask.equals(lastState.f_mask) == false) {
                SkSVGElement* found;
                const char* idStart = strchr(current.f_mask.c_str(), '#');
                SkASSERT(idStart);
                SkString id(idStart + 1, strlen(idStart) - 2);
                bool itsFound = parser.fIDs.find(id.c_str(), &found);
                SkASSERT(itsFound);
                SkSVGElement* gradient = found->getGradient();
                if (gradient) {
                    gradient->write(parser, current.f_fill);
                    gradient->write(parser, current.f_stroke);
                }
            }
        }
        goto setLast;
    }
    {
        bool changed[kTerminal];
        memset(changed, 0, sizeof(changed));
        for (index = kInitial + 1; index < kTerminal; index++) {
            if (index == kTransform || index == kClipPath || index == kStopColor || index == kStopOpacity ||
                    index == kClipRule || index == kFillRule)
                continue;
            SkString* lastAttr = lastState[index];
            SkString* currentAttr = current[index];
            paintChanged |= changed[index] = lastAttr->equals(*currentAttr) == false;
        }
        if (paintChanged) {
            if (current.f_mask.size() > 0) {
                if (current.f_fill.equals("none") == false && strncmp(current.f_fill.c_str(), "url(#", 5) != 0) {
                    SkASSERT(current.f_fill.c_str()[0] == '#');
                    SkString replacement("url(#mask");
                    replacement.append(current.f_fill.c_str() + 1);
                    replacement.appendUnichar(')');
                    current.f_fill.set(replacement);
                }
                if (current.f_stroke.equals("none") == false && strncmp(current.f_stroke.c_str(), "url(#", 5) != 0) {
                    SkASSERT(current.f_stroke.c_str()[0] == '#');
                    SkString replacement("url(#mask");
                    replacement.append(current.f_stroke.c_str() + 1);
                    replacement.appendUnichar(')');
                    current.f_stroke.set(replacement);
                }
            }
            if (current.f_fill.equals("none") && current.f_stroke.equals("none"))
                current.f_opacity.set("0");
            if (parser.fSuppressPaint == false) {
                parser._startElement("paint");
                bool success = writeChangedAttributes(parser, current, changed);
                if (success == false)
                    return paintChanged;
                success = writeChangedElements(parser, current, changed);
                if (success == false)
                    return paintChanged;
                parser._endElement(); // paint
            }
        }
    }
setLast:
    for (index = kInitial + 1; index < kTerminal; index++) {
        SkString* lastAttr = lastState[index];
        SkString* currentAttr = current[index];
        lastAttr->set(*currentAttr);
    }
    return paintChanged;
}
Example #15
0
int main(int argc, char *argv[])
{
	// Need to change to 3. need to remove the logging.
	if (argc != 4)
	{
		printf("Usage: ./maxcut <input data path> <output data path> <log file>\n");
		exit(-1);
	}
	
	// Need to remove when submitting.
	log_file = fopen(argv[3], "w");
	fprintf(log_file, "rate, elasped time (s), max val, avg val\n");

	start_time = get_seconds();

	in 		= fopen(argv[1], "r");
	out 	= fopen(argv[2], "w");
	int i, j, v1, v2, w;	// (v1, v2) is the vertex and w is the weight

	fscanf(in, "%d %d\n", &num_of_vertex, &num_of_edge);
	
	int edge[num_of_vertex+1][num_of_vertex+1];
	
	for (i=0; i<=SIZE; i++)
		for (j=0; j<=SIZE; j++)
			edge[i][j] = 0;

	while (fscanf(in, "%d %d %d\n", &v1, &v2, &w) != EOF)
	{
		edge[v1][v2] = w;
		edge[v2][v1] = w;
	}
	
	init_population();
	init_offsprings();
	init_cost(edge);
	sort_population();
	init_crossover();

	int p1, p2;

	while (!(stop_condition()))
	{
		generation++;
		for (i=1; i<=K; i++)
		{
			selection(&p1, &p2);
			crossover(i, p1, p2);
			mutation(i);
			local_optimization(i, edge);
		}

		replacement(edge);

		sort_population();
	}

	for (i=1; i<=SIZE; i++)
	{
		if (population[N]->ch[i] == 1)
			fprintf(out, "%d ", i);
	}

	free_population();

	fclose(in);
	fclose(out);

 	printf("N: %d, K: %d, S_RATE: %lf, M_THRE: %lf, P0: %lf, POINTS: %d, K_FIT: %d, T: %lf\n", N,     K, S_RATE, M_THRE, P0, POINTS, K_FIT, T);


	return 0;
}
Example #16
0
QSet<int> DirectoryDAO::relocateDirectory(const QString& oldFolder,
                                          const QString& newFolder) {
    // TODO(rryan): This method could use error reporting. It can fail in
    // mysterious ways for example if a track in the oldFolder also has a zombie
    // track location in newFolder then the replace query will fail because the
    // location column becomes non-unique.
    ScopedTransaction transaction(m_database);
    QSqlQuery query(m_database);
    query.prepare("UPDATE " % DIRECTORYDAO_TABLE % " SET " % DIRECTORYDAO_DIR % "="
                  ":newFolder WHERE " % DIRECTORYDAO_DIR % " = :oldFolder");
    query.bindValue(":newFolder", newFolder);
    query.bindValue(":oldFolder", oldFolder);
    if (!query.exec()) {
        LOG_FAILED_QUERY(query) << "coud not relocate directory"
                                << oldFolder << "to" << newFolder;
        return QSet<int>();
    }

    FieldEscaper escaper(m_database);
    QString startsWithOldFolder =
            escaper.escapeString(escaper.escapeStringForLike(oldFolder % '/', '%') + '%');
    // Also update information in the track_locations table. This is where mixxx
    // gets the location information for a track.
    query.prepare(QString("SELECT library.id, track_locations.id, track_locations.location "
                          "FROM library INNER JOIN track_locations ON "
                          "track_locations.id = library.location WHERE "
                          "track_locations.location LIKE %1 ESCAPE '%'")
                  .arg(startsWithOldFolder));
    if (!query.exec()) {
        LOG_FAILED_QUERY(query) << "coud not relocate path of tracks";
        return QSet<int>();
    }

    QSet<int> ids;
    QList<int> loc_ids;
    QStringList old_locs;
    while (query.next()) {
        ids.insert(query.value(0).toInt());
        loc_ids.append(query.value(1).toInt());
        old_locs.append(query.value(2).toString());
    }

    QString replacement("UPDATE track_locations SET location = :newloc "
                        "WHERE id = :id");
    query.prepare(replacement);
    for (int i = 0; i < loc_ids.size(); ++i) {
        QString newloc = old_locs.at(i);
        newloc.replace(0, oldFolder.size(), newFolder);
        query.bindValue("newloc", newloc);
        query.bindValue("id", loc_ids.at(i));
        if (!query.exec()) {
            LOG_FAILED_QUERY(query) << "coud not relocate path of tracks";
            return QSet<int>();
        }
    }

    qDebug() << "Relocated tracks:" << ids.size();

    transaction.commit();
    return ids;
}
Example #17
0
bool wxExEx::Substitute(
  const wxString& begin_address, 
  const wxString& end_address, 
  const wxString& patt,
  const wxString& repl)
{
  if (m_STC->GetReadOnly())
  {
    return false;
  }

  if (m_STC->HexMode())
  {
    wxLogStatus(_("Not allowed in hex mode"));
    return false;
  }
  
  const int begin_line = ToLineNumber(begin_address);
  const int end_line = ToLineNumber(end_address);

  if (begin_line == 0 || end_line == 0 || end_line < begin_line)
  {
    return false;
  }
  
  if (!MarkerAdd('$', end_line - 1))
  {
    return false;
  }

  const wxString pattern = (patt == "~" ? m_Replacement: patt);
  
  wxString replacement(repl);
  m_Replacement = replacement; 
  
  m_STC->SetSearchFlags(m_SearchFlags);

  int nr_replacements = 0;

  m_STC->BeginUndoAction();
  m_STC->SetTargetStart(m_STC->PositionFromLine(begin_line - 1));
  m_STC->SetTargetEnd(m_STC->GetLineEndPosition(MarkerLine('$')));

  while (m_STC->SearchInTarget(pattern) > 0)
  {
    const int target_start = m_STC->GetTargetStart();

    if (target_start >= m_STC->GetTargetEnd())
    {
      break;
    }
    
    if (replacement.Contains("&"))
    {
      wxString target = m_STC->GetTextRange(
        m_STC->GetTargetStart(),
        m_STC->GetTargetEnd());
        
      if (replacement.StartsWith("\\L"))
      {
        target.MakeLower();
        replacement.Replace("\\L", wxEmptyString);
      }
      else if (replacement.StartsWith("\\U"))
      {
        target.MakeUpper();
        replacement.Replace("\\U", wxEmptyString);
      }
    
      replacement.Replace("&", target);
    }
    
    m_STC->MarkTargetChange();
    
    const int length = m_STC->ReplaceTargetRE(replacement); // always RE!
    
    m_STC->SetTargetStart(target_start + length);
    m_STC->SetTargetEnd(m_STC->GetLineEndPosition(MarkerLine('$')));

    nr_replacements++;
  }
  
  m_STC->EndUndoAction();
  
  MarkerDelete('$');

  m_Frame->ShowExMessage(wxString::Format(_("Replaced: %d occurrences of: %s"),
    nr_replacements, pattern.c_str()));

  return true;
}