Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
QuarkJets
Sep 8, 2008

Within that inner loop, you're appending a card to hand, appending hand to res, and then removing a card from hand. But this modifies the hand that's in res, because you're actually appending a pointer to the list instead of a copy of the list.

If you did this instead, it would work as expected:

Python code:
    for card in cards:
        hand.append(card) #add a card from the list of cards to the hand
        res.append(hand[:]) #add a copy of the hand to the list of hands
        hand.remove(card) #remove the card from the hand
And here's a super awesome and fast way to solve the same problem using a nested list comprehension:

Python code:
def replace(hand):
    return [ [ card if card != 'a' else new_card for card in hand ] for new_card in (5, 6, 7, 8, 9)]
Note that this does not actually modify hand, which is a modification from your code's behavior. All that it does is return the list of lists that you wanted

Adbot
ADBOT LOVES YOU

Lyon
Apr 17, 2003

dantheman650 posted:

I'm beating my head against the wall about a seemingly simple problem. This is a simple test block for code that will eventually delete a wild card from a poker hand, then create a list of all possible hands (each represented by a list of cards) by substituting each possible card in for the wild card and adding that hand to the list. This is the homework for the Udacity course recommended on the previous page. (I'm loving the course and also CheckIO - thanks for recommending them!)

code:
def replace(hand): #takes a list of cards as input
    if "a" in hand:
        hand.remove("a") #placeholder for wildcard - remove the wildcard from the hand
    res = []
    cards = [5,6,7,8,9] #placeholder for list of cards to substitute in for wildcard
    for card in cards:
        hand.append(card) #add a card from the list of cards to the hand
        res.append(hand) #add the hand to the list of hands
        hand.remove(card) #remove the card from the hand
    return res

print(replace([1,2,3,4,"a"]))

This should return [[1,2,3,4,5], [1,2,3,4,6], ....] but it's returning [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]].

If I add some print statements to debug, one after each of the statements in the for loop, I get this:

code:
Appended hand: [1, 2, 3, 4, 5]
Result:  [[1, 2, 3, 4, 5]]
Hand after removal:  [1, 2, 3, 4]

Appended hand: [1, 2, 3, 4, 6]
Result:  [[1, 2, 3, 4, 6], [1, 2, 3, 4, 6]]
Hand after removal:  [1, 2, 3, 4]

Appended hand: [1, 2, 3, 4, 7]
Result:  [[1, 2, 3, 4, 7], [1, 2, 3, 4, 7], [1, 2, 3, 4, 7]]
Hand after removal:  [1, 2, 3, 4]
...

The function is correctly appending and removing the cards from the hand, and even appends the hand correctly to res on the first pass through the loop, but on the second and further passes, it's somehow retroactively changing the elements before the current one being appended to all be equal to the current one being appended. What in the world is causing this behavior? Am I missing something incredibly silly?

You're appending a reference to the hand object five times so they all end up being identical. Throw a list() around the hand append so it generates a new list.

res.append(list(hand)) should work.

Harriet Carker
Jun 2, 2009

Thank you both. I can't express how much this thread has been helpful. You are all wonderful!

SurgicalOntologist
Jun 17, 2004

cowofwar posted:

Thanks, this seems to work. Although I had to grep out a bunch of lines and cut excess columns because it doesn't tolerate variation.

If you're doing operations on tabular data from csv format, the library pandas may also be helpful.

Xandu
Feb 19, 2006


It's hard to be humble when you're as great as I am.
I'm pretty new to Python and am trying to scrape a table off a website that's split across multiple pages. This is the address with the page number in bold, going from 1 to 1123.

http://www.vdc-sy.info/index.php/en/martyrs/1/c29ydGJ5PWEua2lsbGVkX2RhdGV8c29ydGRpcj1ERVNDfGFwcHJvdmVkPXZpc2libGV8ZXh0cmFkaXNwbGF5PTB8

Here's what I've managed to come up with, just testing the first 10 pages, but it only writes 2 pages worth of data into the csv file and I can't figure out why. Any ideas?

code:
import urllib.request
from bs4 import BeautifulSoup
import csv

for numb in range(1, 10):
    url = ('http://www.vdc-sy.info/index.php/en/martyrs/' + str(numb) + '/c29ydGJ5PWEua2lsbGVkX2RhdGV8c29ydGRpcj1ERVNDf'
                                                                        'GFwcHJvdmVkPXZpc2libGV8ZXh0cmFkaXNwbGF5PTB8')
    page = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(page)

    with open('out32.csv', 'w') as f:
        csvwriter = csv.writer(f)
        for row in soup.find_all('tr')[2:]:
            tds = [c.text.encode('utf-8') for c in row.find_all('td')]
            csvwriter.writerow(tds)

Xandu fucked around with this message at 09:02 on Feb 22, 2015

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies
code:
with open('out32.csv', 'w') as f:
Opens the file and then truncates it so you're losing data. You want to use 'a' after page one so that data gets "appended" to it, instead of overwriting the previous file writes.

so:
code:
mode = 'w' if numb ==  1 else 'a'
with open('out32.csv', mode) as f:

EAT THE EGGS RICOLA
May 29, 2008

Xandu posted:

I'm pretty new to Python and am trying to scrape a table off a website that's split across multiple pages. This is the address with the page number in bold, going from 1 to 1123.

http://www.vdc-sy.info/index.php/en/martyrs/1/c29ydGJ5PWEua2lsbGVkX2RhdGV8c29ydGRpcj1ERVNDfGFwcHJvdmVkPXZpc2libGV8ZXh0cmFkaXNwbGF5PTB8

Here's what I've managed to come up with, just testing the first 10 pages, but it only writes 2 pages worth of data into the csv file and I can't figure out why. Any ideas?

Take a look at http://import.io if you'd like a tool to handle this automatically for you.

Xandu
Feb 19, 2006


It's hard to be humble when you're as great as I am.
import.io was the first thing I tried, it's really quite cool, but I couldn't quite train it crawl the rest of the pages, though. I've been looking for an excuse to pick up some Python though, anyways.


Master_Odin posted:

code:
with open('out32.csv', 'w') as f:
Opens the file and then truncates it so you're losing data. You want to use 'a' after page one so that data gets "appended" to it, instead of overwriting the previous file writes.

Ah, this makes sense. I've got it working now, though I'm encountering some weird encoding issue when I try to pull the Arabic version of the site.

This pulls the english onto one row per row into the table.

code:
    mode = 'w' if number ==  1 else 'a'
    with open('test.csv', mode) as f:
        csvwriter = csv.writer(f)
        for row in soup.find_all('tr')[2:]:
            tds = [c.text.encode('utf-8') for c in row.find_all('td')]
            csvwriter.writerow(tds)
if I try the same in Arabic, it messes up the encoding (looks like \xd8\xae\xd9\x88\xd9\x84\xd8\xa9 \xd8\ when I save it). So I modified it to write in utf-8

code:
    mode = 'w' if number ==  1 else 'a'
    with open('test.csv', mode, encoding='utf-8') as f:
        csvwriter = csv.writer(f)
        for row in soup.find_all('tr')[2:]:
            tds = [c.text for c in row.find_all('td')]
            csvwriter.writerow(tds)
and it shows up correctly, except it's all split into 2 columns: when I save it

code:
1
		2
		3
		4
		5
		6

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to check if a variable is a file that works for both Python 2 and Python 3?

I have a method that I wanted to be able to accept either a string of a filename or a file like object (like sys.stdin) so I had the following that worked in Python 2:

code:
with open(output_filename, 'wb') if type(output_filename) is not file else output_filename as output_file:
The 'is not file' doesn't seem to work in Python 3, how should I do it?

OnceIWasAnOstrich
Jul 22, 2006

This doesn't work because open() doesn't return a file object in Python3, and in addition there are many file like objects that are not files, so you shouldn't be checking type identity. There are several options, I'm not sure what would be best. I would probably have two different kwargs, one for a filename or one for a handle. Alternatively you could simply try first and ask for forgiveness: try to open a file and try to use the object as a file handle, a file handle passed to open() should result in a TypeError, while a string won't work as a file like object. There are probably better ways I'm not thinking of.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Thanks OnceIWasAnOstrich. The different kwargs was the route I started going down but I ended up just splitting it into two methods:

code:
def do_thing_with_csv_from_file(self, input_filename, output_filename):
    with open(output_filename, 'wb') as output_file:
        with open(input_filename, 'rU') as input_file:
            return self.do_thing_with_csv(input_file, output_file)

def do_thing_with_csv(self, input_file, output_file):
    # do the thing
edit: maybe it makes more sense with the method names reversed

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Got another question now...How come Pycharm is giving me warnings with this line?

code:
from myapp.vendored.six.moves.urllib.parse import urlparse
It has moves.urllib.parse underlined with "Cannot find references 'moves' in 'six.py'" and urlparse has red squiggly lines "Unresolved reference 'urlparse'" yet everything seems to work just fine when I run it. Do I just have to ignore these IDE warnings when using six?

KICK BAMA KICK
Mar 2, 2009

fletcher posted:

It has moves.urllib.parse underlined with "Cannot find references 'moves' in 'six.py'" and urlparse has red squiggly lines "Unresolved reference 'urlparse'" yet everything seems to work just fine when I run it. Do I just have to ignore these IDE warnings when using six?
I've noticed that with some libraries too -- I remember the Voronoi class in scipy.spatial being like that. I assume it has something to do with the way the module exposes names and how PyCharm builds its skeletons. I think I tried looking at the source for libraries where that happens to see if I could spot the cause but I don't remember if I found it. I've just been ignoring it but I'm also curious if there's a way to prompt PyCharm to find it.

On that note like 90% of every name I hover over, standard library, third-party stuff, my own code, the pop-up documentation just comes back blank though the source has proper docstrings and syntax completion works, so I know it's looking at the right name. Am I doing something wrong or is that feature just weak in general?

Fergus Mac Roich
Nov 5, 2008

Soiled Meat
code:
>>> 0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17
What information am I looking up to find out why this happens? I notice it doesn't happen in C with GCC on this machine, which has an i3 M370(not sure if that's relevant).

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Fergus Mac Roich posted:

code:
>>> 0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17
What information am I looking up to find out why this happens? I notice it doesn't happen in C with GCC on this machine, which has an i3 M370(not sure if that's relevant).

https://docs.python.org/2/tutorial/floatingpoint.html

JawnV6
Jul 4, 2004

So hot ...

Fergus Mac Roich posted:

code:
>>> 0.1 + 0.1 + 0.1 - 0.3
5.551115123125783e-17
What information am I looking up to find out why this happens? I notice it doesn't happen in C with GCC on this machine, which has an i3 M370(not sure if that's relevant).

I'd be curious how you're setting it up in C to be confident in the bolded bit. Here's a python doc on it that might be enlightening, if you really want to learn all the lies that surround FP you could start here.

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

JawnV6 posted:

I'd be curious how you're setting it up in C to be confident in the bolded bit. Here's a python doc on it that might be enlightening, if you really want to learn all the lies that surround FP you could start here.

As simply as possible, with printf("%f\n", 0.1+0.1+0.1-0.3). I assume there's some gotcha I'm missing?

edit: Oh, and the link to the Python docs pretty much answered my question. I guess I'll dig into the wikipedia article too, I find it pretty interesting.

Double edit: Figured it out, printf's %f truncates it; %e shows the "correct" value. Thank you guys for being so helpful with my silly questions. One day I will be a good programmer and it will be awesome.

Fergus Mac Roich fucked around with this message at 00:57 on Feb 24, 2015

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord
If you want to reproduce the exact same result make sure you're using double-precision floats.

C code:
#include <stdio.h>

int main(void)
{
    double x = .1;
    printf("%g\n", x);
    x = x + .1;
    printf("%g\n", x);
    x = x + .1;
    printf("%g\n", x);
    x = x - .3;
    printf("%g\n", x);
    return 0;
}
This outputs:
0.1
0.2
0.3
5.55112e-17

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Fergus Mac Roich posted:

One day I will be a good programmer and it will be awesome.

Don't worry, this mythical "good programmer" doesn't exist. You'll just find that you turn from a terrible programmer into a terrible programmer who knows they're terrible.!

