Example #1
0
//==============================================================================
static String getChannelName (const Array<AudioProcessor::AudioProcessorBus>& buses, int index)
{
    return buses.size() > 0 ? AudioChannelSet::getChannelTypeName (buses.getReference(0).channels.getTypeOfChannel (index))
                            : String();
}
Example #2
0
    static CMPIArray* enumToArray(
        const CMPIEnumeration* eEnumObj,
        CMPIStatus* rc)
    {
        PEG_METHOD_ENTER(
            TRC_CMPIPROVIDERINTERFACE,
            "CMPI_Enumeration:enumToArray()");
        Uint32 size;
        CMPI_Object* obj;
        CMPIArray *nar = NULL;
        const CMPIEnumeration* eEnum = (CMPIEnumeration*)eEnumObj->hdl;

        if (!eEnum || !eEnum->hdl)
        {
            PEG_TRACE_CSTRING(
                TRC_CMPIPROVIDERINTERFACE,
                Tracer::LEVEL1,
                "Received invalid Handle - eEnum || eEnum->hdl...");
            CMSetStatus(rc, CMPI_RC_ERR_INVALID_HANDLE);
            PEG_METHOD_EXIT();
            return NULL;
        }
        if ((void*)eEnum->ft == (void*)CMPI_ObjEnumeration_Ftab ||
            (void*)eEnum->ft == (void*)CMPI_InstEnumeration_Ftab)
        {
            Array<SCMOInstance>* ia;
            if ((void*)eEnum->ft == (void*)CMPI_ObjEnumeration_Ftab)
            {
                CMPI_ObjEnumeration* ie = (CMPI_ObjEnumeration*)eEnum;
                ia = (Array<SCMOInstance>*)ie->hdl;
            }
            else
            {
                CMPI_InstEnumeration* ie = (CMPI_InstEnumeration*)eEnum;
                ia = (Array<SCMOInstance>*)ie->hdl;
            }
            size = ia->size();
            nar = mbEncNewArray(NULL,size,CMPI_instance,NULL);
            for (Uint32 i=0; i<size; i++)
            {
                SCMOInstance &inst = (*ia)[i];
                obj = new CMPI_Object(new SCMOInstance(inst),
                                      CMPI_Object::ObjectTypeInstance);
                arraySetElementAt(nar,i,(CMPIValue*)&obj,CMPI_instance);
            }
        }
        else
        {
            CMPI_OpEnumeration* oe = (CMPI_OpEnumeration*)eEnum;
            Array<SCMOInstance>* opa = (Array<SCMOInstance>*)oe->hdl;
            size = opa->size();
            nar = mbEncNewArray(NULL,size,CMPI_ref,NULL);
            for (Uint32 i=0; i<size; i++)
            {
                SCMOInstance &op = (*opa)[i];
                obj = new CMPI_Object(new SCMOInstance(op),
                                      CMPI_Object::ObjectTypeObjectPath);
                arraySetElementAt(nar,i,(CMPIValue*)&obj,CMPI_ref);
            }
        }
        PEG_METHOD_EXIT();
        return nar;
    }
Example #3
0
Value smsglocalkeys(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 3)
        throw runtime_error(
            "smsglocalkeys [whitelist|all|wallet|recv <+/-> <address>|anon <+/-> <address>]\n"
            "List and manage keys.");
    
    if (!fSecMsgEnabled)
        throw runtime_error("Secure messaging is disabled.");
    
    Object result;
    
    std::string mode = "whitelist";
    if (params.size() > 0)
    {
        mode = params[0].get_str();
    };
    
    char cbuf[256];
    
    if (mode == "whitelist"
        || mode == "all")
    {
        uint32_t nKeys = 0;
        int all = mode == "all" ? 1 : 0;
        for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
        {
            if (!all 
                && !it->fReceiveEnabled)
                continue;
            
            CBitcoinAddress coinAddress(it->sAddress);
            if (!coinAddress.IsValid())
                continue;
            
            std::string sPublicKey;
            
            CKeyID keyID;
            if (!coinAddress.GetKeyID(keyID))
                continue;
            
            CPubKey pubKey;
            if (!pwalletMain->GetPubKey(keyID, pubKey))
                continue;
            if (!pubKey.IsValid()
                || !pubKey.IsCompressed())
            {
                continue;
            };
            
            
            sPublicKey = EncodeBase58(pubKey.Raw());
            
            std::string sLabel = pwalletMain->mapAddressBook[keyID];
            std::string sInfo;
            if (all)
                sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on,  " : "off, ");
            sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
            result.push_back(Pair("key", it->sAddress + " - " + sPublicKey + " " + sInfo + " - " + sLabel));
            
            nKeys++;
        };
        
        
        snprintf(cbuf, sizeof(cbuf), "%u keys listed.", nKeys);
        result.push_back(Pair("result", std::string(cbuf)));
        
    } else
    if (mode == "recv")
    {
        if (params.size() < 3)
        {
            result.push_back(Pair("result", "Too few parameters."));
            result.push_back(Pair("expected", "recv <+/-> <address>"));
            return result;
        };
        
        std::string op      = params[1].get_str();
        std::string addr    = params[2].get_str();
        
        std::vector<SecMsgAddress>::iterator it;
        for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
        {
            if (addr != it->sAddress)
                continue;
            break;
        };
        
        if (it == smsgAddresses.end())
        {
            result.push_back(Pair("result", "Address not found."));
            return result;
        };
        
        if (op == "+" || op == "on"  || op == "add" || op == "a")
        {
            it->fReceiveEnabled = true;
        } else
        if (op == "-" || op == "off" || op == "rem" || op == "r")
        {
            it->fReceiveEnabled = false;
        } else
        {
            result.push_back(Pair("result", "Unknown operation."));
            return result;
        };
        
        std::string sInfo;
        sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,");
        sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
        result.push_back(Pair("result", "Success."));
        result.push_back(Pair("key", it->sAddress + " " + sInfo));
        return result;
        
    } else
    if (mode == "anon")
    {
        if (params.size() < 3)
        {
            result.push_back(Pair("result", "Too few parameters."));
            result.push_back(Pair("expected", "anon <+/-> <address>"));
            return result;
        };
        
        std::string op      = params[1].get_str();
        std::string addr    = params[2].get_str();
        
        std::vector<SecMsgAddress>::iterator it;
        for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
        {
            if (addr != it->sAddress)
                continue;
            break;
        };
        
        if (it == smsgAddresses.end())
        {
            result.push_back(Pair("result", "Address not found."));
            return result;
        };
        
        if (op == "+" || op == "on"  || op == "add" || op == "a")
        {
            it->fReceiveAnon = true;
        } else
        if (op == "-" || op == "off" || op == "rem" || op == "r")
        {
            it->fReceiveAnon = false;
        } else
        {
            result.push_back(Pair("result", "Unknown operation."));
            return result;
        };
        
        std::string sInfo;
        sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,");
        sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
        result.push_back(Pair("result", "Success."));
        result.push_back(Pair("key", it->sAddress + " " + sInfo));
        return result;
        
    } else
    if (mode == "wallet")
    {
        uint32_t nKeys = 0;
        BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook)
        {
            if (!IsMine(*pwalletMain, entry.first))
                continue;
            
            CBitcoinAddress coinAddress(entry.first);
            if (!coinAddress.IsValid())
                continue;
            
            std::string address;
            std::string sPublicKey;
            address = coinAddress.ToString();
            
            CKeyID keyID;
            if (!coinAddress.GetKeyID(keyID))
                continue;
            
            CPubKey pubKey;
            if (!pwalletMain->GetPubKey(keyID, pubKey))
                continue;
            if (!pubKey.IsValid()
                || !pubKey.IsCompressed())
            {
                continue;
            };
            
            sPublicKey = EncodeBase58(pubKey.Raw());
            
            result.push_back(Pair("key", address + " - " + sPublicKey + " - " + entry.second));
            nKeys++;
        };
        
        snprintf(cbuf, sizeof(cbuf), "%u keys listed from wallet.", nKeys);
        result.push_back(Pair("result", std::string(cbuf)));
    } else
Example #4
0
Value getworkex(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "getworkex [data, coinbase]\n"
            "If [data, coinbase] is not specified, returns extended work data.\n"
        );

    if (vNodes.empty())
        throw JSONRPCError(-9, "Qibuck is not connected!");

    if (IsInitialBlockDownload())
        throw JSONRPCError(-10, "Qibuck is downloading blocks...");

    if (pindexBest->nHeight >= LAST_POW_BLOCK)
        throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");

    typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
    static mapNewBlock_t mapNewBlock;
    static vector<CBlock*> vNewBlock;
    static CReserveKey reservekey(pwalletMain);

    if (params.size() == 0)
    {
        // Update block
        static unsigned int nTransactionsUpdatedLast;
        static CBlockIndex* pindexPrev;
        static int64_t nStart;
        static CBlock* pblock;
        if (pindexPrev != pindexBest ||
            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
        {
            if (pindexPrev != pindexBest)
            {
                // Deallocate old blocks since they're obsolete now
                mapNewBlock.clear();
                BOOST_FOREACH(CBlock* pblock, vNewBlock)
                    delete pblock;
                vNewBlock.clear();
            }
            nTransactionsUpdatedLast = nTransactionsUpdated;
            pindexPrev = pindexBest;
            nStart = GetTime();

            // Create new block
            pblock = CreateNewBlock(pwalletMain);
            if (!pblock)
                throw JSONRPCError(-7, "Out of memory");
            vNewBlock.push_back(pblock);
        }

        // Update nTime
        pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
        pblock->nNonce = 0;

        // Update nExtraNonce
        static unsigned int nExtraNonce = 0;
        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);

        // Save
        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);

        // Prebuild hash buffers
        char pmidstate[32];
        char pdata[128];
        char phash1[64];
        FormatHashBuffers(pblock, pmidstate, pdata, phash1);

        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

        CTransaction coinbaseTx = pblock->vtx[0];
        std::vector<uint256> merkle = pblock->GetMerkleBranch(0);

        Object result;
        result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
        result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));

        CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
        ssTx << coinbaseTx;
        result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));

        Array merkle_arr;

        BOOST_FOREACH(uint256 merkleh, merkle) {
            merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
        }

        result.push_back(Pair("merkle", merkle_arr));


        return result;
    }
