Integrity
Write
Loading...
Enrique Dans

Enrique Dans

1 year ago

You may not know about The Merge, yet it could change society

More on Technology

Shalitha Suranga

Shalitha Suranga

1 year ago

The Top 5 Mathematical Concepts Every Programmer Needs to Know

Using math to write efficient code in any language

Photo by Emile Perron on Unsplash, edited with Canva

Programmers design, build, test, and maintain software. Employ cases and personal preferences determine the programming languages we use throughout development. Mobile app developers use JavaScript or Dart. Some programmers design performance-first software in C/C++.

A generic source code includes language-specific grammar, pre-implemented function calls, mathematical operators, and control statements. Some mathematical principles assist us enhance our programming and problem-solving skills.

We all use basic mathematical concepts like formulas and relational operators (aka comparison operators) in programming in our daily lives. Beyond these mathematical syntaxes, we'll see discrete math topics. This narrative explains key math topics programmers must know. Master these ideas to produce clean and efficient software code.

Expressions in mathematics and built-in mathematical functions

A source code can only contain a mathematical algorithm or prebuilt API functions. We develop source code between these two ends. If you create code to fetch JSON data from a RESTful service, you'll invoke an HTTP client and won't conduct any math. If you write a function to compute the circle's area, you conduct the math there.

When your source code gets more mathematical, you'll need to use mathematical functions. Every programming language has a math module and syntactical operators. Good programmers always consider code readability, so we should learn to write readable mathematical expressions.

Linux utilizes clear math expressions.

A mathematical expression/formula in the Linux codebase, a screenshot by the author

Inbuilt max and min functions can minimize verbose if statements.

Reducing a verbose nested-if with the min function in Neutralinojs, a screenshot by the author

How can we compute the number of pages needed to display known data? In such instances, the ceil function is often utilized.

import math as m
results = 102
items_per_page = 10 
pages = m.ceil(results / items_per_page)
print(pages)

Learn to write clear, concise math expressions.

Combinatorics in Algorithm Design

Combinatorics theory counts, selects, and arranges numbers or objects. First, consider these programming-related questions. Four-digit PIN security? what options exist? What if the PIN has a prefix? How to locate all decimal number pairs?

Combinatorics questions. Software engineering jobs often require counting items. Combinatorics counts elements without counting them one by one or through other verbose approaches, therefore it enables us to offer minimum and efficient solutions to real-world situations. Combinatorics helps us make reliable decision tests without missing edge cases. Write a program to see if three inputs form a triangle. This is a question I commonly ask in software engineering interviews.

Graph theory is a subfield of combinatorics. Graph theory is used in computerized road maps and social media apps.

Logarithms and Geometry Understanding

Geometry studies shapes, angles, and sizes. Cartesian geometry involves representing geometric objects in multidimensional planes. Geometry is useful for programming. Cartesian geometry is useful for vector graphics, game development, and low-level computer graphics. We can simply work with 2D and 3D arrays as plane axes.

GetWindowRect is a Windows GUI SDK geometric object.

GetWindowRect outputs an LPRECT geometric object, a screenshot by the author

High-level GUI SDKs and libraries use geometric notions like coordinates, dimensions, and forms, therefore knowing geometry speeds up work with computer graphics APIs.

How does exponentiation's inverse function work? Logarithm is exponentiation's inverse function. Logarithm helps programmers find efficient algorithms and solve calculations. Writing efficient code involves finding algorithms with logarithmic temporal complexity. Programmers prefer binary search (O(log n)) over linear search (O(n)). Git source specifies O(log n):

The Git codebase defines a function with logarithmic time complexity, a screenshot by the author

Logarithms aid with programming math. Metas Watchman uses a logarithmic utility function to find the next power of two.

A utility function that uses ceil, a screenshot by the author

Employing Mathematical Data Structures

Programmers must know data structures to develop clean, efficient code. Stack, queue, and hashmap are computer science basics. Sets and graphs are discrete arithmetic data structures. Most computer languages include a set structure to hold distinct data entries. In most computer languages, graphs can be represented using neighboring lists or objects.

