Example #1
0
static void BenchDir(TCHAR *dir)
{
    StrVec files;
    ScopedMem<TCHAR> pattern(str::Format(_T("%s\\*.pdf"), dir));
    CollectPathsFromDirectory(pattern, files, false);
    for (size_t i = 0; i < files.Count(); i++) {
        BenchFile(files.At(i), NULL);
    }
}
Example #2
0
bool operator==(const StrVec &lhs, const StrVec &rhs)
{
	if (lhs.size() != rhs.size())
		return false;
	for (auto pl = lhs.begin(), pr = rhs.begin(); pl != lhs.end(); )
		if (*pl != *pr)
			return false;
	return true;
}
Example #3
0
 bool match(const PackInfo &other) const
 {
   if(other.dirs.size() != dirs.size()) return false;
   assert(dirs.size() == paths.size());
   assert(dirs.size() == other.paths.size());
   for(int i=0; i<dirs.size(); i++)
     if(dirs[i] != other.dirs[i] || paths[i] != other.paths[i])
       return false;
   return true;
 }
Example #4
0
int main()
{
	StrVec str;
	str.push_back("adf");
	str.push_back("sdfd");
	for (auto i = str.begin(); i != str.end(); ++i)
		cout << *i << ends;
	cout << endl;
	return 0;
}
Example #5
0
StrVec getVec(std::istream &is)
{
    StrVec svec;
    std::string s;

    while (is >> s)
        svec.push_back(s);

    // this is where move is necessary
    return svec;
}
Example #6
0
int ImageDirEngineImpl::GetPageByLabel(const TCHAR *label)
{
    for (size_t i = 0; i < pageFileNames.Count(); i++) {
        const TCHAR *fileName = path::GetBaseName(pageFileNames.At(i));
        const TCHAR *fileExt = path::GetExt(fileName);
        if (str::StartsWithI(fileName, label) &&
            (fileName + str::Len(label) == fileExt || fileName[str::Len(label)] == '\0'))
            return (int)i + 1;
    }

    return BaseEngine::GetPageByLabel(label);
}
Example #7
0
StrVec read_lists (const StrVec& fnames)
{
    StrVec rv;
    StrVec::const_iterator itr = fnames.begin ();
    while (itr != fnames.end ())
    {
        StrVec vals = read_list (*itr);
        std::copy (vals.begin (), vals.end (), std::back_inserter (rv));
        itr ++;
    }
    return rv;
}
Example #8
0
std::string make_temp_fname (const char* tmpdir, const char* prefix)
{
    // if directory not passed in, guess one
    std::string tn = temp_dir (tmpdir);;

    // if prefix not passed in, use default
    if (!prefix) prefix = DEFAULT_TEMP_FILE_PREFIX;

    // get temp directory listing
    StrVec dircontent = listdir (tn);

    // find all entries matching prefix and having numeric postfix, get list of numbers
    UintSet postfixes;
    unsigned prefix_len = prefix ? strlen (prefix) : 0;
    for (StrVec::iterator ii = dircontent.begin (); ii != dircontent.end (); ii ++)
    {
        // check if prefix matches
        if (prefix_len && (ii->substr (0, prefix_len) != prefix))
            continue;
        // check if postfix is numeric and get the number
        unsigned number = 0;
        std::string::iterator sitr;
        for (sitr = ii->begin () + prefix_len; sitr != ii->end (); sitr ++)
        {
            number *= 10;
            if (!isdigit (*sitr))
                break;
            else
                number += *sitr - '0';
        }
        if (sitr != ii->end ())
            continue;
        // store number to postfixes set
        postfixes.insert (number);
    }
    // now retrieve the numbers using first gap
    // make a set for quick presence check
    unsigned prev = 0;
    for (UintSet::iterator nitr = postfixes.begin (); nitr != postfixes.end (); nitr ++)
        if (prev + 1 < *nitr)
            break; // found the gap in sequence
        else
            prev = *nitr;
    if (prev == std::numeric_limits<unsigned>::max ()) // just for sanity :)
        ers << "No more temp file names available for prefix " << (prefix ? prefix : "") << " in directory " << tn << Throw;

    // prev + 1 is the right number
    std::ostringstream name (tn, std::ios::out | std::ios::app);
    name << PATH_SEPARATOR;
    if (prefix) name << prefix;
    name << prev + 1;
    return name.str ();
}
Example #9
0
bool StressTest::OpenDir(const TCHAR *dirPath)
{
    assert(filesToOpen.Count() == 0);

    bool hasFiles = CollectStressTestSupportedFilesFromDirectory(dirPath, fileFilter, filesToOpen);
    filesToOpen.SortNatural();

    ScopedMem<TCHAR> pattern(str::Format(_T("%s\\*"), dirPath));
    bool hasSubDirs = CollectPathsFromDirectory(pattern, dirsToVisit, true);

    return hasFiles || hasSubDirs;
}
//! copy constructor
StrVec::StrVec(const StrVec &s)
{
	/**
	* @brief newData is a pair of pointers pointing to newly allocated and copied
	*                  range : [b, e)
	*/
	std::pair<std::string*, std::string*>
		newData = alloc_n_copy(s.begin(), s.end());

	element = newData.first;
	first_free = cap = newData.second;
}
Example #11
0
// Find a record corresponding to the given source file, line number and optionally column number.
// (at the moment the column parameter is ignored)
//
// If there are several *consecutively declared* records for the same line then they are all returned.
// The list of records is added to the vector 'records'
//
// If there is no record for that line, the record corresponding to the nearest line is selected
// (within a range of EPSILON_LINE)
//
// The function returns PDFSYNCERR_SUCCESS if a matching record was found.
UINT Pdfsync::SourceToRecord(const TCHAR* srcfilename, UINT line, UINT col, Vec<size_t> &records)
{
    if (!srcfilename)
        return PDFSYNCERR_INVALID_ARGUMENT;

    ScopedMem<TCHAR> srcfilepath;
    // convert the source file to an absolute path
    if (PathIsRelative(srcfilename))
        srcfilepath.Set(PrependDir(srcfilename));
    else
        srcfilepath.Set(str::Dup(srcfilename));
    if (!srcfilepath)
        return PDFSYNCERR_OUTOFMEMORY;

    // find the source file entry
    size_t isrc;
    for (isrc = 0; isrc < srcfiles.Count(); isrc++)
        if (path::IsSame(srcfilepath, srcfiles.At(isrc)))
            break;
    if (isrc == srcfiles.Count())
        return PDFSYNCERR_UNKNOWN_SOURCEFILE;

    if (fileIndex.At(isrc).start == fileIndex.At(isrc).end)
        return PDFSYNCERR_NORECORD_IN_SOURCEFILE; // there is not any record declaration for that particular source file

    // look for sections belonging to the specified file
    // starting with the first section that is declared within the scope of the file.
    UINT min_distance = EPSILON_LINE; // distance to the closest record
    size_t lineIx = (size_t)-1; // closest record-line index

    for (size_t isec = fileIndex.At(isrc).start; isec < fileIndex.At(isrc).end; isec++) {
        // does this section belong to the desired file?
        if (lines.At(isec).file != isrc)
            continue;

        UINT d = abs((int)lines.At(isec).line - (int)line);
        if (d < min_distance) {
            min_distance = d;
            lineIx = isec;
            if (0 == d)
                break; // We have found a record for the requested line!
        }
    }
    if (lineIx == (size_t)-1)
        return PDFSYNCERR_NORECORD_FOR_THATLINE;

    // we read all the consecutive records until we reach a record belonging to another line
    for (size_t i = lineIx; i < lines.Count() && lines.At(i).line == lines.At(lineIx).line; i++)
        records.Push(lines.At(i).record);

    return PDFSYNCERR_SUCCESS;
}
Example #12
0
bool operator< (const StrVec & s1,const StrVec &s2)
{
	for(size_t i =0 ; i< s1.size() && i < s2.size(); i++)
	{
		if(*(s1.elements+i ) < *(s2.elements+i) )
			return true ;
		else if(*(s1.elements+i ) < *(s2.elements+i) )
			return false;
	}
	if(s1.size() < s2.size())
		return true ;	
	return false;
}
Example #13
0
bool operator==(const StrVec &s1 ,const StrVec &s2)
{
	if(s1.size() == s2.size())
	{
		for(size_t i =0 ; i< s1.size() ; i++)
		{
			if(*(s1.elements+i ) != *(s2.elements+i) )
				return false ;
		}	
		return true;
	}
	return false ;
}
Example #14
0
void CopySelectionToClipboard(WindowInfo *win)
{
    if (!win->selectionOnPage) return;
    CrashIf(win->selectionOnPage->Count() == 0);
    if (win->selectionOnPage->Count() == 0) return;
    CrashIf(!win->dm || !win->dm->engine);
    if (!win->dm || !win->dm->engine) return;

    if (!OpenClipboard(NULL)) return;
    EmptyClipboard();

    if (!win->dm->engine->IsCopyingTextAllowed())
        ShowNotification(win, _TR("Copying text was denied (copying as image only)"));
    else if (!win->dm->engine->IsImageCollection()) {
        ScopedMem<TCHAR> selText;
        bool isTextSelection = win->dm->textSelection->result.len > 0;
        if (isTextSelection) {
            selText.Set(win->dm->textSelection->ExtractText(_T("\r\n")));
        }
        else {
            StrVec selections;
            for (size_t i = 0; i < win->selectionOnPage->Count(); i++) {
                SelectionOnPage *selOnPage = &win->selectionOnPage->At(i);
                TCHAR *text = win->dm->GetTextInRegion(selOnPage->pageNo, selOnPage->rect);
                if (text)
                    selections.Push(text);
            }
            selText.Set(selections.Join());
        }

        // don't copy empty text
        if (!str::IsEmpty(selText.Get()))
            CopyTextToClipboard(selText, true);

        if (isTextSelection) {
            // don't also copy the first line of a text selection as an image
            CloseClipboard();
            return;
        }
    }

    /* also copy a screenshot of the current selection to the clipboard */
    SelectionOnPage *selOnPage = &win->selectionOnPage->At(0);
    RenderedBitmap * bmp = win->dm->engine->RenderBitmap(selOnPage->pageNo,
        win->dm->ZoomReal(), win->dm->Rotation(), &selOnPage->rect, Target_Export);
    if (bmp)
        CopyImageToClipboard(bmp->GetBitmap(), true);
    delete bmp;

    CloseClipboard();
}
Example #15
0
string trimmedName(string& s)
{
    //printf("splitting %s\n",s.c_str());
    StrVec vec;
    int n=strsplit_slash(s, vec);

    //for(int i=0;i<n;i++) printf("  '%s'\n",vec[i].c_str());

    unsigned int i=0;
    while(i<vec.size())
    {
        if(i>0)
        {
            if(vec[i]==".." && vec[i-1]!="..")
            {
                i--;
                vec.erase(vec.begin()+i,vec.begin()+i+2);
                continue;
            }
        }

        i++;
    }
    if(!vec.size()) return "";
    string ret="";
    for(unsigned int i=0; i<vec.size(); i++)
    {
        ret+=vec[i];
        if(i+1!=vec.size()) ret+="/";
    }
    return ret;
}
Example #16
0
	void append(const std::string& word)
	{
		std::string lower;
		cybozu::ToLower(lower, word);
		std::pair<Str2Int::iterator, bool> ret = word2id_.insert(Str2Int::value_type(lower, (int)id2word_.size()));
//printf("word=%s, id=%d, ret=%d\n", ret.first->first.c_str(), ret.first->second, ret.second);
		if (ret.second) {
			id2word_.push_back(lower);
			df_.resize(id2word_.size());
		}
		if (set_.insert(word).second) {
			df_[ret.first->second]++;
		}
	}
