Trending March 2024 # How To Use Sqlalchemy Async With Examples? # Suggested April 2024 # Top 7 Popular

You are reading the article How To Use Sqlalchemy Async With Examples? updated in March 2024 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 How To Use Sqlalchemy Async With Examples?

Introduction to SQLAlchemy Async

The SQLAlchemy async is one of the extension types. It is more connected by using the AsyncEngine with the help of the create_async_engine() method, which helps to create the instance of the ayncengine based on their version of the traditional engine API and also the connect() and begin() transaction methods which deliver both asynchronous context type managers that help for AyncConnection to invoke the statements in the server-side aync results.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

What is SQLAlchemy Async?

SQLAlchemy async is one of the features, and it has the default methods for operating the application functions from the front end to the back end. It always creates the instance using the create_aync_engine() method for the AsyncEngine, which offers more for the async version of the traditional engine API. Using the Asyncio platform, which guided and extended the required python version libraries, depends upon the greenlet library on the default machine. With the help of the pip command to install the sqlalchemy asyncio libraries. The greenlet libraries do not support the current default files. It satisfies the architectures on the platform usages for setting up the extra tools with the help of an asynchronous programming thread.

How to Use SQLAlchemy Async?

Asynchronous programming is one of the programming patterns that mainly enables the code to run with a separate application thread. It is supported by ORM and Core and includes the asyncio imported class feature for calling and utilizing the product. The limitation is available for the async feature with the ORM mapping and notified with the lazy loading concept to upload the Core and ORM package feature. And also, there is a new way of creating the queries with significant versions of the SQLAlchemy with boilerplate codes for spoiler alerts on the syntax query essential for each session object directly called for the users and mapped the ids accordingly supported for declarative mapping with data classes and attributes. The ORM layers of the async capabilities joined with the other types of queries with different Routes to add the entries.

The sqlalchemy models will declare the models in a subclass of the declarative style that works well with the verbose the sqlalchemy engine will create with the help of the create_async_engine() method. For this, each user session is calculated using the AsyncSession class with additional parameters like echo=True for passing the engine instance initialization to generate the sql queries based on the user dependencies, and its behaviors are calculated the session expire with parameter expire_on_commit= true or false boolean statements. This is mainly because of the async settings with sqlalchemy sql queries to perform the database operations which are already accessing the committed objects.

The above diagram shows the difference between the synchronous and asynchronous requests on the sqlalchemy models. In synchronous at a single time request is performed, but asynchronous is the multiple requests passing at a single time.

SQLAlchemy Async Create Models

There are different ways to use and declare the sqlalchemy models will use the declarative subclass types works and perform well with the less verbose. It has n number of column fields to store and retrieve the values using the AsyncSession class imported from the sqlalchemy.ext.asyncio. The create_async_engine class is imported from the sqlalchemy.ext.asyncio packages.

We must use the create engine to connect the databases from the front end to back end operations.

1. Init_model()

It is one of the default functions that can be used to declare the async with the specific definition. Then additionally, we can call the engine.begin () method for performing the database engine connectivity operations from the sqlalchemy packages. But, first, we need to install the sqlalchemy async using the pip command below.

Mainly we can use the below API called Fastapi. The fastapi_asyncalchemy package is installed and imported first to utilize the model’s classes.

Code:

from fastapi_asyncalchemy.models import *

init_model() is the type of the event loop that is only commanded with the CLI command for python execution of the additional arguments.

2. FastAPI Routes

The fast api is the main package that comes under the separate asyncalchemy for the sqlalchemy user and asyncsessions.

Code:

From fastapi import FastAPI From fastapi import Depends From sqlalchemy.ext.asyncio import AsyncSession

The above packages are first imported before the async operations start, then the below packages are imported to connect the database models with additional services.

Code:

From fastapi_asyncalchemy.db.base import init_models From fastapi_asyncalchemy.db.base import get_session From fastapi_asyncalchemy import service

Based on the user requirement and its dependencies, the session can be injected with Depends of the routes that will be created a new session. Finally, we can retrieve the datas by using the await() function.

Code:

Employee.py:

from fastapi_users.authentication import JWTAuthentication from fastapi_users.db import SQLAlchemyUserDatabase from chúng tôi import database from .models import Employee from .schemas import EmployeeDB emp = Employee.__table__ a = SQLAlchemyUserDatabase(EmployeeDB, database, emp) SECRET = "dhfh67ewtf8wgf6ewgc8y28g8q893hc7808fwh7w4bynw74y7" tests= [ JWTAuthentication(secret=SECRET, lifetime_seconds=3600), ]

