Posts

Showing posts with the label python

Understanding Date Formats: ISO 8601 Example & Conversion Code

  Understanding Date Format: 2024-10-08T18:30:00.000+00:00 The date-time format 2024-10-08T18:30:00.000+00:00 follows the ISO 8601 standard for representing date and time. ISO 8601 provides a standardized way to represent dates and times globally, which is useful in software development, database design, and web services to avoid ambiguity. Breaking down the components: 2024-10-08 : This represents the date in the format YYYY-MM-DD , where: 2024 is the year. 10 is the month (October). 08 is the day (8th). T : This is a literal separator that separates the date from the time. 18:30:00 : This represents the time in the format HH:MM:SS , where: 18 is the hour (in 24-hour format, so 6 PM). 30 is the minute (30 minutes past the hour). 00 is the second (0 seconds). .000 : This represents the fraction of a second (in milliseconds). Here it’s 000 , meaning there is no additional fraction beyond the second. +00:00 : This represents the timezone offset . In this case: +00:00 ref...

Python Integration with Gemini: A Practical Guide

  Python Integration with Gemini: A Practical Guide Introduction Gemini is a powerful tool for managing and automating various aspects of your digital ecosystem. Integrating Python with Gemini can streamline your workflows and leverage Python's capabilities for complex data manipulation, automation, and analysis. In this article, we'll explore how to integrate Python with Gemini through a practical example. Prerequisites Before diving into the integration, ensure you have the following: Basic knowledge of Python programming. An active Gemini account and API access. The requests library installed in your Python environment (you can install it via pip install requests ). Overview of Gemini API Gemini provides a RESTful API that allows you to interact with its services programmatically. The API endpoints offer various functionalities, such as retrieving data, creating resources, and managing configurations. Setting Up the Python Environment Install Required Libraries To interact ...

Python Integration with GPT-4 (ChatGPT): A Comprehensive Guide with Examples

Python Integration with GPT-4 (ChatGPT): A Comprehensive Guide with Examples Integrating Python with GPT-4, the latest iteration of OpenAI's language model, unlocks the potential for creating powerful, AI-driven applications. This guide will walk you through the steps to set up and integrate GPT-4 with Python, complete with examples to get you started. Prerequisites Before diving into the integration, ensure you have the following: Python Installed: Ensure you have Python 3.7 or later installed. OpenAI API Key: You'll need an API key from OpenAI to access GPT-4. Step 1: Installing the OpenAI Python Client First, you need to install the OpenAI Python client. This client library allows you to interact with GPT-4 via API calls. bash: pip install openai Step 2: Authenticating with the OpenAI API Once installed, you need to authenticate your API requests using your OpenAI API key. python: import openai openai.api_key = 'your-api-key-here' Replace 'your-api-key-here...

Python Program to Create a Post on WordPress

Python Program to Create a Post on WordPress Creating a post on WordPress programmatically can be achieved using Python by leveraging the WordPress REST API. This approach allows developers to automate content publishing, making it particularly useful for tasks like content migration, bulk posting, or integration with other systems. In this article, we’ll walk through how to set up a Python script to create a post on a WordPress site. Prerequisites Before diving into the code, ensure you have the following: WordPress Site : A running WordPress site with administrative access. REST API Access : Ensure the WordPress REST API is enabled on your site. The API is enabled by default in most installations. API Authentication : You need to authenticate the API requests using Basic Authentication or OAuth. For simplicity, we’ll use Basic Authentication in this example. Python Environment : A working Python environment. You can use pip to install necessary packages. Step 1: Install Required Pyt...

Understanding the Python PIL save() Issue: "The fill character must be a Unicode character, not bytes"

  Understanding the Python PIL save() Issue: "The fill character must be a Unicode character, not bytes" When working with image processing in Python, the Python Imaging Library (PIL) is a popular choice. However, users might encounter issues when using the save() method of the PIL library. One such problem is the error: "The fill character must be a Unicode character, not bytes" This error usually arises in the context of saving image files with certain formats or when handling text within images. In this article, we'll explore the causes of this error and provide solutions to resolve it. What is PIL? PIL, also known as the Python Imaging Library, is a library that provides extensive capabilities for image processing. Although PIL is no longer maintained, it has been succeeded by the Pillow library, which is a more up-to-date fork of PIL. If you're using PIL, consider migrating to Pillow for better support and more features. The save() Method The save() ...