Example #17
0
static bool SetupPluginMode(CommandLineInfo& i)
{
    if (!IsWindow(i.hwndPluginParent) || i.fileNames.Count() == 0)
        return false;

    gPluginURL = i.pluginURL;
    if (!gPluginURL)
        gPluginURL = i.fileNames.At(0);

    assert(i.fileNames.Count() == 1);
    while (i.fileNames.Count() > 1) {
        free(i.fileNames.Pop());
    }
    i.reuseInstance = i.exitOnPrint = false;
    // always display the toolbar when embedded (as there's no menubar in that case)
    gGlobalPrefs.toolbarVisible = true;
    // never allow esc as a shortcut to quit
    gGlobalPrefs.escToExit = false;
    // never show the sidebar by default
    gGlobalPrefs.tocVisible = false;
    if (DM_AUTOMATIC == gGlobalPrefs.defaultDisplayMode) {
        // if the user hasn't changed the default display mode,
        // display documents as single page/continuous/fit width
        // (similar to Adobe Reader, Google Chrome and how browsers display HTML)
        gGlobalPrefs.defaultDisplayMode = DM_CONTINUOUS;
        gGlobalPrefs.defaultZoom = ZOOM_FIT_WIDTH;
    }

    // extract some command line arguments from the URL's hash fragment where available
    // see http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf#nameddest=G4.1501531
    if (i.pluginURL && str::FindChar(i.pluginURL, '#')) {
        ScopedMem<TCHAR> args(str::Dup(str::FindChar(i.pluginURL, '#') + 1));
        str::TransChars(args, _T("#"), _T("&"));
        StrVec parts;
        parts.Split(args, _T("&"), true);
        for (size_t k = 0; k < parts.Count(); k++) {
            TCHAR *part = parts.At(k);
            int pageNo;
            if (str::StartsWithI(part, _T("page=")) && str::Parse(part + 4, _T("=%d%$"), &pageNo))
                i.pageNumber = pageNo;
            else if (str::StartsWithI(part, _T("nameddest=")) && part[10])
                str::ReplacePtr(&i.destName, part + 10);
            else if (!str::FindChar(part, '=') && part[0])
                str::ReplacePtr(&i.destName, part);
        }
    }

    return true;
}
Example #18
0
static StrVec
conn_get_table_list (dbi_conn conn, const std::string& dbname,
                     const std::string& table)
{
    StrVec retval;
    const char* tableptr = (table.empty() ? nullptr : table.c_str());
    auto tables = dbi_conn_get_table_list (conn, dbname.c_str(), tableptr);
    while (dbi_result_next_row (tables) != 0)
    {
        std::string table_name {dbi_result_get_string_idx (tables, 1)};
        retval.push_back(table_name);
    }
    dbi_result_free (tables);
    return retval;
}
Example #19
0
int main() {
    StrVec words;
    words.push_back("ss");
    words.push_back("sb");
    words.push_back("asf");
    words.push_back("safasfd");
    words.push_back("asfas");
    std::cout<<words.size()<<std::endl;
    //words = StrVec();
    //words = words;
    std::cout<<"cap "<<words.capacity()<<std::endl;
    std::cout<<"sz "<<words.size()<<std::endl;
    for_each(words.begin(), words.end(), [](const std::string &s){std::cout<<s<<std::endl;});
    std::cout<<"exit"<<std::endl;
}
Example #20
0
int strsplit_slash(string& st, StrVec& vec)
{
    vec.clear();
    int last_pos=0;
    int pos=0;
    int max_pos=st.size();
    while(pos<max_pos)
    {
        last_pos=pos;
        while(st[pos]!='/' && pos<max_pos) pos++;
        vec.push_back(st.substr(last_pos,pos-last_pos));
        while(st[pos]=='/' && pos<max_pos) pos++;
    }
    return vec.size();
}
Example #21
0
	Option(int argc, const char *const argv[])
	{
		cybozu::Option opt;
		std::string charSetFile;
		std::string dicFile;
		bool debug;
		opt.appendOpt(&charSetFile, "", "cf", "char set file");
		opt.appendOpt(&threadNum, 4, "t", "thread num");
		opt.appendOpt(&dicFile, "", "d", "dictionary file");
		opt.appendOpt(&passLen, 0, "l", "length of pass");
		opt.appendBoolOpt(&debug, "v", "verbose message");
		opt.appendHelp("h");
		opt.appendParam(&encFile, "encrypted file");
		if (!opt.parse(argc, argv)) {
			opt.usage();
			exit(1);
		}
		if (debug) ms::setDebug(1);
		if (charSetFile.empty()) {
			charSet = "abcdefghijklmnopqrstuvwxyz"
			          "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
					  "0123456789-_";
		} else {
			std::ifstream ifs(charSetFile.c_str(), std::ios::binary);
			if (!std::getline(ifs, charSet)) {
				fprintf(stderr, "can't read char set file [%s]\n", charSetFile.c_str());
				exit(1);
			}
			trim(charSet);
		}
		if (!dicFile.empty()) {
			std::ifstream ifs(dicFile.c_str(), std::ios::binary);
			std::string line;
			while (std::getline(ifs, line)) {
				trim(line);
				toUtf8(line);
				passSet.push_back(line);
			}
			if (passSet.empty()) {
				fprintf(stderr, "can't read dicFile [%s]\n", dicFile.c_str());
				exit(1);
			}
			std::sort(passSet.begin(), passSet.end(), &lessByLength);
		}
		if (ms::isDebug()) {
			opt.put();
		}
	}