Example #5
0
static Array HHVM_FUNCTION(getopt, const String& options,
                                   const Variant& longopts /*=null */) {
  opt_struct *opts, *orig_opts;
  int len = parse_opts(options.data(), options.size(), &opts);

  if (!longopts.isNull()) {
    Array arropts = longopts.toArray();
    int count = arropts.size();

    /* the first <len> slots are filled by the one short ops
     * we now extend our array and jump to the new added structs */
    opts = (opt_struct *)realloc(opts, sizeof(opt_struct) * (len + count + 1));
    orig_opts = opts;
    opts += len;

    memset(opts, 0, count * sizeof(opt_struct));

    for (ArrayIter iter(arropts); iter; ++iter) {
      String entry = iter.second().toString();

      opts->need_param = 0;
      opts->opt_name = strdup(entry.data());
      len = strlen(opts->opt_name);
      if ((len > 0) && (opts->opt_name[len - 1] == ':')) {
        opts->need_param++;
        opts->opt_name[len - 1] = '\0';
        if ((len > 1) && (opts->opt_name[len - 2] == ':')) {
          opts->need_param++;
          opts->opt_name[len - 2] = '\0';
        }
      }
      opts->opt_char = 0;
      opts++;
    }
  } else {
    opts = (opt_struct*) realloc(opts, sizeof(opt_struct) * (len + 1));
    orig_opts = opts;
    opts += len;
  }

  /* php_getopt want to identify the last param */
  opts->opt_char   = '-';
  opts->need_param = 0;
  opts->opt_name   = NULL;

  static const StaticString s_argv("argv");
  Array vargv = php_global(s_argv).toArray();
  int argc = vargv.size();
  char **argv = (char **)malloc((argc+1) * sizeof(char*));
  std::vector<String> holders;
  int index = 0;
  for (ArrayIter iter(vargv); iter; ++iter) {
    String arg = iter.second().toString();
    holders.push_back(arg);
    argv[index++] = (char*)arg.data();
  }
  argv[index] = NULL;

  /* after our pointer arithmetic jump back to the first element */
  opts = orig_opts;

  int o;
  char *php_optarg = NULL;
  int php_optind = 1;

  SCOPE_EXIT {
    free_longopts(orig_opts);
    free(orig_opts);
    free(argv);
  };

  Array ret = Array::Create();

  Variant val;
  int optchr = 0;
  int dash = 0; /* have already seen the - */
  char opt[2] = { '\0' };
  char *optname;
  int optname_len = 0;
  int php_optidx;
  while ((o = php_getopt(argc, argv, opts, &php_optarg, &php_optind, 0, 1,
                         optchr, dash, php_optidx))
         != -1) {
    /* Skip unknown arguments. */
    if (o == '?') {
      continue;
    }

    /* Prepare the option character and the argument string. */
    if (o == 0) {
      optname = opts[php_optidx].opt_name;
    } else {
      if (o == 1) {
        o = '-';
      }
      opt[0] = o;
      optname = opt;
    }

    if (php_optarg != NULL) {
      /* keep the arg as binary, since the encoding is not known */
      val = String(php_optarg, CopyString);
    } else {
      val = false;
    }

    /* Add this option / argument pair to the result hash. */
    optname_len = strlen(optname);
    if (!(optname_len > 1 && optname[0] == '0') &&
        is_numeric_string(optname, optname_len, NULL, NULL, 0) ==
        KindOfInt64) {
      /* numeric string */
      int optname_int = atoi(optname);
      if (ret.exists(optname_int)) {
        Variant &e = ret.lvalAt(optname_int);
        if (!e.isArray()) {
          ret.set(optname_int, make_packed_array(e, val));
        } else {
          e.toArrRef().append(val);
        }
      } else {
        ret.set(optname_int, val);
      }
    } else {
      /* other strings */
      String key(optname, strlen(optname), CopyString);
      if (ret.exists(key)) {
        Variant &e = ret.lvalAt(key);
        if (!e.isArray()) {
          ret.set(key, make_packed_array(e, val));
        } else {
          e.toArrRef().append(val);
        }
      } else {
        ret.set(key, val);
      }
    }

    php_optarg = NULL;
  }

  return ret;
}
Error EditorSceneImporterFBXConv::_parse_nodes(State& state,const Array &p_nodes,Node* p_base) {

	for(int i=0;i<p_nodes.size();i++) {

		Dictionary n = p_nodes[i];
		Spatial *node=NULL;
		bool skip=false;

		String id;
		if (n.has("id")) {
			id=_id(n["id"]);
		}

		print_line("ID: "+id);

		if (state.skeletons.has(id)) {

			Skeleton *skeleton = state.skeletons[id];
			node=skeleton;
			skeleton->localize_rests();
			print_line("IS SKELETON! ");
		} else if (state.bones.has(id)) {
			if (p_base)
				node=p_base->cast_to<Spatial>();
			if (!state.bones[id].has_anim_chan) {
				print_line("no has anim "+id);
			}
			skip=true;
		} else if (n.has("parts")) {
			//is a mesh
			MeshInstance *mesh = memnew( MeshInstance );
			node=mesh;

			Array parts=n["parts"];
			String long_identifier;
			for(int j=0;j<parts.size();j++) {

				Dictionary part=parts[j];
				if (part.has("meshpartid")) {
					String partid=part["meshpartid"];
					long_identifier+=partid;
				}
			}

			Ref<Mesh> m;

			if (state.mesh_cache.has(long_identifier)) {
				m=state.mesh_cache[long_identifier];
			} else {
				m = Ref<Mesh>( memnew( Mesh ) );

				//and parts are surfaces
				for(int j=0;j<parts.size();j++) {

					Dictionary part=parts[j];
					if (part.has("meshpartid")) {
						_add_surface(state,m,part);
					}
				}


				state.mesh_cache[long_identifier]=m;
			}

			mesh->set_mesh(m);
		}

		if (!skip) {

			if (!node) {
				node = memnew( Spatial );
			}

			node->set_name(id);
			node->set_transform(_get_transform(n));
			p_base->add_child(node);
			node->set_owner(state.scene);
		}


		if (n.has("children")) {
			Error err = _parse_nodes(state,n["children"],node);
			if (err)
				return err;
		}
	}

	return OK;
}
Transform EditorSceneImporterFBXConv::_get_transform_mixed(const Dictionary& d,const Dictionary& dbase) {




	Array translation;

	if (d.has("translation"))
		translation=d["translation"];
	else if (dbase.has("translation"))
		translation=dbase["translation"];

	Array rotation;

	if (d.has("rotation"))
		rotation=d["rotation"];
	else if (dbase.has("rotation"))
		rotation=dbase["rotation"];

	Array scale;

	if (d.has("scale"))
		scale=d["scale"];
	else if (dbase.has("scale"))
		scale=dbase["scale"];

	Transform t;


	if (translation.size()) {
		Array tr = translation;
		if (tr.size()>=3) {
			t.origin.x=tr[0];
			t.origin.y=tr[1];
			t.origin.z=tr[2];
		}
	}

	if (rotation.size()) {

		Array r = rotation;
		if (r.size()>=4) {

			Quat q;
			q.x = r[0];
			q.y = r[1];
			q.z = r[2];
			q.w = r[3];
			t.basis=Matrix3(q);
		}
	}


	if (scale.size()) {

		Array sc = scale;
		if (sc.size()>=3) {
			Vector3 s;
			s.x=sc[0];
			s.y=sc[1];
			s.z=sc[2];
			t.basis.scale(s);
		}
	}

	return t;


}
//==============================================================================
int ComponentPeer::getNumPeers() noexcept
{
    return heavyweightPeers.size();
}
Example #9
0
/**
 * tryFile is a pointer to a function that resolve_include() will use to
 * determine if a path references a real file.  ctx is a pointer to some context
 * information that will be passed through to tryFile.  (It's a hacky closure)
 */
