In addition to the tools used to effectively loop through data known as Itertools, Python offers its users many important operations and structures that facilitate a simpler dealing with the data. A for-loop-steppable data structure can be iterated over using the Python library called Itertools. Iterator algebra is created using this module as a quick, memory-efficient technique, either alone or in combination. This module includes features that make the optimal use of computing resources.

Additionally, using this module tends to make the code easier to read and maintain. Itertools is a built-in package in Python that enables us to manage the iterators effectively. They simplify the process of iterating across iterables like lists and strings. The Islice() is one such Itertools feature. This section is devoted to the islice approach in its entirety.

Syntax of the Itertools.Islice() Function in Python

The Itertools library’s “islice()” function extracts a segment from an iterable object between the elements specified by the function’s start and end arguments. It accepts an iterable object as input. The following is the normal syntax of the itertools.islice() function in Python:

itertools.islice(iterable, start, stop, step)

 
The functionality of the parameters specified in the itertools.islice() function is discussed in the following:

Iterables: Iterables are objects that produce iterators. Lists, tuples, strings, and dictionaries are some examples of common Python iterables.

Start: Start value establishes the location to start slicing from; examples of natural numbers are 0, 1, 2, 3, and so on.

Stop: Stop value establishes the place at which the slice ends; it slices up to the given number (exclusively). It may also be a natural number.

Step: Step describes the value’s increase or decrease.

The islice method of Itertools returns an iterator that, upon iteration or traversal, returns the individual values. Although the start, stop, and step values for the slice method can all be negative, this is not acceptable for the islice function which yields a ValueError.

Example 1: Program of Using the Itertools.Islice() Function with the Stop Parameter

We simply explained the working of the itertools.islice() function. The stop parameter is a single value given together with the iterable.

import itertools
 
i = itertools.islice(range(12), 5)
for values in i:
    print(values)

 

As already discussed, the islice() function is provided by the itertools module in Python. So, we have to include this module while deploying the islice() function. Here, we first added the itertools with the import keyword. Then, we defined a variable “i” to which we assigned the itertools.islice() function. The itertools.islice() function takes the range method as an input. The range value is also defined in the range method.

After that, we passed the stop parameter value to the islice function. The for loop is used to cycle over each value in the variable “i” and assigned to the new variable – “value”. The print method generates the result obtained from the “values” variable.

The outcome we have from the previous Python script is as follows:

Example 2: Program of Using the Itertools.Islice() Function with the Start and Stop Parameter

Here, we introduced another example of the itertools.islice() function. This time, the itertools.islice function takes the two parameters which are the start and stop parameters.

import itertools
 
iterate = itertools.islice(range(9), 0, 7)
for element in iterate:
    print(element)

 

We started our Python script by importing the module Itertools for utilizing the islice() function. Then, we established a variable with the name given as “iterate”. To the variable iterates, we have given an itertool.islice() function where the range method sets the range value and the start and the stop parameters value are assigned. The slicing takes place from the 0 starting index and stops at index 7 as we passed these values inside the function.

Then, we cycled the loop over each value in the iterating variable provided by the itertools.islice() function with the help of the for loop. We printed the results using a print statement.

The following is the result generated from the islice function with the start and stop index:

Example 3: Program of Using the Itertools.Islice() Function with the Step Parameter

As in the aforementioned illustrations, we passed the start and stop index values to the itertools.islice() function. Now, we have another parameter called the step parameter. We can also pass this step parameter along with the start and the stop index values. Let us implement the step parameter in the subsequent example:

from itertools import islice
x = islice(range(15), 2, 8, 1)
for item in x:
    print(item)

 

There, we introduced another technique to import the islice package from the Python Itertools as you can see in the script implementation. After importing the module of islice, we generated the variable as x. The variable is called the itertools.islice() function and sets the range value with the range method. Also, the itertools.islice() function sets the start index value, the step-index value, and the stop index value. Through the loop, we examined each value provided by the itertools.islice() function and printed the results.

The previous Python script generates the subsequent output:

Example 4: Program of Using the Itertools.Islice() Function to the List

Using the list() function, the iterator can be converted very efficiently. Let us discuss this with the following example code:

import itertools

sliced_value = itertools.islice(range(50), 0, 51, 2)
sliced_List = list(sliced_value)
print(sliced_List)

 

We first included the Itertools module in our script. Then, we have a variable “sliced_value” to which the itertools.islice() function is assigned. The itertools.islice() function takes the range method with the start, step, and stop values as an input. We created another variable “slice_List” where we have to invoke the list method. To the list method, the variable “slice_value” is passed as an input. This converts the islice value to the list values.

You can see that the list is generated in the following output:

Conclusion

The islice() method is discussed in this guide which is provided by the Itertools module of Python. The islice() technique uses an iterator to cycle over a list without requiring a memory because the elements are created as needed. It is a built-in function that you will use frequently to subsequence other sequences, and it frequently pairs with the various functions mentioned in the tutorial.



Source link


We cover the combinations() function by utilizing the Itertools. However, it is crucial to comprehend its utilization before delving further into the topic. Let’s first have a look at it. We frequently experience combinations or permutations when performing different calculations. But even though we may compute numbers, dealing with large values would be challenging sometimes. Think about what might occur if we had tools that could make this determination for users.

