<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2010.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
 */
/*! \file DynamicalSystemsSet.hpp
Set of SP::DynamicalSystem
*/
#ifndef DSSET_H
#define DSSET_H

#include "DynamicalSystem.hpp"
#include "SiconosSet.hpp"

#include <boost/shared_ptr.hpp>

/** DEPRECATED : A set of pointers to dynamical systems, sorted in a growing order
    according to their numbers */
class DynamicalSystemsSet : public std::vector<SP::DynamicalSystem>
{
public:
  typedef std::vector<SP::DynamicalSystem>::iterator iterator;
  typedef std::vector<SP::DynamicalSystem>::const_iterator const_iterator;
  DynamicalSystemsSet() {};

  bool isEmpty() const
  {
    return size() == 0. ;
  };

  SP::DynamicalSystem getPtr(int num) const
  {
    assert(0);
  };

  bool isIn(SP::DynamicalSystem& ds)
  {
    bool find = false;
    for (iterator it = begin(); it != end(); ++it)
    {
      if ((*it)->number() == ds->number())
      {
        find = true;
        break;
      }
    }
    return find;
  };

  bool isIn(int num)
  {
    bool find = false;
    for (iterator it = begin(); it != end(); ++it)
    {
      if ((*it)->number() == num)
      {
        find = true;
        break;
      }
    }
    return find;
  };

  iterator find(int num)
  {
    iterator it;
    for (it = begin(); it != end(); ++it)
    {
      if ((*it)->number() == num)
      {
        break;
      }
    }
    return it;
  };

  void insert(SP::DynamicalSystem s)
  {
    this->push_back(s);
  };

  void insert(iterator begin,
              iterator end)
  {
    for (iterator it = begin; it != end; ++it)
    {
      insert(*it);
    }
  }

  void insert(const_iterator begin,
              const_iterator end)
  {
    for (const_iterator it = begin; it != end; ++it)
    {
      insert(*it);
    }
  }

};

/** Iterator through a set of DS */
typedef DynamicalSystemsSet::iterator DSIterator;

/** const Iterator through a set of DS */
typedef DynamicalSystemsSet::const_iterator ConstDSIterator;

/** return type value for insert function - bool = false if insertion
    failed. */
typedef std::pair<DSIterator, bool> CheckInsertDS;

TYPEDEF_SPTR(DynamicalSystemsSet);

#endif
<commit_msg>getPtr to avoid warnings<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2010.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
 */
/*! \file DynamicalSystemsSet.hpp
Set of SP::DynamicalSystem
*/
#ifndef DSSET_H
#define DSSET_H

#include "DynamicalSystem.hpp"
#include "SiconosSet.hpp"

#include <boost/shared_ptr.hpp>

/** DEPRECATED : A set of pointers to dynamical systems, sorted in a growing order
    according to their numbers */
class DynamicalSystemsSet : public std::vector<SP::DynamicalSystem>
{
public:
  typedef std::vector<SP::DynamicalSystem>::iterator iterator;
  typedef std::vector<SP::DynamicalSystem>::const_iterator const_iterator;
  DynamicalSystemsSet() {};

  bool isEmpty() const
  {
    return size() == 0. ;
  };

  SP::DynamicalSystem getPtr(int num)
  {
    SP::DynamicalSystem ds;
    for (iterator it = begin(); it != end(); ++it)
    {
      if ((*it)->number() == ds->number())
      {
        ds = *it;
        break;
      }
    }
    if (!ds) RuntimeException::selfThrow("getPtr: dynamicalSystem no found");
    return ds;
  };

  bool isIn(SP::DynamicalSystem& ds)
  {
    bool find = false;
    for (iterator it = begin(); it != end(); ++it)
    {
      if ((*it)->number() == ds->number())
      {
        find = true;
        break;
      }
    }
    return find;
  };

  bool isIn(int num)
  {
    bool find = false;
    for (iterator it = begin(); it != end(); ++it)
    {
      if ((*it)->number() == num)
      {
        find = true;
        break;
      }
    }
    return find;
  };

  iterator find(int num)
  {
    iterator it;
    for (it = begin(); it != end(); ++it)
    {
      if ((*it)->number() == num)
      {
        break;
      }
    }
    return it;
  };

  void insert(SP::DynamicalSystem s)
  {
    this->push_back(s);
  };

  void insert(iterator begin,
              iterator end)
  {
    for (iterator it = begin; it != end; ++it)
    {
      insert(*it);
    }
  }

  void insert(const_iterator begin,
              const_iterator end)
  {
    for (const_iterator it = begin; it != end; ++it)
    {
      insert(*it);
    }
  }

};

/** Iterator through a set of DS */
typedef DynamicalSystemsSet::iterator DSIterator;

/** const Iterator through a set of DS */
typedef DynamicalSystemsSet::const_iterator ConstDSIterator;

/** return type value for insert function - bool = false if insertion
    failed. */
typedef std::pair<DSIterator, bool> CheckInsertDS;

TYPEDEF_SPTR(DynamicalSystemsSet);

#endif
<|endoftext|>


