コード例 #1
0
ファイル: arrayfs.cpp プロジェクト: mathtexts/uimacpp
 BasicArrayFS<T, ARRAY_TYPE>::BasicArrayFS(lowlevel::TyFS anFS, uima::CAS & rFSSystem, bool bDoChecks) :
     FeatureStructure(anFS, rFSSystem) {
   if (bDoChecks) {
     checkValidity(UIMA_MSG_ID_EXCON_CREATING_ARRAYFS);
     checkArray(ARRAY_TYPE, iv_tyFS, iv_cas->getHeap(), UIMA_MSG_ID_EXCON_CREATING_ARRAYFS);
   }
 }
コード例 #2
0
ファイル: destructure.cpp プロジェクト: flax-lang/flax
static void checkAndAddBinding(sst::TypecheckState* fs, DecompMapping* bind, fir::Type* rhs, bool immut, bool allowref)
{
	if(!bind->name.empty())
	{
		if(bind->name != "_")
		{
			auto fake = util::pool<sst::VarDefn>(bind->loc);

			fake->id = Identifier(bind->name, IdKind::Name);
			fake->immutable = immut;

			if(bind->ref && !allowref)
				error(bind->loc, "cannot bind to value of type '%s' by reference", rhs);

			else if(bind->ref)
				fake->type = rhs->getPointerTo();

			else
				fake->type = rhs;

			fs->stree->addDefinition(bind->name, fake);
			bind->createdDefn = fake;
		}
	}
	else if(bind->array)
	{
		checkArray(fs, bind, rhs, immut);
	}
	else
	{
		checkTuple(fs, bind, rhs, immut);
	}
}
コード例 #3
0
ファイル: destructure.cpp プロジェクト: flax-lang/flax
void cgn::CodegenState::generateDecompositionBindings(const DecompMapping& bind, CGResult rhs, bool allowref)
{
	auto rt = rhs.value->getType();

	if(!bind.name.empty())
	{
		if(bind.ref && !allowref)
			error(bind.loc, "Cannot bind to value of type '%s' by reference", rt);

		if(bind.ref)
		{
			rhs.value = this->irb.AddressOf(rhs.value, false);
		}
		else
		{
			// rhs.value = this->irb.Dereference(rhs.value);
		}

		handleDefn(this, bind.createdDefn, rhs);
	}
	else if(bind.array)
	{
		checkArray(this, bind, rhs);
	}
	else
	{
		checkTuple(this, bind, rhs);
	}
}
コード例 #4
0
ファイル: imgproc.cpp プロジェクト: CUAir/edges
	static IM * init3( const np::ndarray & d ) {
		checkArray( d, value_type, 2, 3, true );
		
		IM* r = new IM(d.shape(1),d.shape(0),d.get_nd()>2?d.shape(2):1);
		memcpy( r->data(), d.get_data(), r->W()*r->H()*r->C()*sizeof(value_type) );
		return r;
	}
コード例 #5
0
ファイル: HW.c プロジェクト: Kablys/university
int main(){
	int n = 0,			//size of arrays
		i = 0,
		dif = INT_MAX;	//for searching smalles difference
	printf("Size of array(number between %d-%d):",MIN,MAX);
	n=checkInput(MIN,MAX);
	int *data = calloc(n,sizeof(int)), 		//array for input data
		*oneZero = calloc(n,sizeof(int)),	//holds binary numbers for comparing arrays
		*resultArray1 = calloc(n,sizeof(int)),	//holds first result array
		*resultArray2 = calloc(n,sizeof(int));	//holds first result array
	printf("Input numbers\n");
	for (i = 0; i < n; i++){				//input for data array
		data[i] = checkInput(INT_MIN,INT_MAX);
	};
	while (oneZero[n-1]==0){				//creates binary number represented as array
		i = 0;
		while(1){
			if (oneZero[i] == 0){
				oneZero[i] = 1;
				break;
			}
			else if (oneZero[i] == 1){
				oneZero[i] = 0;
				i += 1;
			}
		};
		checkArray(n,oneZero,data,&dif,resultArray1,resultArray2);
	};
	printf("The smallest difference was %d and arrays are\n",dif);
	printArray(n,resultArray1);
	printArray(n,resultArray2);
	free(data);
	free(oneZero);
	return 0;
}
コード例 #6
0
ファイル: arrayShuffle.c プロジェクト: gopoomemsl/Portfolio
int main ()
{
	int array [50];
	int num = 0;
	int result1 = 0;
	int result2 = 0;
	bool isInRange = false;
	
	printf ("Enter a number for last array location\n");
	scanf ("%i", &num);
	
	initializeArray (array, num);	
	shuffleArray (array);
	checkArray (array, num, &result1, &result2, &isInRange);
	
	if (isInRange)
	{
		printf ("data[%i] = %i\ndata[%i] = %i\n", result1, num, result2, num);
	}
	else
	{
		printf ("There are no duplicates\n");
	}
	
	return 0;
}
コード例 #7
0
	void RecentFilesManager::addRecentFile(const MyGUI::UString& _fileName)
	{
		mRecentFiles.insert(mRecentFiles.begin(), _fileName);

		checkArray(mRecentFiles, mMaxRecentFiles);

		SettingsManager::getInstance().setValueList<MyGUI::UString>("Files/RecentFile.List", mRecentFiles);
	}
コード例 #8
0
ファイル: RecentFilesManager.cpp プロジェクト: MyGUI/mygui
	void RecentFilesManager::initialise()
	{
		if (!SettingsManager::getInstance().tryGetValue<size_t>("Files/MaxRecentFolders", mMaxRecentFolders))
			mMaxRecentFolders = 8;

		if (!SettingsManager::getInstance().tryGetValue<size_t>("Files/MaxRecentFiles", mMaxRecentFiles))
			mMaxRecentFiles = 8;

		mRecentFolder = SettingsManager::getInstance().getValue("Files/RecentFolder");

		mRecentFolders = SettingsManager::getInstance().getValueList<MyGUI::UString>("Files/RecentFolder.List");

		mRecentFiles = SettingsManager::getInstance().getValueList<MyGUI::UString>("Files/RecentFile.List");

		checkArray(mRecentFolders, mMaxRecentFolders);
		checkArray(mRecentFiles, mMaxRecentFiles);
	}
