Differentiate Rail routes that exist and not found in anylogic - anylogic

I'm trying to simulate routes from the retailer to the customer in the US in Anylogic and wanted to know what routes could be done by rail. But, if a rail route does not exist I get an error, and the simulation stops. I want the simulation to run and if the route does not exist, it saves in a variable (like a boolean variable, if the route exists it's true and if not is false). Thanks for the help!

You should have a map object that has the road type set to rail and one that has the road type set to rail
Then with some simple code, you can check if there is a rail that exists and if not do something else.
try {
GISRoute route = map.getRoute(fromLatitude, fromLongitude, toLatitude,
toLatitude);
} catch (Exception e) {
traceln("Error - no route found - from " + fromLatitude) + ", " +
fromLongitude + " to " + toLatitude + ", " + toLongitude);
traceln("Exception " + e);
// Maybe look for a road route?
}

Related

walker talk not found when deleting yield in test

import {*} with './tesla_ai.jac';
import {*} with './graph.jac';
import {*} with './nodes.jac';
walker nothing {}
test "Testing Flow"
with graph::tesla_ai by walker::nothing{
flows = file.load_json("master_test.json");
for flow in flows {
std.log("\n==== Testing flow: " + flow["test_name"] + " ====");
for step in flow['flow'] {
spawn here walker::talk(question = step["query"]);
res = std.get_report();
std.log("HERE >>> ", step["query"] , " ==== ", res[-1]);
assert(res[-1] == step['response']);
}
jaseci.walker_yield_delete("talk");
}
}
I'm trying to delete the yield of walker talk after it goes through the flow but it throws this run error when i run the sentinel test.
{"success": false, "response": "Walker talk not found!"}
I am trying to delete the yield everytime it goes to a new flow so it does not keep track with the last response or entities.
You may be able to use the jaseci.walker_yield_list() action call to check that there is indeed actually walkers yielded and only call jaseci.walker_yield_delete("talk"); if its in the list.

Unity Lobby/Relay - joining by code results in error 400 Bad Request

as a beginner I am trying to test new Unity Packages - Unity Lobby and Unity Relay to make multiplayer card game. Quick joining lobby and creating a lobby works fine but I have encountered a problem with joining lobby using Join Code. Here's the code:
public async void JoinByCode() {
string lobbyCode = InputField.text;
Debug.Log(lobbyCode);
Debug.Log("Searching for lobby with code " + lobbyCode + "...");
// UpdateState ?.Invoke("Searching for lobby with code " + lobbyCode + "...");
try {
JoinLobbyByCodeOptions options = new JoinLobbyByCodeOptions();
Lobby lobby = await Lobbies.Instance.JoinLobbyByCodeAsync(lobbyCode, options); //<--- results in error 400 - Bad Request
Debug.Log(lobby);
Debug.Log("Joined lobby: " + lobby.Id);
Debug.Log("Players in lobby: " + lobby.Players.Count);
//RelayCode
string joinCode = lobby.Data["joinCode"].Value;
Debug.Log("Kod dostępu: " + joinCode);
JoinAllocation allocation = await Relay.Instance.JoinAllocationAsync(joinCode);
//obiekt joindata
_joinData = new RelayJoinData {
Key = allocation.Key,
Port = (ushort) allocation.RelayServer.Port,
AllocationID = allocation.AllocationId,
AllocationIDBytes = allocation.AllocationIdBytes,
ConnectionData = allocation.ConnectionData,
HostConnectionData = allocation.HostConnectionData,
IPv4Address = allocation.RelayServer.IpV4
};
_joinData.JoinCode = await Relay.Instance.GetJoinCodeAsync(allocation.AllocationId);
NetworkManager.Singleton.GetComponent<UnityTransport>().SetClientRelayData(
_joinData.IPv4Address,
_joinData.Port,
_joinData.AllocationIDBytes,
_joinData.Key,
_joinData.ConnectionData,
_joinData.HostConnectionData
);
NetworkManager.Singleton.StartClient();
Debug.Log("Found lobby, code: " + joinCode);
UpdateState?.Invoke("Joining lobby, code: " + joinCode + ", players in lobby: " + lobby.Players.Count);
MatchFound?.Invoke();
} catch (LobbyServiceException e) {
Debug.Log("There's a problem finding lobby, try again. " + e);
}
}
In general: Join Code is passed from InputField, then to JoinLobbyByCodeAsync, then send player data to server. The problem is with variable lobby - when I am trying to test JoinByCode, it results with error:
There's a problem finding lobby, try again. Unity.Services.Lobbies.LobbyServiceException: request failed validation ---> Unity.Services.Lobbies.Http.HttpException`1[Unity.Services.Lobbies.Models.ErrorStatus]: HTTP/1.1 400 Bad Request
and I have no idea how to solve this problem. Yes, I was using Unity Documentation for Lobby and trying to find any info about error 400 in Lobby. I will be really grateful if someone could help me with this problem. Cheers!
I had a similar problem, in my case the input contained an extra character. Make sure that there are only 6 characters in your variable "lobbyCode" by checking it with lobbyCode.Length. Also make sure that you have activated the Lobby and Relay service in the dashboard.
My post to this problem:
https://forum.unity.com/threads/problem-joining-a-private-lobby-through-lobbycode-joinlobbybycodeasync.1287908/#post-8171102