<commit_before>/*

This is the global optimization using the tradeoff tables

We decide on parameters for each document based on some constraints on meta data size

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_DOCS 240179

typedef struct
{
    int total;
    int numDistinctFrags;
    int numPostings;
    float wsize;
} linfo;

int comparep(const void* a1, const void* a2)
{
    linfo* l1 = (linfo*)a1;
    linfo* l2 = (linfo*)a2;

    int ret =  l1->numPostings - l2->numPostings;
    int ret2 = l1->total - l2->total;

    if (ret2 == 0)
        return ret;
    else
        return ret2;
}

int main(int argc, char** argv)
{
    linfo* lbuf = new linfo[NUM_DOCS];
    int ptr = 0;
    unsigned* lens = new unsigned[NUM_DOCS];
    memset(lens, 0, NUM_DOCS * sizeof(unsigned));
    char fn[256];
    memset(fn, 0, 256);
    FILE* f2 = fopen("finfos", "wb");
    FILE* f3 = fopen("/data/jhe/wiki_access/numv", "rb");
    int size;
    fread(&size, sizeof(unsigned), 1, f3);
    unsigned* lens2 = new unsigned[size];
    fread(lens2, sizeof(unsigned), size, f3);
    fclose(f3);

    FILE* f4 = fopen("/data/jhe/wiki_access/word_size", "rb");
    unsigned wlens;
    fread(&wlens, sizeof(unsigned), 1, f4);
    unsigned* dlens = new unsigned[wlens];
    fread(dlens, sizeof(unsigned), wlens, f4);
    fclose(f4);
    int wsize = 0;
    FILE* fexcept = fopen("except", "w");

    for (int i = 0; i < atoi(argv[1]); i++)
    {
        memset(fn, 0, 256);
        sprintf(fn, "test/%d.2", i);
        FILE* f1 = fopen(fn, "r");
        ptr = 0;
        printf("processing:%d...", i);
        if (lens2[i] > 1)
        {
            bool change = false;
            while (fscanf(f1, "%f\t%d\t%d\t%d\n", &lbuf[ptr].wsize, &lbuf[ptr].numDistinctFrags,  &lbuf[ptr].total, &lbuf[ptr].numPostings)>0)
            {
                if (ptr > 0 && lbuf[ptr].numPostings != lbuf[ptr-1].numPostings)
                {
                    change = true;
                }
                ptr++;
            }
            fclose(f1);
            memset(fn, 0, 256);
            sprintf(fn, "test/convert-%d", i);
            f1 = fopen(fn, "w");
            qsort(lbuf, ptr, sizeof(linfo), comparep);
            int ptr1 = 0;
            int ptr2 = 1;
            while (ptr2 < ptr)
            {
                while (ptr2 < ptr && lbuf[ptr2].numPostings >= lbuf[ptr1].numPostings)
                    ptr2++;

                if (ptr2 >= ptr)
                    break;

                ptr1++;
                lbuf[ptr1] = lbuf[ptr2];
                ptr2++;
            }
            ptr1++;

            for (int j = 0; j < ptr1; j++)
            {
                fprintf(f1, "%.1f\t%d\t%d\t%d\n", lbuf[j].wsize, lbuf[j].total, lbuf[j].numDistinctFrags, lbuf[j].numPostings);
            }

            fclose(f1);
            fwrite(lbuf, sizeof(linfo), ptr1, f2);
            lens[i] = ptr1;
            if (change == false)
            {
                fprintf(fexcept, "%d\t%d\n", i, ptr);
            }
        }
        else
        {
            fclose(f1);
            lens[i] = 1;
            lbuf[0].wsize = dlens[wsize];
            lbuf[0].total = 1;
            lbuf[0].numDistinctFrags  = 1;
            lbuf[0].numPostings = dlens[wsize];
            fwrite(lbuf, sizeof(linfo), 1, f2);
        }
        wsize += lens2[i];
        printf("done!\n");
    }

    fclose(fexcept);
    size = atoi(argv[1]);
    FILE* fsize = fopen("linfos", "wb");
    fwrite(&size,  sizeof(unsigned), 1, fsize);
    fwrite(lens, sizeof(unsigned), size , fsize);
    fclose(fsize);
    fclose(f2);
    return 0;
}<commit_msg>check if file exists in convert script<commit_after>/*

This is the global optimization using the tradeoff tables

We decide on parameters for each document based on some constraints on meta data size

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_DOCS 240179

typedef struct
{
    int total;
    int numDistinctFrags;
    int numPostings;
    float wsize;
} linfo;

int comparep(const void* a1, const void* a2)
{
    linfo* l1 = (linfo*)a1;
    linfo* l2 = (linfo*)a2;

    int ret =  l1->numPostings - l2->numPostings;
    int ret2 = l1->total - l2->total;

    if (ret2 == 0)
        return ret;
    else
        return ret2;
}

int main(int argc, char** argv)
{
    linfo* lbuf = new linfo[NUM_DOCS];
    int ptr = 0;
    unsigned* lens = new unsigned[NUM_DOCS];
    memset(lens, 0, NUM_DOCS * sizeof(unsigned));
    char fn[256];
    memset(fn, 0, 256);
    FILE* f2 = fopen("finfos", "wb");
    FILE* f3 = fopen("/data/jhe/wiki_access/numv", "rb");
    int size;
    fread(&size, sizeof(unsigned), 1, f3);
    unsigned* lens2 = new unsigned[size];
    fread(lens2, sizeof(unsigned), size, f3);
    fclose(f3);

    FILE* f4 = fopen("/data/jhe/wiki_access/word_size", "rb");
    unsigned wlens;
    fread(&wlens, sizeof(unsigned), 1, f4);
    unsigned* dlens = new unsigned[wlens];
    fread(dlens, sizeof(unsigned), wlens, f4);
    fclose(f4);
    int wsize = 0;
    FILE* fexcept = fopen("except", "w");

    for (int i = 0; i < atoi(argv[1]); i++)
    {
        memset(fn, 0, 256);
        sprintf(fn, "test/meta-vs-index-tradeoff-%d", i);
        FILE* f1 = fopen(fn, "r");
        if (!f1) {
            printf("skipping:%d...\n", i);
            continue;
        }
        ptr = 0;
        printf("processing:%d...", i);
        if (lens2[i] > 1)
        {
            bool change = false;
            while (fscanf(f1, "%f\t%d\t%d\t%d\n", &lbuf[ptr].wsize, &lbuf[ptr].numDistinctFrags,  &lbuf[ptr].total, &lbuf[ptr].numPostings)>0)
            {
                if (ptr > 0 && lbuf[ptr].numPostings != lbuf[ptr-1].numPostings)
                {
                    change = true;
                }
                ptr++;
            }
            fclose(f1);
            memset(fn, 0, 256);
            sprintf(fn, "test/convert-%d", i);
            f1 = fopen(fn, "w");
            qsort(lbuf, ptr, sizeof(linfo), comparep);
            int ptr1 = 0;
            int ptr2 = 1;
            while (ptr2 < ptr)
            {
                while (ptr2 < ptr && lbuf[ptr2].numPostings >= lbuf[ptr1].numPostings)
                    ptr2++;

                if (ptr2 >= ptr)
                    break;

                ptr1++;
                lbuf[ptr1] = lbuf[ptr2];
                ptr2++;
            }
            ptr1++;

            for (int j = 0; j < ptr1; j++)
            {
                fprintf(f1, "%.1f\t%d\t%d\t%d\n", lbuf[j].wsize, lbuf[j].total, lbuf[j].numDistinctFrags, lbuf[j].numPostings);
            }

            fclose(f1);
            fwrite(lbuf, sizeof(linfo), ptr1, f2);
            lens[i] = ptr1;
            if (change == false)
            {
                fprintf(fexcept, "%d\t%d\n", i, ptr);
            }
        }
        else
        {
            fclose(f1);
            lens[i] = 1;
            lbuf[0].wsize = dlens[wsize];
            lbuf[0].total = 1;
            lbuf[0].numDistinctFrags  = 1;
            lbuf[0].numPostings = dlens[wsize];
            fwrite(lbuf, sizeof(linfo), 1, f2);
        }
        wsize += lens2[i];
        printf("done!\n");
    }

    fclose(fexcept);
    size = atoi(argv[1]);
    FILE* fsize = fopen("linfos", "wb");
    fwrite(&size,  sizeof(unsigned), 1, fsize);
    fwrite(lens, sizeof(unsigned), size , fsize);
    fclose(fsize);
    fclose(f2);
    return 0;
}<|endoftext|>


<commit_before>#pragma once

#include <type_traits>
#include <typeinfo>
#include <functional>
#include <cstring>

template <size_t ...args>
struct static_max;

template <size_t value>
struct static_max<value>
{
    static const size_t result = value;
};

template <size_t value, size_t ...values>
struct static_max<value, values...>
{
    static const size_t result =
        value > static_max<values...>::result ?
        value :
        static_max<values...>::result;
};

template <size_t count, typename ...args>
struct variant_lookup;

template <size_t count, typename Lookup>
struct variant_lookup<count, Lookup>
{
    static const int result = -1;
};

template <size_t count, typename Lookup, typename Candidate, typename ...rest>
struct variant_lookup<count, Lookup, Candidate, rest...>
{
    static const int result = std::is_same<Lookup, Candidate>::value ?
        count :
        variant_lookup<count + 1, Lookup, rest...>::result;
};

template <typename... ContainedTypes>
struct Variant
{
    Variant()
        : type(-1)
    {

    }

    Variant(const Variant &copy)
        : type(copy.type)
    {
        void *origin = &copy.data;
        void *destination = &data;
        memcpy(destination, origin, data_size);
    }

    Variant(Variant &&) = delete;

    template <typename Type>
    explicit Variant(const Type &value)
        : type(variant_lookup<0, Type, ContainedTypes...>::value)
    {
        init(value);
        static_cast<Type>(data) = value;
    }

    ~Variant()
    {
        destroy();
    }

    template <typename Type>
    void init(const Type &value)
    {
        Type *ptr = reinterpret_cast<Type *>(&data);
        new (ptr) Type(value);
    }

    void destroy()
    {
        static std::function<void (void *)> destructors[] =
            { build_destructor<ContainedTypes>()... };

        if (type < 0) return;

        destructors[type](&data);
        type = -1;
    }

    Variant<ContainedTypes...> & operator=(const Variant &copy)
    {
        destroy();
        type = copy.type;
        void *origin = &copy.data;
        void *destination = &data;
        memcpy(destination, origin, data_size);

        return *this;
    }

    Variant<ContainedTypes...> & operator=(Variant &&) = delete;

    template <typename Type>
    Variant<ContainedTypes...> & operator=(const Type &value)
    {
        destroy();
        type = variant_lookup<0, Type, ContainedTypes...>::result;

        init(value);

        return *this;
    }

    template <typename Evaluator>
    void apply(Evaluator &value)
    {
        static std::function<void (Evaluator &, void *)> dispatchers[] =
            { build_dispatch<Evaluator, ContainedTypes>()... };

        dispatchers[type](value, &data);
    }

    template <typename Evaluator, typename Target>
    std::function<void (Evaluator &, void *)> build_dispatch()
    {
        return [](Evaluator &functor, void *data)
        {
            auto *v = reinterpret_cast<Target *>(data);

            functor.operator()(*v);
        };
    }

    template <typename Target>
    std::function<void (void *)> build_destructor()
    {
        return [](void *data)
        {
            auto *v = reinterpret_cast<Target *>(data);

            v->~Target();
        };
    }

    static const size_t data_size = static_max<sizeof(ContainedTypes)...>::result;
    static const size_t data_align = static_max<alignof(ContainedTypes)...>::result;
    using Storage = typename std::aligned_storage<data_size, data_align>::type;

    int type;
    Storage data;
};
<commit_msg>Fixed an mistake where we did a redundant operator= operation after doing a copy constructor action.<commit_after>#pragma once

#include <type_traits>
#include <typeinfo>
#include <functional>
#include <cstring>

template <size_t ...args>
struct static_max;

template <size_t value>
struct static_max<value>
{
    static const size_t result = value;
};

template <size_t value, size_t ...values>
struct static_max<value, values...>
{
    static const size_t result =
        value > static_max<values...>::result ?
        value :
        static_max<values...>::result;
};

template <size_t count, typename ...args>
struct variant_lookup;

template <size_t count, typename Lookup>
struct variant_lookup<count, Lookup>
{
    static const int result = -1;
};

template <size_t count, typename Lookup, typename Candidate, typename ...rest>
struct variant_lookup<count, Lookup, Candidate, rest...>
{
    static const int result = std::is_same<Lookup, Candidate>::value ?
        count :
        variant_lookup<count + 1, Lookup, rest...>::result;
};

template <typename... ContainedTypes>
struct Variant
{
    Variant()
        : type(-1)
    {

    }

    Variant(const Variant &copy)
        : type(copy.type)
    {
        void *origin = &copy.data;
        void *destination = &data;
        memcpy(destination, origin, data_size);
    }

    Variant(Variant &&) = delete;

    template <typename Type>
    explicit Variant(const Type &value)
        : type(variant_lookup<0, Type, ContainedTypes...>::value)
    {
        init(value);
    }

    ~Variant()
    {
        destroy();
    }

    template <typename Type>
    void init(const Type &value)
    {
        Type *ptr = reinterpret_cast<Type *>(&data);
        new (ptr) Type(value);
    }

    void destroy()
    {
        static std::function<void (void *)> destructors[] =
            { build_destructor<ContainedTypes>()... };

        if (type < 0) return;

        destructors[type](&data);
        type = -1;
    }

    Variant<ContainedTypes...> & operator=(const Variant &copy)
    {
        destroy();
        type = copy.type;
        void *origin = &copy.data;
        void *destination = &data;
        memcpy(destination, origin, data_size);

        return *this;
    }

    Variant<ContainedTypes...> & operator=(Variant &&) = delete;

    template <typename Type>
    Variant<ContainedTypes...> & operator=(const Type &value)
    {
        destroy();
        type = variant_lookup<0, Type, ContainedTypes...>::result;

        init(value);

        return *this;
    }

    template <typename Evaluator>
    void apply(Evaluator &value)
    {
        static std::function<void (Evaluator &, void *)> dispatchers[] =
            { build_dispatch<Evaluator, ContainedTypes>()... };

        dispatchers[type](value, &data);
    }

    template <typename Evaluator, typename Target>
    std::function<void (Evaluator &, void *)> build_dispatch()
    {
        return [](Evaluator &functor, void *data)
        {
            auto *v = reinterpret_cast<Target *>(data);

            functor.operator()(*v);
        };
    }

    template <typename Target>
    std::function<void (void *)> build_destructor()
    {
        return [](void *data)
        {
            auto *v = reinterpret_cast<Target *>(data);

            v->~Target();
        };
    }

    static const size_t data_size = static_max<sizeof(ContainedTypes)...>::result;
    static const size_t data_align = static_max<alignof(ContainedTypes)...>::result;
    using Storage = typename std::aligned_storage<data_size, data_align>::type;

    int type;
    Storage data;
};
<|endoftext|>


<commit_before>#include <iostream>

#include "ext/dep_gecode/version_problem_oc_ih.h"

// build: g++ test.cpp -o test ext/gecode/dep_selector_to_gecode_interface.o ext/gecode/dep_selector_to_gecode.o -lgecodesupport -lgecodekernel -lgecodeint -lgecodesearch

using namespace std;

int problem_nosol() {
  VersionProblemOCIH* problem = VersionProblemCreate(10);
  // package A has versions 0, 1v
  int pkg_a = AddPackage(problem, 0, 1, 1);
  // package B has versions 0, 1
  int pkg_b = AddPackage(problem, 0, 1, 1);
  // package C has versions 0, 1
  int pkg_c = AddPackage(problem, 0, 1, 0);

  // A0 depends on B1
  AddVersionConstraint(problem, pkg_a, 0, pkg_b, 1, 1);

  // A1 depends on B0, C0
  AddVersionConstraint(problem, pkg_a, 0, pkg_b, 0, 0);
  AddVersionConstraint(problem, pkg_a, 0, pkg_c, 0, 0);

  // B1 depends on C10, which doesn't even exist...
  AddVersionConstraint(problem, pkg_b, 1, pkg_c, 10, 10);

  // metapackage is a "ghost" package whose dependencies are the
  // solution constraints; thereby forcing packages to be
  // appropriately constrained
  int metapkg = AddPackage(problem, 0, 0, 0);

  cout << "before adding solution constraints" << endl;
  VersionProblemPrintPackageVar(problem, pkg_a);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_b);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_c);
  cout << endl;
  VersionProblemPrintPackageVar(problem, metapkg);
  cout << endl;

  // solution constraints: [A,(B=0)], which is satisfiable as A=1, B=0
  //AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 1);
  //AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);
  // solution constraints: [(A=0),(B=0)], which is not satisfiable
  AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 0);
  AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);

  cout << "after adding solution constraints" << endl;
  VersionProblemPrintPackageVar(problem, pkg_a);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_b);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_c);
  cout << endl;
  VersionProblemPrintPackageVar(problem, metapkg);
  cout << endl;

  VersionProblemOCIH *solution = Solve(problem);
  if (solution != NULL) {
    // solve and interrogate problem
    cout << "after running solve" << endl;
    VersionProblemPrintPackageVar(solution, pkg_a);
    cout << endl;
    VersionProblemPrintPackageVar(solution, pkg_b);
    cout << endl;
    VersionProblemPrintPackageVar(solution, pkg_c);
    cout << endl;
    VersionProblemPrintPackageVar(solution, metapkg);
    cout << endl;
    VersionProblemDestroy(solution);
  } else {
    cout << "No solution" << endl;
  }
  VersionProblemDestroy(problem);

}

int problem_sol() {
  VersionProblemOCIH* problem = VersionProblemCreate(10);
  // package A has versions 0, 1v
  int pkg_a = AddPackage(problem, 0, 1, 1);
  // package B has versions 0, 1
  int pkg_b = AddPackage(problem, 0, 1, 1);
  // package C has versions 0
  int pkg_c = AddPackage(problem, 0, 0, 0);

  // A0 depends on B1
  AddVersionConstraint(problem, pkg_a, 0, pkg_b, 1, 1);

  // A1 depends on B0, C0
  AddVersionConstraint(problem, pkg_a, 0, pkg_b, 0, 0);
  AddVersionConstraint(problem, pkg_a, 0, pkg_c, 0, 0);

  // metapackage is a "ghost" package whose dependencies are the
  // solution constraints; thereby forcing packages to be
  // appropriately constrained
  int metapkg = AddPackage(problem, 0, 0, 0);

  cout << "before adding solution constraints" << endl;
  VersionProblemPrintPackageVar(problem, pkg_a);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_b);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_c);
  cout << endl;
  VersionProblemPrintPackageVar(problem, metapkg);
  cout << endl;

  // solution constraints: [A,(B=0)], which is satisfiable as A=1, B=0
  AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 1);
  AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);
  // solution constraints: [(A=0),(B=0)], which is not satisfiable
  //AddVersionConstraint(problem, metapkg, 0, pkg_a, 0, 0);
  //AddVersionConstraint(problem, metapkg, 0, pkg_b, 0, 0);

  cout << "after adding solution constraints" << endl;
  VersionProblemPrintPackageVar(problem, pkg_a);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_b);
  cout << endl;
  VersionProblemPrintPackageVar(problem, pkg_c);
  cout << endl;
  VersionProblemPrintPackageVar(problem, metapkg);
  cout << endl;

  VersionProblemOCIH *solution = Solve(problem);
  if (solution != NULL) {
    // solve and interrogate problem
    cout << "after running solve" << endl;
    VersionProblemPrintPackageVar(solution, pkg_a);
    cout << endl;
    VersionProblemPrintPackageVar(solution, pkg_b);
    cout << endl;
    VersionProblemPrintPackageVar(solution, pkg_c);
    cout << endl;
    VersionProblemPrintPackageVar(solution, metapkg);
    cout << endl;
    VersionProblemDestroy(solution);
  } else {
    cout << "No solution" << endl;
  }
  VersionProblemDestroy(problem);
}

int main() {
  problem_nosol();
}
<commit_msg>Remove garbage file.<commit_after><|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/framework/channel.h"

#include <chrono>
#include <thread>

#include "gtest/gtest.h"

using paddle::framework::Channel;
using paddle::framework::MakeChannel;
using paddle::framework::CloseChannel;

TEST(Channel, MakeAndClose) {
  using paddle::framework::details::Buffered;
  using paddle::framework::details::UnBuffered;
  {
    // MakeChannel should return a buffered channel is buffer_size > 0.
    auto ch = MakeChannel<int>(10);
    EXPECT_NE(dynamic_cast<Buffered<int> *>(ch), nullptr);
    EXPECT_EQ(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
    CloseChannel(ch);
    delete ch;
  }
  {
    // MakeChannel should return an un-buffered channel is buffer_size = 0.
    auto ch = MakeChannel<int>(0);
    EXPECT_EQ(dynamic_cast<Buffered<int> *>(ch), nullptr);
    EXPECT_NE(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
    CloseChannel(ch);
    delete ch;
  }
}

TEST(Channel, SufficientBufferSizeDoesntBlock) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  for (size_t i = 0; i < buffer_size; ++i) {
    ch->Send(&i);  // should not block
  }

  size_t out;
  for (size_t i = 0; i < buffer_size; ++i) {
    ch->Receive(&out);  // should not block
    EXPECT_EQ(out, i);
  }
  CloseChannel(ch);
  delete ch;
}

TEST(Channel, ConcurrentSendNonConcurrentReceiveWithSufficientBufferSize) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  size_t sum = 0;
  std::thread t([&]() {
    // Try to write more than buffer size.
    for (size_t i = 0; i < 2 * buffer_size; ++i) {
      ch->Send(&i);  // should block after 10 iterations
      sum += i;
    }
  });
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait 0.5 sec
  EXPECT_EQ(sum, 45U);

  CloseChannel(ch);
  t.join();
  delete ch;
}

TEST(Channel, SimpleUnbufferedChannelTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  std::thread t([&]() {
    for (int i = 0; i < 5; i++) {
      ch->Send(&i);
      sum_send += i;
    }
  });
  for (int i = 0; i < 5; i++) {
    int recv;
    ch->Receive(&recv);
    EXPECT_EQ(recv, i);
  }

  CloseChannel(ch);
  t.join();
  EXPECT_EQ(sum_send, 10U);
  delete ch;
}

// This tests that closing an unbuffered channel also unblocks
//  unblocks any receivers waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksReceiversTest) {
  auto ch = MakeChannel<int>(0);
  size_t num_threads = 5;
  std::thread t[num_threads];
  bool thread_ended[num_threads];

  // Launches threads that try to read and are blocked becausew of no writers
  for (size_t i = 0; i < num_threads; i++) {
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          ch->Receive(&data);
          *p = true;
        },
        &thread_ended[i]);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all the threads are blocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], false);
  }

  // Explicitly close the thread
  // This should unblock all receivers
  CloseChannel(ch);

  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all threads got unblocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], true);
  }

  for (size_t i = 0; i < num_threads; i++) t[i].join();
  delete ch;
}

// This tests that closing an unbuffered channel also unblocks
//  unblocks any senders waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksSendersTest) {
  auto ch = MakeChannel<int>(0);
  size_t num_threads = 5;
  std::thread t[num_threads];
  bool thread_ended[num_threads];

  // Launches threads that try to read and are blocked becausew of no writers
  for (size_t i = 0; i < num_threads; i++) {
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data = 10;
          ch->Send(&data);
          *p = true;
        },
        &thread_ended[i]);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all the threads are blocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], false);
  }

  // Explicitly close the thread
  // This should unblock all receivers
  CloseChannel(ch);

  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all threads got unblocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], true);
  }

  for (size_t i = 0; i < num_threads; i++) t[i].join();
  delete ch;
}

TEST(Channel, UnbufferedLessReceiveMoreSendTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  // Send should block after three iterations
  // since we only have three receivers.
  std::thread t([&]() {
    // Try to send more number of times
    // than receivers
    for (int i = 0; i < 4; i++) {
      ch->Send(&i);
      sum_send += i;
    }
  });
  for (int i = 0; i < 3; i++) {
    int recv;
    ch->Receive(&recv);
    EXPECT_EQ(recv, i);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait 0.5 sec
  EXPECT_EQ(sum_send, 3U);

  CloseChannel(ch);
  t.join();
  delete ch;
}

TEST(Channel, UnbufferedMoreReceiveLessSendTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  unsigned sum_receive = 0;
  // The receiver should block after 5
  // iterations, since there are only 5 senders.
  std::thread t([&]() {
    for (int i = 0; i < 8; i++) {
      int recv;
      ch->Receive(&recv);  // should block after the fifth iteration.
      EXPECT_EQ(recv, i);
      sum_receive += i;
    }
  });
  for (int i = 0; i < 5; i++) {
    ch->Send(&i);
    sum_send += i;
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec
  EXPECT_EQ(sum_send, 10U);
  EXPECT_EQ(sum_receive, 10U);
  // send three more elements
  for (int i = 5; i < 8; i++) {
    ch->Send(&i);
    sum_send += i;
  }

  CloseChannel(ch);
  t.join();
  EXPECT_EQ(sum_send, 28U);
  EXPECT_EQ(sum_receive, 28U);
  delete ch;
}
<commit_msg>Close buffered channel should unblock the blocked  senders and receivers (#8109)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/framework/channel.h"

#include <chrono>
#include <thread>

#include "gtest/gtest.h"

using paddle::framework::Channel;
using paddle::framework::MakeChannel;
using paddle::framework::CloseChannel;

TEST(Channel, MakeAndClose) {
  using paddle::framework::details::Buffered;
  using paddle::framework::details::UnBuffered;
  {
    // MakeChannel should return a buffered channel is buffer_size > 0.
    auto ch = MakeChannel<int>(10);
    EXPECT_NE(dynamic_cast<Buffered<int> *>(ch), nullptr);
    EXPECT_EQ(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
    CloseChannel(ch);
    delete ch;
  }
  {
    // MakeChannel should return an un-buffered channel is buffer_size = 0.
    auto ch = MakeChannel<int>(0);
    EXPECT_EQ(dynamic_cast<Buffered<int> *>(ch), nullptr);
    EXPECT_NE(dynamic_cast<UnBuffered<int> *>(ch), nullptr);
    CloseChannel(ch);
    delete ch;
  }
}

TEST(Channel, SufficientBufferSizeDoesntBlock) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  for (size_t i = 0; i < buffer_size; ++i) {
    EXPECT_EQ(ch->Send(&i), true);  // should not block
  }

  size_t out;
  for (size_t i = 0; i < buffer_size; ++i) {
    EXPECT_EQ(ch->Receive(&out), true);  // should not block
    EXPECT_EQ(out, i);
  }
  CloseChannel(ch);
  delete ch;
}

TEST(Channel, ConcurrentSendNonConcurrentReceiveWithSufficientBufferSize) {
  const size_t buffer_size = 10;
  auto ch = MakeChannel<size_t>(buffer_size);
  size_t sum = 0;
  std::thread t([&]() {
    // Try to write more than buffer size.
    for (size_t i = 0; i < 2 * buffer_size; ++i) {
      if (i < buffer_size)
        EXPECT_EQ(ch->Send(&i), true);  // should block after 10 iterations
      else
        EXPECT_EQ(ch->Send(&i), false);
      sum += i;
    }
  });
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait 0.5 sec
  EXPECT_EQ(sum, 45U);

  CloseChannel(ch);
  t.join();
  delete ch;
}

TEST(Channel, SimpleUnbufferedChannelTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  std::thread t([&]() {
    for (int i = 0; i < 5; i++) {
      EXPECT_EQ(ch->Send(&i), true);
      sum_send += i;
    }
  });
  for (int i = 0; i < 5; i++) {
    int recv;
    EXPECT_EQ(ch->Receive(&recv), true);
    EXPECT_EQ(recv, i);
  }

  CloseChannel(ch);
  t.join();
  EXPECT_EQ(sum_send, 10U);
  delete ch;
}

// This tests that closing a buffered channel also unblocks
//  any receivers waiting on the channel
TEST(Channel, BufferedChannelCloseUnblocksReceiversTest) {
  auto ch = MakeChannel<int>(1);
  size_t num_threads = 5;
  std::thread t[num_threads];
  bool thread_ended[num_threads];

  // Launches threads that try to read and are blocked because of no writers
  for (size_t i = 0; i < num_threads; i++) {
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          // All reads should return false
          EXPECT_EQ(ch->Receive(&data), false);
          *p = true;
        },
        &thread_ended[i]);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait

  // Verify that all threads are blocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], false);
  }

  // Explicitly close the channel
  // This should unblock all receivers
  CloseChannel(ch);

  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait

  // Verify that all threads got unblocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], true);
  }

  for (size_t i = 0; i < num_threads; i++) t[i].join();
  delete ch;
}

// This tests that closing a buffered channel also unblocks
//  any senders waiting for channel to have write space
TEST(Channel, BufferedChannelCloseUnblocksSendersTest) {
  auto ch = MakeChannel<int>(1);
  size_t num_threads = 5;
  std::thread t[num_threads];
  bool thread_ended[num_threads];
  bool send_success[num_threads];

  // Launches threads that try to write and are blocked because of no readers
  for (size_t i = 0; i < num_threads; i++) {
    thread_ended[i] = false;
    send_success[i] = false;
    t[i] = std::thread(
        [&](bool *ended, bool *success) {
          int data = 10;
          *success = ch->Send(&data);
          *ended = true;
        },
        &thread_ended[i], &send_success[i]);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait

  // Verify that atleast 4 threads are blocked
  int ct = 0;
  for (size_t i = 0; i < num_threads; i++) {
    if (thread_ended[i] == false) ct++;
  }
  // Atleast 4 threads must be blocked
  EXPECT_GE(ct, 4);

  // Explicitly close the thread
  // This should unblock all senders
  CloseChannel(ch);

  std::this_thread::sleep_for(std::chrono::milliseconds(200));  // wait

  // Verify that all threads got unblocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], true);
  }

  // Verify that only 1 send was successful
  ct = 0;
  for (size_t i = 0; i < num_threads; i++) {
    if (send_success[i]) ct++;
  }
  // Only 1 send must be successful
  EXPECT_EQ(ct, 1);

  for (size_t i = 0; i < num_threads; i++) t[i].join();
  delete ch;
}

// This tests that closing an unbuffered channel also unblocks
//  unblocks any receivers waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksReceiversTest) {
  auto ch = MakeChannel<int>(0);
  size_t num_threads = 5;
  std::thread t[num_threads];
  bool thread_ended[num_threads];

  // Launches threads that try to read and are blocked becausew of no writers
  for (size_t i = 0; i < num_threads; i++) {
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data;
          EXPECT_EQ(ch->Receive(&data), false);
          *p = true;
        },
        &thread_ended[i]);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all the threads are blocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], false);
  }

  // Explicitly close the thread
  // This should unblock all receivers
  CloseChannel(ch);

  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all threads got unblocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], true);
  }

  for (size_t i = 0; i < num_threads; i++) t[i].join();
  delete ch;
}

// This tests that closing an unbuffered channel also unblocks
//  unblocks any senders waiting for senders
TEST(Channel, UnbufferedChannelCloseUnblocksSendersTest) {
  auto ch = MakeChannel<int>(0);
  size_t num_threads = 5;
  std::thread t[num_threads];
  bool thread_ended[num_threads];

  // Launches threads that try to read and are blocked becausew of no writers
  for (size_t i = 0; i < num_threads; i++) {
    thread_ended[i] = false;
    t[i] = std::thread(
        [&](bool *p) {
          int data = 10;
          EXPECT_EQ(ch->Send(&data), false);
          *p = true;
        },
        &thread_ended[i]);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all the threads are blocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], false);
  }

  // Explicitly close the thread
  // This should unblock all receivers
  CloseChannel(ch);

  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec

  // Verify that all threads got unblocked
  for (size_t i = 0; i < num_threads; i++) {
    EXPECT_EQ(thread_ended[i], true);
  }

  for (size_t i = 0; i < num_threads; i++) t[i].join();
  delete ch;
}

TEST(Channel, UnbufferedLessReceiveMoreSendTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  // Send should block after three iterations
  // since we only have three receivers.
  std::thread t([&]() {
    // Try to send more number of times
    // than receivers
    for (int i = 0; i < 4; i++) {
      ch->Send(&i);
      sum_send += i;
    }
  });
  for (int i = 0; i < 3; i++) {
    int recv;
    ch->Receive(&recv);
    EXPECT_EQ(recv, i);
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // wait 0.5 sec
  EXPECT_EQ(sum_send, 3U);

  CloseChannel(ch);
  t.join();
  delete ch;
}

TEST(Channel, UnbufferedMoreReceiveLessSendTest) {
  auto ch = MakeChannel<int>(0);
  unsigned sum_send = 0;
  unsigned sum_receive = 0;
  // The receiver should block after 5
  // iterations, since there are only 5 senders.
  std::thread t([&]() {
    for (int i = 0; i < 8; i++) {
      int recv;
      ch->Receive(&recv);  // should block after the fifth iteration.
      EXPECT_EQ(recv, i);
      sum_receive += i;
    }
  });
  for (int i = 0; i < 5; i++) {
    ch->Send(&i);
    sum_send += i;
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));  // wait 0.5 sec
  EXPECT_EQ(sum_send, 10U);
  EXPECT_EQ(sum_receive, 10U);
  // send three more elements
  for (int i = 5; i < 8; i++) {
    ch->Send(&i);
    sum_send += i;
  }

  CloseChannel(ch);
  t.join();
  EXPECT_EQ(sum_send, 28U);
  EXPECT_EQ(sum_receive, 28U);
  delete ch;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/external_pref_extension_provider.h"

#include "app/app_paths.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/version.h"
#include "chrome/common/json_value_serializer.h"

// Constants for keeping track of extension preferences.
const wchar_t kLocation[] = L"location";
const wchar_t kState[] = L"state";
const wchar_t kExternalCrx[] = L"external_crx";
const wchar_t kExternalVersion[] = L"external_version";

ExternalPrefExtensionProvider::ExternalPrefExtensionProvider() {
  FilePath json_file;
  PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &json_file);
  json_file = json_file.Append(FILE_PATH_LITERAL("external_extensions.json"));

  JSONFileValueSerializer serializer(json_file);
  SetPreferences(&serializer);
}

ExternalPrefExtensionProvider::~ExternalPrefExtensionProvider() {
}

void ExternalPrefExtensionProvider::SetPreferencesForTesting(
    std::string json_data_for_testing) {
  JSONStringValueSerializer serializer(json_data_for_testing);
  SetPreferences(&serializer);
}

void ExternalPrefExtensionProvider::VisitRegisteredExtension(
    Visitor* visitor, const std::set<std::string>& ids_to_ignore) const {
  for (DictionaryValue::key_iterator i = prefs_->begin_keys();
       i != prefs_->end_keys(); ++i) {
    const std::wstring& extension_id = *i;
    if (ids_to_ignore.find(WideToASCII(extension_id)) != ids_to_ignore.end())
      continue;

    DictionaryValue* extension = NULL;
    if (!prefs_->GetDictionary(extension_id, &extension)) {
      continue;
    }

    FilePath::StringType external_crx;
    std::string external_version;
    if (!extension->GetString(kExternalCrx, &external_crx) ||
        !extension->GetString(kExternalVersion, &external_version)) {
      LOG(WARNING) << "Malformed extension dictionary for extension: "
                   << extension_id.c_str();
      continue;
    }

    if (external_crx.find(FilePath::kParentDirectory) != StringPiece::npos) {
      LOG(WARNING) << "Path traversal not allowed in path: "
                   << external_crx.c_str();
      continue;
    }

    // See if it's an absolute path...
    FilePath path(external_crx);
    if (!path.IsAbsolute()) {
      // Try path as relative path from external extension dir.
      FilePath base_path;
      PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &base_path);
      path = base_path.Append(external_crx);
    }

    scoped_ptr<Version> version;
    version.reset(Version::GetVersionFromString(external_version));
    visitor->OnExternalExtensionFound(
        WideToASCII(extension_id), version.get(), path);
  }
}

Version* ExternalPrefExtensionProvider::RegisteredVersion(
    std::string id, Extension::Location* location) const {
  DictionaryValue* extension = NULL;
  if (!prefs_->GetDictionary(ASCIIToWide(id), &extension))
    return NULL;

  std::string external_version;
  if (!extension->GetString(kExternalVersion, &external_version))
    return NULL;

  if (location)
    *location = Extension::EXTERNAL_PREF;
  return Version::GetVersionFromString(external_version);
}

void ExternalPrefExtensionProvider::SetPreferences(
    ValueSerializer* serializer) {
  std::string error_msg;
  Value* extensions = serializer->Deserialize(&error_msg);
  scoped_ptr<DictionaryValue> dictionary(new DictionaryValue());
  if (!error_msg.empty()) {
    NOTREACHED() << L"Unable to deserialize json data: "
                 << error_msg.c_str();
  } else {
    // This can be null if the json file specified does not exist.
    if (extensions) {
      if (!extensions->IsType(Value::TYPE_DICTIONARY)) {
        NOTREACHED() << L"Invalid json data";
      } else {
        dictionary.reset(static_cast<DictionaryValue*>(extensions));
      }
    }
  }
  prefs_.reset(dictionary.release());
}
<commit_msg>Fix build. <commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/external_pref_extension_provider.h"

#include "app/app_paths.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/version.h"
#include "chrome/common/json_value_serializer.h"

// Constants for keeping track of extension preferences.
const wchar_t kLocation[] = L"location";
const wchar_t kState[] = L"state";
const wchar_t kExternalCrx[] = L"external_crx";
const wchar_t kExternalVersion[] = L"external_version";

ExternalPrefExtensionProvider::ExternalPrefExtensionProvider() {
  FilePath json_file;
  PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &json_file);
  json_file = json_file.Append(FILE_PATH_LITERAL("external_extensions.json"));

  JSONFileValueSerializer serializer(json_file);
  SetPreferences(&serializer);
}

ExternalPrefExtensionProvider::~ExternalPrefExtensionProvider() {
}

void ExternalPrefExtensionProvider::SetPreferencesForTesting(
    std::string json_data_for_testing) {
  JSONStringValueSerializer serializer(json_data_for_testing);
  SetPreferences(&serializer);
}

void ExternalPrefExtensionProvider::VisitRegisteredExtension(
    Visitor* visitor, const std::set<std::string>& ids_to_ignore) const {
  for (DictionaryValue::key_iterator i = prefs_->begin_keys();
       i != prefs_->end_keys(); ++i) {
    const std::wstring& extension_id = *i;
    if (ids_to_ignore.find(WideToASCII(extension_id)) != ids_to_ignore.end())
      continue;

    DictionaryValue* extension = NULL;
    if (!prefs_->GetDictionary(extension_id, &extension)) {
      continue;
    }

    FilePath::StringType external_crx;
    std::string external_version;
    if (!extension->GetString(kExternalCrx, &external_crx) ||
        !extension->GetString(kExternalVersion, &external_version)) {
      LOG(WARNING) << "Malformed extension dictionary for extension: "
                   << extension_id.c_str();
      continue;
    }

    if (external_crx.find(FilePath::kParentDirectory) != StringPiece::npos) {
      LOG(WARNING) << "Path traversal not allowed in path: "
                   << external_crx.c_str();
      continue;
    }

    // See if it's an absolute path...
    FilePath path(external_crx);
    if (!path.IsAbsolute()) {
      // Try path as relative path from external extension dir.
      FilePath base_path;
      PathService::Get(app::DIR_EXTERNAL_EXTENSIONS, &base_path);
      path = base_path.Append(external_crx);
    }

    scoped_ptr<Version> version;
    version.reset(Version::GetVersionFromString(external_version));
    visitor->OnExternalExtensionFound(
        WideToASCII(extension_id), version.get(), path);
  }
}

Version* ExternalPrefExtensionProvider::RegisteredVersion(
    std::string id, Extension::Location* location) const {
  DictionaryValue* extension = NULL;
  if (!prefs_->GetDictionary(ASCIIToWide(id), &extension))
    return NULL;

  std::string external_version;
  if (!extension->GetString(kExternalVersion, &external_version))
    return NULL;

  if (location)
    *location = Extension::EXTERNAL_PREF;
  return Version::GetVersionFromString(external_version);
}

void ExternalPrefExtensionProvider::SetPreferences(
    ValueSerializer* serializer) {
  std::string error_msg;
  Value* extensions = serializer->Deserialize(&error_msg);
  scoped_ptr<DictionaryValue> dictionary(new DictionaryValue());
  if (!error_msg.empty()) {
    LOG(WARNING) << L"Unable to deserialize json data: "
                 << error_msg.c_str();
  } else {
    // This can be null if the json file specified does not exist.
    if (extensions) {
      if (!extensions->IsType(Value::TYPE_DICTIONARY)) {
        NOTREACHED() << L"Invalid json data";
      } else {
        dictionary.reset(static_cast<DictionaryValue*>(extensions));
      }
    }
  }
  prefs_.reset(dictionary.release());
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <fyut.h>
#include <new> // nothrow
#include<libgen.h>
/*
Description     _fullpath converts the relative path name name 'pathname'
                to a fully qualified pathname, stored in 'buffer'.  The
                     relative path can contain ".\" and "..".

                The maximum size of the supplied buffer is 'maxlen'.
                If the fully qualified path is longer than 'maxlen',
                NULL is returned.  The buffer should be at least _MAX_PATH
                bytes long (this constant is defined in stdlib.h).

                If 'buffer' is NULL, a buffer to store the fully qualified
                path is allocated and is returned.  The calling program
                must free this buffer with GlobalFree(() when it is no longer needed.

                If the pathname does not specify a disk drive, the current
i                drive is used.

 Allocate a temporary buffer to hold the fully qualified path.
if ((tempbuf = (char*)UT_MALLOC(_MAX_PATH*2+1)) == NULL)
      return (NULL);

return (char*)(realloc(tempbuf,len));
*/