Itertools Package

Our requirements are precisely fulfilled by the Itertools package. Its reach extends beyond that, though. It offers additional methods that facilitate the other predefined operations as well. But this package is categorized into three types namely: Infinite Iterators, Combinatorics Iterators. and Terminating Iterators.

We would only discuss the combinations() function because this module is too important to describe in its entirety at this point. While proceeding, let’s look at how to deploy it, how to integrate it, and see what the combinations include.

Installation

Since this approach is built into Python, there is no installation procedure needed. Before utilizing it, we must integrate it. The following command could be used to accomplish it:

 

Definition of Combinations

When we think about combinations, we may define them as a method of organizing a group of objects. The order of the components in combinations is unimportant, therefore “xy” works similarly to “yx”.

Combinations() Method

The particular function is a component of the Itertools package’s combinatorics classification. This group includes the additional functions like products() and permutations(). The combinations() function, on the other hand, usually deals with every combination that could be feasible for the provided data collection.

To be more precise, the suggested method displays every unique data combination without any substitution. However, we may utilize the combinations_with_replacement() approach to display every combination with substitution. We must provide the parameters in proper order in both situations. Now, we will discuss how to utilize the combinations() method in Python.

Example 1:

By using the combinations() method, we will demonstrate the set of two-word combinations that are available with the letter “information” in this instance.

from itertools import combinations
 
str = ‘information’
a = len(str)
print(a)
 
combination = combinations(str,2)
 
x = [‘ ‘.join(j) for j in combination]
print(x)
print(len(x))

 

To start the code, we integrate the “combinations” package from the “itertools” framework. Now, we define the word “information” and that word is stored in “str” variable. We call the len() method to find the length of the specified letter. Then, we print the length of that letter. Using the word “information”, we have to obtain every possible combination. So, we apply the combination() function. We choose the number “2” to stand in for the total number of values in the set. We then call the join() function in the following step.

Along with this, we also utilize the “for” loop to obtain all the possible combinations of the defined word. To hold the possible combinations, we must define a variable “x”. Now, the print() function is used to display those combinations. Lastly, we find the total number of combinations with the help of the len() method and that length is shown by using the print() function.


Since we didn’t sort the letters in the previous instance, the defined string contains the letters in a lexicographical manner.

Example 2:

We will observe from the outcome of the preceding instance that the letters were not changed during the arrangement. We also have an option of replacement setups. The combinations_with_replacement() technique allows us to accomplish that. Here’s an illustration:

from itertools import combinations, combinations_with_replacement
 
w = ‘badminton’
m = len(w)
print(m)
 
combination = combinations_with_replacement(w,3)
 
c = [‘ ‘.join(l) for l in combination]
print(c)
print(len(c))

 

The “combinations” and “combinations with replacement” libraries from the “itertools” framework must be incorporated before we can start coding. Now, we specify the term “badminton” which is maintained in the variable “w.” To determine the length of the provided word, we utilize the len() function. Then, we show how long that letter was. We just want to identify every feasible combination using the word “information”.

In order to do this, we call the function combination with replacement(). The number of items we wish to include in the set is specified as “3”.We use the join() method in the following step. In addition, we use the “for” loop to get every possible combination of the specified term. To retain the possible combinations, an attribute called “c” has to be declared.

Now, the combinations are presented by using the print() method. In the final step, we use the len() function to calculate the total number of combinations and the print() method is used to display that length.

Example 3:

We probably need to retrieve the combinations from the Pandas dataframes. The lambda method will be used to accomplish it. Let’s look at the following scenario:

import pandas as pd
from itertools import combinations
 
d_f = pd.DataFrame({‘subj1’:(‘x’,‘z’), ‘subj2’: (‘i’,‘j’), ‘subj3’: (‘r’, ‘s’),  ‘subj4’: (‘a’, ‘e’)})
 
d_f[‘combinations’] = d_f.apply(lambda v: list(combinations(v, 2)), axis=1)
print(d_f)

 

We import two required header files which include “pandas” as “pd”, and “combinations” from the “itertools” module. We create a data set by using the DataFrame(). This function is associated with the pandas library. We define the elements of the data set within this function.

In the next step, we utilize the lambda and combinations methods. The lambda method contains two parameters. We specify the value of the axis here. To store the generated combinations, we insert a column into the dataset called combinations. Lastly, we represent the required data set with the help of the print() method.

Conclusion

The combination techniques from the Itertools package are discussed in this article. The syntax, setup, and importation procedures for it into the system are all demonstrated. Then, we looked at how to create the combinations of letters by using the combination functions and employing the various data types including strings and arrays. While utilizing the combinations() method, we make use of the dataframe module. In one instance, we performed the combinations with replacements and in another example, we performed the replacement-free combinations.



Source link


We are all aware that an object function and function constructor can be used to refer specifically to a class variable. The setattr() method is the only other alternative to this one. In dynamic programming, where the variable name is not static, the setattr() method is helpful. The dot operator is inapplicable in that situation. Using the user input as an illustration, it sets the value of an object attribute. A value is assigned to an object’s attribute using the setattr() function in Python. It accepts an object, a string, and an unspecified value as parameters but doesn’t provide any output. When we wish to give an object a new attribute and assign a value to it, it is useful.

You will gain knowledge about the setattr() method of Python in this article, while we cover what it accomplishes, when to employ it, and when it is unnecessary. Regardless of whether the attribute is present or not, the method is used to define an attribute’s value for an object.

Syntax of the Setattr() Function in Python

The following is the setattr() syntax that we deployed in a Python script:

setattr(set_object, set_variable, set_value)

 
The object.attribute parameter is set to equal value using the arguments name of the object, variable name, and value. This function does not throw any exceptions because any object property can be of a certain type. It returns Nothing to the calling function.

Example 1: Program of Using the Setattr() Function

The setattr() method shows how the object-oriented programming still works well in these situations and is highly useful if an object’s attributes can change while it is being utilized. Here is the program to demonstrate the working of the setattr() function:

class Employee:
    Emp_name = ‘Alice’
my_object = Employee()
print(«Before setattr employee name : «, my_object.Emp_name)
setattr(my_object, ‘Emp_name’, ‘Alice jeo’)
print(«After setattr employee name : «, my_object.Emp_name)

 

In the script, we first established a class that is represented with the name “Employee”. In the specified class, we created a class variable as “Emp_name”. The class variable “Emp_name” is set with the string value that is the name of the employee. Then, we defined an object as “my_object” and invoked the class “Employee”. The print is utilized here to print the value of the variable “Emp_name” before the setattr() function is deployed.

To the setattr function, we passed three inputs: my_obeject, the variable name “Emp_name”, and the modified value of the variable “Emp_name”. Then, in the last print statement, we printed the employee name after using the setattr() function.

The following is the outcome obtained from the previous script of the Python setattr() function:

Example 2: Program of Using the Setattr() Function Property

Here, we showed the property of the setattr() function in Python.

class Animal:
    animal_name = ‘Cat’
obj1 = Animal()

print(«Before setattr name : «, str(obj1.animal_name))

setattr(obj1, ‘animal_name’, None)

setattr(obj1, ‘detail’, ‘Persian kittens’)

print(«After setattr animal name : « + str(obj1.animal_name))
print(«After setattr animal detail : «, str(obj1.detail))

 

In the previous script, we defined the class to which we have assigned the name “Animal”. To the class “Animal”. We defined a variable as “animal_name” which is set with the string value of the animal’s name “cat”. Then, we have an object as “obj1” where the class “Animal” is invoked. Then, we printed the object by passing it in the str method before the setattr() function.

After that, the setattr() function is deployed where the “obj1” is passed. The “animal_name” variable is also passed with the value “none”. Here, we deployed another setattr() function to the new attribute and initialized it with the new value. The print statement is provided to print the object after the setattr() function.

The setattr() function results before and after utilizing it are shown in the following:

Example 3: Program of Using the Setattr() Function with Dict

Having the ability to set numerous attributes simultaneously is one benefit of utilizing the setattr() function. If you were given a dictionary of an object’s characteristics, what would it contain? To set them for the various attributes of an object, you can loop over them.

class MyDictClass(object)
    def __init__(self, dict1)
        for key in dict1:
            setattr(self, key, dict1[key])
if __name__ == «__main__»:
   
    dict1 = {«Student_Name»: «Edison»,
            «Student_ID»: «3278»,
            «Student_Degree»: «IT»}
   
    my_result = MyDictClass(dict1)
   
    print(«After the conversion of Dictionary to Class : «)
    print(my_result.Student_Name, my_result.Student_ID, my_result.Student_Degree)
    print(type(my_result))

 

In this particular script, we first defined the class “MyDictClass”. We called the object to the class. Then, we have a definition of the init method which takes the “self” and the “dict1” as arguments.

After that, we have the for loop which loops over each key and the value of the given dictionary. We then deployed the setattr() function where the self, key, and dict values are added. Then, within the main function of this script, we created the dictionary. After that, we passed that dictionary to the class “MyDictClass” with the help of the newly created object – “my_result”. In the end, we printed the result.

Example 4: Program of Using Setattr() Function with Exception

Here, we’ll construct the read-only attributes for the object. If we attempt to use the setattr() function to change the attribute’s value, an exception is raised.

class Product:

    def __init__(self):
        self._Function = None

    def Function(self):
        print(‘Function called’)
        return self._Function

    obj = property(Function, None)

p1 = Product()

setattr(p1, ‘obj’, ‘laptop’)

 

First, we have the class definition as “Product”. We defined the init method where the self as an argument is provided to the class. The variable is created as a “Function” that has a value set to none. Then, we defined the function of the previous variable, “Function”.

After that, we created an object as “obj” where we have the property name “function”. To the property function, we passed the variable “Function” and its value. The setattr() function is invoked to which we provided the p1, obj, and the new value which throws the exception.

You can see that the following exception is raised from the previous script:

Conclusion

This article taught us how to utilize the setattr() function to dynamically set the object attributes while an application is running. When the properties are unknown to the developer and an API needs to be flexible, this is a highly helpful way for the Object-Oriented Programming. You learned how to assign a value to an object’s attribute using the Python setattr() function. Your knowledge of defining the function with the setattr() function is also cleared. Then, you learned how to use the setattr() method while using it to set the attributes with a Python dictionary.



