Thursday, 17 June 2021

Playing with Ix.Net and IAsyncEnumerable

When IAsyncEnumerable was introduced along with C# 8 many of us missed missed that Linq to Objects had not been extended to work with IAsyncEnumerables as it does with IEnumerables. Well, the community took the effort in their own hands and it's called System.Linq.Async. It's also called (or it's part of, I'm a bit confused about it) Ix.NET (Interactive Extensions for .Net, one part of the Reactive Extensions for .Netproject) and is sort of the equivalent to the nice javascript library IxJS about which I talked in this post.

As expected, it includes all the main linq methods "Select, Where" so that you can filter, transform... your async pull streams. But in addition, you have methods like SelectAwait, WhereAwait... These methods use an async function (a function returning a Task) rather than a normal function. This means that you can project, filter... your asynchronous streams both with synchronous and asynchronous functions. Let's see an example where I apply first and async function, then filter with a synchronous one and finally apply a synchronous function:



private static async IAsyncEnumerable<string> GetCurrentTrendyCities()
{
    foreach (var city in new List<string> {"Paris", "Toulouse", "Berlin", /*"Bruxelles",*/ "Hamburg" })
    {
        Console.WriteLine("Obtaining Trendy City");
        await Task.Delay(1000);
        Console.WriteLine("Trendy City Obtained");

        yield return city;

    }
}

public static async Task<Country> SearchCountryAsync(string city)
{
    await Task.Delay(2000);
    return countries.FirstOrDefault(country => country.MainCities.Contains(city));
}

private static async Task RunAsyncEnumerableSample(IAsyncEnumerable<string> asyncCities)
{
    var countries = asyncCities.SelectAwait(async (city) => {
        var country = await SearchCountryAsync(city);
        return (city, country);
    })
    .Where (cityCountryTuple => cityCountryTuple.country != null)
    .Select(cityCountryTuple => $"{cityCountryTuple.city} - {cityCountryTuple.country.Name.ToUpper()}");
    
    await foreach(var cityCountry in countries)
    {
        Console.WriteLine(cityCountry);
    }

}


RunAsyncEnumerableSample(GetCurrentTrendyCities());

        

Sometimes we need to apply asynchronous functions to synchronous enumerables. The Linq to Objects extension methods are designed to work with synchronous functions, so when using them with functions returning a Task, you'll end up working all over your methods chain with IEnumerable<Task<TResult>> rather than with IEnumerable<TResult> which makes the thing a bit odd. Let's see what I mean:


IEnumerable<string> citiesToSearch = new List<string> {"Paris", "Toulouse", "Berlin", "Hamburg" };
var cityPromises = citiesToSearch.Select(async (city) => await SearchCountryAsync(city))
    .Select(async (country) => (await country).Name.ToUpper());

foreach (var cityPromise in cityPromises)
{
    var city = await cityPromise;
    Console.WriteLine(city);
}

A much more elegant solution is obtaining an IAsyncEnumerable from your IEnumerable (with ToAsyncEnumerable) and then use the Linq.Async methods, like this:


IEnumerable<string> citiesToSearch = new List<string> {"Paris", "Toulouse", "Berlin", "Hamburg" };
IAsyncEnumerable<string> asyncCities =  citiesToSearch.ToAsyncEnumerable();          
var countries = asyncCities.SelectAwait(async (city) => await SearchCountryAsync(city))
    .Where (country => country != null)
    .Select(country => country.Name.ToUpper());

await foreach(var country in countries)
{
    Console.WriteLine(country);
}

Saturday, 12 June 2021

Mbappé

It feels really nice when you think poorly (very poorly) of someone and then you are proven wrong. That's what has happened to me recently with the French football player, Mbappé, after reading this exemplary interview.

I have to say that I don't like football, watching it and even less playing. I particularly hate the business around it, the idolatry for some players that in too many occasions are just a bunch of arrogant rednecks... Anyway, 3 years ago, due to some personal circunstances, I quite followed the world cup, and I first knew about this French player, Kylian Mbappé. The guy seemed quite humble, well behaved, a normal French guy born to immigrant parents, that having grown up in a poor neighbourhood (in the infamous Seine-Saint-Denis department) was very far away from Anti-French Maghrebian scum (racaille) like Benzema...

However, in the last year a couple of things made me think that Mbappé was just one more "Francais de papier", with no other interest in France than sucking it dry... After the brutal murder by an Islamist of French teacher Samuel Patty several members of the French National team recorded a video to promote respect for the Educational System and its workers. How odd that not a single Muslim player decided to take part in that video... Mbappé was also missing, which even led some people to fear that he had converted to Islam (he was raised as a Christian)... Little after that I found that he had given a signed t-shirt to an Islamist Russian MMA Champio that had asked for "punishing" Charlie Hebdo and its readers. Yes, it's pretty likely that Mbappé knew nothing about this... but well, it didn't smell good to me. By the way, a Russian Islamist... if you still think that Putin is a protector of Christianity you better face reality... Putin is in pretty good terms with the Islamists ruling Chechnya, he did not side at all with Christian Armenians against Turkish Islamist Azerbaijan scum... and so on, and so on...

So when I read the aforementioned interview I was pretty delighted. Mbappé is an idol for many French youngsters, many of them young guys of immigrant descent living in bad areas. All the French youth (but particularly those of non-French ancestry) are subject day after day to a massive stream of anti-French propaganda, vomited by the Left, the Islamists and the Indigenists... "You have to hate France for its evil past and its evil present, you have to identify with the culture of your ancestors rather than the culture of this country, you have to reject to assimilate..." So when the child of 2 immigrants says what he says in that interview, it's important, really important. Many others have said it, like Patrice Quarteron, but they can not reach such a crowd as Mbappé.

I'm going to translate below (sorry for my lack of skills) part of the interview:

  • Are you very attached to France?
    Absolutely. I was born in France, I've grown up in France, France has given everything to me. And I try to give in return, each time that I play with the National Team. I think that my love for France does not need to be proved. Playing for France is above anything.

  • Let's talk about your origins (Cameroonian and Algerian). Is Identity a concern for you?
    No. But I can understand that you ask me about. For me, that's always been clear: I've been born in France, my parents are French, I've grown up in France. I'm 100% French. For sure, I'm very proud of my origins, because that's part of my history, my roots. But me, my contry, it's France.

  • You often talk about "the New France". Do you define yourself as black or arab?
    Not at all. For me, saying that you are black, arab, white, is creating a wall, and in this new France, there are no walls, we are all together.

  • However, there are strong tensions around this issues...
    We should not see France darker that it is! For sure I think that there are problems in this country, but I swear to you, me, someone who is lucky to travel a lot, that this is a very good country.

  • Your parents enrolled you in a private, catholique school. Are you religious?
    I am a believer, but not a practitioner. This college was chosen because of its calm, it gave me an environment that I needed. I was a turbulent, hyperactive child.

  • Your love for France, it comes from your parents?
    I've always been educated with this form of recognition for France, because France does things for other people, and to me and my parents, she has given us a lot. Therefore you have to be proud of your country. The Americans are proud of being Americans. Why French peopler are not proud of being French?

The interview was originally published in a "progressist" magazine, so I can imagine that the journalist was a Left-wing idiot. The questions are very insistent on the same topic, very inquisitional, as if he was expecting the typical answer that the Left loves ("France is evil, France is racist, you evil colonizers...") and as he was getting just the contrary he could not understand it and continued to insist, anxious for a "normal" answer. No way, question after question the answers are perfect, I can taste the feeling of dismay of the blood thirsty Leftist journalist :-D

An additional, very important point. You can read that he attended a Catholic School. We can guess that if he had attended a Public School in Seine Sant Denis, with a majority of Left wing teachers and a 90% of muslim pupils, Mbappé would be now quite a different (worse) person, maybe he would be closer to Benzemá than to the person he is.

Saturday, 5 June 2021

Kill External Thread