Using sets as deduped lists is powerful because set implementations allow iterators. Instead of a list (or array), store WebSocket connections in a set.

Most interviewers ask graph theory questions, yet current software engineers don't practice algorithms. Graph theory challenges become obligatory in IT firm interviews.

Recognizing Applications of Recursion

A function in programming isolates input(s) and output(s) (s). Programming functions may have originated from mathematical function theories. Programming and math functions are different but similar. Both function types accept input and return value.

Recursion involves calling the same function inside another function. In its implementation, you'll call the Fibonacci sequence. Recursion solves divide-and-conquer software engineering difficulties and avoids code repetition. I recently built the following recursive Dart code to render a Flutter multi-depth expanding list UI:

Recursion is not the natural linear way to solve problems, hence thinking recursively is difficult. Everything becomes clear when a mathematical function definition includes a base case and recursive call.

Conclusion

Every codebase uses arithmetic operators, relational operators, and expressions. To build mathematical expressions, we typically employ log, ceil, floor, min, max, etc. Combinatorics, geometry, data structures, and recursion help implement algorithms. Unless you operate in a pure mathematical domain, you may not use calculus, limits, and other complex math in daily programming (i.e., a game engine). These principles are fundamental for daily programming activities.

Master the above math fundamentals to build clean, efficient code.

Farhad Malik

Farhad Malik

1 year ago

How This Python Script Makes Me Money Every Day

Starting a passive income stream with data science and programming

My website is fresh. But how do I monetize it?

Creating a passive-income website is difficult. Advertise first. But what useful are ads without traffic?

Let’s Generate Traffic And Put Our Programming Skills To Use

SEO boosts traffic (Search Engine Optimisation). Traffic generation is complex. Keywords matter more than text, URL, photos, etc.

My Python skills helped here. I wanted to find relevant, Google-trending keywords (tags) for my topic.

First The Code

I wrote the script below here.

import re
from string import punctuation

import nltk
from nltk import TreebankWordTokenizer, sent_tokenize
from nltk.corpus import stopwords


class KeywordsGenerator:
    def __init__(self, pytrends):
        self._pytrends = pytrends

    def generate_tags(self, file_path, top_words=30):
        file_text = self._get_file_contents(file_path)
        clean_text = self._remove_noise(file_text)
        top_words = self._get_top_words(clean_text, top_words)
        suggestions = []
        for top_word in top_words:
            suggestions.extend(self.get_suggestions(top_word))
        suggestions.extend(top_words)
        tags = self._clean_tokens(suggestions)
        return ",".join(list(set(tags)))

    def _remove_noise(self, text):
        #1. Convert Text To Lowercase and remove numbers
        lower_case_text = str.lower(text)
        just_text = re.sub(r'\d+', '', lower_case_text)
        #2. Tokenise Paragraphs To words
        list = sent_tokenize(just_text)
        tokenizer = TreebankWordTokenizer()
        tokens = tokenizer.tokenize(just_text)
        #3. Clean text
        clean = self._clean_tokens(tokens)
        return clean

    def _clean_tokens(self, tokens):
        clean_words = [w for w in tokens if w not in punctuation]
        stopwords_to_remove = stopwords.words('english')
        clean = [w for w in clean_words if w not in stopwords_to_remove and not w.isnumeric()]
        return clean

    def get_suggestions(self, keyword):
        print(f'Searching pytrends for {keyword}')
        result = []
        self._pytrends.build_payload([keyword], cat=0, timeframe='today 12-m')
        data = self._pytrends.related_queries()[keyword]['top']
        if data is None or data.values is None:
            return result
        result.extend([x[0] for x in data.values.tolist()][:2])
        return result

    def _get_file_contents(self, file_path):
        return open(file_path, "r", encoding='utf-8',errors='ignore').read()

    def _get_top_words(self, words, top):
        counts = dict()

        for word in words:
            if word in counts:
                counts[word] += 1
            else:
                counts[word] = 1

        return list({k: v for k, v in sorted(counts.items(), key=lambda item: item[1])}.keys())[:top]


