Categories
Development

Five ways to benchmark your Python code

1. timeit module

timeit module: This is a built-in Python module that provides a simple way to measure the execution time of small bits of Python code. You can use the timeit.timeit() function to time the execution of a single line of code or multiple lines wrapped in a function.

For example:

import timeit

def some_function():
    # code to be timed
    x = [i**2 for i in range(10000)]

print("Time taken by the function:", timeit.timeit(some_function, number=1000), "seconds")

Sure, here’s a simple example that demonstrates how to use the timeit module to measure the execution time of a piece of code:

python
Copy code
import timeit

def some_function():
# code to be timed
x = [i**2 for i in range(10000)]

print(“Time taken by the function:”, timeit.timeit(some_function, number=1000), “seconds”)
In this example, the timeit.timeit() function is used to measure the execution time of the some_function function. The number parameter is used to specify how many times the function should be run. In this case, it’s set to 1000, so the function will be executed 1000 times and the average time will be returned. The output of the code will look like this:

Time taken by the function: 0.17904642399999998 seconds

You can also use timeit to time a single line of code. For example:

import timeit

print("Time taken by the code:", timeit.timeit('x = [i**2 for i in range(10000)]', number=1000), "seconds")

In this case, the timeit.timeit() function is used to measure the execution time of a single line of code. The number parameter is used to specify how many times the code should be run, and the output will be the average time taken to execute the code.

cProfile module: This is a built-in Python module that provides detailed profiling information about your code, including the time spent in each function and how many times each function was called. You can run this module from the command line to profile your code, or you can use it as a library in your code.

2. cprofile module

This is another built-in Python module that provides detailed profiling information about your code, including the time spent in each function and how many times each function was called. You can run this module from the command line to profile your code, or you can use it as a library in your code.

For example;

import cProfile

def some_function():
    # code to be profiled
    x = [i**2 for i in range(10000)]

cProfile.run("some_function()")

In this example, the cProfile.run() function is used to profile the some_function function. The output of the code will look something like this:

         4 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 profile_example.py:3(some_function)
        1    0.000    0.000    0.000    0.000 profile_example.py:4(<listcomp>)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}

The output shows the number of calls to each function, the total time spent in each function, and the cumulative time spent in each function and its subfunctions. This information can be used to identify performance bottlenecks and optimize your code.

Note that cProfile generates a lot of output, so it’s best to run it on a small piece of code first, and then scale up as needed.

3. line_profiler

This is a third-party package that provides line-by-line profiling information for your code. It can be used to find which lines of your code are taking the most time, and to optimize your code accordingly.

First, you need to install line_profiler using pip (pip install line_profiler) and then, you can use the line_profiler decorator to profile a function. For example:


from line_profiler import LineProfiler

def some_function():
    # code to be profiled
    x = [i**2 for i in range(10000)]