char * _ffullpath(char *buffer, const char *pathname, size_t maxlen) {
	if(maxlen < _MAX_PATH) {
		return NULL;
	}
	char * wpath;
	wpath = new (std::nothrow) char[_MAX_PATH];
	if (wpath == NULL) { // could not allocate memory
		return NULL;
	}

	char * wpath2;
	wpath2 = new (std::nothrow) char[_MAX_PATH];
	if (wpath2 == NULL) {
		delete [] wpath;
		return NULL;
	}

	strncpy(wpath, pathname, _MAX_PATH);
	strncpy(wpath2, pathname, _MAX_PATH);

	/* Make relativer paths of ./foo-paths */
	if(pathname[0] == '.' && pathname[1] == UT_SLASH) {
		strncpy(wpath, pathname+2, _MAX_PATH);
		strncpy(wpath, pathname+2, _MAX_PATH);
	}

	char * prevPos = NULL;

	char same[4] = { UT_SLASH, '.', UT_SLASH, '\0' }; // e.g. "/./"
    /* replace /./ with nothing */
    while ((prevPos = strstr(wpath, same)) != NULL) {
        prevPos[1] = '\0';
        UT_StrCopy(wpath2, wpath, _MAX_PATH);
        strncat(wpath2, (prevPos+strlen(same)), _MAX_PATH);
        UT_StrCopy(wpath, wpath2, _MAX_PATH);
    }
	char prev[5] = { UT_SLASH, '.', '.', UT_SLASH, '\0' }; // e.g "/../"

	int i = -1;
	/* Remove /../ and parent folder */
	while ((prevPos = strstr(wpath, prev)) != NULL) {
		/* Walk forward in the string until first slash or start of string */
		while((prevPos + i) >= wpath && prevPos[i] != UT_SLASH) {
			prevPos[i--] = '\0';
		}
		UT_StrCopy(wpath2, wpath, _MAX_PATH);
		strncat(wpath2, (prevPos+strlen(prev)), _MAX_PATH);
		UT_StrCopy(wpath, wpath2, _MAX_PATH);
		i = -1;
	}

	/* prepend cwd on relative paths */
	if(wpath[0] != UT_SLASH) {
		if(getcwd(wpath2, _MAX_PATH) == NULL) {
			delete [] wpath;
		    delete [] wpath2;
			return NULL;
		}
		/* getcwd gives ut the path w/o ending slash */
		strncat(wpath2, UT_STR_SLASH, _MAX_PATH-(strlen(wpath2)+1));
		strncat(wpath2, wpath, _MAX_PATH)-(strlen(wpath2)+1);
		UT_StrCopy(wpath, wpath2, _MAX_PATH);
	}

	int endLen = strlen(wpath);
	int startAt = 0;
	if(wpath[0] == '/') {
		endLen--;
		startAt = 1;
	}
	delete [] wpath2;
	if (endLen < maxlen && buffer != NULL) { /* we have a buffer, and we have room in buffer */
       	UT_StrCopy(buffer, (wpath+startAt), maxlen);
		delete [] wpath;
		return buffer;
	} else if (buffer == NULL) { /* we have no buffer */
		char * tempbuf;
		if ((tempbuf = (char*)UT_MALLOC(endLen+1)) != NULL) {
			UT_StrCopy(tempbuf, (wpath+startAt), (endLen+1));
			delete [] wpath;
			return tempbuf;
		} else { /* failed to alloc memory*/
			delete [] wpath;
            return NULL;
		}
	} else { /* not room in buffer and we were supposed to use the buffer */
		delete [] wpath;
		return NULL;
	}
}

