Beispiel #1
0
/**
 * parseRoutes - parses the routes in the route.dat file and
 * calculates the distance between the ariports
 *
 * IN: mat - Adjacency matrix that contains the
 * distance. mat[src][dest] where src is the starting airport and dest
 * is the destination.
 * IN: fileName - name of the routes file
 * IN: alist - list of all the airports that is used to find the
 * coorindates of the airport in the routes file.
 */
int parseRoutes(double **mat, string fileName, string *adj2Ap,
				map<string, Airport> alist, set<string>& cities,
				map<string, int>& lookup, struct Coordinates *coordinate) {
		char buf[256];
		char *token;
		string src, dest;
		int srcInx = 0, destInx = 0;
		int apSrc = 0, apDest = 0;
		int apCnt = 0, lkuCnt = 0;
		int totAp = 0;

		FILE *fp = fopen(fileName.c_str(), "r");

		if (fp == NULL) {
				printf("Error opening routes file");
				exit(-1);
		}

		while(fgets(buf, sizeof(buf), fp)) {
				token = strtok(buf, ",");
				strtok(NULL, ",");
				src = strtok(NULL, ",");
				strtok(NULL, ",");
				dest = strtok(NULL, ",");

				cities.insert(alist[src].city);
				cities.insert(alist[dest].city);

				// Determine if airport is on the adj matrix
				if (!lookup.count(src)) { // does not find src airport
						lookup[src] = lkuCnt;
						adj2Ap[apCnt++] = src;
						apSrc = lkuCnt++;
						totAp++;
                  (coordinate->visitedAirports).insert(src);
				}
				else {
						apSrc = lookup[src];
				}
				if (!lookup.count(dest)) { // does not find dest airport
						lookup[dest] = lkuCnt;
						adj2Ap[apCnt++] = dest;
						apDest = lkuCnt++;
						totAp++;
                  (coordinate->visitedAirports).insert(dest);
				}
				else {
						apDest = lookup[dest];
				}
				mat[apSrc][apDest] = 1;

				// Haversine math here ~ real: 0.149 seconds
				//mat[src][dest] = haversine(alist[src].latitude, alist[src].longitude,
				//		 alist[dest].latitude, alist[dest].longitude);

				//if no mat use... ~ real: 0.044 seconds

				// 2/18 - Tim... just doing this, without calculation of haversine... ~ real: 0.120 seconds
		}
		fclose(fp);
		return totAp;
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 4)
        throw runtime_error(
            "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
            "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
            "The second optional argument (may be null) is an array of previous transaction outputs that\n"
            "this transaction depends on but may not yet be in the block chain.\n"
            "The third optional argument (may be null) is an array of base58-encoded private\n"
            "keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
            + HelpRequiringPassphrase() + "\n"
#endif

            "\nArguments:\n"
            "1. \"hexstring\"     (string, required) The transaction hex string\n"
            "2. \"prevtxs\"       (string, optional) An json array of previous dependent transaction outputs\n"
            "     [               (json array of json objects, or 'null' if none provided)\n"
            "       {\n"
            "         \"txid\":\"id\",             (string, required) The transaction id\n"
            "         \"vout\":n,                  (numeric, required) The output number\n"
            "         \"scriptPubKey\": \"hex\",   (string, required) script key\n"
            "         \"redeemScript\": \"hex\"    (string, required for P2SH) redeem script\n"
            "       }\n"
            "       ,...\n"
            "    ]\n"
            "3. \"privatekeys\"     (string, optional) A json array of base58-encoded private keys for signing\n"
            "    [                  (json array of strings, or 'null' if none provided)\n"
            "      \"privatekey\"   (string) private key in base58-encoding\n"
            "      ,...\n"
            "    ]\n"
            "4. \"sighashtype\"     (string, optional, default=ALL) The signature hash type. Must be one of\n"
            "       \"ALL\"\n"
            "       \"NONE\"\n"
            "       \"SINGLE\"\n"
            "       \"ALL|ANYONECANPAY\"\n"
            "       \"NONE|ANYONECANPAY\"\n"
            "       \"SINGLE|ANYONECANPAY\"\n"

            "\nResult:\n"
            "{\n"
            "  \"hex\" : \"value\",           (string) The hex-encoded raw transaction with signature(s)\n"
            "  \"complete\" : true|false,   (boolean) If the transaction has a complete set of signatures\n"
            "  \"errors\" : [                 (json array of objects) Script verification errors (if there are any)\n"
            "    {\n"
            "      \"txid\" : \"hash\",           (string) The hash of the referenced, previous transaction\n"
            "      \"vout\" : n,                (numeric) The index of the output to spent and used as input\n"
            "      \"scriptSig\" : \"hex\",       (string) The hex-encoded signature script\n"
            "      \"sequence\" : n,            (numeric) Script sequence number\n"
            "      \"error\" : \"text\"           (string) Verification or signing error related to the input\n"
            "    }\n"
            "    ,...\n"
            "  ]\n"
            "}\n"

            "\nExamples:\n"
            + HelpExampleCli("signrawtransaction", "\"myhex\"")
            + HelpExampleRpc("signrawtransaction", "\"myhex\"")
        );

#ifdef ENABLE_WALLET
    LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
    LOCK(cs_main);
#endif
    RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);

    vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
    vector<CMutableTransaction> txVariants;
    while (!ssData.empty()) {
        try {
            CMutableTransaction tx;
            ssData >> tx;
            txVariants.push_back(tx);
        }
        catch (const std::exception&) {
            throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
        }
    }

    if (txVariants.empty())
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");

    // mergedTx will end up with all the signatures; it
    // starts as a clone of the rawtx:
    CMutableTransaction mergedTx(txVariants[0]);

    // Fetch previous transactions (inputs):
    CCoinsView viewDummy;
    CCoinsViewCache view(&viewDummy);
    {
        LOCK(mempool.cs);
        CCoinsViewCache &viewChain = *pcoinsTip;
        CCoinsViewMemPool viewMempool(&viewChain, mempool);
        view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view

        BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
            const uint256& prevHash = txin.prevout.hash;
            CCoins coins;
            view.AccessCoins(prevHash); // this is certainly allowed to fail
        }

        view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
    }

    bool fGivenKeys = false;
    CBasicKeyStore tempKeystore;
    if (params.size() > 2 && !params[2].isNull()) {
        fGivenKeys = true;
        UniValue keys = params[2].get_array();
        for (unsigned int idx = 0; idx < keys.size(); idx++) {
            UniValue k = keys[idx];
            CBitcoinSecret vchSecret;
            bool fGood = vchSecret.SetString(k.get_str());
            if (!fGood)
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
            CKey key = vchSecret.GetKey();
            if (!key.IsValid())
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
            tempKeystore.AddKey(key);
        }
    }
#ifdef ENABLE_WALLET
    else if (pwalletMain)
        EnsureWalletIsUnlocked();
#endif

    // Add previous txouts given in the RPC call:
    if (params.size() > 1 && !params[1].isNull()) {
        UniValue prevTxs = params[1].get_array();
        for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
            const UniValue& p = prevTxs[idx];
            if (!p.isObject())
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");

            UniValue prevOut = p.get_obj();

            RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));

            uint256 txid = ParseHashO(prevOut, "txid");

            int nOut = find_value(prevOut, "vout").get_int();
            if (nOut < 0)
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");

            vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
            CScript scriptPubKey(pkData.begin(), pkData.end());

            {
                CCoinsModifier coins = view.ModifyCoins(txid);
                if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
                    string err("Previous output scriptPubKey mismatch:\n");
                    err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
                        ScriptToAsmStr(scriptPubKey);
                    throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
                }
                if ((unsigned int)nOut >= coins->vout.size())
                    coins->vout.resize(nOut+1);
                coins->vout[nOut].scriptPubKey = scriptPubKey;
                coins->vout[nOut].nValue = 0; // we don't know the actual output value
            }

            // if redeemScript given and not using the local wallet (private keys
            // given), add redeemScript to the tempKeystore so it can be signed:
            if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
                RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
                UniValue v = find_value(prevOut, "redeemScript");
                if (!v.isNull()) {
                    vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
                    CScript redeemScript(rsData.begin(), rsData.end());
                    tempKeystore.AddCScript(redeemScript);
                }
            }
        }
    }