String resolve_include(const String& file, const char* currentDir,
                       bool (*tryFile)(const String& file, void*), void* ctx) {
  const char* c_file = file->data();

  if (!File::IsPlainFilePath(file)) {
    // URIs don't have an include path
    if (tryFile(file, ctx)) {
      return file;
    }

  } else if (c_file[0] == '/') {
    String can_path(Util::canonicalize(file.c_str(), file.size()),
                    AttachString);

    if (tryFile(can_path, ctx)) {
      return can_path;
    }

  } else if ((c_file[0] == '.' && (c_file[1] == '/' || (
    c_file[1] == '.' && c_file[2] == '/')))) {

    String path(String(g_context->getCwd() + "/" + file));
    String can_path(Util::canonicalize(path.c_str(), path.size()),
                    AttachString);

    if (tryFile(can_path, ctx)) {
      return can_path;
    }

  } else {
    Array includePaths = g_context->getIncludePathArray();
    unsigned int path_count = includePaths.size();

    for (int i = 0; i < (int)path_count; i++) {
      String path("");
      String includePath = includePaths[i].toString();

      if (includePath[0] != '/') {
        path += (g_context->getCwd() + "/");
      }

      path += includePath;

      if (path[path.size() - 1] != '/') {
        path += "/";
      }

      path += file;
      String can_path(Util::canonicalize(path.c_str(), path.size()),
                      AttachString);

      if (tryFile(can_path, ctx)) {
        return can_path;
      }
    }

    if (currentDir[0] == '/') {
      String path(currentDir);
      path += "/";
      path += file;
      String can_path(Util::canonicalize(path.c_str(), path.size()),
                      AttachString);

      if (tryFile(can_path, ctx)) {
        return can_path;
      }
    } else {
      String path(g_context->getCwd() + "/" + currentDir + file);
      String can_path(Util::canonicalize(path.c_str(), path.size()),
                      AttachString);

      if (tryFile(can_path, ctx)) {
        return can_path;
      }
    }
  }

  return String();
}
int MoleculeAutomorphismSearch::_compare_mapped (Graph &graph, const Array<int> &mapping1, const Array<int> &mapping2, const void *context)
{
   const MoleculeAutomorphismSearch &self = *(MoleculeAutomorphismSearch *)context;
   Molecule &mol = (Molecule &)graph;

   QS_DEF(Array<int>, inv_mapping1);
   QS_DEF(Array<int>, inv_mapping2);

   inv_mapping1.clear_resize(graph.vertexEnd());
   inv_mapping2.clear_resize(graph.vertexEnd());

   inv_mapping1.fffill();
   inv_mapping2.fffill();

   for (int i = 0; i < mapping1.size(); i++)
   {
      inv_mapping1[mapping1[i]] = i;
      inv_mapping2[mapping2[i]] = i;
   }

//   int min_diff_beg = graph.vertexEnd();
//   int min_diff_end = graph.vertexEnd();
//   int diff_sign = 0;

   // This function compares two mappings to select one of it 
   // according to the defined (here) order.
   // Canonical mapping is taken as the smallest mapping.
   // To compare two mapping we compare their connectivity matrix 

   QS_DEF(Array<EdgeInfo>, sorted_nei1);
   QS_DEF(Array<EdgeInfo>, sorted_nei2);

   // Compare connectivity matrix line by line
   for (int i = 0; i < mapping1.size(); i++)
   {
      _getSortedNei(graph, mapping1[i], sorted_nei1, inv_mapping1);
      _getSortedNei(graph, mapping2[i], sorted_nei2, inv_mapping2);

      if (sorted_nei1.size() != sorted_nei2.size())
         return sorted_nei1.size() > sorted_nei2.size() ? 1 : -1;

      for (int j = 0; j < sorted_nei1.size(); j++)
      {
         int m1 = sorted_nei1[j].mapped_vertex;
         int m2 = sorted_nei2[j].mapped_vertex;
         if (m1 != m2)
            return m1 > m2 ? 1 : -1;

         int e1 = sorted_nei1[j].edge;
         int e2 = sorted_nei2[j].edge;

         // Compare edge bond orders and parities
         int type1 = self._getMappedBondOrderAndParity(mol, e1, inv_mapping1);
         int type2 = self._getMappedBondOrderAndParity(mol, e2, inv_mapping2);

         if (type1 != type2)
            return type1 > type2 ? 1 : -1;
      }
   }

   return self._compareMappedStereocenters(mol, mapping1, mapping2, inv_mapping1, inv_mapping2);
}
int MoleculeAutomorphismSearch::_compareMappedStereocenters (Molecule &mol,
      const Array<int> &mapping1, const Array<int> &mapping2,
      const Array<int> &inv_mapping1, const Array<int> &inv_mapping2) const
{
   MoleculeStereocenters &stereocenters = mol.stereocenters;

   if (stereocenters.size() == 0)
      return 0;

   int max_stereogroup = 0;
   for (int s = stereocenters.begin(); s != stereocenters.end(); s = stereocenters.next(s))
   {
      int atom_idx = stereocenters.getAtomIndex(s);
      max_stereogroup = __max(stereocenters.getGroup(atom_idx), max_stereogroup);
   }

   int groups_count = 2 * (max_stereogroup + 1);
   QS_DEF(Array<int>, stereogroup1_rank);
   QS_DEF(Array<int>, stereogroup2_rank);
   QS_DEF(Array<int>, stereogroup1_parity_mod);
   QS_DEF(Array<int>, stereogroup2_parity_mod);
   stereogroup1_rank.clear_resize(groups_count);
   stereogroup1_rank.fffill();
   stereogroup2_rank.clear_resize(groups_count);
   stereogroup2_rank.fffill();
   stereogroup1_parity_mod.clear_resize(groups_count);
   stereogroup1_parity_mod.fffill();
   stereogroup2_parity_mod.clear_resize(groups_count);
   stereogroup2_parity_mod.fffill();

   for (int i = 0; i < mapping1.size(); i++)
   {
      int type1 = stereocenters.getType(mapping1[i]);
      int type2 = stereocenters.getType(mapping2[i]);
      if (_getStereo(_stereocenter_state[mapping1[i]]) == _INVALID)
         type1 = 0;
      if (_getStereo(_stereocenter_state[mapping2[i]]) == _INVALID)
         type2 = 0;

      if (type1 != type2)
         throw Error("internal: stereocenter types mismatch");

      if (type1 < MoleculeStereocenters::ATOM_AND)
         continue;

      int pyramid1[4], pyramid2[4];

      memcpy(pyramid1, stereocenters.getPyramid(mapping1[i]), 4 * sizeof(int));
      memcpy(pyramid2, stereocenters.getPyramid(mapping2[i]), 4 * sizeof(int));

      int size1 = 0, size2 = 0;

      for (int j = 0; j < 4; j++)
      {
         if (pyramid1[j] >= 0)
         {
            if (inv_mapping1[pyramid1[j]] >= 0)
               size1++;
            else
               pyramid1[j] = -1;
         }
         if (pyramid2[j] >= 0)
         {
            if (inv_mapping2[pyramid2[j]] >= 0)
               size2++;
            else
               pyramid2[j] = -1;
         }
      }

      if (size1 != size2)
         throw Error("internal: stereocenter sizes mismatch");

      bool rigid1 = true, rigid2 = true;

      if (size1 >= 3)
      {
         if (size1 == 3)
            MoleculeStereocenters::moveImplicitHydrogenToEnd(pyramid1);

         for (int j = 0; j < size1; j++)
            pyramid1[j] = inv_mapping1[pyramid1[j]];

         rigid1 = MoleculeStereocenters::isPyramidMappingRigid(pyramid1);
      }
      if (size2 >= 3)
      {
         if (size2 == 3)
            MoleculeStereocenters::moveImplicitHydrogenToEnd(pyramid2);

         for (int j = 0; j < size2; j++)
            pyramid2[j] = inv_mapping2[pyramid2[j]];

         rigid2 = MoleculeStereocenters::isPyramidMappingRigid(pyramid2);
      }

      int group1 = stereocenters.getGroup(mapping1[i]);
      int group2 = stereocenters.getGroup(mapping2[i]);

      // Encode group with type into one index
      int type_group1 = 2 * group1 + (type1 == MoleculeStereocenters::ATOM_AND ? 0 : 1);
      int type_group2 = 2 * group2 + (type2 == MoleculeStereocenters::ATOM_AND ? 0 : 1);

      if (type1 == MoleculeStereocenters::ATOM_AND || type1 == MoleculeStereocenters::ATOM_OR)
      {
         int &parity_mod1 = stereogroup1_parity_mod[type_group1];
         int &parity_mod2 = stereogroup2_parity_mod[type_group2];

         // First stereocenter in group always maps rigid
         if (parity_mod1 == -1)
            parity_mod1 = rigid1 ? 0 : 1;
         if (parity_mod2 == -1)
            parity_mod2 = rigid2 ? 0 : 1;

         if (parity_mod1 == 1)
            // Invert sterecenter
            rigid1 = !rigid1;

         if (parity_mod2 == 1)
            // Invert sterecenter
            rigid2 = !rigid2;
      }

      if (rigid1 && !rigid2)
         return 1;
      if (rigid2 && !rigid1)
         return -1;

      // Compare stereogroups
      if (type1 == MoleculeStereocenters::ATOM_AND || type1 == MoleculeStereocenters::ATOM_OR)
      {
         int &rank1 = stereogroup1_rank[type_group1];
         int &rank2 = stereogroup2_rank[type_group2];

         if (rank1 == -1)
            rank1 = i;
         if (rank2 == -1)
            rank2 = i;

         int diff = rank1 - rank2;
         if (diff != 0)
            return diff;
      }
   }

   return 0;
}
Example #12
0
bool f_is_callable(CVarRef v, bool syntax /* = false */,
                   Variant name /* = null */) {
  if (v.isString()) {
    if (!name.isNull()) name = v;
    if (syntax) return true;

    String str = v.toString();
    int c = str.find("::");
    if (c != 0 && c != String::npos && c + 2 < str.size()) {
      String classname = str.substr(0, c);
      String methodname = str.substr(c + 2);
      return f_call_user_func_array(s_class_exists,
                                    Array::Create(classname)) &&
        ClassInfo::HasAccess(classname, methodname, true, false);
    }
    return f_function_exists(str);
  }

  if (v.is(KindOfArray)) {
    Array arr = v.toArray();
    if (arr.size() == 2 && arr.exists(0LL) && arr.exists(1LL)) {
      Variant v0 = arr.rvalAt(0LL);
      Variant v1 = arr.rvalAt(1LL);
      Object obj;
      bool staticCall = false;
      if (v0.is(KindOfObject)) {
        obj = v0.toObject();
        v0 = obj->o_getClassName();
      } else if (v0.isString()) {
        if (!f_call_user_func_array(s_class_exists, Array::Create(v0))) {
          return false;
        }
        staticCall = true;
      }
      if (v1.isString()) {
        String str = v1.toString();
        int c = str.find("::");
        if (c != 0 && c != String::npos && c + 2 < str.size()) {
          String name1 = v0.toString();
          String name2 = str.substr(0, c);
          ASSERT(name1.get() && name2.get());
          if (name1->isame(name2.get()) ||
              ClassInfo::IsSubClass(name1, name2, false)) {
            staticCall = true;
            v0 = name2;
            v1 = str.substr(c + 2);
          }
        }
      }
      if (v0.isString() && v1.isString()) {
        if (!name.isNull()) {
          name = v0.toString() + "::" + v1.toString();
        }
        if (same(v0, s_self) || same(v0, s_parent)) {
          throw NotImplementedException("augmenting class scope info");
        }
        return ClassInfo::HasAccess(v0, v1, staticCall, !obj.isNull());
      }
    }
  }

  if (!name.isNull()) {
    name = v.toString();
  }
  return false;
}
Example #13
0
double Clause::getConstantTuples(const Domain* const & domain,
                                 const Database* const & db,
                                 Array<int>* const & mlnClauseTermIds,
                                 const Clause* const & varClause,
                                 PredicateTermToVariable * const & ptermToVar,
                            ClauseToSuperClauseMap* const & clauseToSuperClause,
                                 bool useImplicit)
{
  bool ignoreActivePreds = true;
  double numTrueGndings = 0;

    //initialize the constants tuple with the var Ids - we will fill them in
    //with constants as we go along
  Array<int> *constants = new Array<int>(*mlnClauseTermIds);

    //Copy the literals so that their original order in the clause is
    //not affected by the subsequent sorting
    
  cout<<"***************************************************************"<<endl;
  cout<<"Came to process the clause : "<<endl;
  print(cout, domain);
  cout<<endl;

  createVarIdToVarsGroundedType(domain);

  Array<Predicate*>* origClauseLits = new Array<Predicate*>(*predicates_);

    // Array of partially grounded clauses achieved by using the inverted
    // index
  Array<Array<Predicate*>* > partGroundedClauses;

    //Assign to each variable in clause, the corresponding variable class
    //(stores the list of indexed constants). It is accessed through the
    //predicates appearing in the clause
  PredicateTermToVariable::iterator itr;
  PredicateTerm *pterm;
  Predicate *pred;
  const Term *term;
  Array<Variable *> *eqVars = new Array<Variable *>();
  eqVars->growToSize(mlnClauseTermIds->size());
    
    //initialize with NULL
  for (int i = 0; i < eqVars->size(); i++)
    (*eqVars)[i] = NULL;

  if (useImplicit)
  {
    for (int predno = 0; predno < varClause->getNumPredicates(); predno++)
    {
      pred = varClause->getPredicate(predno);
      int predId = pred->getId();
      for (int termno = 0; termno < pred->getNumTerms(); termno++)
      {
        term = pred->getTerm(termno);
        assert(!term->isConstant());
        int termId = term->getId();
        pterm = new PredicateTerm(predId, termno);
        itr = ptermToVar->find(pterm);
        assert(itr != ptermToVar->end());
        assert(-termId < eqVars->size());
        (*eqVars)[-termId] = itr->second;
        delete pterm;
      }
    }
  }

  if (useInverseIndex)
  {
      // Put the indexable literals first and ground them
    sortLiteralsByNegationAndArity(*origClauseLits, ignoreActivePreds, db);
    groundIndexableLiterals(domain, db, *origClauseLits, partGroundedClauses,
                            ignoreActivePreds);
  }
  else
  {
      //Sort preds in decreasing order of #TrueGndOfLiteral/#numOfGroundings.
      //The larger the number of true groundings of a literal, the more likely
      //it is to be true, so put it in front so that we can decide whether the
      //clause is true early.The larger the number of groundings of the
      //literal, the larger the savings when we decide that preceding literals
      //are true.
    sortLiteralsByTrueDivTotalGroundings(*origClauseLits, domain, db);
      // Put the original clause as the only clause into partGroundedClauses
    Array<Predicate*>* clauseLitsCopy = new Array<Predicate*>;
    clauseLitsCopy->growToSize(origClauseLits->size());
    for (int i = 0; i < origClauseLits->size(); i++)
      (*clauseLitsCopy)[i] = new Predicate(*(*origClauseLits)[i]);
    partGroundedClauses.append(clauseLitsCopy);
  }

    // At this point partGroundedClauses holds the nodes of the branch and
    // bound algorithm. This means nothing more is indexed and we must ground
    // out the rest of the predicates
  if (clausedebug)
  {
    cout << "Partially grounded clauses to be completed: " << endl;
    for (int pgcIdx = 0; pgcIdx < partGroundedClauses.size(); pgcIdx++)
    {
      cout << "\t";
      for (int i = 0; i < partGroundedClauses[pgcIdx]->size(); i++)
      {
        (*partGroundedClauses[pgcIdx])[i]->printWithStrVar(cout, domain);
        cout << " ";
      }
      cout << endl;
    }
  }

  bool skip;
    // Go through each clause in partGroundedClauses (nodes of the branch and
    // bound algorithm if using inverted index; otherwise, the original
    // clause), ground them out and check truth values
  for (int pgcIdx = 0; pgcIdx < partGroundedClauses.size(); pgcIdx++)
  {
      //intially, the list of constants is simply the mln term ids 
    constants->copyFrom(*mlnClauseTermIds);   

    skip = false;
      // clauseLits is a sorted copy of predicates_
    Array<Predicate*> clauseLits = *(partGroundedClauses[pgcIdx]);
    assert(clauseLits.size() == origClauseLits->size());
      // Set the var to groundings in this clause to be those in clauseLits
    Array<int>* origVarIds = new Array<int>;
      
    for (int i = 0; i < clauseLits.size(); i++)
    {
      assert(clauseLits[i]->getNumTerms() == 
             (*origClauseLits)[i]->getNumTerms());
        // Ground variables throughout clause
      for (int j = 0; j < (*origClauseLits)[i]->getNumTerms(); j++)
      {
        const Term* oldTerm = (*origClauseLits)[i]->getTerm(j);
        const Term* newTerm = clauseLits[i]->getTerm(j);
          
        if (oldTerm->getType() == Term::VARIABLE)
        {
          int varId = oldTerm->getId();
          origVarIds->append(varId);
          if (newTerm->getType() == Term::CONSTANT)
          {
            int constId = newTerm->getId();
            assert(constId >= 0);
            Array<Term*>& vars = (*varIdToVarsGroundedType_)[-varId]->vars;
            assert(constants->size() >= (-varId+1));

            if (useImplicit)
            {
              int implicitIndex = 
                (*eqVars)[-varId]->getImplicitIndex(constId);
              if (implicitIndex < 0)
              {
                (*constants)[-varId] = constId;
              }
              else
              {
                if (isRepresentativePartialTuple(constants, implicitIndex,
                                                 eqVars, varId))
                {
                  (*constants)[-varId] = constId;
                }
                else
                {
                  skip = true;
                }
              }
            }
            else
            {
              (*constants)[-varId] = constId;
            }

            for (int k = 0; k < vars.size(); k++) vars[k]->setId(constId);
          }
        }
      }
        // Set the preds in clauseLits to point to the original predicates_
      delete clauseLits[i];
      clauseLits[i] = (*origClauseLits)[i];
    }
      
    if (!skip)
    {
        //simulate a stack, back/front corresponds to top/bottom
        //ivg stands for index, varIds, groundings
      Array<LitIdxVarIdsGndings*> ivgArr;
      createAllLitIdxVarsGndings(clauseLits, ivgArr, domain, true);
      int ivgArrIdx = 0; //store current position in ivgArr
      bool lookAtNextLit = false;
    
        // while stack is not empty
      while (ivgArrIdx >= 0)
      {
          // get variable groundings at top of stack
        LitIdxVarIdsGndings* ivg = ivgArr[ivgArrIdx];
        Predicate* lit = (*origClauseLits)[ivg->litIdx];
        
        Array<int>& varIds = ivg->varIds;
        ArraysAccessor<int>& varGndings = ivg->varGndings;
        bool& litUnseen = ivg->litUnseen;
        bool hasComb;

        if (clausedebug)
        {
          cout << "Looking at lit: ";
          lit->printWithStrVar(cout, domain);
          cout << endl;
        }

        bool gotoNextComb = false;
          // while there are groundings of literal's variables
        while ((hasComb = varGndings.hasNextCombination()) || litUnseen)
        {
            // there may be no combinations if the literal is fully grounded
          if (litUnseen) litUnseen = false;

          if (hasComb)
          {
              //replace back the variables into the constants array
            for (int v = 0; v < varIds.size(); v++)
            {
              (*constants)[-varIds[v]] = varIds[v];
            }
              //ground the literal's variables throughout the clause
            int constId;
            int v = 0; // index of varIds
              //for each variable in literal
            gotoNextComb = false;
            while (varGndings.nextItemInCombination(constId))
            {
              int varId = varIds[v];
              Array<Term*>& vars = (*varIdToVarsGroundedType_)[-varId]->vars;
              
                //store the assignment to this variable
              assert(constants->size() >= (-varId+1));
   
              if (useImplicit)
              {
                int implicitIndex =
                  (*eqVars)[-varId]->getImplicitIndex(constId);
                if (implicitIndex < 0)
                {
                  (*constants)[-varId] = constId;
                }
                else
                {
                    //in case of implicit constant, proceed only if
                    //substitution of this constant
                    //will form a representative tuple - see the body of the
                    //function for the details of 
                    //what a representative tuple is
                  if (isRepresentativePartialTuple(constants, implicitIndex,
                                                   eqVars, varId))
                  {
                    (*constants)[-varId] = constId;
                  }
                  else
                  {
                    gotoNextComb = true;
                  }
                }
              }
              else
              {
                (*constants)[-varId] = constId;
              }
              v++;
              for (int i = 0; i < vars.size(); i++) vars[i]->setId(constId);
            }

              //a sanity check - for debugging purposes   
            assert(varIds.size() == v);
          }

          //removeRedundantPredicates();

          if (clausedebug)
          {
            cout << "Clause is now: ";
            printWithWtAndStrVar(cout, domain);
            cout << endl;
          }
          
          if (gotoNextComb)
            continue;
            
          if (literalOrSubsequentLiteralsAreTrue(lit, ivg->subseqGndLits, db))
          {
            if (clausedebug)
              cout << "Clause satisfied" << endl;
              
              //count the number of combinations of remaining variables
            double numComb = 1;
            for (int i = ivgArrIdx + 1; i < ivgArr.size(); i++)
            {
              int numVar = ivgArr[i]->varGndings.getNumArrays();
              for (int j = 0; j < numVar; j++)
                numComb *= ivgArr[i]->varGndings.getArray(j)->size();
            }
            numTrueGndings += numComb;
          }
          else
          {
              // if there are more literals
            if (ivgArrIdx + 1 < ivgArr.size())
            {
              if (clausedebug) cout << "Moving to next literal" << endl;
              lookAtNextLit = true;
              ivgArrIdx++; // move up stack
              break;
            }
              //At this point all the literals are grounded, and they are
              //either unknown or false (have truth values opposite of their
              //senses).

              //- this so that it matches the hypercube representation.
              //There is no real need to simplify the clause!
            if (false) 
            {
              ++numTrueGndings;
            }
            else
            {
                //Create a new constant tuple
              addConstantTuple(domain, db, varClause, constants, eqVars,
                               clauseToSuperClause, useImplicit);
            }
          }
        } //while there are groundings of literal's variables
        
          //if we exit the while loop in order to look at next literal 
          //(i.e. without considering all groundings of current literal)
        if (lookAtNextLit) { lookAtNextLit = false; }
          //mv down stack
        else
        { 
          varGndings.reset();
          litUnseen = true; 
          ivgArrIdx--; 
            //replace back the variables into the constants array
          for (int v = 0; v < varIds.size(); v++)
          {
            (*constants)[-varIds[v]] = varIds[v];
          }
        }
      } // while stack is not empty
      deleteAllLitIdxVarsGndings(ivgArr); 
    } //end skip
      
      // Restore variables
    for (int i = 0; i < origVarIds->size(); i++)
    {
      int varId = (*origVarIds)[i];
      assert(varId < 0);
      Array<Term*>& vars = (*varIdToVarsGroundedType_)[-varId]->vars;
      for (int j = 0; j < vars.size(); j++) vars[j]->setId(varId);
      (*varIdToVarsGroundedType_)[-varId]->isGrounded = false;
    }
      
    delete origVarIds;
    delete partGroundedClauses[pgcIdx];
  }
  delete origClauseLits;
  delete constants;
  return numTrueGndings;
}
Example #14
0
static bool isStereoPair (const Array<AudioProcessor::AudioProcessorBus>& buses, int index)
{
    return index < 2
            && buses.size() > 0
            && buses.getReference(0).channels == AudioChannelSet::stereo();
}
Example #15
0
static void HHVM_METHOD(IntlGregorianCalendar, __ctor_array,
                        const Array& args) {
  assert(args.size() == 6);

  int32_t numargs;
  for (numargs = 0; numargs < 6; ++numargs) {
    if (args[numargs].isNull()) {
      break;
    }
  }

  if (numargs > 6) {
    s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
                           "intlgregcal_create_instance: too many arguments");
    return;
  }

  icu::GregorianCalendar *gcal = nullptr;
  SCOPE_EXIT { if (gcal) { delete gcal; } };
  icu::TimeZone *tz = nullptr;
  SCOPE_EXIT { if (gcal && tz) { delete tz; } };

  UErrorCode error;
  if (numargs < 3) {
    tz = IntlTimeZone::ParseArg(args[0], "intlgregcal_create_instance",
                                         s_intl_error.get());
    String loc(localeOrDefault(args[1].toString()));
    error = U_ZERO_ERROR;
    gcal = new icu::GregorianCalendar(tz,
               icu::Locale::createFromName(loc.c_str()), error);
    if (U_FAILURE(error)) {
      s_intl_error->setError(error, "intlgregcal_create_instance: error "
               "creating ICU GregorianCalendar from time zone and locale");
      return;
    }
    goto success;
  }

  int32_t intarg[6];
  assert(numargs <= 6);
  for (int i = 0; i < numargs; ++i) {
    int64_t arg = args[i].toInt64();
    if ((arg < INT32_MIN) || (arg > INT32_MAX)) {
      s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
                             "intlgregcal_create_instance: at least one of "
                             "the arguments has an absolute value that is "
                             "too large");
      return;
    }
    intarg[i] = (int32_t)arg;
  }

  error = U_ZERO_ERROR;
  switch (numargs) {
    case 3: // year, month, day
      gcal = new icu::GregorianCalendar(intarg[0], intarg[1], intarg[2],
                                        error);
      break;
    case 4:
      s_intl_error->setError(U_ILLEGAL_ARGUMENT_ERROR,
                             "intlgregcal_create_instance: no variant with "
                             "4 arguments (excluding trailing NULLs)");
      return;
    case 5: // ..., hour, minute
      gcal = new icu::GregorianCalendar(intarg[0], intarg[1], intarg[2],
                                        intarg[3], intarg[4],
                                        error);
      break;
    case 6: // ..., second
      gcal = new icu::GregorianCalendar(intarg[0], intarg[1], intarg[2],
                                        intarg[3], intarg[4], intarg[5],
                                        error);
      break;
    default:
      not_reached();
      return;
  }
  if (U_FAILURE(error)) {
    s_intl_error->setError(error, "intlgregcal_create_instance: error "
                                  "creating ICU GregorianCalendar from date");
    return;
  }

  tz = IntlTimeZone::ParseArg(uninit_null(), "intlgregcal_create_instance",
                                             s_intl_error.get());
  if (!tz) {
    // error already set
    return;
  }
  gcal->adoptTimeZone(tz);