int main(int argc, char** args) {
	if(argc < 2) {
		exit(1);
	}
//   char absPath[_MAX_PATH], absPath2[_MAX_PATH];
//	absPath[0] = '\0';
//	absPath2[0] = '\0';
	char * absPath; char * absPath2;
	absPath2 = _ffullpath(NULL, args[1], _MAX_PATH);
	absPath = _fullpath (NULL, args[1], _MAX_PATH);
	if (absPath == NULL || absPath2 == NULL) {
		if (absPath == NULL)
			printf("\x1b[%dmPRIO returned NULL\x1b[0m\n\n", 31);
		if (absPath2 == NULL)
			printf("\x1b[%dmFREE returned NULL\x1b[0m\n\n", 31);

		return 0;
	}
	if (!(strcmp(absPath, absPath2) == 0)) {
		printf("\x1b[%dmPRIO: '%s'\n", 31, absPath);
		printf("FREE: '%s'\x1b[0m\n\n", absPath2);
	} else {
		printf("\x1b[%dmBOTH: '%s'\x1b[0m\n\n", 32, absPath);
	}
	UT_FREE(absPath); UT_FREE(absPath2);
}

<commit_msg>Cleanup headers, better docs<commit_after>#include <cstdlib> // malloc etc
#include <cstring> // strcat etc
#include <new> // nothrow
#include <fyut.h>