Source link


The list is a popular Redis data type that stores a sequence of strings based on the insertion order. One list can hold more than 4 billion elements. The unique fact about the Redis list is it maintains the HEAD and TAIL properties where the elements can be inserted from both sides. Usually, the LPUSH and RPUSH commands are used to insert the elements into a list. Meanwhile, the brand new list is created with the specified key. All the list commands behave the same way where a new list is created when passed with a non-existing key.


In addition, when all the elements are popped from the list, the associated key will be deleted from the Redis key space. Redis list is the ideal candidate for the low latency applications because the insertion and deletion operations have constant time complexity at the HEAD and TAIL. It doesn’t matter if five or thousand elements are in the list. The time for the insertion and deletion takes a constant time near the left and right ends.

There are some practical needs to remove the elements from the tail or head of a given list. The BRPOP and BLPOP commands are introduced from the Redis version 2.0.0 to fulfill the mentioned requirement. The BRPOP command is evaluated in this guide.

The BRPOP Command

The BRPOP is the advanced version of the RPOP command. The RPOP command pops an element from the tail of the list that is stored at a given key. As the name suggests, the BRPOP command is the Blocking version of the RPOP. When the key doesn’t exist, The BRPOP command won’t return with the nil value right away as in the RPOP command. Instead, it waits until a new list is created at that key. Upon the creation of a new list at the mentioned key, the BRPOP command pops the tail element. Also, this command accepts the multiple keys and only pop the elements from the first non-empty key.

Syntax:

The following is the syntax for the BRPOP command:

BRPOP list_key [list_key …] timeout

 
list_key: This is the key of the list.
timeout: This is the timeout value in seconds where the client is blocked until this timeout reaches.

Usually, the BRPOP command returns an array output:

If a non-empty list is specified, the command returns the popped element value and the key of the containing list as in the following format:

 

When no single element is to be popped from any of the lists specified and the timeout has expired, the nil value is returned.

 

Example: Radiodifusión Station Playlist Manipulation with BRPOP

Let’s assume that a radiodifusión station needs to play songs from a daily playlist. The playlist contains the song IDs to play. The songs should be ordered in the insertion order. Each song is picked from the end of the playlist to play.

We can use the Redis list data structure to implement the mentioned playlist and the list operations to manipulate the playlist songs. Let’s create a playlist called MidNightPlaylist and add some song IDs as shown in the following. The LPUSH command is used for that:

lpush MidNightPlaylist song001 song004 song010 song100 song101

 
This would create a list as shown in the following:

head> song101 | song100 | song010 | song004 | song001 <tail

 
Non-Blocking Behavior of the BRPOP Command

Now is the time to start a show. We should pick some songs from the end of the playlist. Hence, song001 should be removed from the playlist and it has to be played by the recorder. We use the BRPOP command to pop the song001 from the playlist and to get the song ID to the client listener.

 
The timeout argument is specified as five seconds. Since the MidNightPlaylist contains elements, the BRPOP command behaves in a non-blocking way. Hence, it pops and returns the tail element to the client.

Blocking Behavior of the BRPOP Command

The previous results can be achieved through the RPOP command as well. Hence, let’s look into the vivo advantage of the BRPOP command with the blocking behavior. Let’s remove all the elements from the MidNightPlaylist key using the RPOP command.

 
This removes all the remaining elements from the list and the MidNightPlaylist key is deleted from the Redis key space as well.

Let’s execute the BRPOP command with 60 seconds timeout and the non-existing key MidNightPlaylist. Now, the command behaves in a blocking manner. It waits for the key to be created and the element to be present in the playlist MidNightPlaylist.


Let’s push an element to the MidNightPlaylist via another terminal window that is connected to the same Redis data store.

lpush MidNightPlaylist song400

 
Upon the creation of the MidNightPlaylist list with the element song400, the client window which executed the BRPOP command pops the element song400 from the playlist and returns the song ID as output instantly.


Pick a Song from Multiple Playlists

There can be multiple playlists created by the radiodifusión station. Hence, we should pick a song from the given playlists at a given time. Let’s assume we got three playlists: MidNightPlaylist1, MidNightPlaylist2, and MidNightPlaylist3. The MidNightPlaylist1 is already empty while the other two playlists are non-empty.

lpush MidNightPlaylist2 song1002 song1005
lpush MidNightPlaylist3 song3000

 
Let’s call the BRPOP command with all the three keys as shown in the following:

brpop MidNightPlaylist1 MidNightPlaylist2 MidNightPlaylist3 10

 
Since the first key MidNightPlaylist1 is empty, it is ignored by the command here. It checks for the first non-empty key from the available key list. Hence, the command locates the MidNightPlaylist2 as the first non-empty key from the order of keys. As expected, the song1002 is removed from the MidNightPlaylist2.


The BRPOP command has constant time complexity near the head and tail when a single key is specified. The time complexity becomes O(N) when multiple keys are specified in the command. Furthermore, this command is very efficient to use in the low latency applications such as a queue, stack, timeline in social media, etc.