コード例 #9
0
ファイル: main.c プロジェクト: ivanseminara/project
int main(int argc, char **argv) {
	printf("Testing memcpy/memmove with function pointers for array size ");
	printf("%d", ARRAY_SIZE);
#ifdef NO_TAGS
	printf(" (no tags)");
#endif
#ifdef FAKE_TAGS
	printf(" (fake tags)");
#endif
	printf("...\n");
	Object *p = createEvilObject();
	fillArray(p);
	printf("Calling function on original object...\n");
#ifndef NO_TAGS
	printf("Tag on p function pointer is %d\n", (int)load_tag(&(p->fn)));
	assert(load_tag(&(p->fn)) == __RISCV_TAG_CLEAN_FPTR);
#endif
	p->fn();
	Object *q = copyObject(p);
	checkArray(q);
	printf("Calling function on memcpy'ed copy of object...\n");
#ifndef NO_TAGS
	printf("Tag on p function pointer is %d\n", (int)load_tag(&(p->fn)));
	assert(load_tag(&(p->fn)) == __RISCV_TAG_CLEAN_FPTR);
	printf("Tag on q function pointer is %d\n", (int)load_tag(&(q->fn)));
	assert(load_tag(&(q->fn)) == __RISCV_TAG_CLEAN_FPTR);
#endif
	q->fn();
	Object *r = moveObject(p);
	checkArray(r);
	printf("Calling function on memmove'ed copy of object...\n");
#ifndef NO_TAGS
	printf("Tag on p function pointer is %d\n", (int)load_tag(&(p->fn)));
	assert(load_tag(&(p->fn)) == __RISCV_TAG_CLEAN_FPTR);
	printf("Tag on q function pointer is %d\n", (int)load_tag(&(q->fn)));
	assert(load_tag(&(q->fn)) == __RISCV_TAG_CLEAN_FPTR);
	printf("Tag on r function pointer is %d\n", (int)load_tag(&(r->fn)));
	assert(load_tag(&(r->fn)) == __RISCV_TAG_CLEAN_FPTR);
#endif
	r->fn();
	printf("Success!\n");
	deleteObject(p);
	deleteObject(q);
	deleteObject(r);
	return 0;
}
コード例 #10
0
	void RecentFilesManager::addRecentFolder(const MyGUI::UString& _folder)
	{
		MyGUI::UString folder(_folder);
		if (_folder.empty())
			folder = MyGUI::UString(common::getSystemCurrentFolder());

		mRecentFolders.insert(mRecentFolders.begin(), folder);

		checkArray(mRecentFolders, mMaxRecentFolders);
	}
コード例 #11
0
ファイル: repeatCheck.c プロジェクト: guozesheng/test
int main(int argc, const char *argv[])
{
    int a[20];
    initArray(a, 20);
    printArray(a, 20);
    checkArray(a, 20);
    printArray(a, 20);
    
    return 0;
}
コード例 #12
0
ファイル: arrayfs.cpp プロジェクト: mathtexts/uimacpp
 BasicArrayFS<T, ARRAY_TYPE>::BasicArrayFS( FeatureStructure const & fs) :
     FeatureStructure(fs) {
   // don't do checks here, exceptions should only be thrown
   // when accessing an invalid object
   if (isValid()) {
     checkArray(ARRAY_TYPE, iv_tyFS, iv_cas->getHeap(), UIMA_MSG_ID_EXCON_CREATING_ARRAYFS);
   }
   // we should not have any additional members
   assert(sizeof(BasicArrayFS) == sizeof(FeatureStructure));
 }