/*
CH _ffullpath
CD ==============================================================
CD Makes a complete path from a non-complete path. Handles "..",
CD "." and will prepend the path with current working directory
CD if it is relative (does not start with slash)
CD
CD The function returns buffer, pointer to memory area containing
CD full path if buffer was NULL, or NULL if a error occured
CD (e.g. full path was longer than maxlen and a buffer
CD was supplied.) The pointer should be free'd by calling code.
CD
CD Parameters:
CD Type        Name             I/O  Explanation
CD -------------------------------------------------------------
CD char       *buffer           i/o  Buffer to put full path into or NULL.
CD const char *pathname          i   Pathname to expand
CD size_t     maxlen             i   Size of buffer.
CD char *                        r   buffer, pointer to char[] or NULL
CD  ==============================================================
*/
char * _ffullpath(char *buffer, const char *pathname, size_t maxlen) {
	if(maxlen < _MAX_PATH) {
		return NULL;
	}
	char * wpath;
	wpath = new (std::nothrow) char[_MAX_PATH];
	if (wpath == NULL) { // could not allocate memory
		return NULL;
	}

	char * wpath2;
	wpath2 = new (std::nothrow) char[_MAX_PATH];
	if (wpath2 == NULL) {
		delete [] wpath;
		return NULL;
	}

	strncpy(wpath, pathname, _MAX_PATH);
	strncpy(wpath2, pathname, _MAX_PATH);

	/* Make relativer paths of ./foo-paths */
	if(pathname[0] == '.' && pathname[1] == UT_SLASH) {
		strncpy(wpath, pathname+2, _MAX_PATH);
		strncpy(wpath, pathname+2, _MAX_PATH);
	}

	char * prevPos = NULL;

	char same[4] = { UT_SLASH, '.', UT_SLASH, '\0' }; // e.g. "/./"
    /* replace /./ with nothing */
    while ((prevPos = strstr(wpath, same)) != NULL) {
        prevPos[1] = '\0';
        UT_StrCopy(wpath2, wpath, _MAX_PATH);
        strncat(wpath2, (prevPos+strlen(same)), _MAX_PATH);
        UT_StrCopy(wpath, wpath2, _MAX_PATH);
    }
	char prev[5] = { UT_SLASH, '.', '.', UT_SLASH, '\0' }; // e.g "/../"

	int i = -1;
	/* Remove /../ and parent folder */
	while ((prevPos = strstr(wpath, prev)) != NULL) {
		/* Walk forward in the string until first slash or start of string */
		while((prevPos + i) >= wpath && prevPos[i] != UT_SLASH) {
			prevPos[i--] = '\0';
		}
		UT_StrCopy(wpath2, wpath, _MAX_PATH);
		strncat(wpath2, (prevPos+strlen(prev)), _MAX_PATH);
		UT_StrCopy(wpath, wpath2, _MAX_PATH);
		i = -1;
	}

	/* prepend cwd on relative paths */
	if(wpath[0] != UT_SLASH) {
		if(getcwd(wpath2, _MAX_PATH) == NULL) {
			delete [] wpath;
		    delete [] wpath2;
			return NULL;
		}
		/* getcwd gives ut the path w/o ending slash */
		strncat(wpath2, UT_STR_SLASH, _MAX_PATH-(strlen(wpath2)+1));
		strncat(wpath2, wpath, _MAX_PATH)-(strlen(wpath2)+1);
		UT_StrCopy(wpath, wpath2, _MAX_PATH);
	}

	int endLen = strlen(wpath);
	int startAt = 0;
	if(wpath[0] == '/') {
		endLen--;
		startAt = 1;
	}
	delete [] wpath2;
	if (endLen < maxlen && buffer != NULL) { /* we have a buffer, and we have room in buffer */
       	UT_StrCopy(buffer, (wpath+startAt), maxlen);
		delete [] wpath;
		return buffer;
	} else if (buffer == NULL) { /* we have no buffer */
		char * tempbuf;
		if ((tempbuf = (char*)UT_MALLOC(endLen+1)) != NULL) {
			UT_StrCopy(tempbuf, (wpath+startAt), (endLen+1));
			delete [] wpath;
			return tempbuf;
		} else { /* failed to alloc memory*/
			delete [] wpath;
            return NULL;
		}
	} else { /* not room in buffer and we were supposed to use the buffer */
		delete [] wpath;
		return NULL;
	}
}

int main(int argc, char** args) {
	if(argc < 2) {
		exit(1);
	}
//   char absPath[_MAX_PATH], absPath2[_MAX_PATH];
//	absPath[0] = '\0';
//	absPath2[0] = '\0';
	char * absPath; char * absPath2;
	absPath2 = _ffullpath(NULL, args[1], _MAX_PATH);
	absPath = _fullpath (NULL, args[1], _MAX_PATH);
	if (absPath == NULL || absPath2 == NULL) {
		if (absPath == NULL)
			printf("\x1b[%dmPRIO returned NULL\x1b[0m\n\n", 31);
		if (absPath2 == NULL)
			printf("\x1b[%dmFREE returned NULL\x1b[0m\n\n", 31);

		return 0;
	}
	if (!(strcmp(absPath, absPath2) == 0)) {
		printf("\x1b[%dmPRIO: '%s'\n", 31, absPath);
		printf("FREE: '%s'\x1b[0m\n\n", absPath2);
	} else {
		printf("\x1b[%dmBOTH: '%s'\x1b[0m\n\n", 32, absPath);
	}
	UT_FREE(absPath); UT_FREE(absPath2);
}

<|endoftext|>


<commit_before>// Copyright (c) Microsoft. All rights reserved.

// ConsoleApplication.cpp : Defines the entry point for the console application.
//

#include "pch.h"

#include <windows.h>
#include <chrono>
#include <thread>

using namespace std;

// Use to convert bytes to KB
#define DIV 1024

// Specify the width of the field in which to print the numbers.
#define MESSAGE_WIDTH 30
#define NUMERIC_WIDTH 10

void printMessage(LPCSTR msg, bool addColon)
{
    cout.width(MESSAGE_WIDTH);
    cout << msg;
    if (addColon)
    {
        cout << " : ";
    }
}

void printMessageLine(LPCSTR msg)
{
    printMessage(msg, false);
    cout << endl;
}

void printMessageLine(LPCSTR msg, DWORD value)
{
    printMessage(msg, true);
    cout.width(NUMERIC_WIDTH);
    cout << right << value << endl;
}

void printMessageLine(LPCSTR msg, DWORDLONG value)
{
    printMessage(msg, true);
    cout.width(NUMERIC_WIDTH);
    cout << right << value << endl;
}

void checkInput(HANDLE exitEvent)
{
    for (;;)
    {
        char character;
        cin.get(character);
        if (character == 'q')
        {
            SetEvent(exitEvent);
            break;
        }
    }
}

