Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

i'm looking to plot Timedelta in a bar graph using matplotlib from Pandas

[Timedelta('0 days 08:43:07'),
Timedelta('0 days 04:43:07'),
Timedelta('0 days 03:43:07')]

Open in new window


matplot lib see's these as strings and won't plot them?
0
I am new to Python. try to learn. I want to create program where it should ask for birthday just day and month using input function and if the birthday is in the future then should give message that how many days left for your birthday, if it   is already passed then it should give message that your birthday was that many days ago and if it is today then should show message ‘happy birthday’
I spent lot of time but no luck
0
How to concat 2 column in pandas dataframe

My input file is
File1
CountryA|Apple|200
CountryB|Apple|100
CountryA|Orange|150

Output I need is below
CountryAApple|200
CountryBApple|100
CountryAOrange|150

I tried below code. Is this the correct way of doing this..
df1 = pd.read_csv('file1','|')
df2 = df1.iloc[:,:0]
df3 = df1.iloc[0:,:1]
df4 = df1.iloc[1:,:2]

df5 = pd.concat([df2, df3])
df6 = df5+"|"+df4
Print(df6)
0
Hi,

I am attempting  to  use python to loop  through a specified folder (sales_folder monthlysales*.xlsx) and  pull column data (salesTot) from a named tab (currentmonth)  in within the spreadsheet. I can get this
to work with one file, but not with looping through the folder. Th ecode for one file:

import openpyxl
import pandas as pd

pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns',25)
pd.set_option('display.width', 200)
from pandas import ExcelWriter
from pandas import ExcelFile



d1 = pd.read_excel("C:\\sales_folder\ monthlysales", sheet_name= "currentmonth", index=range(5), columns=list('abc')
)
print(d1)
d1.columns
print(d1.columns)

df1=pd.DataFrame(data=d1)
print(d1)
d1_transposed=d1.T
print(d1_transposed)

d1_transposed.to_csv('C:\\ Folder\\Sales.csv')


I have tried to use glob but I cannot get the loop to run through the folder, find the tab and print the output to a csv. Please advise.
0
Hi,
I got 2 files and I need to compare each data and generate boolean output. For eample, from below 2 files i need to take  row 1 and column 1 data and compare. If match I need write output as True and if doesnt match then I need output as False.

File 1 : Year 1990
Fruits|count
Apple|100
Orange|200
Red grapes|120

File 2 : Year 2000
Fruits|count
Apple|100
Orange|150
Green grapes|120

Output that I need.
Fruits|Count
TRUE|TRUE
TRUE|FALSE
FALSE|TRUE

What is the best way to do it,
I tried open the file1 and file2 line by line and output to matrix kind of file..and then compare 2 matrix but I never got my output. 
Is generating 2 matrix and comparing 2 matrix is the correct way of doing this ?
0
I would like to add the results of my ping test in python to a csv file i was hoping someone could please help me with this please as i have been pulling my hair out trying

here the code of my pings

import os
import socket
import csv


iplist = []

#loop from 1 to 255
# Appends the concatenated ip to the ip_list

for ip in range(1,256):
    iplist.append("192.168.1." + str(ip))

#show me the list of ip address in the list

print("*********ADBY IT AND MEDIA SOLUTIONS NETWORK SCAN*********")
# Loop to ping ip_list and check if device up or down
# Outputs to results.txt file
print("Starting ping test")
for ip in iplist:
   
    response = os.popen(f"ping  {ip} -n 1").read()
    if "Received = 4"  and "Approximate" in response:
        try:
            hostname = socket.gethostbyaddr(ip)

            print(" {}ONLINE".format( hostname))
        except socket.error:
            hostname = "No HOST NAME "

            print(" {}{} ONLINE".format( hostname,ip))



       
        #print({hostname} +  "The System is online")
    #else:
       # print(f"{ip} OFFLINE")
0
Hi i'm trying to use the code here, to just connect to SQL SERVER 17 database, i'm assuming that my Driver is not right.... maybe I can't use the '-' ??

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=SCDC-FM5CDW2;'
                      'Database=WideWorldImporters;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute('SELECT top 10 * FROM [WideWorldImporters].[Application].[Cities]')

for row in cursor:
    print(row)
0
Hi all i am writting a python script to scan my network and show me the devices that are currently online and there host names, nwo its kinda working but there are a lot of them comming back and telling me they dont have a hostname so i am sure i am doing something wrong can someone please have a look at my code and let me know if i can do i a better way,

import os
import socket

iplist = []

#loop from 1 to 255
# Appends the concatenated ip to the ip_list