if __name__ == "1__main__":
    from pytrends.request import TrendReq

    nltk.download('punkt')
    nltk.download('stopwords')
    pytrends = TrendReq(hl='en-GB', tz=360)
    tags = KeywordsGenerator(pytrends)\
              .generate_tags('text_file.txt')
    print(tags)

Then The Dependencies

This script requires:

nltk==3.7
pytrends==4.8.0

Analysis of the Script

I copy and paste my article into text file.txt, and the code returns the keywords as a comma-separated string.

To achieve this:

  1. A class I made is called KeywordsGenerator.

  2. This class has a function: generate_tags

  3. The function generate_tags performs the following tasks:

  • retrieves text file contents

  • uses NLP to clean the text by tokenizing sentences into words, removing punctuation, and other elements.

  • identifies the most frequent words that are relevant.

  • The pytrends API is then used to retrieve related phrases that are trending for each word from Google.

  • finally adds a comma to the end of the word list.

4. I then use the keywords and paste them into the SEO area of my website.

These terms are trending on Google and relevant to my topic. My site's rankings and traffic have improved since I added new keywords. This little script puts our knowledge to work. I shared the script in case anyone faces similar issues.

I hope it helps readers sell their work.

Waleed Rikab, PhD

Waleed Rikab, PhD

1 year ago

The Enablement of Fraud and Misinformation by Generative AI What You Should Understand

Recent investigations have shown that generative AI can boost hackers and misinformation spreaders.

Generated through Stable Diffusion with a prompt by the author

Since its inception in late November 2022, OpenAI's ChatGPT has entertained and assisted many online users in writing, coding, task automation, and linguistic translation. Given this versatility, it is maybe unsurprising but nonetheless regrettable that fraudsters and mis-, dis-, and malinformation (MDM) spreaders are also considering ChatGPT and related AI models to streamline and improve their operations.

Malign actors may benefit from ChatGPT, according to a WithSecure research. ChatGPT promises to elevate unlawful operations across many attack channels. ChatGPT can automate spear phishing attacks that deceive corporate victims into reading emails from trusted parties. Malware, extortion, and illicit fund transfers can result from such access.

ChatGPT's ability to simulate a desired writing style makes spear phishing emails look more genuine, especially for international actors who don't speak English (or other languages like Spanish and French).

This technique could let Russian, North Korean, and Iranian state-backed hackers conduct more convincing social engineering and election intervention in the US. ChatGPT can also create several campaigns and various phony online personas to promote them, making such attacks successful through volume or variation. Additionally, image-generating AI algorithms and other developing techniques can help these efforts deceive potential victims.

Hackers are discussing using ChatGPT to install malware and steal data, according to a Check Point research. Though ChatGPT's scripts are well-known in the cyber security business, they can assist amateur actors with little technical understanding into the field and possibly develop their hacking and social engineering skills through repeated use.

Additionally, ChatGPT's hacking suggestions may change. As a writer recently indicated, ChatGPT's ability to blend textual and code-based writing might be a game-changer, allowing the injection of innocent content that would subsequently turn out to be a malicious script into targeted systems. These new AI-powered writing- and code-generation abilities allow for unique cyber attacks, regardless of viability.

OpenAI fears ChatGPT usage. OpenAI, Georgetown University's Center for Security and Emerging Technology, and Stanford's Internet Observatory wrote a paper on how AI language models could enhance nation state-backed influence operations. As a last resort, the authors consider polluting the internet with radioactive or misleading data to ensure that AI language models produce outputs that other language models can identify as AI-generated. However, the authors of this paper seem unaware that their "solution" might cause much worse MDM difficulties.

Literally False News

The public argument about ChatGPTs content-generation has focused on originality, bias, and academic honesty, but broader global issues are at stake. ChatGPT can influence public opinion, troll individuals, and interfere in local and national elections by creating and automating enormous amounts of social media material for specified audiences.