Conclusion

To summarize, a Redis list is a collection of string elements stored at a given key while sorted in the insertion order. Several commands are available to operate on the Redis lists with constant time complexity near the head and tail. As stated, The BRPOP command is used to remove the elements from the right side of the Redis list stored at a given key with the support of blocking. The BRPOP command blocks the client connection when no elements are available to remove from the specified lists. As you know, this command accepts multiple keys where an element pops from the first non-empty list where each key is checked in the order in which they are passed to the command.



Source link


Redis Sorted Set Members

Redis sorted sets store unique elements in an ordered manner. Hence, it can be used in low latency applications such as priority queues, real-time leaderboards, secondary indexing, etc. Each of these set elements is assigned a rank and placed in ascending order based on the score value. Several commands are available to add, update, and remove the sorted set members efficiently. The most important thing about sorted sets is that after the addition or removal of a set member, it still manages to maintain the member ranks and order.


The above figure shows the Redis sorted set element removal scenario and how it behaves when multiple members are removed from it. It manages to keep the correct order and index values by placing each member accordingly. In the next section, we will be looking into the sorted set remove operation in a detailed manner.

Removing Members With ZREM Command

The ZREM command is used to remove one or more members from a sorted set stored at a specified key. This command has logarithmic time complexity. If the command is used to remove one element, then the time complexity is proportional to the logarithmic value of the number of elements. If multiple elements have been specified to remove, then it will be O(number_of_elements_to_remove* log(total_number_of_set_elements)).

Syntax

ZREM sorted_set_key member [member …]

 
sorted_set_key: This is the unique identifier where the sorted set is stored at.
member: This is the member supposed to be removed.

The ZREM command will remove the specified members from the sorted set. It will return an integer reply which is the number of removed members. Whenever you specify a non-existing member, it will be skipped. Also, the command will throw an error if the given key doesn’t hold a sorted set.

Example – Manage Customer Order Queue With Redis ZREM

Let’s take a real-world scenario where a restaurant serves its customers based on the first-comers assigned with the highest priority. Upon serving the highest priority customers first, the restaurant should remove each customer entry from the queue. Redis sorted set will be an ideal data structure to implement this scenario in a memory-effective and efficient manner.
Each member of the Redis sorted set looks like the following.


As shown in the above illustration, each time a customer has been served by the restaurant, that member needs to be removed from the sorted set. We can use the ZREM command to achieve that.

Let’s add the four customers shown in the above figure. We will be using the ZADD command to create the sorted set customerqueue and add four members, as shown in the following.

zadd customerqueue 1 customer:10
zadd customerqueue 9 customer:1
zadd customerqueue 7 customer:6
zadd customerqueue 5 customer:2

 

Let’s inspect the sorted set using the ZRANGE command.

zrange customerqueue 0 10 WITHSCORES

 
Output:


As expected, the sorted set customerqueue has been ordered based on the priority value.

Delete a Member from the Sorted Set

The customer:10 who has the highest priority will be served first. Hence, the customer:10 members have to be removed from the sorted set. Let’s use the ZREM command to remove the member.

ZREM customerqueue customer:10

 
Output:


As expected, the return value is 1, which means one entry has been removed. Let’s inspect the customerqueue again.


The member customer:10 has been deleted successfully.

Delete Multiple Members from the Sorted Set

Let’s say both customer:2 and customer:6 have been served from two windows parallelly. Hence, we should delete both the members from the sorted set. We can use the ZREM command to delete both members at merienda.

ZREM customerqueue customer:2 customer:6

 
Output:


As expected, the return value is 2, which indicates two members have been deleted. Let’s inspect the whole sorted set again.


The ZREM command is recommended to use whenever you need to remove elements from a sorted set.

Conclusion

To summarize, the ZREM command is used to remove one or multiple elements from a Redis sorted set stored at a given key. It simply deletes the specified members from the sorted set. Also, the order will be kept in the resulting sorted set. As stated above, it has a logarithmic time complexity which makes the command to be used in real-time applications. Hence, the ZREM command is recommended to use whenever you need to remove elements from a sorted set.



Source link


“The “setenv ()” function is used in C programming for adding or updating a variable in the environment which is in the calling process. This “setenv ()” function contains three parameters. The envname, envval, and the overwrite are the three parameters of this “setenv ()” function in C. When we want to update or add some new variable in the environment, then, we utilize this “setenv ()” function. It is not mandatory for setenv () to be re-entrant. A function doesn’t need to be thread-safe if re-entrant behavior is not necessary.

In this guide, we will explore this concept in deep detail and will provide codes where we will utilize the “setenv ()” function in C programming. We will also discuss the syntax of this “setenv ()” function here in detail in this guide and will show you how to pass the parameters to this “setenv ()” function in C programming.”

Syntax

The syntax of this “setenv ()” function is here below: Look at this, and you will easily understand the parameters of this “setenv ()” function in C code.

int setenv (const char *envname, const char *envval, int overwrite);

 
In this “setenv ()” function, we have three parameters, as you have seen above in the syntax of this function. The first parameter is an environment variable’s name that must be added or changed as indicated by the envname parameter, which points to a string. The value toward which envval refers must be used as the environment variable value. If envname refers to a string that contains the character “=,” the “setenv ()” must fail. The “setenv ()” must return success and change the environment if the name envname of the environment variable exists here and the value of overwrite is not equal to zero.