Out of curiosity I was looking into how to kill a specific thread from outside the host process. For that I wrote a basic .Net 5 application creating a couple of threads. I create those Threads with the lowest level option available in .Net, the Thread class. The first interesting thing is that the this class has just a ManagedId property, that has nothing to do with the real OS level Thread ID, and indeed .Net does not provide a way to obtain that OS Thread ID. The explanation for this is here

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

This is a bit surprising to me. While Task.Run is clearly a high level mechanism (at this moment the code will run in a thread from the Thread Pool), using the Thread constructor and its Start method seemed to me like the Managed equivalent to the Windows API CreateThread function or to the Posix pthread_create in Linux. I've been doing some tests in .Net 5 both in Windows and Linux, and the Thread constructor seems to use a new OS thread, but well, not sure if after using a certain number of "new Thread(---).Start" calls it could begin to reuse previous threads.

In the old .Net 2-3-4 times... a simple Windows Console application in which you were not explicitly creating any threads (other than the main thread that runs the application) had indeed 3 threads: that main thread, a CLR thread and a Finalizer thread. When running a simple .Net 5 console application on Windows or Linux I can see many more threads (like 10 threads when started, and then, even while doing nothing, new threads show up and die...) I print the current threads from inside the application like this:


private static IEnumerable<string> GetThreadsIDs()
        {
            var processThreads = new List<ProcessThread>();
            foreach (ProcessThread pTh in Process.GetCurrentProcess().Threads){
                processThreads.Add(pTh);
            }
            return processThreads.Select(pTh => pTh.Id.ToString());
        }

Printing that threads list right before and right after calling into "new Thread(delegate)" you can "almost" identify the OS Thread ID of that new Thread. I say almost because indeed you'll see 2 or 3 new threads in the list, but if you wait and run some external command to get updated list of threads, you'll see how some threads come and go... but you'll also see that one of those new threads remains... so that seems to be the thread that corresponds to your "new Thread(delegate)".

To get the list of threads of a given process I use this command in linux (the Thread ID here is shown as "SPID", and other tools seem to call it "LWP"):
ps -T pid

and this one in Windows Powershell:
Get-Process -ID pid | Select-Object -ExpandProperty Threads | Select-Object ID

It's interesting to note that in Linux, the Thread ID of the first thread in one process is the same as the Process ID. My understanding is that each thread is represented by a task structure. For the first thread in the process the taskId and ProcessId fields in that task have the same value, then for the other tasks you'll have a new Thread ID, but the same Process ID. I'm talking about modern Threads implementations, NPTL ("Native posix thread library")

As we can kill a process given its process ID (kill -9, System Monitor, Task Manager...) how about using the Thread ID to kill a certain Thread?

Well, we can do that in Windows from the UI of Process Explorer or ProcessHacker, or from the command line by means again of Process Hacker, like this (I guess it's using the Windows API TerminateThread function):
ProcessHacker.exe -c -ctype thread -cobject threadId -caction terminate

In Linux I've read that you can send a signal (9 or 15 to kill it) to the target thread with the tgkill(threadId, signal) function, but have not found any utility doing that. I just found this, that is doing a syscall(SYS_tgkill, tgid, tid, sig);, but it's not working for me... So for the moment I have no way to kill a thread of another process in Linux.

Sunday, 23 May 2021

Prisons First!

I learnt yesterday from the regional TV news that the inmates in the Asturies regional prison were receiving the Covid19 vaccine, all of them, regardless of their age!!! Yes, I've said inmates, I mean, criminals (I say this in case you think I'm confusing prison workers with prison "inhabitants"). For normal people, the youngest group being vaccinated at this time in Asturies is the 50 to 59 years old group. So criminals are being favored over the rest of the population!!!

The explanation seems to be that due to the living conditions in prison, prisoners are more at risk to get the disease. OK, maybe it's true, but honestly, I don't give a shit. Justice system in Spain (as in all of Western Europe) is terribly soft with criminals, so in most occasions, when someone enters in prison it's because he has done something serious... OK, I admit that there are people in prison that just made a mistake for which they are paying too much (or directly, innocent people that have been wrongly sentenced)... but many of those in prison are real criminals: rapists, murderers, drug dealears, people involved in human trafficking... people that have destroyed other people's lives... and the government is giving precedence to those people over the normal population!

