Planet Python

Subscribe to Planet Python feed
Planet Python - http://planetpython.org/
Updated: 2 hours 50 min ago

Django Weblog: An open letter regarding the DjangoCon Europe CfP

Mon, 2024-04-22 18:32

As many of you are not doubt aware there have recently been some community conversation regarding a license agreement that was published as part of the DjangoCon Europe Call for Proposals for organizers. I believe it is fair to characterize the reaction as negative, with expressions of anger, frustration, and confusion towards the DSF for placing burdensome and one sided requirements for hosting a DjangoCon Europe.

I want to state first and foremost that I added the licensing agreement to the CfP. My deepest apologies for everyone who felt betrayed by it. I hold our conference organizers in the highest regard, for the equity, effort, blood, sweat, and tears they put into creating amazing community events that bring us all together. I considered resigning from the board for the pain and confusion that I have caused. I have not because I want to be part of finding a way forward and keeping DjangoCon Europe the calendar event that so many of us eagerly await. It will be up to all of you if I can be part of that journey back.

The most difficulty accusation to face is that of a lack of transparency and surprising former and prospective organizers with the license. It is difficult for me because I honestly believed I was increasing the level of transparency to organizers. This licensing agreement is not a new document, though I now understand that it is new to, well, everyone. The license has existed in the DSF legal documents repository since at least 2016 and has been signed for at least one DjangoCon Europe. In my years on the board prior to my presidency on several occasions there were todos to have selected organizers "sign the organizer contract". In addition I know that DEFNA is party to an almost identical licensing contract with the DSF. It was my intention to provide to potential organizers with the contract prior to making a proposal so that when a proposal was selected the organizers would not be taken aback when being presented with the license.

I was mortified when I heard, first in private and then publicly, that no DjangoCon Europe organizers of current memory had ever signed the license. The group of some of our community's most dedicated volunteers felt like with the click of a keyboard had turned into an arms length transaction among lawyers. At the same time I was mortified at the potential legal jeopardy the DSF had unknowingly been in by not having license agreements in place for all DjangoCons.

I'd like to touch on several points brought up in the discussion that has come from this.

The first regards the time window of DjangoCon Europe as laid out in the CfP. The DSF has long standing agreements with the PSF, DEFNA, and EuroPython to not adversely impact each other's conferences by scheduling them too close together. The agreement specifies that no two conferences should be within a month of each other. The sentiment of the agreement is well placed, but I believe it is time to revisit it. With new conferences coming into the fold (it was rightly pointed out the DjangoCon Africa is not mentioned in the license), the ability for conferences to have meaningful remote participation, and a calendar that due to weather often has the four stated conferences vying for a 5-7 month slot the one month gap is difficult to plan around. I am publicly proposing here that the interested parties to this agreement modify it such that the one month window apply to either region or theme, but not both. That would have, for instance, DjangoCon US avoiding Pycon and DjangoCons Europe and Africa but not EuroPython and vice versa.

The second point is in regards to the requirement to not schedule against major religious and cultural holidays. While I did not write that, I embody it. My first DjangoCon was DjangoCon Europe. I was unable to attend DjangoCon US in Chicago while I was living in Chicago as it had been partly scheduled against Rosh Hashanah. So I convinced my boss to send me to France instead and fell in love with the Django community.

Finally to the comments that the DSF does not care about organizers and has no interest in helping them put on a conference. Unfortunately DSF does not have inherent knowledge of running conferences, no legal entity outside the US to bring to bear, or the finances to backstop a DjangoCon. We ask for your help every year to run DjangoCon Europe because, quite simply, we can't. There was a meeting in Edinburgh of former organizers to discuss how organizing a DjangoCon Europe coule be improved. That meeting was the start of the European Organizers Support working group. It did take time to get started. We have it now. It is the sincerest hope of all of us that it is the first step in improving the experience of European organizers, and hopefully others down the line. It is a slow process, but one I dearly hope bears fruit.

I sincerely hope that we can all together still work to make DjangoCon Europe 2025 a reality. I will do all that I can to make that happen, if you will continue to have me. I do not participate in social media, but have started a thread on the Django Forum to continue this discussion. For most of the next week I will be unavailable due to the Passover holiday but it was imperative to me that I get this message to you all as soon as I could.

Thank you for your time, and for letting me serve you, Chaim Kirby President, Django Software Foundation

Categories: FLOSS Project Planets

Real Python: Write Unit Tests for Your Python Code With ChatGPT

Mon, 2024-04-22 10:00

Having a good battery of tests for your code may be a requirement for many Python projects. In practice, writing unit tests is hard and can take a lot of time and effort. Therefore, some developers don’t like to write them. However, with large language models (LLMs) and tools like ChatGPT, you can quickly create robust and complete sets of tests for your Python code.

In Python, you can use multiple different tools for writing tests. The most commonly used tools include doctest, unittest, and pytest. ChatGPT can be of great help in writing tests with any of these tools.

In this tutorial, you’ll:

  • Prompt ChatGPT to create tests using doctest
  • Use ChatGPT to write unittest tests, fixtures, and suites
  • Craft ChatGPT prompts to write pytest tests and fixtures
  • Use alternative prompts for cases where the code isn’t available

To get the most out of this tutorial, you should set up a ChatGPT account and know the basics of interacting with this tool using prompt engineering. You should also know the basics of how to test code in Python.

Get Your Code: Click here to download the free sample code you’ll use to write unit tests for your Python code using ChatGPT.

Benefits of Using ChatGPT for Testing Python Code

Having good and up-to-date unit tests for your code is a must for any Python project. Poorly tested code or code without tests may end up being unreliable and weak. With automated tests, you can ensure and show that your code works correctly in different scenarios. So, having tests is important from the technical and commercial point of view.

Writing good tests is hard and can take a lot of time. That’s why some developers don’t like to write them at all. Using large language models (LLM) like ChatGPT can be a viable alternative for providing your projects and code with proper tests.