success:
  Native::data<IntlCalendar>(this_)->setCalendar(gcal);
  gcal = nullptr; // prevent SCOPE_EXIT sweeps
}
Example #16
0
void AuditLogger::logCurrentRegProvider(
    const Array < CIMInstance > & instances)
{
    // check if SMF is gathering this type of records.
    if (_smf.isRecording(CONFIGURATION) ||
        (! _isInternalWriterUsed) )
    {
        unsigned char * provStatRecord;
        unsigned char * cursor;
        int cursorOffset;

        _smf86_provider_status * provStatSection;

        String moduleName;
        int moduleNameLen;
        String statusValue;
        Uint32 pos;

        // For all current registered providers.
        for (Uint32 i = 0; i < instances.size(); i++)
        {
            // Get the module name.
            instances[i].getProperty(instances[i].findProperty(
                _PROPERTY_PROVIDERMODULE_NAME)).getValue().get(moduleName);

            // +1 for the 0x00 termination.
            moduleNameLen = moduleName.size()+1;

            // Allocate the full record.
            provStatRecord = (unsigned char *) calloc(1,
                sizeof(_smf86_provider_status_record) + moduleNameLen );

            // Initialize the header and product section.
            // The length is the total of subtype section + variable parts.
            _smf.initMyProlog((_smf86_record_prolog *)provStatRecord,
                PROVIDER_STATUS,
                sizeof(_smf86_provider_status) + moduleNameLen );

            // Set the pointer to the subtype section.
            provStatSection = (_smf86_provider_status *)
                (provStatRecord + sizeof(_smf86_record_prolog));

            pos = instances[i].findProperty(_PROPERTY_OPERATIONALSTATUS);

            if (pos == PEG_NOT_FOUND)
            {
                provStatSection->CurrStatus = 0;
            }
            else
            {
                CIMValue theValue = instances[i].getProperty(pos).getValue();
                if (theValue.isNull())
                {
                    provStatSection->CurrStatus = 0;
                }
                else
                {
                    Array<Uint16> moduleStatus;
                    // Get the module status
                    theValue.get(moduleStatus);
                    // reset the smf record field
                    provStatSection->CurrStatus = 0;
                    for (int j = 0; j < moduleStatus.size();j++)
                    {
                        // Accumulate the status of the provider
                        // by shifting a bit the value of moduleStatus
                        // times to the left to get the right bit set.
                        provStatSection->CurrStatus =
                            provStatSection->CurrStatus +
                            ( 1 << moduleStatus[j] );
                    }

                }
            } // End of status set.

            // The provider does not change its state.
            provStatSection->IsChanging=0;
            provStatSection->NewStatus=0;

            // The variable values are starting
            // at the end of the subtype section.
            cursor = provStatRecord + sizeof(_smf86_provider_status_record);
            cursorOffset = sizeof(_smf86_provider_status);

            // Set the provider module name.
            provStatSection->ProvNameOf = cursorOffset;
            provStatSection->ProvNameNo = 1;
            provStatSection->ProvNameLen = moduleNameLen;
            _smf.setEBCDICRecordField(cursor,
                (const char*)moduleName.getCString(),
                moduleNameLen,true);

            _writeAuditMessage(PROVIDER_STATUS,(char *)provStatRecord);
            free(provStatRecord);

        } // For all current registered providers.
    }
}
Example #17
0
static bool pre_proc_open(const Array& descriptorspec,
                          std::vector<DescriptorItem> &items) {
  /* walk the descriptor spec and set up files/pipes */
  items.resize(descriptorspec.size());
  int i = 0;
  for (ArrayIter iter(descriptorspec); iter; ++iter, ++i) {
    DescriptorItem &item = items[i];

    auto const index = iter.first().toString();
    if (!index.isNumeric()) {
      raise_warning("descriptor spec must be an integer indexed array");
      break;
    }
    item.index = index.toInt32();

    Variant descitem = iter.second();
    if (descitem.isResource()) {
      auto file = cast<File>(descitem);
      if (!item.readFile(file)) break;
    } else if (!descitem.isArray()) {
      raise_warning("Descriptor must be either an array or a File-Handle");
      break;
    } else {
      Array descarr = descitem.toArray();
      if (!descarr.exists(int64_t(0))) {
        raise_warning("Missing handle qualifier in array");
        break;
      }
      String ztype = descarr[int64_t(0)].toString();
      if (ztype == s_pipe) {
        if (!descarr.exists(int64_t(1))) {
          raise_warning("Missing mode parameter for 'pipe'");
          break;
        }
        if (!item.readPipe(descarr[int64_t(1)].toString())) break;
      } else if (ztype == s_file) {
        if (!descarr.exists(int64_t(1))) {
          raise_warning("Missing file name parameter for 'file'");
          break;
        }
        if (!descarr.exists(int64_t(2))) {
          raise_warning("Missing mode parameter for 'file'");
          break;
        }
        if (!item.openFile(descarr[int64_t(1)].toString(),
                           descarr[int64_t(2)].toString())) {
          break;
        }
      } else {
        raise_warning("%s is not a valid descriptor spec", ztype.data());
        break;
      }
    }
  }

  if (i >= descriptorspec.size()) return true;
  for (int j = 0; j < i; j++) {
    items[j].cleanup();
  }
  return false;
}
Example #18
0
void AuditLogger::logUpdateProvModuleStatus(
    const String & moduleName,
    const Array<Uint16> currentModuleStatus,
    const Array<Uint16> newModuleStatus)
{
        // check if SMF is gathering this type of records.
    if (_smf.isRecording(CONFIGURATION) ||
        (! _isInternalWriterUsed) )
    {
        unsigned char * provStatRecord;
        unsigned char * cursor;
        int cursorOffset;

        _smf86_provider_status * provStatSection;

        // +1 for the 0x00 termination.
        int moduleNameLen = moduleName.size()+1;;
        String statusValue;
        Uint32 pos;

        // Allocate the full record.
        provStatRecord = (unsigned char *) calloc(1,
            sizeof(_smf86_provider_status_record) + moduleNameLen );

        // Initialize the header and product section.
        // The length is the total of subtype section + variable parts.
        _smf.initMyProlog((_smf86_record_prolog *)provStatRecord,
            PROVIDER_STATUS,
            sizeof(_smf86_provider_status) + moduleNameLen );

        // Set the pointer to the subtype section.
        provStatSection = (_smf86_provider_status *)
            (provStatRecord + sizeof(_smf86_record_prolog));

        provStatSection->CurrStatus = 0;

        if (currentModuleStatus.size() > 0)
        {
            for (int j = 0; j < currentModuleStatus.size();j++)
            {
                // Accumulate the status of the provider
                // by shifting a bit the value of moduleStatus
                // times to the left to get the right bit set.
                provStatSection->CurrStatus =
                    provStatSection->CurrStatus +
                    ( 1 << currentModuleStatus[j] );
            }

        }

        // The provider does change.
        provStatSection->IsChanging=1;

        provStatSection->NewStatus=0;

        if (newModuleStatus.size() > 0)
        {
            // Accumulate the new status of the provider
            // by shifting a bit the value of moduleStatus
            // times to the left to get the right bit set.
            for (int j = 0; j < newModuleStatus.size();j++)
            {
                provStatSection->NewStatus =
                    provStatSection->NewStatus + ( 1 << newModuleStatus[j] );
            }

        }

        // The variable values are starting
        // at the end of the subtype section.
        cursor = provStatRecord + sizeof(_smf86_provider_status_record);
        cursorOffset =  sizeof(_smf86_provider_status);

        // Set the provider module name.
        provStatSection->ProvNameOf =cursorOffset;
        provStatSection->ProvNameNo = 1;
        provStatSection->ProvNameLen = moduleNameLen;
        _smf.setEBCDICRecordField(cursor,
            (const char*)moduleName.getCString(),
            moduleNameLen,true);

        _writeAuditMessage(PROVIDER_STATUS,(char *)provStatRecord);
        free(provStatRecord);
    }

}
void EditorSceneImporterFBXConv::_parse_materials(State& state) {

	for(int i=0;i<state.materials.size();i++)	 {

		Dictionary material = state.materials[i];

		ERR_CONTINUE(!material.has("id"));
		String id = _id(material["id"]);

		Ref<FixedMaterial> mat = memnew( FixedMaterial );

		if (material.has("diffuse")) {
			mat->set_parameter(FixedMaterial::PARAM_DIFFUSE,_get_color(material["diffuse"]));
		}

		if (material.has("specular")) {
			mat->set_parameter(FixedMaterial::PARAM_SPECULAR,_get_color(material["specular"]));
		}

		if (material.has("emissive")) {
			mat->set_parameter(FixedMaterial::PARAM_EMISSION,_get_color(material["emissive"]));
		}

		if (material.has("shininess")) {
			float exp = material["shininess"];
			mat->set_parameter(FixedMaterial::PARAM_SPECULAR_EXP,exp);
		}

		if (material.has("opacity")) {
			Color c = mat->get_parameter(FixedMaterial::PARAM_DIFFUSE);
			c.a=material["opacity"];
			mat->set_parameter(FixedMaterial::PARAM_DIFFUSE,c);
		}


		if (material.has("textures")) {

			Array textures = material["textures"];
			for(int j=0;j<textures.size();j++) {

				Dictionary texture=textures[j];
				Ref<Texture> tex;
				if (texture.has("filename")) {


					String filename=texture["filename"];
					String path=state.base_path+"/"+filename.replace("\\","/");
					if (state.texture_cache.has(path)) {
						tex=state.texture_cache[path];
					} else {
						tex = ResourceLoader::load(path,"ImageTexture");
						if (tex.is_null()) {
							if (state.missing_deps)
								state.missing_deps->push_back(path);
						}
						state.texture_cache[path]=tex; //add anyway
					}
				}

				if (tex.is_valid() && texture.has("type")) {

					String type=texture["type"];
					if (type=="DIFFUSE")
						mat->set_texture(FixedMaterial::PARAM_DIFFUSE,tex);
					else if (type=="SPECULAR")
						mat->set_texture(FixedMaterial::PARAM_SPECULAR,tex);
					else if (type=="SHININESS")
						mat->set_texture(FixedMaterial::PARAM_SPECULAR_EXP,tex);
					else if (type=="NORMAL")
						mat->set_texture(FixedMaterial::PARAM_NORMAL,tex);
					else if (type=="EMISSIVE")
						mat->set_texture(FixedMaterial::PARAM_EMISSION,tex);
				}

			}
		}

		state.material_cache[id]=mat;

	}

}
Example #20
0
void AuditLogger::logCurrentConfig(
    const Array<String> & propertyNames,
    const Array<String> & propertyValues)
{
    // check if SMF is gathering this type of records.
    if (_smf.isRecording(CONFIGURATION) ||
        (! _isInternalWriterUsed) )
    {
        unsigned char * confRecord;
        unsigned char * cursor;
        int cursorOffset;

        _smf86_configuration * confSection;
        int nameLen;
        int valueLen;

        // For all properties write a record.
        for (Uint32 i = 0; i < propertyNames.size(); i++)
        {
            // +1 for the 0x00 termination.
            nameLen = propertyNames[i].size()+1;
            valueLen =  propertyValues[i].size()+1;

            // Allocate the full record.
            confRecord = (unsigned char *) calloc(1,
                sizeof(_smf86_configuration_record) + nameLen + valueLen );

            // Initialize the header and product section.
            // The length is the total of subtype section + variable parts.
            _smf.initMyProlog((_smf86_record_prolog *)confRecord, CONFIGURATION,
                sizeof(_smf86_configuration) + nameLen + valueLen );

            // Set the pointer to the subtype section.
            confSection = (_smf86_configuration *)
                (confRecord + sizeof(_smf86_record_prolog));

            // No user Id for logging current configuration.
            _smf.setEBCDICRecordField(confSection->UserID, "",
                sizeof(confSection->UserID),false);

            // Configutation is listed
            confSection->PropChange = 0;

            // The variable values are starting
            // at the end of the subtype section.
            cursor = confRecord + sizeof(_smf86_configuration_record);
            cursorOffset = sizeof(_smf86_configuration);

           // Set the propety name
           confSection->NameOf = cursorOffset;
           confSection->NameNo = 1;
           confSection->NameLen = nameLen;
           _smf.setEBCDICRecordField(cursor,
               (const char*)propertyNames[i].getCString(),
               nameLen,true);

           cursor = cursor + nameLen;
           cursorOffset = cursorOffset + nameLen;

           // Set the property value.
           confSection->ValueOf = cursorOffset;
           confSection->ValueNo = 1;
           confSection->ValueLen = valueLen;
           _smf.setEBCDICRecordField(cursor,
               (const char*)propertyValues[i].getCString(),
               valueLen,true);

            // New property is set to 0, not used at listing the configuration.
            confSection->NewValueOf = 0;
            confSection->NewValueNo = 0;
            confSection->NewValueLen = 0;

            _writeAuditMessage(CONFIGURATION,(char *)confRecord);
            free(confRecord);
        } // End for all properties do.
    }
}
Example #21
0
Variant ArrayUtil::Splice(const Array& input, int offset, int64_t length /* = 0 */,
                          const Variant& replacement /* = uninit_variant */,
                          Array *removed /* = NULL */) {
  int num_in = input.size();
  if (offset > num_in) {
    offset = num_in;
  } else if (offset < 0 && (offset = (num_in + offset)) < 0) {
    offset = 0;
  }

  if (length < 0) {
    length = num_in - offset + length;
  } else if (((unsigned)offset + (unsigned)length) > (unsigned)num_in) {
    length = num_in - offset;
  }

  Array out_hash = Array::Create();
  int pos = 0;
  ArrayIter iter(input);
  for (; pos < offset && iter; ++pos, ++iter) {
    Variant key(iter.first());
    auto const v = iter.secondVal();
    if (key.isNumeric()) {
      out_hash.appendWithRef(v);
    } else {
      out_hash.setWithRef(key, v, true);
    }
  }

  for (; pos < offset + length && iter; ++pos, ++iter) {
    if (removed) {
      Variant key(iter.first());
      auto const v = iter.secondVal();
      if (key.isNumeric()) {
        removed->appendWithRef(v);
      } else {
        removed->setWithRef(key, v, true);
      }
    }
  }

  Array arr = replacement.toArray();
  if (!arr.empty()) {
    for (ArrayIter iterb(arr); iterb; ++iterb) {
      auto const v = iterb.secondVal();
      out_hash.appendWithRef(v);
    }
  }

  for (; iter; ++iter) {
    Variant key(iter.first());
    auto const v = iter.secondVal();
    if (key.isNumeric()) {
      out_hash.appendWithRef(v);
    } else {
      out_hash.setWithRef(key, v, true);
    }
  }

  return out_hash;
}
void RefIntegral::transformZeroForm(const CellJacobianBatch& JVol,
  const Array<int>& isLocalFlag,  
  const RCP<Array<int> >& cellLIDs,
  const double& coeff,
  RCP<Array<double> >& A) const
{
  TimeMonitor timer(ref0IntegrationTimer());

  TEUCHOS_TEST_FOR_EXCEPTION(order() != 0, std::logic_error,
    "RefIntegral::transformZeroForm() called "
    "for form of order " << order());

  Tabs tabs;  
  SUNDANCE_MSG1(integrationVerb(), tabs << "doing zero form by reference");

  double& a = (*A)[0];
  int flops = 0;
  const Array<int>* cellLID = cellLIDs.get();

  /* if we don't need to check whether elements are local, we
   * can streamline the loop. This will be the case when
   * we are evaluating a functional but not its gradient */
  double w = coeff * W_[0][0];
  if ((int) isLocalFlag.size()==0)
  {
     	if (globalCurve().isCurveValid())
     	{     /* ---------- ACI logic ----------- */

     		Array<double> quadWeightsTmp = quadWeights_;
     		Array<Point> quadPointsTmp = quadPts_;
     		bool isCutByCurve;

     		for (int c=0; c<JVol.numCells(); c++)
     		{
     			int fc = 0;
   				/* call the special integration routine */
   				quadWeightsTmp = quadWeights_;
   				quadPointsTmp = quadPts_;
   				quad_.getAdaptedWeights(cellType(), dim(), (*cellLID)[c], fc ,mesh(),
   						globalCurve(), quadPointsTmp, quadWeightsTmp, isCutByCurve);
   				/* if we have special weights then do the same as before */
   				if (isCutByCurve){
   					double sumweights = 0;
   					for (int j=0; j < quadWeightsTmp.size(); j++) sumweights += chop(quadWeightsTmp[j]);
   					flops+=3+quadWeightsTmp.size();  //Todo: the curve stuff not counted
   					a += coeff * sumweights * fabs(JVol.detJ()[c]);
   				} else {
   					flops+=2;  //Todo: the curve stuff not counted
   					a += w * fabs(JVol.detJ()[c]);
   				}
     		}
     	}
     	else /* -------- NO ACI logic ------- */
     	{
     		for (int c=0; c<JVol.numCells(); c++)
     		{
 				flops+=2;
 				a += w * fabs(JVol.detJ()[c]);
     		}
     	}

  }
  else
  {
    TEUCHOS_TEST_FOR_EXCEPTION( (int) isLocalFlag.size() != JVol.numCells(),
      std::runtime_error,
      "mismatch between isLocalFlag.size()=" 
      << isLocalFlag.size()
      << " and JVol.numCells()=" << JVol.numCells());

      int fc = 0;
      if (globalCurve().isCurveValid())
      {   /* ---------- ACI logic ----------- */
    		Array<double> quadWeightsTmp = quadWeights_;
     		Array<Point> quadPointsTmp = quadPts_;
     		bool isCutByCurve;

    		for (int c=0; c<JVol.numCells(); c++)
    		{
    		  if (isLocalFlag[c])
    		  {

    			/* call the special integration routine */
    			quadWeightsTmp = quadWeights_;
    			quadPointsTmp = quadPts_;
    			quad_.getAdaptedWeights(cellType(), dim(), (*cellLID)[c], fc , mesh(),
    					globalCurve(), quadPointsTmp, quadWeightsTmp, isCutByCurve);
    			/* if we do not have special weights then do the same as before */
    			if (isCutByCurve){
    				double sumweights = 0;
    				for (int j=0; j < quadWeightsTmp.size(); j++) sumweights += chop(quadWeightsTmp[j]);
    				flops+=3+quadWeightsTmp.size();  //Todo: the curve stuff not counted
    				a += coeff * sumweights * fabs(JVol.detJ()[c]);
    			} else {
    				flops+=2;  //Todo: the curve stuff not counted
    				a += w * fabs(JVol.detJ()[c]);
    			}
    		  }
    		}
    	}
        else         /* ---------- NO ACI logic ----------- */
    	{
    		for (int c=0; c<JVol.numCells(); c++)
    		{
      		  if (isLocalFlag[c])
      		  {
    			flops+=2;
    			a += w * fabs(JVol.detJ()[c]);
      		  }
    		}
    	}
  }
  addFlops(flops);
}
Example #23
0
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
    Array params;
    BOOST_FOREACH(const std::string &param, strParams)
        params.push_back(param);

    int n = params.size();

    //
    // Special case non-string parameter types
    //
    if (strMethod == "stop"                   && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "getaddednodeinfo"       && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "setgenerate"            && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "getnetworkhashps"       && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "getnetworkhashps"       && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "sendtoaddress"          && n > 1) ConvertTo<double>(params[1]);
    if (strMethod == "settxfee"               && n > 0) ConvertTo<double>(params[0]);
    if (strMethod == "getreceivedbyaddress"   && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "getreceivedbyaccount"   && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "listreceivedbyaddress"  && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "listreceivedbyaddress"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "listreceivedbyaccount"  && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "listreceivedbyaccount"  && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getbalance"             && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "getblockhash"           && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "getblockinfo"           && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "move"                   && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "move"                   && n > 3) ConvertTo<int64_t>(params[3]);
    if (strMethod == "sendfrom"               && n > 2) ConvertTo<double>(params[2]);
    if (strMethod == "sendfrom"               && n > 3) ConvertTo<int64_t>(params[3]);
    if (strMethod == "listtransactions"       && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "listtransactions"       && n > 2) ConvertTo<int64_t>(params[2]);
    if (strMethod == "listaccounts"           && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "walletpassphrase"       && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "getblocktemplate"       && n > 0) ConvertTo<Object>(params[0]);
    if (strMethod == "listsinceblock"         && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "sendmany"               && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "sendmany"               && n > 2) ConvertTo<int64_t>(params[2]);
    if (strMethod == "addmultisigaddress"     && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "addmultisigaddress"     && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "createmultisig"         && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "createmultisig"         && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "listunspent"            && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "listunspent"            && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "listunspent"            && n > 2) ConvertTo<Array>(params[2]);
    if (strMethod == "getblock"               && n > 1) ConvertTo<bool>(params[1]);
    if (strMethod == "getrawtransaction"      && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "createrawtransaction"   && n > 0) ConvertTo<Array>(params[0]);
    if (strMethod == "createrawtransaction"   && n > 1) ConvertTo<Object>(params[1]);
    if (strMethod == "signrawtransaction"     && n > 1) ConvertTo<Array>(params[1], true);
    if (strMethod == "signrawtransaction"     && n > 2) ConvertTo<Array>(params[2], true);
    if (strMethod == "sendrawtransaction"     && n > 1) ConvertTo<bool>(params[1], true);
    if (strMethod == "gettxout"               && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "gettxout"               && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "lockunspent"            && n > 0) ConvertTo<bool>(params[0]);
    if (strMethod == "lockunspent"            && n > 1) ConvertTo<Array>(params[1]);
    if (strMethod == "importprivkey"          && n > 2) ConvertTo<bool>(params[2]);
    if (strMethod == "verifychain"            && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "verifychain"            && n > 1) ConvertTo<int64_t>(params[1]);
    if (strMethod == "keypoolrefill"          && n > 0) ConvertTo<int64_t>(params[0]);
    if (strMethod == "getrawmempool"          && n > 0) ConvertTo<bool>(params[0]);

    return params;
}
void RefIntegral::transformTwoForm(const CellJacobianBatch& JTrans,
  const CellJacobianBatch& JVol,
  const Array<int>& facetIndex, 
  const RCP<Array<int> >& cellLIDs,
  const double& coeff,
  RCP<Array<double> >& A) const
{
  TimeMonitor timer(ref2IntegrationTimer());
  TEUCHOS_TEST_FOR_EXCEPTION(order() != 2, std::logic_error,
    "RefIntegral::transformTwoForm() called for form "
    "of order " << order());
  
  Tabs tabs;  
  SUNDANCE_MSG1(transformVerb(), tabs << "doing two form by reference");

  int nfc = nFacetCases();

	  SUNDANCE_MSG1(transformVerb(), tabs << "doing two form by reference ... ");
  /* If the derivative orders are zero, the only transformation to be done 
   * is to multiply by the cell's Jacobian determinant */
  if (testDerivOrder() == 0 && unkDerivOrder() == 0)
  {
      if (globalCurve().isCurveValid())
      {     /* ----------- ACI logic ------------ */

    	   Array<double> quadWeightsTmp = quadWeights_;
    	   Array<Point> quadPointsTmp = quadPts_;
    	   bool isCutByCurve = false;

    	   double* aPtr = &((*A)[0]);
    	   int count = 0;
    	   for (int c=0; c<JVol.numCells(); c++)
    	   {
    	     int fc = 0;
    	     if (nFacetCases() != 1) fc = facetIndex[c];

    	     /* ---------- ACI ----------- */
    	     /* call the special integration routine */
    	     quadWeightsTmp = quadWeights_;
    	     quadPointsTmp = quadPts_;
    	     quad_.getAdaptedWeights(cellType(), dim(), (*cellLIDs)[c] , fc ,
    	    		 mesh(), globalCurve(), quadPointsTmp, quadWeightsTmp, isCutByCurve);
    	     if (isCutByCurve){
    	    	 Array<double> w;
    	    	 int ci = 0;
    	    	 w.resize(nNodesTest()*nNodesUnk()); //recalculate the special weights
    	    	 for (int nt = 0 ; nt < nNodesTest() ; nt++)
    	    		 for(int nu=0 ; nu < nNodesUnk() ; nu++ , ci++){
    	    			 w[ci] = 0.0;
    	    			 for (int q=0 ; q < quadWeightsTmp.size() ; q++)
    	    				 w[ci] += chop( quadWeightsTmp[q] * W_ACI_F2_[fc][q][0][nt][0][nu] );
    	    		 }
    	    	 // do the integration here
    	    	 double detJ = coeff * fabs(JVol.detJ()[c]);
    	    	 for (int n=0; n<nNodes(); n++, count++)
    	    	 {
    	    		 aPtr[count] += detJ*w[n];
    	    	 }
    	     }
    	     else
    	     {
    	    	  const Array<double>& w = W_[fc];
    	    	  double detJ = coeff * fabs(JVol.detJ()[c]);
    	    	  for (int n=0; n<nNodes(); n++, count++)
    	    	  {
    	    		  aPtr[count] += detJ*w[n];
    	    	  }
    	     }
    	   }
  	  }
      else        /* ---------- NO ACI logic----------- */
      {
    	  double* aPtr = &((*A)[0]);
    	  int count = 0;
    	  for (int c=0; c<JVol.numCells(); c++)
    	  {
    		  int fc = 0;
    		  if (nFacetCases() != 1) fc = facetIndex[c];

    		  const Array<double>& w = W_[fc];
    		  double detJ = coeff * fabs(JVol.detJ()[c]);
    		  for (int n=0; n<nNodes(); n++, count++)
    		  {
    			  aPtr[count] += detJ*w[n];
    		  }
    	  }
      }
    addFlops(JVol.numCells() * (nNodes() + 1));
  }
  else
  {
    /* If the derivative order is nonzero, then we have to do a transformation. 
     * If we're also on a cell of dimension lower than maximal, we need to refer
     * to the facet index of the facet being integrated. */
    int nCells = JVol.numCells();
    double one = 1.0;
    int nTransRows = nRefDerivUnk()*nRefDerivTest();

    createTwoFormTransformationMatrix(JTrans, JVol);
      
    double* GPtr;
    if (testDerivOrder() == 0)
    {
      GPtr = &(G(beta())[0]);
      SUNDANCE_MSG2(transformVerb(),
        Tabs() << "transformation matrix=" << G(beta()));
    }
    else if (unkDerivOrder() == 0)
    {
      GPtr = &(G(alpha())[0]);
      SUNDANCE_MSG2(transformVerb(),
        Tabs() << "transformation matrix=" << G(alpha()));
    }
    else
    {
      GPtr = &(G(alpha(), beta())[0]);
      SUNDANCE_MSG2(transformVerb(),
        Tabs() << "transformation matrix=" 
        << G(alpha(),beta()));
    }
      
    int nNodes0 = nNodes();

    if (nFacetCases()==1)
    {
      /* if we're on a maximal cell, we can do transformations 
       * for all cells in a single batch. 
       */
      if (globalCurve().isCurveValid())
      {          /* ---------- ACI logic ----------- */

    	 Array<double> quadWeightsTmp = quadWeights_;
    	 Array<Point> quadPointsTmp = quadPts_;
    	 bool isCutByCurve = false;

       	 for (int c=0; c<JVol.numCells(); c++)
       	 {
             int fc = 0;
             if (nfc != 1) fc = facetIndex[c];

             double* aPtr = &((*A)[c*nNodes0]);
             double* gPtr = &(GPtr[c*nTransRows]);
             int oneI = 1;
       		 /* call the special integration routine */
         	//SUNDANCE_MSG1(transformVerb(), tabs << "before quad_.getAdaptedWeights");
         	 quadWeightsTmp = quadWeights_;
             quadPointsTmp = quadPts_;
       		 quad_.getAdaptedWeights(cellType(), dim(), (*cellLIDs)[c], fc ,
             mesh(),globalCurve(), quadPointsTmp, quadWeightsTmp, isCutByCurve);
         	//SUNDANCE_MSG1(transformVerb(), tabs << "after quad_.getAdaptedWeights");
       		 if (isCutByCurve){
       			 Array<double> w;
       			 w.resize(nNodesUnk()*nNodesTest()*nRefDerivUnk()*nRefDerivTest());
       			 for ( int i = 0 ; i < w.size() ; i++) w[i] = 0.0;
       			 //recalculate the special weights
       		     for (int t=0; t<nRefDerivTest(); t++){
       		        for (int nt=0; nt<nNodesTest(); nt++)
       		          for (int u=0; u<nRefDerivUnk(); u++)
       		            for (int nu=0; nu<nNodesUnk(); nu++)
       		            	for (int q=0 ; q < quadWeightsTmp.size() ; q++)
       		                // unkNode + nNodesUnk()*testNode  + nNodes()*(unkDerivDir + nRefDerivUnk()*testDerivDir)
       		                    w[nu + nNodesUnk()*nt  + nNodes()*(u + nRefDerivUnk()*t)] +=
       		                    		chop(quadWeightsTmp[q]*W_ACI_F2_[0][q][t][nt][u][nu]);
       		     }
      		      ::dgemm_("N", "N", &nNodes0, &oneI , &nTransRows, &coeff, &(w[0]),
      		        &nNodes0, &(gPtr[0]), &nTransRows, &one,
      		        &(aPtr[0]), &nNodes0);
       		  }else{
       		     ::dgemm_("N", "N", &nNodes0, &oneI , &nTransRows, &coeff, &(W_[0][0]),
       		        &nNodes0, &(gPtr[0]), &nTransRows, &one,
       		        &(aPtr[0]), &nNodes0);
       		  }
       	 } // end from the for loop over the cells
      }
      else /* ---------- NO ACI ----------- */
      {
        	 ::dgemm_("N", "N", &nNodes0, &nCells, &nTransRows, &coeff, &(W_[0][0]),
        		 &nNodes0, GPtr, &nTransRows, &one,
        		 &((*A)[0]), &nNodes0);
      }
    }
    else
    {
      /* If we're on a lower-dimensional cell and have to transform, 
       * we've got to do each transformation using a different facet case */
        if (globalCurve().isCurveValid())
        {   /* ---------- ACI logic ----------- */
            int oneI = 1;
            Array<double> quadWeightsTmp = quadWeights_;
            Array<Point> quadPointsTmp = quadPts_;
            bool isCutByCurve = false;

            for (int c=0; c<JVol.numCells(); c++)
            {
              int fc = 0;
              if (nfc != 1) fc = facetIndex[c];
              double* aPtr = &((*A)[c*nNodes0]);
              double* gPtr = &(GPtr[c*nTransRows]);
              SUNDANCE_MSG2(integrationVerb(),
                tabs << "c=" << c << ", facet case=" << fc
                << " W=" << W_[fc]);

              /* call the special integration routine */
              quadWeightsTmp = quadWeights_;
              quadPointsTmp = quadPts_;
              quad_.getAdaptedWeights(cellType(), dim(), (*cellLIDs)[c], fc ,
            		  mesh(), globalCurve(), quadPointsTmp, quadWeightsTmp, isCutByCurve);
              if (isCutByCurve){
            	  Array<double> w;
            	  w.resize(nNodesUnk()*nNodesTest()*nRefDerivUnk()*nRefDerivTest());
            	  for ( int i = 0 ; i < w.size() ; i++) w[i] = 0.0;
            	  //recalculate the special weights
            	  for (int t=0; t<nRefDerivTest(); t++){
            		  for (int nt=0; nt<nNodesTest(); nt++)
            			  for (int u=0; u<nRefDerivUnk(); u++)
            				  for (int nu=0; nu<nNodesUnk(); nu++)
            					  for (int q=0 ; q < quadWeightsTmp.size() ; q++)
            						  // unkNode + nNodesUnk()*testNode  + nNodes()*(unkDerivDir + nRefDerivUnk()*testDerivDir)
            						  w[nu + nNodesUnk()*nt  + nNodes()*(u + nRefDerivUnk()*t)] +=
            								  chop( quadWeightsTmp[q]*W_ACI_F2_[fc][q][t][nt][u][nu] );
            	  }
            	  ::dgemm_("N", "N", &nNodes0, &oneI , &nTransRows, &coeff, &(w[0]),
            			  &nNodes0, &(gPtr[0]), &nTransRows, &one,
            			  &(aPtr[0]), &nNodes0);
				  }else{
					  ::dgemm_("N", "N", &nNodes0, &oneI , &nTransRows, &coeff, &(W_[fc][0]),
							  &nNodes0, &(gPtr[0]), &nTransRows, &one,
							  &(aPtr[0]), &nNodes0);
				  }
            }
        }
        else         /* ---------- NO ACI ----------- */
        {
            int N = 1;
            for (int c=0; c<JVol.numCells(); c++)
            {
              int fc = 0;
              if (nfc != 1) fc = facetIndex[c];
              double* aPtr = &((*A)[c*nNodes0]);
              double* gPtr = &(GPtr[c*nTransRows]);
              SUNDANCE_MSG2(integrationVerb(),
                tabs << "c=" << c << ", facet case=" << fc
                << " W=" << W_[fc]);

              ::dgemm_("N", "N", &nNodes0, &N, &nTransRows, &coeff, &(W_[fc][0]),
            		  &nNodes0, gPtr, &nTransRows, &one,
            		  aPtr, &nNodes0);
            }
        }
    }// from else of (nFacetCases()==1)
      
    addFlops(2 * nNodes0 * nCells * nTransRows);
  }
}
Example #25
0
Value getworkex(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 2)
        throw runtime_error(
            "getworkex [data, coinbase]\n"
            "If [data, coinbase] is not specified, returns extended work data.\n"
        );

    if (vNodes.empty())
        throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Gytecoin is not connected!");

    if (IsInitialBlockDownload())
        throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Gytecoin is downloading blocks...");

    typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
    static mapNewBlock_t mapNewBlock;    // FIXME: thread safety
    static vector<CBlockTemplate*> vNewBlockTemplate;
    static CReserveKey reservekey(pwalletMain);

    if (params.size() == 0)
    {
        // Update block
        static unsigned int nTransactionsUpdatedLast;
        static CBlockIndex* pindexPrev;
        static int64 nStart;
        static CBlockTemplate* pblocktemplate;
        if (pindexPrev != pindexBest ||
            (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
        {
            if (pindexPrev != pindexBest)
            {
                // Deallocate old blocks since they're obsolete now
                mapNewBlock.clear();
                BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
                    delete pblocktemplate;
                vNewBlockTemplate.clear();
            }

            // Clear pindexPrev so future getworks make a new block, despite any failures from here on
            pindexPrev = NULL;

            // Store the pindexBest used before CreateNewBlock, to avoid races
            nTransactionsUpdatedLast = nTransactionsUpdated;
            CBlockIndex* pindexPrevNew = pindexBest;
            nStart = GetTime();

            // Create new block
            pblocktemplate = CreateNewBlockWithKey(*pMiningKey);
            if (!pblocktemplate)
                throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
            vNewBlockTemplate.push_back(pblocktemplate);

            // Need to update only after we know CreateNewBlock succeeded
            pindexPrev = pindexPrevNew;
        }
        CBlock* pblock = &pblocktemplate->block; // pointer for convenience

        // Update nTime
        pblock->UpdateTime(pindexPrev);
        pblock->nNonce = 0;

        // Update nExtraNonce
        static unsigned int nExtraNonce = 0;
        IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);

        // Save
        mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);

        // Pre-build hash buffers
        char pmidstate[32];
        char pdata[128];
        char phash1[64];
        FormatHashBuffers(pblock, pmidstate, pdata, phash1);

        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();

        CTransaction coinbaseTx = pblock->vtx[0];
        std::vector<uint256> merkle = pblock->GetMerkleBranch(0);

        Object result;
        result.push_back(Pair("data",     HexStr(BEGIN(pdata), END(pdata))));
        result.push_back(Pair("target",   HexStr(BEGIN(hashTarget), END(hashTarget))));

        CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
        ssTx << coinbaseTx;
        result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));

        Array merkle_arr;

        BOOST_FOREACH(uint256 merkleh, merkle) {
            printf("%s\n", merkleh.ToString().c_str());
            merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
        }

        result.push_back(Pair("merkle", merkle_arr));

        return result;
    }