Models.py:

from empls_EmployeeDB import SQLAlchemyBaseUserTable, SQLAlchemyUserDatabase from sqlalchemy import Column, String, Integer, DateTime, Boolean from chúng tôi import Base class Employee(Base, SQLAlchemyBaseUserTable): name = Column(String, unique=True) dob = Column(DateTime) emp = Employee.__table__

Schema.py:

import uuid from typing import Optional import pydantic from empls import models from pydantic import EmailStr, BaseModel class Employee(models.BaseUser): class Test1: orm_mode = True class Test2(BaseModel): id: Optional[str] name: str = "SIva" @pydantic.validator("id", pre=True, always=True) def default_id(cls, v): return v or str(uuid.uuid4()) class Test1: orm_mode = True class Test3(Employee, models.BaseUserCreate): name: str class Test4(Employee, models.BaseUserUpdate): pass class EmployeeDB(Employee, models.BaseUserDB): pass

Routees.py:

from fastapi import APIRouter from emps import empl rout = APIRouter() rout.include_router(empl.router, prefix="/empl")

main.py:

from fastapi import FastAPI from chúng tôi import database from routes import Routees from core.empls import empls app = FastAPI() @app.on_event("empdet") async def empdet(): await database.connect() @app.on_event("empresign") async def empresign(): await database.disconnect() app.include_router(Routees) app.include_router(empls.router, prefix="/employees", tags=["employees"])

Outputs:

The above codes are the basic format for creating the sqlalchemy aync model using the fastAPI imported packages in the python libraries. Routing is essential for mapping the database schema model from the front end to the backend.

Examples of SQLAlchemy Async

Different examples are mentioned below:

Example #1

Code:

import asyncio from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String from sqlalchemy import Table from sqlalchemy.ext.asyncio import create_async_engine md = MetaData() a = Table( "emps", md, Column("id", Integer, primary_key=True), Column("name", String) ) async def async_main(): eng = create_async_engine( 'sqlite:///Mar9.db', echo=True, ) async with eng.begin() as con: await con.run_sync(md.drop_all) await con.run_sync(md.create_all) await con.execute( a.insert(), [{"name": "12"}, {"name": "Welcome To My Domain"}] ) async with eng.connect() as con: res = await con.execute(a.select()) print(res.fetchall()) res = await con.stream(a.select()) async for outs in res: print(outs) asyncio.run(async_main())

Output:

In the above example, we first imported all the required libraries like sqlalchemy import all the table columns and asyncio import drivers.

We mainly used the create_async_engine to perform the asynchronous operations in the application task.

Next, we created a basic table-like emps using the Table() method with additional parameters like columns() with value name and datatype.

Finally the main method is executed on the asyncio.run(async_main()) parameters.

Example #2

Code:

from typing import List import databases import sqlalchemy from fastapi import FastAPI from pydantic import BaseModel engs = 'sqlite:///Mar9.db' db = databases.Database(engs) md = sqlalchemy.MetaData() news = sqlalchemy.Table( "engss", md, sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), sqlalchemy.Column("name", sqlalchemy.String), sqlalchemy.Column("city", sqlalchemy.String), ) vars = sqlalchemy.create_engine( engs, connect_args={"Welcome": "Tup"} ) md.create_all(vars) class funs(BaseModel): name: str city: str1 class funs1(BaseModel): id: int name: str city: str1 app = FastAPI() @app.on_event("first") async def first(): await database.connect() @app.on_event("second") async def second(): await database.disconnect() @app.get("/engs/", response_model=List[ab]) async def funsss2(): qury = engs.select() return await database.fetch_all(qury) @app.post("/engs/", response_model=funs1) async def funsss(ab: funs): qury1 = engs.insert().values(name=ab.name, city=ab.city) vars2 = await database.execute(qury1) return {**a.dict(), "id": vars2}

Output:

In the second example, we used Fast API in the sqlalchemy packages to perform the async operations.

The packages are first imported with the required libraries, classes, keywords, and methods.

The fast api packages have methods like first() and second() and the async and def keywords.

These keywords are performed to store and retrieve the multiple results using the await keyword.

Conclusion