Note: You can use ChatGPT and other LLMs in many useful ways in the context of Python development. Check out the following resources for other use cases and useful insights:

Some of the benefits of using ChatGPT to write tests for your Python code include the following:

  • Efficiency and speed: It can generate unit tests based on specifications or code snippets. This possibility significantly reduces the time that you need to spend writing tests. So you can focus on writing application logic.
  • Coverage improvement: It can suggest tests for edge cases or scenarios that developers might not immediately consider. This way, you can improve your code’s test coverage.
  • Error reduction: It can reduce human error in writing repetitive or boilerplate test code.
  • Learning and onboarding: It can serve as an educational tool for developers who are new to testing frameworks or unfamiliar with best practices in unit testing. The generated tests can help developers learn about testing patterns, assertions, and ways to effectively write tests.

With ChatGPT, you can generate unit tests for your Python code in almost no time. However, you must note that even though the generated tests can look good, you should still review and possibly refine the generated tests.

Note: For this tutorial, you’ll use a free ChatGPT account that’s powered by the GPT-3.5 LLM. You can use this model for free with the default web interface by OpenAI. If you use a paid account with GPT-4, then your results might be more accurate and faster.

Additionally, you’ll use an individual chat thread for each major section in the tutorial. So you’ll use different threads for the doctest, unittest, and pytest sections.

Using a single chat thread to run all the examples in this tutorial may cause the chat to generate significantly different responses because of the past context, which includes previous prompts and responses.

In the following sections, you’ll learn the basics of using ChatGPT as an assistant for creating coherent unit tests for your Python projects using different test frameworks and libraries.

Writing doctest Tests With ChatGPT

Python’s doctest module provides a lightweight testing framework that you can use for test automation. It can read the test cases from your project’s documentation and your code’s docstrings. This framework comes with the Python interpreter, so you’ll have it at your disposal with any Python installation, which is great.

Note: To dive deeper into how to use the doctest module for testing your code, check out Python’s doctest: Document and Test Your Code at Once.

With doctest, you can write code that provides examples of how your code works, simulating REPL sessions. These examples work as documentation and also as test cases or unit tests. Each doctest test needs a statement or expression and an expected result.

You can use ChatGPT to help you out with writing doctest tests. First, you need some code to test. The following function tries to tackle the FizzBuzz challenge, where you return "fizz" for numbers divisible by three, "buzz" for those divisible by five, and "fizz buzz" for those divisible by both three and five.

Go ahead and create a fizzbuzz.py file and add the following code to it:

Python fizzbuzz.py def fizzbuzz(number): if number % 3 == 0: return "fizz" elif number % 5 == 0: return "buzz" elif number % 15 == 0: return "fizz buzz" else: return number Copied!

This function works okay for numbers divisible by 3 or 5. However, there is a slight issue with numbers that are divisible by both. Even though you know this, go ahead and start a new chat thread. Then, prompt ChatGPT to write doctest test for the function:

You: Write doctest tests for the following function:

Python def fizzbuzz(number): if number % 3 == 0: return "fizz" elif number % 5 == 0: return "buzz" elif number % 15 == 0: return "fizz buzz" else: return number Copied!

ChatGPT:

Certainly! The function you’ve provided implements a basic FizzBuzz algorithm but with a slight logical error. The check for divisibility by 15 should come before checks for 3 and 5, as every number divisible by 15 is also divisible by both 3 and 5, but your current order will never reach the "fizz buzz" case. Here’s a corrected version of your function with the logical order fixed, followed by doctest tests for it:

Python def fizzbuzz(number): """ Returns 'fizz' if number is divisible by 3, 'buzz' if number is divisible by 5, 'fizz buzz' if number is divisible by 15, and the number itself otherwise. >>> fizzbuzz(3) 'fizz' >>> fizzbuzz(5) 'buzz' >>> fizzbuzz(15) 'fizz buzz' >>> fizzbuzz(4) 4 >>> fizzbuzz(30) 'fizz buzz' >>> fizzbuzz(9) 'fizz' >>> fizzbuzz(10) 'buzz' >>> fizzbuzz(2) 2 """ if number % 15 == 0: return "fizz buzz" elif number % 3 == 0: return "fizz" elif number % 5 == 0: return "buzz" else: return number Copied!

To use these doctest tests, you’ll need to include them in the docstring of your function as shown above. Then, you can run the tests with the doctest module by adding the following to your script:

Python if __name__ == "__main__": import doctest doctest.testmod() Copied!

This code will automatically run the tests defined in the docstrings when you execute the Python file. Remember, the corrected order of conditions in the function ensures that numbers divisible by both 3 and 5 return "fizz buzz", which is crucial for the FizzBuzz logic.

Wow! That great! The chat not only wrote the doctest tests for you. It also fixed the issue, explained important concepts around doctest, and provided instructions on how to run the tests. Note that the tests cover both regular and edge cases, which is pretty convenient.

Read the full article at https://realpython.com/chatgpt-unit-tests-python/ »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

Zato Blog: Enterprise Python: Integrating with Salesforce

Mon, 2024-04-22 04:00
Enterprise Python: Integrating with Salesforce 2024-04-22, by Dariusz Suchojad Overview

Salesforce connections are one of the newest additions to Zato 3.2, allowing you to look up and manage Salesforce records and other business data. To showcase it, the article will create a sample Salesforce marketing campaign in a way that does not require the usage of anything else except for basic REST APIs combined with plain Python objects, such as dicts.

If you have not done it already, you can download Zato here.

Basic workflow

The scope of our works will be:

  • Creating Salesforce credentials for our integration project
  • Defining a Salesforce connection in Zato
  • Authoring a service that will map input data to the format that Salesforce expects
  • Creating a Zato REST channel that will be invoked through curl during tests
  • Testing the integration
Creating Salesforce credentials

To be able to create as connection to Salesforce in the next step, we need a few credentials. There is a full article about how to prepare them and this section is the gist of it.

In runtime, based on this information, Zato will obtain the necessary authentication and authorization tokens itself, which means that you will only focus on the business side of the integrations, not on the low-level aspects of it.

The process of obtaining the credentials needs to be coordinated with an administrator of your organization. To assist in that, the screenshots below explain where to find them.

The credentials are:

  • Username and password
  • Consumer key
  • Consumer secret

The username and password are simply the same credentials that can be used to log in to Salesforce:

Consumer key and secret are properties of a connected app - this is a term that Salesforce uses for API clients that invoke its services. If you are already an experienced Salesforce REST API user, you may know the key and secret under their aliases of "client_id" and "client_secret" - these are the same objects.

Note that when a connected app already exists and you would like to retrieve the key and secret, they will be available under the "View" menu option for the app, not under "Edit" or "Manage".

Defining a Salesforce connection in Zato

With all the credentials in place, we can create a new Salesforce connection in Zato Dashboard, as below.

Authoring an integration service in Python

Above, we created a connection definition that lets Zato obtain session tokens and establish connections to Salesforce. Now, we can create an API service that will make use of such connections.

In the example below, we are using the POST REST method to invoke an endpoint that creates new Salesforce campaigns. In your own integrations, you can invoke any other Salesforce endpoint, using any REST method as needed, by following the same pattern, which is, create a model with input fields, build a Python dict for the request to Salesforce, invoke it and map all the required from the response from Salesforce to that which your own service returns to its own callers.

Note that we use a datamodel-based SimpleIO definition for the service. Among other things, although we are not going to do it here, this would let us offer definitions for this and other services.

# -*- coding: utf-8 -*- # stdlib from dataclasses import dataclass # Zato from zato.server.service import Model, Service # ########################################################################### if 0: from zato.server.connection.salesforce import SalesforceClient # ########################################################################### @dataclass(init=False) class CreateCampaignRequest(Model): name: str segment: str # ########################################################################### @dataclass(init=False) class CreateCampaignResponse(Model): campaign_id: str # ########################################################################### class CreateCampaign(Service): class SimpleIO: input = CreateCampaignRequest output = CreateCampaignResponse def handle(self): # This is our input data input = self.request.input # type: CreateCampaignRequest # Salesforce REST API endpoint to invoke - note that Zato # will add a prefix to it containing the API version. path = '/sobjects/Campaign/' # Build the request to Salesforce based on what we received request = { 'Name': input.name, 'Segment__c': input.segment, } # .. create a reference to our connection definition .. salesforce = self.cloud.salesforce['My Salesforce Connection'] # .. obtain a client to Salesforce .. with salesforce.conn.client() as client: # type: SalesforceClient # .. create the campaign now .. sf_response = client.post(path, request) # .. build our response object .. response = CreateCampaignResponse() response.campaign_id = sf_response['id'] # .. and return its ID to our caller. self.response.payload = response # ########################################################################### Creating a REST channel

Note that we assign HTTP Basic Auth credentials to the channel. In this manner, it is possible for clients of this REST channel to authenticate using a method that they are already familiar which simplifies everyone's work - it is Zato that deals with how to authenticate against Salesforce whereas your API clients use the ubiquitous HTTP Basic Auth method.

Testing

The last step is to invoke the newly created channel:

$ curl http://api:password@localhost:17010/api/campaign/create -d '{"name":"Hello", "segment":"123"}' {"campaign_id":"8901Z3VHXDTebEJWs"} $

That is everything - you have just integrated with Salesforce and exposed a REST channel for external applications to integrate with!

More blog posts
Categories: FLOSS Project Planets

Go Deh: Searching OEIS tables

Sun, 2024-04-21 16:32

 

 A few months ago I submitted a series to OEIS* that was accepted; yes, but OEIS does not seem to leave my series searchable!

*OEIS is the Online Encyclopedia of  Integer Series. I guess table is not in the name, but...

(best viewed on larger than a portrait phone)

Let me explain.

The documentation for OEIS, explains that if you have a 2D triangle or table of values rather than a one dimensional strict series, then one should antidiagonalise the data and submit the series produced.

They give as an example A003987 . This gives this table:

Table begins   0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, ...   1,  0,  3,  2,  5,  4,  7,  6,  9,  8, 11, 10, ...   2,  3,  0,  1,  6,  7,  4,  5, 10, 11,  8, ...   3,  2,  1,  0,  7,  6,  5,  4, 11, 10, ...   4,  5,  6,  7,  0,  1,  2,  3, 12, ...   5,  4,  7,  6,  1,  0,  3,  2, ...   6,  7,  4,  5,  2,  3,  0, ...   7,  6,  5,  4,  3,  2, ...   8,  9, 10, 11, 12, ...   9,  8, 11, 10, ...  10, 11,  8, ...  11, 10, ...  12, ...  ...

The above gets antidiagonalised to the series beginning:

  0, 1, 1, 2, 0, 2, 3, 3, 3, 3, 4, 2, 0, 2, 4, 5, 5, 1, 1, 5, 5, 6, 4,  6, 0, 6, 4, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 6, 4, 6, 0, 6, 4, 6, 8, 9,  9, 5, 5, 1, 1, 5, 5, 9, 9, 10, 8, 10, 4, 2, 0, 2, 4, 10, 8, 10, 11,  11, 11, 11, 3, 3, 3, 3, 11, 11, 11, 11, 12, 10, 8, 10, 12, 2, 0, 2,  12, 10, 8, 10, 12, 13, 13, 9, 9, 13, 13, 1, 1, 13, 13, 9, 9, 13, 13

Searching...

If we search for a sub-sequence of the antidiagonalised table, we can find the correct entry.