int main(int argc, char **argv)
{
    printMessageLine("Starting to monitor memory consumption! Press enter to start monitoring");
    printMessageLine("You can press q and enter at anytime to exit");
    cin.get();
    HANDLE exitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
    if (NULL == exitEvent)
    {
        printMessageLine("Failed to create exitEvent.");
        return -1;
    }
    std::thread inputThread(checkInput, exitEvent);
    for (;;)
    {
        MEMORYSTATUSEX statex;
        statex.dwLength = sizeof(statex);

        BOOL success = ::GlobalMemoryStatusEx(&statex);
        if (!success)
        {
            DWORD error = GetLastError();
            printMessageLine("*************************************************");
            printMessageLine("Error getting memory information", error);
            printMessageLine("*************************************************");
        }
        else
        {
            DWORD load = statex.dwMemoryLoad;
            DWORDLONG physKb = statex.ullTotalPhys / DIV;
            DWORDLONG freePhysKb = statex.ullAvailPhys / DIV;
            DWORDLONG pageKb = statex.ullTotalPageFile / DIV;
            DWORDLONG freePageKb = statex.ullAvailPageFile / DIV;
            DWORDLONG virtualKb = statex.ullTotalVirtual / DIV;
            DWORDLONG freeVirtualKb = statex.ullAvailVirtual / DIV;
            DWORDLONG freeExtKb = statex.ullAvailExtendedVirtual / DIV;

            printMessageLine("*************************************************");

            printMessageLine("Percent of memory in use", load);
            printMessageLine("KB of physical memory", physKb);
            printMessageLine("KB of free physical memory", freePhysKb);
            printMessageLine("KB of paging file", pageKb);
            printMessageLine("KB of free paging file", freePageKb);
            printMessageLine("KB of virtual memory", virtualKb);
            printMessageLine("KB of free virtual memory", freeVirtualKb);
            printMessageLine("KB of free extended memory", freeExtKb);

            printMessageLine("*************************************************");

        }

        if (WAIT_OBJECT_0 == ::WaitForSingleObject(exitEvent, 100))
        {
            break;
        }
    }

    inputThread.join();
    ::CloseHandle(exitEvent);
    printMessageLine("No longer monitoring memory consumption!");
}
<commit_msg>Adding global scope to SetEvent<commit_after>// Copyright (c) Microsoft. All rights reserved.

// ConsoleApplication.cpp : Defines the entry point for the console application.
//

#include "pch.h"

#include <windows.h>
#include <chrono>
#include <thread>

using namespace std;

// Use to convert bytes to KB
#define DIV 1024

// Specify the width of the field in which to print the numbers.
#define MESSAGE_WIDTH 30
#define NUMERIC_WIDTH 10

void printMessage(LPCSTR msg, bool addColon)
{
    cout.width(MESSAGE_WIDTH);
    cout << msg;
    if (addColon)
    {
        cout << " : ";
    }
}

void printMessageLine(LPCSTR msg)
{
    printMessage(msg, false);
    cout << endl;
}

void printMessageLine(LPCSTR msg, DWORD value)
{
    printMessage(msg, true);
    cout.width(NUMERIC_WIDTH);
    cout << right << value << endl;
}

void printMessageLine(LPCSTR msg, DWORDLONG value)
{
    printMessage(msg, true);
    cout.width(NUMERIC_WIDTH);
    cout << right << value << endl;
}

void checkInput(HANDLE exitEvent)
{
    for (;;)
    {
        char character;
        cin.get(character);
        if (character == 'q')
        {
            ::SetEvent(exitEvent);
            break;
        }
    }
}

int main(int argc, char **argv)
{
    printMessageLine("Starting to monitor memory consumption! Press enter to start monitoring");
    printMessageLine("You can press q and enter at anytime to exit");
    cin.get();
    HANDLE exitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
    if (NULL == exitEvent)
    {
        printMessageLine("Failed to create exitEvent.");
        return -1;
    }
    std::thread inputThread(checkInput, exitEvent);
    for (;;)
    {
        MEMORYSTATUSEX statex;
        statex.dwLength = sizeof(statex);

        BOOL success = ::GlobalMemoryStatusEx(&statex);
        if (!success)
        {
            DWORD error = GetLastError();
            printMessageLine("*************************************************");
            printMessageLine("Error getting memory information", error);
            printMessageLine("*************************************************");
        }
        else
        {
            DWORD load = statex.dwMemoryLoad;
            DWORDLONG physKb = statex.ullTotalPhys / DIV;
            DWORDLONG freePhysKb = statex.ullAvailPhys / DIV;
            DWORDLONG pageKb = statex.ullTotalPageFile / DIV;
            DWORDLONG freePageKb = statex.ullAvailPageFile / DIV;
            DWORDLONG virtualKb = statex.ullTotalVirtual / DIV;
            DWORDLONG freeVirtualKb = statex.ullAvailVirtual / DIV;
            DWORDLONG freeExtKb = statex.ullAvailExtendedVirtual / DIV;

            printMessageLine("*************************************************");

            printMessageLine("Percent of memory in use", load);
            printMessageLine("KB of physical memory", physKb);
            printMessageLine("KB of free physical memory", freePhysKb);
            printMessageLine("KB of paging file", pageKb);
            printMessageLine("KB of free paging file", freePageKb);
            printMessageLine("KB of virtual memory", virtualKb);
            printMessageLine("KB of free virtual memory", freeVirtualKb);
            printMessageLine("KB of free extended memory", freeExtKb);

            printMessageLine("*************************************************");

        }

        if (WAIT_OBJECT_0 == ::WaitForSingleObject(exitEvent, 100))
        {
            break;
        }
    }

    inputThread.join();
    ::CloseHandle(exitEvent);
    printMessageLine("No longer monitoring memory consumption!");
}
<|endoftext|>


<commit_before>//branchLocations.cpp
//create two vectors from the given SMILES string that contain the indicies of the opening and closing parentheses

#include <iostream>
#include <vector>
#include <string>

std::vector<int> locations(std::string sample, char branch);

int main()
{
	std::string SMILES; //SMILES goes here

	char startBranch = '(';
	char endBranch = ')';

	std::vector<int> startResults = locations(SMILES, startBranch);
	std::vector<int> endResults = locations(SMILES, endBranch);

	system("pause");
	return 0;
}

std::vector<int> locations(std::string testString, char testChar)
{
	std::vector<int> characterLocations;
	for (int i = 0; i < testString.size(); i++)
	{
		if (testString[i] == testChar)
		{
			characterLocations.push_back(i); // gives the indicies of the instances of the chosen characters
		}
	}
	return characterLocations;

}<commit_msg>started working on files again<commit_after>//branchLocations.cpp
//create two vectors from the given SMILES string that contain the indicies of the opening and closing parentheses

#include <iostream>
#include <vector>
#include <string>

std::vector<int> locations(std::string sample, char branch);

int main() {
	std::cout << "Please input SMILES\n";
	std::string SMILES;
	std::cin >> SMILES; //SMILES goes here

	char startBranch = '(';
	char endBranch = ')';

	std::vector<int> startResults = locations(SMILES, startBranch);
	std::vector<int> endResults = locations(SMILES, endBranch);

	system("pause");
	return 0;
}

std::vector<int> locations(std::string testString, char testChar) {
	std::vector<int> characterLocations;
	for (int i = 0; i < testString.size(); i++)
	{
		if (testString[i] == testChar)
		{
			characterLocations.push_back(i); // gives the indicies of the instances of the chosen characters
		}
	}
	return characterLocations;

}<|endoftext|>


<commit_before>#include "GUI.hpp"

#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
#endif

namespace Slic3r { namespace GUI {

#if __APPLE__
IOPMAssertionID assertionID;
#endif

void
disable_screensaver()
{
    #if __APPLE__
    CFStringRef reasonForActivity = CFSTR("Slic3r");
    IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
        kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
    // ignore result: success == kIOReturnSuccess
    #elif _WIN32
    SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_CONTINUOUS);
    #endif
}

void
enable_screensaver()
{
    #if __APPLE__
    IOReturn success = IOPMAssertionRelease(assertionID);
    #elif _WIN32
    SetThreadExecutionState(ES_CONTINUOUS);
    #endif
}

bool
debugged()
{
    #ifdef _WIN32
    return IsDebuggerPresent();
	#else
	return false;
    #endif /* _WIN32 */
}

void
break_to_debugger()
{
    #ifdef _WIN32
    if (IsDebuggerPresent())
        DebugBreak();
    #endif /* _WIN32 */
}

} }
<commit_msg>Try to enforce the use of a high performance NVIDIA / ATI GPU on dual graphic card laptops.<commit_after>#include "GUI.hpp"

#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
extern "C" {
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
#endif

namespace Slic3r { namespace GUI {

#if __APPLE__
IOPMAssertionID assertionID;
#endif

void
disable_screensaver()
{
    #if __APPLE__
    CFStringRef reasonForActivity = CFSTR("Slic3r");
    IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
        kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
    // ignore result: success == kIOReturnSuccess
    #elif _WIN32
    SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_CONTINUOUS);
    #endif
}

void
enable_screensaver()
{
    #if __APPLE__
    IOReturn success = IOPMAssertionRelease(assertionID);
    #elif _WIN32
    SetThreadExecutionState(ES_CONTINUOUS);
    #endif
}

bool
debugged()
{
    #ifdef _WIN32
    return IsDebuggerPresent();
	#else
	return false;
    #endif /* _WIN32 */
}

void
break_to_debugger()
{
    #ifdef _WIN32
    if (IsDebuggerPresent())
        DebugBreak();
    #endif /* _WIN32 */
}

} }
<|endoftext|>


<commit_before>/*  This file is part of the KDE libraries and the Kate part.
 *
 *  Copyright (C) 2008-2011 Erlend Hamberg <ehamberg@gmail.com>
 *  Copyright (C) 2011 Svyatoslav Kuzmich <svatoslav1@gmail.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 */

#include "kateviinsertmode.h"
#include "kateviinputmodemanager.h"
#include "kateview.h"
#include "kateviewinternal.h"
#include "kateconfig.h"
#include "katecompletionwidget.h"
#include "kateglobal.h"
#include "katevikeyparser.h"

using KTextEditor::Cursor;

KateViInsertMode::KateViInsertMode( KateViInputModeManager *viInputModeManager,
    KateView * view, KateViewInternal * viewInternal ) : KateViModeBase()
{
  m_view = view;
  m_viewInternal = viewInternal;
  m_viInputModeManager = viInputModeManager;

  m_blockInsert = None;
  m_eolPos = 0;
  m_count = 1;
  m_countedRepeatsBeginOnNewLine = false;
}

KateViInsertMode::~KateViInsertMode()
{
}

bool KateViInsertMode::commandInsertFromAbove()
{
  Cursor c( m_view->cursorPosition() );

  if ( c.line() <= 0 ) {
    return false;
  }

  QString line = doc()->line( c.line()-1 );
  int tabWidth = doc()->config()->tabWidth();
  QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );

  if ( ch == QChar::Null ) {
    return false;
  }

  return doc()->insertText( c, ch  );
}

bool KateViInsertMode::commandInsertFromBelow()
{
  Cursor c( m_view->cursorPosition() );

  if ( c.line() >= doc()->lines()-1 ) {
    return false;
  }

  QString line = doc()->line( c.line()+1 );
  int tabWidth = doc()->config()->tabWidth();
  QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );

  if ( ch == QChar::Null ) {
    return false;
  }

  return doc()->insertText( c, ch );
}

bool KateViInsertMode::commandDeleteWord()
{
    Cursor c1( m_view->cursorPosition() );
    Cursor c2;

    c2 = findPrevWordStart( c1.line(), c1.column() );

    if ( c2.line() != c1.line() ) {
        if ( c1.column() == 0 ) {
            c2.setColumn( doc()->line( c2.line() ).length() );
        } else {
            c2.setColumn( 0 );
            c2.setLine( c2.line()+1 );
        }
    }

    KateViRange r( c2.line(), c2.column(), c1.line(), c1.column(), ViMotion::ExclusiveMotion );

    return deleteRange( r, CharWise, false );
}

