Improve company productivity with a Business Account.Sign Up

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

Implement an algorithm as method to take a BST and convert it to a mirror tree where left and right subtrees are interchanged.
and print BST each level in separate line
All coding should be in Python
0
Build your data science skills into a career
Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

Hi
I had to bitterly accept an expert comment recently, J/K

..Implying that my usage of CamelCasing in my code was lame, and I should use underscores.
My personal feeling was that camelCasing was easier to read, less long, but this article below confirms the expert opinion, underscores are better!

here

So I grudgingly_accept!  j/k

Thanks
0
I am looking for ways to find and identify UK's national speed limit (NSL) signs from screen captures of Google street view.
screen capture
0
Please help me.... I'm currently working a face recognition project using python,opencv and tkinter, In the project i tried to implement the detector module in tkinter but it is not working.I'm not receiving any output it works without any syntax error.

import cv2,os
import sqlite3
import numpy as np
import tkinter as tk
import cv2
from PIL import Image, ImageTk
import pickle
import time
import datetime

width, height = 800, 600
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "Classifiers/face.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
path = 'dataSet'


root = tk.Tk()
root.bind('<Escape>', lambda e: root.quit())
lmain = tk.Label(root)
lmain.pack()

btn = tk.Button(root, text="End", command=root.destroy)
btn.pack(fill="both", expand=True, padx=10, pady=10)

def getProfile(Id):
      conn=sqlite3.connect("facebase.db")
      cmd="SELECT * FROM people WHERE ID="+str(Id)
      cursor=conn.execute(cmd)
      profile=None
      for row in cursor:
            profile=row
      conn.close()
      return profile



#def show_frame():
    #_, frame = cap.read()
    #frame = cv2.flip(frame, 1)
    #cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    #img = Image.fromarray(cv2image)
    #imgtk = ImageTk.PhotoImage(image=img)
    #lmain.imgtk = imgtk
    #lmain.configure(image=imgtk)
    …
0
I had this question after viewing wsadmin script for disabling AutoStart of app.

Team,
 I am having below query for solution, please check and send me script.

Now I have an new request from client,as below.

In websphere,by clicking application, and then click on application ( war or ear) file,then go to target modules,there are 2 options, one is enable startup and disable startup.

Enable star up:- if it is enabled,then when JVM will start by the time ear also up
And
Disable startup:- if it is enabled,then when JVM will start by the time ear will not start,we need to do it manually.

For both the cases,we need to restart JVM post update.

Now requirements is that,we need create a script either Python or shell script to update the startups by selecting option when required ,not from console.

Step1:- option to select JVM
Step2:- option to see status of JVM is up and running or not
Step3:- option to select enable autostart , disable autostart up, status,...Here to select one and check the status.

Step4:- final verification post doing auto startup enabled or disabled

Can you look and send me script.

PMR raised,IBM said it can be automated.

Thanks,
Satish
0
Team,
Now I have an new request from client,as below.

In websphere,by clicking application, and then click on application ( war or ear) file,then go to target modules,there are 2 options, one is enable startup and disable startup.

Enable star up:- if it is enabled,then when JVM will start by the time ear also up
And
Disable startup:- if it is enabled,then when JVM will start by the time ear will not start,we need to do it manually.

For both the cases,we need to restart JVM post update.

Now requirements is that,we need create a script either Python or shell script to update the startups by selecting option when required ,not from console.

Step1:- option to select JVM
Step2:- option to see status of JVM is up and running or not
Step3:- option to select enable autostart , disable autostart up, status,...Here to select one and check the status.

Step4:- final verification post doing auto startup enabled or disabled

Can you look and send me script.

PMR raised,IBM said it can be automated.
0
I have a bunch of TeamCity agents (Windows, Linux, AWS, OpenShift). To have consistent state it is desirable that all of them have the same software(& its modules) +version installed. Manually checking them is very tedious.

Hence I have decided to have an application which shows this information as a dashboard, i.e. a snapshot view of all the agents and the software installed on them. I have decided to use Python(v3.6) for the implementation. I am not a hardcore developer and a novice in python programming hence this will be `learn and do` project for me.

I was thinking of some sort of a code-base on all agents that would fetch the necessary details for that agent only.

I will then have a central server that will utilize this data from each agent and then display it in the form of a dashboard.

Please let me know if the above design is the proper way of doing it or please suggest some alternate if any.