for ip in range(1,256):
    iplist.append("192.168.1." + str(ip))

#show me the list of ip address in the list
print (len(iplist))
# Loop to ping ip_list and check if device up or down
# Outputs to results.txt file
print("Starting ping test")
for ip in iplist:
    response = os.popen(f"ping  {ip} -n 1").read()
    if "Received = 4"  and "Approximate" in response:
        try:
            hostname = socket.gethostbyaddr(ip)
            print(" {}ONLINE".format( hostname))
        except socket.error:
            hostname = "No HOST NAME "
            print(" {}{} ONLINE".format( hostname,ip))



       
        #print({hostname} +  "The System is online")
    #else:
       # print(f"{ip} OFFLINE")
0
Hi,
I got 2 files i.e File1 and File2, as shown below

File1
A | APPLE
B | ORANGE

File2
A | 10
B | 15
D | 20
A | 10

I need following output
Output 1
A | APPLE | 10
B | ORANGE | 15

But I am getting this below output.
A | APPLE | 10
B | ORANGE | 15
A | APPLE | 10

How can I remove the duplicate rows from the output and direct only the duplicate output to a new file.

My code is as follow

Import pandas as pd
df1 = pd.read_csv('file1.txt', sep='|')
df2 = pd.read_csv('file2.txt', sep='|')
Merge12 = pd.merge(df1, df2, how='left', on='A')
Merge12.to_csv('output.txt')
0
I must connect to an old Microsoft Access DB (.mdb) using python pyodbc.

Here's what i've installed on my computer:
  • Microsoft Access 2019, 64-bit
  • Microsoft Visual Studio Code
  • Python 3.7.4, 64-bit
  • I've done the pip install pyodbc

I've tried several connection strings, but none of them work.  I always get an error message
('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
.


Here's some code i've tried:
_ConnStr = 'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\TEMP\\MYFILE.MDB;Persist Security Info=False;'
_conn = pyodbc.connect(_ConnStr)

Open in new window


I've seen previous post about people using 32 bits of python vs access 64 bits, but it's not my case.  I'm using 64 bits for python and for access.

Thanks you
0
In the below script I like to add if someone guess number less than 0 or more than 20 then it should give message and terminate the program. How I can do that? thanks

import random
n = random.randint(1, 20)
guess = int(input("Enter an integer from 1 to 20: "))
while n != "guess":
    print
    if guess < n:
        print ("guess is low")
        guess = int(input("Enter an integer from 1 to 20: "))
    elif guess > n:
        print ("guess is high")
        guess = int(input("Enter an integer from 1 to 20: "))
    else:
        print ("you guessed it!")
        break
    print
0
Hi Guys

I'm using Python 3.8.1 and below is a script I use

import glob
import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate

clip = VideoFileClip (print(glob.glob("*.mp4")))
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000) 
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.audio.duration-2))]
averaged_volumes = np.array([sum(volumes[i:i+10])/10
                             for i in range(len(volumes)-10)])

increases = np.diff(averaged_volumes)[:-1]>=0
decreases = np.diff(averaged_volumes)[1:]<=0
peaks_times = (increases * decreases).nonzero()[0]
peaks_vols = averaged_volumes[peaks_times]
peaks_times = peaks_times[peaks_vols>np.percentile(peaks_vols,90)]

final_times=[peaks_times[0]]
for t in peaks_times:
    if (t - final_times[-1]) < 60:
        if averaged_volumes[t] > averaged_volumes[final_times[-1]]:
            final_times[-1] = t
    else:
        final_times.append(t)

final = concatenate([clip.subclip(max(t-5,0),min(t+5, clip.duration))
                     for t in final_times])
final.to_videofile('iFLY - Cut.mp4') # low quality is the default

Open in new window


When I run the script, I get an error, see below