bool KateViInsertMode::commandDeleteCharBackward()
{
    kDebug( 13070 ) << "Char backward!\n";
    Cursor c( m_view->cursorPosition() );

    KateViRange r( c.line(), c.column()-getCount(), c.line(), c.column(), ViMotion::ExclusiveMotion );

    if (c.column() == 0) {
        if (c.line() == 0) {
            return true;
        } else {
            r.startColumn = doc()->line(c.line()-1).length();
            r.startLine--;
      }
    }

    return deleteRange( r, CharWise );
}

bool KateViInsertMode::commandNewLine()
{
    doc()->newLine( m_view );
    return true;
}

bool KateViInsertMode::commandIndent()
{
    Cursor c( m_view->cursorPosition() );
    doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), 1 );
    return true;
}

bool KateViInsertMode::commandUnindent()
{
    Cursor c( m_view->cursorPosition() );
    doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), -1 );
    return true;
}

bool KateViInsertMode::commandToFirstCharacterInFile()
{
  Cursor c;

  c.setLine( 0 );
  c.setColumn( 0 );

  updateCursor( c );

  return true;
}

bool KateViInsertMode::commandToLastCharacterInFile()
{
  Cursor c;

  int lines = doc()->lines()-1;
  c.setLine( lines );
  c.setColumn( doc()->line( lines ).length() );

  updateCursor( c );

  return true;
}

bool KateViInsertMode::commandMoveOneWordLeft()
{
  Cursor c( m_view->cursorPosition() );
  c = findPrevWordStart( c.line(), c.column() );

  updateCursor( c );
  return true;
}

bool KateViInsertMode::commandMoveOneWordRight()
{
  Cursor c( m_view->cursorPosition() );
  c = findNextWordStart( c.line(), c.column() );

  updateCursor( c );
  return true;
}

bool KateViInsertMode::commandCompleteNext()
{
  // Completion may yield different results when performed
  // other places in the document. Therefore, repeat the
  // inserted text instead of the typed keystrokes.
  m_viInputModeManager->setTextualRepeat();
  if(m_view->completionWidget()->isCompletionActive()) {
    m_view->completionWidget()->cursorDown();
  } else {
    m_view->userInvokedCompletion();
  }
  return true;
}

bool KateViInsertMode::commandCompletePrevious()
{
  m_viInputModeManager->setTextualRepeat();
  if(m_view->completionWidget()->isCompletionActive()) {
    m_view->completionWidget()->cursorUp();
  } else {
    m_view->userInvokedCompletion();
    m_view->completionWidget()->bottom();
  }
  return true;
}

bool KateViInsertMode::commandInsertContentOfRegister(){
    Cursor c( m_view->cursorPosition() );
    Cursor cAfter = c;
    QChar reg = getChosenRegister( m_register );

    OperationMode m = getRegisterFlag( reg );
    QString textToInsert = getRegisterContent( reg );

    if ( textToInsert.isNull() ) {
      error(i18n("Nothing in register %1", reg ));
      return false;
    }

    if ( m == LineWise ) {
      textToInsert.chop( 1 ); // remove the last \n
      c.setColumn( doc()->lineLength( c.line() ) ); // paste after the current line and ...
      textToInsert.prepend( QChar( '\n' ) ); // ... prepend a \n, so the text starts on a new line

      cAfter.setLine( cAfter.line()+1 );
      cAfter.setColumn( 0 );
    }

    doc()->insertText( c, textToInsert, m == Block );

    updateCursor( cAfter );

    return true;
}

// Start Normal mode just for one command and return to Insert mode
bool KateViInsertMode::commandSwitchToNormalModeForJustOneCommand(){
    m_viInputModeManager->setTemporaryNormalMode(true);
    m_viInputModeManager->changeViMode(NormalMode);
    const Cursor cursorPos = m_view->cursorPosition();
    // If we're at end of the line, move the cursor back one step, as in Vim.
    if (doc()->line(cursorPos.line()).length() == cursorPos.column())
    {
      m_view->setCursorPosition(Cursor(cursorPos.line(), cursorPos.column() - 1));
    }
    m_view->setCaretStyle( KateRenderer::Block, true );
    m_view->updateViModeBarMode();
    m_viewInternal->repaint();
    return true;
}

/**
 * checks if the key is a valid command
 * @return true if a command was completed and executed, false otherwise
 */
bool KateViInsertMode::handleKeypress( const QKeyEvent *e )
{
  // backspace should work even if the shift key is down
  if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) {
    m_view->backspace();
    return true;
  }

  if(m_keys.isEmpty()){
  if ( e->modifiers() == Qt::NoModifier ) {
    switch ( e->key() ) {
    case Qt::Key_Escape:
      leaveInsertMode();
      return true;
      break;
    case Qt::Key_Left:
      m_view->cursorLeft();
      return true;
    case Qt::Key_Right:
      m_view->cursorRight();
      return true;
    case Qt::Key_Up:
      m_view->up();
      return true;
    case Qt::Key_Down:
      m_view->down();
      return true;
    case Qt::Key_Delete:
      m_view->keyDelete();
      return true;
    case Qt::Key_Home:
      m_view->home();
      return true;
    case Qt::Key_End:
      m_view->end();
      return true;
    case Qt::Key_PageUp:
      m_view->pageUp();
      return true;
    case Qt::Key_PageDown:
      m_view->pageDown();
      return true;
    default:
      return false;
      break;
    }
  } else if ( e->modifiers() == Qt::ControlModifier ) {
    switch( e->key() ) {
    case Qt::Key_BracketLeft:
    case Qt::Key_3:
      leaveInsertMode();
      return true;
      break;
    case Qt::Key_Space:
      commandCompleteNext();
      return true;
      break;
    case Qt::Key_C:
      leaveInsertMode( true );
      return true;
      break;
    case Qt::Key_D:
      commandUnindent();
      return true;
      break;
    case Qt::Key_E:
      commandInsertFromBelow();
      return true;
      break;
    case Qt::Key_N:
      commandCompleteNext();
      return true;
      break;
    case Qt::Key_P:
      commandCompletePrevious();
      return true;
      break;
    case Qt::Key_T:
      commandIndent();
      return true;
      break;
    case Qt::Key_W:
      commandDeleteWord();
      return true;
      break;
    case Qt::Key_J:
      commandNewLine();
      return true;
      break;
    case Qt::Key_H:
      commandDeleteCharBackward();
      return true;
      break;
    case Qt::Key_Y:
      commandInsertFromAbove();
      return true;
      break;
    case Qt::Key_O:
      commandSwitchToNormalModeForJustOneCommand();
      return true;
      break;
    case Qt::Key_Home:
      commandToFirstCharacterInFile();
      return true;
      break;
    case Qt::Key_R:
      m_keys = "cR";
      // Waiting for register
      return true;
      break;
    case Qt::Key_End:
      commandToLastCharacterInFile();
      return true;
      break;
    case Qt::Key_Left:
      commandMoveOneWordLeft();
      return true;
      break;
    case Qt::Key_Right:
      commandMoveOneWordRight();
      return true;
      break;
    default:
      return false;
    }
  }

  return false;
} else {

    // Was waiting for register for Ctrl-R
    if (m_keys == "cR"){
        QChar key = KateViKeyParser::self()->KeyEventToQChar(
                    e->key(),
                    e->text(),
                    e->modifiers(),
                    e->nativeScanCode() );
        key = key.toLower();

        // is it register ?
        if ( ( key >= '0' && key <= '9' ) || ( key >= 'a' && key <= 'z' ) ||
                key == '_' || key == '+' || key == '*' ) {
          m_register = key;
        } else {
          m_keys = "";
          return false;
        }
        commandInsertContentOfRegister();
        m_keys = "";
        return true;
    }
  }
  return false;
}

// leave insert mode when esc, etc, is pressed. if leaving block
// prepend/append, the inserted text will be added to all block lines. if
// ctrl-c is used to exit insert mode this is not done.
void KateViInsertMode::leaveInsertMode( bool force )
{
    if ( !force && m_blockInsert != None ) { // block append/prepend

        // make sure cursor haven't been moved
        if ( m_blockRange.startLine == m_view->cursorPosition().line() ) {
            int start, len;
            QString added;
            Cursor c;

            switch ( m_blockInsert ) {
            case Append:
            case Prepend:
                if ( m_blockInsert == Append ) {
                    start = m_blockRange.endColumn+1;
                } else {
                    start = m_blockRange.startColumn;
                }

                len = m_view->cursorPosition().column()-start;
                added = getLine().mid( start, len );

                c = Cursor( m_blockRange.startLine, start );
                for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {
                    c.setLine( i );
                    doc()->insertText( c, added );
                }
                break;
            case AppendEOL:
                start = m_eolPos;
                len = m_view->cursorPosition().column()-start;
                added = getLine().mid( start, len );

                c = Cursor( m_blockRange.startLine, start );
                for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {
                    c.setLine( i );
                    c.setColumn( doc()->lineLength( i ) );
                    doc()->insertText( c, added );
                }
                break;
            default:
                error("not supported");
            }
        }

        m_blockInsert = None;
    }
    else if (!force)
    {
        const QString added = doc()->text(Range(m_viInputModeManager->getMarkPosition('^'), m_view->cursorPosition()));

        if (m_count > 1)
        {
            for (unsigned int i = 0; i < m_count - 1; i++)
            {
                if (m_countedRepeatsBeginOnNewLine)
                {
                    doc()->newLine(m_view);
                }
                doc()->insertText( m_view->cursorPosition(), added );
            }
        }
        m_countedRepeatsBeginOnNewLine = false;
    }
    startNormalMode();
}

void KateViInsertMode::setBlockPrependMode( KateViRange blockRange )
{
    // ignore if not more than one line is selected
    if ( blockRange.startLine != blockRange.endLine ) {
        m_blockInsert = Prepend;
        m_blockRange = blockRange;
    }
}

void KateViInsertMode::setBlockAppendMode( KateViRange blockRange, BlockInsert b )
{
    Q_ASSERT( b == Append || b == AppendEOL );

    // ignore if not more than one line is selected
    if ( blockRange.startLine != blockRange.endLine ) {
        m_blockRange = blockRange;
        m_blockInsert = b;
        if ( b == AppendEOL ) {
          m_eolPos = doc()->lineLength( m_blockRange.startLine );
        }
    } else {
        kDebug( 13070 ) << "cursor moved. ignoring block append/prepend";
    }
}
<commit_msg>Refactor this if ... else slightly.<commit_after>/*  This file is part of the KDE libraries and the Kate part.
 *
 *  Copyright (C) 2008-2011 Erlend Hamberg <ehamberg@gmail.com>
 *  Copyright (C) 2011 Svyatoslav Kuzmich <svatoslav1@gmail.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 */

#include "kateviinsertmode.h"
#include "kateviinputmodemanager.h"
#include "kateview.h"
#include "kateviewinternal.h"
#include "kateconfig.h"
#include "katecompletionwidget.h"
#include "kateglobal.h"
#include "katevikeyparser.h"

using KTextEditor::Cursor;

KateViInsertMode::KateViInsertMode( KateViInputModeManager *viInputModeManager,
    KateView * view, KateViewInternal * viewInternal ) : KateViModeBase()
{
  m_view = view;
  m_viewInternal = viewInternal;
  m_viInputModeManager = viInputModeManager;

  m_blockInsert = None;
  m_eolPos = 0;
  m_count = 1;
  m_countedRepeatsBeginOnNewLine = false;
}

KateViInsertMode::~KateViInsertMode()
{
}

bool KateViInsertMode::commandInsertFromAbove()
{
  Cursor c( m_view->cursorPosition() );

  if ( c.line() <= 0 ) {
    return false;
  }

  QString line = doc()->line( c.line()-1 );
  int tabWidth = doc()->config()->tabWidth();
  QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );

  if ( ch == QChar::Null ) {
    return false;
  }

  return doc()->insertText( c, ch  );
}