Take input from stdin in Python

The sys module in python helps us to access the variables maintained by the interpreter. It also provides functions to interact with the interpreter. To use sys in Python, we firstly import sys import sys There are a number of ways in which we can take input from stdin in Python. sys.stdin input() fileinput.input() Using sys.stdin: sys.stdin can be used to get input from the command line directly. It used is for standard input. It internally calls the input() method. It, also, automatically adds ‘\n’ after each sentence. Example: import sys        for line in sys.stdin:      if 'q' == line.rstrip():          break     print(f'Input : {line}')     print("Exit")  Output Using input(): input() can be used to take input from the user while executing the program and also in the middle of the execution. Example: # this accepts the user's input   # and stores in inp  inp = input("Type ...

Convert string to integer in Python

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers. Below is the list of possible ways to convert an integer to string in python: 1. Using int() function Syntax: int(string) Example: num = '10'    # check and print type num variable  print(type(num))      # convert the num into string   converted_num = int(num)     # print type of converted_num  print(type(converted_num))     # We can check by doing some mathematical operations  print(converted_num + 20)  As a side note, to convert to float, we can use float() in Python num = '10.5'    # check and print type num variable  print(type(num))...

Python - http — HTTP modules

http — HTTP modules http is a package that collects several modules for working with the HyperText Transfer Protocol: http.client is a low-level HTTP protocol client; for high-level URL opening use urllib.request http.server contains basic HTTP server classes based on socketserver http.cookies has utilities for implementing state management with cookies http.cookiejar provides persistence of cookies http.client — HTTP protocol client This module defines classes which implement the client side of the HTTP and HTTPS protocols. It is normally not used directly — the module urllib.request uses it to handle URLs that use HTTP and HTTPS. class http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None, blocksize=8192) class http.client.HTTPSConnection(host, port=None, key_file=None, cert_file=None, [timeout, ]source_address=None, *, context=None, check_hostname=None, blocksize=8192) For example, the following calls all create instances that connect to th...

Python - concurrent.futures — Launching parallel tasks

Python - concurrent.futures — Launching parallel tasks The concurrent.futures module provides a high-level interface for asynchronously executing callables. The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor. Both implement the same interface, which is defined by the abstract Executor class. Executor Objects class concurrent.futures.Executor An abstract class that provides methods to execute calls asynchronously. It should not be used directly, but through its concrete subclasses. submit(fn, /, *args, **kwargs) Schedules the callable, fn, to be executed as fn(*args **kwargs) and returns a Future object representing the execution of the callable. with ThreadPoolExecutor(max_workers=1) as executor:     future = executor.submit(pow, 323, 1235)     print(future.result()) map(func, *iterables, timeout=None, chunksize=1) Similar to map(func, *iterables) except: the itera...

Python - Assignment expressions

There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus. In this example, the assignment expression helps avoid calling len() twice: if (n := len(a)) > 10:     print(f"List is too long ({n} elements, expected <= 10)") A similar benefit arises during regular expression matching where match objects are needed twice, once to test whether a match occurred and another to extract a subgroup: discount = 0.0 if (mo := re.search(r'(\d+)% discount', advertisement)):     discount = float(mo.group(1)) / 100.0 The operator is also useful with while-loops that compute a value to test loop termination and then need that same value again in the body of the loop: # Loop over fixed length blocks while (block := f.read(256)) != '':     process(block) Another motivating use case arises in list comprehensions where a...

Recursion

What is Recursion?             A function calls itself is called recursion. Recursion is a useful technique. it is shorter and easier to write. Example: Factorial problems using Recursion.       Java int fact(int n){      if(n==1)         return 1;      else if(n==0)         return 1;      else return n*fact(n-1) } fact(5)       Python def fact(n):       if n==0:           return 1       return n*fact(n-1) print(fact(5))     

Data Structures

Data Structures A data structure is a special structure or format for organize and storing data. Data structure is a way of storing, organizing and manipulating data in a computer. In General data structures includes concepts like array, file, list, stack, queue, tree, graph etc. Data structures are classified into two types:               Linear Data structures:                       Elements are accessed in a sequential order. Example: Arrays, Linked List, stacks, queues               Non- Linear data structures:                         Example:: Trees , graphs