ChatGPT's capacity to generate textual and code output is crucial. ChatGPT can write Python scripts for social media bots and give diverse content for repeated posts. The tool's sophistication makes it irrelevant to one's language skills, especially English, when writing MDM propaganda.

I ordered ChatGPT to write a news piece in the style of big US publications declaring that Ukraine is on the verge of defeat in its fight against Russia due to corruption, desertion, and exhaustion in its army. I also gave it a fake reporter's byline and an unidentified NATO source's remark. The outcome appears convincing:

Worse, terrible performers can modify this piece to make it more credible. They can edit the general's name or add facts about current wars. Furthermore, such actors can create many versions of this report in different forms and distribute them separately, boosting its impact.

In this example, ChatGPT produced a news story regarding (fictional) greater moviegoer fatality rates:

Editing this example makes it more plausible. Dr. Jane Smith, the putative author of the medical report, might be replaced with a real-life medical person or a real victim of this supposed medical hazard.

Can deceptive texts be found? Detecting AI text is behind AI advancements. Minor AI-generated text alterations can upset these technologies.

Some OpenAI individuals have proposed covert methods to watermark AI-generated literature to prevent its abuse. AI models would create information that appears normal to humans but would follow a cryptographic formula that would warn other machines that it was AI-made. However, security experts are cautious since manually altering the content interrupts machine and human detection of AI-generated material.

How to Prepare

Cyber security and IT workers can research and use generative AI models to fight spear fishing and extortion. Governments may also launch MDM-defence projects.

In election cycles and global crises, regular people may be the most vulnerable to AI-produced deceit. Until regulation or subsequent technical advances, individuals must recognize exposure to AI-generated fraud, dating scams, other MDM activities.

A three-step verification method of new material in suspicious emails or social media posts can help identify AI content and manipulation. This three-step approach asks about the information's distribution platform (is it reliable? ), author (is the reader familiar with them? ), and plausibility given one's prior knowledge of the topic.

Consider a report by a trusted journalist that makes shocking statements in their typical manner. AI-powered fake news may be released on an unexpected platform, such as a newly created Facebook profile. However, if it links to a known media source, it is more likely to be real.

Though hard and subjective, this verification method may be the only barrier against manipulation for now.

AI language models:

How to Recognize an AI-Generated Article ChatGPT, the popular AI-powered chatbot, can and likely does generate medium.com-style articles.

AI-Generated Text Detectors Fail. Do This. Online tools claim to detect ChatGPT output. Even with superior programming, I tested some of these tools. pub

Why Original Writers Matter Despite AI Language Models Creative writers may never be threatened by AI language models.

You might also like

Andy Walker

Andy Walker

1 year ago

Why personal ambition and poor leadership caused Google layoffs

Google announced 6% layoffs recently (or 12,000 people). This aligns it with most tech companies. A publicly contrite CEO explained that they had overhired during the COVID-19 pandemic boom and had to address it, but they were sorry and took full responsibility. I thought this was "bullshit" too. Meta, Amazon, Microsoft, and others must feel similarly. I spent 10 years at Google, and these things don't reflect well on the company's leaders.

All publicly listed companies have a fiduciary duty to act in the best interests of their shareholders. Dodge vs. Ford Motor Company established this (1919). Henry Ford wanted to reduce shareholder payments to offer cheaper cars and better wages. Ford stated.

My ambition is to employ still more men, to spread the benefits of this industrial system to the greatest possible number, to help them build up their lives and their homes. To do this we are putting the greatest share of our profits back in the business.

The Dodge brothers, who owned 10% of Ford, opposed this and sued Ford for the payments to start their own company. They won, preventing Ford from raising prices or salaries. If you have a vocal group of shareholders with the resources to sue you, you must prove you are acting in their best interests. Companies prioritize shareholders. Giving activist investors a stick to threaten you almost enshrines short-term profit over long-term thinking.

This underpins Google's current issues. Institutional investors who can sue Google see it as a wasteful company they can exploit. That doesn't mean you have to maximize profits (thanks to those who pointed out my ignorance of US corporate law in the comments and on HN), but it allows pressure. I feel for those navigating this. This is about unrestrained capitalism.

