示例#1
0
void
print_number(U *p)
{
	char *s;
	static char buf[100];
	switch (p->k) {
	case NUM:
		s = mstr(p->u.q.a);
		if (*s == '+' || *s == '-')
			s++;
		print_str(s);
		if (isfraction(p)) {
			print_str("/");
			s = mstr(p->u.q.b);
			print_str(s);
		}
		break;
	case DOUBLE:
		sprintf(buf, "%.10g", p->u.d);
		if (*buf == '+' || *buf == '-')
			print_str(buf + 1);
		else
			print_str(buf);
		break;
	default:
		break;
	}
}
示例#2
0
static int my_xml_leave(MY_XML_PARSER *p, const char *str, uint slen)
{
  char *e;
  uint glen;
  char s[32];
  char g[32];
  int  rc;
  
  /* Find previous '.' or beginning */
  for( e=p->attrend; (e>p->attr) && (e[0]!='.') ; e--);
  glen = (e[0]=='.') ? (p->attrend-e-1) : p->attrend-e;
  
  if (str && (slen != glen))
  {
    mstr(s,str,sizeof(s)-1,slen);
    mstr(g,e+1,sizeof(g)-1,glen),
    sprintf(p->errstr,"'</%s>' unexpected ('</%s>' wanted)",s,g);
    return MY_XML_ERROR;
  }
  
  rc = p->leave_xml ? p->leave_xml(p,p->attr,p->attrend-p->attr) : MY_XML_OK;
  
  *e='\0';
  p->attrend=e;
  
  return rc;
}
	void sd_object::test<9>()
	{
		std::ostringstream resp;
		resp << "{'label':'short binary test', 'singlebinary':b(1)\"A\", 'singlerawstring':s(1)\"A\", 'endoftest':'end' }";
		std::string str = resp.str();
		LLSD sd;
		LLMemoryStream mstr((U8*)str.c_str(), str.size());
		S32 count = LLSDSerialize::fromNotation(sd, mstr, str.size());
		ensure_equals("parse count", count, 5);
		ensure("sd created", sd.isDefined());
		ensure_equals("sd type", sd.type(), LLSD::TypeMap);
		ensure_equals("map element count", sd.size(), 4);
		ensure_equals(
			"label",
			sd["label"].asString(),
			"short binary test");
		std::vector<U8> bin =  sd["singlebinary"].asBinary();
		std::vector<U8> expected;
		expected.resize(1);
		expected[0] = 'A';
		ensure("single binary", (0 == memcmp(&bin[0], &expected[0], 1)));
		ensure_equals(
			"single string",
			sd["singlerawstring"].asString(),
			std::string("A"));
		ensure_equals("end", sd["endoftest"].asString(), "end");
	}
示例#4
0
bool LLMimeParser::parseIndex(
	const std::vector<U8>& buffer,
	LLMimeIndex& index)
{
	LLMemoryStream mstr(&buffer[0], buffer.size());
	return parseIndex(mstr, buffer.size() + 1, index);
}
示例#5
0
static int estr(MY_XML_PARSER *st,const char *attr, uint len)
{
  char str[1024];
  
  mstr(str,attr,len,sizeof(str)-1);
  printf("LEAVE %s\n",str);
  return MY_XML_OK;
}
示例#6
0
int MessageOut(HWND hWnd,long strMsg, long strTitle, UINT mbstatus)
{
	CString tstr("");
	CString mstr("");
	VERIFY(tstr.LoadString(strTitle));
	VERIFY(mstr.LoadString(strMsg));

	return ::MessageBox(hWnd,mstr,tstr,mbstatus);
}
示例#7
0
文件: pub3msgpack.C 项目: dbc60/okws
void
pub3::msgpack::outbuf_t::ready ()
{
  if (!_tmp) {
    _tmp = New mstr (_tlen);
    _tp = _tmp->cstr ();
    _ep = _tp + _tlen;
  }
}
示例#8
0
文件: aparse.C 项目: Halfnhav4/okws
void
async_dumper_t::dump (size_t len, cbs c)
{
  buf = New mstr (len);
  bp = buf->cstr ();
  endp = bp + len;

  dump_cb = c;
  parse (wrap (this, &async_dumper_t::parse_done_cb));
}
示例#9
0
/// Creates and links the program from previously compiled unit processors
bool GLShader::create()
{
	// There must be some shaders to create a program
	if(m_shaders.empty()) return false;

	bool success = false;

	GLuint id = glCreateProgram();
	if(id)
	{
		// Bind attribute locations
		for(std::vector<std::pair<unsigned int, String> >::iterator it = m_attribs.begin(); it != m_attribs.end(); ++it)
		{
			glBindAttribLocation(id, static_cast<GLuint>(it->first), static_cast<const GLchar*>(it->second.c_str()));
		}

		// Attach compiled shaders
		for(std::vector<std::pair<ShaderTypes, unsigned int> >::iterator it = m_shaders.begin(); it != m_shaders.end(); ++it)
		{
			glAttachShader(id, static_cast<GLuint>(it->second));
		}

		// Link the program
		glLinkProgram(id);

		GLint linkStatus = GL_FALSE;
		glGetProgramiv(id, GL_LINK_STATUS, &linkStatus);
		if (linkStatus != GL_TRUE) {

			// -- re do
			GLint bufLength = 0;
			glGetProgramiv(id, GL_INFO_LOG_LENGTH, &bufLength);
			if (bufLength) {
				char* buf = new char[bufLength+1];
				if (buf) {
					glGetProgramInfoLog(id, bufLength, NULL, buf);
					buf[bufLength] = '\0';
					String mstr(buf);
					mstr.removeCharacter('\r');
					mstr.removeCharacter('\n');
					//std::cout << "GLSL: " << mstr << std::endl;
					//PRINTLOG("GLSL", "Failed to link shader program(%d): %s\n",mstr.length(), mstr.c_str());
					delete [] buf;
				}
			}
			// --

			glDeleteProgram(id);
			id = 0;
		}
		else success = true;
	}
	m_id = static_cast<unsigned int>(id);
	return success;
}
示例#10
0
int MessageOut(HWND hWnd, long strMsg, long strTitle, UINT mbstatus, long val1, long val2)
{
	CString tstr("");
	CString mstr("");
	CString fstr("");
	VERIFY(tstr.LoadString(strTitle));
	VERIFY(mstr.LoadString(strMsg));
	fstr.Format(mstr,val1,val2);

	return ::MessageBox(hWnd,fstr,tstr,mbstatus);
}
示例#11
0
文件: xml.c 项目: A-eolus/mysql
static int my_xml_leave(MY_XML_PARSER *p, const char *str, size_t slen)
{
  char *e;
  size_t glen;
  char s[32];
  char g[32];
  int  rc;

  /* Find previous '/' or beginning */
  for (e=p->attrend; (e>p->attr) && (e[0] != '/') ; e--);
  glen = (size_t) ((e[0] == '/') ? (p->attrend-e-1) : p->attrend-e);
  
  if (str && (slen != glen))
  {
    mstr(s,str,sizeof(s)-1,slen);
    if (glen)
    {
      mstr(g,e+1,sizeof(g)-1,glen),
      sprintf(p->errstr,"'</%s>' unexpected ('</%s>' wanted)",s,g);
    }
    else
      sprintf(p->errstr,"'</%s>' unexpected (END-OF-INPUT wanted)", s);
    return MY_XML_ERROR;
  }
  
  if (p->flags & MY_XML_FLAG_RELATIVE_NAMES)
    rc= p->leave_xml ? p->leave_xml(p, str, slen) : MY_XML_OK;
  else
    rc= (p->leave_xml ?  p->leave_xml(p,p->attr,p->attrend-p->attr) :
         MY_XML_OK);
  
  *e='\0';
  p->attrend=e;
  
  return rc;
}
	void sd_object::test<1>()
	{
		std::ostringstream resp;
		resp << "{'connect':true,  'position':[r128,r128,r128], 'look_at':[r0,r1,r0], 'agent_access':'M', 'region_x':i8192, 'region_y':i8192}";
		std::string str = resp.str();
		LLMemoryStream mstr((U8*)str.c_str(), str.size());
		LLSD response;
		S32 count = LLSDSerialize::fromNotation(response, mstr, str.size());
		ensure("stream parsed", response.isDefined());
		ensure_equals("stream parse count", count, 13);
		ensure_equals("sd type", response.type(), LLSD::TypeMap);
		ensure_equals("map element count", response.size(), 6);
		ensure_equals("value connect", response["connect"].asBoolean(), true);
		ensure_equals("value region_x", response["region_x"].asInteger(),8192);
		ensure_equals("value region_y", response["region_y"].asInteger(),8192);
	}