#ifdef ENABLE_WALLET
    const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
    const CKeyStore& keystore = tempKeystore;
#endif

    int nHashType = SIGHASH_ALL;
    if (params.size() > 3 && !params[3].isNull()) {
        static map<string, int> mapSigHashValues =
            boost::assign::map_list_of
            (string("ALL"), int(SIGHASH_ALL))
            (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
            (string("NONE"), int(SIGHASH_NONE))
            (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
            (string("SINGLE"), int(SIGHASH_SINGLE))
            (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
            ;
        string strHashType = params[3].get_str();
        if (mapSigHashValues.count(strHashType))
            nHashType = mapSigHashValues[strHashType];
        else
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
    }

    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);

    // Script verification errors
    UniValue vErrors(UniValue::VARR);

    // Sign what we can:
    for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
        CTxIn& txin = mergedTx.vin[i];
        const CCoins* coins = view.AccessCoins(txin.prevout.hash);
        if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
            TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
            continue;
        }
        const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;

        txin.scriptSig.clear();
        // Only sign SIGHASH_SINGLE if there's a corresponding output:
        if (!fHashSingle || (i < mergedTx.vout.size()))
            SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);

        // ... and merge in other signatures:
        BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
            txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
        }
        ScriptError serror = SCRIPT_ERR_OK;
        if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
            TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
        }
    }