Example #22
0
StrVec split_path (const char* path)
{
    StrVec rv;
    std::string pstr = path;
    std::string::size_type pos, ppos = 0;
    while ((pos = pstr.find (PATH_SEPARATOR, ppos)) != std::string::npos)
    {
        if (pos != ppos || ppos == 0)
            rv.push_back (pstr.substr (ppos, pos - ppos));
        ppos = pos + 1;
    }
    if (ppos < pstr.length ())
        rv.push_back (pstr.substr (ppos, pstr.length () - ppos));

    return rv;
}
Example #23
0
int main(int argc, char const *argv[])
{
	StrVec svec1;
	std::ifstream ifs("in.txt");
	std::istream_iterator<std::string> beg(ifs), end;
	std::vector<std::string> src(beg, end);
	for (auto& s : src)
	{
		svec1.push_back(s);
	}
	svec1.resize(10, "illidan");
	StrVec svec = { "a", "b", "c", "d", "e" };
	display(svec);
	std::cout << svec.size() << std::endl;
	return 0;
}
Example #24
0
StrMap RedisClient::HMGet(const std::string& key, const StrVec& vec){
    StrMap map;
    if( key.empty() || vec.empty()) {
        return map;
    }
    std::stringstream sm;
    sm << "HMGET " << key;
    for(auto & i : vec) {
        sm << " " << i;
    }
    redisReply *redis_reply = RedoCommand(sm.str(),REDIS_REPLY_ARRAY);
    if( redis_reply ) {
        for (size_t i=0; i<redis_reply->elements; ++i) {
            auto reply = redis_reply->element[i];
            if (reply->type == REDIS_REPLY_STRING) {
                map[vec[i]] = redis_reply->element[i]->str;
            }
            else if (reply->type == REDIS_REPLY_NIL) {
                LOGW("HMGet element" << vec[i] <<" is REDIS_REPLY_NIL! command=");
                map[vec[i]] ="";
            }
        }
    }
    freeReplyObject_Safe(redis_reply);
    return map;
}
Example #25
0
int Pdfsync::DocToSource(UINT pageNo, PointI pt, ScopedMem<TCHAR>& filename, UINT *line, UINT *col)
{
    if (IsIndexDiscarded())
        if (RebuildIndex() != PDFSYNCERR_SUCCESS)
            return PDFSYNCERR_SYNCFILE_CANNOT_BE_OPENED;

    // find the entry in the index corresponding to this page
    if (pageNo <= 0 || pageNo >= sheetIndex.Count() || pageNo > (UINT)engine->PageCount())
        return PDFSYNCERR_INVALID_PAGE_NUMBER;

    // PdfSync coordinates are y-inversed
    RectI mbox = engine->PageMediabox(pageNo).Round();
    pt.y = mbox.dy - pt.y;

    // distance to the closest pdf location (in the range <PDFSYNC_EPSILON_SQUARE)
    UINT closest_xydist = UINT_MAX;
    UINT selected_record = UINT_MAX;
    // If no record is found within a distance^2 of PDFSYNC_EPSILON_SQUARE
    // (selected_record == -1) then we pick up the record that is closest
    // vertically to the hit-point.
    UINT closest_ydist = UINT_MAX; // vertical distance between the hit point and the vertically-closest record
    UINT closest_xdist = UINT_MAX; // horizontal distance between the hit point and the vertically-closest record
    UINT closest_ydist_record = UINT_MAX; // vertically-closest record

    // read all the sections of 'p' declarations for this pdf sheet
    for (size_t i = sheetIndex.At(pageNo); i < points.Count() && points.At(i).page == pageNo; i++) {
        // check whether it is closer than the closest point found so far
        UINT dx = abs(pt.x - (int)SYNC_TO_PDF_COORDINATE(points.At(i).x));
        UINT dy = abs(pt.y - (int)SYNC_TO_PDF_COORDINATE(points.At(i).y));
        UINT dist = dx * dx + dy * dy;
        if (dist < PDFSYNC_EPSILON_SQUARE && dist < closest_xydist) {
            selected_record = points.At(i).record;
            closest_xydist = dist;
        }
        else if ((closest_xydist == UINT_MAX) && dy < PDFSYNC_EPSILON_Y &&
                 (dy < closest_ydist || (dy == closest_ydist && dx < closest_xdist))) {
            closest_ydist_record = points.At(i).record;
            closest_ydist = dy;
            closest_xdist = dx;
        }
    }

    if (selected_record == UINT_MAX)
        selected_record = closest_ydist_record;
    if (selected_record == UINT_MAX)
        return PDFSYNCERR_NO_SYNC_AT_LOCATION; // no record was found close enough to the hit point

    // We have a record number, we need to find its declaration ('l ...') in the syncfile
    PdfsyncLine cmp; cmp.record = selected_record;
    PdfsyncLine *found = (PdfsyncLine *)bsearch(&cmp, lines.LendData(), lines.Count(), sizeof(PdfsyncLine), cmpLineRecords);
    assert(found);
    if (!found)
        return PDFSYNCERR_NO_SYNC_AT_LOCATION;

    filename.Set(str::Dup(srcfiles.At(found->file)));
    *line = found->line;
    *col = found->column;

    return PDFSYNCERR_SUCCESS;
}
Example #26
0
void BenchFileOrDir(StrVec& pathsToBench)
{
    gLog = new slog::StderrLogger();

    size_t n = pathsToBench.Count() / 2;
    for (size_t i = 0; i < n; i++) {
        TCHAR *path = pathsToBench.At(2 * i);
        if (file::Exists(path))
            BenchFile(path, pathsToBench.At(2 * i + 1));
        else if (dir::Exists(path))
            BenchDir(path);
        else
            logbench("Error: file or dir %s doesn't exist", path);
    }

    delete gLog;
}
Example #27
0
TCHAR *ImageDirEngineImpl::GetPageLabel(int pageNo)
{
    if (pageNo < 1 || PageCount() < pageNo)
        return BaseEngine::GetPageLabel(pageNo);

    const TCHAR *fileName = path::GetBaseName(pageFileNames.At(pageNo - 1));
    return str::DupN(fileName, path::GetExt(fileName) - fileName);
}
Example #28
0
bool StressTest::GoToNextFile()
{
    for (;;) {
        while (filesToOpen.Count() > 0) {
            // test next file
            ScopedMem<TCHAR> path(filesToOpen.At(0));
            filesToOpen.RemoveAt(0);
            if (!IsInRange(fileRanges, ++fileIndex))
                continue;
            if (OpenFile(path))
                return true;
        }

        if (dirsToVisit.Count() > 0) {
            // test next directory
            ScopedMem<TCHAR> path(dirsToVisit.At(0));
            dirsToVisit.RemoveAt(0);
            OpenDir(path);
            continue;
        }

        if (--cycles <= 0)
            return false;
        // start next cycle
        if (file::Exists(basePath))
            filesToOpen.Append(str::Dup(basePath));
        else
            OpenDir(basePath);
    }
}
Example #29
0
StrVec read_list (const char* fname)
{
    StrVec rv;
    LineReader rd (fname);
    char *l, *lc;
    while ((l = rd.nextLine ()))
    {
        // find first token and add to rv
        while (*l && isspace (*l)) l ++;
        if (!*l) continue;
        lc = l + 1;
        while (*lc && !isspace (*lc)) lc ++;
        *lc = 0;
        rv.push_back (l);
    }
    rd.close ();
    return rv;
}
Example #30
0
File: SLData.cpp Project: clagv/sl
 size_t Data::newEntry(const std::string& key, const SLStore& dv)
 {
     KeyIdx ki(key, m_keyIdx.size());
     KeyIdxVec::iterator it = std::upper_bound(m_keyIdx.begin(), m_keyIdx.end(), ki, key_less);
     m_keys.push_back(key);
     m_varData.push_back(dv);
     m_keyIdx.insert(it, ki);
     return ki.second;
 }