['movie.mp4']
Traceback (most recent call last):
  File "C:\Highlights\soccer_cuts.py", line 16, in <module>
    clip = VideoFileClip (print(glob.glob("*.mp4")))
  File "C:\Python38\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 88, in __init__
    self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt,
  File "C:\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 32, in __init__
    infos = ffmpeg_parse_infos(filename, print_infos, check_duration,
  File "C:\Python38\lib\site-packages\moviepy\video\io\ffmpeg_reader.py", line 245, in ffmpeg_parse_infos
    is_GIF = filename.endswith('.gif')
AttributeError: 'NoneType' object has no attribute 'endswith'

Open in new window


Looking through the error I found line 16 to be the issue

clip = VideoFileClip (print(glob.glob("*.mp4")))

Open in new window


What I'm trying to do with line 16 is set a variable, the file name movie may be called movie1 or movie 2 though there will always be just the 1 mp4 file within the folder called Highlights. I'm hoping you can assist me with this.

Any help is greatly appreciated.
0
Hi Guys

I have a python script that takes a video file called video.mp4 and cuts it down based on sound activity. See below. The python script is saved as PythonVideo.py in directory C:\Users\user\Desktop\Video

import numpy as np # for numerical operations
from moviepy.editor import VideoFileClip, concatenate

clip = VideoFileClip("video.mp4")
cut = lambda i: clip.audio.subclip(i,i+1).to_soundarray(fps=22000) 
volume = lambda array: np.sqrt(((1.0*array)**2).mean())
volumes = [volume(cut(i)) for i in range(0,int(clip.duration-1))]

increases = np.diff(averaged_volumes)[:-1]>=0
decreases = np.diff(averaged_volumes)[1:]<=0
peaks_times = (increases * decreases).nonzero()[0]
peaks_vols = averaged_volumes[peaks_times]
peaks_times = peaks_times[peaks_vols>np.percentile(peaks_vols,90)]

final_times=[peaks_times[0]]
for t in peaks_times:
    if (t - final_times[-1]) < 60:
        if averaged_volumes[t] > averaged_volumes[final_times[-1]]:
            final_times[-1] = t
    else:
        final_times.append(t)

final = concatenate([clip.subclip(max(t-5,0),min(t+5, clip.duration))
                     for t in final_times])
final.to_videofile('video1.mp4') # low quality is the default 

Open in new window


The issue here is when I run PythonVideo.py I get lines of error, see below. Is there something wrong I'm doing here? The python version I'm using 3.6.6

Traceback (most recent call last):
  File "C:\Users\user\Desktop\Video\PythonVideo.py", line 7, in <module>
    volumes = 

Open in new window

0
Hi,
I got 2 files i.e File1 and File2, as shown below

File1
A | APPLE
B | ORANGE
C | GRAPES

File2
A | 10
B | 15
D | 20

I need following 2 outputs,
Output 1
A | APPLE | 10
B | ORANGE | 15

Output 2
C | GRAPES | NA

I got the output1 using below below script.
Script1

for line1 in file1:
Data1 = line1.split("|")
Data10 = Data1[0]
Data11 = Data1[1]
 for line2 in file2:
 Data2 = line2.split("|")
 Data20 = Data2[0]
 Data21 = Data2[1]
  If Data10 == Data20:
  Print ( Data10, "|", Data11, "|", Data21)

My question is, how can I get my output2. I tired putting if data10 != data 20, i tired break and continue function but still I am not getting my output. Can advice what is best way to get my output2.
0
So with the inputs being from_date=2019-01-01 and to_date=today

I need

2019-01-01 - 2019-03-31
2019-04-01 - 2019-06-30
2019-07-01 - 2019-09-30
2019-10-01 - 2019-12-31
2020-01-01 - 2020-02-04

I don't really know any python, but this is the closest I can come up with so far.
The dates are there, I just don't know how to access them or fill in today's date on the last item....

    def get_date_ranges(self, fr_date, to_date):
        qtr_beg = pd.date_range(start=fr_date, end=datetime.date.today(), freq='QS')
        qtr_end = pd.date_range(start=fr_date, end=datetime.date.today(), freq='Q')
        date_range = zip(qtr_beg, qtr_end)
        return date_range

Open in new window

0
How would you code for this problem?

Define the function check(s). The function returns 1 when string 's' contains at least one digit and returns 0 otherwise.
0
Hi, i'm using anaconda/python, trying to simply open up a csv file to play with, but I keep getting errors. The file is on the route of c: Drive c:\pokemon_data.csv

I try to use this command:

df = pd.read_csv ('c:/pokemon_data.csv') I tried with a back slash as well, and I keep get the error:

filenotfounderror
0
How can we make a python application which will run interactively over SSH? Like I will login via SSH this python would be automatically started and ask some user inputs and continue to run or just continue to tail a log file. Please let me know if it is possible
0
I'm very new to Python but I've learned enough to print out the data in a specified range on Sheet 1 in a specified Excel workbook. The current code below will do that but in the Terminal window, each 5 column row is printed vertically in one long column so to speak. How would I modify the code to get it to print out with each 5 column row spread out horizontally as it is in Excel? I'm interested in doing that because 1) it would be easier to read, and 2) just to see if Python will do that.

path = r'C:\Users\t0122059\Documents\ACDetails.xlsx'

f = open(path, 'rb')
print(f.read())

# https://openpyxl.readthedocs.io/en/stable/usage.html

from openpyxl import load_workbook
wb = load_workbook(path)

for row in range(1, 12):
    for col in range(1, 6):
        print(wb.worksheets[0].cell(row, col).value)
print('inspect')

Open in new window

Thanks,
John
0
The attached image contains 2 csv files (csv1 and csv2). I want to combine 2 csv files to get the output csv attached in image. values in the output csv should be on the basis of finding closest years in csv2 to that in csv1. i.e what is the closest year to 2010 (in csv2) among (2012, 2009) (in csv1)? 2010 year in csv2 has 2009 as the closest year in csv1. so, in output csv, 2010 year has values from year 2009 in csv1 as it closest to 2010 than 2012 (highlighted in green). all the other years in output csv have closest year as 2012 from csv1, so output contains values from years 2012 (highlighted in red).
img.png
0
I have a column which contains geometry values (maps) like 01030009777700000000BCA142E2ABD08A2C0CA9466D8B4B4CC. I wanted to convert it into latitude and longitude coordinates. I tried using geopandas but didn't click for me. Any help is appreciated.
0
We're working with an API that has been giving us trouble from the very beginning. The support people informed us of a bug in which their servers expect a content-type of 'application/json' in the header but for the data to actually be passed using the 'form-data' or application/x-www-urlencoded' content type. No matter what I do I get either a 500 response or an error about the content-type in the response from their server when using the python requests library. I did have this working in javascript/node.js and postman, but we need it to work in python.

Here's the code:
import requests

API_URL = "https://api.kenect.com/v1/conversations/messages/"

headers = {
    'x-api-token': '1130FxmIcc6uZWcq8OXoCZZPCpq8ODQo',
    'x-api-key': 'pdwz0naW5hyCeG9SyJ3PpnOf26BZFS28'
}

data = {
    "locationId": 2045,
    "messageBody": 'test',
    "contactPhone": 15857396811       
}

r=requests.post(url=API_URL, headers=headers, data=data)
print(headers)
print(data)
print(r)

Open in new window

0
I remotely connect to Linux virtual box from secure shell (ssh).  I have smallest bitbake project.

I type bitbake from shell prompt.  
The output is as follows:
Nothing to do.  Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information.

Bitbake document says default build task will be executed.
build default task is in Base.bbclass file.

How can I be sure this task actually executed?  How do I print something to the screen from this task?
base.bbclass
bblayers.conf
bitbake.conf
layer.conf
0
Hi all i am having some massive brain farts at the moment and i cant work out the issue i am having, i have been starting at the code for hours and i know its on a small issue, i am getting a error on line 58, i know its got to do with formatting but for the life of me i ant get it to work correctly
#****
# *****
# VERSION 1.0
# DATE 6 Jan 2020
# UPDATED 6 Jan 2020
# *****


import mysql.connector
import pandas as pd
import mysql.connector
import urllib.parse
import requests
import finddatatime  # Getting the date from the second script called finddatetime.py

currentdatetime = finddatatime.date_time

print ("The Current time date is" + " " + currentdatetime)

from mysql.connector import Error
from __main__ import *

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="A*****1",
    database="flightdata"
)