Beispiel #3
0
int main() {
    //assert(freopen("input.txt","r",stdin));
    //assert(freopen("output.txt","w",stdout));

    scanf("%d", &n);

    /*add(root, 1);
    add(root, 4);
    add(root, 5);
    add(root, 7);

    while (true) {
        int x;
        cin >> x;
        if (!x)
            break;
        cout << numG(root, x) << endl;
    }



    while (true) {
        int x;
        cin >> x;
        if (!x)
            break;
        cout << numL(root, x) << endl;
    }*/

    /*for (int i = 1; i < 15; i++)
        t[i] = i;   */

    for (int i = 1; i <= n; i++) {
        int a, b;
        scanf("%d %d", &a, &b);
        if (ind.count(a) == 0)
            ind[a] = a;
        if (ind.count(b) == 0)
            ind[b] = b;
        swap(ind[a], ind[b]);
        //swap(t[a], t[b]);
    }

    /*int cc = 0;
    for (int i = 1; i < 15; i++)
        for (int j = i + 1; j < 15; j++)
            if (t[i] > t[j])
                cc++;

    cout << cc << endl;*/

    for (map <int, int> :: iterator it = ind.begin(); it != ind.end(); it++) {
        v.push_back(make_pair(it->first, it->second));
    }

    int prev = -1;
    for (int i = 0; i < (int) v.size(); i++) {
        int pos = v[i].first;
        int cur = v[i].second;

        if (prev != -1) {
            int from = prev + 1, to = pos - 1;
            if (to >= from) {
                //cout << "F " << from << " " << to << " " << numG(root, from) << endl;
                long long add = 1ll * numG(root, from) * (to - from + 1);
                //cout << add << endl;
                ans += add;
            }
        }

        ans += numG(root, cur);

        prev = pos;
        add(root, cur); 
    }

    root = NULL;

    prev = -1;
    for (int i = v.size() - 1; i >= 0; i--) {
        int pos = v[i].first;
        int cur = v[i].second;

        if (prev != -1) {
            int from = pos + 1, to = prev - 1;
            if (to >= from) {
                long long add = 1ll * numL(root, from) * (to - from + 1);
                //cout << add << endl;
                ans += add;
            }
        }

        prev = pos;
        add(root, cur); 
    }

    cout << ans << endl;
                                                      
    return 0;
}
Beispiel #4
0
int main()
{
	//freopen("in","r",stdin);

	scanf("%d", &n);
	Point source, sink;
	source.init(); sink.init();
	for (int i = 0; i < n; ++i) {
		Point s, e;
		s.init(); e.init();
		if (e < s) swap(s, e);
		segment[i] = Segment(s, e);
	}
	sort(segment, segment + n);
	for (int i = 0; i < n; ++i) if (!hide[i]) {
		interval[i].push_back(segment[i]);
		for (int j = i + 1; j < n; ++j) if (!hide[j] && is_segment_same(segment[i], segment[j])) {
			hide[j] = 1;
			if (segment[j].s == interval[i][interval[i].size() - 1].e) {
				interval[i][interval[i].size() - 1].e = segment[j].e;
			} else {
				interval[i].push_back(segment[j]);
			}
		}
	}
	//for (Segment p : interval[1]) printf("%.3f %.3f\n", p.s.x, p.s.y);
	vector<int> que;
	for (int i = 0; i < n; ++i) if (!hide[i]) {
		que.clear();
		for (int j = 0; j < n; ++j) if (i != j && !hide[j]) {
			if (parallel(segment[i], segment[j])) continue;
			Point p = get_intersect(segment[i], segment[j]);
			que.push_back(count(p));
		}
		sort(que.begin(), que.end(), cmp); 
		int m = unique(que.begin(), que.end()) - que.begin();
		//vector<Segment> :: iterator cur = interval[i].begin();
		for (int k = 0; k < m - 1; ++k) {
			int a = que[k];
			int b = que[k+1];
			edges[a].push_back(b);
			edges[b].push_back(a);
			//              printf("%d\n", cur == interval[i].end());
			//while (cur != interval[i].end() && cur->e < que[k]) ++cur;
			//              printf("%d\n", cur == interval[i].end());
			for (vector<Segment> :: iterator cur = interval[i].begin(); cur != interval[i].end(); ++cur)
				if (is_contains(*cur, Segment(point[que[k]], point[que[k+1]]))) weight[MP(a, b)] = weight[MP(b, a)] = 1;
		}
	}
	int s = 0;
	int t = 0;
	for (int u = 0; u < total; ++u) {
		for (int v : edges[u]) if (!vis.count(MP(u, v))) {
			vis.insert(MP(u, v));
			list.clear();
			list.push_back(u);

			bool can = dfs(v, u, u);
			//      for (int x : list) printf("%d ", x); printf("\n");
			if (can) {
				//              if (list.size() < 3) while(1);
				++area;
				list.push_back(list[0]);
				if (s == 0) s = point_location(source, area);
				if (t == 0) t = point_location(sink, area);
				for (int i = 0; i < (int) list.size() - 1; ++i) {
					//      assert(!belong.count(MP(list[i], list[i+1])));
					//      assert(!belong.count(MP(list[i+1], list[i])) || belong[MP(list[i+1], list[i])] != area);
					belong[MP(list[i], list[i+1])] = area;
				}

				/*
				   for (int x = 0; x < (int) list.size() - 1; ++x)
				   for (int y = 0; y < (int) list.size() - 1; ++y) 
				   assert(MP(list[x], list[x+1]) != MP(list[y+1], list[y]));
				   */

			} else {
				for (int i = 0; i < (int) list.size() - 1; ++i) {
					belong[MP(list[i], list[i+1])] = 0;
				}
			}
		}
	}
	for (int u = 0; u < total; ++u) {
		for (int v : edges[u]) {
			//      assert(u != v);
			int a = belong[MP(u, v)];
			int b = belong[MP(v, u)];
			//      assert(belong.count(MP(u, v)));
			//      assert(belong.count(MP(v, u)));
			//              assert(a != b || a == 0 || b == 0);
			//if (a == b && a != 0) while(1);
			int w = weight.count(MP(u,v)) ? weight[MP(u,v)] : 0;
			gragh[a].push_back(MP(b, w));
			//gragh[b].push_back(MP(a, w));
		}
	}
	printf("%d\n", dijkstra(s, t));

	return 0;
}
Beispiel #5
0
uint256 ParseHashUO(map<string,UniValue>& o, string strKey)
{
    if (!o.count(strKey))
        return uint256();
    return ParseHashUV(o[strKey], strKey);
}
CScript
ParseScript(string s)
{
    CScript result;

    static map<string, opcodetype> mapOpNames;

    if (mapOpNames.size() == 0)
    {
        for (int op = OP_NOP; op <= OP_NOP10; op++)
        {
            const char* name = GetOpName((opcodetype)op);
            if (strcmp(name, "OP_UNKNOWN") == 0)
                continue;
            string strName(name);
            mapOpNames[strName] = (opcodetype)op;
            // Convenience: OP_ADD and just ADD are both recognized:
            replace_first(strName, "OP_", "");
            mapOpNames[strName] = (opcodetype)op;
        }
    }

    vector<string> words;
    split(words, s, is_any_of(" \t\n"), token_compress_on);

    BOOST_FOREACH(string w, words)
    {
        if (all(w, is_digit()) ||
            (starts_with(w, "-") && all(string(w.begin()+1, w.end()), is_digit())))
        {
            // Number
            int64 n = atoi64(w);
            result << n;
        }
        else if (starts_with(w, "0x") && IsHex(string(w.begin()+2, w.end())))
        {
            // Raw hex data, inserted NOT pushed onto stack:
            std::vector<unsigned char> raw = ParseHex(string(w.begin()+2, w.end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w.size() >= 2 && starts_with(w, "'") && ends_with(w, "'"))
        {
            // Single-quoted string, pushed as data. NOTE: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w.begin()+1, w.end()-1);
            result << value;
        }
        else if (mapOpNames.count(w))
        {
            // opcode, e.g. OP_ADD or OP_1:
            result << mapOpNames[w];
        }
        else
        {
            BOOST_ERROR("Parse error: " << s);
            return CScript();
        }                        
    }

    return result;
}
Beispiel #7
0
int is_d_written(unsigned int addr)
{
	return g_map_d_written.count(addr) > 0;
}
Beispiel #8
0
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
    if (mapArgs.count(strArg))
        return atoi64(mapArgs[strArg]);
    return nDefault;
}
Beispiel #9
0
bool input() {
  for(int i=0;i<100;i++)for(int j=0;j<100;j++) unitmap[i][j]=0;
  remainingTime = nextInt();
  int currentStage = nextInt();
  currentTurn = nextInt();
  if (currentTurn == 0) {
    // ターンをまたいで維持される変数はステージが新しくなった時点で初期化を行う。
    stageStart();
    // ステージが始まったことをデバッnグ出力。
    // (クライアントで実行すると標準エラー出力は ./log/io/ 配下にログが出力される)
    cerr << "stage:" << currentStage << endl;
  }

  currentResource = nextInt();
  {
    // 自分のユニットを読み込み。
    map<int, Unit> mp;
    int myNum = nextInt();
    for (int i = 0; i < myNum; i++) {
      int id = nextInt();
      // 前ターンから知っているユニットはそのまま使う。
      // (ユニットに設定した命令がターンをまたいでも引き継がれる実装)
      Unit u;
      if (myUnits.count(id) > 0) u = myUnits[id];
      u.id = id;
      u.y = nextInt();
      u.x = nextInt();
      unitmap[u.y][u.x] = 1;
      u.hp = nextInt();
      u.type = nextInt();
      mp[id] = u;
      if (u.type == CASTLE) {
        myCastle = u;
        // 城が左上と右下のコーナーどちらに近いかで 1P側・2P側を判断
        isTopLeft = dist(myCastle.y, myCastle.x, 0, 0) <  dist(myCastle.y, myCastle.x, 99, 99);
      }else if(u.type == WORKER_FACTORY) workerFactoryMap[u.y][u.x] = true;

      // 一度でも視界に入ったことがあるマスを更新
      int view = VIEW_RANGE[u.type];
      for (int sy = u.y - view; sy <= u.y + view; sy++)
        for (int sx = u.x - view; sx <= u.x + view; sx++)
          if (0 <= sy && sy < 100 && 0 <= sx && sx < 100 && dist(u.y, u.x, sy, sx) <= view)
            see[sy][sx] = true;
    }
    // 死んだユニットをリストから除くため新しい map に追加して、置き換える。
    map<int, Unit> mp1 = myUnits;
    myUnits = mp;
    if(mp1.size() != 0){
      for(map<int, Unit>::iterator it = mp1.begin(); it != mp1.end(); it++) {
        Unit u = it->second;
        if(myUnits.count(u.id) == 0 && u.type == WORKER && !(u.cellNum == -1) && insCellMap[u.cellNum.y][u.cellNum.x] != 0)insCellMap[u.cellNum.y][u.cellNum.x]--;
      }
    }
  }
  {
    // 敵のユニットを読み込み
    map<int, Unit> mp;
    int opNum = nextInt();
    for (int i = 0; i < opNum; i++) {
      int id = nextInt();
      Unit u;
      if (opUnits.count(id) > 0) u = opUnits[id];
      u.id = id;
      u.y = nextInt();
      u.x = nextInt();
      unitmap[u.y][u.x] = -1;
      u.hp = nextInt();
      u.type = nextInt();
      mp[id] = u;
      if (u.type == CASTLE) opCastle = u;
    }
    opUnits = mp;
  }
  {
    // 資源の位置を読み込み
    int resNum = nextInt();
    resourcePoint.clear();
    resourceFreePoint.clear();
    resourceEmenyPoint.clear();
    for (int i = 0; i < resNum; i++) {
      int y = nextInt();
      int x = nextInt();
      point p;
      bool flag=false;
      p.x = x;
      p.y = y;
      if(isTopLeft){
        if(dist(p.y,p.x,0,0) < 100){
          for(auto i:resourceNearMyPoint){
            if(p.x == i.x && p.y == i.y) flag=true;
          }
          if(!flag)resourceNearMyPoint.push_back(p);
        }else if(dist(p.y,p.x,99,99) < 100){
          for(auto i:resourceNearEmenyPoint){
            if(p.x == i.x && p.y == i.y) flag=true;
          }
          if(!flag)resourceNearEmenyPoint.push_back(p);
        }
      }else{
        if(dist(p.y,p.x,0,0) < 100){
          for(auto i:resourceNearEmenyPoint){
            if(p.x == i.x && p.y == i.y) flag=true;
          }
          if(!flag)resourceNearEmenyPoint.push_back(p);
        }else if(dist(p.y,p.x,99,99) < 100){
          for(auto i:resourceNearMyPoint){
            if(p.x == i.x && p.y == i.y) flag=true;
          }
          if(!flag)resourceNearMyPoint.push_back(p);
        }
      }
      resource[y][x] = unitmap[y][x];
      if(resource[y][x] == 0){
        resourceFreePoint.push_back(p);
      }
      if(resource[y][x] != -100){
        resourcePoint.push_back(p);
      }
      if(resource[y][x] == -1){
        resourceEmenyPoint.push_back(p);
      }
    }
    for(auto j:resourceNearEmenyPoint){
      bool flag=false;
      for(auto i:resourceEmenyPoint){
        if(j.x == i.x && j.y == i.y ) flag=true;
      }
      if(!flag && resource[j.y][j.x] == -1) resourceEmenyPoint.push_back(j);
      flag = false;
      for(auto i:resourceFreePoint){
        if(j.x != i.x && j.y != i.y && resource[j.y][j.x] == 0) resourceFreePoint.push_back(j);
      }
    }
    for(auto j:resourceNearMyPoint){
      bool flag = false;
      for(auto i:resourceEmenyPoint){
        if(j.x == i.x && j.y == i.y) flag = true;
      }
      if(!flag && resource[j.y][j.x] == -1)resourceEmenyPoint.push_back(j);
      for(auto i:resourceFreePoint){
        if(j.x != i.x && j.y != i.y && resource[j.y][j.x] == 0) resourceFreePoint.push_back(j);
      }
    }
  }

  string end;
  cin >> end;
  if ("END" == end) return true;
  return false;
}
void solve() {
    id.clear();
    int nextId = 0;
    string startStr, finishStr;
    cin >> startStr >> finishStr;
    assert(startStr != finishStr);
    start = id[startStr] = nextId++;
    finish = id[finishStr] = nextId++;
    int trainCount; cin >> trainCount;
    for (int i = 0; i < trainCount; ++i) {
        string from, to; int m, t, p, d;
        cin >> from >> to >> m >> t >> p >> d;
        Train train;
        train.to = id.count(to) ? id[to] : (id[to] = nextId++);
        train.from = id.count(from) ? id[from] : (id[from] = nextId++);
        train.departure = m;
        train.duration = t;
        train.probability = p / 100.0;
        train.delay = d;

        incoming[train.to].push_back(train);
    }
    
    int n = nextId;
    for (int t = 0; t < 60; ++t) {
        for (int i = 0; i < n; ++i) {
            E[i][t] = 1e100;
        }
        E[finish][t] = 0.0;
    }

    priority_queue< pair<double, pair<int, int> > > q;
    q.push( make_pair(0.0, make_pair(finish, 0)) );
    while (q.size() > 0) {
        double w = -q.top().first;
        int v = q.top().second.first;
        int arrivalTime = q.top().second.second;
        q.pop();
        if (cmp(w, E[v][arrivalTime]) > 0) continue;
        
        for (int k = 0; k < incoming[v].size(); ++k) {
            const Train &train = incoming[v][k];
            assert(train.to == v);
            int u = train.from;
            for (int t = 0; t < 60; ++t) {
                double e = expectedTrip(u, t, train);
                if (cmp(e, E[u][t]) < 0) {
                    E[u][t] = e;
                    q.push(  make_pair(-e, make_pair(u, t)) );
                }
            }
        }
    }
    
    double ans = 1e100;
    for (int t = 0; t < 60; ++t) {
        ans = min(ans, E[start][t]);
    }
    if (ans < 10e20) {
        printf("%.10lf\n", ans);
    } else {
        printf("IMPOSSIBLE\n");
    }
    
    for (int i = 0; i < nextId; ++i) {
        incoming[i].clear();
    }
}
Beispiel #11
0
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
    if (mapArgs.count(strArg))
        return mapArgs[strArg];
    return strDefault;
}
Beispiel #12
0
int main() {
  int cases;
  cin >> cases;
  for(int test = 1; test <= cases; test++) {
    int edge, query;
    cin >> edge >> query >> ws;
    nodes.clear();
    for(int i= 0; i < edge; i++) {
      string authors, title;
      getline(cin, authors, ':');
      getline(cin, title);
      vector<string> splitted;
      istringstream iss(authors.c_str());
      string split;
      bool firstone = true;
      while(getline(iss, split, ',')) {
	if(firstone)
	  splitted.push_back(split);
	else
	  splitted.push_back(split.substr(1));
	firstone = false;
      }
      vector<string> names;
      for(int j = 0; j < splitted.size() - 1; j +=2) {
	names.push_back(splitted[j] + ", " + splitted[j+1]);
      }
      for(int j= 0; j < names.size(); j++) {
	for(int k = j+1; k < names.size(); k++) {
	  string side1 = names[j];
	  string side2 = names[k];
	  if(nodes.count(side1) == 0) {
	    vector<string> side1adj;
	    side1adj.push_back(side2);
	    Node each(side1, side1adj);
	    nodes[side1] = each;
	  } else {
	    nodes[side1].adj.push_back(side2);
	  }

	  if(nodes.count(side2) == 0) {
	    vector<string> side2adj;
	    side2adj.push_back(side1);
	    Node each(side2, side2adj);
	    nodes[side2] = each;
	  } else {
	    nodes[side2].adj.push_back(side1);
	  }
	}
      }
    }
    bfs("Erdos, P.");
    visited.clear();
    cout << "Scenario " << test << endl;
    for(int i = 0; i < query; i++) {
      string querys;
      getline(cin, querys);
      if(nodes.count(querys) == 0 || nodes[querys].degree == -1)
	cout << querys << " infinity" << endl;
      else
	cout << querys << " " << nodes[querys].degree << endl;
    }
  }
  return 0;
}
Beispiel #13
0
CScript ParseScript(const std::string& s)
{
    CScript result;

    static map<string, opcodetype> mapOpNames;

    if (mapOpNames.empty())
    {
        for (int op = 0; op <= OP_NOP10; op++)
        {
            // Allow OP_RESERVED to get into mapOpNames
            if (op < OP_NOP && op != OP_RESERVED)
                continue;

            const char* name = GetOpName((opcodetype)op);
            if (strcmp(name, "OP_UNKNOWN") == 0)
                continue;
            string strName(name);
            mapOpNames[strName] = (opcodetype)op;
            // Convenience: OP_ADD and just ADD are both recognized:
            boost::algorithm::replace_first(strName, "OP_", "");
            mapOpNames[strName] = (opcodetype)op;
        }
    }

    vector<string> words;
    boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);

    for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
    {
        if (w->empty())
        {
            // Empty string, ignore. (boost::split given '' will return one word)
        }
        else if (all(*w, boost::algorithm::is_digit()) ||
            (boost::algorithm::starts_with(*w, "-") && all(string(w->begin()+1, w->end()), boost::algorithm::is_digit())))
        {
            // Number
            int64_t n = atoi64(*w);
            result << n;
        }
        else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(string(w->begin()+2, w->end())))
        {
            // Raw hex data, inserted NOT pushed onto stack:
            std::vector<unsigned char> raw = ParseHex(string(w->begin()+2, w->end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'"))
        {
            // Single-quoted string, pushed as data. NOTE: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w->begin()+1, w->end()-1);
            result << value;
        }
        else if (mapOpNames.count(*w))
        {
            // opcode, e.g. OP_ADD or ADD:
            result << mapOpNames[*w];
        }
        else
        {
            throw runtime_error("script parse error");
        }
    }

    return result;
}
Beispiel #14
0
int Fluidity::WriteHalos(const string& filename, const unsigned int& process, const unsigned int& nprocs, const map<int, int>& npnodes, const map<int, vector<vector<int> > >& send, const map<int, vector<vector<int> > >& recv){
#ifdef DDEBUG
  // Input check
  assert(process < nprocs);
  assert(send.size() == recv.size());
  for(map<int, vector<vector<int> > >::const_iterator sendIter = send.begin(), recvIter = recv.begin();sendIter != send.end() and recvIter != recv.end(), recvIter != recv.end();sendIter++, recvIter++){
    assert(recv.count(sendIter->first) != 0);
    assert(npnodes.count(sendIter->first) != 0);
    assert(sendIter->second.size() == recvIter->second.size());
  }
#endif
  
  TiXmlDocument doc;
  
  ostringstream buffer;
  
  // XML header
  TiXmlDeclaration* header = new TiXmlDeclaration("1.0", "utf-8", "");
  doc.LinkEndChild(header);

  // Add root node
  TiXmlElement* rootEle = new TiXmlElement("halos");
  doc.LinkEndChild(rootEle);
  
  // Add process attribute to root node
  buffer << process;
  rootEle->SetAttribute("process", buffer.str());
  buffer.str("");
  
  // Add nprocs attribute to root node
  buffer << nprocs;
  rootEle->SetAttribute("nprocs", buffer.str());
  buffer.str("");
 
  // Add halo data for each level
  map<int, int>::const_iterator npnodesIter = npnodes.begin();
  for(map<int, vector<vector<int> > >::const_iterator sendLevelIter = send.begin(), recvLevelIter = recv.begin();sendLevelIter != send.end() and recvLevelIter != recv.end() and npnodesIter != npnodes.end();sendLevelIter++, recvLevelIter++, npnodesIter++){
    // Add halo element to root element
    TiXmlElement* haloEle = new TiXmlElement("halo");
    rootEle->LinkEndChild(haloEle);
    
    // Add level attribute to halo element
    buffer << sendLevelIter->first;
    haloEle->SetAttribute("level", buffer.str());
    buffer.str("");
    
    // Add n_private_nodes attribute to halo element
    buffer << npnodesIter->second;
    haloEle->SetAttribute("n_private_nodes", buffer.str());
    buffer.str("");
    
    // Add halo data for each process for each level
    int j = 0;
    for(vector<vector<int> >::const_iterator sendProcIter = sendLevelIter->second.begin(), recvProcIter = recvLevelIter->second.begin();sendProcIter != sendLevelIter->second.end() and recvProcIter != recvLevelIter->second.end();sendProcIter++, recvProcIter++, j++){
      if(j == (int)nprocs){
        break;
      }

      // Add halo_data element to halo element
      TiXmlElement* dataEle = new TiXmlElement("halo_data");
      haloEle->LinkEndChild(dataEle);
    
      // Add process attribute to data element
      buffer << j;
      dataEle->SetAttribute("process", buffer.str());
      buffer.str("");

      // Add send data to data element
      TiXmlElement* sendDataEle = new TiXmlElement("send");
      dataEle->LinkEndChild(sendDataEle);

      // Add data to send data element
      for(vector<int>::const_iterator sendDataIter = sendProcIter->begin();sendDataIter != sendProcIter->end();sendDataIter++){
        buffer << *sendDataIter << " ";
      }
      TiXmlText* sendData = new TiXmlText(buffer.str());
      sendDataEle->LinkEndChild(sendData);
      buffer.str("");

      // Add receive data to data element
      TiXmlElement* recvDataEle = new TiXmlElement("receive");
      dataEle->LinkEndChild(recvDataEle);
      
      // Add data to receive data element
      for(vector<int>::const_iterator recvDataIter = recvProcIter->begin();recvDataIter != recvProcIter->end();recvDataIter++){
        buffer << *recvDataIter << " ";
      }
      TiXmlText* recvData = new TiXmlText(buffer.str());
      recvDataEle->LinkEndChild(recvData);
      buffer.str("");
    }
  }
  
  return doc.SaveFile(filename) ? 0 : -1;
}
Beispiel #15
0
void theSignalHandlerProc(int signum)
{
  assert(sigHandlers.count(signum) != 0);
  assert(!sigHandlers[signum].empty());
  sigHandlers[signum].back()->OnRaise(signum);
}
int findLastCant(const map<int, int> &S){
  int i = 0;
  while (S.count(i)) i++;
  return i;
}
Beispiel #17
0
int main() {
    long long a, b;
    cin >> a >> b;
    cnt[a] = 1;
    bef[a] = a;
    queue< long long > q;
    q.push(a);
    dist[a] = 0;
    while (!q.empty()) {
        long long now = q.front(); q.pop();
        if (now != 2) {
            if (mrtest(now-2)) {
                if (!bef.count(2)) {
                    bef[2] = now;
                    dist[2] = dist[now] + 1;
                    q.push(2);
                }
                if (dist[2] == dist[now] + 1)
                    cnt[2] += cnt[now];
                if (!bef.count(now-2)) {
                    bef[now-2] = now;
                    dist[now-2] = dist[now] + 1;
                    q.push(now-2);
                }
                if (dist[now-2] == dist[now] + 1)
                    cnt[now-2] += cnt[now];
            }
            if (mrtest(now+2)) {
                if (!bef.count(now+2)) {
                    bef[now+2] = now;
                    dist[now+2] = dist[now] + 1;
                    q.push(now+2);
                }
                if (dist[now+2] == dist[now] + 1)
                    cnt[now+2] += cnt[now];
            }
        }
        else {
            if (mrtest(b+2)) {
                if (!bef.count(b+2)) {
                    bef[b+2] = now;
                    dist[b+2] = dist[now] + 1;
                    q.push(b+2);
                }
                if (dist[b+2] == dist[now] + 1)
                    cnt[b+2] += cnt[now];
            }
            if (mrtest(b-2)) {
                if (!bef.count(b)) {
                    bef[b] = now;
                    dist[b] = dist[now] + 1;
                    q.push(b);
                }
                if (dist[b] == dist[now] + 1)
                    cnt[b] += cnt[now];
            }
        }
    }
    if (!cnt.count(b))
        puts("Unlucky Benny");
    else if (cnt[b] > 1)
        puts("Poor Benny");
    else {
        long long now = b;
        stack < long long > st;
        while (now != a) {
            st.push(now);
            now = bef[now];
        }
        cout << a;
        while (!st.empty()) {
            cout << "->" << st.top();
            st.pop();
        }
        cout << endl;
    }
    return 0;
}
bool exists(point<int> const & p) {
    return pos.count(p) and not is_removed[pos[p]];
}
Beispiel #19
0
unsigned int get_pc_imm(unsigned int pc)
{
	if(g_map_pc_imm.count(pc) > 0)
		return g_map_pc_imm[pc];
	return 0;
}
Beispiel #20
0
int getbil(char *s) {
	string st(s);
	if(!bil.count(st)) bil[st] = bil.size() - 1; 
	return bil[st];
}
Beispiel #21
0
int is_dependence_addr(unsigned int addr)
{	
	return g_map_d_data.count(addr);
}
Beispiel #22
0
bool CDB::Rewrite(const string& strFile, const char* pszSkip)
{
    while (!fShutdown)
    {
        {
            LOCK(cs_db);
            if (!mapFileUseCount.count(strFile) || mapFileUseCount[strFile] == 0)
            {
                // Flush log data to the dat file
                CloseDb(strFile);
                dbenv.txn_checkpoint(0, 0, 0);
                dbenv.lsn_reset(strFile.c_str(), 0);
                mapFileUseCount.erase(strFile);

                bool fSuccess = true;
                printf("Rewriting %s...\n", strFile.c_str());
                string strFileRes = strFile + ".rewrite";
                { // surround usage of db with extra {}
                    CDB db(strFile.c_str(), "r");
                    Db* pdbCopy = new Db(&dbenv, 0);
    
                    int ret = pdbCopy->open(NULL,                 // Txn pointer
                                            strFileRes.c_str(),   // Filename
                                            "main",    // Logical db name
                                            DB_BTREE,  // Database type
                                            DB_CREATE,    // Flags
                                            0);
                    if (ret > 0)
                    {
                        printf("Cannot create database file %s\n", strFileRes.c_str());
                        fSuccess = false;
                    }
    
                    Dbc* pcursor = db.GetCursor();
                    if (pcursor)
                        while (fSuccess)
                        {
                            CDataStream ssKey(SER_DISK, CLIENT_VERSION);
                            CDataStream ssValue(SER_DISK, CLIENT_VERSION);
                            int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
                            if (ret == DB_NOTFOUND)
                            {
                                pcursor->close();
                                break;
                            }
                            else if (ret != 0)
                            {
                                pcursor->close();
                                fSuccess = false;
                                break;
                            }
                            if (pszSkip &&
                                strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
                                continue;
                            if (strncmp(&ssKey[0], "\x07version", 8) == 0)
                            {
                                // Update version:
                                ssValue.clear();
                                ssValue << CLIENT_VERSION;
                            }
                            Dbt datKey(&ssKey[0], ssKey.size());
                            Dbt datValue(&ssValue[0], ssValue.size());
                            int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
                            if (ret2 > 0)
                                fSuccess = false;
                        }
                    if (fSuccess)
                    {
                        db.Close();
                        CloseDb(strFile);
                        if (pdbCopy->close(0))
                            fSuccess = false;
                        delete pdbCopy;
                    }
                }
                if (fSuccess)
                {
                    Db dbA(&dbenv, 0);
                    if (dbA.remove(strFile.c_str(), NULL, 0))
                        fSuccess = false;
                    Db dbB(&dbenv, 0);
                    if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
                        fSuccess = false;
                }
                if (!fSuccess)
                    printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
                return fSuccess;
            }
        }
        Sleep(100);
    }
    return false;
}
Beispiel #23
0
	string scan(int n, int b[]) { 
		if (n%6 != 5)		return "bad code";
		if ((n + 1)/6 < 5)	return "bad code";	// S?CKE
		int m = (n + 1)/6;
		int mxw, mnw;
		mxw = 0, mnw = 0x3f3f3f3f;
		for (int i = 0; i < n; i++)
			mxw = max(mxw, b[i]), mnw = min(mnw, b[i]);
		double t = (mnw + mxw) / 2.0;
		mxw = 0, mnw = 0x3f3f3f3f;
		for (int i = 0; i < n; i++) {
			int v = 0;
			if (b[i] < t)
				v = b[i] * 2;
			else
				v = b[i];
			mxw = max(mxw, v), mnw = min(mnw, v);
		}
		if (mxw * 95 > mnw * 105) 	// 5% larger or smaller than intended
			return "bad code";
		string bcode[256];
		for (int i = 0, j = 0; i < n; i += 6, j++) {
			bcode[j] = "";
			for (int k = i; k < i+5; k++) {
				if (b[k] < t)
					bcode[j] = bcode[j] + "0";
				else
					bcode[j] = bcode[j] + "1";
			}
			if (i+5 < n && b[i+5] >= t)	// separate bar = 0 
				return "bad code";
		}
		if (bcode[0] == "01100") {		// modify decode order to START-XXX-STOP
			reverse(bcode, bcode + m);
			for (int i = 0; i < m; i++)
				reverse(bcode[i].begin(), bcode[i].end());
		}
		if (bcode[0] != "00110" || bcode[m-1] != "00110")
			return "bad code";
		for (int i = 0; i < m; i++) { 	// undefine code
			if (!code.count(bcode[i]))
				return "bad code";
			if (i > 0 && i < m-1 && code[bcode[i]] == -1)
				return "bad code";
		}
		
		int C = 0, K = 0;
		for (int i = 1; i < m - 3; i++)
			C = (C + (((m - 4) - i)%10 + 1) * code[bcode[i]])%11;
		for (int i = 1; i < m - 2; i++)
			K = (K + (((m - 4) - i + 1)%9 + 1) * code[bcode[i]])%11;
		
		if (C != code[bcode[m - 3]])
			return "bad C";
		if (K != code[bcode[m - 2]])
			return "bad K";
		
		string res;
		for (int i = 1; i < m - 3; i++) {
			int v = code[bcode[i]];
			if (v < 10)	res += (char)(v + '0');
			else		res += (char)('-');
		}
		return res;
			
	} 
Beispiel #24
0
void naiveBayes(string naiveBayesTestVSM)
{
	ifstream iFile(trainBayes.c_str()); //TF词典"E:\\final\\final\\myData\\myTFDic.txt";
	ifstream featureFile(featureDicPath.c_str());
	cout<<featureDicPath<<endl;
	double featureVal;
	string featureStr;
	string words;
	int TF;
	int cnt;
	int flag;
	int i,j;
	while(featureFile>>featureStr>>featureVal)
		featureDic[featureStr]++;
	while(iFile>>words)
	{
		iFile>>flag>>cnt;
		for(i = 0; i < cnt; i++)
		{
			iFile>>flag>>TF;
			if(featureDic.count(words))
				bayesDic[words][flag] = TF;
		}
	}
	i = j = 0;
	cout<<"******"<<bayesDic.size()<<endl;
	for(map<string,map<int,int> >::iterator itor = bayesDic.begin(); itor != bayesDic.end();itor++)
	{
		//cout<<itor->first<<endl;
		for(int k = 0; k < 8; k++)
			bayes[j][k] = 1.0 / (1000 + bayesDic[itor->first][9]);
		for(map<int,int>::iterator it = itor->second.begin(); it != itor->second.end();it++)
		{
			i = it->first - 1;
			if(i == 8) break;
					bayes[j][i] = 1.0 * (1 + it->second) / (1000.0 + bayesDic[itor->first][9]);
		}
		j++;
	}
	
	ofstream out("mydata\\bayesOnECE.txt");
	for( i = 0; i < 8; i++)
	{
		for(j = 0 ; j < 1000; j++)
				out<<bayes[j][i]<<" ";
		out<<endl;
	}
	double p[8];
	int c,pos,v,b;
	string kk;
	//ifstream in("testBayesOnCross.txt");
	ifstream in(naiveBayesTestVSM.c_str());
	//ofstream myout("ans.txt");
	int result[3117 + 3];
	int reCnt = 0;
	while(in>>kk)
	{
		//in>>kk;
		in>>c;
		for(i = 0; i < 8; i++)p[i] = 0;
		for( i = 0; i < c ;i++)
		{
			in>>pos>>v;
			for(j = 0; j < 8; j++)
			{
				p[j] += v * log(bayes[pos][j]);
				//p[j] += v * log(bayes[j][pos]);
			}
		}
	
		double max = -999999999;
		int ans;
		for(i = 0; i < 8; i++)
		{
			//cout<<p[i]<<endl;
			if(max < p[i])
			{
				max = p[i];
				ans = i;
			}
		}
		//myout<<ans+1<<endl;
		result[reCnt++] = ans;
	}

	for(i = 0; i < reCnt; i++)
    {
            int flag = result[i];
            b = i;
      switch(flag)
		{
		case 2:
			if(b >= 0 && b < 362)artNum[0]++;
			else P[0]++;
			break;
		case 3:
			if(b >= 362 && b < 753)artNum[1]++;
			else P[1]++;
			break;
		case 0:
			if(b >= 753 && b < 1166)artNum[2]++;
			else P[2]++;
			break;
		case 4:
			if(b >= 1166 && b < 1568)artNum[3]++;
			else P[3]++;
			break;
		case 5:
			if(b >= 1568 && b < 1967)artNum[4]++;
			else P[4]++;
			break;
		case 6:
			if(b >= 1967 && b < 2367)artNum[5]++;
			else P[5]++;
			break;
		case 7:
			if(b >= 2367 && b < 2768)artNum[6]++;
			else P[6]++;
			break;
		case 1:
			if(b >= 2768 && b < 3117)artNum[7]++;
			else P[7]++;
			break;
		}
     //b++;
    }
	
}
Beispiel #25
0
static void MutateTxSign(CMutableTransaction& tx, const string& flagStr)
{
    int nHashType = SIGHASH_ALL;

    if (flagStr.size() > 0)
        if (!findSighashFlags(nHashType, flagStr))
            throw runtime_error("unknown sighash flag/sign option");

    vector<CTransaction> txVariants;
    txVariants.push_back(tx);

    // mergedTx will end up with all the signatures; it
    // starts as a clone of the raw tx:
    CMutableTransaction mergedTx(txVariants[0]);
    bool fComplete = true;
    CCoinsView viewDummy;
    CCoinsViewCache view(&viewDummy);

    if (!registers.count("privatekeys"))
        throw runtime_error("privatekeys register variable must be set.");
    bool fGivenKeys = false;
    CBasicKeyStore tempKeystore;
    UniValue keysObj = registers["privatekeys"];
    fGivenKeys = true;

    for (unsigned int kidx = 0; kidx < keysObj.count(); kidx++) {
        if (!keysObj[kidx].isStr())
            throw runtime_error("privatekey not a string");
        CBitcoinSecret vchSecret;
        bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
        if (!fGood)
            throw runtime_error("privatekey not valid");

        CKey key = vchSecret.GetKey();
        tempKeystore.AddKey(key);
    }

    // Add previous txouts given in the RPC call:
    if (!registers.count("prevtxs"))
        throw runtime_error("prevtxs register variable must be set.");
    UniValue prevtxsObj = registers["prevtxs"];
    {
        for (unsigned int previdx = 0; previdx < prevtxsObj.count(); previdx++) {
            UniValue prevOut = prevtxsObj[previdx];
            if (!prevOut.isObject())
                throw runtime_error("expected prevtxs internal object");

            map<string,UniValue::VType> types = boost::assign::map_list_of("txid", UniValue::VSTR)("vout",UniValue::VNUM)("scriptPubKey",UniValue::VSTR);
            if (!prevOut.checkObject(types))
                throw runtime_error("prevtxs internal object typecheck fail");

            uint256 txid = ParseHashUV(prevOut["txid"], "txid");

            int nOut = atoi(prevOut["vout"].getValStr());
            if (nOut < 0)
                throw runtime_error("vout must be positive");

            vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
            CScript scriptPubKey(pkData.begin(), pkData.end());

            {
                CCoinsModifier coins = view.ModifyCoins(txid);
                if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
                    string err("Previous output scriptPubKey mismatch:\n");
                    err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
                        scriptPubKey.ToString();
                    throw runtime_error(err);
                }
                if ((unsigned int)nOut >= coins->vout.size())
                    coins->vout.resize(nOut+1);
                coins->vout[nOut].scriptPubKey = scriptPubKey;
                coins->vout[nOut].nValue = 0; // we don't know the actual output value
            }

            // if redeemScript given and private keys given,
            // add redeemScript to the tempKeystore so it can be signed:
            if (fGivenKeys && scriptPubKey.IsPayToScriptHash() &&
                prevOut.exists("redeemScript")) {
                UniValue v = prevOut["redeemScript"];
                vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
                CScript redeemScript(rsData.begin(), rsData.end());
                tempKeystore.AddCScript(redeemScript);
            }
        }
    }

    const CKeyStore& keystore = tempKeystore;

    bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);

    // Sign what we can:
    for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
        CTxIn& txin = mergedTx.vin[i];
        const CCoins* coins = view.AccessCoins(txin.prevout.hash);
        if (!coins || !coins->IsAvailable(txin.prevout.n)) {
            fComplete = false;
            continue;
        }
        const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;

        txin.scriptSig.clear();
        // Only sign SIGHASH_SINGLE if there's a corresponding output:
        if (!fHashSingle || (i < mergedTx.vout.size()))
            SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);

        // ... and merge in other signatures:
        BOOST_FOREACH(const CTransaction& txv, txVariants) {
            txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
        }
        if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i)))
            fComplete = false;
    }