コード例 #13
0
int main(int argc, char** args)
{
	printArray(array, length);
	heapSort(array, length);
	printArray(array, length);
	if (!checkArray(array, length))
	{
		printf("Error occured!\n");
	}

	return 0;
}
コード例 #14
0
ファイル: varparser.cpp プロジェクト: atikbif/relkonIDE
void VarParser::searchVars()
{
    QString allData;
    foreach (QString str, dataBlock) {
       allData+=str;
    }
    // удаление переходов между строками
    allData.remove(QRegExp("[\\r\\n]+"));
    // замена промежутков пробелом
    allData.replace(QRegExp("[\\s\\t]+")," ");
    // удаление инициализации переменных
    allData.remove(QRegExp("=[\\s\\t]*-*[\\d\\.]+"));
    // удаление фигурных скобок и их содержимого
    allData.remove(QRegExp("\\{[^\\}]*\\}"));
    // удаление фигурных скобок (для влож. массивов) и символа равно
    allData.remove(QRegExp("[\\{\\}=]"));
    // удаление двойных кавычек и их содержимого
    allData.remove(QRegExp("\"[^\"]*\""));

    // сканирование всех фундаментальных типов
    for(int i=0;i<fundTypes.count();i++) {
        QRegExp varsExp(fundTypes.at(i)->getName()+"[\\s\\t]+([^;]+);");
        int pos = 0;
        while(pos>=0) {
            pos = varsExp.indexIn(allData,pos);
            if(pos!=-1) {
                QString body = varsExp.cap(1);
                body.remove(QRegExp("[\\s\\t]+"));
                if(!body.isEmpty()) {
                    QStringList varNames = body.split(',');
                    for(int j=0;j<varNames.count();j++) {
                        // *******************************************
                        QString curVarName = varNames.at(j);
                        if(curVarName.isEmpty()) continue;
                        Variable* var = new Variable();
                        // проверка на массив
                        Array* ptr = checkArray(curVarName,fundTypes.at(i)->getId());
                        if(ptr!=nullptr) {var->setType(ptr->getId());}
                        else{var->setType(fundTypes.at(i)->getId());}
                        var->setName(curVarName);
                        var->setId(idNum++);
                        variables += var;
                        // *******************************************
                    }
                }
                allData.remove(pos,varsExp.matchedLength());
            }
        }
    }
}
コード例 #15
0
ファイル: handle.c プロジェクト: Acidburn0zzz/code
/*--------------------------------------------------------------------*/
int HHMakeHandle(void *pData)
{
  int i;

  checkArray();
  /* 
    find first free slot in the pointerArray, store the pointer and 
    return the index.
  */
  for(i = 0; i < MAXHANDLE; i++)
  {
     if(pointerArray[i] == NULL)
     {
       pointerArray[i] = pData;
       return i;
     }
  }
  return -1;
}
コード例 #16
0
bool Patch::readColumns(json_t *jContainer)
{
  json_t *jColumns = json_object_get(jContainer, PATCH_KEY_COLUMNS);
  if (!checkArray(jColumns, PATCH_KEY_COLUMNS))
    return 0;

  size_t columnIndex;
  json_t *jColumn;
  json_array_foreach(jColumns, columnIndex, jColumn) {

    string columnIndexStr = "column " + gu_itoa(columnIndex);
    if (!checkObject(jColumn, columnIndexStr.c_str()))
      return 0;

    column_t column;
    if (!setInt(jColumn, PATCH_KEY_COLUMN_INDEX, column.index)) return 0;
    if (!setInt(jColumn, PATCH_KEY_COLUMN_WIDTH, column.width)) return 0;

    columns.push_back(column);
  }
コード例 #17
0
ファイル: Ball.cpp プロジェクト: ZSE-Programmers/arkanoid
bool Ball::CollideWithPlayer(glm::vec2 startPos, glm::vec2 endPos)
{
	endPos.x += TILE_WIDTH;
	glm::vec2 centerBallPos = glm::vec2(m_position + BALL_RADIUS);

	float length = endPos.x - startPos.x; //length of platform (in px)
	float partOfPlatform; // <0; 1>
	//<0; 0.5) - colision left x--
	//<0.5> - colision center
	//(0.5; 1> - colision right x++
	if (centerBallPos.y + BALL_RADIUS >= startPos.y)
	{
		if (centerBallPos.x >= startPos.x && centerBallPos.x <= endPos.x)
		{
			partOfPlatform = (centerBallPos.x - startPos.x) / (length - startPos.x);

			m_direction.x += ((partOfPlatform - 0.5) * 0.4);


			//check array
			//x <-0.9 ; -(pow(0.19, 1/2))> & <(pow(0.19, 1/2)); 0.9>
			std::cout << m_direction.x << "\t";
			checkArray();
			std::cout << m_direction.x << "\t";
			normalize();
			std::cout << m_direction.y << std::endl;
			return true;
		}
		else if (Distance(startPos, centerBallPos) <= BALL_RADIUS*BALL_RADIUS
			|| Distance(endPos, centerBallPos) <= BALL_RADIUS*BALL_RADIUS)//colision with corners
		{
			m_direction.y = -m_direction.y;
			m_direction.x = -m_direction.x;
			return true;
		}
    }
    return false; 
}
コード例 #18
0
ファイル: HeapSnapshot.cpp プロジェクト: zhangyinglong/fibjs
result_t HeapSnapshot::load(const char* fname)
{
	Isolate* isolate = holder();
	result_t hr;
	v8::Local<v8::Value> v;
	v8::Local<v8::Object> o;

	QuickArray<int32_t> nodes;
	QuickArray<int32_t> edges;
	QuickArray<qstring> names;
	QuickArray<qstring> node_fields;
	QuickArray<qstring> node_types;
	QuickArray<qstring> edge_fields;
	QuickArray<qstring> edge_types;
	int32_t node_count, edge_count;
	static const char* node_fields_chk[] = {"type", "name", "id", "self_size", "edge_count"};
	static const char* node_types_chk[] = {"hidden", "array", "string", "object",
	                                       "code", "closure", "regexp", "number",
	                                       "native", "synthetic", "concatenated string",
	                                       "sliced string"
	                                      };
	static const char* edge_fields_chk[] = {"type", "name_or_index", "to_node"};
	static const char* edge_types_chk[] = {"context", "element", "property",
	                                       "internal", "hidden", "shortcut", "weak"
	                                      };

	qstring data;
	hr = fs_base::ac_readFile(fname, data);
	if (hr < 0)
		return hr;

	hr = json_base::decode(data.c_str(), v);
	if (hr < 0)
		return hr;
	data.resize(0);

	if (!v->IsObject())
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	o = v8::Local<v8::Object>::Cast(v);
	hr = GetArray(o->Get(isolate->NewFromUtf8("nodes")),
	              nodes);
	if (hr < 0)
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	hr = GetArray(o->Get(isolate->NewFromUtf8("edges")),
	              edges);
	if (hr < 0)
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	hr = GetArray(o->Get(isolate->NewFromUtf8("strings")),
	              names);
	if (hr < 0)
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	v = o->Get(isolate->NewFromUtf8("snapshot"));
	if (v.IsEmpty() || !v->IsObject())
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	o = v8::Local<v8::Object>::Cast(v);
	hr = GetConfigValue(isolate->m_isolate, o, "node_count", node_count);
	if (hr < 0)
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	hr = GetConfigValue(isolate->m_isolate, o, "edge_count", edge_count);
	if (hr < 0)
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	v = o->Get(isolate->NewFromUtf8("meta"));
	if (v.IsEmpty() || !v->IsObject())
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	o = v8::Local<v8::Object>::Cast(v);
	hr = GetArray(o->Get(isolate->NewFromUtf8("node_fields")),
	              node_fields);
	if (hr < 0 || checkArray(node_fields, node_fields_chk, ARRAYSIZE(node_fields_chk)))
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	hr = GetArray(o->Get(isolate->NewFromUtf8("edge_fields")),
	              edge_fields);
	if (hr < 0 || checkArray(edge_fields, edge_fields_chk, ARRAYSIZE(edge_fields_chk)))
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	if (node_fields.size() * node_count != nodes.size())
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	if (edge_fields.size() * edge_count != edges.size())
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	v = o->Get(isolate->NewFromUtf8("node_types"));
	if (v.IsEmpty() || !v->IsArray())
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	hr = GetArray(v8::Local<v8::Array>::Cast(v)->Get(0), node_types);
	if (hr < 0 || checkArray(node_types, node_types_chk, ARRAYSIZE(node_types_chk)))
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	v = o->Get(isolate->NewFromUtf8("edge_types"));
	if (v.IsEmpty() || !v->IsArray())
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	hr = GetArray(v8::Local<v8::Array>::Cast(v)->Get(0), edge_types);
	if (hr < 0 || checkArray(edge_types, edge_types_chk, ARRAYSIZE(edge_types_chk)))
		return CHECK_ERROR(CALL_E_INVALID_DATA);

	int32_t node_pos = 0, edge_pos = 0;

	m_nodes = new List();
	while (node_pos < node_count)
	{
		int32_t _base = node_pos * (int32_t)node_fields.size();
		int32_t _node_type = nodes[_base];
		int32_t _node_name_id = nodes[_base + 1];
		if (_node_name_id < 0 || _node_name_id >= (int32_t)names.size())
			return CHECK_ERROR(CALL_E_INVALID_DATA);
		qstring _node_name = names[_node_name_id];
		int32_t _node_id = nodes[_base + 2];
		int32_t _node_size = nodes[_base + 3];
		int32_t _node_edge = nodes[_base + 4];
		obj_ptr<List> _edges = new List();

		if (edge_pos + _node_edge > edge_count)
			return CHECK_ERROR(CALL_E_INVALID_DATA);

		while (_node_edge --)
		{
			int32_t _base = edge_pos * (int32_t)edge_fields.size();
			int32_t _edge_type = edges[_base];
			int32_t _edge_name_id = edges[_base + 1];
			int32_t _edge_toid = edges[_base + 2];
			qstring _edge_name;

			if (is_num_type(_edge_type))
			{
				char buf[64];

				sprintf(buf, "%d", _edge_name_id);
				_edge_name = buf;
			}
			else
				_edge_name = names[_edge_name_id];

			if (_edge_toid % node_fields.size() != 0 ||
			        _edge_toid >= (int32_t)edges.size())
				return CHECK_ERROR(CALL_E_INVALID_DATA);
			_edge_toid = nodes[_edge_toid + 2];

			obj_ptr<HeapGraphEdge> _edge = new HeapGraphEdge(this, _edge_type,
			        _edge_name, _node_id, _edge_toid);
			_edges->append(_edge);

			edge_pos ++;
		}

		_edges->freeze();

		obj_ptr<HeapGraphNode> _node = new HeapGraphNode(_node_type,
		        _node_name, _node_id, _node_size, _edges);

		_nodes.insert(std::pair<int32_t, int32_t>(_node_id, node_pos));
		m_nodes->append(_node);

		node_pos ++;
	}

	m_nodes->freeze();

	return 0;
}
コード例 #19
0
int FileListModel::importFromCsv(QWidget *parent, const QString &inFile)
{
	QFile file(inFile);
	if(!file.open(QIODevice::ReadOnly))
	{
		return CsvError_FileOpen;
	}

	QTextCodec *codec = NULL;
	QByteArray bomCheck = file.peek(16);

	if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xef\xbb\xbf"))
	{
		codec = QTextCodec::codecForName("UTF-8");
	}
	else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xff\xfe"))
	{
		codec = QTextCodec::codecForName("UTF-16LE");
	}
	else if((!bomCheck.isEmpty()) && bomCheck.startsWith("\xfe\xff"))
	{
		codec = QTextCodec::codecForName("UTF-16BE");
	}
	else
	{
		const QString systemDefault = tr("(System Default)");

		QStringList codecList;
		codecList.append(systemDefault);
		codecList.append(lamexp_available_codepages());

		QInputDialog *input = new QInputDialog(parent);
		input->setLabelText(EXPAND(tr("Select ANSI Codepage for CSV file:")));
		input->setOkButtonText(tr("OK"));
		input->setCancelButtonText(tr("Cancel"));
		input->setTextEchoMode(QLineEdit::Normal);
		input->setComboBoxItems(codecList);
	
		if(input->exec() < 1)
		{
			LAMEXP_DELETE(input);
			return CsvError_Aborted;
		}
	
		if(input->textValue().compare(systemDefault, Qt::CaseInsensitive))
		{
			qDebug("User-selected codec is: %s", input->textValue().toLatin1().constData());
			codec = QTextCodec::codecForName(input->textValue().toLatin1().constData());
		}
		else
		{
			qDebug("Going to use the system's default codec!");
			codec = QTextCodec::codecForName("System");
		}

		LAMEXP_DELETE(input);
	}

	bomCheck.clear();

	//----------------------//

	QTextStream stream(&file);
	stream.setAutoDetectUnicode(false);
	stream.setCodec(codec);

	QString headerLine = stream.readLine().simplified();

	while(headerLine.isEmpty())
	{
		if(stream.atEnd())
		{
			qWarning("The file appears to be empty!");
			return CsvError_FileRead;
		}
		qWarning("Skipping a blank line at beginning of CSV file!");
		headerLine = stream.readLine().simplified();
	}

	QStringList header = headerLine.split(";", QString::KeepEmptyParts);

	const int nCols = header.count();
	const int nFiles = m_fileList.count();

	if(nCols < 1)
	{
		qWarning("Header appears to be empty!");
		return CsvError_FileRead;
	}

	bool *ignore = new bool[nCols];
	memset(ignore, 0, sizeof(bool) * nCols);

	for(int i = 0; i < nCols; i++)
	{
		if((header[i] = header[i].trimmed()).isEmpty())
		{
			ignore[i] = true;
		}
	}

	//----------------------//

	for(int i = 0; i < nFiles; i++)
	{
		if(stream.atEnd())
		{
			LAMEXP_DELETE_ARRAY(ignore);
			return CsvError_Incomplete;
		}
		
		QString line = stream.readLine().simplified();
		
		if(line.isEmpty())
		{
			qWarning("Skipping a blank line in CSV file!");
			continue;
		}
		
		QStringList data = line.split(";", QString::KeepEmptyParts);

		if(data.count() < header.count())
		{
			qWarning("Skipping an incomplete line in CSV file!");
			continue;
		}

		const QString key = m_fileList[i];

		for(int j = 0; j < nCols; j++)
		{
			if(ignore[j])
			{
				continue;
			}
			else if(CHECK_HDR(header.at(j), "POSITION"))
			{
				bool ok = false;
				unsigned int temp = data.at(j).trimmed().toUInt(&ok);
				if(ok) m_fileStore[key].metaInfo().setPosition(temp);
			}
			else if(CHECK_HDR(header.at(j), "TITLE"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setTitle(temp);
			}
			else if(CHECK_HDR(header.at(j), "ARTIST"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setArtist(temp);
			}
			else if(CHECK_HDR(header.at(j), "ALBUM"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setAlbum(temp);
			}
			else if(CHECK_HDR(header.at(j), "GENRE"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setGenre(temp);
			}
			else if(CHECK_HDR(header.at(j), "YEAR"))
			{
				bool ok = false;
				unsigned int temp = data.at(j).trimmed().toUInt(&ok);
				if(ok) m_fileStore[key].metaInfo().setYear(temp);
			}
			else if(CHECK_HDR(header.at(j), "COMMENT"))
			{
				QString temp = data.at(j).trimmed();
				if(!temp.isEmpty()) m_fileStore[key].metaInfo().setComment(temp);
			}
			else
			{
				qWarning("Unkonw field '%s' will be ignored!", QUTF8(header.at(j)));
				ignore[j] = true;
				
				if(!checkArray(ignore, false, nCols))
				{
					qWarning("No known fields left, aborting!");
					return CsvError_NoTags;
				}
			}
		}
	}

	//----------------------//

	LAMEXP_DELETE_ARRAY(ignore);
	return CsvError_OK;
}
コード例 #20
0
ファイル: RecentFilesManager.cpp プロジェクト: MyGUI/mygui
	void RecentFilesManager::addRecentFile(const MyGUI::UString& _fileName)
	{
		mRecentFiles.insert(mRecentFiles.begin(), _fileName);

		checkArray(mRecentFiles, mMaxRecentFiles);
	}
コード例 #21
0
static void 
abv_getdata(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  
  int result;       /* return values for called function */
  mxArray *pArray;  /* generic pointer to a matlab array */
  int lastBlock;    /* the last block which we have seen */
  int nChannels;    /* number of channels */
  int blocksize;    /* the size of blocks */
  int ElementSize;  /* size of one data point. 2 if int16, 4 if int32, etc */
  int reconnect;    /* if we reconnect on connection loss */
  char *bv_hostname = 0;  /* if we reconnect wi need the hostname */
  struct RDA_MessageData *pMsgData;
  struct RDA_MessageStart *pMsgStart;
  
  /* init the input and output values */
  const mxArray* IN_STATE = prhs[0];
  mxArray* OUT_DATA = NULL;
  mxArray* OUT_MRK_TIME = NULL;
  mxArray* OUT_MRK_DESCR = NULL;
  mxArray* OUT_STATE = NULL;
    
  /* get the information from the state and obtain the data */
  lastBlock = (int)getScalar(IN_STATE, FIELD_BLOCK_NO);
  nChannels = getArrayN(IN_STATE, FIELD_CLAB);
  
  result = getData(&pMsgData, &blocksize, lastBlock, nChannels, &ElementSize);
  
  /* If everything is okay, construct the appropriate output. Else
   * return empty arrays.
   */
  if (result != -1) {
    int n;
    int nChans_orig, lag, nPoints, nChans_sel, nMarkers, pDstPosition;
    double *chan_sel, *scale, *pDst0, *pMrkPos, *pSrcDouble;
    struct RDA_Marker *pMarker;
    char *pszType, *pszDesc;
    char* outputTypeDef;
    int outputType;
    double *pMrkToe;

    /* get necessary information from the current state */
    nChans_orig = getArrayN(IN_STATE, FIELD_CLAB);
    lag = (int) getScalar(IN_STATE,FIELD_LAG);

    nPoints = (getFIRPos() + pMsgData->nPoints)/lag;

    chan_sel = getArray(IN_STATE, FIELD_CHAN_SEL);
    nChans_sel = getArrayN(IN_STATE, FIELD_CHAN_SEL);
    
    /* check for the new resample filter */
    abv_assert(checkArray(IN_STATE, FIELD_FILT_SUBSAMPLE, 1, lag), "bbci_acquire_bv: Resample filter has to be a vector. Resample filter has to correspondent with the sampling rate.");
    filterFIRSet(getArray(IN_STATE, FIELD_FILT_SUBSAMPLE));
    
    /* construct the data output matrix. */
    OUT_DATA = mxCreateDoubleMatrix(nPoints, nChans_sel, mxREAL);
    
    pArray = mxGetField(IN_STATE, 0, "scale");
    scale = mxGetPr(pArray);
    pDst0= mxGetPr(OUT_DATA);
    pDstPosition = 0;

    /* convert the source data to double format */
    pSrcDouble = (double*)malloc(pMsgData->nPoints * nChans_orig * sizeof(double));
    if (ElementSize==2) {
        int16_t *pSrc = pMsgData->nData;
        for(n = 0; n != pMsgData->nPoints * nChans_orig; ++n) {
          pSrcDouble[n] = (double)pSrc[n];
        }
    } else if (ElementSize==4) {
        int32_t *pSrc = (int32_t*) pMsgData->nData;
        for(n = 0; n != pMsgData->nPoints * nChans_orig; ++n) {
          pSrcDouble[n] = (double)pSrc[n];
        }
    } else {
        mexErrMsgTxt("bbci_acquire_bv: Unknown element size");
    }
    
    /* filter the data with the filters */
    filterData(pSrcDouble,pMsgData->nPoints ,pDst0,nPoints, chan_sel, nChans_sel, scale);
    free(pSrcDouble);
    
    /* if markers are also requested, construct the appropriate output
       matrices */ 
    if (nlhs >= 2) {
      nMarkers = pMsgData->nMarkers;

      if (nMarkers > 0) {
        /* if markers existed, collect them */
        OUT_MRK_TIME = mxCreateDoubleMatrix(1, nMarkers, mxREAL);
        pMrkPos = mxGetPr(OUT_MRK_TIME);
        
        outputTypeDef = getString(IN_STATE, FIELD_MARKER_FORMAT);
        if(0 == strcmp ("numeric", outputTypeDef)) {
          outputType = 1;
        } else if(0 == strcmp ("string", outputTypeDef)) {
          outputType = 2;
        } else {
          mexErrMsgTxt("bbci_acquire_bv: Unknown ouput type.");
        }
        free(outputTypeDef);

        if (nlhs >= 3) {
          if(1 == outputType) { /* numeric */
            OUT_MRK_DESCR = mxCreateDoubleMatrix(1, nMarkers, mxREAL);
            pMrkToe = mxGetPr(OUT_MRK_DESCR);
          } else if(2 == outputType) {/* string */
            OUT_MRK_DESCR = mxCreateCellMatrix(1,nMarkers);
          } else {
            mexErrMsgTxt("bbci_acquire_bv: Unknown ouput type for output.");
          }
        }

        pMarker = (struct RDA_Marker*)((char*)pMsgData->nData + pMsgData->nPoints * nChans_orig * ElementSize);

        double origFs = getScalar(IN_STATE, FIELD_ORIG_FS);
        for (n = 0; n < nMarkers; n++) {
          pMrkPos[n]= ((double)pMarker->nPosition+1.0) * 1000.0 /origFs;
          pszType = pMarker->sTypeDesc;
          pszDesc = pszType + strlen(pszType) + 1;
          if (nlhs >= 3) {
            if(1 == outputType) { /* numeric */
              pMrkToe[n]= ((*pszDesc =='R') ? -1 : 1) * atoi(pszDesc+1);
            } else if(2 == outputType) {/* string */
              mxSetCell(OUT_MRK_DESCR, n, mxCreateString(pszDesc));
            } else {
              mexErrMsgTxt("bbci_acquire_bv: Unknown ouput type for output.");
            }
          }
          
          pMarker = (struct RDA_Marker*)((char*)pMarker + pMarker->nSize);
        }

      }
      else {
        /* no markers -> return empty matrix */
        OUT_MRK_TIME = mxCreateDoubleMatrix(0, 0, mxREAL);
        if (nlhs >= 3) {
          OUT_MRK_DESCR = mxCreateDoubleMatrix(0, 0, mxREAL);
        }
      }
    } /* end constructing marker outputs */
  }
  else {
    int nChans_sel;
    
    reconnect = (int) getScalar(IN_STATE, FIELD_RECONNECT);
    if(1 == reconnect) {
      printf("bbci_acquire_bv: getData didn't work, reconnecting ");

      /* only close the connection */
      closeConnection();
      connected = 0;
      
      bv_hostname = (char *) malloc(MAX_CHARS);
      /* getting the hostname for the new connection */
      pArray = mxGetField(IN_STATE, 0, "hostname");
      mxGetString(pArray, bv_hostname, MAX_CHARS);
      
      free(pMsgData);
      /* try reconnecting till we get a new connection */
      while(IC_OKAY != (result = initConnection(bv_hostname, &pMsgStart))){
        printf("bbci_acquire_bv: connecting failed, trying again\n");
        free(pMsgData);
      }
      
      /* cleaning things up */
      free(bv_hostname);
      free(pMsgStart);
      connected = 1;
    } else {
      printf("bbci_acquire_bv: getData didn't work, closing connection, returning -2\n ");
      /* close the connection and clean everything up */
      abv_close();
    }
    
    /* We have an error in the data transmition return an empty datablock. */
    pArray = mxGetField(IN_STATE, 0, "chan_sel");
    nChans_sel = mxGetN(pArray);

    OUT_DATA = mxCreateDoubleMatrix(0, nChans_sel, mxREAL);

    if (nlhs >= 2){OUT_MRK_TIME = mxCreateDoubleMatrix(0,0, mxREAL);};
    if (nlhs >= 3){OUT_MRK_DESCR = mxCreateDoubleMatrix(0,0, mxREAL);};
  }
  
  /* clone the state */
  if(nlhs >= 4) {OUT_STATE = mxDuplicateArray(IN_STATE);};
  
  plhs[0] = OUT_DATA;
  if(nlhs >=2) {
    plhs[1] = OUT_MRK_TIME;
  }
  if(nlhs >=3) {
    plhs[2] = OUT_MRK_DESCR;
  }
  if(nlhs >=4) {
    plhs[3] = OUT_STATE;
  }
      
  
  free(pMsgData);
}
コード例 #22
0
ファイル: handle.c プロジェクト: Acidburn0zzz/code
/*---------------------------------------------------------------------*/
void  *HHGetPointer(int handle)
{
  assert(handle < MAXHANDLE && handle >= 0);
  checkArray();
  return pointerArray[handle];
}
コード例 #23
0
ファイル: handle.c プロジェクト: Acidburn0zzz/code
/*---------------------------------------------------------------------*/
void HHRemoveHandle(int handle)
{
  assert(handle < MAXHANDLE && handle >= 0);
  checkArray();
  pointerArray[handle] = NULL;
}
コード例 #24
0
ファイル: symbol_manager.hpp プロジェクト: JasonZen/arrayfire
bool checkArrays(af_backend activeBackend, T a, Args... arg)
{
    return checkArray(activeBackend, a) && checkArrays(activeBackend, arg...);
}
コード例 #25
0
ファイル: filler.cpp プロジェクト: amarcott11/CS225
animation filler::fill( PNG & img, int x, int y,
        colorPicker & fillColor, int tolerance, int frameFreq ) {
    /**
     * @todo You need to implement this function!
     *
     * This is the basic description of a flood-fill algorithm: Every fill
     * algorithm requires an ordering structure, which is passed to this
     * function via its template parameter. For a breadth-first-search
     * fill, that structure is a Queue, for a depth-first-search, that
     * structure is a Stack. To begin the algorithm, you simply place the
     * given point in the ordering structure. Then, until the structure is
     * empty, you do the following:
     *
     * 1.     Remove a point from the ordering structure. 
     *
     *        If it has not been processed before and if its color is
     *        within the tolerance distance (up to and **including**
     *        tolerance away in square-RGB-space-distance) to the original
     *        point's pixel color [that is, \f$(currentRed - OriginalRed)^2 +
              (currentGreen - OriginalGreen)^2 + (currentBlue -
              OriginalBlue)^2 \leq tolerance\f$], then: 
     *        1.    indicate somehow that it has been processed (do not mark it
     *              "processed" anywhere else in your code) 
     *        2.    change its color in the image using the appropriate
     *              colorPicker
     *        3.    add all of its neighbors to the ordering structure, and 
     *        4.    if it is the appropriate frame, send the current PNG to the
     *              animation (as described below).
     * 2.     When implementing your breadth-first-search and
     *        depth-first-search fills, you will need to explore neighboring
     *        pixels in some order.
     *
     *        While the order in which you examine neighbors does not matter
     *        for a proper fill, you must use the same order as we do for
     *        your animations to come out like ours! The order you should put
     *        neighboring pixels **ONTO** the queue or stack is as follows:
     *        **RIGHT(+x), DOWN(+y), LEFT(-x), UP(-y). IMPORTANT NOTE: *UP*
     *        here means towards the top of the image, so since an image has
     *        smaller y coordinates at the top, this is in the *negative y*
     *        direction. Similarly, *DOWN* means in the *positive y*
     *        direction.** To reiterate, when you are exploring (filling out)
     *        from a given pixel, you must first try to fill the pixel to
     *        it's RIGHT, then the one DOWN from it, then to the LEFT and
     *        finally UP. If you do them in a different order, your fill may
     *        still work correctly, but your animations will be different
     *        from the grading scripts!
     * 3.     For every k pixels filled, **starting at the kth pixel**, you
     *        must add a frame to the animation, where k = frameFreq. 
     *
     *        For example, if frameFreq is 4, then after the 4th pixel has
     *        been filled you should add a frame to the animation, then again
     *        after the 8th pixel, etc.  You must only add frames for the
     *        number of pixels that have been filled, not the number that
     *        have been checked. So if frameFreq is set to 1, a pixel should
     *        be filled every frame.
     */
	OrderingStructure <int> xCoordinates;
	OrderingStructure <int> yCoordinates;
	animation myAnimation;
	int frameCount = 0;
	std::vector <bool> checkArray(img.height()*img.width());
	for (size_t i = 0; i < img.height(); i++)
	{
		for(size_t j = 0; j < img.width(); j++)
		{
			checkArray[i*img.width()+j] = false;
		}
	}
	xCoordinates.add(x);
	yCoordinates.add(y);
	int origin_r = img(x,y)->red;
 	int origin_g = img(x,y)->green;
        int origin_b = img(x,y)->blue;

	while(!xCoordinates.isEmpty())
	{
		int currX = xCoordinates.remove();
		int currY = yCoordinates.remove();
		RGBAPixel currPixel = *img(currX,currY);
		int colorDistance = pow(currPixel.red-origin_r,2) + pow(currPixel.green-origin_g,2) + pow(currPixel.blue -origin_b,2);	
		if((!checkArray[currY*img.width()+currX])&& colorDistance <= tolerance)
		{
			checkArray[currY*img.width()+currX] = true;
			RGBAPixel tempPixel = fillColor(currX,currY);
			img(currX,currY)->red = tempPixel.red;
			img(currX,currY)->green = tempPixel.green;
			img(currX,currY)->blue = tempPixel.blue;
			//right
			if(currX + 1 < int(img.height()))
			{
				xCoordinates.add(currX+1);
				yCoordinates.add(currY);
			}
			//down
			if(currY + 1 < int(img.height()))
			{
				xCoordinates.add(currX);
				yCoordinates.add(currY+1);
			}
			//left
			if(currX - 1 >= 0)
			{
				xCoordinates.add(currX-1);
				yCoordinates.add(currY);
			}
			//up
			if(currY - 1 >= 0)
			{
				xCoordinates.add(currX);
				yCoordinates.add(currY-1);
			}			
			if((++frameCount) % frameFreq == 0) 
				myAnimation.addFrame(img);

		}	
	
	}
		
    	return myAnimation;	
}
コード例 #26
0
ファイル: HW.c プロジェクト: Kablys/university
int main (int argc, char *argv[] ){
	int n = 0,			//size of arrays
		i = 0,
		maxArraySize = checkMainArg(argc, argv[2]), //changes array size depending on arguments given to program
		dif = INT_MAX,	//for searching smalles difference
		step = 0,
		exit = 1,
		navigMenu = 0,
		*data = malloc(1 * sizeof (*data)), 		//array for input data
		*oneZero = malloc(1 * sizeof (*oneZero)),		//holds binary numbers for comparing arrays
		*resultArray1 = malloc(1 * sizeof (*resultArray1)),	//holds first result array
		*resultArray2 = malloc(1 * sizeof (*resultArray2));
	
	while (exit){
		drawMenu();
		switch (navigMenu = checkInput(1, 5)){

		case 1://Enter size of array
			printf("Size of array(number between %d-%d):", MIN, maxArraySize);
			n=checkInput(MIN, maxArraySize);
			data = realloc(data, n*sizeof(int)), 		//array for input data
			oneZero = realloc(oneZero, n*sizeof(int)),		//holds binary numbers for comparing arrays
			resultArray1 = realloc(resultArray1, n * sizeof(int)),	//holds first result array
			resultArray2 = realloc(resultArray2, n * sizeof(int));	//holds second result array
			step = 1;
			break;

		case 2://Enter integers fot array
			if ((nextStep(navigMenu,step)) == 0){break;};
			printf("Input %d numbers\n",n);
			for (i = 0; i < n; i++){				//input for data array
				data[i] = checkInput(INT_MIN, INT_MAX);
			};
			step = 2;
			break;

		case 3://Split array
			if ((nextStep(navigMenu,step)) == 0){break;};
			while (oneZero[n-1] == 0){				//creates binary number represented as array
				iterateBinArr(oneZero);
				checkArray(n, oneZero, data, &dif, resultArray1, resultArray2);
				printf("Sucsses! array was split\n");
			};
			step = 3;
			break;

		case 4://Print results
			if ((nextStep(navigMenu,step)) == 0){break;};
			printResults(n, dif, resultArray1, resultArray2);
			break;

		case 5://Exit program
			printf("Good Bye\n");
			exit = 0;
			break;

		default:
			printf("error %d %d", navigMenu, exit);
			break;
		}
	}
	free(data);
	free(oneZero);
	free(resultArray1);
	free(resultArray2);
	return 0;
}
コード例 #27
0
ファイル: tester.cpp プロジェクト: artemeliy/inf4715
int MarketDefaultTest::Tester::verifyValues(MarketDefaults* dflts, const KeyDesc* key)
{
	bool exists = dflts->KeyExists(key->mpName);

	if (exists == key->mMissing) {
		mStatus.message(kErrorMessage,
			exists ? _T("Key [%s]%s exists but should be missing\r\n")
				   : _T("Key [%s]%s is missing but should exist\r\n"),
			dflts->GetSectionName(), key->mpName);
		return 1;
	}

	if (key->mMissing)
		return 0;

	int errors = 0;

	switch (key->mType) {
		case kInt: {
			int val;
			if (!dflts->GetInt(key->mpName, val)) {
				mStatus.message(kErrorMessage, _T("Key [%s]%s didn't return an integer value\r\n"),
					dflts->GetSectionName(), key->mpName);
				++errors;
			} else if (val != static_cast<int*>(key->mpValue)[0]) {
				mStatus.message(kErrorMessage, _T("Key [%s]%s didn't compare\r\n")
											_T("    \"%d\" was expected\r\n")
											_T("    \"%d\" was found\r\n"),
					dflts->GetSectionName(), key->mpName, key->mpValue, val);
				++errors;
			}
		} break;

		case kIntArray: {
			int* val = new int[key->mValueCount + 10];
			errors += checkArray(dflts, key, val, 0, &MarketDefaults::GetIntArray,
				_T("an integer"), _T("%d"));
			errors += checkArray(dflts, key, val, -5, &MarketDefaults::GetIntArray,
				_T("an integer"), _T("%d"));
			errors += checkArray(dflts, key, val, +3, &MarketDefaults::GetIntArray,
				_T("an integer"), _T("%d"));
			delete[] val;
		} break;

		case kFloat: {
			float val;
			if (!dflts->GetFloat(key->mpName, val)) {
				mStatus.message(kErrorMessage, _T("Key [%s]%s didn't return a float value\r\n"),
					dflts->GetSectionName(), key->mpName);
				++errors;
			} else if (val != static_cast<float*>(key->mpValue)[0]) {
				mStatus.message(kErrorMessage, _T("Key [%s]%s didn't compare\r\n")
											_T("    \"%.10g\" was expected\r\n")
											_T("    \"%.10g\" was found\r\n"),
					dflts->GetSectionName(), key->mpName, key->mpValue, val);
				++errors;
			}
		} break;

		case kFloatArray: {
			float* val = new float[key->mValueCount + 10];
			errors += checkArray(dflts, key, val, 0, &MarketDefaults::GetFloatArray,
				_T("a float"), _T("%.10g"));
			errors += checkArray(dflts, key, val, -5, &MarketDefaults::GetFloatArray,
				_T("a float"), _T("%.10g"));
			errors += checkArray(dflts, key, val, +3, &MarketDefaults::GetFloatArray,
				_T("a float"), _T("%.10g"));
			delete[] val;
		} break;

		case kString: {
			TCHAR val[1024];
			if (!dflts->GetString(key->mpName, val, _countof(val))) {
				mStatus.message(kErrorMessage, _T("Key [%s]%s didn't return a string value\r\n"),
					key->mpName);
				++errors;
			} else if (_tcscmp(val, static_cast<TCHAR*>(key->mpValue)) != 0) {
				mStatus.message(kErrorMessage, _T("Key [%s]%s didn't compare\r\n")
											_T("    \"%s\" was expected\r\n")
											_T("    \"%s\" was found\r\n"),
					dflts->GetSectionName(), key->mpName, key->mpValue, val);
				++errors;
			}
		} break;
	}

	return errors;
}
コード例 #28
0
ファイル: main.c プロジェクト: pasketi/TestRep
int main()
{   
    int loop = 0, loopMax = 5;
    double values[5][loopMax], increment[5] = {0,0,0,0,0}, averages[5] = {0,0,0,0,0}, spreads[5] = {0,0,0,0,0};
    do{
        long startTime, endTime;
        unsigned int x = arrayLength;
        int arrayA[x], arrayB[x], arrayC[x], arrayD[x], arrayE[x];
        
        fillArray(arrayA, x, 1);
		fillArray(arrayB, x, 2);
		fillArray(arrayC, x, 3);
		fillArray(arrayD, x, 4);
		fillArray(arrayE, x, 5);
		
		/*
		printArray(arrayA, x);
        printf("\n\n");
        printArray(arrayB, x);
        printf("\n\n");
        printArray(arrayC, x);
        printf("\n\n");
        printArray(arrayD, x);
        printf("\n\n");
        printArray(arrayE, x);
        printf("\n\n");
        
        system("pause");
        */
        
        printf("Starting QuickSort: Random\n");
        startTime = GetTickCount();
        quickSort(arrayA, 0, x);
        endTime = GetTickCount();
        increment[0] += (double)(endTime-startTime)/1000;
        values[0][loop] = (double)(endTime-startTime)/1000;
        printf("Done! Took %.2f s\n\n", (double)(endTime-startTime)/1000);
        
        printf("Starting QuickSort: In order\n");
        startTime = GetTickCount();
        quickSort(arrayB, 0, x);
        endTime = GetTickCount();
        increment[1] += (double)(endTime-startTime)/1000;
        values[1][loop] = (double)(endTime-startTime)/1000;
        printf("Done! Took %.2f s\n\n", (double)(endTime-startTime)/1000);
        
        printf("Starting QuickSort: Reversed\n");
        startTime = GetTickCount();
        quickSort(arrayC, 0, x);
        endTime = GetTickCount();
        increment[2] += (double)(endTime-startTime)/1000;
        values[2][loop] = (double)(endTime-startTime)/1000;
        printf("Done! Took %.2f s\n\n", (double)(endTime-startTime)/1000);
        
        printf("Starting QuickSort: 1,100,2,99...\n");
        startTime = GetTickCount();
        quickSort(arrayD, 0, x);
        endTime = GetTickCount();
        increment[3] += (double)(endTime-startTime)/1000;
        values[3][loop] = (double)(endTime-startTime)/1000;
        printf("Done! Took %.2f s\n\n", (double)(endTime-startTime)/1000);
        
        printf("Starting QuickSort: 100,1,99,2\n");
        startTime = GetTickCount();
        quickSort(arrayE, 0, x);
        endTime = GetTickCount();
        increment[4] += (double)(endTime-startTime)/1000;
        values[4][loop] = (double)(endTime-startTime)/1000;
        printf("Done! Took %.2f s\n\n", (double)(endTime-startTime)/1000);
    
        printf("Checking arrays...\n\n");
        
        //prints
        printf("\n\nChecking QuickSort: Random\n");
        checkArray(arrayA, x);
        printf("\n\nChecking QuickSort: Sorted\n");
        checkArray(arrayB, x);
        printf("\n\nChecking QuickSort: Reversed\n\n");
        checkArray(arrayC, x);
        printf("\n\nChecking QuickSort: 1,100,2,99...\n");
        checkArray(arrayD, x);
        printf("\n\nChecking QuickSort: 100,1,99,2\n");
        checkArray(arrayE, x);

        printf("\n\n");
        loop++;
    }while(loop < loopMax);
    
    int i;
    for(i = 0; i < 5;i++){
          averages[i] = increment[i]/loopMax;
    }
    
    for(i = 0; i < 5;i++){
          spreads[i] = calculateSpread(values[i], loopMax, i, averages);
    }
    
    printf("Random \n");
    printf("Average: %.2f \n", averages[0]);
    printf("Spread: %.2lf \n\n", spreads[0]);
    printf("Sorted \n");
    printf("Average: %.2f \n", averages[1]);
    printf("Spread: %.2lf \n\n", spreads[1]);
    printf("Reversed \n");
    printf("Average: %.2f \n", averages[2]);
    printf("Spread: %.2lf \n\n", spreads[2]);
    printf("1,100,2,99... \n");
    printf("Average: %.2f \n", averages[3]);
    printf("Spread: %.2lf \n\n", spreads[3]);
    printf("100,1,99,2... \n");
    printf("Average: %.2f \n", averages[4]);
    printf("Spread: %.2lf \n\n", spreads[4]);
    
    system("PAUSE");
    return 0;
}
コード例 #29
0
static void 
abv_init(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], bool isStructInit)
{
  int result;
  char *bv_hostname = 0;
  struct RDA_MessageStart *pMsgStart;
  
  mxArray* OUT_STATE;
  
  /* copy the params to the out state */
  if(isStructInit) {
    // init with struct
    OUT_STATE = mxDuplicateArray(prhs[1]);
  } else {
    // init with property list
    int dims[2] = {1,1};
    OUT_STATE = mxCreateStructArray(2, dims, 0, NULL);
    // arguments have beed checked in mexFunction
    for(int i = 1; i < nrhs; i = i + 2) {
      addField(OUT_STATE, prhs[i], prhs[i + 1]);
    }
  }
  
  /* check for the needed fields values 
   * if they don't exist we will set the default values */
  checkString(OUT_STATE,FIELD_HOST, "127.0.0.1");
  
  /* Get server name (or use default "brainamp") */
  bv_hostname = getString(OUT_STATE, FIELD_HOST);

  /* open connection */
  result = initConnection(bv_hostname,&pMsgStart);
  free(bv_hostname);  
    
  if (result == IC_OKAY) {
    /* construct connection state structure */
    int nChans, lag, n;
    double orig_fs;
    mxArray *pArray;
    char *pChannelName;
    double *chan_sel;
    double *filter_buffer_sub;
    double *filter_buffer_a;
    double *filter_buffer_b;
    int iirFilterSize;
    
    nChans = pMsgStart->nChannels;
    orig_fs = 1000000.0 / ((double) pMsgStart->dSamplingInterval);
    
    /* Check fs */
    checkScalar(OUT_STATE,FIELD_FS,orig_fs);
    
    lag = (int) (orig_fs / getScalar(OUT_STATE, FIELD_FS));
    
    abv_assert(lag * (int)getScalar(OUT_STATE,FIELD_FS) == (int)orig_fs,"bbci_acquire_bv: The base frequency has to be a multiple of the requested frequency.");
    
    /* Overwrite the following fields */
    setScalar(OUT_STATE,FIELD_ORIG_FS, orig_fs);
    setScalar(OUT_STATE,FIELD_LAG, lag);
    setScalar(OUT_STATE,FIELD_BLOCK_NO, -1.0);
     /* this odd hack is because pMsgStart contains several variably
       sized arrays, and this is the way to get the channel names 
     */
    setStringCell(OUT_STATE, FIELD_CLAB,(char *) ((double*) pMsgStart->dResolutions + nChans), 1, nChans);
    
    
    /* Check the following fields */
    checkString(OUT_STATE,FIELD_MARKER_FORMAT, "numeric");
    abv_assert(1 == checkScalar(OUT_STATE, FIELD_RECONNECT, 1), "bbci_acquire_bv: Reconnect is no scalar.");
    abv_assert(1 == checkArray(OUT_STATE, FIELD_SCALE, 1, nChans, pMsgStart->dResolutions), "bbci_acquire_bv: Scale is no array or has wrong size.");
    
    chan_sel = (double *) malloc(nChans*sizeof(double));
    for (n = 0;n<nChans;n++) {
        chan_sel[n] = n+1;
    }
    abv_assert(1 == checkArray(OUT_STATE, FIELD_CHAN_SEL, 1, -nChans, chan_sel), "bbci_acquire_bv: chan_sel is no array.");  
    free(chan_sel);
    
    /* Create the default filters */
    
    filter_buffer_sub = (double *) malloc(lag*sizeof(double));
    for(n = 0; n < lag; ++n) {
      filter_buffer_sub[n] = 1.0 / (double)lag;
    }
    filter_buffer_a = (double *) malloc(sizeof(double));
    filter_buffer_a[0] = 1.0;
    filter_buffer_b = (double *) malloc(sizeof(double));
    filter_buffer_b[0] = 1.0;
    
    /* check the filters */
    abv_assert(1 == checkArray(OUT_STATE, FIELD_FILT_SUBSAMPLE, 1, lag, filter_buffer_sub), "bbci_acquire_bv: Subsample filter is no array or has the wrong size.");
    abv_assert(1 == checkArray(OUT_STATE, FIELD_FILT_A, 1, -1, filter_buffer_a), "bbci_acquire_bv: IIR filter aSubsample filter has the wrong size.");
    abv_assert(1 == checkArray(OUT_STATE, FIELD_FILT_B, 1, -1, filter_buffer_b), "bbci_acquire_bv: Subsample filter has the wrong size.");
    
    /* free the default filters */
    free(filter_buffer_sub);
    free(filter_buffer_a);
    free(filter_buffer_b);
    
    /* check if the iir filters have the same size */
    iirFilterSize = getArrayN(OUT_STATE, FIELD_FILT_A);
    
    abv_assert(getArrayN(OUT_STATE, FIELD_FILT_B) == iirFilterSize, "bbci_acquire_bv: bFilter and aFilter must have the same size.");
    
    
    /* get the arrays for the filters and create the filters */
    filter_buffer_sub = getArray(OUT_STATE, FIELD_FILT_SUBSAMPLE);
    filter_buffer_a = getArray(OUT_STATE, FIELD_FILT_A);
    filter_buffer_b = getArray(OUT_STATE, FIELD_FILT_B);
    
    filterFIRCreate(filter_buffer_sub, lag,nChans);
    filterIIRCreate(filter_buffer_a, filter_buffer_b, iirFilterSize, nChans);
    
    connected = 1;
  }
  
  plhs[0] = OUT_STATE;
  free(pMsgStart);
}