Esempio n. 1
0
static PyObject* PyView_select(PyView *o, PyObject* _args, PyObject* kwargs) {
  try {
    c4_Row temp;
    PWOSequence args(_args);
    if (args.len() == 0) 
    {
      o->makeRow(temp, kwargs, false);
      return new PyView(o->Select(temp), o, o->computeState(NOTIFIABLE));
    }
    if (args.len() == 1) 
    {
      o->makeRow(temp, args[0], false);
      return new PyView(o->Select(temp), o, o->computeState(NOTIFIABLE));
    }

    if (PyObject_Length(args[0]) > 0)
      o->makeRow(temp, args[0], false);

    c4_Row temp2; // force an error if neither boundary has useful values
    if (temp.Container().NumProperties() == 0 || PyObject_Length(args[1]) > 0)
      o->makeRow(temp2, args[1], false);
    
    return new PyView(o->SelectRange(temp, temp2), o, o->computeState(NOTIFIABLE));
  }
  catch (...) { return 0; }
}
bool TuplesDefaultImpl::m_parse(va_list ap)
{
  bool ret_val = false;
  TupleInDefaultImpl *ptupleIn = m_current_tuple_in();


  if (!m_tuple)
  {
    /*
    NOTE в режиме execute не исключено значение m_tuple = NULL; это означает, что:
      -- для функции PyNoArgsFunction (флаг METH_NOARGS) вызывается проверка аргументов
      -- метод создан только для получения данных (TupleFillState::modGetter)
    в обоих случаях исключение сработает раньше -- в TupleState::parse
    */
    throw ArgsException();
  }

  try
  {
    char * const * keywords = ptupleIn->keywords();
    if
    (
        ptupleIn->args().empty() && !PyObject_Length(m_tuple) && (!m_kw || !PyObject_Length(m_kw))
      || m_kw && PyArg_VaParseTupleAndKeywords(m_tuple, m_kw, ptupleIn->format().c_str(), const_cast<char **>(keywords), ap)
      || !m_kw && PyArg_VaParse(m_tuple, ptupleIn->format().c_str(), ap)
    )
    {
      ret_val = true;
    }
  }
  catch (const TupleBase::FormatException &ex)
  {
    /*TODO
    Возможно правильнее было бы перехватить здесь исключение
    Вопрос особенно актуален, когда сигнатур несколько и большая часть из них правильные
    см также function_dublicate в pytest_pyhrol_keywords.cpp -- этот эффект будет ликвидирован, а многие тесты будут провалены
    ptupleIn->parseError = ex.what();
    */
    throw;
  }

  if (!ret_val && PyErr_Occurred())
  {
    PyObject *ptype, *pvalue, *ptraceback;
    PyErr_Fetch(&ptype, &pvalue, &ptraceback);

    const char *pStrErrorMessage = PyString_AsString(pvalue);
    if (pStrErrorMessage)
    {
      ptupleIn->parseError = pStrErrorMessage;
    }
    Py_DecRef(ptype);
    Py_DecRef(pvalue);
    Py_DecRef(ptraceback);
    PyErr_Clear();
  }

  return ret_val;
}
Esempio n. 3
0
int DippyDecompApp::generateCuts(const double* x, DecompCutList& cutList)
{
   if (!m_pyGenerateCuts) {
      return 0;
   }

   // PyObject *pSolutionList = pyTupleList_FromDoubleArray(x, m_colList);
   // MO (28/2/2012) - Don't need this anymore as solution is contained within node
   PyObject* pPackagedNode = pyTupleList_FromNode(getDecompAlgo(), STAT_FEASIBLE);
   PyObject* pCutList = PyObject_CallMethod(m_pProb, "generateCuts", "O", pPackagedNode);

   if (pCutList == NULL) {
      throw UtilException("Error calling method prob.generateCuts()", "generateCuts", "DippyDecompApp");
   }

   // This should never happen, pyGenerateCuts should be set to false in dippy.py
   if (pCutList == Py_None)
      // method exists, but is not implemented, return 0
   {
      return 0;
   }

   // generateCuts returns constraints, i.e., dictionary of (variable, value) pairs also with name, lb, ub
   const int len = PyObject_Length(pCutList);
   // loop through each cut
   // We can use these to construct a C++ DecompVar objects
   double lb, ub;
   PyObject *pLb, *pUb;
   string name;
   double value;

   for (int i = 0; i < len; i++) {
      PyObject* pRow = PySequence_GetItem(pCutList, i);
      pLb = PyObject_CallMethod(pRow, "getLb", NULL);

      if (pLb == NULL) {
         throw UtilException("Error calling method row.getLb()", "generateCuts", "DippyDecompApp");
      }

      pUb = PyObject_CallMethod(pRow, "getUb", NULL);

      if (pUb == NULL) {
         throw UtilException("Error calling method row.getUb()", "generateCuts", "DippyDecompApp");
      }

      lb = (pLb == Py_None) ? -m_infinity : PyFloat_AsDouble(pLb);
      ub = (pUb == Py_None) ?  m_infinity : PyFloat_AsDouble(pUb);
      int*     varInds = NULL;
      double* varVals = NULL;
      int numPairs = pyColDict_AsPackedArrays(pRow, m_colIndices, &varInds, &varVals);
      assert(numPairs == PyObject_Length(pRow));
      // arrays are now owned by the Cut object
      DippyDecompCut* cut =  new DippyDecompCut(lb, ub, numPairs, varInds, varVals);
      cutList.push_back(cut);
   }

   return len;
}
Esempio n. 4
0
int parse_board(PyObject *board, QuartoBoard *newBoard)
{
	//Board must be 4x4!
	int outer_size, inner_size = 0;
	outer_size = PyObject_Length(board);
	if(outer_size > 0){
		inner_size = PyObject_Length(PySequence_GetItem(board, 0));
	}
	if(outer_size != 4 || inner_size != 4){
		PyErr_SetString(PyExc_TypeError, "The array passed into this function\
is not a 4x4 array");
		return 0;
	}
Esempio n. 5
0
void CopyTranslationTable(Normalizer *self, PyObject *table) {
    
    int i;

    self->table = PyList_New(0);

    table = PySequence_Fast(table, "argument must be sequence"); 

    for (i=0; i<PyObject_Length(table); i++) {
        PyObject *item, *key, *value, *tp;

        item = PySequence_Fast_GET_ITEM(table, i);

        key   = PyTuple_GetItem(item,0);
        value = PyTuple_GetItem(item,1);

        if (PyString_Check(key))  
            key = PyUnicode_FromEncodedObject(key, self->encoding,"strict");
        else Py_XINCREF(key);

        if (PyString_Check(value)) 
            value = PyUnicode_FromEncodedObject(value, self->encoding,"strict");
        else Py_XINCREF(value);

        tp = Py_BuildValue("(OO)",key,value);
        PyList_Append(self->table, tp);
    
        Py_DECREF(tp);
        Py_DECREF(value);
        Py_DECREF(key);
    }

    Py_DECREF(table);
}
static int
proxy_length(PyWeakReference *proxy)
{
    if (!proxy_checkref(proxy))
        return -1;
    return PyObject_Length(PyWeakref_GET_OBJECT(proxy));
}
STDMETHODIMP PyGEnumDebugStackFrames::Next( 
            /* [in] */ ULONG celt,
            /* [length_is][size_is][out] */ DebugStackFrameDescriptor __RPC_FAR *rgVar,
            /* [out] */ ULONG __RPC_FAR *pCeltFetched)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	Py_ssize_t len;
	HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt);
	if ( FAILED(hr) )
		return hr;

	if ( !PySequence_Check(result) )
		goto error;
	len = PyObject_Length(result);
	if ( len == -1 )
		goto error;
	if ( len > (Py_ssize_t)celt)
		len = celt;

	if ( pCeltFetched )
		*pCeltFetched = PyWin_SAFE_DOWNCAST(len, Py_ssize_t, ULONG);

	Py_ssize_t i;
	for ( i = 0; i < len; ++i )
	{
		PyObject *ob = PySequence_GetItem(result, i);
		if ( ob == NULL )
			goto error;
		if (!PyTuple_Check(ob)) {
			Py_DECREF(ob);
			PyErr_SetString(PyExc_TypeError, "PyIEnumDebugStackFrames::Next must return a tuple.");
			goto error;
		}
		PyObject *obEnum, *obUnk;
		if (!PyArg_ParseTuple(ob, "OiiiO", &obEnum, &rgVar[i].dwMin, &rgVar[i].dwLim, &rgVar[i].fFinal, &obUnk)) {
			Py_DECREF(ob);
			goto error;
		}

		if ( !PyCom_InterfaceFromPyInstanceOrObject(obEnum, IID_IDebugStackFrame, (void **)&rgVar[i].pdsf, FALSE) ||
		     !PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&rgVar[i].punkFinal, TRUE) )
		{
			Py_DECREF(ob);
			Py_DECREF(result);
			return PyCom_SetCOMErrorFromPyException(IID_IEnumDebugStackFrames);
		}
		Py_DECREF(ob);
	}

	Py_DECREF(result);

	return len < (Py_ssize_t)celt ? S_FALSE : S_OK;

  error:
	hr = PyErr_Occurred() ? PyCom_SetCOMErrorFromPyException(IID_IEnumDebugStackFrames)
		                          : PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnumDebugStackFrames);
	Py_DECREF(result);
	return hr;
}
Esempio n. 8
0
static PyObject *
_mysql_escape_sequence(
	PyObject *self,
	PyObject *args)
{
	PyObject *o=NULL, *d=NULL, *r=NULL, *item, *quoted;
	int i, n;
	if (!PyArg_ParseTuple(args, "OO:escape_sequence", &o, &d))
		goto error;
	if (!PyMapping_Check(d)) {
              PyErr_SetString(PyExc_TypeError,
                              "argument 2 must be a mapping");
              return NULL;
        }
	if ((n = PyObject_Length(o)) == -1) goto error;
	if (!(r = PyTuple_New(n))) goto error;
	for (i=0; i<n; i++) {
		item = PySequence_GetItem(o, i);
		if (!item) goto error;
		quoted = _escape_item(item, d);
		Py_DECREF(item);
		if (!quoted) goto error;
		PyTuple_SET_ITEM(r, i, quoted);
	}
	return r;
  error:
	Py_XDECREF(r);
	return NULL;
}
Esempio n. 9
0
/* assumes dest is already correct type. */
static int
python_to_array(ConvertInfo *info, PyObject *pyobj, avro_value_t *dest)
{
    int rval;
    Py_ssize_t i;
    Py_ssize_t element_count;

    element_count = PyObject_Length(pyobj);

    if (element_count < 0) {
        set_error_prefix("while finding length for array: ");
        return EINVAL;
    }

    for (i = 0; i < element_count; i++) {
        PyObject *pyval = PySequence_GetItem(pyobj, i);
        avro_value_t child;

        avro_value_append(dest, &child, NULL);
        rval = python_to_avro(info, pyval, &child);
        Py_DECREF(pyval);
        if (rval) {
            return rval;
        }
    }

    return 0;
}
Esempio n. 10
0
int set_all(PyObject *target, PyObject *item)
{
	int i, n;

	n = PyObject_Length(target);
	if(n < 0)
	{
		return -1;
	}

	for(i=0; i<n; ++i)
	{
		PyObject *index = PyInt_FromLong(i);
		if(index == NULL)
		{
			return -1;
		}

		if(PyObject_SetItem(target, index, item) < 0)
		{
			Py_DECREF(index);
			return -1;
		}
		Py_DECREF(index);
	}

	return 0;
}
Esempio n. 11
0
static c_module::matrix_t pyobject_to_cxx(PyObject * py_matrix)
{
	c_module::matrix_t result;
	result.resize(PyObject_Length(py_matrix));
	for (size_t i=0; i<result.size(); ++i) {
		PyObject * py_row = PyList_GetItem(py_matrix, i);
		c_module::row_t & row = result[i];
		row.resize(PyObject_Length(py_row));
		for (size_t j=0; j<row.size(); ++j) {
			PyObject * py_elem = PyList_GetItem(py_row, j);
			const double elem = PyFloat_AsDouble(py_elem);
			row[j] = elem;
		}
	}
	return result;
}
Esempio n. 12
0
void TuplesDefaultImpl::m_parse_no_arg()
{
  if (m_tuple && PyObject_Length(m_tuple))
  {
    throw ParseException ();
  }
}
Esempio n. 13
0
BOOL CATIDsFromPyObject( PyObject *obCatIds, CATID **ppCatIds, UINT *pNumIds)
{
    if (!PySequence_Check(obCatIds)) {
        PyErr_SetString(PyExc_TypeError, "Object must be a sequence of CATIDs");
        return FALSE;
    }
    Py_ssize_t len = PyObject_Length(obCatIds);
    CATID *ids = new CATID[len];
    BOOL rc = TRUE;
    for (Py_ssize_t i=0; rc && i<len; i++) {
        PyObject *obThis = PySequence_GetItem(obCatIds, i);
        if (obThis==NULL) {
            rc = FALSE;
            break;
        }
        if (!PyWinObject_AsIID(obThis, ids+i)) {
            PyErr_SetString(PyExc_TypeError, "CATID is not valid");
            rc = FALSE;
        }
        Py_DECREF(obThis);
    }
    if (rc) {
        *ppCatIds = ids;
        *pNumIds = PyWin_SAFE_DOWNCAST(len, Py_ssize_t, UINT);
    } else {
        delete [] ids;
    }
    return rc;
}
Esempio n. 14
0
void mat_process_iterable_object(PyObject *obj, char *error_msg)
{
        int length;
        PyObject *iterator, *item;
        
        length = PyObject_Length(obj);

        MLPutFunction(stdlink, "List", 1);
        MLPutFunction(stdlink, "Sequence", length);
        
        iterator = PyObject_GetIter(obj);
        
        if(iterator==NULL) {
            MLPutString(stdlink, error_msg);
            return;
        }
        
        while(item = PyIter_Next(iterator)) {
            python_to_mathematica_object(item);
            Py_DECREF(item);
        }
        
        Py_DECREF(iterator);

        return;
}
Esempio n. 15
0
run_user_validation(char *ofile)
{
    int i, status;                /* should also check status everywhere */
    char *errors, *warnings;
    PyObject *results, *orders, *nextorder=NULL;
    Py_Initialize();
    PyRun_SimpleString("import sys; sys.path.append('..')");
    PP_Run_Function("inventory", "load_orders", "O", &orders, "(s)", ofile);

    PP_Run_Function("inventory", "print_files", "", NULL, "()");    
    for (i=0; i < PyObject_Length(orders); i++) {                   /* len(x) */
        Py_XDECREF(nextorder);
        nextorder = PyObject_GetItem(orders, PyInt_FromLong(i));    /* x[i] */
        printf("\n%d ", i);
        PyObject_Print(nextorder, stdout, 0);
        printf("\n");

        status = PP_Run_Function(                /* validate2.validate(p,q,b) */
                         "validate2", "validate",  
                         "O",          &results,
                         "O",          nextorder);
        if (status == -1) {
            printf("Python error during validation.\n");
            PyErr_Print();  /* show traceback */
            continue;
        }
        PyArg_Parse(results, "(ss)", &warnings, &errors);
        printf("errors:   %s\n", strlen(errors)? errors : "none"); 
        printf("warnings: %s\n", strlen(warnings)? warnings : "none"); 
        Py_DECREF(results);  /* ok to free strings */
        PP_Run_Function("inventory", "print_files", "", NULL, "()");    
    }
}
Esempio n. 16
0
/**
 * APPheuristics callback
 *
 * Called by DIP, we interface with Python
 */