Example #26
0
    inline bool zsuper(STATE, CallFrame* call_frame, intptr_t literal) {
      Object* block = stack_pop();
      Object* const recv = call_frame->self();

      VariableScope* scope = call_frame->method_scope(state);
      interp_assert(scope);

      MachineCode* mc = scope->method()->machine_code();
      Object* splat_obj = 0;
      Array* splat = 0;

      size_t arg_count = mc->total_args;

      if(mc->splat_position >= 0) {
        splat_obj = scope->get_local(state, mc->splat_position);
        splat = try_as<Array>(splat_obj);
        if(splat) {
          arg_count += splat->size();
        } else {
          arg_count++;
        }
      }

      Tuple* tup = Tuple::create(state, arg_count);
      native_int tup_index = 0;

      native_int fixed_args;
      if(splat) {
        fixed_args = mc->splat_position;
      } else if(mc->keywords) {
        fixed_args = mc->total_args - 1;
      } else {
        fixed_args = mc->total_args;
      }
      for(native_int i = 0; i < fixed_args; i++) {
        tup->put(state, tup_index++, scope->get_local(state, i));
      }

      if(splat) {
        for(native_int i = 0; i < splat->size(); i++) {
          tup->put(state, tup_index++, splat->get(state, i));
        }
      } else if(splat_obj) {
        tup->put(state, tup_index++, splat_obj);
      }

      if(mc->post_args) {
        native_int post_position = mc->splat_position + 1;
        for(native_int i = post_position; i < post_position + mc->post_args; i++) {
          tup->put(state, tup_index++, scope->get_local(state, i));
        }
      }

      if(mc->keywords) {
        native_int placeholder_position = splat_obj ? mc->total_args : mc->total_args - 1;
        native_int keywords_position = placeholder_position + 1;

        Object* placeholder = scope->get_local(state, placeholder_position);
        Array* ary = Array::create(state, 2);

        for(native_int i = keywords_position; i <= mc->keywords_count; i++) {
          ary->set(state, 0, as<Symbol>(call_frame->compiled_code->local_names()->at(state, i)));
          ary->set(state, 1, scope->get_local(state, i));

          placeholder->send(state, state->symbol("[]="), ary);
        }

        tup->put(state, tup_index++, scope->get_local(state, placeholder_position));
      }

      CallSite* call_site = reinterpret_cast<CallSite*>(literal);

      Arguments new_args(call_site->name(), recv, block, arg_count, 0);
      new_args.use_tuple(tup, arg_count);

      Object* ret;

      Symbol* current_name = call_frame->original_name();
      if(call_site->name() != current_name) {
        call_site->name(state, current_name);
      }

      ret = call_site->execute(state, new_args);

      state->vm()->checkpoint(state);

      CHECK_AND_PUSH(ret);
    }