If I can have some pointers as how to go about implementing it that would be of great help.

This is what i have come up till now;

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Product")
for objItem in colItems:
    print (objItem.Caption, objItem.Version)
    print ("\n")

However this dosen't display all the packages/modules, i suppose this is …
0
I want to check for a particular sender outlook mail and process it automatically wherever it arrives

I am looking for a case, if my outlook credentials got expired and tried to login with my new credentials or my system was restarted .. mean while i got 3 mails ... can you suggest me how to proceed with these 2 cases

For continuous monitor for a new mail for a specific subject i have found the following code

import win32com.client
import pythoncom
import re

class Handler_Class(object):
  def OnNewMailEx(self, receivedItemsIDs):
    # RecrivedItemIDs is a collection of mail IDs separated by a ",".
    # You know, sometimes more than 1 mail is received at the same moment.
    for ID in receivedItemsIDs.split(","):
        mail = outlook.Session.GetItemFromID(ID)
        subject = mail.Subject
    print subject  
        try:
            command = re.search(r"%(.*?)%", subject).group(1)

            print command # Or whatever code you wish to execute.
        except:
            pass


outlook = win32com.client.DispatchWithEvents("Outlook.Application",Handler_Class)

#and then an infinit loop that waits from events.
pythoncom.PumpMessages()
0
In my computer science class, I received an assignment that required me to write a small script to predict the rate of rabbit population each year with given parameters. Originally, I was supposed to write it in java, but because I am a noob in that language, I decided to first write it out in python. After doing so, the python script ended up working and yielding the correct results. However, when I attempted to write the script in java, the result is completely different compared to the python version. I spent countless hours looking over the java code, and I can't find out why this is happening.

This is the python version:

from time import sleep
##Summer to summer basis
##There are E female rabbits and E male rabbits in summer of year one
##Rabbits can't reproduce in the first year, so for year one E females and E males will remain the same 
##Every winter, AI kills percentage P of all female and male rabbits equally 
##If outcome is a decimal, round DOWN
##Every surviving female will give birth to R baby rabbits in the spring 
##These rabbits will reach reproduction age by the next spring, if they survive the AI winter 

def calcPopulation(E,P,R,Y):
    if E > 1000 or P > 100 or R > 50 or Y > 10:
        print("One or more values that you entered is too high")
        return None
    elif Y == 1:
        return E*2

    males = E
    females = E
    #^For first year
    for i in range(Y-1): #males
        males -= int((P*males)/100)

    for i in range(Y-1):

Open in new window

0
how do  i get input from other window in python gui programming ?
0
The 14th Annual Expert Award Winners
LVL 7
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Hi
I'm whipping up this quick chessBoard data structure in Python, but I think my C/Java habits are tripping me somehow.
The objects aren't linking up correctly,and are giving a roll of errors : I have a chessGame class to contain the chessBoard.
I'll do the chessPiece class once this works.
It should be simple

Here is the big chessGame class: That now, just creates the chessboard, and has the main code
import chessBoard

class chessGame:
    def __init__(self):
        print("\n\n.........")
        c=chessBoard()


print('chess main')

chessGame()

Open in new window


Here is the chessBoard:
class chessBoard:

    def __init__(self):

        self.pieces=[]

        #white pawns
        for i in range(0,9):
            print(i)

Open in new window


There are missing lines, but once this simple structure works, I'll be set

Where am I going wrong?

Thanks
0
I built the attached config rule in Python that provides security automation around IAM access key rotation.  It checks if the users access keys have been rotated within a specified timeframe, sending all compliance data directly to AWS Config. If the user is non-compliant, it then sends an email via SES. Since not all our IAM usernames match the user’s email address, there are some challenges with getting notifications sent out. If I were to create a Dynamo DB table that maps the IAM user to an email address, is there there a way to have lambda import that table to determine the intended recipient?
lambda.py
0
Hi
For my Python RTS / MOBA server,

I am at a decision where I should either make a class for reading UDP activity updates from the clients over TCP activity ( a failsafe)
Should I have a UDPlistener class and a TCPlistener class?
or should I have a packetListener class with a UDPlisten method and  also, a TCPlisten method? - that are each made into Threads?
I think an all-in-one approach would make linking into the game smoother?

both would work, but which would look best? Is Python better suited to one?

Thanks
0
from enum import Enum