When Google went public, Larry Page and Sergey Brin knew the risks and worked hard to keep control. In their Founders' Letter to investors, they tried to set expectations for the company's operations.

Our long-term focus as a private company has paid off. Public companies do the same. We believe outside pressures lead companies to sacrifice long-term opportunities to meet quarterly market expectations.

The company has transformed since that letter. The company has nearly 200,000 full-time employees and a trillion-dollar market cap. Large investors have bought company stock because it has been a good long-term bet. Why are they restless now?

Other big tech companies emerged and fought for top talent. This has caused rising compensation packages. Google has also grown rapidly (roughly 22,000 people hired to the end of 2022). At $300,000 median compensation, those 22,000 people added $6.6 billion in salary overheads in 2022. Exorbitant. If the company still makes $16 billion every quarter, maybe not. Investors wonder if this value has returned.

Investors are right. Google uses people wastefully. However, by bluntly reducing headcount, they're not addressing the root causes and hurting themselves. No studies show that downsizing this way boosts productivity. There is plenty of evidence that they'll lose out because people will be risk-averse and distrust their leadership.

The company's approach also stinks. Finding out that you no longer have a job because you can’t log in anymore (sometimes in cases where someone is on call for protecting your production systems) is no way to fire anyone. Being with a narcissistic sociopath is like being abused. First, you receive praise and fancy perks for making the cut. You're fired by text and ghosted. You're told to appreciate the generous severance package. This firing will devastate managers and teams. This type of firing will take years to recover self-esteem. Senior management contributed to this. They chose the expedient answer, possibly by convincing themselves they were managing risk and taking the Macbeth approach of “If it were done when ’tis done, then ’twere well It were done quickly”.

Recap. Google's leadership did a stupid thing—mass firing—in a stupid way. How do we get rid of enough people to make investors happier? and "have 6% less people." Empathetic leaders should not emulate Elon Musk. There is no humane way to fire 12,000 people, but there are better ways. Why is Google so wasteful?

Ambition answers this. There aren't enough VP positions for a group of highly motivated, ambitious, and (increasingly) ruthless people. I’ve loitered around the edges of this world and a large part of my value was to insulate my teams from ever having to experience it. It’s like Game of Thrones played out through email and calendar and over video call.

Your company must look a certain way to be promoted to director or higher. You need the right people at the right levels under you. Long-term, growing your people will naturally happen if you're working on important things. This takes time, and you're never more than 6–18 months from a reorg that could start you over. Ambitious people also tend to be impatient. So, what do you do?

Hiring and vanity projects. To shape your company, you hire at the right levels. You value vanity metrics like active users over product utility. Your promo candidates get through by subverting the promotion process. In your quest for growth, you avoid performance managing people out. You avoid confronting toxic peers because you need their support for promotion. Your cargo cult gets you there.

Its ease makes Google wasteful. Since they don't face market forces, the employees don't see it as a business. Why would you do when the ads business is so profitable? Complacency causes senior leaders to prioritize their own interests. Empires collapse. Personal ambition often trumped doing the right thing for users, the business, or employees. Leadership's ambition over business is the root cause. Vanity metrics, mass hiring, and vague promises have promoted people to VP. Google goes above and beyond to protect senior leaders.

The decision-makers and beneficiaries are not the layoffees. Stock price increase beneficiaries. The people who will post on LinkedIn how it is about misjudging the market and how they’re so sorry and take full responsibility. While accumulating wealth, the dark room dwellers decide who stays and who goes. The billionaire investors. Google should start by addressing its bloated senior management, but — as they say — turkeys don't vote for Christmas. It should examine its wastefulness and make tough choices to fix it. A 6% cut is a blunt tool that admits you're not running your business properly. why aren’t the people running the business the ones shortly to be entering the job market?

This won't fix Google's wastefulness. The executives may never regain trust after their approach. Suppressed creativity. Business won't improve. Google will have lost its founding vision and us all. Large investors know they can force Google's CEO to yield. The rich will get richer and rationalize leaving 12,000 people behind. Cycles repeat.