lp = LineProfiler()
lp_wrapper = lp(some_function)
lp_wrapper()
lp.print_stats(

In this example, the LineProfiler class is used to profile the some_function function. The lp_wrapper function is created by passing some_function to the lp instance, and the lp_wrapper function is then executed. Finally, the lp.print_stats() function is used to print the results of the profiling. The output will look something like this:

Timer unit: 1e-06 s

File: <ipython-input-7-1a39a0d7dc68>
Function: some_function at line 5

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     5                                           def some_function():
     6                                               # code to be profiled
     7       1000      278032     278.0     97.3      x = [i**2 for i in range(10000)]

The output shows the number of hits (executions) for each line of code, the total time spent on each line, and the percentage of time spent on each line. This information can be used to identify performance bottlenecks and optimize your code.

4. perf

This is a Linux tool. With perf, you can profile the entire code execution, measure the time taken by individual functions, and determine which functions are taking the most time.

An example:

First, you need to install the Linux perf tool. On Ubuntu, you can do this with:
> sudo apt-get install linux-tools-common

Next, you need to run your Python script with the perf tool, for example:
> perf record -g -F 99 python your_script.py

Finally, you can generate a report of the profile results:
> perf report

In this example, the perf tool is used to profile the your_script.py script. The perf record command is used to start profiling, and the -g option is used to generate call graph information. The -F 99 option is used to specify the sampling frequency (99 Hertz). The perf report command is then used to generate a report of the profile results. The report will show you information such as the function call tree, the number of samples, and the total time spent in each function.

Note that the perf tool is a Linux-specific tool, and is not available on other operating systems. Also, it requires administrative privileges to run.

5. memory_profiler

This is another third-party package that provides detailed information about the memory usage of your code. It can be used to identify memory leaks, monitor memory usage over time, and optimize memory usage in your code.

First, you need to install memory_profiler using “pip install memory_profiler”. Then, you can use the @profile decorator to profile a function. For example:

from memory_profiler import profile

@profile
def some_function():
    # code to be profiled
    x = [i**2 for i in range(10000)]

some_function()

In this example, the @profile decorator is used to profile the some_function function. The some_function function is then executed, and the memory usage of the function is recorded. Finally, the results of the profiling are printed to the console. The output will look something like this:

Line #    Mem usage    Increment   Line Contents
================================================
     4   18.967 MB    0.000 MB   @profile
     5                             def some_function():
     6   18.967 MB    0.000 MB       x = [i**2 for i in range(10000)]

The output shows the memory usage of each line of code, and the incremental change in memory usage between lines. This information can be used to identify memory leaks and optimize your code.

That’s it we hope that this article was helpful. Let us know if you know any other method to benchmark Python code!

Categories
Security

Three tools to detect if your Python 3 project has vulnerabilities

1. PyUp Safety

PyUp Safety is a tool that helps you identify and fix security vulnerabilities in your Python dependencies. It integrates with your development process, and runs continuously in the background to notify you of new vulnerabilities in your dependencies. You can also run manual scans of your code and dependencies to get a comprehensive report of all known vulnerabilities.

Here’s how PyUp Safety works:

  1. Scanning: PyUp Safety scans your dependencies and compares them against a database of known vulnerabilities. This database is constantly updated, so you always have the latest information about vulnerabilities in your dependencies.
  2. Notifications: Whenever PyUp Safety finds a vulnerability in one of your dependencies, it sends you a notification with information about the vulnerability and how to fix it.
  3. Remediation: PyUp Safety provides detailed information and guidance on how to fix each vulnerability, including recommended upgrades and patches. You can also use PyUp Safety to automate the process of upgrading your dependencies to the latest secure version.

PyUp Safety also offers additional features such as a dashboard that provides an overview of your project’s security status, and the ability to customize your notifications and remediation process to fit your specific needs.

Overall, PyUp Safety is a useful tool for anyone who is concerned about the security of their Python dependencies and wants to stay on top of any vulnerabilities.

2. Bandit

Bandit is a security-focused source code analysis tool for Python. It performs a variety of tests on your code to identify potential security vulnerabilities, including checks for issues like cross-site scripting, SQL injection, and other types of security flaws.

Bandit does the following.

  1. Analysis: Bandit analyzes your Python code and performs a series of tests to identify potential security vulnerabilities. It can be run as part of your development process or as a standalone tool.
  2. Reporting: Bandit provides detailed information about any vulnerabilities it finds in your code, including a description of the vulnerability, the severity of the issue, and the line of code where the vulnerability was detected. This information can be used to prioritize remediation efforts and track progress.
  3. Customization: Bandit provides a flexible and customizable architecture, allowing you to define your own security tests and customize the reporting format to suit your needs.

Bandit is a great tool for developers and security professionals who want to ensure the security of their Python code. It is open source, easy to use, and can be integrated into your existing development processes. By using Bandit to identify and remediate security vulnerabilities, you can help protect your applications and data from potential security threats.

3. Snyk

Note: this one has limited number of tests that you can run per month.

Snyk is a security tool that helps you find and fix vulnerabilities in your dependencies, including those written in Python. Snyk integrates with your development workflows and provides notifications when new vulnerabilities are discovered in your dependencies, so you can take action to remediate them quickly.

Here’s how Snyk works:

  1. Scanning: Snyk scans your code and dependencies and identifies known vulnerabilities. It also provides recommendations for how to fix each vulnerability, including suggested upgrades and patches.
  2. Notifications: Snyk sends notifications to keep you informed of new vulnerabilities as they are discovered, so you can take action to remediate them quickly.
  3. Remediation: Snyk provides detailed guidance on how to remediate vulnerabilities, including step-by-step instructions for upgrading dependencies to the latest secure versions. Snyk also provides the ability to automate the remediation process, so you can resolve vulnerabilities quickly and efficiently.
  4. Dashboard: Snyk provides a centralized dashboard that gives you an overview of your project’s security status, including information about the number and severity of vulnerabilities in your dependencies, and a timeline of when they were discovered.

Overall, Snyk is a powerful tool for anyone who wants to ensure the security of their dependencies. With Snyk, you can stay informed of new vulnerabilities, take action to remediate them quickly, and keep your applications and data secure.

Let me know if you know any other good ones in the comments!

Categories
Administration Development

How can I prevent SQL injection in PHP?

Disclaimer that this article talks about the best practices that you can use to decrease the likelihood of preventing SQL/MySQL injection when writing code in PHP. This, however, does not guarantee that you will never be victim to MySQL injection. You will always need to be cautious when coding and test appropriately.

1. Us PHP Data Objects (PDO Extension)

PDO is an extension for PHP that provides a common interface for accessing databases. It was introduced in PHP 5.1 and is now the recommended way to interact with databases in PHP. PDO provides a consistent, object-oriented interface for working with databases, regardless of the underlying database system (e.g., MySQL, PostgreSQL, SQLite, etc.).

In summary it can:

  1. Support for multiple database systems: PDO supports a wide range of databases, including MySQL, PostgreSQL, SQLite, MS SQL Server, Oracle, and others.
  2. Consistent interface: PDO provides a consistent interface for performing common database operations, such as executing queries, fetching data, and managing transactions.
  3. Prepared statements: PDO supports prepared statements, which allow you to execute the same statement multiple times with different parameters. Prepared statements can help prevent SQL injection attacks.
  4. Error handling: PDO provides an exception-based error handling mechanism that makes it easier to handle and debug errors in your database code.
  5. Transactions: PDO supports transactions, allowing you to execute a series of database operations as a single, atomic transaction.
  6. Easy data binding: PDO supports data binding, which allows you to bind values to placeholders in your SQL statements. This makes it easy to write secure and efficient database code.

By using PDO, you can write database-agnostic code that works with multiple database systems, and you can take advantage of its advanced features, such as prepared statements and transactions, to write secure and efficient database code. If you are developing a new PHP application, you should consider using PDO to interact with your database. If you are upgrading an existing application, you may want to consider migrating your database code to PDO to take advantage of its improved features and security.

2. Mysqli extension

Mysqli is an improved version of the MySQL extension for PHP. It provides an improved, object-oriented interface for accessing and manipulating databases in PHP. Mysqli stands for MySQL Improved.

In short it can provide you with the following.

  1. Support for both procedural and object-oriented programming styles.
  2. Support for prepared statements, which allow you to execute the same statement multiple times with different parameters. Prepared statements can help prevent SQL injection attacks.
  3. Improved security features, including support for SSL-encrypted connections and improved error handling.
  4. Improved performance, as mysqli is optimized for modern hardware and software environments.
  5. Support for transactions, allowing you to execute a series of database operations as a single, atomic transaction.
  6. Support for multiple statements, allowing you to execute multiple SQL statements with a single call to mysqli.

Mysqli is the recommended database extension for PHP, as it provides a number of improvements over the older MySQL extension. If you are developing a new PHP application, you should use Mysqli instead of the older MySQL extension. If you are upgrading an existing application, you should consider migrating from MySQL to Mysqli to take advantage of its improved features and security.

3. Limit Privileges on the database side

Limit the privileges of the database user to only the minimum required to perform its intended tasks. This way, even if an attacker is able to inject malicious code into an SQL statement, they will be limited in the actions they can take on the database.

4. Always update

Keep your PHP and database software up-to-date with the latest security patches. New vulnerabilities are often discovered and fixed in software updates, so keeping your software up-to-date is an important part of securing your application.

You should also keep the habit of subscribing to new changelogs and security newsletters. They will usually announce when there is a new vulnerability.

5. Enable error logs

If you have not done that yet you should make sure that you have error logs available. Logs take a significant space but you might think about enabling them one in a while to do an audit and check if everything is running as expected.

6. Use a web application firewall

A WAF can be used to monitor and block malicious requests, including those that attempt to exploit SQL injection vulnerabilities. You could take a popular one from Cloudflare for example. Or if cost is too high then you can also go with an open source WAF like ModSecurity.

There are other obvious ways like validating user input but this should be common sense by now. Let me know if you know any other means to secure against SQL Injection or actually any other database vulnerability in the comments!

Categories
Management

Which management course should a software engineer do?

There are many management courses available. This article will focus on three most popular ones. Six Sigma, PMP and MBA.

Six Sigma

Six Sigma is a data-driven, continuous improvement methodology designed to eliminate defects and improve processes in an organization. It focuses on reducing variability in processes and improving efficiency and customer satisfaction. Six Sigma professionals are trained to use statistical analysis and problem-solving techniques to identify and eliminate the root causes of defects and inefficiencies.

Project Management Professional

PMP is a project management certification offered by the Project Management Institute (PMI). It is aimed at project managers who are responsible for leading and managing projects from start to finish. PMP certification requires passing an exam and demonstrating experience in leading and directing projects. PMP certified professionals have the knowledge and skills to effectively manage scope, schedule, budget, and resources, and to ensure the successful delivery of projects.

Master of Business Administration

An MBA is a graduate-level degree program in business administration that provides students with a comprehensive education in business and management. The program covers topics such as finance, marketing, operations, and strategy, and is designed to provide students with a broad understanding of business and the skills needed to lead and manage organizations. An MBA program typically involves coursework and may also include hands-on experience such as internships, case studies, and group projects.

Which one is best for software engineering?

It depends on the specific goals and career aspirations of the software engineer. Here’s a brief overview of how each of the certifications may be relevant to a software engineer:

For Six Sigma, while it may not be directly relevant to software engineering, it could be useful for software engineers who are interested in process improvement and quality control, especially if they are working in a software development organization that has adopted Six Sigma as its standard for continuous improvement.

PMP certification can be beneficial for software engineers who are interested in transitioning into project management roles, or for those who are already managing software development projects. The PMP certification provides a comprehensive understanding of project management principles, including how to manage scope, schedule, budget, and resources, and how to ensure project success.

An MBA can be valuable for software engineers who are interested in advancing their careers into management and leadership roles, especially in technology-focused organizations. An MBA program provides a broad education in business and management, including courses in finance, marketing, and strategy, which can be useful for software engineers who want to understand the business side of software development.

Ultimately, the best certification for a software engineer will depend on their individual career goals and aspirations. A software engineer may find that obtaining multiple certifications, such as PMP and Six Sigma, can be beneficial for broadening their skills and knowledge, and increasing their marketability in the job market.

Our recommendation is to start with a projection management certificate.

Categories
Uncategorized

How to wait in Python?

In Python, you can wait or pause the execution of your code by using the time module. The time module provides several functions to handle time-related operations, including the ability to pause execution. Here’s how you can use the time.sleep() function to wait in Python:

import time

print("Start")

# Wait for 5 seconds
time.sleep(5)

print("End")

The time.sleep() function takes one argument, which is the number of seconds to wait. In the example above, the code will wait for 5 seconds before printing “End”.

It’s important to note that the time.sleep() function will pause the entire process, so it’s not suitable for applications where you need to respond to events in real-time.

Categories
Development

How to learn Python for beginners?

Learning Python as a beginner can seem like a daunting task, but with the right resources and approach, it can be quite manageable. Here are some steps that can help you get started with learning Python:

1. Set your goals

What do you want to do with Python? Do you want to build web applications, data analysis, machine learning, or something else? Knowing your end goal will help you stay motivated and focused.

2. Choose a good resource

Choose a good resource: There are many resources available for learning Python, including online tutorials, video courses, books, and interactive platforms. Some popular options include Codecademy, Udemy, Coursera, and Google’s Python Class.

3. Start with the basics

Python is a relatively easy programming language to learn, and it’s a great idea to start with the basics. Learn about variables, data types, control structures, functions, and basic syntax.

4. You need to make time for practice

The more you practice coding, the better you will become. Try to solve small problems and complete simple projects to apply your knowledge and solidify your skills.

5. Get involved in the community:

Python has a large and supportive community of developers, and getting involved with the community can help you learn faster, get answers to questions, and stay motivated. Join online forums, attend local meetups, or participate in online groups.

6. Work on a project

Once you have a good understanding of the basics, try to work on a project that interests you. This could be anything from building a simple calculator to creating a web application or a data analysis tool.

Remember, learning to code takes time and effort, but with persistence and determination, you can become proficient in Python.

Categories
Development

How to clear list in python?

Reassigning list to an empty list

You can clear a list in Python by reassigning the list to an empty list. For example:

my_list = [1, 2, 3, 4, 5]
print("Before clearing:", my_list)
my_list = []
print("After clearing:", my_list)

Output:

Before clearing: [1, 2, 3, 4, 5]
After clearing: []

Using clear() in Python 3.3

Another way to clear a list is to use the clear() method, which is available in Python 3.3 and later:

my_list = [1, 2, 3, 4, 5]
print("Before clearing:", my_list)
my_list.clear()
print("After clearing:", my_list)

Output:

Before clearing: [1, 2, 3, 4, 5]
After clearing: []
Categories
Development

How to clear screen in python?

There are several ways to clear the screen in Python, depending on the operating system you are using. Here are some of the common methods:

Using the os module:

import os
os.system('clear') # for linux/macOS
os.system('cls') # for Windows

Using ANSI escape codes:

print("\033c", end="")

Using the subprocess module:

import subprocess
subprocess.run("clear") # for linux/macOS
subprocess.run("cls") # for Windows

Disclaimer that you might need to run the following code in a terminal and that this might not work in a Python IDE by Pycharm.

Categories
Development

How to fix pip install automl getting stuck?

First of all you will need to change your “pip install automl” to “pip install automl”. This will give you a verbose output and you will find exactly where the installation is failing.

For example a common case for the installation to get stuck is at the point when it tries to install multiprocess as one of its dependencies.

Requirement already satisfied: multiprocess>=0.70.7 in ...\lib\site-packages (from pathos<0.3.0,>=0.2.1->automl) (0.70.11.1)
Collecting multiprocess>=0.70.7
...

Turns out that multiprocess, at the time of writing, worked only on Python 3.6 instead of Python 3.11 (which I was trying to use).

To fix the issue in this case you can switch between Python interpreter. If you want to support multiple versions of Python on Windows this is a good tutorial: https://levelup.gitconnected.com/how-to-install-and-manage-multiple-python-versions-on-windows-10-c90098d7ba5a

If you are on Linux: https://levelup.gitconnected.com/install-multiple-python-versions-on-linux-8bd6d301d78c

For my case I was on Pycharm. If you would like to change Python interpreter on Pycharm you can go to “Find Actions” -> type “Python Interpreter” and then just point it to an installation of folder of Python 3.6.

Anyway, this is if the installation is failing at multiprocess. The root cause of your issue might be different, like a permission issue, but whatever it is just turning on the verbose output and searching online should you give you enough information to unblock yourself.

In case you are still stuck, try to comment below and I will get back to you.

Categories
Business Management

How to pay less tax as a freelance developer?

This blog post highlights the main way that I have found out, legally, that you can use to pay less in tax as a freelance software developer. A disclaimer here that you will have to crosscheck the contents in this blog post to the laws of the country that you are operating in.

Registering as a private company to pay less in tax and how?

Usually freelancers register themselves as an independent contractor. This is faster to start your operations but this means that the you will have to pay taxes on all your income (minus a few expenses that you can deduct). The main “hack” is to instead open a private company. Why is that? Because you can pay taxes on dividends instead. If we use the UK as example there is a nice article here that you can read https://www.crunch.co.uk/knowledge-tax/what-tax-do-i-pay-on-dividends

The gist of it is as follows:

  1. Charge your customers from the company
  2. Optional: Pay yourself a minimum salary
  3. At end of the year declare a profit
  4. Pay yourself dividends which have much less tax

But how to maintain cash flow?

If you have cashflow issues and cannot wait until the end of the year to get paid with your dividends, then you might need to seek out a short term loan. In some countries this can be a business loan too. The ideal way is to at least have savings to sustain a year or part of it.

Last step: get an accountant

An accountant could easily advise you on the above for around 150 USD and it’s worth it. Seek them out before doing anything and you won’t regret it. The disclaimer again that this vary largely on the country that you are operating in.

Good luck, it’s a tough world out there 🙂