If, however, we search for a row of the values from the table,  A003987 is not found!
The values chosen: to search for: 5,4,7,6,1,0,3 appear near the end of the table which shows that that row of numbers should be followed by a 2.
The table shows 13*13 / 2 ~ 85 values. OEIS has a list of 104 values, so it has the data to search through.

No intuitive search of OEIS tables

It seems to me that the most intuitive way to search a table of values is by row, left to right. There are other ways to search a table, (assuming an origin at top left and the table extends to the right and down):

  • By row, L2R. , R2L
  • By Column Top2Bottom, , B2T
  • By 45 degree diagonals, ↘, ↖, ↙, ↗

OEIS doesn't seem to do these searches on tabular data.

Regenerating a 2D table from antidiagonalised data.

I did play around and created some code to recreate a table as a list of row-lists, in Python, given an OEIS B-file. The options handling is a work in progress, but the main part was being able to generate the table.

# -*- coding: utf-8 -*-# %%"""adia_to_table.py file
Generate 2D table from OEIS type anti-diagonalised sequence held in file

Created on Thu Apr  4 18:16:07 2024
@author: paddy3118"""
from itertools import zip_longestimport math# from pprint import ppfrom antidiagonals import antidiag_triangle_indices

def read_bfile(bfname: str) -> tuple[int | None,  # first index                                     list[int]]:   # anti-diag values    """Read B-file bfname
## B-File format:* Ref: https://oeis.org/SubmitB.html* Blank lines ignored* Lines beginning  with # ignored* Lines of two, space-separated integers <index> <indexed-value>
It is assumed the index increments by one on subsequent lines.    """    first_index, values = None, []    with open(bfname) as bfile:        for line in bfile:            ln = line.strip()            if not ln or ln.startswith('#'):                continue            index, value = [int(field) for field in ln.split()[:2]]            if first_index is None:                first_index = index            values.append(value)
    return first_index, values

def antidiag_to_table(sequence: list[int]) -> list[list[int]]:    """    Convert anti-diagonalised sequence back to infinite 2D table.
    Parameters    ----------    sequence : list[int]        Anti-diagonalised values from table.
    Returns    -------    list[list[int]]        Table of rows of ints.
    Table rows will fill in from successive sequence values like this:
     1  2  4  7 11 16 ...     3  5  8 12 17     6  9 13 18    10 14 19    15 20    21    .    .    .    """
    # 1, 3, 6, 10, 15, 21, ... rows*(rows+1) / 2
    # min columns in triangular table generation. ~= min rows    size = len(sequence)                                  # = rows*(rows+1)/2    rows = math.ceil((-1 + math.sqrt(4 * 2 * size)) / 2)  # solve for rows    # cols = rows  # last row may be deleted if last anti-diag is part filled.    # print(f"{(size, cols) = }")
    # Empty (triangular) table of None's    table = [[None] * (rows - i)             for i in range(rows)]
    indices = antidiag_triangle_indices()    col = 0  # for if sequence is empty    for val, (row, col) in zip(sequence, indices):        table[row][col] = val
    # Remove unfilled part of last anti-diag of table    while col > 0:        row, col = next(indices)        table[row].pop(-1)    # remove last row if present and empty    if table and not table[-1]:        table.pop(-1)
    return table

def pp_table(table: list[list[int]]) -> None:    "Pretty-print table of differring row lengths"    if not table:        return    col_width = max(max(len(str(val)) for val in row) for row in table)    for row in table:        print(''.join(f"{val:{col_width}}" for val in row))

def transpose(table: list[list[int]]) -> list[list[int]]:    "Table of rows to x<>y transposed table of new rows"    fv = math.nan    tr = [list(new_row)          for new_row in zip_longest(*table, fillvalue=fv)]    # remove fillvalues in triangular transposition    for row in tr:        try:            row[row.index(fv):] = []        except ValueError:            continue
    return tr

if __name__ == "__main__":    print("# TEST FILL BY ANTI-DIAGONAL\n")    for n in range(0, 8):        print(f"{n = }:\n")        ans = antidiag_to_table(list(range(1, n+1)))        pp_table(ans)        print()
    fname, m = 'b365096.txt', 505    print(f"\n\n# Data from {fname}, first {m} values:\n")    ad = read_bfile(fname)    ans = antidiag_to_table(ad[1][:m])    pp_table(ans)    print("\n## Transposed:\n")    pp_table((tr:=transpose(ans)))


And antidiagonals.py is this:

# -*- coding: utf-8 -*-"""Anti-diagonals:
0,0 0,1 0,2 0,31,0 1,1 1,2 1,32,0 2,1 2,2 2,33,0 3,1 3,2 3,3
Of Square:0,0  0,1 1,0  0,2 1,1 2,0  0,3 1,2 2,1 3,0   1,3 2,2 3,1  2,3 3,2  3,3
of Infinite table:0,0  0,1 1,0  0,2 1,1 2,0  0,3 1,2 2,1 3,0   0,4 1,3 2,2 3,1 4,0 ...