class Side(Enum):
    none = 0
    left = 1
    right = 2

class ChainLink:

    def __init__(self):
        self._left = None
        self._right = None

    def append(self, link):
        if self._right is not None: raise Exception('Link already connected!')
        self._right = link
        link._left = self

    def longer_side(self):
        return None

left = ChainLink()
middle = ChainLink()
right = ChainLink()
left.append(middle)
middle.append(right)
print(left.longer_side() == Side.right)
0
I have wrote a python script to open arround 1k urls and process them to get the desired result,but it seems like eventhough multithreading has been introduced its working slowly, and after some urls have been processed,the process seems to be hanged, I am not able to decide whether its still running or stopped.How can I create multiple threads to process them faster.Any help will be highly appreciated.Thanks in Advance. Below is my script.

import threading
from multiprocessing.pool import ThreadPool
from selenium import webdriver
from selenium.webdriver.phantomjs.service import Service
from selenium.webdriver.common.desired_capabilities import
DesiredCapabilities
from selenium.webdriver.remote.webdriver import WebDriver as
RemoteWebDriver
from multiprocessing.dummy import Pool  # This is a thread-based Pool
from multiprocessing import cpu_count
import csv

def fetch_url(url):
    driver = webdriver.PhantomJS()
    driver.get(url)
    html = driver.page_source
    print(html)
    print("'%s\' fetched in %ss" % (url[0], (time.time() - start)))

def thread_task(lock,data_set):
    lock.acquire()
    fetch_url(url)
    lock.release()

if __name__ == "__main__":
    data_set = []
    with open('file.csv', 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in spamreader:
            data_set.append(row)

    lock = threading.Lock()
    # data set will contain a list of 1k urls
    for url in…
0
I am trying to write a program in Python which do the following:

Using Windows environment,

1) Run queries against an Oracle Database
2) Generate output of the Queries in Step 1 as Excel Files
3) Import the Excel file into an Access Database

Please advise.
0
How to get weather information of next two days. I created the script but i gives only current day information. Here, i attach the code.
api_address = "http://api.openweathermap.org/data/2.5/weather?appid=6784429f5eff661309aaa5280a143f97&q="
city = input("city name :")
url=api_address+city
j_data=requests.get(url).json()

Open in new window

0
I have a large pandas dataframe with ~3MM observations of users and artists listened to. Each row includes user id and artist id (encoded for easier integer handling). I have executed several methods to generate a binary sparse matrix, however the size of the dataset is greatly challenging my computer's memory allocation, specifically when working in my Jupyter kernel.

I have divided my dataframe into training and testing sets, but still my training set isn't happy with the scale at which it's being asked to do calculations.

My three objectives are as follows:

1) assign users as row and artists by column, then input dataframe entries in binary form, i.e. 0s and 1s
2) scale the training matrix to fit ~2MM stored elements
3) convert the matrix into CSR format for collaborative filtering purposes

I am happy to implement batching if tihs is a fix, however my experience with chunking data is very limited.

My ultimate objective is to measure distance between users to formulate artist recommendations. Please help!
0
My script.py should keep running Daily between 7:00 am to 22:00 , for example if my script finish at 10:00am it run again till 22:00Pm, how can i do it ?
0
What Kind of Coding Program is Right for You?
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

Hi All,

This is my frist python script working on... I would like to list the servers or cluster from websphere. The script contents are below...
run by cmd - wsadmin.bat -lang jython -F listServers.py
Error -
WASX7209I: Connected to process "dmgr" on node dmgrNode using SOAP connector;  The type of process is: DeploymentManager
WASX7017E: Exception received while running file "listServers.py"; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (most recent call last):
  File "<string>", line 13, in <module>
ValueError: call stack is not deep enough

Content of the script - this example got from - C:\IBM\WebSphere\AppServer\scriptLibraries\servers\V70

#--------------------------------------------------------------------
# Set global constants
#--------------------------------------------------------------------
import sys
import java
import AdminUtilities

# Setting up Global Variable within this script
bundleName = "com.ibm.ws.scripting.resources.scriptLibraryMessage"
resourceBundle = AdminUtilities.getResourceBundle(bundleName)

# Retrieve scripting objects from local name space
AdminConfig = sys._getframe(1).f_locals['AdminConfig']
AdminApp = sys._getframe(1).f_locals['AdminApp']
AdminControl = sys._getframe(1).f_locals['AdminControl']
AdminTask = sys._getframe(1).f_locals['AdminTask']
Help = sys._getframe(1).f_locals['Help']    


## Example 1 List available servers with given server type and node ##
def …
0
In my organization, we have a requirement where our deployment tool uses packages for distribution to servers.  A package may contain may contain artifacts such as binaries and configuration files.

I'm working on a project that require python modules to be installed on the target hosts, but I must use the deployment tool to install the modules versus using the pip tool.  Furthermore, the target hosts do not have internet access making the pip tool useless even if we're allowed to use pip.

I've found the other members in the organization packaged their modules into .pyd files.  For example, in order for the python pyodbc moduled to be installed, it was converted to a single file ending .pyd.  Google searches showed the .pyd files are nothing but DLLs for windows, and cythonize may have been used to package the pyodbc module into a DLL.  The distribution also included a .pth, which is a text file indication the path where the module should be installed on.

I'm attempting to recreate the steps that other members in my organization successfully implemented: how do I convert python modules (such as pyodbc, requets, etc) into their respective .pyd counterparts?
0
I'm running python (v3.4) in IBM I / AS400 (very similar to mainframes) to generate QR code dynamically to print in customer statements.
Using PyQRCode and PyPNG, I've generated QR code in PNG file. But PNG isn't supported in IBM I, neither is SVG or EPS.
Hence I need to convert PNG to JPEG or TIFF. BUT again PILLOW/numpy is not an option as there was no C/CPP in AS400 and GCC couldn't be setup properly.
So, need to convert (or generate) QR Code in JPG using only pure python libraries.

I'm very new to python and not getting clear leads on ways to
i) generate QR code in JPEG
  or
ii) to convert PNG/SVG to JPG without PIL/PILLOW

any help?
0
I ran across some python code that allows continuous, live plotting of twitter stream data and sentiment rating. When the author of the code demonstrated it on Youtube, he was able to plot the twitter in a graph, and the graph updated  with each tweet. However, when I run the same code, I get one graph for each tweet and the plot points do not form a continuous line--instead the output consists of one graph, one plot point for each tweet. I would like to  get the graph to show the plotted point for all tweets in one chart in a continuous line.

BTW I am not the  only person who ran into this same problem with the code.  FYI I am currently running python 2.7,  in a Spyder 3.2.8 development environment on Mac.  I have attached the code (without access key information) and it has not been altered from the author's version. Any assistance would be greatly appreciated.

Thanks!
wasmithpfs
test31818.py
Screen-Shot-2018-03-18-at-9.28.21-PM.png
0
Hi: Norie has just helped me with a python question.. here is a follow up. I am having to convert some python2 programs to python3.   Now I have another bank statement that I need to reconfigure to a csv format for importing to a foxpro database. This time the bank sees fit to put commas  within the text so unless  I hunt down the stray commas my conversion to true csv falls flat. To do this  I created a list of instances where the stray commas arise , then take them out by replacing the commas with semi colons thus:

# remove extra commas in text field
input = open("santander2.csv", "r")
output = open("santander22.csv", "wb")
lines = input.readlines()
input.close()
for (line) in lines:
      newcontents = re.sub(r", MANDATE","; MANDATE",line)
      newcontents1 = re.sub(r", REFERENCE",";REFERENCE",newcontents)
      newcontents2 = re.sub(r"PL,","PL;",newcontents1)
      newcontents3 = re.sub(r"PLAIN,","PLAIN;",newcontents2)
      newcontents4 = re.sub(r"GBP, ON","GBP; ON",newcontents3)
      newcontents5 = re.sub(r" COMM FIN, "," COMM FIN; ",newcontents4)
      newcontents6 = re.sub(r" TT2, "," TT2; ",newcontents5)
      newcontents7 = re.sub(r" CHARGE, "," CHARGE; ",newcontents6)
      #print  >> output,newcontents7.strip()
      output.write(newcontents7.strip())
output.close()

I have commented out the print line that worked in python2 but the new line returns the erro as shown in attached file.
Can anybody see my mistake?
Thanks!
santander.png
0
I want to get input from a user in order to pass it as a listlike set of integers for iloc, but cannot get the list into a working form like [1,3,4,5] for example.

df.iloc[:,choices]

In the above code, I want to specify column indexes from user input instead of hard coding the numbers in.  Please advise.
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.