Posts by @intersex (218)


My name is Jasper Camber Holton. I write, code, make music, and I am the developer of Uglek.com.

π

This user is an administrator.

Has 218 posts, follows 15 users and is followed by 9 users.

Last seen at November 27, 2021 09:24

Premium Member
@intersexs profile photo

How Uglek's Message Client Frontend Works Uglek has a new message client, with a dynamic layout that is fast and responsive. The frontend is fairly simple, it consists of HTTP requests to get information and render it to the screen. It is coupled with a backend that allows the user to send messages, checks the messages for spam, and sends the user a push notification. I will update with instructions for the push notifications another day. This is the javascript code for the frontend. I have added comments describing what each part of the code does. You can see this code in action at uglek.com/message/ by messaging a user on their profile, like uglek.com/user/intersex/, or replying to one of your messages. The internal URLs are URLs under uglek.com and are used for displaying the message sidebar, incoming messages, and page links, as well as message counts respectively.

// This part of the code reloads the sidebar to show last users in the users following who are active 
// along with how many new messages from each user have been received. 
if(document.getElementById("message-sidebar")){ // If the sidebar exists (the part we are reloading)
        var sidebar = document.getElementById("message-sidebar"); // Get the sidebar
        function reloadSidebar(){ // A function to reload it
                const Http = new XMLHttpRequest(); // Use an XML request
                const url="(internal URL, the sidebar to reload)";
                Http.responseType = 'text';
                Http.onload = function() { // When the request loads
                        if(Http.readyState === Http.DONE){ // If it is done (200)
                                sidebar.innerHTML = Http.responseText; // Set the inner HTML of the sidebar
                        }
                };
                Http.open("GET", url, true);
                Http.send(null);
        }
        var interval = setInterval(function() { // Run this every 15 seconds
                reloadSidebar();
        }, 15000);
}

if(document.getElementById("user-messages")){ // If we are on the message user screen
        var msgs = document.getElementById("user-messages"); // Get the users messages
        function reloadMessages(){ // A function to reload the messages 
                const Http = new XMLHttpRequest();
                const url="(internal URL, raw messages by user)" + document.getElementById("user-username") + "/" // With the user username (rendered to the template)
                Http.responseType = 'text';
                Http.onload = function() {
                        if(Http.readyState === Http.DONE){
                                msgs.innerHTML = Http.responseText; // Update the messages
                        }
                };
                Http.open("GET", url, true);
                Http.send(null);
        }
        const urlParams = new URLSearchParams(window.location.search); // Get URL parameters
        var count = 0; // Save message count
        var lastcount = 0
        var firstLoad = true;
        if(urlParams.get('page') == '1' || !urlParams.get('page')){
                const Http = new XMLHttpRequest();
                 // With the users username
                const url="(internal URL, number of messages sent by each user)" + document.getElementById("user-username") + "/";
                Http.responseType = 'text';
                Http.open("GET", url, true);
                Http.onload = function() {
                        if(Http.readyState === Http.DONE){
                                count = parseInt(Http.responseText);
                                if(count != lastcount && !firstLoad){ // If there are new or deleted messages and this isn't the first page load
                                        reloadMessages(); // Reload the messages
                                }
                                firstLoad = false;
                                lastcount = count;
                        }
                };
                var interval = setInterval(function() {
                        Http.open("GET", url, true);
                        Http.send(null);
                }, 5000); // Reload messages every five seconds
                Http.send(null);
        }
}
This is all the JavaScript code it takes to build a messaging frontend for a website. The code simply needs to update the users' incoming messages and message counts, along with information about followers the user is messaging (their last seen, profile picture, and message count). The messaging is nearly instant, with an average delay of 2.5 seconds, and image uploads are supported.


@intersexs profile photo

I've made some updates to the chat You can now read live messages from other people on the site. The latency is pretty fast, which means it's nice to use. The page updates every time you send a message or get a new message, as long as you're on the first page. Try it out by messaging someone, the link is on the profile. You can see users by going to uglek.com/users/ or message me at uglek.com/message/intersex/. You can also message your follower by visiting uglek.com/followers/.

View the photo from a post by @intersex

@intersexs profile photo

New Viruses and Antibiotic-Resistant Bacteria May be Released from Thawing Permafrost Thawing permafrost is a major concern across many parts of the northern and southern hemispheres. Towards the poles, ice formed in the ground from the last ice age, called permafrost, melts and causes infrastructure problems. Roadways may need repair, structures can sink into the melting permafrost, and now new evidence shows that viruses and bacteria may be released from melting permafrost. Thawing permafrost could introduce new viruses to society, and pose health risks. The research, published in Nature Climate Change, also showed that now-banned pollutants and even radioactive waste from Cold War nuclear reactors and submarines could be released from the permafrost. Permafrost is permanently frozen land, but it's not so permanent anymore. Covering about 23 million square kilometers of the northern hemisphere. The permafrost is up to a million years old, and the older permafrost is deeper. Nearly a third of this near-surface permafrost could be lost by 2100. Beyond this, thawing permafrost releases greenhouse gasses. There are also by-products of fossil fuels in permafrost, introduced at the beginning of the industrial revolution. The artic contains natural metal deposits, which have been mined and caused widespread contamination from mining waste. The research describes deep permafrost, at a depth of three meters or more. This microbial environment in this permafrost hasn't been exposed to modern antibiotics, and there are more than 100 microorganisms that have been found to be resistant to antibiotics in Siberias permafrost alone. Melting permafrost increases water flow, so contamination from permafrost is likely to spread through moving water. This can damage native species as well as lead to contaminated material from permafrost entering the human food chain. More than 1000 settlements have been built on permafrost in the last 70 years, for all sorts of purposes. Despite these findings, the risks of melting permafrost aren't well understood yet. Further research needs to be done in order to better understand the nature of permafrost.