Created on Mon Aug 21 13:36:31 2023
@author: paddy
"""# %% Triangles
from itertools import islice

def antidiag_triangle_indices() -> tuple[int, int]:    x = y = 0    while True:        yield (x, y)        x, y = (x+1, y-1) if y else (0, x+1)

list(islice(antidiag_triangle_indices(), 15))
# %% Rectangles
from itertools import islice

def antidiag_rectangle_indices(sizex: int=4, sizey: int=4) -> tuple[int, int]:    x = y = 0    while True:        yield (x, y)        if (x, y) == (sizex - 1, sizey - 1):            break        x, y = (x+1, y-1)        if x == sizex or y < 0:            u = x + y + 1            x, y = (0, u) if u < sizey else (u - sizey + 1, sizey - 1)
list(antidiag_rectangle_indices(3, 4))


END.

Categories: FLOSS Project Planets

ListenData: 4 Ways to Use ChatGPT API in Python

Sat, 2024-04-20 07:28

In this tutorial, we will explain how to use ChatGPT API in Python, along with examples.

Steps to Access ChatGPT API

Please follow the steps below to access the ChatGPT API.

  1. Visit the OpenAI Platform and sign up using your Google, Microsoft or Apple account.
  2. After creating your account, the next step is to generate a secret API key to access the API. The API key looks like this -sk-xxxxxxxxxxxxxxxxxxxx
  3. If your phone number has not been associated with any other OpenAI account previously, you may get free credits to test the API. Otherwise you have to add atleast 5 dollars into your account and charges will be based on the usage and the type of model you use. Check out the pricing details in the OpenAI website.
  4. Now you can call the API using the code below.
To read this article in full, please click hereThis post appeared first on ListenData
Categories: FLOSS Project Planets

ListenData: How to Build ChatGPT Clone in Python

Sat, 2024-04-20 02:17

In this article, we will see the steps involved in building a chat application and an answering bot in Python using the ChatGPT API and gradio.

Developing a chat application in Python provides more control and flexibility over the ChatGPT website. You can customize and extend the chat application as per your needs. It also help you to integrate with your existing systems and other APIs.

To read this article in full, please click hereThis post appeared first on ListenData
Categories: FLOSS Project Planets

Python Morsels: Multiline comments in Python

Fri, 2024-04-19 19:00

Python does not have multiline comments. But you can use alternatives like docstrings, editor shortcuts, and conventional commenting methods, depending on your requirements.

Table of contents

  1. Does Python have multi-line comments?
  2. What about triple quotes?
  3. Docstrings versus comments
  4. What if I want to comment-out a whole block of code?
  5. How to comment multiple lines
  6. Use docstrings, your code editor, or version control

Does Python have multi-line comments?

For single-line comments, Python uses the octothorpe character (#), also known as pound, number sign, crunch, and of course, the hashtag character:

# This is a comment this = "is not a comment"

But what if you want to comment out a whole block of code?

Unlike some programming languages, Python does not have multi-line comments.

What about triple quotes?

You might be thinking, wait, …

Read the full article: https://www.pythonmorsels.com/multiline-comments/
Categories: FLOSS Project Planets

Real Python: Python's unittest: Writing Unit Tests for Your Code

Fri, 2024-04-19 08:00

In this quiz, you’ll test your understanding of testing your Python code with the unittest framework.

Testing in Python is a huge topic and can come with a lot of complexity, but it doesn’t need to be hard. You can create simple tests for your application in a few easy steps and then build on them from there.

With this quiz, you can check your understanding of testing with Python’s unittest framework. Good luck!

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

Real Python: The Real Python Podcast – Episode #201: Decoupling Systems to Get Closer to the Data

Fri, 2024-04-19 08:00

What are the benefits of using a decoupled data processing system? How do you write reusable queries for a variety of backend data platforms? This week on the show, Phillip Cloud, the lead maintainer of Ibis, will discuss this portable Python dataframe library.

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

ListenData: Complete Guide to Visual ChatGPT

Fri, 2024-04-19 04:37

In this post, we will talk about how to run Visual ChatGPT in Python with Google Colab. ChatGPT has garnered huge popularity recently due to its capability of human style response. As of now, it only provides responses in text format, which means it cannot process, generate or edit images. Microsoft recently released a solution for the same to handle images. Now you can ask ChatGPT to generate or edit the image for you.

Demo of Visual ChatGPT

In the image below, you can see the final output of Visual ChatGPT - how it looks like.

To read this article in full, please click hereThis post appeared first on ListenData
Categories: FLOSS Project Planets

ListenData: AutoGPT : Everything You Need To Know

Fri, 2024-04-19 04:37

In this post we have covered AutoGPT in detail. By end of this tutorial, you will not only understand how it works but also will be able to run it on your system. Auto-GPT has gained a significant amount of popularity in the media. It has become one of the most talked-about topics across various social media platforms after ChatGPT. It has not only captured the attention of people in Artifical Intelligence community but also people from other background. Media outlets across countries covered it and reported how it can automate everything ranging from simple to complex tasks.

Table of Contents What is AutoGPT?

AutoGPT is an experimental open-source project built on the latest ChatGPT model i.e GPT-4. It is not limited to ChatGPT as it can also do web search and try to find information from internet. When a client gives us a project with instructions on what to do. We, as analysts, perform tasks to fulfill the project requirements. In the same way, by assigning a project to AutoGPT, it will do on its own all the necessary tasks to meet the project's requirements.

Let's say you ask AutoGPT to do market research about different headphones in the market. It will do web search and try to find this information on internet and produce output for you in a cleaned and structured format. See the video below.

To read this article in full, please click hereThis post appeared first on ListenData
Categories: FLOSS Project Planets

ListenData: Complete Guide to Massively Multilingual Speech (MMS) Model

Fri, 2024-04-19 04:36

In this article we have covered everything about the latest multilingual speech model from the basics of how it works to the step-by-step implementation of the model in Python.

Meta, the company that owns Facebook, released a new AI model called Massively Multilingual Speech (MMS) that can convert text to speech and speech to text in over 1,100 languages. It is available for free. It will not only help academicians and researchers across the world but also language preservationists or activists to document and preserve endangered languages to prevent their extinction.

MMS is trained on a large dataset of text and audio in over 1,100 languages. Another best part about the model is that it generates audio which sounds very natural, like human speech. It is also able to identify more than 4,000 spoken languages.

To read this article in full, please click hereThis post appeared first on ListenData
Categories: FLOSS Project Planets

ListenData: Transformers Agent: AI Tool That Automates Everything

Fri, 2024-04-19 04:36

We have a new AI tool in the market called Transformers Agent which is so powerful that it can automate just about any task you can think of. It can generate and edit images, video, audio, answer questions about documents, convert speech to text and do a lot of other things.

Hugging Face, a well-known name in the open-source AI world, released Transformers Agent that provides a natural language API on top of transformers. The API is designed to be easy to use. With a single line code, it provides a variety of tools for performing natural language tasks, such as question answering, image generation, video generation, text to speech, text classification, and summarization.

To read this article in full, please click hereThis post appeared first on ListenData
Categories: FLOSS Project Planets

Talk Python to Me: #457: Software Supply Chain Security with Phylum

Fri, 2024-04-19 04:00
We've spoken previously about security and software supply chains and we are back at it this episode. We're diving in again with Charles Coggins. Charles works at a software supply chain company and is on to give us the insiders and defender's perspective on how to keep our Python apps and infrastructure safe.<br/> <br/> <strong>Episode sponsors</strong><br/> <br/> <a href='https://talkpython.fm/sentry'>Sentry Error Monitoring, Code TALKPYTHON</a><br> <a href='https://talkpython.fm/mailtrap'>Mailtrap</a><br> <a href='https://talkpython.fm/training'>Talk Python Courses</a><br/> <br/> <strong>Links from the show</strong><br/> <br/> <div><b>Pick a Python Lockfile and Improve Security</b>: <a href="https://blog.phylum.io/pick-a-python-lockfile-and-improve-security/" target="_blank" rel="noopener">blog.phylum.io</a><br/> <b>Bad Beat Poetry</b>: <a href="https://blog.phylum.io/bad-beat-poetry/" target="_blank" rel="noopener">blog.phylum.io</a><br/> <b>PEP 665 – A file format to list Python dependencies for reproducibility of an application</b>: <a href="https://peps.python.org/pep-0665/" target="_blank" rel="noopener">peps.python.org</a><br/> <b>PEP 517 – A build-system independent format for source trees</b>: <a href="https://peps.python.org/pep-0517/" target="_blank" rel="noopener">peps.python.org</a><br/> <b>PEP 518 – Specifying Minimum Build System Requirements for Python Projects</b>: <a href="https://peps.python.org/pep-0518/" target="_blank" rel="noopener">peps.python.org</a><br/> <b>Lockfiles should be committed on all projects</b>: <a href="https://classic.yarnpkg.com/blog/2016/11/24/lockfiles-for-all/" target="_blank" rel="noopener">classic.yarnpkg.com</a><br/> <b>An Overview of Software Supply Chain Security</b>: <a href="https://tldrsec.com/p/supply-chain-security-overview" target="_blank" rel="noopener">tldrsec.com</a><br/> <b>Typosquatting</b>: <a href="https://docs.phylum.io/analytics/typosquatting" target="_blank" rel="noopener">docs.phylum.io</a><br/> <b>Common Attack Pattern Enumeration and Classification</b>: <a href="https://capec.mitre.org/data/definitions/693.html" target="_blank" rel="noopener">capec.mitre.org</a><br/> <b>Dependency Confusion</b>: <a href="https://docs.phylum.io/analytics/dependency_confusion" target="_blank" rel="noopener">docs.phylum.io</a><br/> <b>Expired Author Domains</b>: <a href="https://docs.phylum.io/analytics/expired_author_domains" target="_blank" rel="noopener">docs.phylum.io</a><br/> <b>Unverifiable Dependency</b>: <a href="https://docs.phylum.io/analytics/odd_dependency" target="_blank" rel="noopener">docs.phylum.io</a><br/> <b>Repo Jacking: Hidden Danger in Broken Links</b>: <a href="https://blog.phylum.io/repojacking-software-supply-chain-vulnerability/" target="_blank" rel="noopener">blog.phylum.io</a><br/> <b>Software Libraries Are Terrifying</b>: <a href="https://medium.com/@dmrickert/software-libraries-are-terrifying-4875b6a74be6" target="_blank" rel="noopener">medium.com</a><br/> <b>phylum 0.43.0</b>: <a href="https://pypi.org/project/phylum/" target="_blank" rel="noopener">pypi.org</a><br/> <b>linguist</b>: <a href="https://github.com/github-linguist/linguist" target="_blank" rel="noopener">github.com</a><br/> <b>rich-codex ⚡️📖⚡️</b>: <a href="https://ewels.github.io/rich-codex/" target="_blank" rel="noopener">ewels.github.io</a><br/> <b>Phylum Community Discord</b>: <a href="https://discord.gg/Fe6pr5eW6p" target="_blank" rel="noopener">discord.gg</a><br/> <b>The dream is dead?</b>: <a href="https://mastodon.social/@tveskov/111289358585305218" target="_blank" rel="noopener">mastodon.social</a><br/> <b>When "Everything" Becomes Too Much: The npm Package Chaos of 2024</b>: <a href="https://socket.dev/blog/when-everything-becomes-too-much?utm_source=tldrnewsletter" target="_blank" rel="noopener">socket.dev</a><br/> <b>pip-tools</b>: <a href="https://github.com/jazzband/pip-tools" target="_blank" rel="noopener">github.com</a><br/> <b>Watch this episode on YouTube</b>: <a href="https://www.youtube.com/watch?v=uB-2nMphYBI" target="_blank" rel="noopener">youtube.com</a><br/> <b>Episode transcripts</b>: <a href="https://talkpython.fm/episodes/transcript/457/software-supply-chain-security-with-phylum" target="_blank" rel="noopener">talkpython.fm</a><br/> <br/> <b>--- Stay in touch with us ---</b><br/> <b>Subscribe to us on YouTube</b>: <a href="https://talkpython.fm/youtube" target="_blank" rel="noopener">youtube.com</a><br/> <b>Follow Talk Python on Mastodon</b>: <a href="https://fosstodon.org/web/@talkpython" target="_blank" rel="noopener"><i class="fa-brands fa-mastodon"></i>talkpython</a><br/> <b>Follow Michael on Mastodon</b>: <a href="https://fosstodon.org/web/@mkennedy" target="_blank" rel="noopener"><i class="fa-brands fa-mastodon"></i>mkennedy</a><br/></div>
Categories: FLOSS Project Planets

Test and Code: 218: Balancing test coverage with test costs - Nicole Tietz-Sokolskaya

Thu, 2024-04-18 00:26

Nicole is a software engineer and writer, and recently wrote about the trade-offs we make when deciding which tests to write and how much testing is enough.

We talk about:

  • Balancing schedule vs testing
  • How much testing is the right about of testing
  • Should code coverage be measured and tracked
  • Good refactoring can reduce code coverage
  • Is it worth testing error conditions?
  • Are rare error codes ok to just monitor?
  • API drift and autospec
  • Mitigating risk
  • Deciding what to test and what not to test
  • Focus testing on key money-making features 
  • If there's a bug in this part of the code, how much business impact is there?
  • Performance testing needs to approximately match real world workloads
  • Cost of a service breaking vs the cost of creating, maintaining, and running tests
  • Keeping test suites quick to minimize getting distracted


Links:


Sponsored by Mailtrap.io

  • An Email Delivery Platform that developers love. 
  • An email-sending solution with industry-best analytics, SMTP, and email API, SDKs for major programming languages, and 24/7 human support. 
  • Try for Free at MAILTRAP.IO

Sponsored by PyCharm Pro

The Complete pytest Course

  • For the fastest way to learn pytest, go to courses.pythontest.com
  • Whether your new to testing or pytest, or just want to maximize your efficiency and effectiveness when testing.
<p>Nicole is a software engineer and writer, and recently wrote about the trade-offs we make when deciding which tests to write and how much testing is enough.</p><p>We talk about:</p><ul><li>Balancing schedule vs testing</li><li>How much testing is the right about of testing</li><li>Should code coverage be measured and tracked</li><li>Good refactoring can reduce code coverage</li><li>Is it worth testing error conditions?</li><li>Are rare error codes ok to just monitor?</li><li>API drift and autospec</li><li>Mitigating risk</li><li>Deciding what to test and what not to test</li><li>Focus testing on key money-making features </li><li>If there's a bug in this part of the code, how much business impact is there?</li><li>Performance testing needs to approximately match real world workloads</li><li>Cost of a service breaking vs the cost of creating, maintaining, and running tests</li><li>Keeping test suites quick to minimize getting distracted</li></ul><p><br></p><p>Links:</p><ul><li><a href="https://ntietz.com/blog/too-much-of-a-good-thing-the-cost-of-excess-testing/">Too much of a good thing: the trade-off we make with tests</a> </li><li><a href="https://ntietz.com/blog/load-testing-is-hard-but-why/">Load testing is hard, and the tools are... not great. But why?</a></li><li><a href="https://yarr.fyi">Yet Another Rust Resource (YARR!)</a></li><li><a href="https://en.wikipedia.org/wiki/Goodhart%27s_law">Goodhart's law</a> - "When a measure becomes a target, it ceases to be a good measure"</li></ul> <br><p><strong>Sponsored by Mailtrap.io</strong></p><ul><li>An Email Delivery Platform that developers love. </li><li>An email-sending solution with industry-best analytics, SMTP, and email API, SDKs for major programming languages, and 24/7 human support. </li><li>Try for Free at <a href="https://l.rw.rw/pythontest">MAILTRAP.IO</a></li></ul><p><strong>Sponsored by PyCharm Pro</strong></p><ul><li>Use code PYTEST for 20% off PyCharm Professional at <a href="https://www.jetbrains.com/pycharm/">jetbrains.com/pycharm</a></li><li>Now with Full Line Code Completion</li><li>See how easy it is to run pytest from PyCharm at <a href="https://pythontest.com/pycharm/">pythontest.com/pycharm</a></li></ul><p><strong>The Complete pytest Course</strong></p><ul><li>For the fastest way to learn pytest, go to <a href="https://courses.pythontest.com/p/complete-pytest-course">courses.pythontest.com</a></li><li>Whether your new to testing or pytest, or just want to maximize your efficiency and effectiveness when testing.</li></ul>
Categories: FLOSS Project Planets

Matt Layman: Importing Content - Building SaaS with Python and Django #189

Wed, 2024-04-17 20:00
In this episode, I built the import view that is needed to allow users to add their own journal entries to JourneyInbox. After completing that, I handled the pull requests from dependabot, then I worked on some quality of life to do better handling with beta user trials.
Categories: FLOSS Project Planets

Matt Layman: Why Django and why not Flask?

Wed, 2024-04-17 20:00
Why would someone pick Django over Flask? That’s the question that I got on stream and here is my answer.
Categories: FLOSS Project Planets

Tryton News: Security Release for issue #13142

Wed, 2024-04-17 12:00

Cédric Krier has found that trytond accepts compressed content from unauthenticated requests which makes it vulnerable to zip bomb attacks.

Impact

CVSS v3.0 Base Score: 5.3

  • Attack Vector: Network
  • Attack Complexity: Low
  • Privileges Required: None
  • User Interaction: None
  • Scope: Unchanged
  • Confidentiality: None
  • Integrity: None
  • Availability: Low
Workaround

A proxy can be deployed in front of the trytond server to forbid this kind of request.

Resolution

All affected users should upgrade trytond to the latest version.

Affected versions per series:

  • trytond:
    • 7.0: <= 7.0.9
    • 6.8: <= 6.8.14
    • 6.0: <= 6.0.44

Non affected versions per series:

  • trytond:
    • 7.0: >= 7.0.10
    • 6.8: >= 6.8.15
    • 6.0: >= 6.0.45
Reference Concerns?

Any security concerns should be reported on the bug-tracker at https://bugs.tryton.org/ with the confidential checkbox checked.

1 post - 1 participant

Read full topic

Categories: FLOSS Project Planets

Mike Driscoll: Announcing The Python Logging Book &amp; Course Kickstarter

Wed, 2024-04-17 10:12

What does every new developer do when they are first learning to program? They print out strings to their terminal. It’s how we learn! But printing out to the terminal isn’t what you do with most professional applications.

Support on Kickstarter 

In those cases, you log into files. Sometimes, you log into multiple locations at once. These logs may serve as an audit trail for compliance purposes or help the engineers debug what went wrong.

Python Logging teaches you how to log in the Python programming language. Python is one of the most popular programming languages in the world. Python comes with a logging module that makes logging easy.

What You’ll Learn

In this book, you will learn how about the following:

  • Logger objects
  • Log levels
  • Log handlers
  • Formatting your logs
  • Log configuration
  • Logging decorators
  • Rotating logs
  • Logging and concurrency
  • and more!
Book formats

The finished book will be made available in the following formats:

  • paperback (at the appropriate reward level)
  • PDF
  • epub

The paperback is a 6″ x 9″ book and is approximately 150 pages long.

 

You can support the book by clicking the button below:

Support on Kickstarter

The post Announcing The Python Logging Book & Course Kickstarter appeared first on Mouse Vs Python.

Categories: FLOSS Project Planets

Real Python: How to Format Floats Within F-Strings in Python

Wed, 2024-04-17 10:00

You’ll often need to format and round a Python float to display the results of your calculations neatly within strings. In earlier versions of Python, this was a messy thing to do because you needed to round your numbers first and then use either string concatenation or the old string formatting technique to do this for you.

Since Python 3.6, the literal string interpolation, more commonly known as a formatted string literal or f-string, allows you to customize the content of your strings in a more readable way.

An f-string is a literal string prefixed with a lowercase or uppercase letter f and contains zero or more replacement fields enclosed within a pair of curly braces {...}. Each field contains an expression that produces a value. You can calculate the field’s content, but you can also use function calls or even variables.

While most strings have a constant value, f-strings are evaluated at runtime. This makes it possible for you to pass different data into the replacement fields of the same f-string and produce different output. This extensibility of f-strings makes them a great way to embed dynamic content neatly inside strings. However, even though f-strings have largely replaced the earlier methods, they do have their short-comings.

For example, one of the most common attacks performed on a relational database is a SQL injection attack. Often, users provide parameters to SQL queries, and if the query is formed within an f-string, it may be possible to damage a database by passing in rogue commands. F-strings can also be used in a denial-of-service attack by attacking Python’s logging module code.

In older versions of Python, f-strings had a number of other limitations that were only fixed with Python version 3.12. This version is used throughout this tutorial.

Take a look at the example below. It shows you how to embed the result of a calculation within an f-string:

Python >>> f"One third, expressed as a float is: {1 / 3}" 'One third, expressed as a float is: 0.3333333333333333' Copied!

Without any explicit rounding, once an expression has produced its value it’ll be inserted into the string using a default number of decimal places. Here, the result is shown to sixteen decimal places, which, in most cases, is more precision than you’ll ever need. So you’ll likely want to round your final answer to a more practical number of digits.

In this tutorial, you’ll learn how to use a Python f-string to format floats to meet your requirements.

Get Your Code: Click here to download the free sample code and exercise solutions you’ll use for learning how to format floats within f-strings in Python.

Take the Quiz: Test your knowledge with our interactive “Format Floats Within F-Strings” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Interactive Quiz

Format Floats Within F-Strings

In this quiz, you'll test your understanding of how to format floats within f-strings in Python. This knowledge will let you control the precision and appearance of floating-point numbers when you incorporate them into formatted strings.

How to Format and Round a Float Within a Python F-String

To format a float for neat display within a Python f-string, you can use a format specifier. In its most basic form, this allows you to define the precision, or number of decimal places, the float will be displayed with.

The code below displays the same calculation as before, only it’s displayed more neatly:

Python >>> f"One third, rounded to two decimal places is: {1 / 3:.2f}" 'One third, rounded to two decimal places is: 0.33' Copied!

To use Python’s format specifiers in a replacement field, you separate them from the expression with a colon (:). As you can see, your float has been rounded to two decimal places. You achieved this by adding the format specifier .2f into the replacement field. The 2 is the precision, while the lowercase f is an example of a presentation type. You’ll see more of these later.

Note: When you use a format specifier, you don’t actually change the underlying number. You only improve its display.

Python’s f-strings also have their own mini-language that allows you to format your output in a variety of different ways. Although this tutorial will focus on rounding, this is certainly not the only thing you can use them for. As you’ll see later, their mini-language is also used in other string formatting techniques.

In addition to displaying the result of calculations, the precision part of a format specifier can also be applied directly to variables and the return values of function calls:

Python >>> def total_price(cost): ... return cost * 1.2 ... >>> cost_price = 1000 >>> tax = 0.2 >>> f"£{1000:,.2f} + £{cost_price * tax:,.2f} = £{total_price(cost_price):,.2f}" '£1,000.00 + £200.00 = £1,200.00' Copied!

This time, you’ve used multiple replacement fields in the same string. The first one formats a literal number, the second formats the result of a calculation, while the third formats the return value from a function call. Also, by inserting a comma (,) before the decimal point (.) in the format specifier, you add a thousands separator to your final output.

In everyday use, you display numbers with a fixed amount of decimals, but when performing scientific or engineering calculations, you may prefer to format them using significant figures. Your results are then assumed to be accurate to the number of significant figures you display them with.

If you want to round numbers to significant figures, you use the lowercase letter g in the format specifier. You can also use an uppercase G, but this automatically switches the format to scientific notation for large numbers.

Suppose you have a circle with a radius of 10.203 meters. To work out the area, you could use this code:

Read the full article at https://realpython.com/how-to-python-f-string-format-float/ »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

Pages