The sqlalchemy has many features and must be implemented and satisfied with the required libraries. Like that, async is the keyword and feature for performing the database operations like storing and retrieving the datas with multithreaded or multiple requests are called and performed at a single time instance.

Recommended Articles

This is a guide to SQLAlchemy Async. Here we discuss the introduction; SQLAlchemy async creates models and examples. You may also have a look at the following articles to learn more –

You're reading How To Use Sqlalchemy Async With Examples?

How To Use Java Serversocket With Examples

Introduction to Java ServerSocket

The following article provides an outline on Java ServerSocket. In web technology, we have used front end and backend codes separately for creating web applications for the secure chúng tôi web application contains servers for receiving the client request and sent to the response for the clients’ particular request. In java technology, with the help of socket programs, we can achieve these tasks when we will send multiple requests with the help of multiple pcs, which has to be connected with the protocols like tcp and udp. We can write the server codes like ServerSocket class, connect with the specified ports, and send them to the data.

Start Your Free Software Development Course

Syntax:

The serversocket class is used for the client and server transfer process.

Server Class:

java packages import(import java.io.*,import java.net.*) class serverclassname { public static void main(String[] args) { try { --some logic— } catch() { } } }

Client class:

Java packages import(import java.io.*,import java.net.*) class clientclassname { public static void main(String[] args) { try { --some logic— } catch() { } } } How to use Java ServerSocket?

Java server socket connections will use the two types of protocols for sent and receive the data.

TCP(transfer control protocol) and udp(user datagram protocol) will use the sockets class to transfer the data.

We also see some difference between these two protocols while we use in the socket class when we use udp, it means is a connection less, and there are no sessions for storing the log data regarding client and server transmissions, but in tcp, it is a connection-oriented, so the client and server have the session storages in the log folders.

The socket programs will be used for communications between the web applications running with the different jre.

The serversocket class are mainly with the connection-oriented socket programs.

When we connect the applications with the help of socket, we need to get the information’s like IP Address of the servers and port numbers which has to be connected with the applications for a specified way so that the data transmission will not be interpreted.

Basically, the socket class between client and server is one-way data transmission. The client will send the request messages to the server, servers read the client messages, and send the response to the client, or else it will display the data on the client screen like browsers.

So that we will use two types of java net classes are used a socket and serversocket classes; the socket class is responsible for client-server communications, serversocket class is used for server-side applications it will authenticate the request from the client-side until the client machine is connected with the socket class after the successful connections it will return the socket class instance in the server-side applications.

Examples of Java ServerSocket

Given below are the examples:

Example #1

Code: Client Example

import java.io.IOException; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class clientSample { public static void main(String arg[]) throws UnknownHostException,IOException { int n,n1; String s; Scanner sc=new Scanner(System.in); Socket s1=new Socket("127.0.0.1",1408); Scanner sc1=new Scanner(s1.getInputStream()); System.out.println("Enter any port numbers"); n=sc.nextInt(); PrintStream p=new PrintStream(s1.getOutputStream()); p.println(n); n1=sc1.nextInt(); System.out.println("Square of the given port number is: "+n1); } }

Output:

import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class ServerSample { public static void main(String[] args)throws IOException { int n,n1; String s; ServerSocket s1=new ServerSocket(1408); Socket s2=s1.accept(); Scanner sc=new Scanner(s2.getInputStream()); s=s2.toString(); n =sc.nextInt(); n1=n*n; PrintStream p=new PrintStream(s2.getOutputStream()); p.println(n1); System.out.println("Server started and working.. "); } }

Output:

Example #2

Code: Client Example