示例#13
0
/// Compiles a shader to be linked when create() is called, from a source file
bool GLShader::loadShaderFromFile(ShaderTypes type, const String& filename)
{
	bool success = false;

	GLuint shader = 0;

	switch(type)
	{
	case VertexUnit:	shader = glCreateShader(GL_VERTEX_SHADER);	break;
	case FragmentUnit:	shader = glCreateShader(GL_FRAGMENT_SHADER);   break;
	}

	String shaderCode = getFileContents(filename);
	const char* source = shaderCode.c_str();

	if (shader) {
		glShaderSource(shader, 1, &source, NULL);
		glCompileShader(shader);
		GLint compiled = 0;
		glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
		if (!compiled) {
			GLint infoLen = 0;
			glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
			if (infoLen) {
				char* buf = new char[infoLen];
				if (buf) {
					glGetShaderInfoLog(shader, infoLen, NULL, buf);
					//PRINTLOG("GLSL", "Failed to load shader: %s\n", buf);
					String mstr(buf);
					//mstr.removeCharacter('\r');
					//mstr.removeCharacter('\n');
					//std::cout << "GLSL: " << mstr << std::endl;
					delete [] buf;
				}	
				glDeleteShader(shader);
				shader = 0;
			}
		}
		else
		{
			m_shaders.push_back(std::make_pair(type, static_cast<unsigned int>(shader)));
			success = true;
		}
	}

	return success;
}
示例#14
0
文件: main.cpp 项目: hintjens/azmq
void test_message_constructors() {
    // default init range has 0 size
    azmq::message m;
    BOOST_ASSERT(m.size() == 0);

    // pre-sized message construction
    azmq::message mm(42);
    BOOST_ASSERT(mm.size() == 42);

    // implicit construction from asio::const_buffer
    std::string s("This is a test");
    azmq::message mstr(boost::asio::buffer(s));
    BOOST_ASSERT(s.size() == mstr.size());
    BOOST_ASSERT(s ==  mstr.string());

    // construction from string
    azmq::message mmstr(s);
    BOOST_ASSERT(s == mmstr.string());
}
示例#15
0
void Shader::loadFile(const char* fn, string & str)
{
    p_str = dir_path;
    string mstr(fn);
    p_str = p_str + mstr;
 //   cout << "p_str is " << endl << p_str << endl;


    ifstream in(p_str);

    if(!in.is_open())
    {
        cout << "The file " << fn << "cannot be openned\n" << endl;
        return;
    }

    char tmp[300];
    while(!in.eof())
    {
        in.getline(tmp,300);

    //    if(p_str == "./shaders/shadow_SecondRender_dir_pt_include.fs")
     //   {
       //     cout << tmp << endl;
        if(loadIncludeFiles(str, tmp))
            continue;
      //  }

        str+=tmp;
        str+='\n';
    }

/*
    if(p_str == "./shaders/shadow_SecondRender_dir_pt_include.fs")
    {
        cout << str << endl;
    }
*/
}
示例#16
0
 Bucket *StatFile::replaceMap(int cacheIndex, int64_t pageIndex, bool toWrite)
 {
     if (pages[cacheIndex].ptr != 0)
     {
         mm_->unmap(pages[cacheIndex].ptr, fileHeader_->page_size);
     }
     recordPageMiss();
     void *mapped = mm_->map(fd_, pageIndex * fileHeader_->page_size, fileHeader_->page_size, toWrite);
     if (!mapped)
     {
         std::stringstream msg;
         msg << "mmap(" << fileHeader_->name << ", offset=" << pageIndex * fileHeader_->page_size << ", size=" << fileHeader_->page_size << ") failed in StatFile::mapBucketPage()";
         std::string mstr(msg.str());
         Log(LL_Error, "istat") << mstr;
         throw std::runtime_error(mstr);
     }
     //  tell the kernel to please slurp these pages in, asynchronously
     pages[cacheIndex].ptr = (Bucket *)mapped;
     pages[cacheIndex].writable = toWrite;
     pages[cacheIndex].page = pageIndex;
     return (Bucket *)mapped;
 }