What disturbs me the most is that nobody seems to care. I have hardly seen any article revolting against this shameful situation... it's as if nobody gives a damn... Bearing in mind that in most cases rapists are getting their vaccine before the women that they raped, one could at least expect that the feminists would have something to say... but no, it seems as if the idea that "those in prison are victims of our evil society" has permeated everything.

Well, it could have been even worst. In France for example, where the far-left sickening hatred for our civilization has infected most of the so called "journalists" and 95% of judges... we can consider it as an achievement that nobody has proposed to vaccinate Muslims and Non-whites first, as a way to compensate for centuries of "European oppression, racism, slave trade and islamophobia...". Indeed, feminists could also have asked to vaccinate women first, again as a form of compensation. Yes, indeed, why should the white, heterosexual, European man, that evil creature that is responsible for all the injustices in the world, be vaccinated at all? Ah, yes, maybe because when the next pandemia arrives you'll need that white, heterosexual monster to help design the new vaccine...

Sunday, 16 May 2021

Vive le Congo!

J'ai appris récemment que les attaques djihadistes en Afrique se sont répandues bien au-delà du Sahel, la Somalie et la Nigeria. Ça qui m'a profondément surpris c'est qu'ils ont touché des pays que je n'associais pas avec l'Islam: Mozambique, RDC. Ces pays sont majoritairement cristians, mais malheurosament il y a une présence musulmane importante aussi (entre 2% et 10% en RDC, mais 18% en Mozambique... puff, ça fait peur...).. Même qu'a République Centro-africaine ou le Cameroun, l'Islam est concentré dans certaines areas du pays, mais il est aussi bien présent dans toutes les grandes villes.

Cette semaine une bagarre a éclaté entre 2 groupes musulmans rivaux pendant la cérémonie de clôture du ramadan à Kinshasa, RDC. La police a dû intervenir et un policier a été tu (et autres très gravement blesses)... Après ces faits déplorables, la justice est rapidement intervenue, et contrairement à ce qui se passe en Europa, la justice a fait JUSTICE, et 30 malfaiteurs ont été condamnes à mort! Bravo!

On peut rêver de voir la même JUSTICE appli en France. Voir la racaille qui attaque gratuitement, tue et viol a les "blancs", a les Asiatiques, aux Juifs (bref, aux non musulmans), être guillotiné en la Place de la République, la Place Bellecour, la Place du Capitole, la Place de la Bourse... Mais non, ici c'est le royaume des "droits de l'Homme"... C'est bien ça, le problème c'est quand on donne ces droits à des sous-hommes... Mais bon, on sait bien que dans le monde d'aujourd'hui, souhaiter justice est une aspiration de "facho".

Sunday, 9 May 2021

Playing with ixjs AsyncIterable

Some days ago I came across this beautiful library that by means of an ix.Iterable and ix.AsyncIterable classes sort of brings the functionality available for push streams in rxjs to pull streams (both synchronous and asynchronous iterables and generators). They talk about the "arrays extras" methods, but there are more. It's related to what I prototyped time ago here and here.

The usage pattern is based on rxjs, so once you have created an (ix)Iterable/AsyncIterable object from a generator/iterable, you use the pipe function to chain functions. This ends up creating a chain of objects (FiterIterable, MapIterable...) working in a lazy way. Once you've created the chain, nothing will happen until you start to iterate the resulting Iterable, and the functions in the chain are not executed for all the items at the same time when the iteration starts, but just one by one the moment you are retriving that specific element. Well, this should sound very familiar if you're used to working with Linq in the .Net world.

The samples in their web give you a basic introduction. For AsyncIterables, one of the most useful use case is related to what they explain in the Converting from Iterable to AsyncIterable section, but the sample there is too trivial to get the full idea I think. Imagine we have an array and we want to apply some mapping and filtering, but some of the iteratee functions (lodash/fp parlor, the function that we pass to map-filter) are asynchronous and others synchrous. For that you'll need the methods in the ix.AsyncIterable, that work both with async and sync functions. Let's see an example (given an array of cities, call and async api to get its countries, filter the non null results, and then convert to upper case)


