blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
2cd39927b2095f6d6c5f8952918c580f5fc2442f | ardalothlorien/python-warsztaty-2 | /zadania/zadanie2.py | 790 | 3.90625 | 4 | import turtle
with open('zolw.txt') as plik: # wczytujemy plik
for linia in plik: # iterujemy po liniach
linia = linia.strip() # usuwamy biale znaki z poczatku i konca
podzielone = linia.split() # dzielimy po spacjach
komenda = podzielone[0] # pierwszy element podzielonego
lic... |
a51cacae7e51367d5450d2c769e60924a50e24e9 | finescribe83/linear_regression | /Linear_regression_program.py | 2,405 | 3.859375 | 4 | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from statistics import mean
#setting the date as the index since it is located in 3rd column from left
#data is with saved as AP.csv which is available in the same direc... |
780eabe514383f635b01477446988e40128eb6af | DDL/trial-exam-python-2016-06-06 | /3.py | 884 | 4.03125 | 4 | # Create a class that represents a cuboid:
# It should take it's three sizes as constructor parameters (numbers)
# It should have a method called `getSurface` that returns the cuboid's surface
# It should have a method called `getVolume` that returns the cuboid's volume
class Cuboid():
def __init__(self, length, w... |
dc2d0398fad08c5c22265f4c394888188d34ec2f | gabrielcicero45/ECT_COMPUTACAO_NUMERICA | /Terceira Parte/Integral/Integral Trapézio Composto.py | 1,086 | 3.8125 | 4 | # made by Leonardo Saads
import math
a = float(input())
b = float(input())
numero = int(input())
def particao(function, valor_a, valor_b, numero_de_particoes):
particionar = (valor_b - valor_a) / numero_de_particoes
criador_particao = valor_a
criador_x = [] # cria o vetor x
criador_y = [... |
45604eed82920a670b167d3197ff138aa4a8dcb4 | gabrielcicero45/ECT_COMPUTACAO_NUMERICA | /Primeira Parte/Séries de Taylor/Taylor_exponencial.py | 349 | 3.6875 | 4 | import math
def taylor_exp(x0: float, x: float, n: int):
"""
Aproximará a função e^x pela série de Taylor.
x0 -> ponto incial.
x -> ponto para aproximação.
n -> número de termos.
"""
soma = 0
for i in range(n):
soma += math.e ** x0 * ((x - x0) ** i) / math.factorial... |
4b10808168db598575839cf3356ea958400e6d04 | MarioGN/python | /oop/ex-veiculos/exemplo_interface.py | 1,673 | 3.8125 | 4 | from abc import ABC, abstractmethod
class Veiculo(ABC):
@abstractmethod
def ligar(self):
pass
@abstractmethod
def desligar(self):
pass
@abstractmethod
def acelerar(self, velocidade=10):
pass
@abstractmethod
def freiar(self):
pass
class Carro(Veiculo... |
e49a973b5297e852b9556483d56113e371dd7dcc | zouberou-sayibou/Python-Projects | /Hangman Game with Graphics/playHangman.py | 3,550 | 3.828125 | 4 | from cs1graphics import*
from hangmanGraphics import*
secret = input("Please put in a secret word: ")
def playHangman(secret):
paper = Canvas(600,600, 'white', "HANGMAN-GAME")
secreT = secret.upper() #making the secret number all capital
completion_list = list('_'*len(secret)) #creating the list of the pl... |
f31ebd93575ce0fa24c8586784d2f504d3060fe0 | jomunlak/ThisIsCodingTest_withPython | /그래프_어두운 길.py | 721 | 3.78125 | 4 | # 어두운 길
def find(parent, x):
if parent[x] != x:
parent[x] = find(parent, parent[x])
return parent[x]
def union(parent, a, b):
a = find(parent, a)
b = find(parent, b)
if a<b: parent[b] = a
else: parent[a] = b
n, m = map(int, input().split())
parent = list(range(n))
sumValue = 0
edges = []
for _ in ran... |
53f7db25b5a27fe0de3d12184fa1199a46e5a340 | IvankaCaron/Robot | /robots/modelNG.py | 1,058 | 3.578125 | 4 | from robots.model import Robot
class RobotNG(Robot):
def __init__(self, nom):
super().__init__(nom)
self.__turbo = False
def avance(self,pas=2):
if self.__turbo==True:
pas = pas * 3
for i in range(pas):
super().avance()
def demiTour(se... |
6534ad9e4ff81bc07d81a7e3011b0032c3d303db | Ziadpydev/PythonTutorials | /chp20.py | 452 | 3.8125 | 4 | #x = int(input("How Many Candies?"))
#i = 1
#candy = 20
#while i<=x:
# if i>candy:
# print("Insufficient Candy")
# break
# print(i,"Candy")
# i+=1
#print()
#print("Numbers")
#for i in range(1,30):
# if i%3==0 or i%5==0:
# continue
# print(i)
print("Fibonaci Series")
j=1
i=1
temp=0... |
491f6f58a2c37af8d167448e14182a8f51111dc4 | Ziadpydev/PythonTutorials | /chp18.py | 343 | 3.640625 | 4 | i = 1
while i<=5:
j = 1
print("Zaid ", end="")
while j<=4:
print("Rocks ", end="")
j = j+1
i = i+1
print()
i=1
for i in range(1,101):
if i%3==0 or i%5==0:
continue
print(i)
i=1
print("Perfect Squares")
for i in range(1,501):
if(i**2<=500):
print(i**2)
... |
e2d93cdb46eb01b76528733b7aed2fc1cf1b8988 | Ziadpydev/PythonTutorials | /chp30.py | 199 | 3.5625 | 4 | def person(name,age=18):
print(name)
print(age)
def sum(a,*b):
c=a
for i in b:
c=c+i
print(c)
person('Zaid',27)
person(age=27,name='Zaid')
person('Zaid')
sum(5,6,12,34) |
7d4f38bd5e1faf16bb2d6cd9b10767ba5ab0658f | joeyFuck/joeyPython | /1高级特性/2生成器.py | 849 | 3.734375 | 4 | #generator
L = [x*x for x in range(10)]
print(L)
G = (x*x for x in range(10))
print(G)
#for x in G:
# print(G.__next__())
#斐波拉契数列
def fib1(max):
n,a,b = 0,0,1
while(n<max):
print(b)
a,b = b,a+b
n+=1
return 'done'
#fib1(6)
#fib函数实际上是定义了斐波拉契数列的推算规则
#要把fib函数变成generator,只需要把print(b... |
81955b1f833cb06d674f435c560e32de17d64677 | joeyFuck/joeyPython | /2函数式编程/2.1高级函数/高阶函数.py | 631 | 4.0625 | 4 | #高阶函数 higher order function
# 变量可以指向函数
l = abs(-10.123)
print(l)
joey = abs
print(joey(-5))
# 函数名只是个变量,abs是内置的函数名,如果手动将其指向其他对象,则变为其他变量
#abs = 10
#print(abs)
#print(abs(-10))#TypeError: 'int' object is not callable
#既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
def add(x,y,f):
return f(x)+f(y)
print(... |
448237c962ff904902e57d4fdf38fc41b64817eb | joeyFuck/joeyPython | /17异步IO/三asyncio/2示例.py | 1,230 | 3.578125 | 4 | import threading
import asyncio
@asyncio.coroutine
def hello():
print('Hello world! (%s)' % threading.currentThread())
yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
... |
e709e252a21f6da6164e207ef1a2c0b644a0a452 | sanayei/mlalg | /regression.py | 916 | 3.5 | 4 | import numpy as np
class Regression:
def __init__(self, learning_rate=0.01, max_it=1000):
self.learning_rate = learning_rate
self.max_it = max_it
self.W = None
def cost_fn(self, X, y):
prediction = self.predict(X)
error = prediction - y
m = y.size
cost ... |
3258e8592459eb9fadc61add0ff317f5f3ca4aaf | francechi/Python | /Listas.py | 201 | 3.984375 | 4 | diccionario={23:"Jordan", "Nombre":"Michael", "Equipo":"Chicago", "anillos":{"temporadas":[1991,1992,1993,1996,1997,1998]}}
print(diccionario.keys())
print(diccionario.values())
print(len(diccionario)) |
4d7a671bd1c582fd9556bdf6b3a77044b4094db8 | francechi/Python | /Ejercicios Prácticos.py | 528 | 3.640625 | 4 | contraseña=input("Contraseña: ")
contador= 0
for i in contraseña:
if i== " ":
contador= contador * 0
if i==i:
contador= contador + 1
if contador>8 and contador<15:
print("Contraseña OK")
else:
print("Contraseña incorrecta")
email=input("Email: ")
contador1= 0
elpunto= False
for e in email:
if e== "@":
... |
03915958c720a8dc8cfbdb2b52009d9ce0adcbd5 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/z_duck_typing.py | 392 | 3.953125 | 4 | """
Purpose: Duck Typing
Duck Typing refers to the principle of not constraining or binding
the code to specific data types.
"""
class Duck:
def swim(self):
print("Duck swimming")
def fly(self):
print("Duck flying")
class Whale:
def swim(self):
print("Whale swimming"... |
f91c9dd7ea1c66a0a757d32dc00c3e1f0adef7e7 | udhayprakash/PythonMaterial | /python3/06_Collections/03_Sets/a_sets_usage.py | 1,219 | 4.40625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Purpose: Working with Sets
Properties of sets
- creating using {} or set()
- can't store duplicates
- sets are unordered
- can't be indexed
- Empty sets need to be represented using set()
- stores only immutable object - ... |
627c4ac2e040d41a4e005253e1dd7c20f9d5cf63 | udhayprakash/PythonMaterial | /python3/04_Exceptions/11_raising_exception.py | 1,248 | 4.28125 | 4 | #!/usr/bin/python3
"""
Purpose: Raising exceptions
"""
# raise
# RuntimeError: No active exception to reraise
# raise Exception()
# Exception
# raise Exception('This is an error')
# Exception: This is an error
# raise ValueError()
# ValueError
# raise TypeError()
# raise NameError('This is name error')
# NameErro... |
a7d1b42f27990b36a9cceea4278e65e9087fb7b7 | udhayprakash/PythonMaterial | /python3/06_Collections/03_Sets/g_hashables.py | 1,339 | 4.0625 | 4 | #!/usr/bin/python3
"""
Purpose: hash() function
"""
print(f"{hash(123) =}")
assert (123).__hash__() == hash(123)
# my_set = {1, 2, [3, 4]} # TypeError: unhashable type: 'list'
# my_set = {1, 2, {3, 4}} # TypeError: unhashable type: 'set'
# my_set = {1, 2, {3:4}} # TypeError: unhashable type: 'dict'
my_set = {1,... |
2c783f03dea622499d96e1ca78992b4169a48036 | udhayprakash/PythonMaterial | /python3/13_OOP/b_MRO_inheritance/07b_Tight_coupling.py | 1,530 | 3.640625 | 4 | """
Purpose: Module coupling, or tight coupling
It refers to the degree of interdependence between modules in a software system.
It occurs when modules are closely connected and rely heavily on each other's internal details and implementation.
Tight coupling can make the system less flexible, maintainable, ... |
79eb6b4be07ee81b3a360a3fe2ab759947735a5e | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/b1_process_pool.py | 1,587 | 4.40625 | 4 | """
Purpose: Multiprocessing with Pools
Pool method allows users to define the number of workers and
distribute all processes to available processors in a
First-In-First-Out schedule, handling process scheduling automatically.
Pool method is used to break a function into multiple small parts using
... |
fd8ebadb511ebb1df2219d65b09c58f071187b56 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/e_Calculator2/test_calculator4.py | 738 | 3.5 | 4 | import math
import unittest
from calculator import ArithmeticOperations
class TestMultiplication(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.mul = ArithmeticOperations().multiplication
def test01_multiplication(self):
assert self.mul(10, 20) == 200
self.asse... |
b3e6a1ed4b2aa616179807ff3ded322e9e0ee0e1 | udhayprakash/PythonMaterial | /python3/10_Modules/15_turtle_module/traffic_light.py | 2,135 | 3.921875 | 4 | #!/usr/bin/python
"""
Purpose: Traffic Light Simulation
"""
import turtle
def draw_signal_stand():
"""Draw a nice housing to hold the traffic lights"""
tess.pensize(3)
tess.color("black", "white")
tess.begin_fill()
tess.forward(80)
tess.left(90)
tess.forward(157)
tess.circle(40, 180)
... |
1bad217136738b325f1dd38d8484904f13d69989 | udhayprakash/PythonMaterial | /python3/07_Functions/014_keyword_only_args.py | 1,541 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Functions Demo
Function with Keyword ONLY args
Named arguments appearing after '*' can only be
passed by keyword
Present only in Python 3.X
"""
def servr_login(server_name, user_name, password):
print(
f"""
{server_name =}
{user_name =}
... |
d71e5012d3496298f770c075eaeaa3afe8f1a168 | udhayprakash/PythonMaterial | /python3/04_Exceptions/07_exception_handling_order.py | 1,672 | 3.921875 | 4 | #!/usr/bin/python3
"""
Purpose: Exception handling
In [1]: int("123")
Out[1]: 123
In [2]: int("123.123")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In [2], line 1
----> 1 int("123.123")
ValueError: inval... |
6782bce539f905db7c05238f1b906edf054b5aeb | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/f_custom_thread_class.py | 939 | 4.375 | 4 | #!/usr/bin/python
# Python multithreading example to print current date.
# 1. Define a subclass using Thread class.
# 2. Instantiate the subclass and trigger the thread.
import datetime
import threading
class myThread(threading.Thread):
def __init__(self, name, counter):
threading.Thread.__init__(self... |
0f39ba4fb7de201f9bf21ceac445f5246c785886 | udhayprakash/PythonMaterial | /python3/04_Exceptions/13_custom_exceptions.py | 1,183 | 4.15625 | 4 | #!/usr/bin/python3
"""
Purpose: Using Custom Exception
"""
# # Method 1 - stop when exception is raised
# try:
# votes = 0
# i = 0
# while i < 5:
# age = int(input('Enter your age:'))
# if age <= 0:
# raise Exception('Invalid Entry for the age!')
# elif age < 18:
# ... |
2e7734c27ca1713f780710c935c2981fa7bc0577 | udhayprakash/PythonMaterial | /python3/09_Iterators_generators_coroutines/02_iterators/e_user_defined_iterators.py | 926 | 4.65625 | 5 | #!/usr/bin/python3
"""
Purpose: Iterators
- To get values from an iterator objects
1. Iterate over it
- for loop
- converting to other iterables
- list(), tuple(), set(), dict()
2. To apply next()
... |
37b606ca02ac4bfd4e53e038c0280ee660d3277c | udhayprakash/PythonMaterial | /python3/10_Modules/04a_os_module/display_tree_of_dirs.py | 637 | 4.125 | 4 | #!/usr/bin/python
"""
Purpose: To display the tree strcuture of directories only , till three levels
test
sub1
sub2
subsub1
"""
import os
import sys
MAX_DEPTH = 3 # levels
given_path = sys.exec_prefix # input('Enter the path:')
print(given_path)
def display_folders(_path, _depth):
if _depth !=... |
579801db3bc333555bda77d629ca7a6f608c51aa | udhayprakash/PythonMaterial | /python3/13_OOP/a_OOP/07_with_classes.py | 1,100 | 3.96875 | 4 | """
Purpose: Solving Bank account management problem, using classes
"""
class Account:
def __init__(self, name):
self.balance = 0
self.account_holder = name
def deposit(self, amount):
self.balance = self.balance + amount
def withdrawl(self, amount):
self.balance = self.ba... |
ca274fd46640be5558c0135b7d76e090dd0db8f6 | udhayprakash/PythonMaterial | /python3/03_Language_Components/07_Conditional_Operations/f_temperature_conversion.py | 943 | 3.953125 | 4 | #!/usr/bin/python3
"""
Purpose: Temperature Conversions
- celsius to fahrenheit , or vice versa
user input : 23c
output : xF
user input : 23F
output : xC
23c, 23C, 23F, 23f
23C, 23F
23 C
23C
"""
import sys
temperature = input("Enter the temperature, followed by C or F:").upper().strip()
if "C" in temp... |
434db15da66e82503542f09919fac4e12bd390ae | udhayprakash/PythonMaterial | /python3/02_Basics/02_String_Operations/q_bytearray_strings.py | 1,033 | 4.03125 | 4 | #!/usr/bin/python
"""
Purpose: demo of bytearray strings
bytearray objects are a mutable strings
"""
# Creating an empty instance:
print("bytearray() ", bytearray())
# Creating a zero-filled instance with a given length:
print("bytearray(10) ", bytearray(10))
# From an iterable of integers:
print("by... |
2092711b21189ba25fc075792ce866e95c0a95fc | udhayprakash/PythonMaterial | /python3/16_Web_Services/f_web_application/using_bottle/01_example.py | 1,027 | 3.5 | 4 | """
Purpose: Creating a REST API using bottle framework
"""
from bottle import delete, get, post, run
persons = [
{"name": "Udhay", "age": 30, "city": "Hyderabad"},
{"name": "Prakash", "age": 56, "city": "New Delhi"},
{"name": "someone", "age": 99, "city": "Mumbai"},
]
@get("/persons")
def get_all():
... |
f99296176c5701a5fe9cbc10d37767fa91ab06f4 | udhayprakash/PythonMaterial | /python3/15_Regular_Expressions/d_re_search.py | 965 | 4.59375 | 5 | """
Purpose: Regular Expressions
Using re.match
- It helps to identify patterns at the starting of string
Using re.search
- It helps to identify patterns at the ANYWHERE of string
"""
import re
target_string = "Python Programming is good for health"
# search_string = "python"
for search_strin... |
37aac93895c30c071aa6f9e296e6b6cea0bd65e9 | udhayprakash/PythonMaterial | /python3/10_Modules/15_turtle_module/turtleGraphics.py | 1,720 | 3.765625 | 4 | """
"Turtle Graphics
"""
import random
import turtle
turtle.screensize(900, 900)
c = (0.1, 0.01, 0.3)
turtle.bgcolor(c)
a = turtle.Turtle("classic", 1000, False)
b = turtle.Turtle("classic", 1000, False)
b.up()
b.goto(-180, 200)
b.write(
"The Power of Recursion!!\n FRACTALS --> Order in Chaos!!",
False,
"c... |
a9bafcaa72533199973fad8a3ea5ba444dadf162 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/d_MultipleTestScripts_ex/mymod.py | 240 | 4.15625 | 4 | """
Purpose:
anagram
cat <--> act
"""
def is_anagram(a_word, b_word):
"""
>>> is_anagram('cat', 'act')
True
>>> is_anagram('tom', 'mat') is not True
True
"""
return sorted(a_word) == sorted(b_word)
|
b91999695cdf2e77903a14636c3d2f49d421d474 | udhayprakash/PythonMaterial | /python3/02_Basics/01_Arithmetic_Operations/a_arithmetic_operations.py | 2,721 | 4.0625 | 4 | #!/usr/bin/python3
"""
Purpose: Arithmetic Operations
Integer Family
- int
- long -> only in python 2.x
- float
- complex
- bool
"""
# + - * / // %
# NOTE: PEP 8 recommends to place one space around the operator
# = assignment operator
num1 = 100 # int
num2 = 123 # int
... |
02a45c32be0f7080b012f596aa83dfe84e2cf079 | udhayprakash/PythonMaterial | /python3/13_OOP/f_Advanced/13_Metaclasses_inheritance.py | 667 | 4 | 4 | #!/usr/bin/python3
"""
Purpose: INheritance Using Metaclasses
using type() function
"""
class CuteMixin:
def be_cute(self):
print("cuteMixin- be_cute")
class Mascot:
def __init__(self, name):
self.name = name
if __name__ == "__main__":
# Method 1 - Class-Level Changes
k1 = Masc... |
6ea6d22d2829598bb077f55eddc844a335d73730 | udhayprakash/PythonMaterial | /python3/10_Modules/08_time_related/d_calendar_module/d_generate_dates.py | 389 | 4.09375 | 4 | #!/usr/bin/python
"""
Purpose: Given two dates,
generate a list of dates between these dates
"""
from datetime import date, timedelta
def daterange(date1, date2):
for n in range(int((date2 - date1).days) + 1):
yield date1 + timedelta(n)
start_dt = date(2015, 12, 20)
end_dt = date(2016, 1, 11)
for d... |
e12c213d1234b0229d1a6e9c51de5d809c4a3968 | udhayprakash/PythonMaterial | /python3/02_Basics/01_Arithmetic_Operations/b_arithmetic_operations.py | 1,265 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Arithmetic Operations
NOTE: PEP 8 recommends to place one space around the operator
"""
print("power operation **")
print("4 ** 2 = ", 4**2)
print("64 ** (1/2) = ", 64 ** (1 / 2)) # square root
print("64 ** (1/2.0) = ", 64 ** (1 / 2.0)) # square root
print("64 *... |
da46171c56e002b5bc69e5d5fc2264fe80d0e5a4 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/f_iterator.py | 375 | 4.125 | 4 | """
Purpose: Static typing
"""
from typing import Iterator
# Using Dynamic typing
def fib(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
# Static typing
def fib1(n: int) -> Iterator[int]:
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
if __name__ == "__main_... |
8c66aa3500cc0f2dc4212d1dae1e91f282beeeb0 | udhayprakash/PythonMaterial | /python3/06_Collections/04_Dictionaries/i_frequency_analyses.py | 3,087 | 4.09375 | 4 | #!/usr/bin/python3
"""
Purpose: Test Frequency Analyses
"""
sentence = """Python is a wonderful language.
we can solve any
computational problem with this language"""
# Character frequency analyses
# Method 1
frequency = {}
for each_char in sentence:
# print(each_char)
try:
frequency[each_char] = freq... |
b181dce0f711cbed0ec5b94c5a41cd8ec7a3b338 | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b7_timer_threads_with_locks.py | 738 | 4.09375 | 4 | """
Purpose: Working with Timer threads, with locks
"""
import threading
import time
tLock = threading.Lock()
def timer(name, delay, repeat):
print(f"Timer: {name} Started")
tLock.acquire()
print("{name} has acquired lock")
while repeat > 0:
time.sleep(delay)
print(name + ":" + str(t... |
23c21e5b00303e3a55f400eef3b100f85f198699 | udhayprakash/PythonMaterial | /python3/10_Modules/28_MiscellaneousModules/shlex_module.py | 2,078 | 3.625 | 4 | #!/usr/bin/python
"""
Purpose: shlex Module
- built-in module
- for Lexical analysis of shell-style syntaxes
"""
import shlex
def get_word_tokens(sentence):
print("\n\n", sentence)
print("\nTOKENS:")
lexer = shlex.shlex(sentence)
for token in lexer:
print("\t", repr(token))
sentence1... |
a09bab1878819e6069d4afe189fcf43f63593695 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/g_example.py | 1,046 | 4.3125 | 4 | """
Purpose: Static typing
"""
from typing import Dict, List, Tuple
# Traditional Approach
my_data = ("Adam", 10, 5.7)
print(f"{my_data =}")
# Adding Typing
my_data2: Tuple[str, int, float] = ("Adam", 10, 5.7)
print(f"{my_data2 =}")
# --------------------------------
# A list of integers
# Traditional Approach
num... |
66c6cf5dc25e81f8e1adad58ac56c932f0d4a41e | udhayprakash/PythonMaterial | /python3/04_Exceptions/06_handling_multiple_exceptions.py | 761 | 4.1875 | 4 | #!/usr/bin/python3
"""
Purpose: Exception Handling
Exception Hierarchy
"""
# try:
# num1 = int(input("Enter an integer:"))
# num2 = int(input("Enter an integer:"))
# division = num1 / num2
# except Exception as ex:
# print(f"{ex =}")
# print("Please enter integers only (or) denominator is 0")
... |
5399535d50a3bc576a80fd1cd911b70a8891d6c6 | udhayprakash/PythonMaterial | /python3/10_Modules/03_argparse/b_calculator.py | 1,183 | 4.5 | 4 | #!/usr/bin/python
"""
Purpose: command-line calculator
"""
import argparse
def addition(n1, n2):
return n1 + n2
def subtraction(s1, s2):
return s1 - s2
def multiplication(m1, m2, m3):
return m1 * m2 * m3
# Step 1: created parser object
parser = argparse.ArgumentParser(description="Script to add two/... |
d85262260f5fcfc72b9d23bb046cc460d51bc8e3 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/k_Union_type.py | 610 | 4.21875 | 4 | """
Purpose: Union type
"""
from typing import Union
def is_even_whole(num) -> Union[bool, str]:
if num < 0:
return "Not a whole number"
return True if num % 2 == 0 else False
assert is_even_whole(10) is True
assert is_even_whole(19) is False
assert is_even_whole(-2) == "Not a whole number"
def is... |
c2bd17abda187508248dc64cc2e4880b9689575c | udhayprakash/PythonMaterial | /python3/15_Regular_Expressions/r_iLmsux_FLAGS.py | 941 | 3.875 | 4 | """
Purpose: Regular Expressions flags ?iLmsux
i: tells the searching engine to ignore case
L: makes \w, \b, and \s locale dependent
m: enables multiline expression
s: the dotall flag; it makes the dot match all characters, including newline character
u: makes \w, \b, \d, and \s unicode dependent
... |
54aeda96085c6ea90ea2a22b9b612906e59e794c | udhayprakash/PythonMaterial | /python3/02_Basics/01_Arithmetic_Operations/j_type_conversions.py | 3,869 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Data Type Conversions
- int, float, complex, boolean, string, None
int - decimal - int() -base 10 (0-9)
- binary - bin() -base 2 (0-1)
- hexadecimal - hex()
- octal - oct()
float
float()
... |
06912a3c7309550d76b2940b873690b3021d1ccc | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/c1_without_threading.py | 513 | 3.859375 | 4 | """
Purpose: Solving this problem
conventionally without using threads
"""
import time
def PrintSquare(numbers):
print("Print squares of the given numbers")
for n in numbers:
time.sleep(0.2)
print("Square", n * n)
def PrintCube(numbers):
print("Print cubes of the given numbers")
... |
dd77bab520ed98687eb0962b1a8b21c7dfa48636 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/05_mocking/example_0/exampleC.py | 571 | 3.625 | 4 | import unittest
from unittest.mock import Mock
def foo(some_object, number):
if number > 2:
some_object.method(number**2) # foo.method(3)
else:
some_object.method(number - 1)
class MyClass:
def __init__(self) -> None:
self.val = 0
def method(self, value):
self.val =... |
3e5cef21cfefe858a0ef07243e52d70b414efb67 | udhayprakash/PythonMaterial | /python3/10_Modules/08_time_related/c_datetime_module/b_datetime_module.py | 1,109 | 3.71875 | 4 | #!/usr/bin/python
"""
Purpose: datetime.date
"""
from datetime import date, datetime, timedelta
today = date.today()
print(today) # 2020-06-24
print("ctime :", today.ctime()) # Wed Jun 24 00:00:00 2020
print("tuple :", today.timetuple())
# time.struct_time(tm_year=2020, tm_mon=6, tm_mday=24, tm_hour=0, tm_min=0, ... |
ef14eb6c7361331b6c3ba966a7a128a48d7b0b45 | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b1a_class_based_solution.py | 760 | 4.21875 | 4 | """
Purpose: Class based implementation of
synchronization using locks
"""
from threading import Lock, Thread
from time import sleep
class Counter:
def __init__(self):
self.value = 0
self.lock = Lock()
def increase(self, by):
self.lock.acquire()
current_value = self.value... |
6dcf49e88d0e324e683ce28021f2ad84a16c850d | udhayprakash/PythonMaterial | /python3/10_Modules/15_turtle_module/turtle_module.py | 418 | 3.546875 | 4 | import turtle as t
# print "List of attributes in turtle module are\n"
# for i, j in enumerate(dir(t)):
# print i, j
# print "help(t)", help(t)
# print "help(t.width)", help(t.width)
t.forward(100) # same as fd(100)
t.shape("turtle")
# help(t.shape())
t.reset() # to reset the graphics window
for i in range(... |
fe091212f494adae9b1f2b997dccc88f635e45a2 | udhayprakash/PythonMaterial | /python3/09_Iterators_generators_coroutines/03_generators/generators.py | 9,336 | 4.34375 | 4 | import itertools as it
import random
def squares(start, end):
curr = start
while curr < end:
yield curr * curr
curr += 1
print("\nPrinting the squares with generator:")
for x in squares(1, 10):
print(x, end=" ")
print("\n")
class Squares:
def __init__(self, start, end):
sel... |
94ca57456aa5e5a26960f87141690958fb274d20 | udhayprakash/PythonMaterial | /python3/06_Collections/04_Dictionaries/h_using_zip_function.py | 2,053 | 3.875 | 4 | #!/usr/bin/python3
"""
Purpose: ways of defining dictionaries
"""
from pprint import pprint
# ways of creating dictionary
a = {"one": 1, "two": 2, "three": 3}
b = dict(one=1, two=2, three=3)
c = dict([("two", 2), ("one", 1), ("three", 3)])
d = dict(zip(["one", "two", "three"], [1, 2, 3]))
e = dict({"three": 3, "one": ... |
3ad6f75a30dd2d95d94de71aa33227fa86fd192f | udhayprakash/PythonMaterial | /python3/07_Functions/007_sum_function.py | 3,145 | 4.5 | 4 | #!/usr/bin/python3
"""
Purpose: WAP to display the addition of given values
"""
# Function definition
def addition(num1, num2, num3):
result = num1 + num2 + num3
return result
# Function call
addition(10, 20, 30)
result = addition(10, 20, 30)
print(f"result:{result}")
# --- sum() - builtin function for ... |
470cd2fc44c2f2313fe79afe8d6e06db8d611649 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/h_MultiThreading/b_Printing/test_printing.py | 843 | 3.546875 | 4 | import unittest
from printing import multithreaded_printing
class TestMultithreadedPrinting(unittest.TestCase):
def test_prints_hello_world_4_times_with_2_threads(self):
multithreaded_printing("Hello, world!", 4)
# Ensure that the message was printed the correct number of times
self.asser... |
3259d55b1aa7a9a2112a9eafe5ef2234966e0adc | udhayprakash/PythonMaterial | /python3/13_OOP/b_MRO_inheritance/01_single_inheritance.py | 1,521 | 4.28125 | 4 | """
Purpose: Single Inheritance
Parent - child classes relation
Super - sub classes relation
NOTE: All child classes should make calls to the parent class
constructors
MRO - method resolution order
"""
class Account:
"""
Parent or super class
"""
def __init__(self):
self.balanc... |
b92994e333cf4ef258773b508a5107d81a1d321c | udhayprakash/PythonMaterial | /python3/13_OOP/a_OOP/11_static_n_class_methods.py | 1,243 | 4.28125 | 4 | #!/usr/bin/python
"""
Methods
1. Instance Methods
2. class Methods
3. static Methods
Default Decorators: @staticmethod, @classmethod, @property
"""
class MyClass:
my_var = "something" # class variable
def display(self, x):
print("executing instance method display(%s,%s)" % (self, x))
... |
3ba1eb6074395e110aa63c5774956a3e1d805620 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/03_doctests/e_example.py | 890 | 3.640625 | 4 | """
Purpose:
"""
import doctest
def power(x, y, /, mod=None):
"""
All parameters to the left of / (in this case, x and y) can only be passed positionally.
mod can be passed positionally or with a keyword.
>>> power(2, 10)
1024
>>> power(2, 10, 17)
4
>>> power(2, 10, mod=17)
4
... |
23978697bff6a4c96fa402731c3a700a5ab6a6ab | udhayprakash/PythonMaterial | /python3/06_Collections/02_Tuples/04_immutability.py | 471 | 4.3125 | 4 | #!/usr/bin/python3
"""
Purpose: Tuples are immutable
- They doesnt support in-object changes
"""
mytuple = (1, 2, 3)
print("mytuple", mytuple, id(mytuple))
# Indexing
print(f"{mytuple[2] =}")
# updating an element in tuple
try:
mytuple[2] = "2.2222"
except TypeError as ex:
print(ex)
print("t... |
c579d388c2a84758f2905ab7f14588f6576f5770 | udhayprakash/PythonMaterial | /python3/03_Language_Components/06_Range_Function/b_range_function.py | 654 | 4.03125 | 4 | #!/usr/bin/python3
"""
Purpose: range() builtin function
"""
list(range(0)) # [] -> range(0, 0, 1)
list(range(1, 0)) # [] -> range(1, 0, 1)
list(range(1, 0, -1)) # [1]
r = range(0, 20, 2)
print(r) # range(0, 20, 2)-> 0, 2, 4, 6, 8, 10, 12, 14, 16, 18
# 0 1 2 3 4 5 6 7 8 9
... |
c293474046807cdf97be6d151442f28333af4324 | udhayprakash/PythonMaterial | /python3/10_Modules/22_ctypes/b_get_value_at_address.py | 491 | 3.5625 | 4 | import ctypes
value3 = 100
# Getting address of variable
memory_addr2 = id(value3)
print("value 3 =", value3)
print("Memory addr (INT) =", memory_addr2)
# Integer to hex conversion
memory_addr3 = hex(memory_addr2)
print("Memory addr (HEX) =", memory_addr3)
# Revert to Integer Type from hex
memory_addr4 = int(memory... |
c81f107aece79ddbbddbe4b9185f3dd2ab40f8a7 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/00_static_code_analyses/e_ast_module.py | 1,820 | 4.15625 | 4 | #!/usr/bin/python
"""
Purpose: AST(Abstract Syntax Tree) Module
Usage
- Making IDEs intelligent and making a feature everyone knows as intellisense.
- Tools like Pylint uses ASTs to perform static code analysis
- Custom Python interpreters
- Modes of Code Compilation
- exec: We ... |
2bbe4ff0ddbcfd289fc41c8308825c564e43db17 | udhayprakash/PythonMaterial | /python3/11_File_Operations/03_multimedia/a_image_files/06_scaling_image.py | 994 | 4 | 4 | #!/usr/bin/python3
"""
Purpose: Scaling the Image
"""
from PIL import Image
def scale_image(input_image_path, output_image_path, width=None, height=None):
original_image = Image.open(input_image_path)
w, h = original_image.size
print(f"The original image size is {w} wide x {h} " "high")
if width and h... |
3be5733f110380ae95309e87f5d809d8f058a4ab | udhayprakash/PythonMaterial | /python3/14_Code_Quality/01_static_typing/i_new_types.py | 263 | 3.859375 | 4 | #!/usr/bin/python
"""
Purpose:
Use the NewType() helper function to create
distinct types:
"""
from typing import NewType
UserId = NewType("UserId", int)
some_id = UserId(524313)
print(f"type(some_id):{type(some_id)}")
print(f"some_id :{some_id}")
|
6b3091f5d2f58b6813054037972dee9cc1087d03 | udhayprakash/PythonMaterial | /python3/10_Modules/10_collections_module/c_collections_Counter.py | 345 | 3.515625 | 4 | import collections
c1 = collections.Counter(["a", "b", "c", "a", "b", "b"])
c2 = collections.Counter("alphabet")
print("c1:", c1)
print("c2:", c2)
print("Combined counts:")
print(c1 + c2)
print("Subtraction:")
print(c1 - c2)
print("Intersection (taking positive minimums):")
print(c1 & c2)
print("Union (taking max... |
089032f1e919883ee09451761df8261fe17c238a | udhayprakash/PythonMaterial | /python3/02_Basics/02_String_Operations/t_string_module.py | 1,412 | 4.25 | 4 | #!/usr/bin/python3
"""
Purpose: String Module
"""
import string
# print(dir(string))
print(string.__doc__, end="\n\n")
print(f"{string.ascii_letters =}")
print(f"{string.ascii_lowercase =}")
print(f"{string.ascii_uppercase =}")
print(f"{string.digits =}")
print(f"{string.hexdigits =}")
print(f"{strin... |
6f42831a4b75764b4683bc0a1f0b8429d1c9cea7 | udhayprakash/PythonMaterial | /python3/11_File_Operations/01_unstructured_file/a_create_file.py | 1,046 | 3.84375 | 4 | #!/usr/bin/python
"""
Purpose:
file operations
- read - r
- write - w -> if file not present, file will be created;
if present, existing content will be overwritten
- append- a
default is read mode
"""
# open('a_first_file.txt')
# FileNotFoundError: [Errno 2... |
3e5f259b609506ad136cebf3015cbd0215eaf094 | udhayprakash/PythonMaterial | /python3/02_Basics/02_String_Operations/l_f_strings.py | 3,250 | 4.375 | 4 | #!/usr/bin/python3
"""
Purpose: String formatting using F-strings
Introducted in python 3.6
"""
import decimal
import math
from datetime import datetime
print("" % ()) # OLD Style
print("{}".format("")) # NEW Style
print(f'{""}') # F-String
print()
print("Hello {name}")
print("Hello {name}".format(name="wo... |
9f167639fe082b79e4fdc9edf429fae98126acb8 | udhayprakash/PythonMaterial | /python3/10_Modules/03_argparse/e_parse_date.py | 491 | 3.65625 | 4 | """
Purpose: parse the dates with argparse
"""
import argparse
import datetime
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--start",
# type=datetime.date,
type=lambda d: datetime.datetime.strptime(d, "%Y-%m-%d").date(),
help="Set a start date",
)
# args = parser.parse_args(["-s"... |
52d5d2268407c434c4ca567c1cf52bc3d8c72783 | udhayprakash/PythonMaterial | /python3/03_Language_Components/09_Loops/i_loops.py | 916 | 4.28125 | 4 | #!/usr/bin/python3
"""
Purpose: Loops
break - breaks the complete loop
continue - skip the current loop
pass - will do nothing. it is like a todo
sys.exit - will exit the script execution
"""
import sys
i = 0
while i <= 7:
i += 1
print(i, end=" ")
print("\n importance of break")
i ... |
a362103f14ee2281057ea3939dcb37af389814eb | udhayprakash/PythonMaterial | /python3/09_Iterators_generators_coroutines/03_generators/03_fibonacci_generator.py | 1,081 | 4 | 4 | #!/usr/bin/python3
"""
Purpose: Fibonacci Series
- first two values are 0 & 1
- subseqeunt values are summation of previous two values
- 0, 1, 1, 2, 3, 5, 8, 13, ...
"""
# Method 1 -- using functions -- you get all values at a time
def fib_series(num):
if num < 0:
return "Invalid Input"
fi... |
7f68f53a23e323c05f2bf7e311e991c82c4b6bb8 | udhayprakash/PythonMaterial | /python3/08_Decorators/decorators/decorator1.py | 1,278 | 3.5 | 4 | # decorator1.py
# simple example of decorators
def changeDoc(func):
func.__doc__ = "This is new docstring"
return func
@changeDoc
def foo(bar):
"""My old docstring"""
return bar
if __name__ == "__main__":
print(foo.__doc__)
# decorator2.py
# simple example of decorators
def changeDoc(docst... |
84bf69bff600bc10230bfa70b6ab23172168139c | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/a_unittests/l_test__setup_tearDown_class_methods.py | 1,410 | 3.53125 | 4 | """
Purpose: unit testing
setupClass & tearDownClass methods are executed ONCE, per test suite
setUp & tearDown methods are executed for each test case
setupClass
setUp
test_case_1
tearDown
setUp
test_case_2
tearDown
...
tearDownClass
"""
import unittest
class TestCaseDemo(unittest... |
ba8331158fd779ca12dc76a62642c8aa223d1ad3 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/02_Code_Analyses/python_2to3_ex.py | 304 | 3.796875 | 4 | #!/usr/bin/python
"""
Purpose: converting script written in python 2.x to 3.x
How to run :
python -m lib2to3 -w python_2to3_ex.py
removing -w means to show the differences
"""
nums = range(10)
try:
name = input("Name:")
except Exception as ex:
print(ex)
else:
print("name", name)
|
ab57df1e74e0e9bbeb772d2ffa3eddc6e1004aad | udhayprakash/PythonMaterial | /python3/10_Modules/06_subprocess/01_subprocess_ex.py | 1,081 | 3.5 | 4 | import os
from subprocess import PIPE, Popen, call
from sys import exit, platform
# subprocess.Popen is more general than subprocess.call.
# Popen doesn't block, allowing you to interact with the
# process while it's running, or continue with other things
# in your Python program; whereas call does block.
if platform... |
151a7dcf87ee5c6458eac386a5831f90dcc746a3 | udhayprakash/PythonMaterial | /python3/15_Regular_Expressions/a_re_match.py | 734 | 4.5 | 4 | """
Purpose: Regular Expressions
Using re.match
- It helps to identify patterns at the starting of string
- By default, it is case-sensitive
"""
import re
# print(dir(re))
target_string = "Python Programming is good for health"
search_string = "python"
print(f"{target_string.find(search_string) =... |
d7ba2535f26ddb9c348677172cec14dff0179192 | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/b2_sync_with_locks.py | 591 | 3.984375 | 4 | """
Purpose: Synchronization in threads, with lock
"""
import threading
import time
# global variable x
x = 0
def transaction(i, lock):
lock.acquire()
print("from thread %d" % i)
lock.release()
# creating a lock
lock = threading.Lock()
# creating threads
t1 = threading.Thread(
target=transaction,
... |
31fcb6bff7762bc0fb0ea7aa7911c04d21ca77ad | udhayprakash/PythonMaterial | /python3/10_Modules/03_argparse/a_arg_parse.py | 1,775 | 4.34375 | 4 | #!/usr/bin/python3
"""
Purpose: importance and usage of argparse
"""
# # Method 1: hard- coding
# user_name = 'udhay'
# password = 'udhay@123'
# server_name = 'issadsad.mydomain.in'
# # Method 2: input() - run time
# user_name = input('Enter username:')
# password = input('Enter password:')
# server_name = input('Ent... |
9bc58aa2c81ab4f4c67ef6a111bed94848410437 | udhayprakash/PythonMaterial | /python3/15_Regular_Expressions/jc_greedy_n_non_greedy_patterns.py | 2,690 | 3.921875 | 4 | #!/usr/bin/python3
"""
Purpose: Regular Expressions
Greedy Patterns
.+ Any character( except newline) can occur 1 or any no. of time
.* Any character( except newline) can occur 0 or any no. of time
"""
import re
res = re.search("a.*", "a")
if res:
res.group()
print(re.search("a.*", "a").group(... |
d6454682adf71704b9012d1a6d28d2275de63af0 | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/e_timed_threads.py | 654 | 4.03125 | 4 | """
Purpose: Timer in threads
A Timer starts its work after a delay,
and can be canceled at any point within that delay time period.
"""
import logging
import threading
import time
logging.basicConfig(
level=logging.DEBUG,
format="(%(threadName)-10s) %(message)s",
)
def delayed():
logging.debug(... |
725f4b5e6cd42f37f749613efcea24f71da53c05 | udhayprakash/PythonMaterial | /python3/13_OOP/d_magicmethods/05_repr_dunder_method.py | 1,164 | 3.90625 | 4 | """
Purpose: __repr__
"""
class TheProblem:
def __init__(self, items):
self.items = list(items)
def __repr__(self):
items = self.items
return f"{items}"
# def __str__(self):
# return 'str is called'
__str__ = __repr__
# NOTE: print will call __str__ if present, els... |
db9068e92410896906bab8d1cea37f9753e99c19 | udhayprakash/PythonMaterial | /python3/09_Iterators_generators_coroutines/03_generators/07_chained_generator_expressions.py | 845 | 3.796875 | 4 | #!/usr/bin/python3
"""
Purpose: Generator Expressions
and chained generator Expressions
"""
listCompr = [i for i in range(7)]
print(f"{listCompr} {type(listCompr)}")
setCompr = {i for i in range(7)}
print(f"{setCompr} {type(setCompr)}")
dictCompr = {i: i**2 for i in range(7)}
print(f"{dictCompr} {type(dictCompr)}... |
7951f57f3f1c437e4f447df3f821e5ee64c2b411 | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/c_locks/c1_problem_with_locks.py | 655 | 3.890625 | 4 | """
Purpose: Problem with threading.Lock
program to illustrate the use of Locks
"""
import threading
import time
# creating a Lock object
lock = threading.Lock()
# initializing the shared resource
geek = 0
def sumOne():
global geek
# locking the shared resource
lock.acquire()
time.sleep(5)
... |
0f125673c1a51afb7de0d4c5d94a4c9ba4d4a2b2 | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/a_unittests/b_execution_order_of_testcases.py | 1,117 | 4.09375 | 4 | #!/usr/bin/python
"""
Purpose: Unit testing using unittest module
NOTE: All the test cases will be executed in
alphabetical order
"""
import unittest
# print(dir(unittest))
# help(unittest)
choice1 = True
choice2 = False
assert choice1 != choice2
class TestCheck(unittest.TestCase):
def test_two_strings... |
6473f82475a39c63e9c3cdd46726b15656253137 | udhayprakash/PythonMaterial | /python3/07_Functions/030_closures_ex.py | 492 | 4.59375 | 5 | #!/usr/bin/python3
"""
Purpose: closure example demo
"""
def outer(num1):
num3 = 30
def hello_world():
print("Hello world")
def wrapper(num2): # closure function
result = num1 + num2 + num3
return result
print(f"{hello_world.__closure__ =}")
print(f"{wrapper.__closure__... |
696622f014f6ab152e691c301c2ae66a054aa1c9 | udhayprakash/PythonMaterial | /python3/07_Functions/032_currying_functions.py | 1,944 | 5.03125 | 5 | #!/usr/bin/python3
"""
Purpose: Currying Functions
- Inner functions are functions defined inside another function that can be used for various purposes, while
currying is a technique that transforms a function that takes multiple arguments into a sequence of functions that each take a single argument.
-... |
72c62102f0bbc2997c54f30ce335de7d8a718677 | udhayprakash/PythonMaterial | /python3/02_Basics/02_String_Operations/r_byte_strings.py | 1,465 | 3.921875 | 4 | #!/usr/bin/python
"""
Purpose: byte strings
bytes objects actually behave like
immutable sequences of integers, with each
value in the sequence restricted such that
0 <= x < 256
"""
# Question: bytearray vs bytes
# bytearray('Python:αλεπού', 'ascii')
# UnicodeEncodeError: 'ascii' codec can't encode
# ... |
713d449e4646683292f37d3e16792f2eaa58052d | udhayprakash/PythonMaterial | /python3/11_File_Operations/01_unstructured_file/i_reading_large_file.py | 757 | 4.1875 | 4 | #!/usr/bin/python3
"""
Purpose: To read large file
"""
from functools import partial
def read_from_file(file_name):
"""Method 1 - reading one line per iteration"""
with open(file_name, "r") as fp:
yield fp.readline()
def read_from_file2(file_name, block_size=1024 * 8):
"""Method 2 - reading bloc... |
896490ee65e78b99ca813366a0c523cc8c226c10 | Winddoing/CodeWheel | /python/test/test_OOP.py | 1,376 | 3.546875 | 4 |
#-*-coding:UTF-8-*-
class Std(object):
def __init__(self, name, score) :
self.__name = name
self.__score = score
def print_score(self) :
print "%s,%s" %(self.__name, self.__score)
def __set_name(self, name) :
self.__name = name
def set_score(self, score... |
d1d25c75754642be035c0ed92ee68130ea2ba94e | oxavelar/TreeMap | /treemap.py | 4,228 | 4.0625 | 4 | #!/usr/bin/env python
"""
Author: Omar Avelar
DESCRIPTION
===========
Simple class extension of a dictionary data type that can print in a tree
esque way to see what you got organized in it, also tested in Python 2.6.
EXAMPLE
=======
>>> a = { 'cat':{'legs' : 4, 'hea... |
f5723625e2f2db2bfd3b14e6955bf20278235b30 | adingler711/School_Deep_Learning | /simple_MLP_fixed_size.py | 65,980 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import random # we randomly define initial values for connection weights, and also randomly select
# which training data that we will use for a given run.
from math import exp #the exp function (e to the x); it's part of our transfer function definition
import numpy as np
###################... |
163c0c8b0c04cb5ef5acf28457a82cd731243b62 | evisalguero/basic-tcp-echo | /echo_client.py | 1,189 | 3.59375 | 4 | import socket
import argparse
host = '127.0.0.1'
def echo_client(port):
# create TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect socket to the server
server_addr = (host, port)
print("Connecting to %s port %s" %server_addr)
sock.connect(server_addr)
# send da... |
3fb7fd7580e9778a151950880b7b30f046037dc1 | jdolitsky/kenken | /client/stopwatch.py | 1,992 | 3.5625 | 4 |
from Tkinter import *
import time
class StopWatch(Frame):
def __init__(self, win):
Frame.__init__(self, win)
self.label = Label(self)
timeFont = ('helevetica', 12, 'bold')
self.label.config(bd=4, relief=SUNKEN, bg='black', fg = 'yellow', text='00:00', font = timeFont)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.