vikingstrike
Sep 23, 2007

whats happening, captain

Thermopyle posted:

Don't worry, this mythical "good programmer" doesn't exist. You'll just find that you turn from a terrible programmer into a terrible programmer who knows they're terrible.!

This should probably be in the OP.

EAT THE EGGS RICOLA
May 29, 2008

fletcher posted:

Got another question now...How come Pycharm is giving me warnings with this line?

It has moves.urllib.parse underlined with "Cannot find references 'moves' in 'six.py'" and urlparse has red squiggly lines "Unresolved reference 'urlparse'" yet everything seems to work just fine when I run it. Do I just have to ignore these IDE warnings when using six?

If you click on it then hover for a sec, it'll give you a little lightbulb that lets you properly install/import urlparse.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

EAT THE EGGS RICOLA posted:

If you click on it then hover for a sec, it'll give you a little lightbulb that lets you properly install/import urlparse.

No, in this case PyCharm just isn't smart enough to understand the way the six package manually adjusts the entries in sys.modules.

Master_Odin
Apr 15, 2010

My spear never misses its mark...

ladies

Xandu posted:

import.io was the first thing I tried, it's really quite cool, but I couldn't quite train it crawl the rest of the pages, though. I've been looking for an excuse to pick up some Python though, anyways.


Ah, this makes sense. I've got it working now, though I'm encountering some weird encoding issue when I try to pull the Arabic version of the site.

This pulls the english onto one row per row into the table.

code:
    mode = 'w' if number ==  1 else 'a'
    with open('test.csv', mode) as f:
        csvwriter = csv.writer(f)
        for row in soup.find_all('tr')[2:]:
            tds = [c.text.encode('utf-8') for c in row.find_all('td')]
            csvwriter.writerow(tds)
if I try the same in Arabic, it messes up the encoding (looks like \xd8\xae\xd9\x88\xd9\x84\xd8\xa9 \xd8\ when I save it). So I modified it to write in utf-8

code:
    mode = 'w' if number ==  1 else 'a'
    with open('test.csv', mode, encoding='utf-8') as f:
        csvwriter = csv.writer(f)
        for row in soup.find_all('tr')[2:]:
            tds = [c.text for c in row.find_all('td')]
            csvwriter.writerow(tds)
and it shows up correctly, except it's all split into 2 columns: when I save it

code:
1
		2
		3
		4
		5
		6
It's because the td fields contain a bunch of whitespace and stuff which doesn't actually get displayed on the HTML, but gets captured by beautifulsoup. You want to use .strip() inside your list comphrension like so:
code:
tds = [c.text.strip() for c in row.find_all('td')]
which in turn (at least for me) gives you:

1,2,3,4,5,6

Xandu
Feb 19, 2006


It's hard to be humble when you're as great as I am.
You are fantastic!

That also strips out the obnoxious /n/t/t/t that was showing up.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

fletcher posted:

Why is --no-site-packages not working? I can't figure out how six 1.8.0 is making it into my virtualenv, I didn't think I even had to specify --no-site-packages since it should be the default behavior, it doesn't seem to work either way though.

code:
[vagrant@vagrant ~]$ pip freeze
argparse==1.2.1
six==1.8.0
stevedore==1.0.0
virtualenv==1.11.6
virtualenv-clone==0.2.5
virtualenvwrapper==4.3.1
wsgiref==0.1.2

[vagrant@vagrant ~]$ mkvirtualenv test --no-site-packages
New python executable in test/bin/python
Installing setuptools, pip...done.

[vagrant@vagrant ~]$ workon test

(test)[vagrant@vagrant ~]$ which pip
~/.virtualenvs/test/bin/pip

(test)[vagrant@vagrant ~]$ pip freeze
argparse==1.2.1
six==1.8.0
stevedore==1.0.0
virtualenv==1.11.6
virtualenv-clone==0.2.5
virtualenvwrapper==4.3.1

Anybody know what was going on with this madness? The only way I could fix it was by uninstalling six from my global install.

lotor9530
Apr 29, 2009
Question about structuring loops in python:

I'm trying to make a loop that will restart at a different point depending on the outcome of checking a condition. I've tried googling, but can't seem to phrase the question right.

