geekcomputers / python Goto Github PK
View Code? Open in Web Editor NEWMy Python Examples
Home Page: http://www.thegeekblog.co.uk
License: MIT License
My Python Examples
Home Page: http://www.thegeekblog.co.uk
License: MIT License
Please can you help solve this in Python and explain to me
mystery_int_1 = 7
mystery_int_2 = 2
You may modify the lines of code above, but don't move them! When you Submit your code, we'll change these lines to assign different values to the variables.
The variables below hold two integers, mystery_int_1 and
mystery_int_2. Complete this program below such that it
prints "Factors!" if either of the numbers is a factor of the other. If neither number is a factor of the other, do not print anything.
Hint: You can do this with just one conditional statement
by using the logical expressions (and, or, and not). You'll also use the modulus operator
Please help me with the Add your code here!
Have tried several means am just not getting it
Hi ,
I was trying to copy a file into a A.jar (without extracting it) but it didn't work.
Suppose i have file copy.txt in D:\python\copy.txt and i want this file to be copied into my A.jar/org/here
for this I have written a code in python but what it is doing is , It is taking the contents of copy.txt and pasting the content to target dir-> A.jar/org/. It is not pasting the file instead it is pasting the content. I want the file to be copied with the content and if the file is already exist it will replace it in the target dir.
Please see my below code and suggest .
import zipfile, os
def show_jar_classes(jar_file):
zf = zipfile.ZipFile(jar_file, 'a')
try:
#Code to write inside org folder in inside z.jar
dir=input("please give the source file dir along with the file")# taking complete path frm user
m='/'
dir= dir.replace('\\',m) #formating the path by replacing '\' with '/'
clas=os.path.basename(dir) #extracting the file name from the given path
zf.write(dir, "org\\"+clas) #writing into A.jar/org/
finally:
zf.close()
jar_file = 'D:/python/A.jar'
show_jar_classes(jar_file)
why remove the filename from filenames in for ??
it will decrease the number of for
Hi
I'm using Spyder 3.6 for Python on Windows 10, every time I try to open the editor, it takes nearly 4-6 mins of my time and sometimes even longer. The same happens if I open through Anaconda launcher. Is there anything that I could do to fix it,
thanks in advance
my H/W: i7, 8GB memory, 1 TB SSD
I'm learning python, and after having done some lessons, it was suggested that I browse Github, find a python project, and just read some code to gain more experience. Your batch file rename script is the first one I looked at, and it appears to have an error.
You have the following code:
if old_ext == file_ext:
which means it will only "rename" to the same name, defeating the purpose of the entire script.
~/Desktop/GIT/other/Python$ python youtube.py
Enter the song to be played: hero
Traceback (most recent call last):
File "youtube.py", line 28, in
song = songs[0].contents[0].contents[0].contents[0]
IndexError: list index out of range
Script will help user to know their public and local IP address
I looked through your code and as a current student learning python I was asked to pick any code and see if I can correct any errors.
Well I would think adding an "else" statement to the main function would help in preventing the processing of empty password files by the users.
hey,
really liked these codes. inspirational i must say... 💯 ..
Why don't you create a .txt file and put all dependencies for using any of the codes in this source, might be helpful for all.
Here's the content of server.txt file under /root/python folder i put in with the nslookup script.
google.com
bbc.co.uk
Is this correct?
If so, the script didn't work.
I tested this script on python 2.6.6 and this error appeared.
Traceback (most recent call last):
File "nslookup_check.py", line 4, in
subprocess.Popen(('nslookup '+server))
File "/usr/lib64/python2.6/subprocess.py", line 642, in init
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1238, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
In case of python 3.4
Traceback (most recent call last):
File "nslookup_check.py", line 4, in
subprocess.Popen(('nslookup '+server))
File "/opt/rh/rh-python34/root/usr/lib64/python3.4/subprocess.py", line 858, in init
restore_signals, start_new_session)
File "/opt/rh/rh-python34/root/usr/lib64/python3.4/subprocess.py", line 1456, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'nslookup google.com\n'
.
Hi,I use python3 to test a model which need opencv(CV2),but I failed to install opencv on windows.
Therefore,I try to find a functions which belongs to numpy or PIL to replace it.
Here are partial codes of the program.
for rec_val, img,x,y in zip(reconstruction_vals, test_images, xs, ys):
rec_hid = (255. * (rec_val+1)/2.).astype(int)
rec_con = (255. * (img+1)/2.).astype(int)
rec_con[y:y+64, x:x+64] = rec_hid
cv2.imwrite( os.path.join(result_path, 'img_'+str(ii)+'.'+str(int(iters/100))+'.jpg'), rec_con)
ii += 1
if ii > 50: break
if iters == 0:
ii = 0
for test_image in test_images_ori:
test_image = (255. * (test_image+1)/2.).astype(int)
test_image[32:32+64,32:32+64] = 0
cv2.imwrite( os.path.join(result_path, 'img_'+str(ii)+'.ori.jpg'), test_image)
ii += 1
if ii > 50: break
and the code can be find in https://github.com/jazzsaxmafia/Inpainting /src/train.imagenet.py
I have get a problem when I run test.py on pycharm, but the code can run success when use IDLE
error message:
Traceback (most recent call last):
File "E:/python/test/database2.py", line 6, in <module>
import mysql.connector
File "C:\Python27\lib\site-packages\mysql\connector\__init__.py", line 37, in <module>
from .connection import MySQLConnection
File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 27, in <module>
from io import IOBase
ImportError: cannot import name IOBase
test.py
import mysql.connector
conn = mysql.connector.connect(host='localhost', user='root', password='z2457098495924', database='test')
cur = conn.cursor()
cur.execute('select * from student')
result = cur.fetchall()
print result
conn.commit()
cur.close()
conn.close()
def readfile(filename):
with open(filename, 'r') as f: # Ensure file is correctly closed under all circumstances
line = f.read() # more convenient it should be file = f.read()
print(line) # print(file)
#Because it is reading whole file not a single line.It is just an enhancement.
import glob
import os,sys
import re
if sys.version_info < (2, 6) and sys.version_info < (2, 7):
print "This is not valid version"
sys.exit()
if sys.platform != "linux2":
print "This is not valid OS"
sys.exit()
os.chdir('/sys/block/')
def size(dev):
nr_sectors = open(dev+'/size').read().rstrip('\n')
sect_size = open(dev+'/queue/hw_sector_size').read().rstrip('\n')
# The sect_size is in bytes, so we convert it to GiB and then send it back
return (float(nr_sectors)*float(sect_size))/(1024.0*1024.0*1024.0)
def device_detail():
for dev in glob.glob('/sys/block/sd*'):
vendor_name = open(dev+'/device/vendor','r').read().rstrip('\n')
Read_link = os.readlink(dev).split('/')[4]
print ('Device {0}:: Size {1} GB :: Vendor {2}:: Controller {3}'.format(dev, size (dev), vendor_name, Read_link))
if name =='main':
device_detail()
page = ('.... facebook .....')
Link_start = (page.find('<a href'))
starting_quote = (page.find('"','Link_start'))
end_quote = (page.find('"','starting_quote+1'))
url = (page.find('stating quote+1','end quote'))
print (url)
Shouldn't all the .py files all have shebangs?
For example:
(Assuming the user is on Linux/Unix. If the user is on windows it will be read as a comment and no harm will be done.)
FYI, you can use enumerate() to simplify osinfo.py. Instead of this:
i=1
for item in profile:
print( '#',i,' ',item)
i=i+1;
... do this ...
for i, item in enumerate(profile, 1):
print( '#',i,' ',item)
python study
when player enter same position again and agian two times, then game not proceed ahead.
This repo has a lot of great programs, it would be great if similar types of programs were organized into folders so it is easier to find them and would be better in the future for more programs to be added to this repo.
it says,
ImportError no module named crypt:
Your scripts are not PEP8 valids. However, there're a lot of others issues :
Should I contribute to fix them ?
import shownfile#i have named this script
Enter a file name: r'c:\python27\showfile.py'
Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\showfile.py", line 18, in
file_stats = os.stat(file_name)
WindowsError: [Error 123] : "r'c:\python27\showfile.py'"
Is that helpful? I appreciate these are just code examples you're publishing.
Kind Regards
Duncan
For ex20.py
Comment "What is the program and what will it do"
I installed python
from brew
brew install python
then installed pip
sudo easy_install pip
in Terminal
$ which easy_install
/usr/bin/easy_install
$ which python
/usr/bin/python
But then when I want to install any Python script I get this:
Searching for pexpect
Best match: pexpect 4.2.1
Adding pexpect 4.2.1 to easy-install.pth file
Using /Library/Python/2.7/site-packages
Processing dependencies for pexpect
Finished processing dependencies for pexpect
Searching for pycrypto
Best match: pycrypto 2.6.1
pycrypto 2.6.1 is already the active version in easy-install.pth
Using /Library/Python/2.7/site-packages
Processing dependencies for pycrypto
Finished processing dependencies for pycrypto
Searching for pyopenssl
Best match: pyOpenSSL 0.13.1
pyOpenSSL 0.13.1 is already the active version in easy-install.pth
Using /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
Processing dependencies for pyopenssl
Finished processing dependencies for pyopenssl
Searching for pefile
Best match: pefile 2017.9.3
pefile 2017.9.3 is already the active version in easy-install.pth
Using /Library/Python/2.7/site-packages
Processing dependencies for pefile
Finished processing dependencies for pefile
Here's an image of the problem:
Tried to search win10toast replacement for windows 7. Couldn't.
Hey i started a project mcpe server with python and if soneone wants to come help that would be great!
the url https://myapp.herokuapp.com working fine but the url https://myapp.herokuapp.com/admin/ showing Server Error (500) and it also not serving the images from the s3 bucket i already did these
`heroku run python manage.py migrate
heroku run python manage.py createsuperuser`
my settings.py file
"""
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(file))))
SECRET_KEY = '$$!#%(2lqx#ckmc9#j6lw5ts4_9n$qjy$@=zv09wxvo_=qa=po'
DEBUG = False
ALLOWED_HOSTS = ["shoppingwave.herokuapp.com"]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products',
'storages',
'boto',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ecommerce.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ecommerce.wsgi.application'
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'online_shopping',
'USER': 'postgres',
'PASSWORD': 'abc2x',
'HOST': '',
'PORT': ''
}
}
import dj_database_url
db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY", "")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME", "")
AWS_QUERYSTRING_AUTH = False
AWS_S3_CUSTOM_DOMAIN = os.environ.get("AWS_S3_CUSTOM_DOMAIN", "")
MEDIA_ROOT = os.environ.get("MEDIA_URL", "")
MEDIA_URL = '/media/'
As I saw, most of the scripts support only Python 2.x. There should be a support for python 3.X also.
It includes adding aliases for function names, such as raw_input() to input() , adding parantheses to print.
I have a c++ code,there are two classes,that in the init function,they need the other class' object. also in one class,init function need itself object as a parameter.
how to deal with such situation in python.
many thanks!
total=0
temp =0
i=0;
j=1;
counter=0
MIN_val = 100
MAX_val = 0
file = open("C:/Users/Shrikanth/Desktop/Report.csv")
csv_reader = csv.reader(file)
next(csv_reader)
for all in csv_reader:
FileName, Channel, OrgSize, TransSize = all
if Channel == "TimesNow_LB":
total_redn= (float(OrgSize)- float(TransSize))/float(OrgSize) * 100
counter = counter + 1
MIN_val(float(total_redn))
MAX_val(float(total_redn))
AVG_val(float(total_redn))
print counter
def MIN_val(num):
global MIN_val
if MIN_val > num:
MIN_val = num
print MIN_val
def MAX_val(num):
global MAX_val
if MAX_val < num:
MAX_val=num
print MAX_val
So i'm getting ''MIN_val(float(total_redn))
TypeError: 'int' object is not callable'' error.
Why does it happen and what is the solution?
Exception
, not Exceptions
Modified Code
import os # Import the OS module
try:
home = os.path.expanduser("~") # Set the variable home by expanding the users set home directory
print home # Print the location
if not os.path.exists(home+'/testdir'):
os.makedirs(home+'/testdir') # If not create the directory, inside their home directory
else:
print 'Given directory already exists in the path'
except Exception as e: # changed Exceptions to Exception
print e
Created Pull request #48
paiton meiks mi crai
flake8 testing of https://github.com/geekcomputers/Python on Python 2.7.13
$ # stop the build if there are Python syntax errors or undefined names
$ flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics
./daily_checks.py:37:22: F821 undefined name 'conffilename'
for server in open(conffilename): # Open the file server_list.txt, loop through reading each line - 1.1 -Changed - 1.3 Changed name to use variable conffilename
^
./ping_servers.py:28:68: F821 undefined name 'filename'
sys.exit ('\nYou need to supply the app group. Usage : ' + filename + ' followed by the application group i.e. \n \t dms or \n \t swaps \n then the site i.e. \n \t 155 or \n \t bromley')
^
Hi,
I need a code in python that classifies a document by it's extension.
Thanks,
Yugank Narula
I have created a PR for getting likes on Facebook.
Please review it. https://github.com/geekcomputers/Python/pull/120
I have to change this code to array format
What should I have to do?
import numpy as np
import matplotlib.pyplot as plt
#factors
Sun_0 = 1.989 * 10 ** 30
Planet_0 = Sun_0 * 0.05
Radius_0 = 0.7785 * 10 ** 12
Sun_mass = 1
Planet_mass = 0.05
Time_0 = 365.24 * 24 * 3600
Grav_0 = 6.673 * 10 ** -11
Grav_planet = Grav_0 * Sun_0 * 10 ** 6 / Radius_0 ** 2
Grav_sun = -Grav_0 * Planet_0 * 10 ** 6 / Radius_0 ** 2
dt = 0.1; Time = np.arange(1,10,dt)
#Coordinates-Planet
Planet_x = 5.2
Planet_y = 0
PlaVel_x = 0
PlaVel_y = 6.28
#Coordinates-Sun
Sun_x = 0
Sun_y = 0
SunVel_x = 0
SunVel_y = -0.314
def Accel(Sun_x,Sun_y,Planet_x,Planet_y,Grav,i):
Rel_x = Planet_x - Sun_x
Rel_y = Planet_y - Sun_y
Rel_3 = (Rel_xRel_x+ Rel_yRel_y) **1.5
Aug = (-Grav/Rel_3)
return AugRel_x,AugRel_y
for i in range(len(Time)) :
SunAcc_1 = Accel(Sun_x,Sun_y,Planet_x,Planet_y,Grav_sun,i)
PlaAcc_1 = Accel(Sun_x,Sun_y,Planet_x,Planet_y,Grav_planet,i)
Sun_x += SunVel_x * dt + 0.5 * dt * dt * SunAcc_1[0]
Sun_y += SunVel_y * dt + 0.5 * dt * dt * SunAcc_1[1]
Planet_x += PlaVel_x * dt + 0.5 * dt *dt * PlaAcc_1[0]
Planet_y += PlaVel_y * dt + 0.5 * dt *dt * PlaAcc_1[1]
SunAcc_2 = Accel(Sun_x,Sun_y,Planet_x,Planet_y,Grav_sun,i)
PlaAcc_2 = Accel(Sun_x,Sun_y,Planet_x,Planet_y,Grav_planet,i)
SunVelAvg_x = (SunAcc_1[0] + SunAcc_2[0]) /2
SunVelAvg_y = (SunAcc_1[1] + SunAcc_2[1]) /2
PlaVelAvg_x = (PlaAcc_1[0] + PlaAcc_2[0]) /2
PlaVelAvg_y = (PlaAcc_1[1] + PlaAcc_2[1]) /2
SunVel_x += SunVelAvg_x * dt
SunVel_y += SunVelAvg_y * dt
PlaVel_x += PlaVelAvg_x * dt
PlaVel_y += PlaVelAvg_y * dt
plt.plot(Planet_x,Planet_y,".r",ms = 2 + idt)
plt.plot(Sun_x,Sun_y,".b",ms = 2 + idt)
plt.show()
I saw your files and they are not compatible with python 3. I will like to make them work with Python 3.5 too. Let me know if you want someone to work on it.
Hey, guys. I want to join it, but how to start it. Anybody could tell me? Thanks for help.
@geekcomputers will you help me with my projects? I would be honored if you would!
testing
sides_change parameter is passed to the function set_sides. Within the function set_sides, instead of using the sides_change variable directly, self.sides_change is used. It is resulting in an error.
Traceback (most recent call last):
File "MitosisDetection_server.py", line 4, in <module>
import train
File "/home/workspace/server/train.py", line 3, in <module>
from keras.models import Sequential
File "/root/miniconda2/lib/python2.7/site-packages/keras/__init__.py", line 3, in <module>
from . import activations
File "/root/miniconda2/lib/python2.7/site-packages/keras/activations.py", line 4, in <module>
from . import backend as K
File "/root/miniconda2/lib/python2.7/site-packages/keras/backend/__init__.py", line 72, in <module>
assert _backend in {'theano', 'tensorflow'}
AssertionError
what should i do ?
thanks so much!
In check_file.py, the list filenames
is changed on line 40 and line 47.
Thus, some items may skip the for loop (and does not get the existance check and read permission check), when you try to read such items on line 54, an error may be thrown.
For example, suppose there is non-readable file f1 and non-exist file f2 in current directory, and we execute the command python check_file.py f1 f2
, we will see an error as shown in the picture.
temperature = -3.7
celsius = True
You may modify the lines of code above, but don't move them! When you Submit your code, we'll change these lines to assign different values to the variables.
Above are given two variables. temperature is a float that holds a temperature. celsius is a boolean that represents whether the temperature is in Celsius; if it's False, then the given temperature is actually in Fahrenheit.
Add some code below that prints "Freezing" if the values above represent a freezing temperature, and "Not freezing" if they don't.
In Celsius, freezing is less than or equal to 0 degrees. In Fahrenheit, freezing is less than or equal to 32 degrees.
Comment your code
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.