int DippyDecompApp::APPheuristics(const double* xhat, const double* origCost, vector<DecompSolution*>& xhatIPFeas)
{
   if (!m_pyHeuristics) {
      return 0;
   }

   PyObject* pSolution = pyTupleList_FromDoubleArray(xhat, m_colList);
   PyObject* pObjective = pyTupleList_FromDoubleArray(origCost, m_colList);
   PyObject* pSolList = PyObject_CallMethod(m_pProb, "solveHeuristics", "OO", pSolution, pObjective);

   if (pSolList == NULL) {
      throw UtilException("Error calling method prob.solveHeuristics()", "APPheuristics", "DippyDecompApp");
   }

   // This should never happen, pyHeuristics should be set to false in dippy.py
   if (pSolList == Py_None)
      // method exists, but is not implemented, return 0
   {
      return 0;
   }

   // APPheuristics returns dictionary of (variable, value) pairs
   const int len = PyObject_Length(pSolList);

   // loop through each solution
   for (int i = 0; i < len; i++) {
      pSolution = PyList_GetItem(pSolList, i);
      int*     varInds = NULL;
      double* varVals = NULL;
      int numPairs = pyColDict_AsPackedArrays(pSolution, m_colIndices, &varInds, &varVals);
      assert(numPairs == PyObject_Length(pSolution));
      double* sol = new double[m_numCols];
      UtilFillN(sol, m_numCols, 0.0);

      for (int j = 0; j < numPairs; j++) {
         sol[varInds[j]] = varVals[j];
      }

      xhatIPFeas.push_back(new DecompSolution(m_numCols, sol, origCost));
      delete [] sol;
      delete [] varInds;
      delete [] varVals;
   }

   return len;
}
Esempio n. 17
0
// @pymethod |PyICatRegister|RegisterCategories|Registers one or more component categories. Each component category consists of a CATID and a list of locale-dependent description strings.
PyObject *PyICatRegister::RegisterCategories(PyObject *self, PyObject *args)
{
    PyObject *obCatList;
    // @pyparm [ (<o PyIID>, int, string), ...]|[ (catId, lcid, description), ...]||A sequence of category descriptions.
    if ( !PyArg_ParseTuple(args, "O:RegisterCategories", &obCatList) )
        return NULL;

    ICatRegister *pICR = GetI(self);
    if ( pICR == NULL )
        return NULL;

    if (!PySequence_Check(obCatList)) {
        PyErr_SetString(PyExc_TypeError, "Argument must be a list of CATEGORYINFO tuples");
        return NULL;
    }
    Py_ssize_t noInfos = PyObject_Length(obCatList);
    CATEGORYINFO *infos = new CATEGORYINFO [noInfos];
    if (infos==NULL) {
        PyErr_SetString(PyExc_MemoryError, "Allocating CATEGORYINFO array");
        return NULL;
    }
    for (Py_ssize_t i=0; i<noInfos; i++) {
        PyObject *obCatId;
        PyObject *obThis = PySequence_GetItem(obCatList, i);
        if (obThis==NULL) return NULL;
        BOOL ok = TRUE;
        PyObject *obDesc;
        if (!PyArg_ParseTuple(obThis, "OlO", &obCatId, (long *)&infos[i].lcid, &obDesc)) {
            Py_DECREF(obThis);
            PyErr_SetString(PyExc_TypeError, "Category infos must be CATID, lcid, description");
            delete [] infos;
            return NULL;
        }
        Py_DECREF(obThis);
        if (!PyWinObject_AsIID(obCatId, &infos[i].catid)) {
            delete [] infos;
            return NULL;
        }
        OLECHAR *oc;
        if (!PyWinObject_AsWCHAR(obDesc, &oc, FALSE)) {
            delete [] infos;
            return NULL;
        }
        wcsncpy(infos[i].szDescription, oc,
                sizeof(infos->szDescription)/sizeof(infos->szDescription[0]));
        PyWinObject_FreeWCHAR(oc);
    }

    PY_INTERFACE_PRECALL;
    HRESULT hr = pICR->RegisterCategories(PyWin_SAFE_DOWNCAST(noInfos, Py_ssize_t, ULONG),
                                          infos);
    PY_INTERFACE_POSTCALL;
    delete [] infos;
    if ( FAILED(hr) )
        return PyCom_BuildPyException(hr, pICR, IID_ICatRegister);
    Py_INCREF(Py_None);
    return Py_None;
}
Esempio n. 18
0
static PyObject *
PyTuple_NewByPreappending(PyObject *firstObject, PyObject *tuple)
{
    PyObject *result = PyTuple_New(PyObject_Length(tuple) + 1);

    PyTuple_SetItem(result, 0, firstObject);
    Py_XINCREF(firstObject);

    unsigned i;

    for (i = 0; i < PyObject_Length(tuple); ++i) {
        PyObject *member = PyTuple_GetItem(tuple, i);

        Py_XINCREF(member);
        PyTuple_SetItem(result, i + 1, member);
    }

    return result;
}
Esempio n. 19
0
static PyObject *
hv_cli_dictof_get_static_types_list(NyHeapViewObject *hv) {
    if (PyObject_Length(hv->static_types) == 0) {
	PyObject *h = hv_heap(hv, Py_None, Py_None); /* It updates static_types */
	if (!h)
	  return 0;
	Py_DECREF(h);
    }
    return PySequence_List(hv->static_types);
}
inline index_type sequence_len(boost::python::object const& obj){
    if( !PySequence_Check( obj.ptr() ) ){
        raise_error( PyExc_TypeError, "Sequence expected" );
    }

    index_type result = PyObject_Length( obj.ptr() );
    if( PyErr_Occurred() ){
        boost::python::throw_error_already_set();
    }
    return result;
}
Esempio n. 21
0
static foreign_t python_len(term_t tobj, term_t tf) {
  Py_ssize_t len;
  PyObject *o;

  o = term_to_python(tobj, true);
  if (o == NULL) {
    return false;
  }
  len = PyObject_Length(o);
  return PL_unify_int64(tf, len);
}
Esempio n. 22
0
/**
 * generateInitVars callback
 *
 * Called by DIP, we interface with Python
 */
