Can't get Supervisor Strategy to work in Akka.NET - akka.net

I am trying to Supervisor Strategy to work. Here is an illustration of the scenario.
A diagram of a demo app the implements a SupversiorStrategy
I have an actor, FloorTrader that upon OnReceive(object message), creates a FederalRegulator Actor:
var regulator = Context.ActorOf(Props.Create(() => new FederalRegulator("EAST_USA",trade)), "EastFedRegulator");
Then, upon construction, FederalRegulator creates StateRegulators
public class FederalRegulator : RegulatorBase
{
public FederalRegulator(string name, Trade trade) : base(name, trade)
{
StateRegulate(trade);
}
protected override void OnReceive(object message)
{
var msg = message as string;
if(!string.IsNullOrEmpty(msg) && msg.ToUpper().Equals("STOP"))throw new TradeException("No Trading Today");
}
private static void StateRegulate(Trade trade)
{
Context.ActorOf(Props.Create(() => new StateRegulator("NY", trade)), "NYRegulator");
Context.ActorOf(Props.Create(() => new StateRegulator("MA", trade)), "MARegulator");
Context.ActorOf(Props.Create(() => new StateRegulator("CT", trade)), "CTRegulator");
}
}
All the Regulators emit Console.Write() behavior upon construction like so:
public abstract class RegulatorBase : UntypedActor
{
protected RegulatorBase(string name, Trade trade)
{
Name = name;
Trade = trade;
Regulate(Name, Trade);
}
public string Name { get; private set; }
public Trade Trade { get; private set; }
protected void Regulate(string name, Trade trade)
{ // Create a timer
var myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += delegate { Console.WriteLine("{0} is regulating the trade for, {1} ", Name,Trade.Ticker); };
// Set it to go off every 1/2 second,
myTimer.Interval = 500;
// And start it
myTimer.Enabled = true;
}
protected override void OnReceive(object message)
{
//put stuff in later
}
}
The implementation of SupervisionStrategy() in the FloorTrader actor is:
protected override SupervisorStrategy SupervisorStrategy()
{
return new OneForOneStrategy(
0, // maxNumberOfRetries
TimeSpan.FromSeconds(1), // duration
x =>
{
if (x is TradeException)
{
Console.WriteLine("---BLOW UP-----");
return Directive.Stop;
}
return Directive.Restart;
});
}
When the FederalRegulator receives a STOP message, it fires a custom exception, TradeException, as is shown above in the FederalRegulator code.
The output before a fire the STOP message is the expected:
EAST_USA is regulating the trade for, HP
MA is regulating the trade for, HP
NY is regulating the trade for, HP
CT is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
MA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
MA is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
MA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
MA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
MA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
My thinking is that because I am using a OneForOneStrategy, once I fire the STOP message, the FederalRegulator actor, the one emitting , EAST_USA is regulating the trade for, HP should stop, but its children, the StateRegulators should keep on going.
HOWEVER, when I fire the STOP message using: regulator.Tell("STOP");
TradeException gets thrown, but the FederalRegulator keeps emitting. In addition, I am getting Dead Letter messages:
EAST_USA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
MA is regulating the trade for, HP
---BLOW UP-----
[ERROR][2/27/2016 12:18:49 AM][Thread 0011][akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator] No Trading Today
Cause: AkkaNetDemo.Exceptions.TradeException: No Trading Today
at AkkaNetDemo.Regulators.FederalRegulator.OnReceive(Object message) in c:\Users\Bob\Documents\GitHub\AkkaNetDemo\AkkaNetDemo\Regulators\FederalRegulator.cs:line 20
at Akka.Actor.UntypedActor.Receive(Object message)
at Akka.Actor.ActorBase.AroundReceive(Receive receive, Object message)
at Akka.Actor.ActorCell.ReceiveMessage(Object message)
at Akka.Actor.ActorCell.Invoke(Envelope envelope)
[INFO][2/27/2016 12:18:49 AM][Thread 0013][akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator] Message DeathWatchNotification from akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator to akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator was not delivered. 1 dead letters encountered.
[INFO][2/27/2016 12:18:49 AM][Thread 0012][akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator] Message DeathWatchNotification from akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator to akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator was not delivered. 2 dead letters encountered.
[INFO][2/27/2016 12:18:49 AM][Thread 0011][akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator] Message DeathWatchNotification from akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator to akka://TradingSystem/user/MyBroker/SellFloorTrader/EastFedRegulator was not delivered. 3 dead letters encountered.
EAST_USA is regulating the trade for, HP
CT is regulating the trade for, HP
MA is regulating the trade for, HP
NY is regulating the trade for, HP
Enter Trade: EAST_USA is regulating the trade for, HP
CT is regulating the trade for, HP
MA is regulating the trade for, HP
NY is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
MA is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
MA is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
CT is regulating the trade for, HP
NY is regulating the trade for, HP
MA is regulating the trade for, HP
EAST_USA is regulating the trade for, HP
Can anybody help me figure out the error of my ways. From what I have been reading, when one uses a OneForOneStrategy(), the parent should stop and the children will continue.

Fact that you've received message in dead letters means, that actor has been stopped correctly.
However I think, that the major problem here could be caused by the fact, that you're using Timer class - which is a disposable resource - without disposing it and unpinning the delegates, which may result in emitting console writes even after an actor is dead.
In general you probably don't want to use timers, as Akka.NET gives you a free scheduler feature, which supports sending messages or executing actions in delayed or repeatable fashion. It supports cancellation too.
Also:
My thinking is that because I am using a OneForOneStrategy, once I fire the STOP message, the FederalRegulator actor, the one emitting , EAST_USA is regulating the trade for, HP should stop, but its children, the StateRegulators should keep on going.
In case of OneForOneStrategy, the resulting directive will be applied to an actor, but that means it will also have consequences in it's children. If actor will be stopped, it's children will be too, as they cannot live without the parent. Difference between one-for-one and all-for-one is that all-for-one rule works horizontally (in case of actor failure it will be applied to all of it's siblings).

Related

ALC: define an ALC Knowledge Base

Hello I am new to description logics and ALC and I find it confusing defining a KB.
More specifically I am trying to create an ALC KB for the first 3 sentences below and
an ALC formula φ that formalizes the last one.
Sentences:
• Anna is a person.
• The only kind of coffee that Anna drinks is latte.
• A French is a person who drinks only latte coffee.
• Anna is French.
My KB so far:
TBox T:
French ≡ Person ⊓ ∀drinks.Latte
Abox A:
Person(ANNA), drinks(ANNA, LATTE)
φ: French(ANNA)
My questions are:
Is it wrong that I considered latte as concept or I should have written ∀drinks.Coffee instead, because coffee could be considered also a concept?
Is the assertion drinks(ANNA, LATTE) redundant because in the Tbox ∀drinks.Latte exists?
Any suggestions would be appreciated. Cheers!
I think you can model Person, French, Coffee and Latte as concepts with the following axioms:
French ⊑ Person
Latte ⊑ Coffee
The axiom French ≡ Person ⊓ ∀drinks.Latte may be problematic. The reason being that the reasoner will infer whenever an individual x is a Person and x only drinks coffee, that x is French. But it is completely possible that there are people who only drink only lattes but they are not necessarily French. For that reason it is better to express it as follows:
French ⊑ Person ⊓ ∀drinks.Latte
If you now have ANNA as an individual and you assert French(ANNA), this is sufficient. I.e., the reasoner will "know" that ANNA drinks only lattes. However, if you do this in Protege (for example), the reasoner will not infer that ANNA only drinks lattes. The reason for this is that ANNA is in essence an instance of the complex concept expression Person ⊓ ∀drinks.Latte, because we said she is French. Reasoners give inferences in terms of named concepts only because in general there can be an infinite number of inferences in terms of complex concept expressions.
To see that the reasoner "knows" this. Create another sublass of Coffee class, say Expresso that is disjoint with Latte. Create an instance of Expresso, say EXPRESSO and assert drinks(ANNA, EXPRESSO). Running the reasoner now will cause an inconsistency.
As for your question regarding modeling Latte as concept or an individual: usually it is better to model as a class. I explain this for OWL in this SO question. This holds to true for ALC as well.
If you want understand more about when to use equivalence versus subsumption, I have written about this on my blog here.

Natural Text Generation based on key-value pairs

I have 40 entities forming a table. These entities consist of numerical or alphabetical key:value pairs in the context of real estate.
A table could look like this:
- Address 10066 Cielo Dr BEVERLY HILLS, CA 90210 UNITED STATES
- Price: $69,995,000
- Interior: 21,000 Sq Ft.
- Property Type: Single Family Home
- Year Home Built: 1996
Based on this table, which is generated synthetically, I would like to develop a grammatically correct natural text that considers the entire set of key:value pairs.
In our example, something like this:
"The property is located at 10066 Cielo Dr BEVERLY HILLS, CA 90210 UNITED STATES and costs
$69,995,000. The beautiful interior of the Single Family home sums up to 21,000 Sq Ft. The home was built in 1996."
I learned that GAN BERT might be the approach for this problem. Would it be possible to make that work or do you know a better approach?
Thanks for any sort of help, I really appreciate it!
NLPChoppa

Pyspark (from csv file) is loading dataframe in a different format

(I am new to pyspark)
I am trying to read a csv file into a pyspark dataframe as follows:
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession, SQLContext
spark = SparkSession.builder.master("local[1]").appName("SampleWork").getOrCreate()
df = spark.read.csv('train.csv',sep=",",header=True,inferSchema=True)
But I am not getting expected result dataframe here. How to read this file correctly.
I have added the first 3 rows of the sample csv file here.
csv file:
id,url_legal,license,excerpt,target,standard_error
c12129c31,,,"When the young people returned to the ballroom, it presented a decidedly changed appearance. Instead of an interior scene, it was a winter landscape.
The floor was covered with snow-white canvas, not laid on smoothly, but rumpled over bumps and hillocks, like a real snow field. The numerous palms and evergreens that had decorated the room, were powdered with flour and strewn with tufts of cotton, like snow. Also diamond dust had been lightly sprinkled on them, and glittering crystal icicles hung from the branches.
At each end of the room, on the wall, hung a beautiful bear-skin rug.
These rugs were for prizes, one for the girls and one for the boys. And this was the game.
The girls were gathered at one end of the room and the boys at the other, and one end was called the North Pole, and the other the South Pole. Each player was given a small flag which they were to plant on reaching the Pole.
This would have been an easy matter, but each traveller was obliged to wear snowshoes.",-0.340259125,0.464009046
85aa80a4c,,,"All through dinner time, Mrs. Fayre was somewhat silent, her eyes resting on Dolly with a wistful, uncertain expression. She wanted to give the child the pleasure she craved, but she had hard work to bring herself to the point of overcoming her own objections.
At last, however, when the meal was nearly over, she smiled at her little daughter, and said, ""All right, Dolly, you may go.""
""Oh, mother!"" Dolly cried, overwhelmed with sudden delight. ""Really?
Oh, I am so glad! Are you sure you're willing?""
""I've persuaded myself to be willing, against my will,"" returned Mrs. Fayre, whimsically. ""I confess I just hate to have you go, but I can't bear to deprive you of the pleasure trip. And, as you say, it would also keep Dotty at home, and so, altogether, I think I shall have to give in.""
""Oh, you angel mother! You blessed lady! How good you are!"" And Dolly flew around the table and gave her mother a hug that nearly suffocated her.",-0.315372342,0.480804970
b69ac6792,,,"As Roger had predicted, the snow departed as quickly as it came, and two days after their sleigh ride there was scarcely a vestige of white on the ground. Tennis was again possible and a great game was in progress on the court at Pine Laurel. Patty and Roger were playing against Elise and Sam Blaney, and the pairs were well matched.
But the long-contested victory finally went against Patty, and she laughingly accepted defeat.
""Only because Patty's not quite back on her game yet,"" Roger defended; ""this child has been on the sick list, you know, Sam, and she isn't up to her own mark.""
""Well, I like that!"" cried Patty; ""suppose you bear half the blame, Roger. You see, Mr. Blaney, he is so absorbed in his own Love Game, he can't play with his old-time skill.""
""All right, Patsy, let it go at that. And it's so, too. I suddenly remembered something Mona told me to tell you, and it affected my service.""",-0.580117966,0.476676226
You can use the custom escape character with the multiLine option.
df = spark.read.csv("test.csv", header=True, inferSchema=True, escape="\"", multiLine=True)
+---------+---------+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+--------------+
|id |url_legal|license|excerpt |target |standard_error|
+---------+---------+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+--------------+
|c12129c31|null |null |When the young people returned to the ballroom, it presented a decidedly changed appearance. Instead of an interior scene, it was a winter landscape.
The floor was covered with snow-white canvas, not laid on smoothly, but rumpled over bumps and hillocks, like a real snow field. The numerous palms and evergreens that had decorated the room, were powdered with flour and strewn with tufts of cotton, like snow. Also diamond dust had been lightly sprinkled on them, and glittering crystal icicles hung from the branches.
At each end of the room, on the wall, hung a beautiful bear-skin rug.
These rugs were for prizes, one for the girls and one for the boys. And this was the game.
The girls were gathered at one end of the room and the boys at the other, and one end was called the North Pole, and the other the South Pole. Each player was given a small flag which they were to plant on reaching the Pole.
This would have been an easy matter, but each traveller was obliged to wear snowshoes.|-0.340259125|0.464009046 |
|85aa80a4c|null |null |All through dinner time, Mrs. Fayre was somewhat silent, her eyes resting on Dolly with a wistful, uncertain expression. She wanted to give the child the pleasure she craved, but she had hard work to bring herself to the point of overcoming her own objections.
At last, however, when the meal was nearly over, she smiled at her little daughter, and said, "All right, Dolly, you may go."
"Oh, mother!" Dolly cried, overwhelmed with sudden delight. "Really?
Oh, I am so glad! Are you sure you're willing?"
"I've persuaded myself to be willing, against my will," returned Mrs. Fayre, whimsically. "I confess I just hate to have you go, but I can't bear to deprive you of the pleasure trip. And, as you say, it would also keep Dotty at home, and so, altogether, I think I shall have to give in."
"Oh, you angel mother! You blessed lady! How good you are!" And Dolly flew around the table and gave her mother a hug that nearly suffocated her. |-0.315372342|0.48080497 |
|b69ac6792|null |null |As Roger had predicted, the snow departed as quickly as it came, and two days after their sleigh ride there was scarcely a vestige of white on the ground. Tennis was again possible and a great game was in progress on the court at Pine Laurel. Patty and Roger were playing against Elise and Sam Blaney, and the pairs were well matched.
But the long-contested victory finally went against Patty, and she laughingly accepted defeat.
"Only because Patty's not quite back on her game yet," Roger defended; "this child has been on the sick list, you know, Sam, and she isn't up to her own mark."
"Well, I like that!" cried Patty; "suppose you bear half the blame, Roger. You see, Mr. Blaney, he is so absorbed in his own Love Game, he can't play with his old-time skill."
"All right, Patsy, let it go at that. And it's so, too. I suddenly remembered something Mona told me to tell you, and it affected my service." |-0.580117966|0.476676226 |
+---------+---------+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+--------------+

How to shuffle a hashmap in kotlin

I have created a hashmap. Now I want to shuffle the objects in it. We have Collections.shuffle() to shuffle all the elements in a list. How can I do the same in hashmap?
This is my hashmap:
val tips = hashMapOf("Having a balanced diet is the key" to "Have nutritious foods like vegetables and fruits along with legumes, whole wheat, cereals etc., at regular intervals. Avoid oily and spicy food to ease your pregnancy symptoms. Plan your food intake and have it as 4-5 light meals every day."
, "Fluids will help you manage" to "Drink sufficient water and fluids to maintain the retention of water in your body. This will help you control constipation, indigestion, dryness, fatigue, bloating and gas. Avoid alcohol and caffeine drinks which may have serious effects during pregnancy."
, "Do not miss prenatal supplements" to "Doctors prescribe prenatal vitamin and mineral supplements for the normal growth and development. Do not skip these supplements as they can prevent preterm labour and many serious health concerns in the newborn."
, "Folic acid is essential" to "During pregnancy, have folic acid (supplement) or folate (natural source of folic acid) to avoid various health problems. They are rich in green leafy vegetables, oranges, avocado etc.")
This code should work:
tips.map { it.key to it.value }.shuffled().toMap()
It converts Map to List, shuffles it and then converts back to Map.
I am assuming that you want a random tip, but not the same one twice until the map is exhausted. For that, you should not alter the map at all. Use a singleton which provides you with random tips like that.
val tips = /*...*/
fun main(args: Array<String>) {
val (title, text) = TipProvider.next()
println("$title: $text")
}
object TipProvider {
var tipPool = mutableListOf<String>()
fun next(): Pair<String, String> {
if(tipPool.isEmpty()) {
// create copy of keys
tipPool = mutableListOf(*(tips.keys.shuffled().toTypedArray()))
}
val nextTipKey = tipPool.first()
tipPool.remove(nextTipKey)
return nextTipKey to tips[nextTipKey]!!
}
}

Unescaped control characters in NSJSONSerialization

I have this JSON http://www.progmic.com/ielts/retrive.php that I need to parse. When I do it with NSJSONSerialization, I get "Unescaped control character around character 1981" error.
I need to know:
What the heck are the unescaped control characters? Is there a list or something?
How do I get rid of this error? The easiest way?
Thanks in advance.
I added this method to remove the unescaped characters from retrieved string:
- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
if (range.location != NSNotFound) {
NSMutableString *mutable = [NSMutableString stringWithString:inputString];
while (range.location != NSNotFound) {
[mutable deleteCharactersInRange:range];
range = [mutable rangeOfCharacterFromSet:controlChars];
}
return mutable;
}
return inputString;
}
After recieving the NSData, I convert it to NSString, call the above method to get a new string with removed control characters and then convert the new NSString to NSData again for further processing.
What are you doing before using NSJSONSerialization? Check the encodings, maybe the issue lies there.
I quickly tried and it worked. The source JSON is valid. This is what I got when I serialize the array back to JSON with the pretty print thingy:
[
{
"url2": "http://ielts.progmic.com/app/i_COFANewSouthWhales.html",
"title": "COFA New South Whales ",
"img": "http://ielts.progmic.com/images/uni/1340407904.jpg",
"url": "http://ielts.progmic.com/app/COFANewSouthWhales.html",
"desc": "The College offers nine undergraduate degrees including some double degrees associated with other UNSW faculties.",
"img2": "http://ielts.progmic.com/images/uni/thumb/1340407904.jpg"
},
{
"url2": "http://ielts.progmic.com/app/i_RoyalCollegeOfArts.html",
"title": "Royal College Of Arts ",
"img": "http://ielts.progmic.com/images/uni/1340542224.jpg",
"url": "http://ielts.progmic.com/app/RoyalCollegeOfArts.html",
"desc": "The Royal College of Art (informally the RCA) is a public research university specialised in art and design located in London, United Kingdom. It is the world's only wholly postgraduate university of art and design, offering the degrees of Master of Arts (M.A.), Master of Philosophy (M.Phil.) and Doctor of Philosophy (Ph.D.). It was founded in 1837",
"img2": "http://ielts.progmic.com/images/uni/thumb/1340542224.jpg"
},
{
"url2": "http://ielts.progmic.com/app/i_MIDDLESEXUNIVERSITY.html",
"title": "MIDDLESEX UNIVERSITY ",
"img": "http://ielts.progmic.com/images/uni/1340410005.jpg",
"url": "http://ielts.progmic.com/app/MIDDLESEXUNIVERSITY.html",
"desc": "We have a reputation for the highest quality teaching, research that makes a real difference to people’s lives and a practical, innovative approach to working with businesses to develop staff potential and provide solutions to business issues. Our expertise is wide ranging, from engineering, information, health and social sciences, to business, arts and education - and we’re national leaders in work based learning solutions.",
"img2": "http://ielts.progmic.com/images/uni/thumb/1340410005.jpg"
},
{
"url2": "http://ielts.progmic.com/app/i_UNIVERSITYOFSCOTLAND.html",
"title": "UNIVERSITY OF SCOTLAND ",
"img": "http://ielts.progmic.com/images/uni/1340410189.jpg",
"url": "http://ielts.progmic.com/app/UNIVERSITYOFSCOTLAND.html",
"desc": " Founded in 1451, Glasgow is the fourth-oldest university in the English-speaking world. Over the last five centuries and more, we’ve constantly worked to push the boundaries of what’s possible. We’ve fostered the talents of seven Nobel laureates, one Prime Minister and Scotland’s inaugural First Minister. We’ve welcomed Albert Einstein to give a lecture on the origins of the general theory of relativity. Scotland’s first female graduates completed their degrees here in 1894 and the world’s first ultrasound images of a foetus were published by Glasgow Professor Ian Donald in 1958. In 1840 we became the first university in the UK to appoint a Professor of Engineering, and in 1957, the first in Scotland to have an electronic computer. All of this means that if you choose to work or study here, you’ll be walking in the footsteps of some of the world’s most renowned innovators, from scientist Lord Kelvin and economist Adam Smith, to the pioneer of television John Logie Baird.",
"img2": "http://ielts.progmic.com/images/uni/thumb/1340410189.jpg"
}
]
You can copy and paste the JSON in a file, save it in various encodings and see what's going on with your code. UTF-8 should be the way to go.