The function must restore success, and the environment must not change in case the name envname of the environment variable exists here and the relevant value of overwrite is zero.

Example # 1

Ubuntu 20.04 will be used for the examples demonstrated in this guide. We first installed Ubuntu 20.04 and entered some commands for installing the GCC compiler. We must install this GCC compiler so that we will do this code in C programming in Ubuntu 20.04. When this compiler is installed in Ubuntu 20.04, then we open the text editor for coding on it and start typing some code lines in which we will utilize the “setenv ()” function in C programming. We use several header files in this text editor at the beginning of the C code. When writing C code, all we need to do is add the header files; otherwise, we won’t get the functions we require in our C code. You can see that we placed the standard input and output header file, “stdio.h”, on the first line of the code in this example.

Then we place another header file which is “stdlib,” here it is used for including different functions, and it is the standard library in C. After this, we create or declare an “extern char” with the name “environ,” and below this, we are using the “int main ()” function. We are passing three parameters to this “main ()” function. The first parameter is “int argc”, the second parameter is “const char *argv []”, and the last parameter of this “main ()” function is “const char *envp []”. Then we utilize the “printf” function; we use this function when we want to render some statements on the screen. We utilize two different “printf” here and put “%p” inside the “printf” statements. This “%p” is used for displaying the pointer data type in C codes.

Below this, we are utilizing the “setenv ()” function. We pass three parameters here. The first parameter is used for indicating an environment variable’s name that must be added or changed. The value toward which the second parameter implies must be utilized as the environment variable value. And the third parameter here is non-zero, so it means that the “setenv ()” returns success, and the value of the environment variable will be changed. Then we have “puts ()” here, which we utilize for rendering the line on the terminal. The line which we write in this “puts” will render on the output terminal.

After this, we again utilize two “printf” statements below this “puts”. And again, use the “environ” and “envp” in separate “printf” statements and again utilize “%p” here. Both statements will display on the screen. Then we have the “exit ()” statement and pass “EXIT-SUCCESS” here as the parameter of this “exit ()”. Here the code is completed, and now we just need to save this file, and we must put the “.c” file extension with the name of the file.


Now, open the terminal of Ubuntu 20.04. We put the first GCC command after launching the terminal, which aids in compiling this c code. We use the other command, which is used to run C code after this code has been executed. These commands are also indicated in the picture below. It displays the outcome of the code which we have created above. Here, notice that the value of “environ” has changed, but the “envp” pointer still has the identical value after the call.

Conclusion

This guide shows how to use the C programming function “setenv ()”. Here, we have given a full description of the “setenv ()” function and examples of how to utilize it in our C programming codes. We have also provided the output here to make it easier for you to understand how to utilize the C “setenv ()” function and how it returns the output. As previously mentioned, this “setenv ()” function is used for adding or updating a variable in the environment, which is in the calling process in C programming, and we also discussed that we must pass three parameters for this “setenv ()” function. We expect that this guide should assist you in gaining a deeper grasp of C programming functions.



Source link


GoTTY is a lightweight Go language-based command-line application that enables Raspberry Pi users to access and control the device terminal on their browsers. It turns your CLI tools into a web application, thus allowing you to see your Raspberry Pi terminal using the IP address of your device. It’s useful when someone wants to access your device terminal to work on a project.

In this article, we will show your how you can share your Raspberry Pi terminal by installing GoTTY.

Share Raspberry Pi Terminal: Install GoTTY on Raspberry Pi

You cannot install GoTTY directly on your Raspberry Pi device because the Raspberry Pi repository doesn’t have its repository. However, you can easily install this application by downloading the tar.gz file from the GitHub website. The steps to successfully perform the GoTTY installation on your Raspberry Pi device are given below:

Step 1: Download GoTTY tar.gz File

To download GoTTY tar.gz file on your Raspberry Pi device, you can use the following command:

$ wget -O gotty.tar.gz https://github.com/yudai/gotty/releases/latest/download/gotty_linux_arm.tar.gz

 

Step 2: Extract GoTTY contents From tar.gz File

After successfully downloading GoTTY tar.gz file, you can extract its contents through the below-mentioned command:

 

Step 3: Move GoTTY to Bin Directory

Next, you will need to move the GoTTY directory to the binary file location “usr/recinto/bin” using the following command:

$ sudo mv gotty /usr/recinto/bin

 

Step 4: Grant Permission to the File

After moving the GoTTY directory to binary file location, you will need to grant permission to the file using the following command:

$ sudo chmod a+x /usr/recinto/bin/gotty

 

Step 5: Check GoTTY Version

You can execute the following command to confirm the installation of the latest version of GoTTY on your Raspberry Pi device.

 

Step 6: Remove GoTTY tar.gz file

With the installation now successfully completed, you can remove the unnecessary GoTTY tar.gz using the following command:

 

Step 7: Access Terminal From Browser

To access the Raspberry Pi terminal on your browser, you will first need to run the following command to run GoTTY service on your device:

 