Example #27
0
 Disposable<Array> FdmHullWhiteOp::apply_mixed(const Array& r) const {
     Array retVal(r.size(), 0.0);
     return retVal;
 }
Example #28
0
xdebug_xml_node* xdebug_var_export_xml_node(const char* name,
        const char* fullName,
        const char* facet,
        const Variant& var,
        XDebugExporter& exporter) {
    // Setup the node. Each const cast is necessary due to xml api
    xdebug_xml_node* node = xdebug_xml_node_init("property");
    if (name != nullptr) {
        xdebug_xml_add_attribute_ex(node, "name", const_cast<char*>(name), 0, 1);
    }
    if (fullName != nullptr) {
        xdebug_xml_add_attribute_ex(node, "fullname", const_cast<char*>(fullName),
                                    0, 1);
    }
    if (facet != nullptr) {
        xdebug_xml_add_attribute_ex(node, "facet", const_cast<char*>(facet), 0, 1);
    }
    xdebug_xml_add_attribute_ex(node, "address",
                                xdebug_sprintf("%ld", (long) &var), 0, 1);

    // Case on the type for the rest
    if (var.isBoolean()) {
        xdebug_xml_add_attribute(node, "type", "bool");
        xdebug_xml_add_text(node, xdebug_sprintf("%d",  var.toBoolean()));
    } else if (var.isNull()) {
        xdebug_xml_add_attribute(node, "type", "null");
    } else if (var.isInteger()) {
        xdebug_xml_add_attribute(node, "type", "int");
        xdebug_xml_add_text(node, xdebug_sprintf("%ld", var.toInt64()));
    } else if (var.isDouble()) {
        xdebug_xml_add_attribute(node, "type", "float");
        xdebug_xml_add_text(node, xdebug_sprintf("%lG", var.toDouble()));
    } else if (var.isString()) {
        // Add the type and the original size
        String str = var.toString();
        xdebug_xml_add_attribute(node, "type", "string");
        xdebug_xml_add_attribute_ex(node, "size",
                                    xdebug_sprintf("%d", str.size()), 0, 1);

        // Possibly shrink the string, then add it to the node
        if (exporter.max_data != 0 && str.size() > exporter.max_data) {
            str = str.substr(0, exporter.max_data);
        }
        xdebug_xml_add_text_encodel(node, xdstrdup(str.data()), str.size());
    } else if (var.isArray()) {
        Array arr = var.toArray();
        xdebug_xml_add_attribute(node, "type", "array");
        xdebug_xml_add_attribute(node, "children",
                                 const_cast<char*>(arr.size() > 0 ? "1" : "0"));

        // If we've already seen this object, return
        if (exporter.counts[arr.get()]++ > 0) {
            xdebug_xml_add_attribute(node, "recursive", "1");
            return node;
        }

        // Write the # of children then short-circuit if we are too deep
        xdebug_xml_add_attribute_ex(node, "numchildren",
                                    xdebug_sprintf("%d", arr.size()), 0, 1);
        if (exporter.level++ >= exporter.max_depth) {
            return node;
        }

        // Compute the page and the start/end indices
        // Note that php xdebug doesn't support pages except for at the top level
        uint32_t page = exporter.level == 0 ? exporter.page : 0;
        uint32_t start = page * exporter.max_children;
        uint32_t end = (page + 1) * exporter.max_children;
        xdebug_xml_add_attribute_ex(node, "page", xdebug_sprintf("%d", page), 0, 1);
        xdebug_xml_add_attribute_ex(node, "pagesize",
                                    xdebug_sprintf("%d", exporter.max_children),
                                    0, 1);
        // Add each child
        ArrayIter iter(arr);
        iter.setPos(start);
        for (uint32_t i = start; i < end && iter; i++, ++iter) {
            xdebug_array_element_export_xml_node(*node, name,
                                                 iter.first(),
                                                 iter.second(),
                                                 exporter);
        }

        // Done at this level
        exporter.level--;
        exporter.counts[arr.get()]--;
    } else if (var.isObject()) {
        // TODO(#4489053) This could be merged into the above array code. For now,
        // it's separate as this was pulled originally from xdebug
        ObjectData* obj = var.toObject().get();
        Class* cls = obj->getVMClass();
        Array props = get_object_props(obj);

        // Add object info
        xdebug_xml_add_attribute(node, "type", "object");
        xdebug_xml_add_attribute_ex(node, "classname",
                                    xdstrdup(cls->name()->data()), 0, 1);
        xdebug_xml_add_attribute(node, "children",
                                 const_cast<char*>(props.size() ? "1" : "0"));

        // If we've already seen this object, return
        if (exporter.counts[obj]++ > 0) {
            return node;
        }

        // Add the # of props then short circuit if we are too deep
        xdebug_xml_add_attribute_ex(node, "numchildren",
                                    xdebug_sprintf("%d", props.size()), 0, 1);
        if (exporter.level++ >= exporter.max_depth) {
            return node;
        }

        // Compute the page and the start/end indices
        // Note that php xdebug doesn't support pages except for at the top level
        uint32_t page = exporter.level == 1 ? exporter.page : 0;
        uint32_t start = page * exporter.max_children;
        uint32_t end = (page + 1) * exporter.max_children;
        xdebug_xml_add_attribute_ex(node, "page", xdebug_sprintf("%d", page), 0, 1);
        xdebug_xml_add_attribute_ex(node, "pagesize",
                                    xdebug_sprintf("%d", exporter.max_children),
                                    0, 1);

        // Add each property
        ArrayIter iter(props);
        iter.setPos(start);
        for (uint32_t i = start; i < end && iter; i++, ++iter) {
            xdebug_object_element_export_xml_node(*node, name, obj,
                                                  iter.first(),
                                                  iter.second(),
                                                  exporter);
        }

        // Done at this level
        exporter.level--;
        exporter.counts[(void*) obj]--;
    } else if (var.isResource()) {
        ResourceData* res = var.toResource().get();
        xdebug_xml_add_attribute(node, "type", "resource");
        const char* text = xdebug_sprintf("resource id='%ld' type='%s'",
                                          res->o_getId(),
                                          res->o_getResourceName().data());
        xdebug_xml_add_text(node, const_cast<char*>(text));
    } else {
        xdebug_xml_add_attribute(node, "type", "null");
    }
    return node;
}
Example #29
0
Value smsgoptions(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 3)
        throw runtime_error(
            "smsgoptions [list|set <optname> <value>]\n"
            "List and manage options.");
    
    std::string mode = "list";
    if (params.size() > 0)
    {
        mode = params[0].get_str();
    };
    
    Object result;
    
    if (mode == "list")
    {
        result.push_back(Pair("option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false")));
        result.push_back(Pair("option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false")));
        
        result.push_back(Pair("result", "Success."));
    } else
    if (mode == "set")
    {
        if (params.size() < 3)
        {
            result.push_back(Pair("result", "Too few parameters."));
            result.push_back(Pair("expected", "set <optname> <value>"));
            return result;
        };
        
        std::string optname = params[1].get_str();
        std::string value   = params[2].get_str();
        
        if (optname == "newAddressRecv")
        {
            if (value == "+" || value == "on"  || value == "true"  || value == "1")
            {
                smsgOptions.fNewAddressRecv = true;
            } else
            if (value == "-" || value == "off" || value == "false" || value == "0")
            {
                smsgOptions.fNewAddressRecv = false;
            } else
            {
                result.push_back(Pair("result", "Unknown value."));
                return result;
            };
            result.push_back(Pair("set option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false")));
        } else
        if (optname == "newAddressAnon")
        {
            if (value == "+" || value == "on"  || value == "true"  || value == "1")
            {
                smsgOptions.fNewAddressAnon = true;
            } else
            if (value == "-" || value == "off" || value == "false" || value == "0")
            {
                smsgOptions.fNewAddressAnon = false;
            } else
            {
                result.push_back(Pair("result", "Unknown value."));
                return result;
            };
            result.push_back(Pair("set option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false")));
        } else
        {
            result.push_back(Pair("result", "Option not found."));
            return result;
        };
    } else
    {
        result.push_back(Pair("result", "Unknown Mode."));
        result.push_back(Pair("expected", "smsgoption [list|set <optname> <value>]"));
    };
    return result;
}
Example #30
0
/**
 * New sprintf implementation for PHP.
 *
 * Modifiers:
 *
 *  " "   pad integers with spaces
 *  "-"   left adjusted field
 *   n    field size
 *  "."n  precision (floats only)
 *  "+"   Always place a sign (+ or -) in front of a number
 *
 * Type specifiers:
 *
 *  "%"   literal "%", modifiers are ignored.
 *  "b"   integer argument is printed as binary
 *  "c"   integer argument is printed as a single character
 *  "d"   argument is an integer
 *  "f"   the argument is a float
 *  "o"   integer argument is printed as octal
 *  "s"   argument is a string
 *  "x"   integer argument is printed as lowercase hexadecimal
 *  "X"   integer argument is printed as uppercase hexadecimal
 */