View the photo from a post by @intersex

@intersexs profile photo

I added django-allauth to the site, so now you will be able to log in using your social account if you like. To use the feature, go to the login or register page and select a button from the list to log in with Google, Facebook, Twitter, or Github. Invite your friends to make an account and challenge them to a game, it's really easy to do now!


@intersexs profile photo

Packrafts on Lake 22 in Washington Over the summer I had some awesome adventures with @AussieinthePNW hiking, camping and packrafting at alpine lakes in Washington. Lake 22 was beautiful in the summer, we had a sunny hike and a nice paddle in the lake.

View the photo from a post by @intersex

@intersexs profile photo

Tag-Preserving Translation Template Block Filter This is a block translation template filter, for translating a block of text into any language from English on a Django website. You can use this filter to translate an entire page of text using Python.

 # templatetags/app_filters.py
from django.template.base import Node # Imports
from googletrans import Translator
from langdetect import detect
from django.contrib import messages

translator = Translator() # Initialize translator and template library
register = template.Library()

def translatevalue(lang, input): # A method to translate HTML while preserving styles
    values = input.splitlines() # Split the html
    output = '' # Init outputs
    translations = list()
    strippedvalues = list()
    for value in values: # For each value
        stripped = ''
        try: # Try to strip the tags
            tagsplit = value.split('>', 1);
            otag = tagsplit[0] + '>'
            ctag = '<' + tagsplit[1].split('<', 1)[1]
            stripped = tagsplit[1].split('<', 1)[0]
            if(len(stripped) > 0): # If they contain something
                translations.append(translator.translate(stripped, dest=lang, src='en').text) # Translate that
            else:
                translations.append("") # Or store no translation
            strippedvalues.append(stripped) # Saved the stripped value
        except:
            translations.append("") # Fallback
            strippedvalues.append(stripped)
    for x in range(len(values)): # Build the translated text
        output = output + values[x].replace(strippedvalues[x], translations[x]) + '\n'
    return output # Return it

# The tag
@register.tag
def blocktranslate(parser, token):
    nodelist = parser.parse(('endblocktranslate',))
    parser.delete_first_token()
    return TranslateNode(nodelist)

# The node
class TranslateNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist
    def render(self, context): 
        input = self.nodelist.render(context) # Get the HTML
        lang = context['request'].LANGUAGE_CODE # Get the language code and querystring
        if(context['request'].GET.get('lang', '') != ''):
            lang = context['request'].GET.get('lang', '')
        if lang == None:
            lang = 'en'
        translation = ''
        if not lang == 'en':
            translation = translatevalue(lang, input) # Translate if the user language isn't english
        if translation != '': 
            return translation # Return the translation
        return input
This template tag looks like {% blocktranslate %}Some text here{% endblocktranslate %}. I use it to translate whole pages, like the TOS and Privacy. It's much quicker to implement than using the single-line template filter.


@intersexs profile photo

Universal Language Translation Django Template Tags This is a Django template tag for universal translation, that is, translation from any language to the clients' language. It uses locale middleware to work and otherwise consists of app filters that translate the text as needed. The code is commented in order to describe what each piece does. The first part is the settings, where we need to add locale middleware so we can get the request.LANGUAGE_CODE.

# settings.py
MIDDLEWARE = [
    '...',
    'django.middleware.locale.LocaleMiddleware' # Add this to the end
]
And the template tags, as well as a filter.
# templatetags/app_filters.py
from django import template # Imports
from googletrans import Translator
from langdetect import detect # Detect language
register = template.Library() # Initialize template library and translator
translator = Translator()

@register.simple_tag(takes_context=True) # Pass context so we can get the language code
def etranslate(context, value): # Translate from english
    request = context['request'] # Get request context
    lang = request.LANGUAGE_CODE # Get language code
    if(request.GET.get('lang', '') != ''): # Override with URL parameter if there is one
        lang = request.GET.get('lang', '')
    if lang == None: # Fallback for none
        lang = 'en'
    translation = None # Init translation
    if not lang == 'en': # Translate only if language isn't english
        try:
            translation = translator.translate(value, dest=lang, src='auto').text # Auto translate
        except:
            translation = None # No translation on error
    if translation != None:
        return translation # Return translation
    return value # Return untranslated text on error

@register.simple_tag(takes_context=True)
def translate(context, value): # Translate from any language
    request = context['request']
    lang = request.LANGUAGE_CODE
    if(request.GET.get('lang', '') != ''):
        lang = request.GET.get('lang', '')
    if lang == None:
        lang = 'en'
    translation = None
    if not value == '' and not detect(value) == lang: # If the text isn't already in the users language
        try:
            translation = translator.translate(value, dest=lang, src='auto').text
        except:
            translation = None
    if translation != None:
        return translation
    return value

@register.filter(name='detectlanguage') 
def detectlanguage(value): # Detect the language
    return detect(value) # Return value (en, es, de, etc)
In action, the tag looks like {% etranslate 'Text here' %}. For an English client, this isn't translated by the site and just shows in English. For anyone else, the text is translated to their language (or at least an attempt is made). For non-English translations, such as a post that could be in German or Dutch, use {% translate 'Text here' %} for universal translation from any language to the browser language or language passed by a URL parameter lang. Also, I use the template filter detectlanguage with text on the site, {{ post.content|detectlanguage }} to display the language of posts next to them.


@intersexs profile photo

I wrote code to translate this website from any language, people see contributions in their language.


@intersex, likes this, one comment.

intersex's profile photo

Uglek also now displays the language of posts.

© Uglek, 2021

Terms of Use and Privacy Policy