I've diagrammed what I mean below. In this case, A is computationally expensive, so I'm trying to avoid it by checking the condition at C and just restarting the loop from B if things are "good enough."



Any help is appreciated.

SurgicalOntologist
Jun 17, 2004

You could put a short-circuit within A:

Python code:
def A(arg):
    if is_good_enough(arg):
        return arg
    return do_expensive_stuff(arg)

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Why not set a skip flag at C, and check it at A to see whether the stuff needs doing? Just make sure it's initially false so you process A the first time around

(Which is the same basic idea as the above but with the logic in the loop itself, whichever makes most sense in your program's structure)

baka kaba fucked around with this message at 05:30 on Feb 25, 2015

Dominoes
Sep 20, 2007

SurgicalOntologist posted:

You could put a short-circuit within A:

Python code:
def A(arg):
    if is_good_enough(arg):
        return arg
    return do_expensive_stuff(arg)
I'd guess something like this to. Post an example of what you're trying to do.

QuarkJets
Sep 8, 2008

I've been using the community version of PyCharm on my laptop for awhile now, and I love it but I don't think that I have a solid understanding of what advantages are offered by a Professional license. Is it basically only useful if you're doing webapp development? I've looked at the editions comparison page, but I don't understand what most of this stuff is (jinja2, pyramid, appengine? These are not things that I've ever used. I've at least heard of django and flask, in passing, but I don't use those either)

The one thing that I am familiar with that's on the Pro list is SQL support. I have noticed that the community edition isn't checking SQL statements, so that basically comes with Pro? Are there any other significant advantages that I'm missing? Am I hamstringing myself and not realizing it? All of my work is just tinkering around, so I'm not worried about the lack of a commercial license, but I would like to support JetBrains if there's a tangible advantage to the professional license

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

QuarkJets posted:

I've been using the community version of PyCharm on my laptop for awhile now, and I love it but I don't think that I have a solid understanding of what advantages are offered by a Professional license. Is it basically only useful if you're doing webapp development? I've looked at the editions comparison page, but I don't understand what most of this stuff is (jinja2, pyramid, appengine? These are not things that I've ever used. I've at least heard of django and flask, in passing, but I don't use those either)

The one thing that I am familiar with that's on the Pro list is SQL support. I have noticed that the community edition isn't checking SQL statements, so that basically comes with Pro? Are there any other significant advantages that I'm missing? Am I hamstringing myself and not realizing it? All of my work is just tinkering around, so I'm not worried about the lack of a commercial license, but I would like to support JetBrains if there's a tangible advantage to the professional license

Yup I think the real benefits of the pro version are when you are doing webapp development. That's when support for all those web frameworks and CSS preprocessors and such really shine.

Another thing I really like with the pro version of PyCharm is being able to run tests with code coverage reports. For $99 it's a no-brainer for me. If you are just tinkering around and not doing webapp stuff with those frameworks, I'd say community edition is probably fine for you.

Nippashish
Nov 2, 2005

Let me see you dance!

QuarkJets posted:

I've been using the community version of PyCharm on my laptop for awhile now, and I love it but I don't think that I have a solid understanding of what advantages are offered by a Professional license. Is it basically only useful if you're doing webapp development? I've looked at the editions comparison page, but I don't understand what most of this stuff is (jinja2, pyramid, appengine? These are not things that I've ever used. I've at least heard of django and flask, in passing, but I don't use those either)

For me the killer pro feature is the remote interpreter / debugger. It lets you have a setup that feels like you're doing local development on your laptop but really everything is being executed on your big beefy cloud server.

Fergus Mac Roich
Nov 5, 2008

Soiled Meat
So I'm starting to build python apps that, while still pretty small in scope(single-threaded, totally local, etc), are big enough to warrant multiple classes and the like. I'm still a beginner and my learning background is in C, so I don't really have a good grasp of object oriented programming. I understand, on a basic level, the ideas behind encapsulation, inheritance, and polymorphism, but what I'm struggling with is how to put it all together and create a program with a really good, idiomatic structure. I'm looking for Python-specific tips, concepts, or hopefully reading material on how to master this aspect of programming.