bool KateViInsertMode::commandInsertFromBelow()
{
  Cursor c( m_view->cursorPosition() );

  if ( c.line() >= doc()->lines()-1 ) {
    return false;
  }

  QString line = doc()->line( c.line()+1 );
  int tabWidth = doc()->config()->tabWidth();
  QChar ch = getCharAtVirtualColumn( line, m_view->virtualCursorColumn(), tabWidth );

  if ( ch == QChar::Null ) {
    return false;
  }

  return doc()->insertText( c, ch );
}

bool KateViInsertMode::commandDeleteWord()
{
    Cursor c1( m_view->cursorPosition() );
    Cursor c2;

    c2 = findPrevWordStart( c1.line(), c1.column() );

    if ( c2.line() != c1.line() ) {
        if ( c1.column() == 0 ) {
            c2.setColumn( doc()->line( c2.line() ).length() );
        } else {
            c2.setColumn( 0 );
            c2.setLine( c2.line()+1 );
        }
    }

    KateViRange r( c2.line(), c2.column(), c1.line(), c1.column(), ViMotion::ExclusiveMotion );

    return deleteRange( r, CharWise, false );
}

bool KateViInsertMode::commandDeleteCharBackward()
{
    kDebug( 13070 ) << "Char backward!\n";
    Cursor c( m_view->cursorPosition() );

    KateViRange r( c.line(), c.column()-getCount(), c.line(), c.column(), ViMotion::ExclusiveMotion );

    if (c.column() == 0) {
        if (c.line() == 0) {
            return true;
        } else {
            r.startColumn = doc()->line(c.line()-1).length();
            r.startLine--;
      }
    }

    return deleteRange( r, CharWise );
}

bool KateViInsertMode::commandNewLine()
{
    doc()->newLine( m_view );
    return true;
}

bool KateViInsertMode::commandIndent()
{
    Cursor c( m_view->cursorPosition() );
    doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), 1 );
    return true;
}

bool KateViInsertMode::commandUnindent()
{
    Cursor c( m_view->cursorPosition() );
    doc()->indent( KTextEditor::Range( c.line(), 0, c.line(), 0), -1 );
    return true;
}

bool KateViInsertMode::commandToFirstCharacterInFile()
{
  Cursor c;

  c.setLine( 0 );
  c.setColumn( 0 );

  updateCursor( c );

  return true;
}

bool KateViInsertMode::commandToLastCharacterInFile()
{
  Cursor c;

  int lines = doc()->lines()-1;
  c.setLine( lines );
  c.setColumn( doc()->line( lines ).length() );

  updateCursor( c );

  return true;
}

bool KateViInsertMode::commandMoveOneWordLeft()
{
  Cursor c( m_view->cursorPosition() );
  c = findPrevWordStart( c.line(), c.column() );

  updateCursor( c );
  return true;
}

bool KateViInsertMode::commandMoveOneWordRight()
{
  Cursor c( m_view->cursorPosition() );
  c = findNextWordStart( c.line(), c.column() );

  updateCursor( c );
  return true;
}

bool KateViInsertMode::commandCompleteNext()
{
  // Completion may yield different results when performed
  // other places in the document. Therefore, repeat the
  // inserted text instead of the typed keystrokes.
  m_viInputModeManager->setTextualRepeat();
  if(m_view->completionWidget()->isCompletionActive()) {
    m_view->completionWidget()->cursorDown();
  } else {
    m_view->userInvokedCompletion();
  }
  return true;
}

bool KateViInsertMode::commandCompletePrevious()
{
  m_viInputModeManager->setTextualRepeat();
  if(m_view->completionWidget()->isCompletionActive()) {
    m_view->completionWidget()->cursorUp();
  } else {
    m_view->userInvokedCompletion();
    m_view->completionWidget()->bottom();
  }
  return true;
}

bool KateViInsertMode::commandInsertContentOfRegister(){
    Cursor c( m_view->cursorPosition() );
    Cursor cAfter = c;
    QChar reg = getChosenRegister( m_register );

    OperationMode m = getRegisterFlag( reg );
    QString textToInsert = getRegisterContent( reg );

    if ( textToInsert.isNull() ) {
      error(i18n("Nothing in register %1", reg ));
      return false;
    }

    if ( m == LineWise ) {
      textToInsert.chop( 1 ); // remove the last \n
      c.setColumn( doc()->lineLength( c.line() ) ); // paste after the current line and ...
      textToInsert.prepend( QChar( '\n' ) ); // ... prepend a \n, so the text starts on a new line

      cAfter.setLine( cAfter.line()+1 );
      cAfter.setColumn( 0 );
    }

    doc()->insertText( c, textToInsert, m == Block );

    updateCursor( cAfter );

    return true;
}

// Start Normal mode just for one command and return to Insert mode
bool KateViInsertMode::commandSwitchToNormalModeForJustOneCommand(){
    m_viInputModeManager->setTemporaryNormalMode(true);
    m_viInputModeManager->changeViMode(NormalMode);
    const Cursor cursorPos = m_view->cursorPosition();
    // If we're at end of the line, move the cursor back one step, as in Vim.
    if (doc()->line(cursorPos.line()).length() == cursorPos.column())
    {
      m_view->setCursorPosition(Cursor(cursorPos.line(), cursorPos.column() - 1));
    }
    m_view->setCaretStyle( KateRenderer::Block, true );
    m_view->updateViModeBarMode();
    m_viewInternal->repaint();
    return true;
}

/**
 * checks if the key is a valid command
 * @return true if a command was completed and executed, false otherwise
 */
bool KateViInsertMode::handleKeypress( const QKeyEvent *e )
{
  // backspace should work even if the shift key is down
  if (e->modifiers() != Qt::ControlModifier && e->key() == Qt::Key_Backspace ) {
    m_view->backspace();
    return true;
  }

  if(m_keys.isEmpty()){
  if ( e->modifiers() == Qt::NoModifier ) {
    switch ( e->key() ) {
    case Qt::Key_Escape:
      leaveInsertMode();
      return true;
      break;
    case Qt::Key_Left:
      m_view->cursorLeft();
      return true;
    case Qt::Key_Right:
      m_view->cursorRight();
      return true;
    case Qt::Key_Up:
      m_view->up();
      return true;
    case Qt::Key_Down:
      m_view->down();
      return true;
    case Qt::Key_Delete:
      m_view->keyDelete();
      return true;
    case Qt::Key_Home:
      m_view->home();
      return true;
    case Qt::Key_End:
      m_view->end();
      return true;
    case Qt::Key_PageUp:
      m_view->pageUp();
      return true;
    case Qt::Key_PageDown:
      m_view->pageDown();
      return true;
    default:
      return false;
      break;
    }
  } else if ( e->modifiers() == Qt::ControlModifier ) {
    switch( e->key() ) {
    case Qt::Key_BracketLeft:
    case Qt::Key_3:
      leaveInsertMode();
      return true;
      break;
    case Qt::Key_Space:
      commandCompleteNext();
      return true;
      break;
    case Qt::Key_C:
      leaveInsertMode( true );
      return true;
      break;
    case Qt::Key_D:
      commandUnindent();
      return true;
      break;
    case Qt::Key_E:
      commandInsertFromBelow();
      return true;
      break;
    case Qt::Key_N:
      commandCompleteNext();
      return true;
      break;
    case Qt::Key_P:
      commandCompletePrevious();
      return true;
      break;
    case Qt::Key_T:
      commandIndent();
      return true;
      break;
    case Qt::Key_W:
      commandDeleteWord();
      return true;
      break;
    case Qt::Key_J:
      commandNewLine();
      return true;
      break;
    case Qt::Key_H:
      commandDeleteCharBackward();
      return true;
      break;
    case Qt::Key_Y:
      commandInsertFromAbove();
      return true;
      break;
    case Qt::Key_O:
      commandSwitchToNormalModeForJustOneCommand();
      return true;
      break;
    case Qt::Key_Home:
      commandToFirstCharacterInFile();
      return true;
      break;
    case Qt::Key_R:
      m_keys = "cR";
      // Waiting for register
      return true;
      break;
    case Qt::Key_End:
      commandToLastCharacterInFile();
      return true;
      break;
    case Qt::Key_Left:
      commandMoveOneWordLeft();
      return true;
      break;
    case Qt::Key_Right:
      commandMoveOneWordRight();
      return true;
      break;
    default:
      return false;
    }
  }

  return false;
} else {

    // Was waiting for register for Ctrl-R
    if (m_keys == "cR"){
        QChar key = KateViKeyParser::self()->KeyEventToQChar(
                    e->key(),
                    e->text(),
                    e->modifiers(),
                    e->nativeScanCode() );
        key = key.toLower();

        // is it register ?
        if ( ( key >= '0' && key <= '9' ) || ( key >= 'a' && key <= 'z' ) ||
                key == '_' || key == '+' || key == '*' ) {
          m_register = key;
        } else {
          m_keys = "";
          return false;
        }
        commandInsertContentOfRegister();
        m_keys = "";
        return true;
    }
  }
  return false;
}

// leave insert mode when esc, etc, is pressed. if leaving block
// prepend/append, the inserted text will be added to all block lines. if
// ctrl-c is used to exit insert mode this is not done.
void KateViInsertMode::leaveInsertMode( bool force )
{
    if ( !force )
    {
      if ( m_blockInsert != None ) { // block append/prepend

          // make sure cursor haven't been moved
          if ( m_blockRange.startLine == m_view->cursorPosition().line() ) {
              int start, len;
              QString added;
              Cursor c;

              switch ( m_blockInsert ) {
              case Append:
              case Prepend:
                  if ( m_blockInsert == Append ) {
                      start = m_blockRange.endColumn+1;
                  } else {
                      start = m_blockRange.startColumn;
                  }

                  len = m_view->cursorPosition().column()-start;
                  added = getLine().mid( start, len );

                  c = Cursor( m_blockRange.startLine, start );
                  for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {
                      c.setLine( i );
                      doc()->insertText( c, added );
                  }
                  break;
              case AppendEOL:
                  start = m_eolPos;
                  len = m_view->cursorPosition().column()-start;
                  added = getLine().mid( start, len );

                  c = Cursor( m_blockRange.startLine, start );
                  for ( int i = m_blockRange.startLine+1; i <= m_blockRange.endLine; i++ ) {
                      c.setLine( i );
                      c.setColumn( doc()->lineLength( i ) );
                      doc()->insertText( c, added );
                  }
                  break;
              default:
                  error("not supported");
              }
          }

          m_blockInsert = None;
      }
      else
      {
          const QString added = doc()->text(Range(m_viInputModeManager->getMarkPosition('^'), m_view->cursorPosition()));

          if (m_count > 1)
          {
              for (unsigned int i = 0; i < m_count - 1; i++)
              {
                  if (m_countedRepeatsBeginOnNewLine)
                  {
                      doc()->newLine(m_view);
                  }
                  doc()->insertText( m_view->cursorPosition(), added );
              }
          }
          m_countedRepeatsBeginOnNewLine = false;
      }
    }
    startNormalMode();
}

void KateViInsertMode::setBlockPrependMode( KateViRange blockRange )
{
    // ignore if not more than one line is selected
    if ( blockRange.startLine != blockRange.endLine ) {
        m_blockInsert = Prepend;
        m_blockRange = blockRange;
    }
}

void KateViInsertMode::setBlockAppendMode( KateViRange blockRange, BlockInsert b )
{
    Q_ASSERT( b == Append || b == AppendEOL );

    // ignore if not more than one line is selected
    if ( blockRange.startLine != blockRange.endLine ) {
        m_blockRange = blockRange;
        m_blockInsert = b;
        if ( b == AppendEOL ) {
          m_eolPos = doc()->lineLength( m_blockRange.startLine );
        }
    } else {
        kDebug( 13070 ) << "cursor moved. ignoring block append/prepend";
    }
}
<|endoftext|>