/* ****************************************************************************
*
* addTriggeredSubscriptions -
*/
static bool addTriggeredSubscriptions
(
  ContextRegistration                   cr,
  map<string, TriggeredSubscription*>&  subs,
  std::string&                          err,
  std::string                           tenant
)
{

  BSONArrayBuilder          entitiesNoPatternA;
  std::vector<std::string>  idJsV;
  std::vector<std::string>  typeJsV;

  for (unsigned int ix = 0; ix < cr.entityIdVector.size(); ++ix)
  {
    // FIXME: take into account subscriptions with no type
    EntityId* enP = cr.entityIdVector.get(ix);

    // The registration of isPattern=true entities is not supported, so we don't include them here
    if (enP->isPattern == "false")
    {
      entitiesNoPatternA.append(BSON(CASUB_ENTITY_ID << enP->id <<
                                     CASUB_ENTITY_TYPE << enP->type <<
                                     CASUB_ENTITY_ISPATTERN << "false"));
      idJsV.push_back(enP->id);
      typeJsV.push_back(enP->type);
    }
  }

  BSONArrayBuilder attrA;
  for (unsigned int ix = 0; ix < cr.contextRegistrationAttributeVector.size(); ++ix)
  {
    ContextRegistrationAttribute* craP = cr.contextRegistrationAttributeVector.get(ix);
    attrA.append(craP->name);
  }

  BSONObjBuilder queryNoPattern;
  queryNoPattern.append(CASUB_ENTITIES, BSON("$in" << entitiesNoPatternA.arr()));
  if (attrA.arrSize() > 0)
  {
    // If we don't do this checking, the {$in: [] } in the attribute name part will
    // make the query fail
    //

    // queryB.append(CASUB_ATTRS, BSON("$in" << attrA.arr()));
    queryNoPattern.append("$or", BSON_ARRAY(
                            BSON(CASUB_ATTRS << BSON("$in" << attrA.arr())) <<
                            BSON(CASUB_ATTRS << BSON("$size" << 0))));
  }
  else
  {
    queryNoPattern.append(CASUB_ATTRS, BSON("$size" << 0));
  }
  queryNoPattern.append(CASUB_EXPIRATION, BSON("$gt" << (long long) getCurrentTime()));


  //
  // This is JavaScript code that runs in MongoDB engine. As far as I know, this is the only
  // way to do a "reverse regex" query in MongoDB (see
  // http://stackoverflow.com/questions/15966991/mongodb-reverse-regex/15989520).
  // Note that although we are using a isPattern=true in the MongoDB query besides $where, we
  // also need to check that in the if statement in the JavaScript function given that a given
  // sub document could include both isPattern=true and isPattern=false documents
  //
  std::string idJsString = "[ ";

  for (unsigned int ix = 0; ix < idJsV.size(); ++ix)
  {
    if (ix != idJsV.size() - 1)
    {
      idJsString += "\""+idJsV[ix]+ "\" ,";
    }
    else
    {
      idJsString += "\"" +idJsV[ix]+ "\"";
    }
  }
  idJsString += " ]";

  std::string typeJsString = "[ ";

  for (unsigned int ix = 0; ix < typeJsV.size(); ++ix)
  {
    if (ix != typeJsV.size() - 1)
    {
      typeJsString += "\"" +typeJsV[ix] + "\" ,";
    }
    else
    {
      typeJsString += "\"" + typeJsV[ix] + "\"";
    }
  }
  typeJsString += " ]";

  std::string function = std::string("function()") +
    "{" +
      "enId = " + idJsString + ";" +
      "enType = " + typeJsString + ";" +
      "for (var i=0; i < this." + CASUB_ENTITIES + ".length; i++) {" +
        "if (this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_ISPATTERN + " == \"true\") {" +
          "for (var j = 0; j < enId.length; j++) {" +
            "if (enId[j].match(this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_ID +
              ") && this." + CASUB_ENTITIES + "[i]." + CASUB_ENTITY_TYPE + " == enType[j]) {" +
              "return true; " +
            "}" +
          "}" +
        "}" +
      "}" +
      "return false; " +
    "}";
  LM_T(LmtMongo, ("JS function: %s", function.c_str()));


  std::string     entPatternQ = CSUB_ENTITIES "." CSUB_ENTITY_ISPATTERN;
  BSONObjBuilder  queryPattern;

  queryPattern.append(entPatternQ, "true");
  queryPattern.append(CASUB_EXPIRATION, BSON("$gt" << (long long) getCurrentTime()));
  queryPattern.appendCode("$where", function);

  auto_ptr<DBClientCursor> cursor;
  BSONObj                  query = BSON("$or" << BSON_ARRAY(queryNoPattern.obj() << queryPattern.obj()));

  TIME_STAT_MONGO_READ_WAIT_START();
  DBClientBase* connection = getMongoConnection();
  if (!collectionQuery(connection, getSubscribeContextAvailabilityCollectionName(tenant), query, &cursor, &err))
  {
    TIME_STAT_MONGO_READ_WAIT_STOP();
    releaseMongoConnection(connection, &cursor);
    return false;
  }
  TIME_STAT_MONGO_READ_WAIT_STOP();

  /* For each one of the subscriptions found, add it to the map (if not already there) */
  while (moreSafe(cursor))
  {
    BSONObj     sub;
    std::string err;
    if (!nextSafeOrError(cursor, &sub, &err))
    {
      LM_E(("Runtime Error (exception in nextSafe(): %s", err.c_str()));
      continue;
    }
    BSONElement idField = getField(sub, "_id");

    //
    // BSONElement::eoo returns true if 'not found', i.e. the field "_id" doesn't exist in 'sub'
    //
    // Now, if 'sub.getField("_id")' is not found, if we continue, calling OID() on it, then we get
    // an exception and the broker crashes.
    //
    if (idField.eoo() == true)
    {
      LM_E(("Database Error (error retrieving _id field in doc: %s)", sub.toString().c_str()));
      continue;
    }

    std::string subIdStr = idField.OID().toString();

    if (subs.count(subIdStr) == 0)
    {
      LM_T(LmtMongo, ("adding subscription: '%s'", sub.toString().c_str()));

      TriggeredSubscription* trigs = new TriggeredSubscription(
        sub.hasField(CASUB_FORMAT) ? stringToFormat(getStringField(sub, CASUB_FORMAT)) : XML,
        getStringField(sub, CASUB_REFERENCE),
        subToAttributeList(sub));

      subs.insert(std::pair<string, TriggeredSubscription*>(subIdStr, trigs));
    }
  }
  releaseMongoConnection(connection, &cursor);

  return true;
}
Beispiel #27
0
int getid(string s)
{
    if(!id.count(s))
        return id[s]=cnt++;
    return id[s];
}
Beispiel #28
0
bool HasHandler(int signum)
{
  return sigHandlers.count(signum) != 0 && !sigHandlers[signum].empty();
}
Beispiel #29
0
int ID (Set x) {
    if(IDcache.count(x)) return IDcache[x];
    Setcache.push_back(x);
    return IDcache[x] = Setcache.size() - 1;
}
Beispiel #30
0
void* proxy(  )
{

	fd_set	writeSet;
	fd_set	readSet;
	int		maxfd = 0;
	//unsigned char	buf[MAXBUF];
	struct timeval	timeout;

	int		maxfdp		= 0;
	int ret=0;
	ssl_info *sslinfo1;
	sockinfo *tempinfo ;
	sockinfo *tempinfo1;
	map<int, sockinfo*>::iterator it;
	map<int, sockinfo*>::iterator it1;
	map<int, sockinfo*>::iterator it3;
    list<TunnelInfo*>::iterator listit;
    TunnelInfo *tunnelinfo;
    char ReqId[20]={0};
	int backcode=0;

	while ( true )
	{
        //ping
        checkping();//ping

        //控制链接断开,关闭所有连接
        if(mainsockstatus==0){
            shutdown( mainsock,2);
            //释放所有连接
            for ( it3 = socklist.begin(); it3 != socklist.end(); )
            {
                clearsock( it3->first,  it3->second);
                it3++;
            }
            socklist.clear();
            mainsock = 0;
            //改回状态
            mainsockstatus=1;
            //初始化通道
            InitTunnelList(&tunnellist,&tunneladdr);
        }

	    if (lastdnsback == -1 ||(lastdnstime + 600) < get_curr_unixtime())
		{
			lastdnsback	= net_dns( &server_addr, s_name, s_port );
			lastdnstime	= get_curr_unixtime();
			printf( "update dns\r\n" );
		}
		//dns解析成功
        if (lastdnsback != -1)
        {
            CheckStatus();
        }

        //注册端口
        if(socklist.count(mainsock)!=0&&mainsock!=0){

            tempinfo=socklist[mainsock];
            if(tempinfo->isauth==1&&regtunneltime+60<get_curr_unixtime()){
                regtunneltime=get_curr_unixtime();
                for ( listit = tunnellist.begin(); listit != tunnellist.end(); ++listit )
                {
                    tunnelinfo =(TunnelInfo	*)*listit;
                    if(tunnelinfo->regstate==0){
                        memset(ReqId,0,20);
                        memset(tunnelinfo->ReqId,0,20);
                        #if OPENSSL
                        SendReqTunnel(mainsock,mainsslinfo->ssl,ReqId,tunnelinfo->protocol,tunnelinfo->hostname,tunnelinfo->subdomain, tunnelinfo->remoteport ,authtoken);
                        #else
                        SendReqTunnel(mainsock,&mainsslinfo->ssl,ReqId,tunnelinfo->protocol,tunnelinfo->hostname,tunnelinfo->subdomain, tunnelinfo->remoteport,authtoken );
                        #endif
                        //copy
                        memcpy(tunnelinfo->ReqId,ReqId,strlen(ReqId));
                        tunnelinfo->regtime=get_curr_unixtime();//已发
                    }
                }
            }
        }


		timeout.tv_sec	= 0;
		timeout.tv_usec = 5000;
		FD_ZERO( &readSet );
		maxfd	= 0;
		maxfdp	= 0;
		FD_ZERO( &writeSet );

		/* 遍历添加 */
		//map<int, sockinfo*>::iterator it;
		for ( it = socklist.begin(); it != socklist.end();  )
		{

			tempinfo = it->second;
			/* 如果未连接才添加,写入监听 */
			if ( tempinfo->isconnect == 0 )
			{
				FD_SET( it->first, &writeSet );
			}
			else{
				FD_SET( it->first, &readSet );
			}
			maxfdp = it->first > maxfdp ? it->first : maxfdp;
			maxfd++;
			//继续遍历
			sleeps(1);
			++it;
		}

        #if UDPCMD
        if(udpsocket>0){
            maxfdp = udpsocket > maxfdp ? udpsocket : maxfdp;
            FD_SET(udpsocket,&readSet );
        }
        #endif //

		if(maxfd==0)
		{
			sleeps( 500 );
		}

		/*  printf("add ok \r\n"); */
        ret = select( maxfdp + 1, &readSet, &writeSet, NULL, &timeout ); /* 为等待时间传入NULL,则永久等待。传入0立即返回。不要勿用。 */
		if ( ret == -1 && maxfd != 0 )
		{
            echo("select error\r\n");
			continue;
		}

		if ( ret > 0 )
		{


            #if UDPCMD
            if(FD_ISSET(udpsocket,&readSet))
            {
                UdpCmd(udpsocket);
            }
            #endif

			for ( it1 = socklist.begin(); it1 != socklist.end(); )
			{
			    tempinfo = it1->second;
			      //ping
                checkping();//这里添加个ping避免超时
                //判断连接超时sock
                if((tempinfo->linktime+10)<get_curr_unixtime()&&tempinfo->isconnect==0)
                {
					//关闭远程连接
                    if(tempinfo->istype==2){
                        echo("连接本地失败");
                        shutdown( tempinfo->tosock, 2 );
                    }
                    clearsock(it1->first,tempinfo);
                    socklist.erase(it1++);
                    continue;
                }

			    /*等于1才是添加到 readSet的*/
				if (FD_ISSET( it1->first, &readSet )&&tempinfo->isconnect==1 )
				{

                    sslinfo1 = tempinfo->sslinfo;
                    /* 远程的转发给本地 */
                    if ( tempinfo->istype == 1 )
                    {
                        //未连接本地
                        if ( tempinfo->isconnectlocal == 0 )
                        {
                            backcode=ConnectLocal(sslinfo1,&it1,tempinfo,&socklist,&tunneladdr);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }
                        //等待本地连接完成
                        if( tempinfo->isconnectlocal == 1 )
                        {
                            sleeps( 1 );//避免频繁触发cpu过高
                        }
                        //本地连接完成转发
                        if( tempinfo->isconnectlocal == 2 )
                        {
                            backcode=RemoteToLocal(sslinfo1,tempinfo,&it1,&socklist);
                            if(backcode==-1)
                            {
                              continue;
                            }
                        }
                    }
                    /* 本地的转发给远程 */
                    else if(tempinfo->istype == 2){
                        backcode=LocalToRemote(&it1,tempinfo,sslinfo1,&socklist);
                        if(backcode==-1)
                        {
                          continue;
                        }
                    }
                    //控制连接
                    else if(tempinfo->istype ==3){
                         backcode=CmdSock(&mainsock,tempinfo,&socklist,server_addr,&ClientId,authtoken,&tunnellist,&tunneladdr);
                         if(backcode==-1)
                         {
                             //控制链接断开,标记清空
                             mainsockstatus=0;
                             lasterrtime=get_curr_unixtime();
                             break;
                         }
                    }


				}
				//可写,表示连接上了
				if ( FD_ISSET( it1->first, &writeSet )&&tempinfo->isconnect==0 )
				{
					if ( tempinfo->isconnect == 0 )
					{
					    //检测连接是否可用
						if (check_sock(it1->first)!= 0 )
						{
						    	//关闭远程连接
							if(tempinfo->istype==2){
                                echo("连接本地失败");
							    shutdown( tempinfo->tosock, 2 );
							}
							clearsock(it1->first,tempinfo);
							socklist.erase(it1++);
							continue;
						}


						/* 为远程连接 */
						if ( tempinfo->istype == 1 )
						{
						    //初始化远程连接
                            backcode=RemoteSslInit(&it1,tempinfo,ClientId,&socklist);
                            if(backcode==-1)
                            {
                               continue;
                            }
                            /* 置为1 */
                            tempinfo->isconnect = 1;
						}

                        //本地连接
                        if ( tempinfo->istype == 2 )
						{
                            if(socklist.count(tempinfo->tosock)>0)
                            {
                                tempinfo1 = socklist[tempinfo->tosock];
                                tempinfo1->isconnectlocal=2;
                            }
                            /* 置为1 */
                            tempinfo->isconnect = 1;
						}

					}
				}
				//继续遍历
				++it1;
			}
		}
		//睡1豪秒,避免CPU过高
		sleeps(2);
	}
	return(0);
}