import java.net.*; import java.io.*; public class clientSample { public static void main(String[] args) throws Exception { try{ Socket s=new Socket("127.0.0.1",8888); DataInputStream d=new DataInputStream(s.getInputStream()); DataOutputStream out=new DataOutputStream(s.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String client="",server=""; while(!client.equals("")){ System.out.println("Enter the number :"); client=br.readLine(); out.writeUTF(client); out.flush(); server=d.readUTF(); System.out.println(server); } out.close(); out.close(); s.close(); }catch(Exception e){ System.out.println(e); } } }

Code: Server Client

import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; class ServerClients extends Thread { Socket sockets; int clients; int squre; ServerClients(Socket s,int count){ sockets = s; clients=count; } public void run(){ try{ DataInputStream inStream = new DataInputStream(sockets.getInputStream()); DataOutputStream outStream = new DataOutputStream(sockets.getOutputStream()); String client="", server=""; while(!client.equals("")){ client=inStream.readUTF(); System.out.println("From Client side-" +clients+ ": Number of client is :"+client); squre = Integer.parseInt(client) * Integer.parseInt(client); server="From Server to Client request-" + clients + " Square of the client " + client + " is " +squre; outStream.writeUTF(server); outStream.flush(); } inStream.close(); outStream.close(); sockets.close(); }catch(Exception ex){ System.out.println(ex); }finally{ System.out.println("Client -" + clients + " exit!! "); } } }

Code: Server Example

import java.net.*; import java.io.*; public class ServerSample { public static void main(String[] args) throws Exception { try{ ServerSocket s=new ServerSocket(8888); int count=0; System.out.println("Server is Started ...."); while(true){ count++; Socket socket=s.accept(); ServerClients sc = new ServerClients(socket,count); sc.start(); } }catch(Exception e){ System.out.println(e); } } }

Output:

Example #3

Code: Client Program

import java.net.*; import java.io.*; public class ClientMain { public static void main (String[] args ) throws IOException { int size=1022388; int bytess; int c = 0; Socket sockets = new Socket("localhost",12345); byte [] bytes = new byte [size]; InputStream in = sockets.getInputStream(); FileOutputStream out = new FileOutputStream("F:\copy.doc"); BufferedOutputStream b = new BufferedOutputStream(out); bytess= in.read(bytes,0,bytes.length); c = bytess; do { bytess = in.read(bytes, c, (bytes.length-c)); } b.write(bytes, 0 , c); b.flush(); b.close(); sockets.close(); } }

Code: Server Program

import java.net.*; import java.io.*; public class Main { public static void main (String [] args ) throws IOException { ServerSocket serverSockets = new ServerSocket(12345); Socket sockets = serverSockets.accept(); System.out.println("Server connection Accepted : " + sockets); File f = new File ("F:\Sample.docx"); byte [] bytes = new byte [(int)f.length()]; FileInputStream input = new FileInputStream(f); BufferedInputStream b = new BufferedInputStream(input); b.read(bytes,0,bytes.length); OutputStream output = sockets.getOutputStream(); System.out.println("Sending Files..."); output.write(bytes,0,bytes.length); output.flush(); sockets.close(); System.out.println("File transfer complete"); } }

Output:

Conclusion

In java programming technology, the package is called java.net.* In that each version of java it may vary the classes in the package the server socket connection is a basic networking feature for file transmission, upload and even though we have sent an email from one client to another client with the help of socket connections

Recommended Articles

This is a guide to Java ServerSocket. Here we discuss the introduction, how to use Java ServerSocket, along with respective examples. You may also have a look at the following articles to learn more –

How To Use Html Schriftart With Examples

Introduction to HTML Schriftart

Web development, programming languages, Software testing & others

Syntax:

Htmlfonts(Schriftart) is using some style attributes in CSS styles, and also using font tag we declared the font face, size, and colors.

The above code is one of the basic syntaxes for the html fonts declared and used in the web pages. We also displayed the fonts in different style attributes like bold, italic and underlined views.

How to Use Html Schriftart?

The annotation-based html tag is used in the CSS styles on the side of the browser; it will load the default one in the HTML web page it may be created an issue. If we call the external fonts in the web browsers using the style like @font-face, whenever the user use the text, it will convert automatically to the given font styles whichever we assign the fonts in the css it will be used for the completely invisible side in the front end. In some type of browsers will be waiting for loading the custom fonts in the web pages; it may take some time to load the web page; normally, it will take 3 seconds to display the web pages.

In Webkit type of browsers like safari, android browsers, and blackberry mobile browsers, it may take upto 30 seconds over time to load the web pages. Some times custom fonts will represent in potentially some failure in the usable sites. If we use css styles, it will look appearance more flexible, user-friendly even we download any other files it also looks pretty and very simple to use on the web pages.

In most browsers, the default font size is 3, and in the majority of the web sites, the text values will be the range from 2 to 3; it may vary when compared to each browser and web sites. The font size will be declared into two different categories 1. Absolutely and chúng tôi Absolute sizes range between 1 and 7; the values will have differed when the user browsers compatibility. We can also resize the fonts after the declaration of the font sizes it will affect the user texts in the web pages also differ it will adapt the user preferences that is the text size will be displayed somewhat different from user expectation it will show like high, very high or low text will be shown as the above types. If we set the font size will be very less length it’s difficult to read the web pages on the user end.

If we use high font length, then the web page will be a continuation from another page; the user will also scroll the web pages the navigation it’s needed for the front end. The text font size will be user end, so it will choose the user point of view it will show the normal and the appearance will be more sophisticated in the front end. Whenever we create a web page, it will intend to make them accessible in the www consortium; then, it will permit us to display the web page in globally.

Generally, font face values will be some fixed one like “Times New Roman, Comic sans MS, Arial, Calibri”, etc. the above 3 to 4 font faces will be used for most of the web sites even though the “Schriftart” this font will be used in the web page documents. We can set the font face with the help of face attributes, but we should also be aware that if the user does not log in and view the pages in the browsers because the font styles should be installed in the user pcs then only it will be displayed in the browser screen. If the font is not installed, the user will see the screen using the default font, which already installed on the pc.

Examples to Implement HTML Schriftart

Below are the examples mentioned:

Example #1

Code:

Example #2

Code:

Output:

Example #3

Welcome User Welcome To My Domain

Output:

Explanation to the above examples: In the above three examples, we discussed the font sizes with different ranges; the above three outputs are executed in the chrome browsers the font size whatever we mention in the code it will be displayed in the browser the final example we have seen the font size, styles, and colors.

Conclusion

We have seen the html schriftart(font) is angerman language fonts; we will use the fonts to translate the html predefined tags to convert the german language, but the functionalities of the fonts are to be the same as we discussed in the font features, colors, and sizes. In CSS, it will declare in the font style attributes it will mention all the font behaviors.

Recommended Articles

This is a guide to HTML Schriftart. Here we discuss the introduction to Html Schriftart with examples for better understanding. You can also go through our other related articles to learn more –

How We Can Use Gulp Rename With Examples?

Introduction to Gulp rename

We know that Gulp is used to automate web tasks of developers; it provides different kinds of features to the developer during automation. The rename is one of the features that are offered by Gulp. Gulp development sometimes requires the developer to rename the file; at that time, the developer can use the rename feature. The developer can also rename the folder names as per their requirement. In other words, we can say that sometimes the developer wants to modify the JavaScript file, or we need to copy them at that time; we can use the gulp rename method.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

What is Gulp rename? Using Gulp rename

Now let’s see how we can use gulp rename as follows:

Code:

var renamefile = require("gulp-rename"); gulp.src("./Gulp/Demo/main/text/demofile.txt") .pipe(rename("Demo/main/text/sample/secondfile.txt")) .pipe(gulp.dest("./Gulp/Demo/main/text")); gulp.src("./Gulp/Demo/**/demofile.txt") .pipe(rename(function (path) { path.directname += "/text"; path.bname += "sample"; path.ename = ".txt"; })) .pipe(gulp.dest("./Gulp/Demo/main/")); gulp.src("./text/**/demofile.txt") .pipe(rename(function (path) { return { directname: path. directname + "/text", bname: path.bname + "sample" ename: ".txt” }; })) .pipe(gulp.dest("./text")); gulp.src("./Gulp/Demo/main/text/demofile.txt", { base: process.cwd() }) .pipe(rename({ dirname: "Demo/main/text", bname: "texfile", pre: "sampledemo", suff: "Demo", ename: ".text" })) .pipe(gulp.dest("./Demo/main"));

Explanation:

gulp.dest() renames the registries among the process.cwd() and dirrectname (for example, the base comparative with CWD). Use dirrectname to rename the registries matched by the glob or descendants of the foundation of choice. bname is the filename without the augmentation-like path.bname(filename, path.ename(specified filename)). ename is the record augmentation, including the. like path.ename(specified filename).

While utilizing a capacity, a second record contention is furnished with the entire setting and unique document esteem. While using a capacity, on the off chance that no Object is returned, the passed boundary object (alongside any adjustments) is re-utilized.

Examples of Gulp rename

Now let’s see different examples of gulp rename as follows:

Now let’s see how we can install gulp as follows:

First, we need to confirm all setup and installation of gulp with the help of the following command.

Code:

node -v

Explanation:

Using the above command, we can see the installed version of chúng tôi after execution, we can see the result in the following command.

Output:

In the command line prompt, enter the accompanying order to show the variant of npm (Node.js bundle chief), which is utilized to introduce modules. It will show the introduced chúng tôi form with the help of the below command.

Code:

npm -v

Explanation:

After executing the above command, we can see the currently installed version of npm on our machine, as shown in the screenshot below.

Output:

We successfully installed chúng tôi now, we need to install the gulp using the below command.

Code:

npm install gulp -g

Explanation:

In the above command, we use g for a flag that ensures gulp is globally available for all projects. After entering the above command, we get the following screen, as shown in the below screenshot.

Output:

For verification of gulp, we need to run the below command below.

Code:

gulp –v

Explanation:

After executing the above command, we get the currently installed version of a gulp, as shown in the screenshot below.

Output:

Now we can add the rename plugin in gulp with the help of the following command.

Code:

npm install gulp-rename

First, let’s see how we can perform a rename operation using the following function.

Code:

var gulpr = require('gulp'); var renamef = require("gulp-rename"); gulp.task('renamef', function() { gulp.src("maps/Gulp/Demo/main.txt") .pipe(rename(function (path) { path.dname += "/txt"; path.bname = "file.txt"; path.ename = ".txt" })) .pipe(gulp.dest("./Demo/main/dist")); });

Explanation:

In the above example, we try to implement a rename method here. First, declare the variable shown in the above code after using the map function to rename the file from the source folder and store the renamed file inside the destination folder. The final output is shown in the below screenshot as follows.

Output:

Similarly, we can implement using different methods mentioned in usages.

Conclusion

With the help of the above article, we saw about the Gulp rename. From this article, we learned basic things about the Gulp rename, and we also saw the integration of the Gulp rename and how we use it in the Gulp rename.

Recommended Articles

This is a guide to Gulp rename. Here we discuss the introduction, using gulp rename and examples to understand better. You may also have a look at the following articles to learn more –

C# Queue With Examples: What Is C# Queue And How To Use?

What is Queue in C#?

The Queue is a special case collection which represents a first in first out concept. Imagine a queue of people waiting for the bus. Normally, the first person who enters the queue will be the first person to enter the bus. Similarly, the last person to enter the queue will be the last person to enter into the bus. Elements are added to the queue, one on the top of each other.

The process of adding an element to the queue is the enqueuer operation. To remove an element from a queue, you can use the dequeuer operation. The operation in Queues C# is similar to stack we saw previously.

Let’s look at how to use Queue in C# and the operations available for the Queue collection in C# in more details.

Declaration of the Queue

The declaration of a Queue is provided below. A Queue is created with the help of the Queue Data type. The “new” keyword is used to create an object of a Queue. The object is then assigned to the variable qt.

Queue qt = new Queue() Adding elements to the Queue

The enqueue method is used to add an element onto the queue. The general syntax of the statement is given below.

Queue.enqueue(element) Removing elements from the queue

The dequeue method is used to remove an element from the queue. The dequeue operation will return the first element of the queue. The general syntax of the statement is given below

Queue.dequeue() Count

This property is used to get the number of items in the queue. Below is the general syntax of this statement.

Queue.Count Contains

This method is used to see if an element is present in the Queue. Below is the general syntax of this statement. The statement will return true if the element exists, else it will return the value false.

Queue.Contains(element)

Now, let’s see this working at a code level. All of the below-mentioned code will be written to our Console application.

The code will be written to our chúng tôi file. In the below program, we will write the code to see how we can use the above-mentioned methods.

Example

In this Queue in C# example, we will see how a queue gets created. Next, we will see how to display the elements of the queue, and use the Count and Contain methods.

C# Queue example

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Program { static void Main(string[] args) { Queue qt = new Queue(); qt.Enqueue(1); qt.Enqueue(2); qt.Enqueue(3); foreach (Object obj in qt) { Console.WriteLine(obj); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("The number of elements in the Queue " + qt.Count); Console.WriteLine("Does the Queue contain " + qt.Contains(3)); Console.ReadKey(); } } } Code Explanation

The first step is used to declare the Queue. Here we are declaring qt as a variable to hold the elements of our Queue.

Next, we add 3 elements to our Queue. Each element is added via the “enqueue” method.

Now one thing that needs to be noted about Queues is that the elements cannot be accessed via the index position like the array list. We need to use a different approach to display the elements of the Queue. So here’s how we go about displaying the elements of a queue.

We first declare a temporary variable called obj. This will be used to hold each element of the Queue.

We then use the foreach statement to go through each element of the Queue.

For each Queue element, the value is assigned to the obj variable.

We then use the Console.Writeline command to display the value to the console.

We are using the “Count” property to get the number of items in the Queue. This property will return a number. We then display this value to the console.

We then use the “Contains” method to see if the value of 3 is present in our Queue. This will return either a true or false value. We then display this return value to the console.

If the above code is entered properly and the program is run the following output will be displayed.

Output

Queue C# example

From the output, we can clearly see that the elements of the Queue are displayed. Note that, unlike “stack” in “queue” the first element pushed on to the queue is displayed first. The count of queue elements is also shown in the output. Also, the value of True is displayed to say that the value of 3 is defined on the queue.

C# Queue Dequeue

Now let’s look at the remove functionality. We will see the code required to remove the last element from the queue.

C# Queue Dequeue example

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoApplication { class Program { static void Main(string[] args) { Queue qt = new Queue(); qt.Enqueue(1); qt.Enqueue(2); qt.Enqueue(3); qt.Dequeue(); foreach (Object obj in qt) { Console.WriteLine(obj); } Console.ReadKey(); } } } Code Explanation

Here we just issue the “dequeue” method, which is used to remove an element from the queue. This method will remove the first element of the queue.

If the above code is entered properly and the program is run the following output will be displayed.

Output:

C# Queue Dequeue example

From the output, we can see that the first element which was added to the queue, which was the element 1, was removed from the queue.

Summary

A Queue is based on the first in first out concept. The operation of adding an element to the queue is called the enqueue operation. The operation of removing an element to the queue is called the dequeue operation.

How To Use Excel Countif Function (Examples + Video)

Simple calculation such as adding the values in a range of cells or counting the values in reach of cells is something that you would have to do when working with data in Excel.

And in some cases, you may have to count only those cells that meet a specific criterion.

And you can easily do that with the COUNTIF function in Excel

In this tutorial, I will show you how the Excel COUNTIF function works with simple examples add a detailed explanation

Let’s first look at the syntax of the COUNTIF function:

=COUNTIF(range, criteria)

where

range is the range of cells where you want to count cells that meet the condition

criteria is the condition that must be evaluated against the range of cells for a cell to be counted.

Now let’s have a look at some examples that will show you how to use the COUNTIF function in Excel.

With the COUNTIF function, you can count all the cells that contain a specific text string.

Suppose you have a dataset as shown below and you want to count all the cells that have the text Printer in it.

Here is the formula that will do this:

=COUNTIF(A2:A9,"Printer")

The above formula uses the text I specified as the second argument as the criteria and counts all the cells that have the same text (which is “Printer”)

In this example, I have manually entered the criteria text, but you can also refer to a cell that contains the criteria text.

Note: Criteria text in the COUNTIF formula is not case sensitive. So I can also use ‘printer’ or ‘PRINTER’, as the result would still be the same

Just like I used the COUNTIF function with text, I can also use it with cells containing numbers.

Suppose I have a dataset as shown below and I want to count all the cells where the number in column B is greater than 30.

Below is the formula that will do this:

The above formula uses the greater than an operator with the number as the criteria. This tells Excel to only consider those cells where the value is more than 30.

While there is the COUNTA function that counts the cells that contain numbers, there is no in-built formula that can count only those cells that contain a text string.

But it can easily be done using the COUNTIF function.

Suppose you have a dataset as shown below and you only want to count the number of cells that are text (and ignore the numbers).

Here is the formula that will do this:

=COUNTIF(A2:A10,"*")

The above formula uses an asterisk (which is a wildcard character). An asterisk represents the text of any length.

So this criteria would count all the cells where there is any text string (of any length). In case the cells are empty/blank or have numbers in them, then those would not be counted.

Criteria could be a number, expression, cell reference, text, or a formula.

Criteria which are text or mathematical/logical symbols (such as =,+,-,/,*) should be in double-quotes.

Wildcard characters can be used in criteria.

There are three wildcard characters in Excel – the question mark (?), an asterisk (*), and tilde (~)

A question mark (?) matches any single character

An asterisk matches (*) any sequence of characters.

If you want to find an actual question mark or asterisk, type a tilde (~) before the character.

Criteria are case-insensitive (“Hello” and “hello” are treated as the same).

Related Excel Functions:

Update the detailed information about How To Use Sqlalchemy Async With Examples? on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!