CAP Dialog not found for Dialog Id

I am using SS7 Stack to receive IDP packets and forward to core using a new dialog.
I am able to successfully forward the request using following code:
#Override
public void onInitialDPRequest(InitialDPRequest arg0) {
try {
String refId = StringUtility.createRefId("sc");
logger.info("[" + refId + "] IDP Recieved");
String outgoingGTDigits = "92308985051";
int calledSSN = 146;
int remotePC = 3003;
SccpAddress remoteAddress = MapUtilities.getSccpAddress(RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE, outgoingGTDigits, calledSSN, remotePC);
arg0.getCAPDialog().setRemoteAddress(remoteAddress);
logger.debug("[" + refId + "] Forwading to Core with remoteAddress [" + remoteAddress + "]");
InitialDPRequestImpl initialDPRequestImpl = (InitialDPRequestImpl) arg0;
Invoke invoke = SCCPProxy.tcapStack_cap.getProvider().getComponentPrimitiveFactory()
.createTCInvokeRequest(InvokeClass.Class2);
invoke.setTimeout(_Timer_CircuitSwitchedCallControl_Short);
OperationCode oc = SCCPProxy.tcapStack_cap.getProvider().getComponentPrimitiveFactory().createOperationCode();
oc.setLocalOperationCode((long) CAPOperationCode.initialDP);
AsnOutputStream aos = new AsnOutputStream();
initialDPRequestImpl.encodeData(aos);
Parameter p = SCCPProxy.tcapStack_cap.getProvider().getComponentPrimitiveFactory().createParameter();
p.setTagClass(initialDPRequestImpl.getTagClass());
p.setPrimitive(initialDPRequestImpl.getIsPrimitive());
p.setTag(initialDPRequestImpl.getTag());
p.setData(aos.toByteArray());
invoke.setParameter(p);
invoke.setOperationCode(oc);
// Create a new dialog
Dialog clientDialog = SCCPProxy.tcapStack_cap.getProvider().getNewDialog(arg0.getCAPDialog().getLocalAddress(), remoteAddress);
invoke.setInvokeId(clientDialog.getLocalDialogId());
clientDialog.sendComponent(invoke);
logger.debug("[" + refId + "] set invoke id " + clientDialog.getLocalDialogId());
//long[] _ACN_ = new long[]{0, 4, 0, 0, 1, 0, 19, 2};
ApplicationContextName acn = SCCPProxy.tcapStack_cap.getProvider().getDialogPrimitiveFactory()
.createApplicationContextName(arg0.getCAPDialog().getApplicationContext().getOID());
// Create begin request
TCBeginRequest tcbr = SCCPProxy.tcapStack_cap.getProvider().getDialogPrimitiveFactory().createBegin(clientDialog);
tcbr.setApplicationContextName(acn);
clientDialog.send(tcbr);
logger.info("[" + refId + "] Forwaded to core with id: " + clientDialog.getLocalDialogId());
} catch (Exception ex) {
logger.error("Exception: ", ex);
}
}
TCPDump
Now when core node replies to this packet (packet #3) . I am getting CAP Dialog not found for Dialog Id n in sigtran logs.
Sigtran Logs
Am I forwarding packet correctly?
It's a little bit more complicated.
I may assume that you want to handle all in same Sbb..
When you create a new capDialog(clientDialog in your case), it created with new TCAP otid and dtid. So even when you receive a response in terms of new capDialog, you have to correlate it with original capDialog.
Sbb knows only about ActivityContext from initial event, as you didn't attach sbbLocalObject to new ActivityContext.
It's better to use Parent->Child architecture for such tasks. Parent Sbb handles all original dialog events. Child Sbb creates new dialog, attach sbbLocalObject to new ActivityContext and handles all related events for new dialog.
I was able to forward packet and get reply without any issue by doing following changes:
Have to create new dialog like this
CAPDialogCircuitSwitchedCall capDialog = capProvider.getCAPServiceCircuitSwitchedCall().createNewDialog(arg0
.getCAPDialog().getApplicationContext(), proxyOwnAddress, destinationAddress, arg0.getCAPDialog().getRemoteDialogId());
Copy payload from original dialog and put in new dialog
capDialog.addInitialDPRequest((int) arg0.getInvokeId(),
arg0.getServiceKey(), arg0.getCalledPartyNumber(),
arg0.getCallingPartyNumber(), arg0.getCallingPartysCategory(),
arg0.getCGEncountered(), arg0.getIPSSPCapabilities(),
arg0.getLocationNumber(), arg0.getOriginalCalledPartyID(),
arg0.getExtensions(), arg0 .getHighLayerCompatibility(),
arg0.getAdditionalCallingPartyNumber(), arg0.getBearerCapability(),
arg0.getEventTypeBCSM(), arg0 .getRedirectingPartyID(),
arg0.getRedirectionInformation(), arg0.getCause(),
arg0.getServiceInteractionIndicatorsTwo(),
arg0.getCarrier(),
arg0.getCugIndex(), arg0.getCugInterlock(),
arg0.getCugOutgoingAccess(), arg0.getIMSI(),
arg0.getSubscriberState(), arg0 .getLocationInformation(),
arg0.getExtBasicServiceCode(), arg0.getCallReferenceNumber(),
arg0.getMscAddress(), arg0 .getCalledPartyBCDNumber(),
arg0.getTimeAndTimezone(), arg0.getCallForwardingSSPending(),
arg0.getInitialDPArgExtension());
Save and Forward new dialog
dialogHashMap.put(capDialog.getLocalDialogId(), arg0.getCAPDialog());
capDialog.setReturnMessageOnError(true);
capDialog.send();
logger.info("[" + refId + "] Forwaded with id: " +
capDialog.getLocalDialogId());
Retrieve and reply
So now when I received the reply from core. I just needed to retrieve original dialog from dialogHashMap using local dialogId and reply back

Is there a better way to log information in Scala than using a function?

I'm writing a web service and am often sending messages over HTTPS.
val response = sendJson(JsonUtil.getTextMessageJson("Sorry I don't understand what day you want. You can say " + "things like \"tomorrow\" or \"next Friday\""))
I could follow this call with onComplete {} and handle the resulting Success or Failure but since I do this so often I have written a simple function in a helper class:
def logSendResult(response: Future[WSResponse])(implicit userId: String): Unit = {
response onComplete {
case Success(res) => Logger.info("Message to " + userId + " sent successfully with " +
"response code: " + res.status)
case Failure(exception) => Logger.info("Message to " + userId + " failed with " +
"exception: " + exception.getMessage)
}
}
Which I then call with:
LogUtils.logSendResult(response)
This is working fine but I was wondering if there is a better way?
I believe you have a cross cutting concerns. If not handled properly might cause problem: https://en.wikipedia.org/wiki/Cross-cutting_concern
AOP (aspect oriented programming) can fix 'cross cutting concerns'.
Here is a sample AOP program using AspectJ library in scala.
This sample aspect will print Method, its input and result detail, when a method is entered annotated with the #Loggable annotation and finished execution.
https://github.com/knoldus/CrossCuttingConcern_Scala/blob/master/src/main/scala/com/knoldus/aspect/Aspect.scala
Hope this help. Best of luck!
HTTP Filters
This sounds like a good application of a Filter https://www.playframework.com/documentation/2.5.x/ScalaHttpFilters
In the example they even show ho to Build a logging Filter.

How to make log code less side-effect?

There are lot of log statements in some important method, they are used to log the progress and some important information.
val result = user.login()
if(result) {
logger.info("User has logged in successful: " + user.id)
val questions = user.queryQuestions()
logger.info("User has " + questions.size + " questions")
val latestQuestion = questions.headOption
logger.info("The latest question is: " + latestQuestion)
...
} else {
logger.info("User has logged failed: " + user.id)
}
Suppose all the log information are very important, they need to be logged and audit. But the code looks like Java rather than Scala.
How can we improve it so it looks more functional and less side-effect?