示例#17
0
static int cs_value(MY_XML_PARSER *st,const char *attr, size_t len)
{
  struct my_cs_file_info *i= (struct my_cs_file_info *)st->user_data;
  struct my_cs_file_section_st *s;
  int    state= (int)((s= cs_file_sec(st->attr.start,
                                      st->attr.end - st->attr.start)) ?
                      s->state : 0);
  int rc= MY_XML_OK;

  switch (state) {
  case _CS_MISC:
  case _CS_FAMILY:
  case _CS_ORDER:
    break;
  case _CS_ID:
    i->cs.number= strtol(attr,(char**)NULL,10);
    break;
  case _CS_BINARY_ID:
    i->cs.binary_number= strtol(attr,(char**)NULL,10);
    break;
  case _CS_PRIMARY_ID:
    i->cs.primary_number= strtol(attr,(char**)NULL,10);
    break;
  case _CS_COLNAME:
    i->cs.name=mstr(i->name,attr,len,MY_CS_NAME_SIZE-1);
    break;
  case _CS_CSNAME:
    i->cs.csname=mstr(i->csname,attr,len,MY_CS_NAME_SIZE-1);
    break;
  case _CS_CSDESCRIPT:
    i->cs.comment=mstr(i->comment,attr,len,MY_CS_CSDESCR_SIZE-1);
    break;
  case _CS_FLAG:
    if (!strncmp("primary",attr,len))
      i->cs.state|= MY_CS_PRIMARY;
    else if (!strncmp("binary",attr,len))
      i->cs.state|= MY_CS_BINSORT;
    else if (!strncmp("compiled",attr,len))
      i->cs.state|= MY_CS_COMPILED;
    break;
  case _CS_UPPERMAP:
    fill_uchar(i->to_upper,MY_CS_TO_UPPER_TABLE_SIZE,attr,len);
    i->cs.to_upper=i->to_upper;
    break;
  case _CS_LOWERMAP:
    fill_uchar(i->to_lower,MY_CS_TO_LOWER_TABLE_SIZE,attr,len);
    i->cs.to_lower=i->to_lower;
    break;
  case _CS_UNIMAP:
    fill_uint16(i->tab_to_uni,MY_CS_TO_UNI_TABLE_SIZE,attr,len);
    i->cs.tab_to_uni=i->tab_to_uni;
    break;
  case _CS_COLLMAP:
    fill_uchar(i->sort_order,MY_CS_SORT_ORDER_TABLE_SIZE,attr,len);
    i->cs.sort_order=i->sort_order;
    break;
  case _CS_CTYPEMAP:
    fill_uchar(i->ctype,MY_CS_CTYPE_TABLE_SIZE,attr,len);
    i->cs.ctype=i->ctype;
    break;

  /* Special purpose commands */
  case _CS_UCA_VERSION:
    rc= tailoring_append(st, "[version %.*s]", len, attr);
    break;

  case _CS_CL_SUPPRESS_CONTRACTIONS:
    rc= tailoring_append(st, "[suppress contractions %.*s]", len, attr);
    break;

  case _CS_CL_OPTIMIZE:
    rc= tailoring_append(st, "[optimize %.*s]", len, attr);
    break;

  case _CS_CL_SHIFT_AFTER_METHOD:
    rc= tailoring_append(st, "[shift-after-method %.*s]", len, attr);
    break;

  /* Collation Settings */
  case _CS_ST_STRENGTH:
    /* 1, 2, 3, 4, 5, or primary, secondary, tertiary, quaternary, identical */
    rc= tailoring_append(st, "[strength %.*s]", len, attr);
    break;

  case _CS_ST_ALTERNATE:
    /* non-ignorable, shifted */
    rc= tailoring_append(st, "[alternate %.*s]", len, attr);
    break;

  case _CS_ST_BACKWARDS:
    /* on, off, 2 */
    rc= tailoring_append(st, "[backwards %.*s]", len, attr);
    break;

  case _CS_ST_NORMALIZATION:
    /*
      TODO for WL#896: check collations for normalization: vi.xml
      We want precomposed characters work well at this point.
    */
    /* on, off */
    rc= tailoring_append(st, "[normalization %.*s]", len, attr);
    break;

  case _CS_ST_CASE_LEVEL:
    /* on, off */
    rc= tailoring_append(st, "[caseLevel %.*s]", len, attr);
    break;

  case _CS_ST_CASE_FIRST:
    /* upper, lower, off */
    rc= tailoring_append(st, "[caseFirst %.*s]", len, attr);
    break;

  case _CS_ST_HIRAGANA_QUATERNARY:
    /* on, off */
    rc= tailoring_append(st, "[hiraganaQ %.*s]", len, attr);
    break;

  case _CS_ST_NUMERIC:
    /* on, off */
    rc= tailoring_append(st, "[numeric %.*s]", len, attr);
    break;

  case _CS_ST_VARIABLE_TOP:
    /* TODO for WL#896: check value format */
    rc= tailoring_append(st, "[variableTop %.*s]", len, attr);
    break;

  case _CS_ST_MATCH_BOUNDARIES:
    /* none, whole-character, whole-word */
    rc= tailoring_append(st, "[match-boundaries %.*s]", len, attr);
    break;

  case _CS_ST_MATCH_STYLE:
    /* minimal, medial, maximal */
    rc= tailoring_append(st, "[match-style %.*s]", len, attr);
    break;


  /* Rules */
  case _CS_RESET:
    rc= tailoring_append(st, "%.*s", len, attr);
    break;

  case _CS_DIFF1:
  case _CS_DIFF2:
  case _CS_DIFF3:
  case _CS_DIFF4:
  case _CS_IDENTICAL:
    rc= tailoring_append(st, diff_fmt[state - _CS_DIFF1], len, attr);
    break;


  /* Rules: Expansion */
  case _CS_EXP_EXTEND:
    rc= tailoring_append(st, " / %.*s", len, attr);
    break;

  case _CS_EXP_DIFF1:
  case _CS_EXP_DIFF2:
  case _CS_EXP_DIFF3:
  case _CS_EXP_DIFF4:
  case _CS_EXP_IDENTICAL:
    if (i->context[0])
    {
      rc= tailoring_append2(st, context_diff_fmt[state - _CS_EXP_DIFF1],
                            strlen(i->context), i->context, len, attr);
      i->context[0]= 0;
    }
    else
      rc= tailoring_append(st, diff_fmt[state  - _CS_EXP_DIFF1], len, attr);
    break;

  /* Rules: Context */
  case _CS_CONTEXT:
    if (len < sizeof(i->context))
    {
      memcpy(i->context, attr, len);
      i->context[len]= '\0';
    }
    break;

  /* Rules: Abbreviating Ordering Specifications */
  case _CS_A_DIFF1:
  case _CS_A_DIFF2:
  case _CS_A_DIFF3:
  case _CS_A_DIFF4:
  case _CS_A_IDENTICAL:
    rc= tailoring_append_abbreviation(st, diff_fmt[state - _CS_A_DIFF1], len, attr);
    break;

  /* Rules: Placing Characters Before Others */
  case _CS_RESET_BEFORE:
    /*
      TODO for WL#896: Add this check into text customization parser:
      It is an error if the strength of the before relation is not identical
      to the relation after the reset. We'll need this for WL#896.
    */
    rc= tailoring_append(st, "[before %.*s]", len, attr);
    break;


  default:
    break;
  }

  return rc;
}
示例#18
0
//M+	
void mp(
	int MinCoreSize,
	int MaxCoreSize,
	int SamplingFreq,
	int NumReplicates,
	char* OutFilePath,
	std::string Kernel,
	vector<int> KernelAccessionIndex,
	vector<int> AccessionNameList,
	vector<vector<vector<int> > > ActiveAlleleByPopList,
	vector<vector<vector<int> > > TargetAlleleByPopList,
	vector<int> ActiveMaxAllelesList,
	vector<int> TargetMaxAllelesList,
	vector<std::string> FullAccessionNameList
	)	
{

	//PERFORM INITIAL MPI STUFF
	MPI_Status status; //this struct contains three fields which will contain info about the sender of a received message
						 // MPI_SOURCE, MPI_TAG, MPI_ERROR
	
	//MPI::Init ();  //Initialize MPI.
	int nproc = MPI::COMM_WORLD.Get_size ( );  //Get the number of processes.
	int procid = MPI::COMM_WORLD.Get_rank ( );  //Get the individual process ID.
	

	//set up vectors to fill with results
	//below is a stupid way to calculate the number of rows in the output file, value l (which = V1) 
	//used to monitor progress and as the maximum vector index for shared output vectors
	int l=0;
	for (int i=MinCoreSize;i<MaxCoreSize+1;i=i+SamplingFreq)
	{
		for (int j=0;j<NumReplicates;j++)
		{
			l++;
		}
	}
	
	double V1 = (double)l; //(MaxCoreSize - MinCoreSize + 1)*NumReplicates; //number of rows in output vectors
	vector<vector<double> > Results(V1, vector<double>(9)); //will contain numerical results
	vector<vector<string> > Members(V1); //will contain core set members
	
	//***MPI:  RECEIVE RESULTS AT MASTER 0
	//receive values from any slave, in any order, exiting when the number of 'receives' = the top vector size
	if ( procid == 0 ) 
	{
		//set up variables for monitoring progress
		int percent; //percent of analysis completed
		int progindex = 0;  //index to monitor progress, percent = 100*(progindex/l)

		//receive and process results from slave processors
		unsigned int i = 0;
		while (i<2*(Results.size())) //two receives per row
		{
			//probe the incoming message to determine its tag
			int nchar; //will contain the length of the char array passed with tag=1
			int vchar; //will contain the length of the vector passed with tag=0
			int tag; //tag of message from sender
			int source; //procid of sender
			
			MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
			//MPI_Get_count(&status, MPI_CHAR, &nchar); //probes the length of the message, saves it in nchar
			tag = status.MPI_TAG; //the tag defines which kind of comm it is, a vector of stats (0=resvec()) 
			                      //or a char array describing the members of the core (1=cc)
			source = status.MPI_SOURCE; //determine the source of the message so that you can define which sender to Recv from.  This will avoid an intervening message coming in after the MPI_Probe with a different length, causing a message truncated error.
			
			if (tag == 0)
			{
				//determine the length of the message tagged 0
				MPI_Get_count(&status, MPI_DOUBLE, &vchar);

				//cout <<" vchar="<<vchar<<" tag="<<tag<<" MPI_SOURCE="<<status.MPI_SOURCE<<" MPI_ERROR="<<status.MPI_ERROR<<"\n";

				//receive the vector of results, tagged 0, from:
				//MPI_Send(&resvec[0], resvec.size(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
				vector<double> t(10);
				MPI_Recv(&t[0], vchar, MPI_DOUBLE, source, 0, MPI_COMM_WORLD, &status);
			
				//load data from vector received onto Results, row number is last item t[9]
				for (int j=0;j<9;++j)
				{
					Results[ t[9] ][j] = t[j];
				}
				t.clear();
			}

			else if (tag == 1)
			{
				//determine the length of the message tagged 1
				MPI_Get_count(&status, MPI_CHAR, &nchar); //probes the length of the message, saves it in nchar

				//cout <<" nchar="<<nchar<<" tag="<<tag<<" MPI_SOURCE="<<status.MPI_SOURCE<<" MPI_ERROR="<<status.MPI_ERROR<<"\n";
				
				//receive the vector<string> of the core set, tagged 1, from:
				//MPI_Send(&m[0], nchar, MPI_CHAR, 0, 1, MPI_COMM_WORLD);
				//vector<string> m(nchar);
				char m[nchar];
				MPI_Recv(&m[0], nchar, MPI_CHAR, source, 1, MPI_COMM_WORLD, &status);
			
				//load core set onto Members
				//1. convert char array into a string
				string mstr(m);
			
				//2. split string on delimiter ',<!>,'
				string delim = ",<!>,";
				vector<string> mvec( countSubstring(mstr, delim) );
				unsigned int st = 0;
				std::size_t en = mstr.find(delim);
				int k = 0;
				while (en != std::string::npos)
				{
					mvec[k] = mstr.substr(st, en-st);
					st = en + delim.length();
					en = mstr.find(delim,st);
					++k;
				}
				string z = mstr.substr(st); //get row number as last item in mstr
				int zz = atoi(z.c_str()); //convert string to c-string then to int
			
				//3. load onto Members
				Members[zz] = mvec;
				
				//4. clean up
				memset(m, 0, nchar);; mstr=""; mvec.clear();
				

			}


			++i;
			
			//display progress
			progindex = progindex + 1;
			percent = 100*( progindex/(V1*2) ); //number of rows X 2 repeats needed to complete search
			printProgBar(percent); 
		}
	}//***MPI: END MASTER RECEIVE***/

	
	/***MPI:  SEND RESULTS FROM SLAVE PROCESSES***/
	else if ( procid != 0 )
	{
		unsigned int r; //r = core size, 
		//int nr, RandAcc, b, bsc, plateau; //nr = controller to repeat NumReplicates times
		int RandAcc, b, bsc, plateau; //nr = controller to repeat NumReplicates times
								//row = result vector row number, bsc = holds best sub core member, and other indexed accessions
									//plateau = index of the number of reps in optimization loop with same diversity value
		double RandomActiveDiversity;
		double AltRandomActiveDiversity;
		double StartingRandomActiveDiversity;
		double StartingAltRandomActiveDiversity;
		double RandomTargetDiversity;
		double AltRandomTargetDiversity;
		double StartingDiversity;
		double TempAltOptimizedActiveDiversity;
		double AltOptimizedActiveDiversity;
		double OptimizedTargetDiversity;
		double AltOptimizedTargetDiversity;
		double best;
		double nnew;
		vector<vector<vector<int> > > AlleleList;
		vector<vector<vector<int> > > CoreAlleles;
		vector<vector<vector<int> > > TdTempList;
		vector<vector<vector<int> > > BestSubCoreAlleles;
		std::string Standardize = "yes";  //a run that mimics the MSTRAT approach can be accomplished by setting Standardize="no", and setting up the var file so that each column in the .dat file is treated as a single locus, rather than two (or more) adjacent columns being treated as a single codominant locus.
		vector<int> AccessionsInCore;
		vector<int> AccessionsInSubCore;
		vector<int> BestSubCore;
		vector<int> BestSubCoreRevSorted;
		vector<int> TempList;
		vector<int> TempList2;
		vector<int> bestcore;
		vector<std::string> TempListStr;
	
		//seed the random number generator for each processor
		int tt;
		tt = (time(NULL));
		srand ( abs(((tt*181)*((procid-83)*359))%104729) );
			
		//do parallelization so that each rep by core size combo can be
		//handled by a distinct thread.  this involves figuring out the total
		//number of reps*coresizes taking into account the SamplingFreq
		int rsteps = 1 + floor( (MaxCoreSize - MinCoreSize) / SamplingFreq ); //number of steps from MinCoreSize to MaxCoreSize

		//***MPI: figure out where to start and stop loop for each processor
		int nreps = rsteps*NumReplicates;
		int count = nreps/(nproc-1); //p-1 assumes a master, i.e. one less processor than total
		int start = (procid-1) * count; //procid-1 makes you start at 0, assumes master is p0
		int stop;
		
		if (nreps % (nproc-1) > (procid-1))
		{
			start += procid - 1;
			stop = start + (count + 1); 
		}
		else
		{
			start += nreps % (nproc-1);
			stop = start + count;
		}
		
		//iterate thru the relevant rows
		for (int rnr=start;rnr<stop;++rnr)
		{
			r = MinCoreSize + ((rnr / NumReplicates) * SamplingFreq); //int rounds to floor
			
			//develop random starting core set
			//clear AccessionsInCore and set size
			AccessionsInCore.clear();
			AccessionsInCore.resize(r);
			
			//add kernel accessions to core, if necessary
			if (Kernel == "yes")
			{
				for (unsigned int i=0;i<KernelAccessionIndex.size();i++)
				{
					AccessionsInCore[i] = KernelAccessionIndex[i];
				}
			}

			//clear TempList and set size					
			TempList.clear();
			TempList.resize( AccessionNameList.size() );
			
			//set list of available accessions in TempList, by erasing those already in the core
			TempList = AccessionNameList;
			//expunge the kernel accessions, so they are not available for random addition below
			//KernelAccessionIndex has been reverse sorted so you don't go outside range after automatic resize by .erase
			for (unsigned int i=0;i<KernelAccessionIndex.size();i++)
			{
				b = KernelAccessionIndex[i];
				TempList.erase(TempList.begin()+b);
			}
		
			//randomly add accessions until r accessions are in the core. if there is a kernel, include those (done above)
			//plus additional, randomly selected accessions, until you get r accessions
			for (unsigned int i=KernelAccessionIndex.size();i<r;i++)
			{
				//choose an accession randomly from those available
				RandAcc = rand() % TempList.size();
				//add it to the list
				AccessionsInCore[i] = TempList[RandAcc];
			
				//remove it from the list of available accessions
				TempList.erase(TempList.begin()+RandAcc);
			}
	
			//assemble genotypes for random core and calculate diversity
			//1. put together initial list of active alleles
			CoreAlleles.clear();
			CoreAlleles.resize( AccessionsInCore.size() );
			for (unsigned int i=0;i<AccessionsInCore.size();i++)
			{
				b = AccessionsInCore[i];
				CoreAlleles[i] = ActiveAlleleByPopList[b];
			}

			//2. calculate diversity from random selection at active loci
			AlleleList.clear();
			AlleleList = CoreAlleles;
	
			MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
			//in MyCalculateDiversity, latter two variables are updated as references
			//save them away in non-updated variables
			StartingRandomActiveDiversity = RandomActiveDiversity;
			StartingAltRandomActiveDiversity = AltRandomActiveDiversity;

			//3. calculate diversity from random selection at target loci
			AlleleList.clear();
			AlleleList.resize( AccessionsInCore.size() );
			for (unsigned int j=0;j<AccessionsInCore.size();j++)
			{
				b = AccessionsInCore[j];
				AlleleList[j] = TargetAlleleByPopList[b];
			}
			MyCalculateDiversity(AlleleList, TargetMaxAllelesList, Standardize, RandomTargetDiversity, AltRandomTargetDiversity);


			//BEGIN OPTIMIZATION
			StartingDiversity = 0; //this is the diversity recovered during the prior iteration.
			plateau = 0; //count of the number of times you have found the best value, evaluates when you are
						 //stuck on a plateau, assuming acceptance criterion allows downhill steps
			//this is the iterations step, now an indefinite loop that is broken when 
			//no improvement is made during the course of the optimization algorithm
			//If r = kernel size = MinCoreSize then do no optimization but still calculate all variables.
			if (KernelAccessionIndex.size() == r)
			{
				//assemble genotypes for core
				//1. put together initial list
				CoreAlleles.clear();
				CoreAlleles.resize(r);
				for (unsigned int i=0;i<r;i++)
				{
					b = AccessionsInCore[i];
					CoreAlleles[i] = ActiveAlleleByPopList[b];
				}
				
				AlleleList = CoreAlleles;
				
				MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
				best = RandomActiveDiversity; //best is equivalent to OptimizedActiveDiversity
				AltOptimizedActiveDiversity = AltRandomActiveDiversity;
			}
			else
			{
				//do optimization
				while ( true )
				{
					//assemble genotypes for core
					//1. put together initial list
					CoreAlleles.clear();
					CoreAlleles.resize(r);
					for (unsigned int i=0;i<r;i++)
					{
						b = AccessionsInCore[i];
						CoreAlleles[i] = ActiveAlleleByPopList[b];
					}
		
					//2. go through all possible subsets of size r-1, one at a time, noting which is best.
					//If there is a kernel, do not swap out any of those accessions (they are retained as the
					//first KernelAccessionIndex.size() items in CoreAlleles).  Accomplished by starting for loop
					//at KernelAccessionIndex.size().
					best=0;
					for (unsigned int i=KernelAccessionIndex.size();i<CoreAlleles.size();i++)
					{
						//remove each item consecutively from the list of all populations in the core
						AlleleList.clear();
						TdTempList.clear();
				
						TdTempList = CoreAlleles; //swap to temporary vector
						TdTempList.erase( TdTempList.begin() + i);
						AlleleList = TdTempList;
			
						TempList2.clear();
						TempList2 = AccessionsInCore;
						TempList2.erase(TempList2.begin() + i);
						AccessionsInSubCore = TempList2;

						/*Data structure for SubCoreAlleles:
						SubCore 1..r
							Population 1..(r-1)
								AlleleArray 1..NumLoci		
			
						--3. fuse alleles from the same locus into a single array, for all accessions, for the current subcore
						--4. assemble a list of diversity (M) for each locus separately
						--5. standardize the M values to the maximum possible number of alleles at that locus, and add them up to get final estimate of standardized allelic diversity in the core.  then divide by the number of loci to get a number that is comparable across data sets.
						--5.5. simultaneous to the calculation, keep track of which subcore is best
						*/
			
						MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
						nnew = RandomActiveDiversity;

						if (nnew >= best) // >= allows sideways movement during hill climbing
						{
							best = nnew;

							BestSubCore.clear();
							BestSubCore = AccessionsInSubCore;
							BestSubCoreAlleles.clear();
							BestSubCoreAlleles = AlleleList;
						}
					}  //for loop cycles thru all subcores

					//reverse sort BestSubCore to support easy assembly of pared TempList below
					BestSubCoreRevSorted = BestSubCore;
					std::sort(BestSubCoreRevSorted.begin(), BestSubCoreRevSorted.end(), std::greater<int>());
	
					/*
					6. take the subcore with greatest diversity and consecutively add each 
					possible additional accession from the base collection.  find the core of size r 
					(not r-1 subcore) that has the greatest diversity.

					suppress the IDs of those accessions found in the BestSubCore from the 
					list of all accessions to get a list of remaining accessions.*/
					TempList = AccessionNameList;
					for (unsigned int k=0;k<BestSubCoreRevSorted.size();k++)
					{
						bsc = BestSubCoreRevSorted[k];
						TempList.erase( TempList.begin() + bsc );
					}
			
					//shuffle the list of remaining accessions, so addition order is not predictable
					std::random_shuffle (TempList.begin(), TempList.end());
				
					//add each remaining accession consecutively, calculate diversity, test 
					//whether it is better than the prior one
					best = 0;
					for (unsigned int k=0;k<TempList.size();k++)
					{
						bsc = TempList[k];
			
						//define the core
						TempList2 = BestSubCore;
						TempList2.resize( TempList2.size() + 1 );
						//TempList2.push_back(i);
						TempList2[TempList2.size()-1] = bsc; //add new accession to last vector element
						AccessionsInCore = TempList2;
			
						//assemble the allelelist for the core
						TdTempList = BestSubCoreAlleles;
						TdTempList.resize( TdTempList.size() + 1 );
						//TdTempList.push_back( ActiveAlleleByPopList[i] );
						TdTempList[TdTempList.size()-1] = ActiveAlleleByPopList[bsc];
						AlleleList = TdTempList;
			
						//calculate diversity
						MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, nnew, TempAltOptimizedActiveDiversity); 
		
						//test whether current diversity is higher than the best diversity found so far
						if (nnew >= best) // >= allows sideways movement during hill climbing
						{
							best = nnew;
							bestcore = AccessionsInCore;
							//save the alternative diversity value for the best core
							AltOptimizedActiveDiversity = TempAltOptimizedActiveDiversity;
						}
					}

					AccessionsInCore = bestcore; //define starting variable for next MSTRAT iteration
		
					//if there has been no improvement from the prior iteration, you have reached
					// the plateau and should exit the repeat
					if (best == StartingDiversity) 
					{
						plateau++;
						if (plateau > 0) break;
					}
					//update starting value and repeat
					else if (best > StartingDiversity) StartingDiversity = best;
				
				} //while(true) endless loop
			}

			//7. Calculate diversity at target loci
			//assemble the target loci allelelist for the accessions in the best core
			AlleleList.clear();
			AlleleList.resize( AccessionsInCore.size() );
			for (unsigned int j=0;j<AccessionsInCore.size();j++)
			{
				b = AccessionsInCore[j];
				AlleleList[j] = TargetAlleleByPopList[b];
			}
	
			//calculate diversity at target loci based upon the optimized core selection
			MyCalculateDiversity(AlleleList, TargetMaxAllelesList, Standardize, OptimizedTargetDiversity, AltOptimizedTargetDiversity);

			//8. Assemble stats for optimized core and add to output vectors
			//create a list of accession names from the list of accession ID's in AccessionsInCore
			sort( AccessionsInCore.begin(), AccessionsInCore.end() );
			
			TempListStr.clear();
			TempListStr.resize(r);
			for (unsigned int i=0;i<AccessionsInCore.size();i++)
			{
				b = AccessionsInCore[i];
				TempListStr[i] = FullAccessionNameList[b];
			}

			/***MPI: BUILD & SEND RESULTS VECTOR***/
			//load the variables onto the results vectors
			
			//no need to calculate row number, it is the same as rnr, formula saved because it might be useful later
			//row = ((r - MinCoreSize)*NumReplicates) + nr - ( (NumReplicates*(SamplingFreq-1))*( (r-MinCoreSize)/SamplingFreq ) );
			// (r - MinCoreSize)*NumReplicates) + nr specifies row number if SamplingFreq=1
			// (NumReplicates*(SamplingFreq-1)) specifies a step value to correct when SamplingFreq>1
			// ( (r-MinCoreSize)/SamplingFreq ) specifies the replicate on core size, accounting for SamplingFreq
			// see file Calculation of row value.xlsx for development of the 'row' index
			
			//put results 0-8 into a vector, resvec, return row as last item
			vector<double> resvec(10);

			resvec[0] = double(r);
			resvec[1] = StartingRandomActiveDiversity;//RandomActiveDiversity;
			resvec[2] = best; //equivalent to OptimizedActiveDiversity
			resvec[3] = RandomTargetDiversity;
			resvec[4] = OptimizedTargetDiversity;
			resvec[5] = StartingAltRandomActiveDiversity;//AltRandomActiveDiversity;
			resvec[6] = AltOptimizedActiveDiversity;
			resvec[7] = AltRandomTargetDiversity;
			resvec[8] = AltOptimizedTargetDiversity;
			resvec[9] = double(rnr);
			
			
			//cout<<"MPI_Rank="<<MPI_Rank<<" 
			
			
			//send result vector to master 0, send row number, rnr, as last element.
			//message is tagged as 0
			//here you are pointing to the first element, then returning resvec.size() doubles-
			//worth of memory from that starting location.
			MPI_Send(&resvec[0], resvec.size(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
			/***MPI: END BUILD & SEND RESULTS VECTOR***/


			/***MPI: BUILD & SEND MEMBERS VECTOR***/
			//add row number as last item in TempListStr
			TempListStr.resize(TempListStr.size()+1);
			stringstream ss;
			ss << rnr;	//convert int to stringstream to string			
			TempListStr[ TempListStr.size() - 1 ] = ss.str();
		
			//convert vector<string> to a single, ',<!>,' delimited, string
			string concat;
			for (unsigned int i=0;i<TempListStr.size();++i)
			{
				concat += TempListStr[i]; //add vector element
				if (i<TempListStr.size()-1) concat += ",<!>,"; //add delimiter, except for last item
			}
			//convert the string to a char array
			char cc[concat.size()+1];
			strcpy(cc, concat.c_str());
			
			//send the char array to master0 tagged as 1
			//tagged as 1 to distinguish from result vector send
			MPI_Send(&cc, sizeof(cc), MPI_CHAR, 0, 1, MPI_COMM_WORLD);

		} //end for loop over rows
	} //***MPI:  END SEND
	

	/*MPI: MASTER 0 WRITES OUTPUT*/
	if ( procid == 0 )
	{
		//set up file stream for output file
		ofstream output; 
		output.open(OutFilePath);
		output.close(); //quick open close done to clear any existing file each time program is run
		output.open(OutFilePath, ios::out | ios::app); //open file in append mode
		output << "core size	random reference diversity	optimized reference diversity	random target diversity	optimized target diversity	alt random reference diversity	alt optimized reference diversity	alt random target diversity	alt optimized target diversity	core members" << "\n";
		
		//write out results row by row
		for (int i=0;i<V1;i++)
		{
			//write variables
			output 	<< Results[i][0] 
					<< "	" << Results[i][1] 
					<< "	" << Results[i][2] 
					<< "	" << Results[i][3] 
					<< "	" << Results[i][4] 
					<< "	" << Results[i][5] 
					<< "	" << Results[i][6] 
					<< "	" << Results[i][7] 
					<< "	" << Results[i][8] 
					<< "	" << "(";
			//write Accessions retained
			for (unsigned int j=0;j<Members[i].size();j++)
			{
				if ( j==(Members[i].size() - 1) )
				{
					//add trailing parentheses and move to next row
					output << Members[i][j] << ")\n";
				}
				else
				{
					output << Members[i][j] << ",";
				}
			}
		}
	
		//wrap up write step
		output.close();
	} /***MPI: END MASTER WRITE***/
	
	//Terminate MPI.
	//MPI::Finalize ( );

}
示例#19
0
文件: mygz2.C 项目: Halfnhav4/okws
int 
main (int argc, char *argv[])
{
  setprogname (argv[0]);
  if (argc != 2)
    usage ();
  str s = file2str (argv[1]);

  if (!s)
    fatal << "cannot open file: " << argv[1];

  u_int niter = 10;
  u_int osz = 0;
  u_int32_t tot = 0;
  mstr *outbuf = NULL;

  u_int slen = s.len ();
  u_int out_avail = u_int ((slen / 1000) * 1001) + 16;

  for (u_int i = 0; i < niter; i++) {

    if (outbuf)
      delete outbuf;
    outbuf = New mstr (out_avail);

    warn << "+ starting compression\n";
    startt ();
    osz = go (s, outbuf, out_avail); 
    u_int t = stopt ();
    warn << "- ending compression (time=" << t << ")\n";
    tot += t;
    
  }

  outbuf->setlen (osz);

  //
  // write out the buffer once, just to make sure we were getting reasonable
  // data output (and not some bullshit)
  //
  u_int i = 0;
  do {
    int rc = write (1, outbuf->cstr () + i, min<u_int> (2048, osz - i));
    if (rc < 0)
      panic ("write error!\n");
    i += rc;
  } while (i < osz);

  u_int64_t bw = osz / 1024;
  bw *= 1000000;
  bw /= tot;
  bw *= niter;


  warn ("Input: %d bytes\n"
	"Output: %d bytes\n"
	"Iterations: %d\n"
	"Usecs Total: %d\n"
	"Compression ratio * 1000: %d\n"
	"Throughput (kB/sec): %d\n",
	slen, osz, niter, tot, osz * 1000 / slen, u_int32_t (bw));

}
示例#20
0
static int cs_value(MY_XML_PARSER *st,const char *attr, uint len)
{
  struct my_cs_file_info *i= (struct my_cs_file_info *)st->user_data;
  struct my_cs_file_section_st *s;
  int    state= (int)((s=cs_file_sec(st->attr, (int) strlen(st->attr))) ? s->state : 0);
  
  switch (state) {
  case _CS_ID:
    i->cs.number= strtol(attr,(char**)NULL,10);
    break;
  case _CS_BINARY_ID:
    i->cs.binary_number= strtol(attr,(char**)NULL,10);
    break;
  case _CS_PRIMARY_ID:
    i->cs.primary_number= strtol(attr,(char**)NULL,10);
    break;
  case _CS_COLNAME:
    i->cs.name=mstr(i->name,attr,len,MY_CS_NAME_SIZE-1);
    break;
  case _CS_CSNAME:
    i->cs.csname=mstr(i->csname,attr,len,MY_CS_NAME_SIZE-1);
    break;
  case _CS_CSDESCRIPT:
    i->cs.comment=mstr(i->comment,attr,len,MY_CS_CSDESCR_SIZE-1);
    break;
  case _CS_FLAG:
    if (!strncmp("primary",attr,len))
      i->cs.state|= MY_CS_PRIMARY;
    else if (!strncmp("binary",attr,len))
      i->cs.state|= MY_CS_BINSORT;
    else if (!strncmp("compiled",attr,len))
      i->cs.state|= MY_CS_COMPILED;
    break;
  case _CS_UPPERMAP:
    fill_uchar(i->to_upper,MY_CS_TO_UPPER_TABLE_SIZE,attr,len);
    i->cs.to_upper=i->to_upper;
    break;
  case _CS_LOWERMAP:
    fill_uchar(i->to_lower,MY_CS_TO_LOWER_TABLE_SIZE,attr,len);
    i->cs.to_lower=i->to_lower;
    break;
  case _CS_UNIMAP:
    fill_uint16(i->tab_to_uni,MY_CS_TO_UNI_TABLE_SIZE,attr,len);
    i->cs.tab_to_uni=i->tab_to_uni;
    break;
  case _CS_COLLMAP:
    fill_uchar(i->sort_order,MY_CS_SORT_ORDER_TABLE_SIZE,attr,len);
    i->cs.sort_order=i->sort_order;
    break;
  case _CS_CTYPEMAP:
    fill_uchar(i->ctype,MY_CS_CTYPE_TABLE_SIZE,attr,len);
    i->cs.ctype=i->ctype;
    break;
  case _CS_RESET:
  case _CS_DIFF1:
  case _CS_DIFF2:
  case _CS_DIFF3:
    {
      /*
        Convert collation description from
        Locale Data Markup Language (LDML)
        into ICU Collation Customization expression.
      */
      char arg[16];
      const char *cmd[]= {"&","<","<<","<<<"};
      i->cs.tailoring= i->tailoring;
      mstr(arg,attr,len,sizeof(arg)-1);
      if (i->tailoring_length + 20 < sizeof(i->tailoring))
      {
        char *dst= i->tailoring_length + i->tailoring;
        i->tailoring_length+= sprintf(dst," %s %s",cmd[state-_CS_RESET],arg);
      }
    }
  }
  return MY_XML_OK;
}
示例#21
0
文件: pub3msgpack.C 项目: dbc60/okws
pub3::msgpack::outbuf_t::outbuf_t ()
  : _tlen (0x100),
    _tmp (New mstr (_tlen)), 
    _tp (_tmp->cstr ()), 
    _ep (_tp + _tlen) {}
示例#22
0
bool LLMimeParser::parseIndex(const U8* buffer, S32 length, LLMimeIndex& index)
{
	LLMemoryStream mstr(buffer, length);
	return parseIndex(mstr, length + 1, index);
}