Within the terminal, you will be able to see the URL to access the GoTTY web interface on your browser.


Head back to your Raspberry Pi terminal, and use “CTRL+C” one time. When you see the message “Send ^C to force exit”, add the following command below this message and then press Enter.

$ gotty -w nano myfile.txt

 

Go back to your browser and reload the page again and you will be able to see your file opened on the browser and you can edit it easily without going back to your Raspberry Pi terminal.


The above image shows that you have successfully got access to your device terminal through GoTTY. You can also access the Raspberry Pi configuration on any browser by applying the following command:

$ gotty -w sudo raspi-config

 

 

The addition of “w” in the above commands is necessary as this allows you to manage the writing operation on your browser.

Removing GoTTY From Raspberry Pi

In case you no longer want to use the GoTTY service on your Raspberry Pi device, you can remove its binary file any time through the following command:

$ sudo rm -rf /usr/recinto/bin/gotty

 

Conclusion

GoTTY is a useful command-line utility that allows you to control the Raspberry Pi terminal from the browser. You can set up this application by downloading and extracting the tar.gz file on your Raspberry Pi and then executing the permission to the binary file to successfully install the utility on your device. To start working on your device terminal from the browser, you need to execute a command with “gotty -w” at the beginning so that you can access it on your browser.



Source link


“The two most significant challenges that server administrators face when attempting the SASL configuration on Linux or any other platform are the installation channel and the choice of the mechanisms you want to support with SASL.

You can install SASL using the tarball installation method or the UNIX package installation methods. Again, there is an array of mechanisms that SASL can support.

You can choose to support plaintext mechanisms such as LOGIN and PLAIN mechanisms. You can also opt for any type of shared secret mechanism. Shared secret mechanisms include CRAM-MD5, SCRAM, or DIGEST-MD5. Finally, Kerberos authentication protocol users may also choose GSSAPI for Kerberos 5 or KERBEROS_V4 for Kerberos version 4.

This article is specific and will discuss the SASL installation using the shared secret mechanism (CRAM-MD5). Again, this article will use the LDAP protocol. Thus, only attempt going through this guide merienda you have LDAP-SASL properly running in your systems.”

Let us get into the step-by-step guide!

Step 1: Download and Install the Berkeley DB

Firstly, you will need to download the SleepyCat 4.2.52. Proceed to compile and unpack the bundle manually into your systems. Merienda done with the downloading process, follow the instructions listed in the docs/index.html file within the directory from which you unpacked the .tar.gz packages. Since we are using an auxprop plugin, we will use the Berkley DB.

You can run the following commands after you unpack the packages;

Step 2: Download Cyrus SASL 2.1.17

With the first step done, the next step will be to download SASL. Proceed to unpack it and follow the instructions on the doc/install.html in the directory from which you unpacked the .tar.gz file. Ensure that you use the environmental parameters when running the configuration of SASL, as shown in the figure below.


Ensure that the LDFLAGS and CPPFLAGS env parameters lib and include directories on which you installed the Berkley DB files. Merienda you ascertain this, you can run these commands;

Step 3: Install and Configure OpenLDAP 2.2.5

This step is one of the most critical steps in this guide since we will use LDAP as the protocol. Of course, you can use a module of your choice here. Download OpenLDAP and install it by using the directions provided in the document. Proceed to configure it the same way you configured SASL.

This command should help;


Merienda done with that, go ahead and run these commands;

Step 4: Create the SASL User Database

Use the below command to create a user database;


When run successfully, the above command prompts you for a password. Your user name at this point should not be a distinguished name (DN). Note that it is also the same password you will use for your admin entry.

Step 5: Set the sasl-regexp Directive

It is time to set up the sasl-regexp Directive, which is available in the slapd.conf file. Ensure that you do this before starting or running the SLAPD and testing any authentication processes. You will find the slapd.conf file in the /usr/específico/etc/openldap, and this command will help.


Of course, the above parameter exists in the

uid=<username>,cn=<realm>,cn=<mech>,cn=auth format.

Take the user name from SASL and insert it in the LDAP search string where you see kenhint. Again, your realm should be your fully qualified domain name or FQDN. You can use the following command to find your realm;


We will use linhint.com as our realm, and a fully qualified name should have at least a single dot. Thus, our credentials will look like this;


You can continue to add entries into your LDAP directory using this command;

Step 6: Start the slapd Daemon

Finally, start the slapd daemon as this is your final stage of configuring SASL to use DIGEST-MD5. You can then use the ldapsearch command to query your system as in the example below;

Conclusion

This article highlighted how to configure SASL to work with LDAP and on a DIGEST-MD5 mechanism. Other variations exist on how to use SASL with other protocols and various SASL mechanisms. Hopefully, you can now go through this process without any serious challenges.

Sources



Source link


The bottom command is an open-source command-line utility that enables Linux users to preceptor the performance of their systems, such as CPU resources, system temperature, memory information, network resources and much more. Since this tool supports both Linux and ARM-based architecture, thus you can install it on your Raspberry Pi to preceptor your device performance.

This article shows you the most straightforward approach to install the bottom command on Raspberry Pi to preceptor your system performance.