Here's an example of a challenge I'm facing with a small program.

I'm writing an application that more or less acts as a leaderboard/record for performance in a board game(I have a group that meets once weekly). I've got some idea of how I want to structure my data in terms of classes. I have a player class that contains a name and methods that take a dictionary of games(keyed with a date object that's also a member of each game object). It also has __hash__ and _eq__ methods. I have a game class that contains said date object, and also a dictionary of player objects as keys with their respective scores as values. Game objects can also tell you who won them, and maybe some other things if I can think of some cool stuff to throw in there. I'm fine up to that point; there's almost definitely ways to improve upon this arrangement, but I think I can figure them out on my own.

My issue is that, to manage it all, I've essentially created a class of which there is only ever one instance that manages dictionaries* of all the games we've played and all the players who have played by prompting the user for commands and then either returning or inserting the appropriate data. I'm concerned that in doing this, I've created a "God" class that's as bad as just a global state. Is this the violation of OOP that I perceive it to be? If so, how do I overcome it? I can't figure out what kind of structure I need to come up with that can avoid a class that sees and manages all the data.

*I will probably change the top-level dictionaries to shelves for persistence.

Fergus Mac Roich fucked around with this message at 02:05 on Feb 26, 2015

Dominoes
Sep 20, 2007

It sounds like you should use a database ORM like SQLalchemy.

I'm not sure what your God class looks like, but abstract wrapper classes are common in OOP. More common in Java than Python. I personally don't use them.

Post example code.

Don't try to make everything a class.

Dominoes fucked around with this message at 02:19 on Feb 26, 2015

EAT THE EGGS RICOLA
May 29, 2008

Nippashish posted:

For me the killer pro feature is the remote interpreter / debugger. It lets you have a setup that feels like you're doing local development on your laptop but really everything is being executed on your big beefy cloud server.

The pro features I use the most are the Remote interpreter/debugger, the REST client, SQLAlchemy support, VM Support (full Vagrant integration), and Database stuff.

And also the new Jinja2 stuff, but you're not using that at all.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

EAT THE EGGS RICOLA posted:

The pro features I use the most are the Remote interpreter/debugger, the REST client, SQLAlchemy support, VM Support (full Vagrant integration), and Database stuff.

And also the new Jinja2 stuff, but you're not using that at all.

I always forget about the REST client. I've never used it but come across it in the online help or wherever from time to time and think "I should try that out".

I should try that out.

billy cuts
Aug 14, 2003

wrists of fury
Buglord
If you're a college student or faculty member, you can get a free academic license for PyCharm Professional Edition and save $99 by just filling out this form - https://www.jetbrains.com/eforms/academicRequest.action?licenseRequest=PCP02NS

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
How do I set a cookie in a requests session?

edit: Ah!

code:
session = requests.Session()
self.session.cookies = cookiejar_from_dict({'name': 'value'})

fletcher fucked around with this message at 19:20 on Feb 26, 2015

Hughmoris
Apr 21, 2007
Let's go to the abyss!
I'm trying to make me program easier for my users and am a bit stumped on something.

We have an account number that ends in a Julian date. For instance: 22365003. I need to key off of the last four numbers, the "5003". The "5" is for 2015, and the "003" is the third day of the year. So the date associated with this account number is 01/03/2015.

With an account number of 436114028, I'd like to know that the associated date is 01/28/2014.

Any ideas on how to convert the last four numbers to a date format of MM/DD/YYYY?

Adbot
ADBOT LOVES YOU

KICK BAMA KICK
Mar 2, 2009

Hughmoris posted:

Any ideas on how to convert the last four numbers to a date format of MM/DD/YYYY?

Python code:
import datetime as dt

def acct_to_date(acct_no):
    """
    acct_no: str
    return: datetime.date
    """
    last_four = acct_no[-4:]
    year_offset, day_offset = int(last_four[0]), int(last_four[1:]) - 1
    date = dt.date(2010 + year_offset, 1, 1) + dt.timedelta(days=day_offset)
    return date
That's a basic idea; you can futz the input and output into whatever format you like and you'd definitely want to add some sanity checks.

  • Locked thread