mycursor = mydb.cursor()

fnumber = (input("Please enter flight number:  "))

sql = 'SELECT * FROM flightdata.flightinfo where flightnumbers =' + "'" + fnumber + "'"
# print(sql)

mycursor.execute(sql)
# connection.commit()

myresult = mycursor.fetchall()

for x in myresult:
    flightnumber = x[3]
    orgin = x[10]
    dest = x[2]
    departtime = x[4]
    status = x[8]

answer = (input("Flight #: " + str(flightnumber) + " From: " + str(orgin) + " To: " + str(dest) + " At: " + str(
    departtime) + "is that correct? yes/no: "))
# if statment for answer start
if answer == "yes":
    print("Current status of your flight as of " + 

Open in new window

0
Hi Bash experts,

Trying to parse multiple xml files in a directory.
Extract an attribute value from available xml files. e.g liferay-version="20.0.1.5"
sort them and get the greatest value from the identified list. e.g "20.0.1.8" and store them in a variable

Was trying using python, but due to restriction on my work server. couldn't install additional packages, so couldn't use python.

Is it possible using sed/awk/bash or any way please.

file1.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.5" patch-version="5.0">
  <description />
  <system />
</package>

Open in new window


file2.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.6" patch-version="6.0">
  <description />
  <system />
</package>

Open in new window



file3.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.7" patch-version="7.0">
  <description />
  <system />
</package>

Open in new window


file4.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.8" patch-version="8.0">
  <description />
  <system />
</package>

Open in new window

0

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.