String string_printf(const char *format, int len, const Array& args) {
  Array vargs = args;
  if (!vargs.isNull() && !vargs->isVectorData()) {
    vargs = Array::Create();
    for (ArrayIter iter(args); iter; ++iter) {
      vargs.append(iter.second());
    }
  }

  if (len == 0) {
    return empty_string();
  }

  int size = 240;
  StringBuffer result(size);

  int argnum = 0, currarg = 1;
  for (int inpos = 0; inpos < len; ++inpos) {
    char ch = format[inpos];

    int expprec = 0;
    if (ch != '%') {
      result.append(ch);
      continue;
    }

    if (format[inpos + 1] == '%') {
      result.append('%');
      inpos++;
      continue;
    }

    /* starting a new format specifier, reset variables */
    int alignment = ALIGN_RIGHT;
    int adjusting = 0;
    char padding = ' ';
    int always_sign = 0;
    int width, precision;
    inpos++;      /* skip the '%' */
    ch = format[inpos];

    if (isascii(ch) && !isalpha(ch)) {
      /* first look for argnum */
      int temppos = inpos;
      while (isdigit((int)format[temppos])) temppos++;
      if (format[temppos] == '$') {
        argnum = getnumber(format, &inpos);
        if (argnum <= 0) {
          throw_invalid_argument("argnum: must be greater than zero");
          return String();
        }
        inpos++;  /* skip the '$' */
      } else {
        argnum = currarg++;
      }

      /* after argnum comes modifiers */
      for (;; inpos++) {
        ch = format[inpos];

        if (ch == ' ' || ch == '0') {
          padding = ch;
        } else if (ch == '-') {
          alignment = ALIGN_LEFT;
          /* space padding, the default */
        } else if (ch == '+') {
          always_sign = 1;
        } else if (ch == '\'' && inpos != len - 1) {
          padding = format[++inpos];
        } else {
          break;
        }
      }
      ch = format[inpos];

      /* after modifiers comes width */
      if (isdigit(ch)) {
        if ((width = getnumber(format, &inpos)) < 0) {
          throw_invalid_argument("width: must be greater than zero "
                                 "and less than %d", INT_MAX);
          return String();
        }
        adjusting |= ADJ_WIDTH;
      } else {
        width = 0;
      }
      ch = format[inpos];

      /* after width and argnum comes precision */
      if (ch == '.') {
        ch = format[++inpos];
        if (isdigit((int)ch)) {
          if ((precision = getnumber(format, &inpos)) < 0) {
            throw_invalid_argument("precision: must be greater than zero "
                                   "and less than %d", INT_MAX);
            return String();
          }
          ch = format[inpos];
          adjusting |= ADJ_PRECISION;
          expprec = 1;
        } else {
          precision = 0;
        }
      } else {
        precision = 0;
      }
    } else {
      width = precision = 0;
      argnum = currarg++;
    }

    if (argnum > vargs.size()) {
      throw_invalid_argument("arguments: (too few)");
      return String();
    }

    if (ch == 'l') {
      ch = format[++inpos];
    }
    /* now we expect to find a type specifier */
    Variant tmp = vargs[argnum-1];

    switch (ch) {
    case 's': {
      String s = tmp.toString();
      appendstring(&result, s.c_str(),
                   width, precision, padding, alignment, s.size(),
                   0, expprec, 0);
      break;
    }
    case 'd':
      appendint(&result, tmp.toInt64(),
                width, padding, alignment, always_sign);
      break;
    case 'u':
      appenduint(&result, tmp.toInt64(),
                 width, padding, alignment);
      break;

    case 'g':
    case 'G':
    case 'e':
    case 'E':
    case 'f':
    case 'F':
      appenddouble(&result, tmp.toDouble(),
                   width, padding, alignment, precision, adjusting,
                   ch, always_sign);
      break;

    case 'c':
      result.append(tmp.toByte());
      break;

    case 'o':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 3, hexchars, expprec);
      break;

    case 'x':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 4, hexchars, expprec);
      break;

    case 'X':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 4, HEXCHARS, expprec);
      break;

    case 'b':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 1, hexchars, expprec);
      break;

    case '%':
      result.append('%');

      break;
    default:
      break;
    }
  }

  return result.detach();
}