System Monitoring on Raspberry Pi Using the bottom Command

You cannot install the bottom command directly on your Raspberry Pi device; however, you can install a deb package for the GitHub website according to your system architecture using the following steps:

Step 1: Update Raspberry Pi Source List

Before installing the bottom utility on your Raspberry Pi device, you must update the current packages on your system through the following command:

$ sudo apt update && sudo apt upgrade

Step 2: Download bottom Utility Deb Package on Raspberry Pi

Next, you will need to download bottom utility deb package on Raspberry Pi for 64Bit Raspberry Pi OS and to do this apply the following command:

$ wget https://github.com/ClementTsang/bottom/releases/download/nightly/bottom_aarch64-unknown-linux-gnu.deb

You can also find a 32Bit version of the deb package for your Raspberry Pi from GitHub website and to download this version, you just need to replace the version in the above command.

Step 3: Install bottom Utility Deb Package

After successfully downloading the deb package, run the below-mentioned command to install the bottom utility on your Raspberry Pi device:

$ sudo apt install ./bottom_aarch64-unknown-linux-gnu.deb

Make sure to replace the version of the bottom in the above command as well.

After completing the installation, apply the following command to confirm the latest version of the bottom version installed on your Raspberry Pi.

Step 4: Run bottom Utility on Raspberry Pi

To get the information about your Raspberry Pi system’s resources, you have to apply the following command:

The above result shows the system resources on your Raspberry Pi terminal and if you want to have further information about your device resources, you can issue the following command for help:

From the help section, you will see several commands ranging from basic to complete and you can use these commands to get the overview of your device resources.

Remove bottom Utility From Raspberry Pi

In case you are not interested in using the bottom utility services on your Raspberry Pi device, you can easily remove it using the following command:

$ sudo apt remove bottom-arm64 -y

Conclusion

The bottom is a lightweight system monitoring tool that displays your Raspberry Pi device information onto the terminal window. You can install this application easily on your device by downloading the deb package and through an apt installer. The detailed step-by-step instructions are already provided in the above-given guidelines.



Source link


The SD is the backbone of your Raspberry Pi device because, without it, you won’t be able to use an operating system on your device. The reason is that most operating systems don’t support USB boot on your Raspberry Pi device. Thus, having a good-speed SD card is necessary for the users to enjoy a smooth desktop environment. If you somehow purchase an SD card for your Raspberry Pi device and you don’t have information about whether the card is good enough for a smooth desktop experience, you should need to perform an SD card test.

This article provides a way to determine your Raspberry Pi card speed, as this will help you continue with the current SD card or purchase a new one for your device.

Raspberry Pi SD Card Speed Test

There are two simple methods through which you can perform a speed test for your Raspberry Pi SD card:

  1. SD Card Speed Test Using Agnostics
  2. SD Card Speed Test Using the dd Command

The details of both these methods are discussed as below.

1: SD Card Speed Test Using Agnostics

One of the simplest ways to perform SD card speed test is using the Agnostics tool, which is pre-installed on your Raspberry Pi device. However, if you don’t have then you can install it anytime using the following command:

$ sudo apt install agnostics -y

To open this tool, head to the Raspberry Pi menu, and in the “Accessories” option, click on the “Raspberry Pi Diagnostics”.

This will open up the following screen on your Raspberry Pi desktop, where you will be able to run a SD card speed test merienda you click on the “Run Tests” button.

If you find the output result as PASS, it means that your SD card is fast enough to provide you with a smooth desktop experience and if it outputs the result as FAIL, then you should need to replace your SD card as soon as possible.

2: SD Card Speed Test Using the dd Command

You can also find detailed information about your SD card speed test using the dd command, which provides information related to your SD card write and read speed performance.

To find out the SD card write speed performance, we are creating 100MB of free storage space and five blocks of 20MB each. You can change this preference according to your choice as greater storage space provides better results but requires more time. With this information, you can apply the following command in your Raspberry Pi terminal to find out the write speed performance of your SD card:

$ dd if=/dev/zero of=./speedTestFile bs=20M count=5 oflag=direct

From the above command, “if” and “of” are used for reading and writing from a source file to destination file respectively. While the “/dev/zero” is a built-in special Linux file that is used to fill the memory of any kind where all bits are set to zero. This file is mostly utilized in the reading and writing process. The result in the last row shows the time spent and promedio speed of the writing operation on your SD card.

To find out the read speed information of your SD card, issue the following command in the terminal:

$ dd if=./speedTestFile of=/dev/zero bs=20M count=5 oflag=dsync

From the above command, we are reading the data from the previously generated source file, so in that case, we use the “if” command to read from the source file and uses the oflag as dysnc instead of direct. While the output in the last row shows the time spent and promedio speed of the reading operation on your SD card, which should always be greater than the write speed.

Conclusion

Raspberry Pi SD card speed test is an important test that every user must perform to keep a check on the card performance. The easiest way to perform an SD card speed test is to use the Raspberry Pi Diagnostics from the Raspberry Pi menu, where you will be able to find out whether your SD card can provide you with adequate performance or not. You can also find out the write and read speed of your SD card using the dd command, which is crucial if you have proper knowledge of SD card reading and writing speed.



Source link