int DippyDecompApp::generateInitVars(DecompVarList& initVars)
{
   if (!m_pyInitVars) {
      return 0;
   }

   PyObject* pVarList = PyObject_CallMethod(m_pProb, "generateInitVars", NULL);

   if (pVarList == NULL) {
      throw UtilException("Error calling method prob.generateInitVars()", "generateInitVars", "DippyDecompApp");
   }

   if (pVarList == Py_None)
      // method exists, but is not implemented, return 0
   {
      return 0;
   }

   int nVars = PyObject_Length(pVarList);
   // generateInitVars returns 2-tuples (index, (cost, dictionary of (variable, value) pairs))
   // We can use these to construct a C++ DecompVar objects

   for (int i = 0; i < nVars; i++) {
      PyObject* pTuple = PyList_GetItem(pVarList, i);
      int whichBlock = m_relaxIndices[PyTuple_GetItem(pTuple, 0)];
      PyObject* pVarTuple = PyTuple_GetItem(pTuple, 1);
      double cost   = PyFloat_AsDouble(PyTuple_GetItem(pVarTuple, 0));
      PyObject* pColDict = PyTuple_GetItem(pVarTuple, 1);
      int*     varInds = NULL;
      double* varVals = NULL;
      DecompVarType varType; 
      
      int numPairs = pyColDict_AsPackedArrays(pColDict, m_colIndices, &varInds, &varVals, varType);
      assert(numPairs == PyObject_Length(pColDict));
      DecompVar* var =  new DecompVar(numPairs, varInds, varVals, cost, varType);
      var->setBlockId(whichBlock);
      initVars.push_back(var);
   }

   return nVars;
}
Esempio n. 23
0
static PyObject *real_encode_string(PyObject *data, PyObject *output)
{
	/* XXX Hm.  It would be nice to build the whole thing in C land and then spew it in a single call to Python land...   --Zooko 2001-11-28 */
    PyObject *ret, *str, *length = NULL;
    PyObject *owrite_method;
    PyObject *excval;

    owrite_method = PyObject_GetAttrString(output, "write");
    if (!owrite_method || !PyCallable_Check(owrite_method)) {
	    excval = Py_BuildValue("(is)", 0, "output object must have a callable write method");
	    if (excval != NULL) {
		    PyErr_SetObject(PyExc_ValueError, excval);
		    Py_DECREF(excval);
	    }
	    Py_XDECREF(owrite_method);
	    return NULL;
    }

    //    result.write('(6:string')
    ret = PyObject_CallObject(owrite_method, str_tup_const);
    RETURN_IF_EXC(ret);
    Py_DECREF(ret);
 
    //    result.write(str(len(data)))
    length = PyInt_FromLong((long)PyObject_Length(data));
    str = PyObject_Str(length);
    ret = PyObject_CallFunction(owrite_method, "S", str);
    Py_DECREF(length);
    Py_DECREF(str);
    RETURN_IF_EXC(ret);
    Py_DECREF(ret);
    
    // result.write(':')
    ret = PyObject_CallObject(owrite_method, colon_tup_const);
    RETURN_IF_EXC(ret);
    Py_DECREF(ret);
    
    // result.write(str(data))
    ret = PyObject_CallFunction(owrite_method, "S", data);
    RETURN_IF_EXC(ret);
    Py_DECREF(ret);
    
    // result.write(')')
    ret = PyObject_CallObject(owrite_method, close_paren_tup_const);
    RETURN_IF_EXC(ret);
    Py_DECREF(ret);
    
    Py_XDECREF(owrite_method);

    Py_INCREF(Py_None);
    return Py_None;
} 
Esempio n. 24
0
static int
typecast_cmp(PyObject *obj1, PyObject* obj2)
{
    typecastObject *self = (typecastObject*)obj1;
    typecastObject *other = NULL;
    PyObject *number = NULL;
    Py_ssize_t i, j;
    int res = -1;

    if (PyObject_TypeCheck(obj2, &typecastType)) {
        other = (typecastObject*)obj2;
    }
    else {
        number = PyNumber_Int(obj2);
    }

    Dprintf("typecast_cmp: other = %p, number = %p", other, number);

    for (i=0; i < PyObject_Length(self->values) && res == -1; i++) {
        long int val = PyInt_AsLong(PyTuple_GET_ITEM(self->values, i));

        if (other != NULL) {
            for (j=0; j < PyObject_Length(other->values); j++) {
                if (PyInt_AsLong(PyTuple_GET_ITEM(other->values, j)) == val) {
                    res = 0; break;
                }
            }
        }

        else if (number != NULL) {
            if (PyInt_AsLong(number) == val) {
                res = 0; break;
            }
        }
    }

    Py_XDECREF(number);
    return res;
}
Esempio n. 25
0
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGEnumSTATPROPSTG::Next( 
            /* [in] */ ULONG celt,
            /* [length_is][size_is][out] */ STATPROPSTG __RPC_FAR *rgVar,
            /* [out] */ ULONG __RPC_FAR *pCeltFetched)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt);
	if ( FAILED(hr) )
		return hr;

	if ( !PySequence_Check(result) )
		goto error;
	int len;
	len = PyObject_Length(result);
	if ( len == -1 )
		goto error;
	if ( len > (int)celt)
		len = celt;

	if ( pCeltFetched )
		*pCeltFetched = len;

	int i;
	PyObject *obname;
	for ( i = 0; i < len; ++i )
	{
		TmpPyObject ob = PySequence_GetItem(result, i);
		if ( ob == NULL )
			goto error;

		if (!PyArg_ParseTuple(ob, "OkH", &obname, &rgVar[i].propid, &rgVar[i].vt)
			||!PyWinObject_AsTaskAllocatedWCHAR(obname, &rgVar[i].lpwstrName, TRUE))
		{
			Py_DECREF(result);
			for (; i--; )
				CoTaskMemFree(rgVar[i].lpwstrName);
			return PyCom_SetCOMErrorFromPyException(IID_IEnumSTATPROPSTG);
		}
	}

	Py_DECREF(result);

	return len < (int)celt ? S_FALSE : S_OK;

  error:
	PyErr_Clear();	// just in case
	Py_DECREF(result);
	return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnumSTATPROPSTG, "Next() did not return a sequence of objects");
}
STDMETHODIMP PyGEnumVARIANT::Next( 
            /* [in] */ ULONG celt,
            /* [length_is][size_is][out] */ VARIANT __RPC_FAR *rgVar,
            /* [out] */ ULONG __RPC_FAR *pCeltFetched)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt);
	if ( FAILED(hr) )
		return hr;

	if ( !PySequence_Check(result) )
		goto error;
	int len;
	len = PyObject_Length(result);
	if ( len == -1 )
		goto error;
	if ( len > (int)celt)
		len = celt;

	if ( pCeltFetched )
		*pCeltFetched = len;

	int i;
	for ( i = 0; i < len; ++i )
	{
		PyObject *ob = PySequence_GetItem(result, i);
		if ( ob == NULL )
			goto error;

		if ( !PyCom_VariantFromPyObject(ob, &rgVar[i]) )
		{
			Py_DECREF(ob);
			Py_DECREF(result);
			return PyCom_SetCOMErrorFromPyException(IID_IEnumVARIANT);
		}
		Py_DECREF(ob);
	}

	Py_DECREF(result);

	return len < (int)celt ? S_FALSE : S_OK;

  error:
	PyErr_Clear();	// just in case
	PyCom_LogF("PyGEnumVariant::Next got a bad return value");
	Py_DECREF(result);
	return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnumVARIANT, "Next() did not return a sequence of objects");
}
// Std delegation
STDMETHODIMP PyGEnumResources::Next( 
            /* [in] */ ULONG celt,
            /* [out] */ SHELL_ITEM_RESOURCE *rgVar,
            /* [out] */ ULONG *pCeltFetched)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt);
	if ( FAILED(hr) )
		return hr;

	if ( !PySequence_Check(result) )
		goto error;
	int len;
	len = PyObject_Length(result);
	if ( len == -1 )
		goto error;
	if ( len > (int)celt)
		len = celt;

	if ( pCeltFetched )
		*pCeltFetched = len;

	int i;
	for ( i = 0; i < len; ++i )
	{
		PyObject *ob = PySequence_GetItem(result, i);
		if ( ob == NULL )
			goto error;

		if ( !PyWinObject_AsSHELL_ITEM_RESOURCE(ob, &rgVar[i]))
		{
			Py_DECREF(result);
			return PyCom_SetCOMErrorFromPyException(IID_IEnumResources);
		}
	}

	Py_DECREF(result);

	return len < (int)celt ? S_FALSE : S_OK;

  error:
	PyErr_Clear();	// just in case
	Py_DECREF(result);
	return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnumResources, "Next() did not return a sequence of objects");
}
Esempio n. 28
0
STDMETHODIMP PyGEnumConnectionPoints::Next( 
            /* [in] */ ULONG celt,
            /* [length_is][size_is][out] */ IConnectionPoint **rgVar,
            /* [out] */ ULONG __RPC_FAR *pCeltFetched)
{
	PY_GATEWAY_METHOD;
	PyObject *result;
	HRESULT hr = InvokeViaPolicy("Next", &result, "i", celt);
	if ( FAILED(hr) )
		return hr;

	if ( !PySequence_Check(result) )
		goto error;
	int len;
	len = PyObject_Length(result);
	if ( len == -1 )
		goto error;
	if ( len > (int)celt)
		len = celt;

	if ( pCeltFetched )
		*pCeltFetched = len;

	int i;
	for ( i = 0; i < len; ++i )
	{
		PyObject *ob = PySequence_GetItem(result, i);
		if ( ob == NULL )
			goto error;

		if ( !PyCom_InterfaceFromPyObject(ob, IID_IConnectionPoint, reinterpret_cast<void **>(&rgVar[i]), FALSE) )
		{
			Py_DECREF(result);
			return PyCom_SetCOMErrorFromPyException(IID_IEnumConnectionPoints);
		}
	}

	Py_DECREF(result);

	return len < (int)celt ? S_FALSE : S_OK;

  error:
	PyErr_Clear();	// just in case
	Py_DECREF(result);
	return PyCom_SetCOMErrorFromSimple(E_FAIL, IID_IEnumConnectionPoints);
}
Esempio n. 29
0
// ----------------------------------------------------------------
static PyObject *
FormatsRepr(PyFormatsObject *cFormats)
{
	char sBuf[ 1000 ];
	int i;
	PyObject* cTmp= PyDict_Keys( FormatsType.tp_dict );
	sBuf[ 0 ]= '\0';
	for( i= 0; i< PyObject_Length( cTmp ); i++ )
	{
		char *s= PyString_AsString( PyList_GetItem( cTmp, i ));
		if( strlen( s )> 2 && ( s[ 0 ]== s[ 1 ] ) && ( s[ 1 ]== '_' ) )
			continue;
		if( i )
			strcat( sBuf, ",");
		strcat( sBuf, s);
	}
	return PyString_FromString( sBuf );
}
Esempio n. 30
0
static int
decoding_feof(struct tok_state *tok)
{
	if (tok->decoding_state >= 0) {
		return feof(tok->fp);
	} else {
		PyObject* buf = tok->decoding_buffer;
		if (buf == NULL) {
			buf = PyObject_CallObject(tok->decoding_readline, NULL);
			if (buf == NULL) {
				error_ret(tok);
				return 1;
			} else {
				tok->decoding_buffer = buf;
			}
		}
		return PyObject_Length(buf) == 0;
	}
}