It doesn’t have to be this way. In 2013, Nintendo's CEO said he wouldn't fire anyone for shareholders. Switch debuted in 2017. Nintendo's stock has increased by nearly five times, or 19% a year (including the drop most of the stock market experienced last year). Google wasted 12,000 talented people. To please rich people.

Edward Williams

Edward Williams

1 year ago

I currently manage 4 profitable online companies. I find all the generic advice and garbage courses very frustrating. The only advice you need is this.

A man playing chess.

This is for young entrepreneurs, especially in tech.

People give useless success advice on TikTok and Reddit. Early risers, bookworms, etc. Entrepreneurship courses. Work hard and hustle.

False. These aren't successful traits.

I mean, organization is good. As someone who founded several businesses and now works at a VC firm, I find these tips to be clichés.

Based on founding four successful businesses and working with other successful firms, here's my best actionable advice:

1. Choose a sector or a niche and become an expert in it.

This is more generic than my next tip, but it's a must-do that's often overlooked. Become an expert in the industry or niche you want to enter. Discover everything.

Buy (future) competitors' products. Understand consumers' pain points. Market-test. Target keyword combos. Learn technical details.

The most successful businesses I've worked with were all formed by 9-5 employees. They knew the industry's pain points. They started a business targeting these pain points.

2. Choose a niche or industry crossroads to target.

How do you choose an industry or niche? What if your industry is too competitive?

List your skills and hobbies. Randomness is fine. Find an intersection between two interests or skills.

Say you build websites well. You like cars.

Web design is a *very* competitive industry. Cars and web design?

Instead of web design, target car dealers and mechanics. Build a few fake demo auto mechanic websites, then cold call shops with poor websites. Verticalize.

I've noticed a pattern:

  • Person works in a particular industry for a corporation.

  • Person gains expertise in the relevant industry.

  • Person quits their job and launches a small business to address a problem that their former employer was unwilling to address.

I originally posted this on Reddit and it seemed to have taken off so I decided to share it with you all.

Focus on the product. When someone buys from you, you convince them the product's value exceeds the price. It's not fair and favors the buyer.

Creating a superior product or service will win. Narrowing this helps you outcompete others.

You may be their only (lucky) option.

Eitan Levy

Eitan Levy

1 year ago

The Top 8 Growth Hacking Techniques for Startups

The Top 8 Growth Hacking Techniques for Startups

These startups, and how they used growth-hack marketing to flourish, are some of the more ethical ones, while others are less so.

Before the 1970 World Cup began, Puma paid footballer Pele $120,000 to tie his shoes. The cameras naturally focused on Pele and his Pumas, causing people to realize that Puma was the top football brand in the world.

Early workers of Uber canceled over 5,000 taxi orders made on competing applications in an effort to financially hurt any of their rivals.

PayPal developed a bot that advertised cheap goods on eBay, purchased them, and paid for them with PayPal, fooling eBay into believing that customers preferred this payment option. Naturally, Paypal became eBay's primary method of payment.

Anyone renting a space on Craigslist had their emails collected by AirBnB, who then urged them to use their service instead. A one-click interface was also created to list immediately on AirBnB from Craigslist.

To entice potential single people looking for love, Tinder developed hundreds of bogus accounts of attractive people. Additionally, for at least a year, users were "accidentally" linked.

Reddit initially created a huge number of phony accounts and forced them all to communicate with one another. It eventually attracted actual users—the real meaning of "fake it 'til you make it"! Additionally, this gave Reddit control over the tone of voice they wanted for their site, which is still present today.

To disrupt the conferences of their main rival, Salesforce recruited fictitious protestors. The founder then took over all of the event's taxis and gave a 45-minute pitch for his startup. No place to hide!

When a wholesaler required a minimum purchase of 10, Amazon CEO Jeff Bezos wanted a way to purchase only one book from them. A wholesaler would deliver the one book he ordered along with an apology for the other eight books after he discovered a loophole and bought the one book before ordering nine books about lichens. On Amazon, he increased this across all of the users.


Original post available here