import { from as asyncIterableFrom } from 'ix/asynciterable/index.js';
import { filter as asyncFilter, map as asyncMap } from 'ix/asynciterable/operators/index.js';

function asyncSleep(interval){
    return new Promise(resolveFn => setTimeout(resolveFn, interval));
}

async function findCountryForCityAsync(city){
    let countries = [
        {
            name: "France",
            mainCities: ["Toulouse", "Paris", "Lyon", "Marseille", "Bordeaux"]
        },
        {
            name: "Belgium",
            mainCities: ["Bruxelles", "Antwerp", "Liege"]
        }
    ];
    console.log("finding country for " + city);
    await asyncSleep(2000);
    let country = countries.find(country => country.mainCities.findIndex(_city => _city == city) > -1);
    return country ? country.name : null;
}

let cities = ["Toulouse", "Paris", "Ghent", "Bruxelles"];

let transformedCitiesIterable = asyncIterableFrom(cities).pipe(
    asyncMap(findCountryForCityAsync),
    asyncFilter(city => city !== null),
    asyncMap(x => x.toLocaleUpperCase())
);
console.log("transformedCitiesIterable type: " + transformedCitiesIterable.constructor.name);
//we have an objects chain like this:
// MapAsyncIterable -> FilterAsyncIterable -> MapAsyncIterable -> FromAsyncIterable

//async main
(async () => {
    console.log("starting asyncIterableTest");
    for await (let city of transformedCitiesIterable){
        console.log(city);
    }
    console.log("ending asyncIterableTest");
})();


I've uploaded it to a gist. The documentation for this nice library is mainly missing, but someone generated docs for it here

The .Net equivalent (more or less) to this library is System.Linq.Async, and you can find a good sample here.

Sunday, 2 May 2021

The German Doctor

I've recently watched a rather interesting Argentinian film, The German Doctor. It's a fictional story inspired by partially known real events, the months of exile spent in Bariloche, Argentina, by Nazi Doctor/Researcher/Psychopath, Josef Menguele

It's known that many Nazis found refuge in South America after WWII. One of the main routes to get there went through Spain (that in some cases was not just a stopover, but the final destination), which is not strange as Spain was under the dictatorship of Franco, that during the war had sympathised with Hitler (whatever hatred I feel for Franco and regardless of all the support he received from Germany and Italy during the Spanish Civil War, I have to admit that I don't think he was completely in line with Nazi ideology, though and important part of "his guys", the Falange scum mainly, were real Nazi admirers). What I was not so aware of is that the Argentinian president, Peron, was a nazi sympathizer, so while the large German community established in Argentine well before the War firmly helped the nazis to accomodate in the country, it was the Argentinian government itself who played the major role.

The film tells the story of how Mengele established for some months in Bariloche, helped by the local, pro-nazi, German community (and some "invisible hand" that seemed to fund him). There he continued his genetic "research", focused on a local family where the mother is pregnant with twins and the daugher is a teenager with serious growth problems. This family is fictional, and the stay of Menguele in Bariloche is not proved, but the shocking setting of the large pro-Nazi community with their German, "Nazi youth like" school, is quite realistic. By the way, it's amazing how Bariloche looked like and Alpine ville.

One can find a bit disturbing that for the most part Mengele is depicted as a rather kind, even charming, person, that at first seems pretty involved helping this family, even helping the father, that does not get on well with him since the beginning (indeed, this animosity makes the husband look like unfair). Well, from what I've watched in an old documentary, it's likely that Menguele was a bit like that. You can be a beast with those that you consider inferior, and a correct, kind person with the rest. The fact that Hitler loved his dogs is commonly used as an example.

There's a short but good interview with the writer-director, Lucía Puezo, here. She makes a smart reflection on how paradoxical it is that Nazis ended up finding refuge in such a Mestizo place as South America.

But I was especially interested in their obsession with genetics, with making the perfect race. It is almost a paradox that Mengele, so obsessed with racial purity, should end up in a continent (not only in Argentina – he spent a year in Paraguay and Brazil), where we all have mixed blood.