Go Premium for a chance to win a PS4. Enter to Win

x

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.

Share tech news, updates, or what's on your mind.

Sign up to Post

I need some advice on how I can execute a script on multiple computers within my organization.
Lets say I have 4 computers. It will be done in a chain e.g it starts with my computer and if the script fails then it will try and run it on computer 2 and if it fails then the 3rd and so on, but if it succeed then it won't be run on the remaining computers.
0
Vote for the Most Valuable Expert
LVL 7
Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Hello,
i need to process lots of small text files (1k to ~1M in size) millions per day.
they are syslogs files. the processing logic can be summarized in: filter out unwanted lines.
i did some tests with: cat File | grep -v bla | grep -v foo | grep -v bar > File.2
and i get huge space and clearness benefits. But the piping have some limits, after 20 not good any more :)
i'm not a day to day programmer, but kept playing around over the years.
i know/remember C,C++,Perl, some basic bash, started to learn Python some years back. i see that the fancy thing now is Go :)
do any of the language would offer a performance plus or minus, in this scenario? or the limiting factor for all will be the disk access?
Thank you for your thoughts

Ciprian
0
Hi I am trying to plot an autocorrelation in time series but I keep getting an error. I am not sure what I am doing wrong please help.

import numpy as np
import pandas as pd
from pandas.plotting import autocorrelation_plot
import matplotlib.pyplot as plt

import pandas_datareader.data as web
import datetime
start = datetime.datetime(2012, 7, 31)
end = datetime.datetime(2017, 6, 30)
aapl = web.DataReader('AAPL', 'yahoo', start, end)

[In]: aapl['Close'].autocorr(lag=1)

[Out]: 0.9979838827312616

But I dont know how I would plot this in a time series graph
0
import numpy as np
import pandas as pd

import matplotlib.pyplot as plt

start = datetime.datetime(2012, 7, 31)
end = datetime.datetime(2017, 6, 30)
aapl = web.DataReader('AAPL', 'google', start, end,)

aapl.plot()
plt.show()

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-229-3da2899dcb8e> in <module>()
      1 aapl.plot()
----> 2 plt.show()

TypeError: 'list' object is not callable
Screen-Shot-2017-11-18-at-10.53.00-A.png
0
Hi,
We are looking for an option to convert RTF file to TXT.  Please suggest any tool.
Tried python...any option

Thanks!
CPH
0
I have a csv with 3 cols:

(PDH-CSV 4.0) (SA Pacific Standard Time)(300),"\\server1\PhysicalDisk(_Total)\% Disk Read Time","\\server1\PhysicalDisk(_Total)\% Disk Write Time"
10/30/2017 15:00:15.568," "," "
10/30/2017 15:00:30.530,"25.763655942362824","130.21748494987176"
10/30/2017 15:00:45.518,"25.591636684958058","135.81093813384427"

What is the python code to get 95 percentile from col1 and col2 ?

This is the far that I've got:

import csv
import numpy as np

subtot = 0
i = 1
colnum = 2

while i <= colnum:
    with open('new1.csv') as csvfile:
        leercsv = csv.reader(csvfile, delimiter = ',')
        csvfile.__next__()
        for valor in leercsv:
            valorx = (valor[i])
            print(valor)
            valory = np.array(valor)
            p = np.percentile(valory, 95) # return 50th percentile, e.g median.
            print(p)

        if i == 1:
            print("95 percentile Disk Read Time: ",p)
        else:
            print("95 percentile Disk Write Time: ", p)
        i = i + 1

Open in new window

I get this error:

> ['10/30/2017 15:00:30.530,"25.763655942362824","130.21748494987176"']
Traceback (most recent call last):File "<stdin>", line 16, in <module>TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('U65') dtype('U65') dtype('U65')


Thanks and apologize if I'm making any mistakes on this request.
0
population_dict = ['mississauga = 780', 'brampton = 380', 'vaughn = 180']

population = pd.Series(population_dict)
population

0    mississauga = 780
1       brampton = 380
2         vaughn = 180
dtype: object # here I am getting an output

but when I type this function I get an error

population ['brampton']

--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

TypeError: an integer is required

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-53-938f5943ac7e> in <module>()
----> 1 population ['brampton']

~/anaconda3/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
    599         key = com._apply_if_callable(key, self)
    600         try:
--> 601             result = self.index.get_value(self, key)
    602
    603             if not is_scalar(result):

