Devsearch Synopsis
Devsearch Synopsis
Devsearch Synopsis
SUBMITTED TO
2
INDEX
3
ACKNOWLEDGEMENT
DATE: SIGNATURE:
4
CERTIFICATE OF ORIGINALITY
I hereby declare that the MCA Major Project (KCA-451) titled “Devsearch”
submitted to the IT Department, IMS Noida, which is affiliated with DR.
A.P.J. ABDUL KALAM TECHNICAL UNIVERSITY
LUCKNOW (U.P.) for the partial fulfillment of the degree of Masters of
Computer Application, in Session (2022-24). This has not previously
formed the basis for the award of any other degree, diploma, or other title
from any other University.
DATE:
SIGNATURE:
5
6
1.Project Profile
What is Devsearch?
Devsearch is a vast platform that changes how software developers work together on
projects. It’s more than just a place to store code; it offers tools for controlling versions,
tracking issues, and reviewing code, which are essential for creating software today.
Devsearch also has features like forks, pull requests, and merges that help
developers from all over the world work on open-source projects and other
collaborative efforts together.
It’s a system that lets developers keep track of and manage changes in their code, allowing
many people to work on the same project at the same time without messing up each other’s
work. This system keeps a detailed record of all changes, so you can go back to earlier
versions if you need to.
Because Git can handle projects of any size efficiently and flexibly, it’s the go-to choice
for developers and is key to making Devsearch a place where people can work together
effectively.
7
1.2 Project Description
DevSearch is an innovative platform designed to streamline the process of
discovering, connecting, and collaborating with developers worldwide. With the
exponential growth of the tech industry, the demand for skilled developers has
never been higher. However, the challenge lies in finding the right talent for
specific projects or roles. DevSearch addresses this challenge by providing a
comprehensive solution that empowers both developers and employers.
8
Furthermore, DevSearch offers a seamless hiring process, allowing employers to
manage job postings, applications, and interviews all within the platform. From
posting a job opening to extending an offer, employers can efficiently navigate
each step of the hiring process, saving time and resources.
Security and privacy are paramount on DevSearch. The platform employs robust
encryption protocols to safeguard sensitive information and ensure user privacy.
Developers have control over the visibility of their profiles and can choose to
share only relevant information with potential employers.
Overall, DevSearch revolutionizes the way developers are discovered, hired, and
connected within the tech industry. By providing a user-friendly platform with
powerful search and recommendation capabilities, DevSearch empowers both
developers and employers to find the perfect match for their projects and career
opportunities.
9
1.3 Existing System / Work Environment
10
6. Security and Privacy: DevSearch prioritizes security and privacy,
employing robust encryption protocols to safeguard sensitive information
and ensure user privacy. Developers have control over the visibility of their
profiles and can choose what information to share with potential employers.
11
1.3.2) Work Environment
12
7. Continuous Learning: DevSearch encourages continuous learning and
professional development. Team members have access to resources such
as online courses, workshops, and conferences to enhance their skills and
stay updated on industry trends.
13
1.4 Problem Statements
The problem statement for DevSearch revolves around the challenges faced
by both developers and employers in the tech industry:
14
6. Privacy and Security Concerns:
Both developers and employers are concerned about the security and
privacy of their data when using online platforms for hiring and
networking. Ensuring the confidentiality of sensitive information is
paramount to
building trust in such platforms.
In summary, the problem statement for DevSearch revolves around the need for a
comprehensive solution that simplifies the process of discovering, connecting, and
collaborating with developers while addressing concerns related to talent sourcing,
networking, privacy, and security in the tech industry.
15
1.5 Need for New System
3. Tailored Job Matching: Employers seek a platform where they can find
developers whose skills align with their project requirements or job openings.
DevSearch facilitates tailored job matching by allowing employers to search for
developers based on specific criteria such as programming languages,
experience level, and location.
16
7. Streamlined Hiring Process: DevSearch streamlines the hiring process by
providing tools for managing job postings, applications, and interviews within one
centralized platform. Employers can track candidate progress, schedule
interviews, and make hiring decisions efficiently.
11. Privacy and Data Security: Both developers and employers require
assurance that their data is secure and their privacy is protected when using the
platform for hiring and networking. DevSearch prioritizes data security and
implements robust measures to safeguard user information.
13. Diverse Talent Pool: Employers value access to a diverse talent pool with
developers from different backgrounds, experiences, and perspectives.
DevSearch promotes diversity and inclusion, ensuring that employers have access
to a wide range of talented developers.
17
14. Community Engagement: DevSearch fosters a sense of community by
encouraging engagement through forums, discussions, and events within the
platform. Developers can exchange ideas, seek advice, and collaborate on
projects, creating a vibrant and supportive community.
18
1.6 Proposed System & Features
The proposed system of DevSearch builds upon its existing features while
introducing enhancements to further streamline the process of discovering,
connecting, and collaborating with developers. Here's an outline of the proposed
system:
19
5. Virtual Collaboration Spaces: DevSearch introduces virtual collaboration
spaces where developers can work together on projects in real-time. These
spaces include features such as code editors, video conferencing, and task
management tools, enabling seamless collaboration regardless of geographical
location.
20
Overall, the proposed system of DevSearch aims to provide an even more
seamless and efficient experience for both developers and employers, leveraging
advanced technology to facilitate talent discovery, collaboration, and professional
growth within the tech industry.
21
1.6.2) Features of Devsearch:
22
7. Continuous Learning Resources: DevSearch offers a library of educational
23
resources such as online courses, tutorials, articles, and webinars to support
developers in their continuous learning and skill development.
Developers can access relevant learning materials to enhance their skills and stay
updated on the latest technologies.
10. Feedback and Review Mechanism: Employers can provide feedback and
ratings on developers they have worked with, helping to build trust and credibility
within the community. Reviews and ratings contribute to developers' reputations
on the platform and help employers make informed hiring decisions.
24
1.7 Scope
26
1.8 Outcomes
1. For Developers:
2. For Employers:
27
- Streamlined Hiring Process: DevSearch streamlines the hiring process by
offering tools for managing job postings, applications, interviews, and
candidate evaluations within one centralized platform.
28
1.9 Tools and technology used:-
For Frontend
1) HTML:-
● HTML (HyperText Markup Language) is the standard language used to
create and structure content on the web.
● It consists of a series of elements, represented by tags, that define
different parts of a webpage, such as headings, paragraphs, links, images,
and other multimedia.
● HTML tags are written within angle brackets, like <html>, <head>, <body>,
<p>, and <a>. HTML provides the skeleton of a webpage, enabling
browsers to display text, images, and interactive forms in a structured
format.
● Each HTML document begins with a <!DOCTYPE html>
declaration, followed by an <html> element that encompasses the
entire content.
● The <head> section contains metadata, links to stylesheets, and scripts,
while the <body> section includes the actual content displayed to users.
● HTML works in conjunction with CSS (Cascading Style Sheets) for
styling and JavaScript for interactivity, forming the core technologies for
web development.
29
2) CSS:-
● CSS, or Cascading Style Sheets, is a stylesheet language used to describe
the presentation of a document written in HTML or XML.
● CSS defines how elements should be displayed on screen, paper, or in
other media.
● It enables developers to separate content from design, providing a
more flexible and efficient method for designing web pages.
● CSS allows for the styling of multiple elements simultaneously,
promoting consistency across a website.
● It includes features for layout, color, font, spacing, and responsive
design, ensuring that web pages look good on various devices and screen
sizes.
● By using selectors and properties, developers can target HTML elements
and apply specific styles to them.
● CSS can be embedded within HTML documents, included as an external
file, or written inline within HTML tags.
● Its cascading nature means that styles can be applied hierarchically, with
more specific rules overriding more general ones.
30
3) Javascript:-
● JavaScript is a versatile, high-level programming language primarily used
for creating and enhancing interactive elements on websites.
● As a core technology of the World Wide Web, alongside HTML and CSS,
JavaScript enables dynamic content that can respond to user actions, such as
form validations, animated graphics, interactive maps, and real-time
updates.
● Initially developed by Netscape in 1995, JavaScript has evolved
significantly and is now an essential tool for front-end development, often
employed in conjunction with frameworks like React, Angular, and Vue.js.
● Additionally, with the advent of Node.js, JavaScript can also be used
for server-side programming, making it a full-stack language.
● Its syntax is similar to Java and C++, which helps in learning
other programming languages.
● JavaScript's versatility and widespread adoption make it a fundamental
skill for web developers, facilitating the creation of modern, responsive,
and user-friendly web applications.
31
For Backend
Django:-
32
Python:-
33
● This encourages a clean, consistent coding style and reduces the likelihood
of syntax errors. Furthermore, Python's dynamic typing system allows
variables to be assigned without specifying their data types explicitly,
enhancing code flexibility and reducing verbosity.
34
1.10 Project Plan
2. Planning Phase:
- Develop a detailed project plan outlining tasks, dependencies,
timelines, and resources required for each phase.
- Identify and prioritize features and functionalities based on user needs
and market demand.
- Define technical specifications, architecture, and technology stack for
the platform.
- Establish project milestones and deliverables.
35
4. Development Phase:
- Develop the backend infrastructure, databases, and APIs required for
the platform.
- Implement frontend components and user interfaces based on the
approved designs.
- Integrate third-party services and tools as needed, such as AI
algorithms, collaboration tools, and communication platforms.
- Conduct regular code reviews, testing, and debugging to ensure quality
and stability.
6. Deployment Phase:
- Prepare for the deployment of the platform to production servers or
cloud infrastructure.
- Configure deployment pipelines, continuous integration, and
automated deployment processes.
- Perform final checks and validations to ensure a smooth
deployment process.
- Monitor system performance and user feedback post-deployment,
and address any issues as they arise.
36
- Monitor user acquisition, engagement, and feedback post-launch,
and iterate on marketing strategies as needed.
37
2. Requirement Analysis
2.1 Feasibility Study
38
8. Scalability and Performance:- Assess the platform's ability to handle
increasing user traffic and data volumes. - Implement scalable architecture
and performance optimization techniques. - Conduct stress tests to identify
potential bottlenecks and performance limitations.
9. Pilot Testing and Feedback:- Conduct pilot tests with a small group of
users to gather feedback and iterate on the platform. - Use feedback to refine
features, address usability issues, and improve overall satisfaction.
39
2.2 Users of the System:
1. Individual Developers:
Freelancers: Looking for new projects and clients to work with. They use
Devsearch to find job postings and project opportunities that match their skill sets.
Learners: New or junior developers aiming to gain experience and build their
portfolios. They use Devsearch to find mentorship opportunities, open-source
projects to contribute to, and learning resources.
40
4. Community Builders and Educators:
Educators: Instructors and trainers who provide coding boot camps, courses, and
workshops. They use the platform to reach potential students and collaborate on
educational content.
41
2.3 Modules
2. Search Engine:
The core functionality of DevSearch, this module enables users to search for
programming languages, frameworks, libraries, tools, documentation, tutorials,
articles, and discussions. It utilizes search algorithms and indexing techniques
to provide relevant and accurate search results.
4. Documentation Repository:
DevSearch maintains a comprehensive repository of documentation for various
programming languages, frameworks, and libraries. This module organizes and
categorizes documentation, making it easily accessible to users for reference
and learning purposes.
6. Recommendation Engine:
Based on user preferences, search history, and behavior, this module provides
personalized recommendations for programming tools, resources, tutorials, and
articles. It utilizes machine learning algorithms and data analysis techniques to
suggest relevant content and enhance the user experience.
42
7. Integration Support with External Tools and Platforms:
DevSearch integrates with other developer tools and platforms, such as IDEs,
version control systems, project management tools, and online repositories. This
module ensures seamless interoperability and allows users to access relevant
information from their preferred tools within the DevSearch ecosystem.
10. Analytics and Insights: This module collects and analyzes data related
to user behavior, search patterns, engagement metrics, and platform usage. It
generates insights and reports to help administrators understand user
preferences, identify trends, and make data-driven decisions to improve the
platform.
43
2.4 Hardware & Software Requirements
Hardware requirements:
Software requirements:
● VS Code
● Python
● TensorFlow
● NumPy
● IDE (Integrated Development Environment)
● Version Control System (e.g., Git)
● Text Editors (for Documentation)
44
3) Design
3.1) Diagram
3.1.1) DFD
0 level DFD:-
45
1 level DFD:-
46
2 Level DFD:-
47
3.1.2) ER Diagram:-
48
4) Implementation:
4.1) Code:-
4.1.1) HTML Code:-
main.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<body>
<!-- Header Section -->
<header class="header">
<div class="container container--narrow">
<a href="{% url 'profiles' %}" class="header logo">
49
<img src="{% static 'images/logo.svg' %}" alt="DevSearch Logo" />
</a>
<nav class="header nav">
<input type="checkbox" id="responsive-menu" />
<label for="responsive-menu" class="toggle-menu">
<span>Menu</span>
<div class="toggle-menu lines"></div>
</label>
<ul class="header menu">
<li class="header menuItem"><a href="{% url 'profiles'
%}">Developers</a></li>
<li class="header menuItem"><a href="{% url 'projects'
%}">Projects</a></li>
{% if request.user.is_authenticated %}
<li class="header menuItem"><a href="{% url 'account'
%}">Account</a></li>
<li class="header menuItem"><a href="{% url 'inbox' %}">Inbox</a></li>
</ul>
</nav>
</div>
</header>
{% if messages %}
50
{% for message in messages %}
<div class="alert alert--{{messgae.tags}}">
<p class="alert message">{{message}}</p>
<button class="alert close">x</button>
</div>
{% endfor %}
{% endif %}
51
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<body>
<!-- Header Section -->
<header class="header">
<div class="container container--narrow">
<a href="/" class="header logo">
<img src="images/logo.svg" alt="DevSearch Logo" />
</a>
<nav class="header nav">
<input type="checkbox" id="responsive-menu" />
52
<label for="responsive-menu" class="toggle-menu">
<span>Menu</span>
<div class="toggle-menu lines"></div>
</label>
<ul class="header menu">
<li class="header menuItem"><a href="index.html">Developers</a></li>
<li class="header menuItem"><a href="projects.html">Projects</a></li>
<li class="header menuItem"><a href="inbox.html">Inbox</a></li>
<li class="header menuItem"><a
href="account.html">My Account</a></li>
<li class="header menuItem"><a href="login.html"
class="btn btn--sub">Login/Sign Up</a></li>
</ul>
</nav>
</div>
</header>
53
<input class="btn btn--sub btn--lg" type="submit" value="Search" />
</form>
</div>
</div>
</section>
<!-- Search Result: DevList -->
<section class="devlist">
<div class="container">
<div class="grid grid--three">
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">
<img class="avatar avatar--md"
src="https://avatars.githubusercontent.com/u/22437186" alt="image" />
<div class="dev meta">
<h3>Shahriar P. Shuvo</h3>
<h5>FullStack Web Designer & Developer</h5>
</div>
</div>
<p class="dev info">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
animi, exercitationem molestias nam doloremque architecto odit.
</p>
<div class="dev skills">
<span class="tag tag--pill tag--main">
<small>JavaScript</small>
</span>
<span class="tag tag--pill tag--main">
<small>React</small>
</span>
<span class="tag tag--pill tag--main">
54
<small>SCSS</small>
</span>
<span class="tag tag--pill tag--main">
<small>Nodejs</small>
</span>
<span class="tag tag--pill tag--main">
<small>Express</small>
</span>
<span class="tag tag--pill tag--main">
<small>GraphQL</small>
</span>
</div>
</a>
</div>
</div>
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">
<img class="avatar avatar--md"
src="https://avatars.githubusercontent.com/u/1868782" alt="image" />
<div class="dev meta">
<h3>Cody Seibert</h3>
<h5>React Developer, Coding Youtuber</h5>
</div>
</div>
<p class="dev info">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Cupiditate,
ducimus inventore! Sunt,
veniam veritatis? Veritatis placeat, deleniti iure tempore veniam
perspiciatis, soluta cupiditate
animi, exercitationem molestias nam doloremque architecto odit.
55
</p>
<div class="dev skills">
<span class="tag tag--pill tag--main">
<small>Elixir</small>
</span>
</div>
</a>
</div>
</div>
<div class="column card">
<div class="dev">
<a href="/profile.html" class="card body">
<div class="dev profile">
<small>Python</small>
</span>
<span class="tag tag--pill tag--main">
<small>Django</small>
</span>
<span class="tag tag--pill tag--main">
<small>Rest API</small>
</span>
</div>
</a>
</div>
</div>
<div class="column card">
<div class="dev">
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<body>
<div class="auth">
<div class="card">
<div class="auth header text-center">
<a href="/">
<img src="images/icon.svg" alt="icon" />
</a>
<h3>Account Login</h3>
<p>Hello Developer, Welcome Back!</p>
</div>
class="input input--password"
id="formInput#passowrd"
type="password"
name="password"
placeholder="••••••••"
/>
</div>
<div class="auth actions">
<input class="btn btn--sub btn--lg" type="submit" value="Log In" />
<a href="forgetpassword.html">Forget Password?</a>
</div>
</form>
<div class="auth alternative">
<p>Don’t have an Account?</p>
<a href="signup.html">Sign Up</a>
</div>
</div>
</div>
</body>
</html>
62
profile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<body>
<!-- Header Section -->
<header class="header">
63
<div class="container container--narrow">
<a href="/" class="header logo">
<img src="images/logo.svg" alt="DevSearch Logo" />
</a>
<nav class="header nav">
<input type="checkbox" id="responsive-menu" />
<label for="responsive-menu" class="toggle-menu">
<span>Menu</span>
<div class="toggle-menu lines"></div>
</label>
<ul class="header menu">
<li class="header menuItem"><a href="index.html">Developers</a></li>
<li class="header menuItem"><a href="projects.html">Projects</a></li>
<li>
<a title="Personal Website" href="#" target="_blank"><i class="im
im-globe"></i></a>
</li>
</ul>
<a href="#" class="btn btn--sub btn--lg">Send Message </a>
</div>
</div>
</div>
<div class="column column--2of3">
<div class="devInfo">
<h3 class="devInfo title">About Me</h3>
<p class="devInfo about">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ex illum ipsum
iusto consequatur. Totam,
dolorum fugiat, debitis facere illo nostrum nesciunt maxime, deserunt enim
voluptatibus modi natus velit
voluptatum. Dicta eritatis exercitationem ut quos a placeat obcaecati?
Architecto illum!
<br />
Amet consectetur adipisicing elit. Veritatis exercitationem ut quos a placeat
obcaecati? Architecto
illum, atque delectus nemo dolorem inventore ab facilis? Dolor placeat vel
delectus ipsam ullam.
65
</p>
</div>
<div class="devInfo">
<h3 class="devInfo title">Skills</h3>
<div class="devInfo skills">
<div class="devSkill">
<h4 class="devSkill title">JavaScript</h4>
<p class="devSkill info">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Recusandae
neque voluptatum ut? Quaerat, ea
cumque! Dolorum provident esse molestias commodi odit sapiente quod
quasi corrupti obcaecati? Nobis
ex temporibus quaerat!
</p>
</div>
<div class="devSkill">
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>NextJS</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>Postgres</small>
</span>
<span class="tag tag--pill tag--sub tag--lg">
<small>MongoDB</small>
</span>
</div>
</div>
</div>
<div class="devInfo">
<h3 class="devInfo title">Projects</h3>
<div class="grid grid--two">
<div class="column">
<div class="card project">
<a href="single-project.html" class="project">
<img class="project thumbnail" src="images/project-b.png"
alt="project thumbnail" />
67
<div class="card body">
<h3 class="project title">DevSearch UI Design</h3>
<p><a class="project author" href="profile.html">By Shahriar
P. Shuvo</a></p>
<p class="project--rating">
<span style="font-weight: bold;">92%</span> Postitive
Feedback (62 Votes)
</p>
<div class="project tags">
<span class="tag tag--pill tag--main">
<small>NextJS</small>
</span>
<span class="tag tag--pill tag--main">
<small>GraphQL</small>
</span>
<span class="tag tag--pill tag--main">
<small>TypeScript</small>
</span>
</div>
</div>
</a>
</div>
</div>
<div class="column">
<div class="card project">
<a href="single-project.html" class="project">
<img class="project thumbnail" src="images/project-
c.png" alt="project thumbnail" />
<div class="card body">
<h3 class="project title">Another Landing Page</h3>
<p><a class="project author" href="profile.html">By
Dennis Ivanov</a></p>
<p class="project--rating">
<span style="font-weight: bold;">36%</span> Postitive
Feedback (18 Votes)
</p>
<div class="project tags">
<span class="tag tag--pill tag--main">
68
<small>NextJS</small>
</span>
<span class="tag tag--pill tag--main">
<small>GraphQL</small>
</span>
<span class="tag tag--pill tag--main">
<small>TypeScript</small>
</span>
</div>
</div>
</a>
</div>
</div>
<div class="column">
<div class="card project">
<a href="single-project.html" class="project">
<img class="project thumbnail" src="images/project-
a.png" alt="project thumbnail" />
</div>
</div>
</div>
</div>
</div>
</main>
</body>
</html>
views.py
def loginUser(request):
70
# This if condition will check if the user is loged in and if its true and then if the
user tries to access the login page by search bar it will restrict and redirect it to the
profiles page
if request.user.is_authenticated:
return redirect('profiles')
if request.method == 'POST':
page = 'login'
username = request.POST['username'].lower()
password = request.POST['password']
try:
user = User.objects.get(username=username)
except:
messages.error(request, "User doesn't exist")
login(request, user)
return redirect(request.GET['next'] if 'next' in request.GET else 'account')
else:
messages.error(request, "User or password is wrong")
return render(request,
'users/login_register.html') def
logoutUser(request):
logout(request)
messages.info(request, "User successfully loged out")
return redirect('login')
71
def registerUser(request):
72
page = 'register'
form = CustomUserCreationForm()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.username = user.username.lower()
user.save()
login(request, user)
return redirect('edit-account')
else:
messages.error(request, "An error has been occurred during reqistration")
def profiles(request):
73
context = {"profile": profile, "topskills": topskills, "otherskills": otherskills}
return render(request, 'users/single-profile.html', context)
@login_required(login_url="login")
def userAccount(request):
profile = request.user.profile
skills = profile.skill_set.all()
projects = profile.project_set.all()
@login_required(login_url="login")
def editAccount(request):
profile = request.user.profile
form = ProfileForm(instance=profile)
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES,
instance=profile) if form.is_valid():
form.save()
return redirect("account")
@login_required(login_url='login')
def createSkill(request):
profile = request.user.profile
form = SkillForm()
if request.method == 'POST':
form = SkillForm(request.POST)
if form.is_valid():
skill = form.save(commit=False)
skill.owner = profile
skill.save()
74
messages.success(request, "skill was added successfully!")
return redirect("account")
@login_required(login_url='login')
def updateSkill(request, pk):
profile = request.user.profile
skill = profile.skill_set.get(id=pk)
form = SkillForm(instance=skill)
if request.method == 'POST':
form = SkillForm(request.POST, instance=skill)
if form.is_valid():
form.save()
messages.success(request, "skill was updated successfully!")
return redirect("account")
@login_required(login_url='login')
def deleteSkill(request, pk):
profile = request.user.profile
skill = profile.skill_set.get(id=pk)
if request.method == 'POST':
skill.delete()
messages.success(request, "Skill was deleted successfully!")
return redirect('account')
@login_required(login_url='login')
75
def inbox(request):
profile = request.user.profile
messageRequest = profile.messages.all()
unreadCount = messageRequest.filter(is_read = False).count()
context = {'messageRequest': messageRequest, 'unreadCount': unreadCount}
return render(request, 'users/inbox.html', context)
@login_required(login_url='login')
def viewMessage(request, pk):
profile = request.user.profile
message = profile.messages.get(id=pk)
if message.is_read == False:
message.is_read = True
message.save()
context = {'message': message}
return render(request, 'users/message.html', context)
try:
sender = request.user.profile
except:
sender = None
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
message = form.save(commit=False)
message.sender = sender
message.recipient = recipient
if sender:
message.name = sender.name
message.email = sender.email
message.save()
76
messages.success(request, "Your message was successfully sent!")
return redirect('single-profile', pk=recipient.id)
form.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name', 'email', 'username', 'password1', 'password2']
labels = {
'first_name': 'Name',
77
}
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['name', 'email', 'username', 'location', 'short_intro', 'bio', 'profile_image',
'social_github', 'social_linkedin', 'social_twitter', 'social_website', ]
class SkillForm(ModelForm):
class Meta:
model = skill
fields = ' all '
exclude = ['owner']
class MessageForm(ModelForm):
class Meta:
model = Message
fields = ['name', 'email', 'subject', 'body']
78
def init (self, *args, **kwargs):
super(MessageForm, self). init (*args, **kwargs)
admin.py
admin.site.register(Project)
admin.site.register(Review)
admin.site.register(Tags)
79
urls.py
urlpatterns = [
# path('', views.home, name='home'),
path('', views.projects, name='projects'),
path('single_projects/<str:pk>/', views.single_projects,
name='single_projects'), path('create-project/', views.create_project,
name='create-project'),
path('update-project/<str:pk>/', views.update_project, name='update-
project'), path('delete-project/<str:pk>/', views.delete_project, name='delete-
project'),
]
typing_extensions.py
import abc
import collections
import collections.abc
import functools
import inspect
import operator
80
import sys
81
import types as _types
import typing
import warnings
all = [
# Super-special typing primitives.
'Any',
'ClassVar',
'Concatenate',
'Final',
'LiteralString',
'ParamSpec',
'ParamSpecArgs',
'ParamSpecKwargs',
'Self',
'Type',
'TypeVar',
'TypeVarTuple',
'Unpack',
# One-off things.
'Annotated',
'assert_never',
'assert_type',
'clear_overloads',
'dataclass_transform',
'deprecated',
'get_overloads',
'final',
'get_args',
'get_origin',
'get_original_bases',
'get_protocol_members',
'get_type_hints',
'IntVar',
'is_protocol',
'is_typeddict',
'Literal',
'NewType',
'overload',
'override',
'Protocol',
'reveal_type',
'runtime',
'runtime_checkable',
'Text',
'TypeAlias',
'TypeAliasType',
83
'TypeGuard',
'TYPE_CHECKING',
'Never',
'NoReturn',
'Required',
'NotRequired',
'Optional',
'Pattern',
'Reversible',
'Sequence',
'Set',
'Sized',
84
'TextIO',
'Tuple',
'Union',
'ValuesView',
'cast',
'no_type_check',
'no_type_check_decorator',
]
class _Sentinel:
def repr (self):
return "<sentinel>"
_marker = _Sentinel()
not _is_unpack(t)
):
tvars.append(t)
86
if _should_collect_from_parameters(t):
87
tvars.extend([t for t in t. parameters if t not in tvars])
return tuple(tvars)
NoReturn = typing.NoReturn
# Some unconstrained type variables. These are used by the container types.
# (These are not for export.)
T = typing.TypeVar('T') # Any type.
KT = typing.TypeVar('KT') # Key
type.
VT = typing.TypeVar('VT') # Value type.
T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
class _AnyMeta(type):
def instancecheck (self, obj):
if self is Any:
raise TypeError("typing_extensions.Any cannot be used with
isinstance()") return super(). instancecheck (obj)
class Any(metaclass=_AnyMeta):
"""Special type indicating an unconstrained type.
- Any is compatible with every type.
- Any assumed to have all methods.
- All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of
static type checkers. At runtime, Any should not be used with instance
88
checks.
89
"""
def new (cls, *args,
**kwargs): if cls is Any:
raise TypeError("Any cannot be
instantiated") return super(). new (cls,
*args, **kwargs)
ClassVar = typing.ClassVar
class _ExtensionsSpecialForm(typing._SpecialForm,
_root=True): def repr (self):
return 'typing_extensions.' + self._name
Final = _FinalForm('Final',
doc="""A special typing construct to indicate that a name
cannot be re-assigned or overridden in a subclass.
For example:
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
90
TIMEOUT = 1 # Error reported by type checker
91
There is no runtime checking of these properties.""")
class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...
92
pass
93
return f
def IntVar(name):
return typing.TypeVar(name)
def _value_and_type_iter(params):
for p in params:
yield p, type(p)
class _LiteralGenericAlias(typing._GenericAlias,
_root=True): def eq (self, other):
if not isinstance(other, _LiteralGenericAlias):
return NotImplemented
these_args_deduped = set(_value_and_type_iter(self. args ))
other_args_deduped = set(_value_and_type_iter(other. args ))
return these_args_deduped == other_args_deduped
class _LiteralForm(_ExtensionsSpecialForm,
_root=True): def init (self, doc: str):
self._name = 'Literal'
94
self._doc = self. doc = doc
parameters = _flatten_literal_params(parameters)
val_type_pairs = list(_value_and_type_iter(parameters))
try:
deduped_pairs = set(val_type_pairs)
except TypeError:
# unhashable parameters
pass
else:
# similar logic to typing._deduplicate on Python 3.9+
if len(deduped_pairs) < len(val_type_pairs):
new_parameters = []
for pair in val_type_pairs:
if pair in deduped_pairs:
new_parameters.append(pair[0])
deduped_pairs.remove(pair)
assert not deduped_pairs, deduped_pairs
parameters = tuple(new_parameters)
Literal = _LiteralForm(doc="""\
A type that can be used to indicate to type checkers
that the corresponding value has a value literally equivalent
to the provided parameter. For example:
var: Literal[4] = 4
95
_overload_dummy = typing._overload_dummy
def overload(func):
"""Decorator for overloaded functions/methods.
In a stub file, place two or more stub definitions for the same
function in a row, each decorated with @overload. For example:
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
def utf8(value):
# implementation goes here
96
The overloads for a function can be retrieved at runtime using the
get_overloads() function.
"""
# classmethod and staticmethod
f = getattr(func, " func ", func)
try:
_overload_registry[f. module ][f. qualname ][
f. code .co_firstlineno
] = func
except AttributeError:
# Not a normal function; ignore.
pass
return _overload_dummy
def get_overloads(func):
"""Return all defined overloads for *func* as a
sequence.""" # classmethod and staticmethod
f = getattr(func, " func ", func)
if f. module not in _overload_registry:
return []
mod_dict = _overload_registry[f. module ]
if f. qualname not in mod_dict:
return []
return list(mod_dict[f. qualname ].values())
def clear_overloads():
"""Clear all overloads in the registry."""
_overload_registry.clear()
Awaitable = typing.Awaitable
Coroutine = typing.Coroutine
97
AsyncIterable =
typing.AsyncIterable AsyncIterator =
typing.AsyncIterator Deque =
typing.Deque
ContextManager = typing.ContextManager
AsyncContextManager = typing.AsyncContextManager
DefaultDict = typing.DefaultDict
# 3.7.2+
if hasattr(typing, 'OrderedDict'):
OrderedDict = typing.OrderedDict
# 3.7.0-3.7.2
else:
OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
Counter = typing.Counter
ChainMap = typing.ChainMap
AsyncGenerator = typing.AsyncGenerator
Text = typing.Text
TYPE_CHECKING = typing.TYPE_CHECKING
_PROTO_ALLOWLIST = {
'collections.abc': [
'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
],
'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
'typing_extensions': ['Buffer'],
}
_EXCLUDED_ATTRS = {
" abstractmethods ", " annotations ", " weakref ", "_is_protocol",
"_is_runtime_protocol", " dict ", " slots ", " parameters ",
" orig_bases ", " module ", "_MutableMapping marker", " doc ",
" subclasshook ", " orig_class ", " init ", " new ",
" protocol_attrs ", " callable_proto_members_only ",
98
}
99
if sys.version_info < (3, 8):
_EXCLUDED_ATTRS |= {
"_gorg", " next_in_mro ", " extra ", " tree_hash ", " args ",
" origin "
}
_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS)
def _get_protocol_attrs(cls):
attrs = set()
for base in cls. mro [:-1]: # without object
if base. name in {'Protocol', 'Generic'}:
continue
annotations = getattr(base, ' annotations ', {})
for attr in (*base. dict , *annotations):
if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
attrs.add(attr)
return attrs
def _maybe_adjust_parameters(cls):
"""Helper function used in Protocol. init_subclass and
_TypedDictMeta. new .
def _caller(depth=2):
try:
return sys._getframe(depth).f_globals.get(' name ', ' main ')
except (AttributeError, ValueError): # For platforms without
_getframe()
return None
101
# The performance of runtime-checkable protocols is significantly improved on
102
Python 3.12,
# so we backport the 3.12 version of Protocol to Python <=3.11
if sys.version_info >= (3, 12):
Protocol = typing.Protocol
else:
def _allow_reckless_class_checks(depth=3):
"""Allow instance and class checks for special stdlib modules.
The abc and functools modules indiscriminately call isinstance() and
issubclass() on the whole MRO of a user class, which may contain protocols.
"""
return _caller(depth) in {'abc', 'functools', None}
class _ProtocolMeta(_ProtocolMetaBase):
# This metaclass is somewhat unfortunate,
# but is necessary for several reasons...
#
# NOTE: DO NOT call super() in any methods in this class
# That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
# and those are slow
def new (mcls, name, bases, namespace,
**kwargs): if name == "Protocol" and len(bases) < 2:
pass
elif {Protocol, _typing_Protocol} & set(bases):
for base in bases:
103
if not (
104
base in {object, typing.Generic, Protocol, _typing_Protocol}
or base. name in _PROTO_ALLOWLIST.get(base. module ,
[])
or is_protocol(base)
):
raise TypeError(
f"Protocols can only inherit from other protocols, "
f"got {base!r}"
)
return abc.ABCMeta. new (mcls, name, bases, namespace, **kwargs)
106
if not getattr(cls, '_is_runtime_protocol', False):
raise TypeError(
"Instance and class checks can only be used with "
"@runtime_checkable protocols"
)
if (
not getattr(cls, '_is_runtime_protocol', False) and
not _allow_reckless_class_checks()
):
raise TypeError("Instance and class checks can only be used
with" " @runtime_checkable protocols")
return False
107
def eq (cls, other):
# Hack so that typing.Generic. class_getitem
# treats typing_extensions.Protocol
# as equivalent to typing.Protocol on Python
3.8+ if abc.ABCMeta. eq (cls, other) is
True:
return True
return (
cls is Protocol and other is getattr(typing, "Protocol", object())
)
@classmethod
def _proto_hook(cls, other):
if not cls. dict .get('_is_protocol', False):
return NotImplemented
108
break
109
return NotImplemented
return True
_is_protocol = True
_is_runtime_protocol = False
else:
class Protocol(metaclass=_ProtocolMeta):
# There is quite a lot of overlapping code with typing.Generic.
# Unfortunately it is hard to avoid this on Python <3.8,
# as the typing module on Python 3.7 doesn't let us subclass typing.Generic!
"""Base class for protocol classes. Protocol classes are defined as::
class Proto(Protocol):
def meth(self) -> int:
...
Such classes are primarily used with static type checkers that recognize
110
structural subtyping (static duck-typing), for example::
111
class C:
def meth(self) -> int:
return 0
class GenProto(Protocol[T]):
def meth(self) -> T:
...
"""
slots = ()
_is_protocol = True
_is_runtime_protocol = False
@typing._tp_cache
def class_getitem (cls, params):
if not isinstance(params, tuple):
params = (params,)
if not params and cls is not typing.Tuple:
raise TypeError(
f"Parameter list to {cls. qualname }[...] cannot be empty")
112
msg = "Parameters to generic types must be types."
params = tuple(typing._type_check(p, msg) for p in params)
if cls is Protocol:
# Generic can only be subscripted with unique type variables.
if not all(isinstance(p, typing.TypeVar) for p in params):
i=0
while isinstance(params[i], typing.TypeVar):
i += 1
raise TypeError(
"Parameters to Protocol[...] must all be type variables."
114
if sys.version_info >= (3, 8):
runtime_checkable = typing.runtime_checkable
else:
def runtime_checkable(cls):
"""Mark a protocol class as a runtime protocol, so that it
can be used with isinstance() and issubclass(). Raise
TypeError if applied to a non-protocol class.
@abc.abstractmethod
def int (self) -> int:
pass
@runtime_checkable
class SupportsFloat(Protocol):
"""An ABC with one abstract method float ."""
slots = ()
@abc.abstractmethod
def float (self) -> float:
pass
@runtime_checkable
class SupportsComplex(Protocol):
"""An ABC with one abstract method complex ."""
slots = ()
@abc.abstractmethod
def complex (self) -> complex:
pass
@runtime_checkable
class SupportsBytes(Protocol):
"""An ABC with one abstract method bytes ."""
slots = ()
@abc.abstractmethod
def bytes (self) -> bytes:
pass
@runtime_checkable
class SupportsIndex(Protocol):
slots = ()
116
@abc.abstractmethod
def index (self) -> int:
pass
@runtime_checkable
class SupportsAbs(Protocol[T_co]):
"""
An ABC with one abstract method abs that is covariant in its return type.
"""
slots = ()
@abc.abstractmethod
def abs (self) -> T_co:
pass
@runtime_checkable
class SupportsRound(Protocol[T_co]):
"""
An ABC with one abstract method round that is covariant in its return type.
"""
slots = ()
@abc.abstractmethod
def round (self, ndigits: int = 0) -> T_co:
pass
def _ensure_subclassable(mro_entries):
def inner(func):
if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
cls_dict = {
" call ": staticmethod(func),
" mro_entries ": staticmethod(mro_entries)
}
t = type(func. name , (), cls_dict)
return functools.update_wrapper(t(), func)
else:
117
func. mro_entries = mro_entries
return func
return inner
NotRequired.
# Generic TypedDicts are also impossible using typing.TypedDict on Python
<3.11.
# Aaaand on 3.12 we add orig_bases to TypedDict
# to enable better runtime introspection.
# On 3.13 we deprecate some odd ways of creating TypedDicts.
TypedDict = typing.TypedDict
_TypedDictMeta = typing._TypedDictMeta
is_typeddict = typing.is_typeddict
else:
# 3.10.0 and later
_TAKES_MODULE = "module" in
inspect.signature(typing._type_check).parameters
class _TypedDictMeta(type):
def new (cls, name, bases, ns,
total=True): """Create new typed dict class
object.
119
Subclasses and instances of TypedDict return actual dictionaries.
"""
for base in bases:
if type(base) is not _TypedDictMeta and base is not typing.Generic:
raise TypeError('cannot inherit from both a TypedDict type '
'and a non-TypedDict base class')
# typing.py generally doesn't let you inherit from plain Generic, unless
# the name of the class happens to be "Protocol" (or "_Protocol" on 3.7).
tp_dict = type. new (_TypedDictMeta, _fake_name, (*generic_base,
ns) dict),
annotations = {}
own_annotations = ns.get(' annotations ', {})
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
if _TAKES_MODULE:
own_annotations = {
n: typing._type_check(tp, msg, module=tp_dict. module )
for n, tp in own_annotations.items()
}
else:
own_annotations = {
n: typing._type_check(tp, msg)
for n, tp in own_annotations.items()
}
120
required_keys = set()
121
optional_keys = set()
annotations.update(own_annotations)
for annotation_key, annotation_type in own_annotations.items():
annotation_origin = get_origin(annotation_type)
if annotation_origin is Annotated:
annotation_args = get_args(annotation_type)
if annotation_args:
annotation_type = annotation_args[0]
annotation_origin = get_origin(annotation_type)
if annotation_origin is Required:
required_keys.add(annotation_key)
elif annotation_origin is NotRequired:
optional_keys.add(annotation_key)
elif total:
required_keys.add(annotation_key)
else:
optional_keys.add(annotation_key)
instancecheck = subclasscheck
122
_TypedDict = type. new (_TypedDictMeta, 'TypedDict', (), {})
TypedDict creates a dictionary type such that a type checker will expect all
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime.
Usage::
class Point2D(TypedDict):
x: int
y: int
label: str
The type info can be accessed via the Point2D. annotations dict, and
the Point2D. required_keys and Point2D. optional_keys frozensets.
TypedDict supports an additional equivalent form::
class Point2D(TypedDict,
total=False): x: int
y: int
This means that a Point2D TypedDict can have any of the keys omitted. A type
checker is only expected to support a literal False or True as the value of
the total argument. True is the default, and makes all items defined in the
class body be required.
123
The Required and NotRequired special forms can also be used to mark
individual keys as being required or not required::
class Point2D(TypedDict):
x: int # the "x" key must always be present (Required is the default)
y: NotRequired[int] # the "y" key can be omitted
if hasattr(typing, "_TypedDictMeta"):
_TYPEDDICT_TYPES = (typing._TypedDictMeta,
_TypedDictMeta) else:
_TYPEDDICT_TYPES = (_TypedDictMeta,)
def is_typeddict(tp):
"""Check if an annotation is a TypedDict class
For example::
class Film(TypedDict):
title: str
year: int
if hasattr(typing, "assert_type"):
assert_type = typing.assert_type
else:
def assert_type( val, typ):
"""Assert (to the type checker) that the value is of the given type.
if hasattr(typing, "Required"):
get_type_hints = typing.get_type_hints
else:
# replaces _strip_annotations()
def _strip_extras(t):
"""Strips Annotated, Required and NotRequired from a given type."""
if isinstance(t, _AnnotatedAlias):
return _strip_extras(t. origin )
if hasattr(t, " origin ") and t. origin in (Required, NotRequired):
return _strip_extras(t. args [0])
if isinstance(t, typing._GenericAlias):
stripped_args = tuple(_strip_extras(a) for a in t. args )
if stripped_args == t. args :
return t
return t.copy_with(stripped_args)
if hasattr(_types, "GenericAlias") and isinstance(t,
_types.GenericAlias): stripped_args = tuple(_strip_extras(a) for a in t.
args )
if stripped_args == t. args :
return t
return _types.GenericAlias(t. origin , stripped_args)
if hasattr(_types, "UnionType") and isinstance(t,
_types.UnionType): stripped_args = tuple(_strip_extras(a) for a in
t. args )
if stripped_args == t. args :
return t
return functools.reduce(operator.or_,
stripped_args) return t
126
This is often the same as obj. annotations , but it handles
forward references encoded as string literals, adds Optional[t] if
a
127
default value equal to None is set and recursively replaces all
'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
(unless 'include_extras=True').
At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
with extra annotations. The alias behaves like a normal typing alias,
instantiating is the same as instantiating the underlying type, binding
it to types is also the same.
"""
def init (self, origin, metadata):
if isinstance(origin, _AnnotatedAlias):
metadata = origin. metadata + metadata
origin = origin. origin
super(). init (origin, origin)
self. metadata = metadata
129
if not isinstance(other, _AnnotatedAlias):
return NotImplemented
130
if self. origin != other. origin :
return False
return self. metadata == other. metadata
class Annotated:
"""Add context specific metadata to a type.
Details:
slots = ()
@typing._tp_cache
def class_getitem (cls, params):
if not isinstance(params, tuple) or len(params) < 2:
raise TypeError("Annotated[...] should be used "
"with at least two arguments (a type and an "
"annotation).")
allowed_special_forms = (ClassVar, Final)
if get_origin(params[0]) in allowed_special_forms:
origin = params[0]
else:
msg = "Annotated[t, ...]: t must be a type."
origin = typing._type_check(params[0], msg)
metadata = tuple(params[1:])
return _AnnotatedAlias(origin, metadata)
# Python 3.8 has get_origin() and get_args() but those implementations aren't
# Annotated-aware, so we can't use those. Python 3.9's versions don't support
# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
if sys.version_info[:2] >= (3, 10):
get_origin = typing.get_origin
get_args = typing.get_args
# 3.7-3.9
else:
try:
# 3.9+
from typing import _BaseGenericAlias
132
except ImportError:
_BaseGenericAlias = typing._GenericAlias
try:
# 3.9+
from typing import GenericAlias as _typing_GenericAlias
except ImportError:
_typing_GenericAlias = typing._GenericAlias
def get_origin(tp):
"""Get the unsubscripted version of a type.
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
and Annotated. Return None for unsupported types. Examples::
get_origin(Literal[42]) is Literal
get_origin(int) is None
get_origin(ClassVar[int]) is ClassVar
get_origin(Generic) is Generic
get_origin(Generic[T]) is Generic
get_origin(Union[T, int]) is Union
get_origin(List[Tuple[T, T]][int]) == list
get_origin(P.args) is P
"""
if isinstance(tp, _AnnotatedAlias):
return Annotated
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias,
_BaseGenericAlias,
ParamSpecArgs, ParamSpecKwargs)):
return tp. origin
if tp is typing.Generic:
return typing.Generic
return None
def get_args(tp):
"""Get type arguments with all substitutions performed.
# 3.10+
if hasattr(typing, 'TypeAlias'):
TypeAlias = typing.TypeAlias
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def TypeAlias(self, parameters):
For example::
For example::
def _set_module(typevarlike):
# for pickling:
def_mod = _caller(depth=3)
if def_mod != 'typing_extensions':
typevarlike. module = def_mod
class _DefaultMixin:
"""Mixin for TypeVarLike defaults."""
slots = ()
init = _set_default
135
# Classes using this metaclass must provide a _backported_typevarlike ClassVar
class _TypeVarLikeMeta(type):
def instancecheck (cls, instance: Any) -> bool:
return isinstance( instance, cls._backported_typevarlike)
# Add default and infer_variance parameters from PEP 696 and 695
class TypeVar(metaclass=_TypeVarLikeMeta):
"""Type variable."""
_backported_typevarlike = typing.TypeVar
_set_default(typevar, default)
_set_module(typevar)
return typevar
137
# 3.7-3.9
else:
class _Immutable:
"""Mixin to indicate that object should not be copied."""
slots = ()
class ParamSpecArgs(_Immutable):
"""The args for a ParamSpec object.
This type is meant for runtime introspection and has no special meaning to
static type checkers.
"""
def init (self, origin):
self. origin = origin
class ParamSpecKwargs(_Immutable):
"""The kwargs for a ParamSpec object.
138
Given a ParamSpec object P, P.kwargs is an instance of
This type is meant for runtime introspection and has no special meaning to
static type checkers.
"""
def init (self, origin):
self. origin = origin
# 3.10+
if hasattr(typing, 'ParamSpec'):
_backported_typevarlike = typing.ParamSpec
140
paramspec = typing.ParamSpec(name, bound=bound,
covariant=covariant,
contravariant=contravariant)
paramspec. infer_variance = infer_variance
_set_default(paramspec, default)
_set_module(paramspec)
return paramspec
# 3.7-3.9
else:
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
class ParamSpec(list, _DefaultMixin):
"""Parameter specification variable.
Usage::
P = ParamSpec('P')
T = TypeVar('T')
P = ParamSpec('P')
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y
Note that only parameter specification variables defined in global scope can
be pickled.
"""
@property
def args(self):
return ParamSpecArgs(self)
@property
def kwargs(self):
return ParamSpecKwargs(self)
142
def init (self, name, *, bound=None, covariant=False,
contravariant=False, infer_variance=False, default=_marker):
super(). init ([self])
self. name = name
self. covariant = bool(covariant)
self. contravariant = bool(contravariant)
self. infer_variance = bool(infer_variance)
if bound:
self. bound = typing._type_check(bound, 'Bound must be a type.')
else:
self. bound = None
_DefaultMixin. init (self, default)
# for pickling:
def_mod = _caller()
if def_mod != 'typing_extensions':
self. module = def_mod
# 3.7-3.9
if not hasattr(typing, 'Concatenate'):
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
class _ConcatenateGenericAlias(list):
# Flag in 3.8.
_special = False
@property
def parameters (self):
return tuple(
tp for tp in self. args if isinstance(tp, (typing.TypeVar, ParamSpec))
)
144
# 3.7-3.9
@typing._tp_cache
def _concatenate_getitem(self, parameters):
if parameters == ():
raise TypeError("Cannot take a Concatenate of no types.")
if not isinstance(parameters, tuple):
parameters = (parameters,)
if not isinstance(parameters[-1], ParamSpec):
raise TypeError("The last parameter to Concatenate should be a "
"ParamSpec variable.")
msg = "Concatenate[arg, ...]: each arg must be a type."
parameters = tuple(typing._type_check(p, msg) for p in parameters)
return _ConcatenateGenericAlias(self, parameters)
# 3.10+
if hasattr(typing, 'Concatenate'):
Concatenate = typing.Concatenate
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def Concatenate(self, parameters):
"""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
higher order function which adds, removes or transforms parameters of a
callable.
For example::
Concatenate = _ConcatenateForm(
'Concatenate',
doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
higher order function which adds, removes or transforms parameters of a
callable.
For example::
# 3.10+
if hasattr(typing, 'TypeGuard'):
TypeGuard = typing.TypeGuard
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def TypeGuard(self, parameters):
"""Special typing form used to annotate the return type of a user-defined
type guard function. ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
Using ``-> TypeGuard`` tells the static type checker that for a given
function:
For example::
``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
"""
item = typing._type_check(parameters, f'{self} accepts only a single type.')
return typing._GenericAlias(self, (item,))
# 3.7-3.8
else:
class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
def getitem (self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type')
return typing._GenericAlias(self, (item,))
TypeGuard =
_TypeGuardForm( 'TypeGuard',
Using ``-> TypeGuard`` tells the static type checker that for a given
function:
For example::
``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
148
""")
raise AttributeError(item)
self] def
149
raise TypeError(f"{self} cannot be used with isinstance()")
150
def subclasscheck (self, cls):
raise TypeError(f"{self} cannot be used with issubclass()")
@typing._tp_cache
def getitem (self, parameters):
return self._getitem(self,
parameters)
if hasattr(typing, "LiteralString"):
LiteralString = typing.LiteralString
else:
@_SpecialForm
def LiteralString(self, params):
"""Represents an arbitrary literal string.
Example::
"""
raise TypeError(f"{self} is not subscriptable")
if hasattr(typing, "Self"):
Self = typing.Self
else:
@_SpecialForm
def Self(self, params):
"""Used to spell the type of "self" in classes.
151
Example::
class ReturnsSelf:
def parse(self, data: bytes) -> Self:
...
return self
"""
if hasattr(typing, "Never"):
Never = typing.Never
else:
@_SpecialForm
def Never(self, params):
"""The bottom type, a type that has no members.
None:
pass
152
"""
if hasattr(typing, 'Required'):
Required = typing.Required
NotRequired =
typing.NotRequired
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def Required(self, parameters):
"""A special typing construct to mark a key of a total=False TypedDict
as required. For example:
class Movie(TypedDict,
total=False): title: Required[str]
year: int
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
@_ExtensionsSpecialForm
def NotRequired(self, parameters):
"""A special typing construct to mark a key of a TypedDict as
potentially missing. For example:
class Movie(TypedDict):
title: str
year: NotRequired[int]
153
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
"""
item = typing._type_check(parameters, f'{self._name} accepts only a single
type.')
return typing._GenericAlias(self, (item,))
else:
class _RequiredForm(_ExtensionsSpecialForm,
_root=True): def getitem (self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
Required = _RequiredForm(
'Required',
doc="""A special typing construct to mark a key of a total=False TypedDict
as required. For example:
class Movie(TypedDict,
total=False): title: Required[str]
year: int
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
class Movie(TypedDict):
154
title: str
year: NotRequired[int]
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
""")
_UNPACK_DOC = """\
Type unpack operator.
The type unpack operator takes the child types from some container type,
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
example:
Ts = TypeVarTuple('Ts')
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into
the # `Generic[]`.)
class Bar(Generic[Unpack[Ts]]):
... Bar[int] # Valid
Bar[int, str] # Also valid
From Python 3.11, this can also be done using the `*` operator:
Foo[*tuple[int, str]]
class Bar(Generic[*Ts]): ...
class Movie(TypedDict):
155
name: str
year: int
# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
Note that there is only some runtime checking of this operator. Not
everything the runtime allows may be accepted by static type checkers.
if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
Unpack = typing.Unpack
def _is_unpack(obj):
return get_origin(obj) is Unpack
@_UnpackSpecialForm
def Unpack(self, parameters):
item = typing._type_check(parameters, f'{self._name} accepts only a single
type.')
return _UnpackAlias(self, (item,))
def _is_unpack(obj):
return isinstance(obj, _UnpackAlias)
else:
class _UnpackAlias(typing._GenericAlias, _root=True):
156
class = typing.TypeVar
def _is_unpack(obj):
return isinstance(obj, _UnpackAlias)
_backported_typevarlike = typing.TypeVarTuple
else:
class TypeVarTuple(_DefaultMixin):
"""Type variable tuple.
Usage::
Ts = TypeVarTuple('Ts')
157
In the same way that a normal type variable is a stand-in for a single
type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
type such as ``Tuple[int, str]``.
The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
where ``T1`` and ``T2`` are type variables. To use these type variables
as type parameters of ``Array``, we must *unpack* the type variable tuple using
the star operator: ``*Ts``. The signature of ``Array`` then behaves
as if we had simply written ``class Array(Generic[T1, T2]): ...``.
In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
us to parameterise the class with an *arbitrary* number of type parameters.
class Array(Generic[*Ts]):
"""
159
def iter (self):
yield self. unpacked
# for pickling:
def_mod = _caller()
if def_mod != 'typing_extensions':
self. module = def_mod
if hasattr(typing, "reveal_type"):
reveal_type = typing.reveal_type
else:
def reveal_type( obj: T) -> T:
"""Reveal the inferred type of a variable.
x: int = 1
reveal_type(x)
"""
print(f"Runtime type is {type( obj). name !r}", file=sys.stderr)
return obj
if hasattr(typing, "assert_never"):
assert_never = typing.assert_never
else:
def assert_never( arg: Never) -> Never:
"""Assert to the type checker that a line of code is unreachable.
Example::
"""
raise AssertionError("Expected code to be unreachable")
161
if sys.version_info >= (3, 12):
# dataclass_transform exists in 3.11 but lacks the frozen_default parameter
dataclass_transform = typing.dataclass_transform
else:
def dataclass_transform(
*,
Example:
_T = TypeVar("_T")
@create_model
class CustomerModel:
id: int
name: str
class CustomerModel(ModelBase):
id: int
name: str
# Used on a metaclass
@dataclass_transform()
class ModelMeta(type): ...
class CustomerModel(ModelBase):
id: int
name: str
"""
def decorator(cls_or_fn):
163
cls_or_fn. dataclass_transform ={
164
"eq_default": eq_default,
"order_default": order_default,
"kw_only_default": kw_only_default,
"frozen_default": frozen_default,
"field_specifiers": field_specifiers,
"kwargs": kwargs,
}
return cls_or_fn
return decorator
if hasattr(typing, "override"):
override = typing.override
else:
_F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
Usage:
class Base:
def method(self) -> None: ...
pass
class Child(Base):
@override
def method(self) -> None:
super().method()
165
"""
try:
arg. override = True
except (AttributeError, TypeError):
# Skip the attribute silently if it is not writable.
# AttributeError happens if the object has slots or a
# read-only property, TypeError if it's a builtin class.
pass
return arg
if hasattr(typing, "deprecated"):
deprecated = typing.deprecated
else:
_T = typing.TypeVar("_T")
def deprecated(
msg: str,
*,
category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
stacklevel: int = 1,
) -> typing.Callable[[_T], _T]:
"""Indicate that a class, function or overload is deprecated.
Usage:
@deprecated("Use B instead")
class A:
pass
@deprecated("Use g instead")
def f():
pass
@overload
@deprecated("int support is deprecated")
def g(x: int) -> int: ...
@overload
def g(x: str) -> int: ...
166
When this decorator is applied to an object, the type checker
will generate a diagnostic on usage of the deprecated object.
"""
def decorator( arg: _T) ->
_T: if category is None:
arg. deprecated = msg
return arg
elif isinstance( arg, type):
original_new = arg. new
has_init = arg. init is not object. init
@functools.wraps(original_new)
def new (cls, *args, **kwargs):
warnings.warn( msg, category=category, stacklevel=stacklevel + 1)
if original_new is not object. new :
return original_new(cls, *args, **kwargs)
# Mirrors a similar check in object. new .
elif not has_init and (args or kwargs):
raise TypeError(f"{cls. name }() takes no arguments")
else:
return original_new(cls)
167
arg. new = staticmethod( new )
arg. deprecated = new . deprecated = msg
return arg
elif callable( arg):
@functools.wraps( arg)
def wrapper(*args, **kwargs):
warnings.warn( msg, category=category, stacklevel=stacklevel +
1) return arg(*args, **kwargs)
raise TypeError(
"@deprecated decorator with non-None category must be applied to
" f"a class or callable, not { arg!r}"
)
return decorator
169
else:
def _make_nmtuple(name, types, module, defaults=()):
fields = [n for n, t in types]
annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
for n, t in types}
nm_tpl = collections.namedtuple(name, fields,
defaults=defaults, module=module)
nm_tpl. annotations = nm_tpl. new . annotations = annotations
# The `_field_types` attribute was removed in 3.9;
# in earlier versions, it is the same as the ` annotations ` attribute
if sys.version_info < (3, 9):
nm_tpl._field_types = annotations
return nm_tpl
_prohibited_namedtuple_fields = typing._prohibited
_special_namedtuple_fields = frozenset({' module ', ' name ',
' annotations '})
class _NamedTupleMeta(type):
def new (cls, typename, bases, ns):
assert _NamedTuple in bases
for base in bases:
if base is not _NamedTuple and base is not typing.Generic:
raise TypeError(
'can only inherit from a NamedTuple type and Generic')
bases = tuple(tuple if base is _NamedTuple else base for base in
bases) types = ns.get(' annotations ', {})
default_names = []
for field_name in types:
if field_name in ns:
default_names.append(field_name)
elif default_names:
raise TypeError(f"Non-default namedtuple field {field_name} "
f"cannot follow default field"
f"{'s' if len(default_names) > 1 else ''} "
f"{', '.join(default_names)}")
nm_tpl = _make_nmtuple(
typename, types.items(),
defaults=[ns[n] for n in default_names],
module=ns[' module ']
170
)
nm_tpl. bases = bases
if typing.Generic in bases:
if hasattr(typing, '_generic_class_getitem'): # 3.12+
nm_tpl. class_getitem =
classmethod(typing._generic_class_getitem)
else:
class_getitem = typing.Generic. class_getitem . func
nm_tpl. class_getitem = classmethod(class_getitem)
# update from user namespace without overriding special namedtuple
attributes
for key in ns:
if key in _prohibited_namedtuple_fields:
raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
@_ensure_subclassable(_namedtuple_mro_entries)
def NamedTuple( typename, fields=_marker, **kwargs):
"""Typed version of namedtuple.
Usage::
class Employee(NamedTuple):
name: str
id: int
else:
deprecated_thing = "Failing to pass a value for the 'fields'
parameter" example = f"`{ typename} =
NamedTuple({ typename!r}, [])`" deprecation_msg = (
"{name} is deprecated and will be disallowed in Python {remove}. "
"To create a NamedTuple class with 0 fields "
"using the functional syntax, "
"pass an empty list, e.g. "
) + example + "."
elif fields is None:
if kwargs:
raise TypeError(
"Cannot pass `None` as the 'fields' parameter "
"and also specify fields using keyword arguments"
)
else:
deprecated_thing = "Passing `None` as the 'fields' parameter"
example = f"`{ typename} = NamedTuple({ typename!r}, [])`"
deprecation_msg = (
"{name} is deprecated and will be disallowed in Python {remove}. "
"To create a NamedTuple class with 0 fields "
"using the functional syntax, "
"pass an empty list, e.g. "
) + example + "."
172
elif kwargs:
raise TypeError("Either list of fields or keywords"
" can be provided to NamedTuple, not
both") if fields is _marker or fields is
None:
warnings.warn(
deprecation_msg.format(name=deprecated_thing, remove="3.15"),
DeprecationWarning,
stacklevel=2,
)
fields = kwargs.items()
nt = _make_nmtuple( typename, fields, module=_caller())
nt. orig_bases = (NamedTuple,)
return nt
if hasattr(collections.abc, "Buffer"):
Buffer = collections.abc.Buffer
else:
class Buffer(abc.ABC):
"""Base class for classes that implement the buffer protocol.
174
To indicate support for the buffer protocol in earlier versions,
inherit from this ABC, either in a stub file or at runtime,
or use ABC registration. This ABC provides no methods, because
there is no Python-accessible methods shared by pre-3.12 buffer
classes. It is useful primarily for static checks.
"""
get_original_bases = _types.get_original_bases
else:
def get_original_bases( cls):
"""Return the class's "original" bases prior to modification by
` mro_entries `.
Examples::
T = TypeVar("T")
class Foo(Generic[T]): ...
class Bar(Foo[int], float): ...
class Baz(list[str]): ...
Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
Spam = TypedDict("Spam", {"a": int, "b": str})
else:
class NewType:
"""NewType creates simple unique types with almost zero
runtime overhead. NewType(name, tp) is considered a subtype of tp
by static type checkers. At runtime, NewType(name, tp) returns
a dummy callable that simply returns its argument. Usage::
UserId = NewType('UserId', int)
def name_by_id(user_id: UserId) -> str:
...
UserId('user') # Fails type check
name_by_id(42) # Fails type check
name_by_id(UserId(42)) # OK
num = UserId(5) + 1 # type: int
"""
class Dummy:
def init_subclass (cls):
subcls_name = cls. name
raise TypeError(
f"Cannot subclass an instance of NewType. "
f"Perhaps you were looking for: "
f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
)
return (Dummy,)
if hasattr(typing, "TypeAliasType"):
177
TypeAliasType = typing.TypeAliasType
else:
def _is_unionable(obj):
"""Corresponds to is_unionable() in unionobject.c in CPython."""
return obj is None or isinstance(obj, (
type,
_types.GenericAlias,
_types.UnionType,
TypeAliasType,
))
class TypeAliasType:
"""Create named, parameterized type aliases.
is equivalent to:
T = TypeVar("T")
ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
The name ListOrSet can then be used as an alias for the type it refers to.
The type_params argument should contain all the type parameters used
in the value of the type alias. If the alias is not generic, this
argument is omitted.
Static type checkers should only support type aliases declared using
TypeAliasType that follow these rules:
"""
178
def init (self, name: str, value, *,
type_params=()): if not isinstance(name, str):
raise TypeError("TypeAliasType name must be a
string") self. value = value
self. type_params = type_params
parameters = []
for type_param in type_params:
if isinstance(type_param, TypeVarTuple):
parameters.extend(type_param)
else:
parameters.append(type_param)
self. parameters = tuple(parameters)
def_mod = _caller()
if def_mod != 'typing_extensions':
self. module = def_mod
# Setting this attribute closes the TypeAliasType from further
modification self. name = name
self._raise_attribute_error( name)
super(). setattr ( name, value)
if hasattr(typing, "is_protocol"):
is_protocol = typing.is_protocol
get_protocol_members = typing.get_protocol_members
else:
def is_protocol( tp: type) -> bool:
"""Return True if the given type is a Protocol.
Example::
>>> is_protocol(int)
False
"""
return (
isinstance( tp, type)
and getattr( tp, '_is_protocol', False)
and tp is not Protocol
and tp is not getattr(typing, "Protocol", object())
)
Example::
Collection = typing.Collection
Container = typing.Container
Dict = typing.Dict
ForwardRef = typing.ForwardRef
FrozenSet = typing.FrozenSet
Generator = typing.Generator
Generic = typing.Generic
Hashable = typing.Hashable
IO = typing.IO
ItemsView = typing.ItemsView
Iterable = typing.Iterable
Iterator = typing.Iterator
KeysView = typing.KeysView
List = typing.List
Mapping = typing.Mapping
182
MappingView = typing.MappingView
Match = typing.Match
MutableMapping = typing.MutableMapping
MutableSequence = typing.MutableSequence
MutableSet = typing.MutableSet
Optional = typing.Optional
Pattern = typing.Pattern
Reversible = typing.Reversible
Sequence = typing.Sequence
Set = typing.Set
Sized = typing.Sized
TextIO = typing.TextIO
Tuple = typing.Tuple
Union = typing.Union
ValuesView = typing.ValuesView
cast = typing.cast
no_type_check = typing.no_type_check
no_type_check_decorator = typing.no_type_check_decorator
183
5) Testing
5.1) Test Strategy/ Test Case
1. Requirement Analysis:
- Understand the functional and non-functional requirements of DevSearch.
- Analyze user stories, use cases, and acceptance criteria to define
test scenarios.
2. Test Planning:
- Define testing objectives, scope, and timelines.
- Allocate resources, including testing environments, tools, and team members.
- Determine testing techniques and methodologies, such as manual
testing, automated testing, and exploratory testing.
184
5. Functional Testing:
- Conduct functional testing to verify that all features and modules
of DevSearch work as intended.
- Test search functionality, user authentication, profile management,
documentation access, community interaction, and recommendation
engine.
- Verify integration with external tools and platforms for
seamless interoperability.
6. Usability Testing:
- Evaluate the user interface, navigation flow, and overall user experience
of DevSearch.
- Test accessibility, responsiveness, and compatibility across different
devices and browsers.
- Gather feedback from real users to identify usability issues and areas
for improvement.
7. Performance Testing:
- Perform load testing, stress testing, and scalability testing to assess
the performance of DevSearch under various conditions.
- Measure response times, throughput, and resource utilization to
identify performance bottlenecks.
- Optimize system architecture and configurations to ensure
optimal performance and responsiveness.
8. Security Testing:
- Conduct security testing to identify vulnerabilities and ensure data protection.
- Test authentication mechanisms, authorization controls, data encryption,
and secure communication protocols.
- Perform penetration testing and vulnerability scanning to uncover
potential security risks.
185
9. Compatibility Testing:
- Verify compatibility with different operating systems, browsers, and devices.
- Test DevSearch on various platforms to ensure consistent functionality
and user experience across different environments.
186
6) Future Enhancement
2. Interactive Tutorials:
Integrate interactive tutorials and coding exercises directly into
DevSearch to provide hands-on learning experiences for users, helping
them learn new technologies more effectively.
187
7. Code Analysis and Debugging Tools: Integrate code analysis
tools and debugging utilities into DevSearch to help developers
identify and fix issues in their code more efficiently.
7) Screenshot:-
Home page
189
Profile page
190
Message page
191
Project page
192
About the page
193
Login page
194
195
8) Bibliography
Online Resources:
TensorFlow Documentation:
https://www.tensorflow.org/ OpenCV Documentation:
https://docs.opencv.org/
GitHub Repositories:
GitHub - TensorFlow:
196
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: