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

Dear experts,

Can anyone point to any online site which can has c/c++/Python programs written/used for Financial Engineering.

The idea is show the content/calculations involved in Financial Engineering to my tutor who can then teach me leading to building my fundamentals.

My tutors teaches for Engineering college students and may not have the orientation of Financial Engineering programming features/calculations.

Kindly guide.

Thank you
0
Upgrade your Question Security!
LVL 12
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Hi Experts,

      I get the following error when I run python3 manage.py collectstatic.  Please see the error below.

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/debug_toolbar/toolbar.py", line 118, in get_panel_classes
    mod = import_module(panel_module)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/usr/local/lib/python3.6/dist-packages/debug_toolbar/panels/request.py", line 3, in <module>
    from django.core.urlresolvers import resolve
ModuleNotFoundError: No module named 'django.core.urlresolvers'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File 

Open in new window

0
How to write python code that would find a biggest value from a file and print the line that hold that big value

example:
file.txt
10 172.1.1.1
200 172.1.1.2
3  172.1.1.3

The script should loop through file.txt find and select number 200 and print 200 172.1.1.2 to a file.

I have the following, but it only print the first number 200

max_num = 0
with open('file.txt', 'r') as data: # use the with context so that the file closes gracefully
  for line in data.readlines(): # read the lines as a generator to be nice to my memory

    val = int(line.split()[0])
    if val > max_num: # logic
     max_num = val
print max_num #result
0
I am learning python and see the below line of code. I would like to know what it means

print("%.*f" % (digits, pi))

Here is the full code to return the value of pi up to first 10 digits.

Thanks
AB
0
How do I count repetitive consecutive two words from a text file.

input.txt file contains

backend error oracle error insufficient space
oracle error
insufficient space insufficient space
complete order etc

output should be
backend error count 1
oracle error count  2
insufficient space count 3
complete order 1
etc 1
0
Hi

I already asked a dragging question, but didn't ask about not leaving a trail of smudged pixels.
For anyone curious,
This is the stack overflow page i'm using for my Pygame mouse select, mouse-down and drag.

 here

My strategy for smooth dragging over existing pieces is...
On a piece select,
1) paste a blank square over that  piece, to clear its start off space,
2) Remember the x,y click displacement from the top left of the piece square, to help maintain the location of the piece as it is dragged under the cursor.
2) Capture the region under the mouse cursor to be repasted once the piece is dragged to cover up the old piece image. Can I save and re-paste the entire screen, super fast way? Redraw would be 2 slow.
Is the double buffing automatic? SetActivePage? setVisualPage()?

Thanks
0
Hi
My Python chess GUI is coming on well.
The 8x8, black and white is perfectly structured, colored at a changeable square_size

The white squares are just the white window background.
However, my transparent pieces don't render on a black square (rectangle draw.rect)
They are pasted under it! I can move the piece location by a few pixels, and see it emerge slowly from under the black square.

Is this a known issue?

Here is my relevant code, there is no code between them

pygame.draw.rect(screen, square_color, (x*square_size,y*square_size,square_size,square_size), 0)
       
            screen.blit(white_king,(x*square_size,y*square_size))

Open in new window

Thanks
0
Hi
I found this page of 60x60 chess images to use in my uncontestedly invulnerable ;) Python AI development

here

Instead of  trial and error myself, is there an example page with code for a Python Frame of image load, drag and drop? w listeners? like in chess apps? I have pygame ready.
I can see the functions on pygame.org, but I'd love to see it mostly in one screen.

Thanks
0
Dear experts,

I am a chartered accountant, CIMA and CFA.

I have a lot of experience in writing excel formulae (the entire credit goes to this forum, thank you experts).

I now want to pursue Financial Engineering.

I am learning C, C++ now. Once I become well versed with these two languages, I will move to learning Python.

Now from robustness, depth and FE requirement is Python better or MATLAB

I am not sure I have the bandwidth to complete/learn both.

Till date I have been learning C and I did not struggle to pick up the synatax or logic.

Kindly advice.
0
Hi
My invulnerable :) chess AI is going to be done, but I'd appreciate some pointers on a chess GUI in Python
I have a legal-move generator coming on nicely, I have pyGame.
Right now, I am printf'ing the board state to the Pycharm console, list of lists, White upper case and black lower case characters, init'ed like this:
It is legible in the fixed width font printout method below, but in array format - a GUI would ease the pain.
self.board = [[' ',' ',' ',' ',' ',' ',' ',' '] for i in range(8)]


        self.board[0] = ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
        self.board[1] = ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P']
        self.board[7] = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']
        self.board[6] = ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p']

Open in new window


This is my ChessBoard class's print method...
    def print(self):

        for i in range(7,-1,-1):
            print(i, '>', self.board[i])

Open in new window



What might the best GUI approach be?
Would I need transparent pieces over my own board GUI, to do select and drag and drop movements w a mouse?

Thanks
0
Free Tool: IP Lookup
LVL 12
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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
singleparentmeet.com is a really pitiful dating site. I want to unenroll, but their site is truly pathetic.
They don't have tech support and their help page requires 3rd party cookies.
Dating is a hotbed of scammers. Enabling 3rd party cookies doesn't appeal to me, especially from a crappy site that might have vultures, or Nigerians waiting for idiots to allow them access to info. Nigerian vultures!? How can I safely unenroll from this  site? Can I get VISA to read them the riot act? They will probably charge me soon, month end!

Thanks
0
I am having a couple of issues getting some python classes setup for some security testing. I'm just reading the instructions to get these setup for testing, and it says:

Start cmd.exe as Administrator and run:
pip install pyasn1
pip install impacket

I am not sure that either pip or install are actual windows commands. I noticed there is a setup.py script which I wondered if I should run that initially, but as I am new to python, do you have to change directory to the folder setup.py is installed in like you would say a vbs? If so what is the command to change directory to my USB where the files currently live?

Does pip or install sound like python commands as opposed to windows commands?

FYI this is the instructions:

https://medium.com/@airman604/installing-impacket-on-windows-ded7ba8bec9a

 and the download:

https://github.com/CoreSecurity/impacket
0
How to do following scripting in python ?

USGS (US Geological Survey) publishes various earthquake data as JSON feed. Here’s a feed spanning all domestic earthquakes from the past week:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson

Using this JSON feed:
1) identify every earthquake in California from past week,
2) list them chronologically (ascending),
3. and finally output in a format resembling the following e.g.:

2017-07-13T20:43:37+00:00 | 3km NW of Greenville, California | Magnitude: 1
2017-07-13T22:09:53+00:00 | 41km SW of Ferndale, California | Magnitude: 2.76
2017-07-13T22:31:04+00:00 | 11km E of Mammoth Lakes, California | Magnitude: 1.31
2017-07-13T22:32:48+00:00 | 15km SE of Mammoth Lakes, California | Magnitude: 0.92
2017-07-13T22:37:52+00:00 | 12km E of Mammoth Lakes, California | Magnitude: 0.95
2017-07-13T22:45:28+00:00 | 37km SE of Bridgeport, California | Magnitude: 1.7
2017-07-13T22:49:58+00:00 | 8km ENE of Mammoth Lakes, California | Magnitude: 0.92
2017-07-13T22:54:30+00:00 | 3km SE of Atascadero, California | Magnitude: 2.04
0
Hi All,

Need a python script

Write a script that outputs the network interfaces on a system with the corresponding IP addresses in CIDR format.  
Bonus points for including IPv6 addresses.
0
Product I would like to understand how it works buy looking at the content then creating it anew with a different language since it can no longer be purchased.I have a file for a small program called "SQL Grep" it was designed by a company called www.Gatherbirdsoftware.com the product and company seem to no longer be in business. Last I heard was around 2010-2011. The file I have might be helpful with the design of the product I want to make a similar tool in another language. Python & Java. I do not think it was written in either of those languages.

My questions are:
1. Is it legal to look at someone else's code "if I can even open it...?"
2. And determine how the flow of the code works with the developers language. I do this because I am learning to develop now.
3. The intention is to  build my own product to do the same thing with a newer different language?
4. The product is no longer sold and the site down with no response from the owners? I have sincerely tried.

Originally the products on the site were sold to benefit a childrens hospital. I am doing this for a charity as well. If of course I can do this in the way I hope.
Please advise. Product I would like to understand how it works buy looking at the content then creating it anew with a different language since it can no longer be purchased.
0
How to remove the unicode characters from csv file using Python 3?
0
Hi,

Anyone know if the R server in SQL 2016 and R and Python feature in SQL 2017 need additional license?

Answer should be a no as MS always license everything SQL server by a single cost and ALL feature is charged already.
0
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
Hi
I am bewildered by some of my Python bugs today, with a new approach of my Python chess engine.

The ChessBoard class doesn't connect with my ChessPiece data members.ChessBoard.pyChessPiece.pyChessGame.pyChessPlayer.py

The board tries to instantiate ChessPiece objects that are a white pawn, like ChessPiece.PIECE_PAWN
PIECE_PAWN is a totally valid data member in the ChessPiece class,
but the error states it is a non-existent attribute - PIECE_COLOR... too

Maybe I'm being poisoned by my Java old habits, eg there are no public static equivalents

How does my code look, also, style wise? My code must be stylistically proper! What have I missed, attached?
Does my ABC player look okay?

Thanks
0
Free Tool: Site Down Detector
LVL 12
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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
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
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
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
Hi
I am not certain if League of Legends is an RTS type network server, or an FPS? The player movements are well spaced out, so I'd think RTS

In Summoner's rift, is it only 5 people/champions playing? Is that the practical limit on players, in most network games?

If I port my working Java RTS server that I finished a little while ago to Python, could I expect any performance shift? It is TCP messaging, with UDP duplicates sent afterwards for speed.

Thanks
0
I'm trying to call mattermost "platform" application from a python script to create users & teams from a CSV file but i'm having an issue with the subprocess.call command which doesn't seems to recognize any parameter passed after --name.  I'm new to python so i won't be offended if you point me the obvious.

my CSV files got columns group, group_display, email, password.

with open("./accounts.csv", "rb") as wFile:
    os.chdir("/opt/mattermost/bin")
    wReader = csv.DictReader(wFile)
    for wLine in wReader:
        wCommand = []
        wCommand.append('./platform')
        wCommand.append('team')
        wCommand.append('create')
        wCommand.append('--name ' + wLine['group'])
        wCommand.append('--display_name \"' + wLine['group_display'] + '\"')
        wCommand.append('--private')
        print wCommand
        wRet = subprocess.call(wCommand)
        if (wRet == 0):
                print 'Imported ' + wLine['email']
        else:
                print 'Error importing ' + wLine['email']

Open in new window


i'm getting the error:

Error: unknown flag: --name mycustomername
Usage: platform team create [flags]


If i run the command from the cmd line with this command, it will pass:
./platform team create --name mycustomername --display_name "The Full Customer Name" --private

Any idea what i'm missing?
0
HI: I have a process where we email our invoices as pdf's to customers. I then extract the pdfs,  rename, and move to another directory using the python script below. The original files begin with the customer number; the renamed files begin with the date - so they can be sorted differently in explorer. However, the python script MOVES the file so I have been losing the originals and of course I sometimes need to sort invoices by customer (the first three characters of the original pdf). Does any python expert know how to change the script below from a MOVE process to a COPY?
Thanks!

target = ('C:\pythonrename\\files')
destination = ('C:\pythonrename\\invoices\\')
os.chdir(target)
allfiles = os.listdir(target)
for filename in allfiles:
    t = os.path.getmtime(filename)
    v = datetime.datetime.fromtimestamp(t)
    x = v.strftime('%Y%m%d')
    p = filename
    py = p[0:3]
    newstuff = (destination + x + "_" + py +".pdf")
    if not  os.path.isfile(newstuff):
                  os.rename(filename, newstuff)
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.