~/anaconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   2475         try:
   2476             return self._engine.get_value(s, k,
-> 2477                                           tz=getattr(series.dtype, 'tz', None))
   2478         …
0
Hi,
I have taken a jython script which checks for the Application server, Node status and mails it to the admin if anything is stopped.
The only issue I am having is that for running the jython script, I have to pass the username and password either through command line or through prompt, when running the script through wsadmin.
I would like to get this automated such that, the script automatically picks the windows credentials.

Any help would be highly appreciated.

Thank you.
0
ValueError: too many values to unpack (expected 2) this error occured when executing below program
# USAGE
# python distance_to_camera.py

# import the necessary packages
import numpy as np
import cv2

def find_marker(image):
	# convert the image to grayscale, blur it, and detect edges
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	gray = cv2.GaussianBlur(gray, (5, 5), 0)
	edged = cv2.Canny(gray, 35, 125)

	# find the contours in the edged image and keep the largest one;
	# we'll assume that this is our piece of paper in the image
	(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
	c = max(cnts, key = cv2.contourArea)

	# compute the bounding box of the of the paper region and return it
	return cv2.minAreaRect(c)

def distance_to_camera(knownWidth, focalLength, perWidth):
	# compute and return the distance from the maker to the camera
	return (knownWidth * focalLength) / perWidth

# initialize the known distance from the camera to the object, which
# in this case is 24 inches
KNOWN_DISTANCE = 24.0

# initialize the known object width, which in this case, the piece of
# paper is 12 inches wide
KNOWN_WIDTH = 11.0

# initialize the list of images that we'll be using
IMAGE_PATHS = ["images/2ft.png", "images/3ft.png", "images/4ft.png"]

# load the furst image that contains an object that is KNOWN TO BE 2 feet
# from our camera, then find the paper marker in the image, and initialize
# the focal length
image = cv2.imread(IMAGE_PATHS[0])

Open in new window

0
I have two arrays

 OldDataSet = {
 'id': [20,30,40,50,60,70]
 ,'OdoLength': [26.12,43.12,46.81,56.23,111.07,166.38]}

 NewDataSet = {
 'id': [3000,4000,5000,6000,7000,8000]
 ,'OdoLength': [25.03,42.12,45.74,46,110.05,165.41]}

 df1= pd.DataFrame(OldDataSet)
 df2 = pd.DataFrame(NewDataSet)

 OldDataSetArray = df1.as_matrix()
 NewDataSetArray = df2.as_matrix()

Open in new window


Array 1 and Array 2 Match by closes difference, based on left over number from Array2.

Starting at Array 1, ID 20, find the nearest which in this case would be the first Number in Array 2 ID 3000 (26.12-25.03). so ID 20, gets matched to 3000. Where it gets tricky is if one value in Array 2 is not the closest, then it is skipped. for example, ID 40 value 46.81 is compared to 45.74, 46 and the smallest value is .81 from 46 ID 6000. So ID 40--> ID 6000. ID 5000 in array 2 is now skipped for any future comparisons. So now when comparing array 1 ID 50, it is compared to the next available number in array 2, 110.05. array 1 ID 50 is matched to Array 2 ID 7000.   I have attached an excel file to better explain the logic.

Final Match set is as follows.  
20  26.12   3000    25.03  
30  43.12   4000    42.12  
40  46.81   6000    46  
50  56.23   7000    110.05  
60  111.07  8000    165.41  
70  166.38  0   0
0
How to Use the Help Bell
LVL 11
How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

I have a table TABLEAA in a MS Access database and I want to retrieve the data into some Python code.

I can connect to the database using win32com and run a query (SELECT, Z00, Z01, Z02, Z03 FROM TABLEAA) but how do I then refer to Z00, Z01 etc in the Python code? Here is my sample code...

import win32com.client
from win32com.client import Dispatch

strDbName = r'C:\\Users\Ross\Documents\TESTDB.mdb'
objAccess = Dispatch("Access.Application")
objAccess.OpenCurrentDatabase(strDbName)

objAccess.DoCmd.OpenQuery('AAQUERY')
0
Hello! I am a python beginner. I write a code, with pyowm module (Pyowm on github: https://github.com/csparpa/pyowm), but its for some reason wrong. I has download the pyowm module and I using the terminal for module installation on python 3. My os is Mac OS X Yosemite and the my python version is 3.6.3. I even use Sublime Text 3 as a code editor. What I do wrong? Please help me!
My code:
   
    import pyowm
   
    city = input('Write a city for weather analysis:')
   
    owm = pyowm.OWM('5f28df836a35fc458e6270eb8f01ec86')
    observation = own.weather_at_place(city)
    w = observation.get_weather()
    temperature = w.get_temperature('celsius')['temp']
   
    print("The temperature in" + city + "is: " + str(temperature) + "on celsius")

But python say:

Traceback (most recent call last):
  File "untitled.py", line 3, in <module>
    city = input('Write a city for weather analysis:')
  File "<string>", line 1, in <module>
NameError: name 'London' is not defined
SBSC02PBB8G9402:pythonpractice dchim$ python untitled.py
Write a city for weather analysis: London
Traceback (most recent call last):
  File "untitled.py", line 3, in <module>
    city = input(str('Write a city for weather analysis:'))
  File "<string>", line 1, in <module>
NameError: name 'London' is not defined.


Thanks!!!
untitled.py
0
i appear to be having issues using anaconda.
i have copied the code into Jupyter note as follows:
In [1]:
def CryptoDataCSV(symbol, frequency):

#Params: String symbol, int frequency = 300,900,1800,7200,14400,86400

#Returns: df from first available date

url ='https://poloniex.com/public?command=returnChartData¤cyPair='+symbol+'&end=9999999999&period='+str(frequency)+'&start=0'

df = pd.read_json(url)

df.set_index('date',inplace=True)

df.to_csv(symbol + '.csv')

print('Processed: ' + symbol)
In [2]:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
In [3]:
tickers = ['USDT_BTC','USDT_ETC','USDT_XMR','USDT_ETH','USDT_DASH',
'USDT_XRP','USDT_LTC','USDT_NXT','USDT_STR','USDT_REP','USDT_ZEC']
In [4]:
crypto_df = pd.DataFrame()
for ticker in tickers:
crypto_df[ticker] = pd.read_csv(ticker+'.csv', index_col = 'date')['close']
crypto_df.dropna(inplace=True)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-b59f4116fa1a> in <module>()
      1 crypto_df = pd.DataFrame()
      2 for ticker in tickers:
----> 3     crypto_df[ticker] = pd.read_csv(ticker+'.csv', index_col = 'date')['close']
      4 crypto_df.dropna(inplace=True)
~\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, …
0
So, I've been working on a Tic Tac Toe app. (Trying to learn how to user django/python)
All of my code seems to be functional, but the issue is that when the user submits the form, the data doesn't seem to go into the database at all. Because it doesn't find its way into a db table, I can't use that value on another page.
Could anyone review my code and see if you notice anything wrong?
Thanks in advance!

views.py -
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response
import os
from .forms import PlayerInfo
from .models import Player

def index(request):
    return render(request, 'index.html')

def start(request):
    if request.method == 'POST':
        form = PlayerInfo(request.POST)
        if form.is_valid():
            obj = Player()
            obj.player_one_name = form.cleaned_data['player_one_name']
            obj.player_two_name = form.cleaned_data['player_two_name']
            form.save()
            return HttpResponseRedirect('game/')

    else:
        form = PlayerInfo()

        return render(request, 'start.html')


def game(request):
    queryset = Player.objects.all()

    args = {'fpn': queryset.values('player_one_name'), 'spn': queryset.values('player_two_name')}
    return render_to_response('game.html', args)

Open in new window


models.py -
from django.db import models

class Player(models.Model):
    player_one_name = models.CharField(max_length=30, default='')
    player_two_name = models.CharField(max_length=30, default='')

Open in new window


forms.py -
from django import forms

class PlayerInfo(forms.Form):
    player_one_name = forms.CharField(max_length=30, label='First player name')
    player_two_name = forms.CharField(max_length=30, label='Second player name')

Open in new window


start.html -
{% extends 'base.html' %}
{% block botRow %}
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
{% endblock %}

Open in new window


game.html -
{% extends 'base.html' %}
{% block midRow %}
    <p>{{ fpn }}</p>
    <p>{{ spn }}</p>
{% endblock %}

Open in new window

0
hi

just started learning python. installed python and pycham and wrote hello world kind of application.

can you please point me to good links, resources, free video courses, trainings available on python.

Please advise
pythin.png
pythin.png
0
I am scraping https://manulife.taleo.net/careersection/external_global/jobsearch.ftl?lang=en&location=1038# , when i inspect the next button's link , I get :
<span class="pagerlink">
				<a href="#" id="next" title="Go to the next page">Next</a>
			</span>

Open in new window


Can you help with it, how can I perform pagination in this website.
0
I need to create a solution that will allow me to randomly split up a group of N people (that number will change over time) into meeting groups of two each month.  No two people should work together again until/unless every person has met with every other person.  I'm not sure of how to best do this (SQL, Excel, Python? the simpler, the better) so would appreciate any solution you can provide.
0
I am trying to update a dict with values searched from mongoDB whose parameters are taken from another dict. What I have till now is:

    lst = {'a':1}
    b={'Name':'name_1', 'Address':'Address_1'}
    lst.update(k:coll.find({"_id":id}{v:1})) for k,v in b.items()

What is the right way to do this procedure?
0
Python Gurus,

I have an outer loop where I pull node information off the network, within that loop I pull the device information, within that loop, I pull the connected device info. Mostly I cycle through this loop without errors, however, lately I've been getting the error "string indices must be integers". The failure is happening in the last inner loop (clients). Since this just started happening, I'll have to assume new data came through that I haven't accommodated.  I would like to write this in such a way that I accomplish 2 things: 1.) Identify which element is the culprit; 2.) when there's an error, it is noted (logged), then on to the next, without an exit.

       
  
       try:

            [snippet begin]
         
             clients_json = clients_response.json()
  
              for clientEntry in clients_json:
                    mdnsName = clientEntry['mdnsName']
                    deviceDesc = clientEntry['description']
                    dhcpHostName = clientEntry['dhcpHostname']
                    clientMac          = clientEntry['mac']
                    Id          = clientEntry['id']
                    Ip          = clientEntry['ip']
                    usageRecv     = clientEntry['usage']['recv']
                    usageSent         = clientEntry['usage']['sent']
                    #TODO: Get this is UTC format
                    InsertDate = '10/24/2017' 

      
                pass

               [snippet ends]

        except 

Open in new window

0
Free Tool: Port Scanner
LVL 11
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

hi,im new in python and pillow, i wanna do one of filtering (box,mean,median) to a lena picture however i have problems and i cant do it.How can i do it?Could you help me please?,thanks :)
0
I tried to Run but DB not connected i am using Xampp mysql server,  any idea for this?

Send Querys like

#!/usr/bin/python
from Tkinter import *
import MySQLdb
#-----------------------------------------------------------
## Connect to DB
conn = MySQLdb.connect(host='localhost', user='root', db='mind0')
##Create a cursor
curs = conn.cursor()
## *****************************************************
# Root level form
class MyApp:
  def __init__(self):
    window = Tk()
    window.title('Data Entry Form')  
    frame = Frame(window)
    frame.pack()
## BEGIN Fields ***********************************************    
    self.fields = {}
#--------------    
    l = Label(frame, text="vendID:")
    l.grid(row=0, column=0)    
    self.fields['vendID'] = Entry(frame)
    self.fields['vendID'].grid(row=0, column=1)    
#--------------      
    l = Label(frame, text="vendName:")
    l.grid(row=2, column=0)  
    self.fields['vendName'] = Entry(frame)
    self.fields['vendName'].grid(row=2, column=1)
## END Fields ************************************************    
 
## BEGIN Buttons ########
    clearbtn = Button(frame, text="Clear", command=self.do_clear)
    clearbtn.grid(row=11, column=0)
       
    submitbtn = Button(frame, text="Submit", command=self.do_insert)
    submitbtn.grid(row=11, column=1)
 
    updatebtn = Button(frame, text="Update", command=self.do_update)
    updatebtn.grid(row=11, column=2)
## END Buttons ##########…
0
dear all,
I have got video and audio files I need to segment them based on their text.
I need to segment all the files. for example ( a single word contain n audio frames and n of visual frames (images) )
Can any one help or advice how can I make it?

Thanks
0
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-63-41f0d72a57d4> in <module>()
----> 1 grocery_list.append (Onions)
      2 print (grocery_list2)

AttributeError: 'tuple' object has no attribute 'append'

What does the error message mean? Why won't my list append?
0
Write a function called my_gcd() that takes parameters a and b and returns their greatest common divisor. Create your own implementation of the algorithm and test your code by comparing the output of your function to Python's gcd() function from math package.Test the code with the following inputs: (39, 91), (20, 30) and (40,40). Explain the logic of your function.
0
n=3

def countdown (n):
    if n <= 0:
        print ('Blastoff!')
    else:
        print (n)
        countdown (n-1)

when I press shift + enter I get a blank answer
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.