text
stringlengths 226
34.5k
|
---|
NLTK was unable to find stanford-postagger.jar! Set the CLASSPATH environment variable
Question: I am working on a project that requires me to tag tokens using nltk and
python. So I wanted to use this. But came up with a few problems. I went
through a lot of other already asked questions and other forums but I was
still unable to get a soultion to this problem. The problem is when I try to
execute the following:
* * *
`from nltk.tag import StanfordPOSTagger st = StanfordPOSTagger('english-
bidirectional-distsim.tagger')`
* * *
I get the following:
* * *
Traceback (most recent call last):
`File "<pyshell#13>", line 1, in <module> st = StanfordPOSTagger('english-
bidirectional-distsim.tagger')`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-
packages\nltk-3.1-py3.5.egg\nltk\tag\stanford.py", line 131, in __init__
super(StanfordPOSTagger, self).__init__(*args, **kwargs)`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-
packages\nltk-3.1-py3.5.egg\nltk\tag\stanford.py", line 53, in __init__
verbose=verbose)`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-
packages\nltk-3.1-py3.5.egg\nltk\internals.py", line 652, in find_jar
searchpath, url, verbose, is_regex))`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-
packages\nltk-3.1-py3.5.egg\nltk\internals.py", line 647, in find_jar_iter
raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))`
LookupError:
===========================================================================
NLTK was unable to find stanford-postagger.jar! Set the CLASSPATH environment
variable.
==============================
I already set the CLASSPATH - `C:\Users\MY3\Desktop\nltk\stanford\stanford-
postagger.jar` I tried it as `C:\Users\MY3\Desktop\nltk\stanford` as well..
STANFORD_MODELS - `C:\Users\MY3\Desktop\nltk\stanford\models\`
I tried doing this as well..in vain `File "C:\Python27\lib\site-
packages\nltk\tag\stanford.py", line 45, in __init__
env_vars=('STANFORD_MODELS',), verbose=verbose)` but it doesn't solve the
problem either. Please Help me in solving this issue.
I use Windows 8, python 3.5 and nltk 3.1
Oh btw please excuse few mistakes..I'm new to stackoverflow :)
Answer: I had the same problem (but using OS X and PyCharm), finally got it to work.
Here's what I've pieced together from the [StanfordPOSTagger
Documentation](http://www.nltk.org/api/nltk.tag.html#nltk.tag.stanford.StanfordPOSTagger)
and [alvas' work on the
issue](https://gist.github.com/alvations/e1df0ba227e542955a8a) (big thanks!):
from nltk.internals import find_jars_within_path
from nltk.tag import StanfordPOSTagger
from nltk import word_tokenize
# Alternatively to setting the CLASSPATH add the jar and model via their path:
jar = '/Users/nischi/PycharmProjects/stanford-postagger-full-2015-12-09/stanford-postagger.jar'
model = '/Users/nischi/PycharmProjects/stanford-postagger-full-2015-12-09/models/english-left3words-distsim.tagger'
tagger = StanfordPOSTagger(model, jar)
# Add other jars from Stanford directory
stanford_dir = pos_tagger._stanford_jar.rpartition('/')[0]
stanford_jars = find_jars_within_path(stanford_dir)
pos_tagger._stanford_jar = ':'.join(stanford_jars)
text = tagger.tag(word_tokenize("What's the airspeed of an unladen swallow ?"))
print(text)
Hope this helps.
|
Floating point decimals in python
Question: I have a python script within which I define a variable called `dt` and
initialize it as such: `dt=0.30`. For some specific reason, I have had to
convert my python script into a C++ program, but the two programs are written
to produce the exact same results. The problem is that the results start to
deviate at some point. I believe the problem occurs due to the fact that 0.03
does not have an exact representation in binary floating point in python;
whereas in C++ `dt=0.30` gives 0.300000000000, the python output to my file
gives `dt=0.300000011921`.
What I really need is a way to force `dt=0.30` precisely in python, so that I
can then compare my python results with my C++ code, for I believe the
difference between them is simply in this small difference, which over runs
builds up to a substantial difference. I have therefore looked into the
`decimal` arithmetic in python by calling `from decimal import *`, but I then
cannot multiply `dt` by any floating point number (which I need to do for the
calculations in the code). Does anyone know of a simple way of forcing dt to
exactly 0.30 without using the 'decimal floating point' environment?
Answer: I do not have your context, but try this:
$ python
> from decimal import Decimal
> dt = Decimal('0.30')
> sum = Decimal(0)
> for _ in range(1000000000): sum += dt
> sum
Decimal('30000000.00')
Note that `Decimal` is called with a _string_.
Check for instance the difference:
> Decimal(0.30)
Decimal('0.299999999999999988897769753748434595763683319091796875')
> Decimal('0.30')
Decimal('0.30')
|
SoftLayer API Hardware Order Options Specification
Question: I am trying to order a couple of very specific node types, and am wondering
how it would be possible to do this via the SoftLayer API. When running the
command slcli server create-options or call the get_create_options() function
in the Python API, I do not receive a full list of available hardware,
operating systems, network controller options (mostly due to not having
redundant options), and subnet types. In other words, the choices in the API
do not match up with the choices in the SoftLayer web portal. The nodes that I
would want to hypothetically order are specified below.
Chassis: 4U
CPU: 4*E7-4850 v2 (12-core HT, 2.30 GHz)
RAM: 256GB
HDD: 2*1TB SATA RAID 1 (Boot); 8*600GB SAS RAID 10 (Ephemeral) (10 total)
NIC: 2*10Gbps
OS: Ubuntu 14.04 LTS Minimal Install
Chassis: 2U
CPU: 2*E5-2650 v3 (10-core HT, 2.30 GHz)
RAM: 64 GB
HDD: 2*1TB SATA RAID 1 (Boot); 6*600GB SAS RAID 10 (Data) (8 total)
NIC: 2*10 Gbps
OS: Ubuntu 14.04 LTS Minimal Install
Chassis: 2U
CPU: 2*E5-2690 v3 (12-core HT, 2.60 GHz)
RAM: 128GB
HDD: 2*1TB SATA RAID 1 (Boot); 4*600GB SAS RAID 10 (Ephemeral) (6 total)
NIC: 2*1 Gbps
OS: Ubuntu 14.04 LTS Minimal Install
Is there any documentation for the full hardware ordering options? Any help is
greatly appreciated.
Answer: The slcli only displays the “FAST SERVERS”, these servers have a preset
configuration which makes the provisioning process easy and fast. You can see
more information about the preset configuration in bare metal servers here:
<http://sldn.softlayer.com/blog/bpotter/ordering-bare-metal-servers-using-
softlayer-api> So using the scli, currently, it is not possible to order all
the bare metal server flavors like the SL Portal. But that task is possible
using API calls, for that you need to call the palceOrder() method (which is
the same method that the SL portal uses). Please see this documentation about
how to order devices using the API:
<http://sldn.softlayer.com/es/blog/bpotter/Going-Further-SoftLayer-API-Python-
Client-Part-3> Take a look at this code to order bare metal servers using the
placeOrder method.
"""
Order a new server.
Build a SoftLayer_Container_Product_Order object for a new
server order and pass it to the SoftLayer_Product_Order API service to order
it. In this care we'll order a Xeon 3460 server with 2G RAM, 100mbit NICs,
2000GB bandwidth, a 500G SATA drive, CentOS 5 32-bit, and default server
order options. See below for more details.
Important manual pages:
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Hardware_Server
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <[email protected]>
"""
import SoftLayer
# Your SoftLayer API username and key.
USERNAME = 'set me'
API_KEY = 'set me'
# The number of servers you wish to order in this configuration.
quantity = 1
"""
Where you'd like your new server provisioned.
This can either be the id of the datacenter you wish your new server to be
provisioned in or the string.
Location id 3 = Dallas
Location id 18171 = Seattle
Location id 37473 = Washington, D.C.
"""
location = 'AMSTERDAM'
"""
The id of the SoftLayer_Product_Package you wish to order.
In this case the Intel Xeon 3460's package id is 145.
"""
packageId = 146
"""
Build a skeleton SoftLayer_Hardware_Server object to model the hostname and
domain we want for our server. If you set quantity greater then 1 then you
need to define one hostname/domain pair per server you wish to order.
"""
hardware = [
{
'hostname': 'test', # The hostname of the server you wish to order.
'domain': 'example.org' # The domain name of the server you wish to order.
}
]
"""
Build a skeleton SoftLayer_Product_Item_Price objects. These objects contain
much more than ids, but SoftLayer's ordering system only needs the price's id
to know what you want to order.
Every item in SoftLayer's product catalog is assigned an id. Use these ids
to tell the SoftLayer API which options you want in your new server. Use
the getActivePackages() method in the SoftLayer_Account API service to get
a list of available item and price options per available package.
"""
prices = [
{'id': 17232}, # Single Processor Quad Core Xeon 3460 - 2.80GHz (Lynnfield) - 1 x 8MB cache w/HT
{'id': 637}, # 2 GB DDR2 667
{'id': 682}, # CentOS 5.x (32 bit)
{'id': 876}, # 2 GB DDR2 667
{'id': 20}, # 500GB SATA II
{'id': 342}, # 20000 GB Bandwidth
{'id': 273}, # 100 Mbps Public & Private Network Uplinks
{'id': 55}, # Host Ping
{'id': 58}, # Automated Notification
{'id': 420}, # Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': 418}, # Nessus Vulnerability Assessment & Reporting
{'id': 21}, # 1 IP Address
{'id': 57}, # Email and Ticket
{'id': 906} # Reboot / KVM over IP
]
"""
Build a skeleton SoftLayer_Container_Product_Order_Hardware_Server object
containing the order you wish to place.
"""
orderTemplate = {
'quantity': quantity,
'location': location,
'packageId': packageId,
'prices': prices,
'hardware': hardware
}
# Create a SoftLayer API client object
client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)
try:
"""
verifyOrder() will check your order for errors. Replace this with a call
to placeOrder() when you're ready to order. Both calls return a receipt
object that you can use for your records.
Once your order is placed it'll go through SoftLayer's approval and
provisioning process. When it's done you'll have a new
SoftLayer_Hardware_Server object and server ready to use.
"""
receipt = client['Product_Order'].verifyOrder(orderTemplate)
print(receipt)
except SoftLayer.SoftLayerAPIError as e:
print("Unable to place a server order faultCode=%s, faultString=%s"
% (e.faultCode, e.faultString))
exit(1)
And also see this example which returns all the available servers to order:
"""
List all the servers to order.
Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package_Server/getAllObjects
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Package_Server/
http://sldn.softlayer.com/article/Object-Filters
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <[email protected]>
"""
import SoftLayer
import json
USERNAME = 'set me'
API_KEY = 'set me'
client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)
packageService = client['SoftLayer_Product_Package_Server']
objectFilter = {"packageType": {"operation": "in", "options": [{"name": "data", "value": ["BARE_METAL_CORE", "BARE_METAL_CPU", "BARE_METAL_CPU_FAST_PROVISION"]}]}}
try:
servers = packageService.getAllObjects(filter=objectFilter)
print(json.dumps(servers, sort_keys=True, indent=2, separators=(',', ': ')))
except SoftLayer.SoftLayerAPIError as e:
print("Unable to list the servers to order. faultCode=%s, faultString=%s" % (e.faultCode, e.faultString
|
Why does Python allow instance variables to be added after initialization?
Question:
class MyClass(object):
class_var = []
def __init__(self, i_var):
self.i_var = i_var
a = MyClass(2)
a.hit = 1
print a.hit
As we can see, `hit` is added to `a` as an instance variable after
initialization. What's a good reason to allow defining instance variable in
such a way? And, is it dangerous?
Answer: > What's a good reason to allow defining instance variable in such a way?
I think it's important to note that `self` inside your `__init__` function is
exactly the same as `self` in any other method on that instance. It's also the
same as `a` outside the class. The magic of the `__init__` method lies in
_when_ it gets called and nothing else (which is true of _all_ python magic
methods). To have `__init__` "freeze" the object in one way or another would
go against the way things have always been done in python.
So, I would say that the "good reason" is because it makes things very
consistent.
> And, is it dangerous?
Yes. It can be.
The practice of _intentionally_ adding methods/attributes to an instance is
known as Monkey Patching (also occasionally called Duck Punching)1 \-- And it
really shouldn't be done unless you don't have any other options.
The practice of _unintentionally_ adding methods/attributes to an instance is
known as creating bugs (and we've all done it :-).
Fortunately, there are tools to help you prevent these types of bugs. Linters
are the most common. I personally use `pylint` to help warn me about these
sorts of bugs.
Between the linter and using common sense (see above about not Monkey
Patching), I've very rarely been hit with a hard-to-track bug because of this
part of python's ideology.
1I suppose that it isn't duck punching if you add more attributes in a later
instance method -- But you probably shouldn't be doing that either . . .
|
Returning 5 best cards containing a pair from a set of 7 playing cards using Python
Question: I'm currently trying to use Python's Enum module on Python 2.7 to identify
pair of cards from a hand of 7
import collections
import operator
import enum
Card = collections.namedtuple("Card", "rank suit")
#in the below hand there is a pair of fours.
hand = [
Card(rank=<Ranks.four: 3>, suit=<Suits.spades: 1>),
Card(rank=<Ranks.nine: 8>, suit=<Suits.clubs: 3>),
Card(rank=<Ranks.ten: 9>, suit=<Suits.spades: 1>),
Card(rank=<Ranks.jack: 10>, suit=<Suits.diamonds: 4>),
Card(rank=<Ranks.six: 5>, suit=<Suits.hearts: 2>),
Card(rank=<Ranks.four: 3>, suit=<Suits.diamonds: 4>),
Card(rank=<Ranks.two: 1>, suit=<Suits.clubs: 3>),
]
#My function
def is_pair():
#count duplicate-numbers in `hand`
ranks = collections.Counter(map(operator.attrgetter("rank"), hand))
pair_card=[]
if len(ranks) == 6:
# get most common if there are individual counts
# (so one is duplicated and not counted)
pair_card = ranks.most_common(1)[0]6
for i in hand:
print i
print pair_card
print type(pair_card)
The above code will recognize a pair but I want it to return the 5 best cards,
which would be the pair of cards plus the three highest (as per the rules of
Poker). So my question is how can I get the above function to return any pair
from any 7 cards, along with the other three highest cards?
So in this case, the desired output is:
output = [
Card(rank=<Ranks.four: 3>, suit=<Suits.spades: 1>),
Card(rank=<Ranks.nine: 8>, suit=<Suits.clubs: 3>),
Card(rank=<Ranks.ten: 9>, suit=<Suits.spades: 1>),
Card(rank=<Ranks.jack: 10>, suit=<Suits.diamonds: 4>),
Card(rank=<Ranks.four: 3>, suit=<Suits.diamonds: 4>),
]
That's to say, removal of the 2 of clubs and 6 of hearts.
Answer: Is your Rank enum also a subclass of `int`?
If so, just order the remainng cards and take the last three.
If not, add ordering:
def __lt__(self, other):
if not isinstance(other, Rank): # or self.__class__ instead of Rank
return NotImplemented
return self.value < other.value
|
Proper way to run a PyCharm project
Question: This is a seemingly simple problem but it proves to be harder than expected.
I've created a project in pycharm in the following layout
bin
main
helpers
userhelper
models
user
session
tests
userTest
in my main I run the code that calls everything and this works like a charm in
pycharm. Now I want to run this on a server and start it with cron. How do I
start this from cron while keeping all the module references in place?
I guess I need to add the root of my project to the python path. To do this I
added the following bash script to invoke my project with:
PYTHONPATH="${PYTHONPATH}:/home/steven/projectX"
export PYTHONPATH
python bin/main.py
But this does not seem to do anything, what would be the best way to
periodically run the bin/main.py within this project and have all my modules
and things like
'ConfigParser.RawConfigParser().read(os.path.abspath("../configuration.cfg"))'
in place relative to my project?
EDIT: I am not trying to fix my imports or debugging my code, I have a large
project in pycharm that runs a simulation that I want to invoke on the server
an maintain within my development setup. The question is how do I run this in
the same way pycharm does?
Answer: It sounds like you're interested in making a distributable Python package. You
should read through the tutorial [here](https://python-packaging-user-
guide.readthedocs.org/en/latest/distributing/). Ultimately, you're going to
want to write a setup.py (sure you could call it something else, but it's like
renaming `self` \-- why do it?) that will configure your project. Now a word
of advice since I've seen many people go down a wrong path here. You NEVER
want to modify your PYTHONPATH directly. It might be the quickest solution to
get something up and working, but it WILL cause lasting problems.
|
Writing output csv file python
Question: I'm trying to write a list into a csv file so that it's properly formatted.
I've read from other stack overflow posts that below is the correct way to do
so, (in order to preserve commas that I want to be printed out, etc), but this
is just not working for me.
Rather than printing every list (within `final_list`) in its own csv row, it
just prints one list per cell in one long, continuous line aka no line breaks.
Any ideas on what I can do?
import csv
final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']
for key, value in sorted(stats_dict.iteritems()):
if value[5] != 0:
final_list.append([key, value[4], value[5], value[0], value[1]])
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerow(final_list)
Answer: You need to split your data into headers and then the rows (of data).
header = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']
final_list = []
for key, value in sorted(stats_dict.iteritems()):
if value[5] != 0:
final_list.append([key, value[4], value[5], value[0], value[1]])
with open('output.csv', 'wb') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(header)
writer.writerows(final_list) # note .writerows
# f.close() - not needed, the with statement closes the file for you
|
How to compare two .sql files in python?
Question: I would like to compare the *.sql files in python and capture the difference
in a new file (.sql file)
Are there any packages in python which helps in performing the below tasks.
For example:
### file_1.sql
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
### file_2.sql
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Salary int,
JobDetail int
);
Expected Output file ->
### diff.sql
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255),
**Salary int,
JobDetail int**
);
Answer: You can use [difflib](https://docs.python.org/2/library/difflib.html) python
module for this:
from difflib import Differ
from pprint import pprint
d = Differ()
result = list(d.compare(open('1.sql', 'r').readlines(), open('2.sql', 'r').readlines()))
pprint(result)
|
Download a file from GoogleDrive exportlinks
Question: Trying to download a file directly using Python and the Google Drive API
exportlinks response.
1. Suppose I have an export link like this:
a)
[https://docs.google.com/feeds/download/documents/export/Export?id=xxxx&exportFormat=docx](https://docs.google.com/feeds/download/documents/export/Export?id=xxxx&exportFormat=docx)
2. To download this file, I simply paste it into the browser, and the file automatically downloads to my Downloads folder.
3. How do I do the same thing in Python?
EX:
module.download_file_using_url([https://docs.google.com/feeds/download/documents/export/Export?id=xxxx&exportFormat=docx](https://docs.google.com/feeds/download/documents/export/Export?id=xxxx&exportFormat=docx))
Answer: This is a repost of [How do I download a file over HTTP using
Python?](http://stackoverflow.com/questions/22676/how-do-i-download-a-file-
over-http-using-python)
In Python 2, use urllib2 which comes with the standard library.
import urllib2 response = urllib2.urlopen('<http://www.example.com/>') html =
response.read()
This is the most basic way to use the library, minus any error handling. You
can also do more complex stuff such as changing headers. The documentation can
be found [here](https://docs.python.org/2/library/urllib2.html).
|
How to save a plot in Seaborn with Python
Question: I have a Pandas dataframe and try to save a plot in a png file. However, it
seems that something doesn't work as it should. This is my code:
import pandas
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='ticks')
df = pandas.read_csv("this_is_my_csv_file.csv")
plot = sns.distplot(df[['my_column_to_plot']])
plot.savefig("myfig.png")
And I have this error:
AttributeError: 'AxesSubplot' object has no attribute 'savefig'
Answer: You could save any seaboard figure like this.
Suppose If you want to create a violin plot to show the salary distribution
gender wise. You could do it like this and will save it using the get_figure
method.
ax = sns.violinplot(x="Gender", y="Salary", hue="Degree", data=job_data)
#Returns the :class:~matplotlib.figure.Figure instance the artist belongs to
fig = ax.get_figure()
fig.savefig('gender_salary.png')
|
IOError: [Errno 13] Permission denied How do I fix this?
Question: Iam newbie to python and keep on getting this error when run this script, I
have given full permission to the file.
Traceback (most recent call last):
File "/usr/local/bin/ftp_site.py", line 3, in <module>
import anprint
File "/usr/local/bin/anprint.py", line 17, in <module>
hdlr = logging.FileHandler(LOG_FILENAME)
File "/usr/lib/python2.7/logging/__init__.py", line 897, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python2.7/logging/__init__.py", line 916, in _open
stream = open(self.baseFilename, self.mode)
IOError: [Errno 13] Permission denied: '/tmp/anpr_log'
I have recently upgraded from MYSQL to mariadb.
Script : anprint.py
def all_in_cam_ids_by_site_id(self,site_id):
ret_list =[]
sql = """SELECT .......WHERE carparks.id = "%s" AND in_out = 1 """ % site_id
ret_val = self.cursor.execute(sql)
if (ret_val > 0):
ret_array = self.cursor.fetchall()
for retId in ret_array:
ret_list.append(retId[0])
else:
logging.error("No Cameras for Site id %s", site_id)
return ret_list
Answer: Script has no permission to write into log file. Changing `chmod` of
`tmp/anpr_log` should fix your issue:
sudo chmod +rw /tmp/anpr_log
|
Python/Selenium: Whitespace issue when retrieving text content from XPath (normalize-space)
Question: I am having some difficulties with a relative `XPath` web scraper
implementation with `Selenium` for `Python`.
From this [Börse Frankfurt web page](http://www.boerse-frankfurt.de/etp/db-x-
trackers-STOXX-GLOBAL-SELECT-DIVIDEND-100-UCITS-ETF-1D-LU0292096186), I want
to get the text in the cell adjacent to `<td> UCITS IV-Konform </td>`, namely
the text in the cell that says `<td class="text-right"> Ja </td>`.
I have tested the XPath I'm using with
[Freeformatter](http://www.freeformatter.com/xpath-tester.html#ad-output)
which states that my XPath is correct.
Navigation to the page works fine. However, when I try to retrieve the text
content, I get `None`. Apparently, it's not finding the XPath.
**Post-answer edit** : The issue is due to _whitespace_ leading/trailing the
text content.
* * *
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox()
driver.get("http://www.boerse-frankfurt.de/etp/db-x-trackers-STOXX-GLOBAL-SELECT-DIVIDEND-100-UCITS-ETF-1D-LU0292096186")
try:
find_value = driver.find_element_by_xpath("//td[text()=' UCITS IV-Konform ']/following-sibling::td").text
except NoSuchElementException:
find_value = None
print find_value
Answer: Try the XPath `"//td[normalize-space(.) = 'UCITS IV-Konform']/following-
sibling::td"` as I think there is a lot of leading and trailing white space in
that cell.
|
Python Tkinter error object has no attribute
Question: So I am making a program similar to the arcade games. I want the lableGuess to
appear in the toplevel window after clicking the frame but it gives me this
error:
AttributeError: 'Window' object has no attribute 'window'
Here's the code:
from tkinter import *
from tkinter import font
import time
class Window(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
master.title("Arcade Games")
master.geometry("800x600+560+240")
b = Button(self, text="Guess the number", command=self.new_window)
b.pack(side="top")
self.customFont = font.Font(master, font="Heraldica", size=12)
self.guess_number()
def new_window(self):
id = "Welcome to the 'Guess your number' game!\nAll you need to do is follow the steps\nand I will guess your number!\n\nClick anywhere to start!"
self.window = Toplevel(self.master)
frame = Frame(self.window)
frame.bind("<Button-1>", self.guess_number)
frame.pack()
self.window.title("Guess the number")
self.window.geometry("400x300+710+390")
label = Label(self.window, text=id, font=self.customFont)
label.pack(side="top", fill="both", padx=20, pady=20)
def guess_number(self):
labelGuess = Label(self.window, text="Pick a number between 1 and 10", font=self.customFont)
time.sleep(2)
labelGuess.pack(fill=BOTH, padx=20, pady=20)
if __name__ == "__main__":
root = Tk()
view = Window(root)
view.pack(side="top", fill="both", expand=True)
root.mainloop()
Answer: Your initial call to `guess_number` in your initializer method is probably
being invoked before you press the button and trigger the `new_window` event
callback. In `guess_number` you're trying to pass `self.window` as an argument
to `Label()` but it would be undefined at that time.
|
How subtotal rounding works in quotation for Odoo 8?
Question: I face an inconsistent Subtotal rounding in Quotation. The quotation comes
from external data (via import menu). My current Odoo version is 8.
I have quantity 60 with 6 decimal precision and Unit Price 90.075600 with also
6 decimal precision (which is already defined in Settings > Database Structure
> Decimal Accuracy > Product Price, Account, Product Unit of Measure, Product
UoS all set to 6). But the subtotal result shows 5404.54 (it's supposed to be
5404.536).
How subtotal rounding works in Quotation?
If I need to change the python code, which part/file I have to change?
Thank you.
[odoo subtotal quotation rounding example
pic](http://i.stack.imgur.com/WIVlI.png)
Answer: Working on .v8:
First.
Subtotal field responds for decimal precision to 'Account', not 'Price Unit'.
price_subtotal = fields.Float(string='Amount', digits= dp.get_precision('Account'),
store=True, readonly=True, compute='_compute_price')
Second.
Even giving 6 decimal precision in 'Database Structure' you get 2 decimal
precision for 'price_subtotal', because you have only separated 6 spaces but
have not for rounding, to have a rounding factor of 6 decimal, you need to
change the 'Rounding factor', them go to the currency of your company,
'Invoicing>Configuration>Miscellaneous>Currencies' and select the currency of
your company, then update the 'Rounding Factor' field putting '0.000001' for 6
decimal precision in rounding factor.
Making these changes, it should work perfectly, I hope this can be helpful for
you.
|
Python - unichr() - 'charmap' codec can't encode character
Question: I would like to ask you for help. I have to decode unicode decimal to chars,
but I am not decoding only clasisc letters, I am decoding special characters
like: ؋,лв and some more ¥ and it doesn't work - it says : 'charmap' codec
can't encode character. Can you help me?
I have to work with all symbols of currency from this page:
<http://www.xe.com/symbols.php>, thank you.
Edit: For example I need to get from decimal number 1547 symbol "؋".
Answer: It helps to provide an example like the following. This makes it clear about
the operating environment (OS and Python version):
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(unichr(1547))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u060b' in position 0: character maps to <undefined>
The problem is not with conversion, but with printing. In the above case, the
Windows console is using `cp437` encoding, and that doesn't support the
character being printed.
The conversion works correctly, `c` contains a Unicode character, and it is
the `AFGHANI SIGN`.
>>> c = unichr(1547)
>>> c
u'\u060b'
>>> import unicodedata as ud
>>> ud.name(c)
'AFGHANI SIGN'
If you want it to print correctly, one way is to use an IDE `PythonWin` from
the `pywin32` extensions that supports UTF-8 encoded output:
PythonWin 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> unichr(1547)
u'\u060b'
>>> print(unichr(1547))
؋
Another is to write the output to a UTF-8-encoded file, and open the result in
Notepad:
with io.open('out.txt','w',encoding='utf8') as f:
f.write(unichr(1547)+unichr(402)+unichr(165))
Output file:
؋ƒ¥
|
Read a python variable in a shell script?
Question: my python file has these 2 variables:
week_date = "01/03/16-01/09/16"
cust_id = "12345"
how can i read this into a shell script that takes in these 2 variables?
my current shell script requires manual editing of "dt" and "id". I want to
read the python variables into the shell script so i can just edit my python
parameter file and not so many files.
shell file:
#!/bin/sh
dt="01/03/16-01/09/16"
cust_id="12345"
In a new python file i could just import the parameter python file.
Answer: Consider something akin to the following:
#!/bin/bash
# ^^^^ NOT /bin/sh, which doesn't have process substitution available.
python_script='
import sys
d = {} # create a context for variables
exec(open(sys.argv[1], "r").read()) in d # execute the Python code in that context
for k in sys.argv[2:]:
print "%s\0" % str(d[k]).split("\0")[0] # ...and extract your strings NUL-delimited
'
read_python_vars() {
local python_file=$1; shift
local varname
for varname; do
IFS= read -r -d '' "${varname#*:}"
done < <(python -c "$python_script" "$python_file" "${@%%:*}")
}
You might then use this as:
read_python_vars config.py week_date:dt cust_id:id
echo "Customer id is $id; date range is $dt"
...or, if you didn't want to rename the variables as they were read, simply:
read_python_vars config.py week_date cust_id
echo "Customer id is $cust_id; date range is $week_date"
* * *
Advantages:
* Unlike a naive regex-based solution (which would have trouble with some of the details of Python parsing -- try teaching `sed` to handle both raw and regular strings, and both single and triple quotes without making it into a hairball!) or a similar approach that used newline-delimited output from the Python subprocess, this will correctly handle any object for which `str()` gives a representation with no NUL characters that your shell script can use.
* Running content through the Python interpreter also means you can determine values programmatically -- for instance, you could have some Python code that asks your version control system for the last-change-date of relevant content.
Think about scenarios such as this one:
start_date = '01/03/16'
end_date = '01/09/16'
week_date = '%s-%s' % (start_date, end_date)
...using a Python interpreter to parse Python means you aren't restricting how
people can update/modify your Python config file in the future.
Now, let's talk caveats:
* If your Python code has side effects, those side effects will obviously take effect (just as they would if you chose to `import` the file as a module in Python). Don't use this to extract configuration from a file whose contents you don't trust.
* Python strings are Pascal-style: They can contain literal NULs. Strings in shell languages are C-style: They're terminated by the first NUL character. Thus, some variables can exist in Python than cannot be represented in shell without nonliteral escaping. To prevent an object whose `str()` representation contains NULs from spilling forward into other assignments, this code terminates strings at their first NUL.
* * *
Now, let's talk about implementation details.
* `${@%%:*}` is an expansion of `$@` which trims all content after and including the first `:` in each argument, thus passing only the Python variable names to the interpreter. Similarly, `${varname#*:}` is an expansion which trims everything up to and including the first `:` from the variable name passed to `read`. See [the bash-hackers page on parameter expansion](http://wiki.bash-hackers.org/syntax/pe).
* Using `<(python ...)` is process substitution syntax: The `<(...)` expression evaluates to a filename which, when read, will provide output of that command. Using `< <(...)` redirects output from that file, and thus that command (the first `<` is a redirection, whereas the second is part of the `<(` token that starts a process substitution). Using this form to get output into a `while read` loop avoids the bug mentioned in [BashFAQ #24 ("I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?")](http://mywiki.wooledge.org/BashFAQ/024).
* The `IFS= read -r -d ''` construct has a series of components, each of which makes the behavior of `read` more true to the original content:
* Clearing `IFS` for the duration of the command prevents whitespace from being trimmed from the end of the variable's content.
* Using `-r` prevents literal backslashes from being consumed by `read` itself rather than represented in the output.
* Using `-d ''` sets the first character of the empty string `''` to be the record delimiter. Since C strings are NUL-terminated and the shell uses C strings, that character is a NUL. This ensures that variables' content can contain any non-NUL value, including literal newlines.
See [BashFAQ #001 ("How can I read a file (data stream, variable) line-by-line
(and/or field-by-field)?")](http://mywiki.wooledge.org/BashFAQ/001) for more
on the process of reading record-oriented data from a string in bash.
|
Made a button class in python but cannot add to screen with pygame
Question:
import pygame, sys, time, random
from pygame.locals import*
pygame.init()
class Button(object):
def __init__(self, x, y):
'''x_size, y_size,'''
#self.name = name
'''self.length = x_size'''
'''self.height = y_size'''
self.xpos = x
self.ypos = y
self.rect = (100,100)
self.image = ('Images\Button_Test.png')
def getRect(self):
return self.rect
def onClick():
for event in pygame.event.get():
if event.type == pygame.mouse.get_pressed():
pos = pygame.mouse.get_pos()
if self.collidepoint(pos):
return
the main class
screen.blit(background,(0,0))
screen.blit(testButton, testButton.getRect())
pygame.display.flip()
> TypeError: argument 1 must be pygame.Surface, not Button
Can any one help me solve this error?
Answer: try this:
screen.blit(testbutton.image,testbutton.get_rect())
you're currently telling it to `blit` an object and not the object's sprite
|
Create an Entry box if a specific item on Optionmenu is selected
Question: i'm new to Python scripting. I'm trying to create an entry box for a user to
manually input a variable that doesn't exist in a list of a optionmenu widget.
is this possible?
from Tkinter import *
import Tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
x = (master.winfo_screenwidth() - master.winfo_reqwidth()) / 2
y = (master.winfo_screenheight() - master.winfo_reqheight()) / 2
master.geometry("+%d+%d" % (x, y))
master.deiconify()
self.subtests = StringVar()
self.subtests.set("Enter Test Type")
choices = ['Potato','Tomato','Onion','Other']
self.testnumber = OptionMenu(master, self.subtests, *choices).grid(row = 2, column = 3)
self.confirmbutton = Button (master, text="Confirm Test", width=20, command =lambda: self.confirmsubtest(master))
self.confirmbutton.grid(row = 5, sticky = E)
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
As mentioned, if the user needs to select a variable that is not on the list.
Is it possible to allow the user to manually enter the variable through an
entry box in the same window (ex: Selecting "Other" in the list that generates
an entry/widget/something)?
Thanks,
M
Answer: If anyone searches for the same thing. The process is to add the command
variable to the optionmenu and disable the entry widget once the desired
highlighted choice is on. This is done by configuring the
button/widget/anything with a .config(state=NORMAL) or
.config(state=DISABLED).
self.testnumber = OptionMenu(master, self.subtests, *choices, command = self.optupdate).grid(row = 2, column = 3)
self.testnumber.grid(row = 4, column = 1)
def optupdate(self,value):
if value == "Other":
self.otherEntry.config(state=NORMAL)
else:
self.otherEntry.config(state=DISABLED)
return
|
Unsuccessful post to asp.net form using Python requests
Question: I am attempting to use Python requests to post a value to the "employer" form
in the <http://www.myvisajobs.com/Search_Visa_Sponsor.aspx?N=>
This is what I have tried so far in Python:
import requests
url = "http://www.myvisajobs.com/Search_Visa_Sponsor.aspx?N="
data = {"ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$txtCompany":"Microsoft"}
r = requests.post(url,data)
print(r.text)
Which returns only the original HTML. I am trying to return the resulting
HTML. My gut feeling is I am doing something fundamentally wrong, but I am not
sure what.
Answer: There are much more parameters sent in the search POST request than just the
`ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$txtCompany` referring to
the company name.
Instead, to make things transparent and easy, I would use
[`RoboBrowser`](https://github.com/jmcarp/robobrowser) that would "auto-fill"
other form POST parameters needed. Example working code:
from robobrowser import RoboBrowser
url = "http://www.myvisajobs.com/Search_Visa_Sponsor.aspx?N="
browser = RoboBrowser(history=True)
browser.open(url)
form = browser.get_form(id='aspnetForm')
form['ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$txtCompany'].value = 'Microsoft'
browser.submit_form(form)
results = browser.select('div#ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_divContent table tr')[1:]
for result in results:
cells = result.find_all("td")
print(cells[2].get_text(strip=True))
It prints the company names from the search results:
Microsoft Corporation
Microsoft Operations Puerto Rico, Llc
Microsoft Caribbean, Inc.
Standard Microsystems Corporation
4Microsoft Corporation
Microsoft Business Solutions Corporation
Microsoft C98052orporation
Microsoft Ccrporation
Microsoft Coiporation
Microsoft Copporation
Microsoft Corforation
Microsoft Licensing, GP
Microsoft Way
Microsoftech Inc
Quantitative Micro Software Llc
Webtv Networks Microsoft Sub
Microsoft
FAST, A Microsoft Subsidiary
Microsoft Corporation - Sham
Microsoft Partner Careers (sponsored By Microsoft Dynamics)
Microsoft Iberica
Microsoft Karthi
|
Executing script with sudo in virtual environment - packages not found
Question: I created a virtual environment and wrote a Scapy project in it. For this I
wrote some modules and packages and put them in the environments site-packages
folder. Now when I enter the environment with `source bin/activate` and try to
execute the script with `sudo` some modules I put in the virtual environments
site-packages folder can't be found. When I execute it as normal user the
module is found, but the script, of course, won't work because it needs super
user rights. How can I fix this?
(Project)user@pc ~/git/Fuzzing/src $ python BACnetMonitoring.py
WARNING: No route found for IPv6 destination :: (no default route?)
Traceback (most recent call last):
File "BACnetMonitoring.py", line 17, in <module>
webRequest_timeout=1
File "/home/user/git/Fuzzing/local/lib/python2.7/site-packages/BACnetMonitor.py", line 78, in __init__
self._socket = conf.L2socket(iface=self._iface)
File "/home/user/git/Fuzzing/local/lib/python2.7/site-packages/scapy/arch/linux.py", line 414, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
File "/usr/lib/python2.7/socket.py", line 187, in __init__
_sock = _realsocket(family, type, proto)
socket.error: [Errno 1] Operation not permitted
(Project)user@pc ~/git/Fuzzing/src $ sudo python BACnetMonitoring.py
Traceback (most recent call last):
File "BACnetMonitoring.py", line 7, in <module>
import BACnetMonitor
ImportError: No module named BACnetMonitor
(Project)user@pc ~/git/Fuzzing/src $
Answer: `sudo` doesn't inherit your environment. Specify the full path to the
Project's python executable.
Look at `sys.executable` with and without `sudo`.
|
How to import argparse when I am using qsub in Linux server?
Question: I want to use CoNIFER, which is a python program for bioinformatics.
So, I wrote a script for qsub because of my institute's rule.
Here is my qsub script. I inserted enter in front of -- to show it clear.
#!/bin/bash
#$ -N oh
#$ -cwd
cd /usr/etc/GRAPE_ENV/Python/
python /home/osj118/tools/conifer_v0.2.2/conifer.py rpkm
--probes/home/osj118/input/GBM/Gastric/Exome_probe/Exome_probe_capture_library_coordinate.txt
--input /scratch/Gastric_cell_bam/AGS_2.fastq.gz_Illumina_exome_Exome.RGadded.marked.realigned.fixed.recal.bam
--output /home/osj118/output/AGS_rpkm.txt
cd /home/osj118/pyscripts
CoNIFER did not work and show error message that
> ImportError: No module named argparse
I already used `sys.append.path` function but it failed to solve my problem.
Strangely, when I ran batch job, CoNIFER worked correctly without any error
message.
As batch job violates the rule, I want to use qsub to work in Linux server.
Please give me any solution for this situation.
Answer: This smells like a pythonpath problem. The pythonpath determines where python
can find the required modules. If you installed CoNIFER in a directory
together with the packages it uses, then Python will find the packages only if
they are on the pythonpath.
You can specify the pythonpath as follows:
export PYTHONPATH=/directory where CoNIFER is installed
|
py2exe missing modules: oauth2client.client and gspread modules
Question: I have created the following Python script using the gspread and oauth2
modules
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
credentials = SignedJwtAssertionCredentials("client_email","private_key", "https://spreadsheets.google.com/feeds")
gc = gspread.authorize(credentials)
spreadsheet = gc.open_by_key("spreadsheet_id")
worksheet = spreadsheet.worksheet("sheet_name")
lstoforders = worksheet.get_all_values()
...some extra code...
When I run this code as a .py file everything works smoothly. However, when I
try to package it into an executable Windows program using py2exe, I get the
following output
The following modules appear to be missing
['ElementC14N', 'IronPythonConsole', 'System', 'System.Windows.Forms.Clipboard', '_scproxy', 'ca_certs_locater', 'clr', 'console', 'email.FeedParser', 'email.Message', 'email.Utils', 'google.appengine.api', 'google.appengine.api.urlfetch','google3.apphosting.api', 'google3.apphosting.api.urlfetch', 'http', 'modes.editingmodes', 'oauth2client.client' 'pyreadline.keysyms.make_KeyPress', 'pyreadline.keysyms.make_KeyPress_from_keydescr', 'pyreadline.keysyms.make_keyinfo', 'pyreadline.keysyms.make_keysym', 'startup', 'urllib.parse']
Accordingly, when I try to run the resulting exe file, I get the following
error
Traceback (most recent call last):
File "gspread_to_autocomplete_json.py", line 2, in <module> ImportError: No module named oauth2client.client
It appears as if py2exe cannot find the gspread and oauth2client.client
modules. These modules are installed on my machine.
Does anybody have a clue why this is happening?
Thanks.
Nicola
Answer: You can choose in your setup.py with packages and modules you want to
include.It might be that your setup script is not finding all the dependencies
automatically (actually it is pretty common).Try to have a look at [the answer
I gave to this question](http://stackoverflow.com/a/34772426/5687152).
> **Add options to your setup.py**
You can also use more [py2exe
options](http://www.py2exe.org/index.cgi/ListOfOptions) in order that you are
importing all the modules and the packages required by your project. E.g.
# setup.py
from distutils.core import setup
import py2exe
setup(console=["script.py"],
options={
"py2exe":{
"optimize": 2,
"includes": ["mf1.py", "mf2.py", "mf3.py"], # List of all the modules you want to import
"packages": ["package1"] # List of the package you want to make sure that will be imported
}
}
)
In this way you can force the import of the missing script of your project
|
Python Minidom Parsing File Objects
Question: I wrote a code using minidom which takes an `xml` script, opens it as a file
object and then parses that file object. Not only that, but I want the script
to open multiple files that are all contained in a folder, and parse each one
individually.
An example of the `xml` script is:
<?xml version="1.0"?>
<Data>
<data1>1</data1>
<data2>2</data2>
<data3>3</data3>
<Sub_data>
<sub_data1>0.1111111111111</sub_data1>
<sub_data2>0.2222222222222</sub_data2>
... and so on.
i.e., it's pretty standard.
Now, my code looks like this:
import os
import io
from xml.dom import minidom
#folder where xml files are located
indir = '/foo/bar/docs/'
masterlist = []
for root, dirs, filenames in os.walk(indir):
for f in filenames:
row = []
fsock = io.open(indir + f, mode = 'rt', encoding = 'cp1252')
xmldoc = minidom.parse(fsock)
...
and the error I am getting is:
Traceback (most recent call last): File "kgp_2.py", line 34, in
<module> xmldoc = minidom.parse(fsock) File
"/usr/lib/python2.7/xml/dom/minidom.py", line 1918, in parse return
expatbuilder.parse(file) File
"/usr/lib/python2.7/xml/dom/expatbuilder.py", line 928, in parse
result = builder.parseFile(file) File
"/usr/lib/python2.7/xml/dom/expatbuilder.py", line 211, in parseFile
parser.Parse("", True) xml.parsers.expat.ExpatError: no element found:
line 203, column 1381
Now, when I make the change:
fsock = io.open(indir + filenames[0], mode = 'rt', encoding = 'cp1252')
this works fine, that is, it opens the first file in the folder; but I want to
parse all the files in the folder. When I do a loop like:
m = 0
... in loop:
fsock = io.open(indir + filenames[m], mode = 'rt', encoding = 'cp1252')
...
m = m+1
I get the original error.
The reason I am using the io library instead of the usual file open function
is that a previous stack overflow article recommended it. Using:
fsock = open(indir + filenames[0])
like before, gets no error, but:
fsock = open(indir + f)
or
#with a loop over m, like above
fsock = open(infir + filenames[m])
get the same error as above.
A strange problem. When I print the filenames they are correct. And they
**are** being opened, there's no error there. It's the parser that just won't
parse the object files, even with `filenames[m]` where `m = 0`, surely this
should be no problem?
EDIT: [Parsing document with python
minidom](http://stackoverflow.com/questions/3625897/parsing-document-with-
python-minidom)
in this post they had a similar problem, the resolution was to use
xmldoc.seek(0)
however, for me this returns
Traceback (most recent call last):
File "kgp_2.py", line 45, in <module>
xmldoc.seek(0)
AttributeError: Document instance has no attribute 'seek'
**EDIT 2: THIS HAS BEEN RESOLVED. IT WAS A CASE OF A CORRUPTED INPUT XML
FILE.**
Answer: Are you sure the XML data contained in all XML files is correct? Perhaps one
is empty an you have to handle such Exception. Anyhow I recommend you to use
`xml.etree`
[doc](https://docs.python.org/2/library/xml.etree.elementtree.html).
|
pass vim argument in completefunc
Question: I am writing a `vimscript` that uses `completefunc` as:
" GetComp: Menu and Sunroutine Completion {{{1
function! GetComp(arg, findstart, base)
if a:findstart
" locate the start of the word
let line = getline('.')
let start = col('.') - 1
while start > 0 && line[start - 1] =~ '\a'
let start -= 1
endwhile
return start
else
echomsg '**** completing' a:base
python << EOF
import vim
import os
flsts = [' ']
path = "."
for dirs, subdirs, files in os.walk(path):
for tfile in files:
if tfile.endswith(('f90', 'F90', 'f', 'F')):
ofile = open(dirs+'/'+tfile)
for line in ofile:
if line.lower().strip().startswith(vim.eval("a:arg")):
modname = line.split()[1]
flsts.append(modname)
vim.command("let flstsI = %s"%flsts)
EOF
if eval("a:arg") = "module"
for m in ["ieee_arithmatic", "ieee_exceptions", "ieee_features", "iso_c_bindings", "iso_fortran_env", "omp_lib", "omp_lib_kinds"]
if m =~ "^" . a:base
call add(flstsI, m)
endif
endfor
elseif eval("a:arg") = "subroutine"
for m in ["alarm()", "date_and_time()", "backtrace", "c_f_procpointer()", "chdir()", "chmod()", "co_broadcast()", "get_command()", "get_command_argument()", "get_environment_variable()", "mvbits()", "random_number()", "random_seed()"]
if m =~ "^" . a:base
call add(flstsI, m)
endif
endfor
endif
return flstsI
endif
endfunction
I will call it for 2 different argument as:
inoremap <leader>call call <C-o>:set completefunc=GetComp("subroutine", findstart, base)<CR><C-x><C-u>
inoremap <leader>use use <C-o>:set completefunc=GetComp("module", findstart, base)<CR><C-x><C-u>
But trying so, gives error: `Unknown function GetComp(`
I don't know how to call them. If I don't use `arg`, then, using this
[reply](http://stackoverflow.com/questions/34745939/vim-update-complete-popup-
as-i-type/34747283#34747283), I can call this perfectly. Kindly help.
Answer: You'll have to attach a context to your completion. If you look closely at [my
message on vi.se](http://vi.stackexchange.com/questions/5820/dynamic-
completion), you'll see a framework that permits to bind data to a user-
completion. From there in your mapping, it just becomes a question of which
context to attach.
A simplified way would be to execute a (preparation) function from the
mappings and have the function set script global variables that will be used
in your completion function.
|
selenium: webdriver.PhantomJS(): "Error: Can not connect to GhostDriver on port 51263"
Question: I want to use PhantomJS() in python3.4 and typed
Therefore:
from selenium import webdriver
browser = webdriver.PhantomJS()
I got the error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/selenium/webdriver/phantomjs/webdriver.py", line 51, in __init__
self.service.start()
File "/usr/local/lib/python3.4/dist-packages/selenium/webdriver/phantomjs/service.py", line 83, in start
"Can not connect to GhostDriver on port {}".format(self.port))
selenium.common.exceptions.WebDriverException: Message: Can not connect to GhostDriver on port 40236
I know the error is thrown inside `selenium.webdriver.phantomjs.service`,
because the function `utils.is_connectable(self.port)` can't connect to the
localhost (the localhost is reachable).
try:
self.process = subprocess.Popen(
self.service_args, stdin=subprocess.PIPE,
close_fds=platform.system() != 'Windows',
stdout=self._log, stderr=self._log)
except Exception as e:
raise WebDriverException("Unable to start phantomjs with ghostdriver: %s" % e)
count = 0
while not utils.is_connectable(self.port):
count += 1
time.sleep(1)
if count == 30:
raise WebDriverException("Can not connect to GhostDriver on port {}".format(self.port))
I couldn't find a solution that worked for me, so it would be create if
someone has an idea.
My system:
Linux controller 4.1.15-v7+ #830 SMP Tue Dec 15 17:02:45 GMT 2015 armv7l GNU/Linux
Answer: you must download phantomJS - [LINK](http://phantomjs.org/download.html)
and after that give path to it in your code
browser = webdriver.PhantomJS(pathToPhantomJS)
|
Changing BASH script to Python
Question: I am trying to convert this script to Python but am having problems with the
BASH syntax `${variable}`. This does something I do not understand as I have
very little experience with BASH scripting. My question is basically,how can I
do the dollar brackets variable thing in Python `${variable}`. In my case the
variable is a number from zero to two-hundred and fifty-five. Please see the
BASH script below. I am trying to do the exact same thing in Python.
do
for code in {0..255};
do echo -e "\e[38;05;${code}m $code: Test";
done;
done
Here is my attempt to convert the code to a Python script. Unfortunately, I am
still having to call BASH via the os.system() method or function. Please check
out my script below. The script does not function the same way though, with
changing the text in the BASH shell. The Python script below simply prints out
the crazy text below and increments the numbers... :/
#! /usr/bin/env python
import os
def run():
for code in range(0, 255):
os.system('echo -e "\e[38;05;%dm %s Test"' % (code,str(code)))
run()
Answer: You can use `print` command and [string
formatting](https://docs.python.org/2/library/string.html#string-formatting)
to evaluate your variable during the print.
BTW, you can use `xrange` rather than `range` in order not to generate all the
numbers in your memory, but to `yield` it one-by-one (for large range)
You can use this:
import os
def run():
for code in range(0, 256):
print "\x1b[38;05;{code}m {code} Test".format(code=code)
run()
|
How to slice and access text with TkInter's indices?
Question: In Python, to slice a string to use indices, e.g.
word = "Python" # immutable string
word[2:5] # characters from position 2 (included) to 5 (excluded)
outputs `'tho'`
The Text Widget for TkInter outputs text location at
line.char
which indicates the _char'th_ character on _line_ line.
If I input a simple text file into a Text Widget GUI as follows:
from tkinter import *
from tkinter.ttk import *
filename = "textfile1.txt"
with open(filename, "rt", encoding='latin1') as in_file:
readable_file = in_file.read()
root = Tk()
text = Text(root)
text.insert(1.0, readable_file)
text.pack(expand=YES, fill=BOTH)
root.mainloop()
I could access locations in text file. How can I "slice" this string
`readable_file` with the initial `line.char` and the final `line.char`?
Is there a different way to accomplish this?
Answer: Yes, you can simply use the
[`get`](http://effbot.org/tkinterbook/text.htm#Tkinter.Text.get-method) method
of your `Text` widget using the `Text` widget's indices:
>>> from tkinter import *
>>> root = Tk()
>>> text = Text(root)
>>> text.insert("end", "Hello world, how are you?")
>>> text.pack(fill="both", expand=1)
>>> text.get("1.0", "1.4")
'Hell'
>>> text.get("1.4", "end")
'o world, how are you?\n'
>>> text.get("2.0", "end") # because there's just one line
''
>>> text.get("1.7", "end-1c") # without the newline at the end
'orld, how are you?'
This is the only way I know to do it easily. You could also get all the text
(again using `Text` widget's indices) and store in in a string, and then
manipulate the string, but it is more work.
|
lxml: error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
Question: I've seen some posts on lxml installing problems, but none of the answers I
found was of any help. Many said to install python-dev, libxml2 and libxslt to
solve the problem. They are already installed, but I still get the following
outcome (keep in mind that I'm installing everything locally using
virtualenv):
(scrapers)~$ pip install lxml
Downloading/unpacking lxml
Downloading lxml-3.5.0.tar.gz (3.8MB): 3.8MB downloaded
Running setup.py (path:/home/pigna/scrapers/build/lxml/setup.py) egg_info for package lxml
Building lxml version 3.5.0.
Building without Cython.
Using build configuration of libxslt 1.1.28
warning: no previously-included files found matching '*.py'
Installing collected packages: lxml
Running setup.py install for lxml
Building lxml version 3.5.0.
Building without Cython.
Using build configuration of libxslt 1.1.28
building 'lxml.etree' extension
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -Isrc/lxml/includes -I/usr/include/python2.7 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o -w
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o -lxslt -lexslt -lxml2 -lz -lm -o build/lib.linux-x86_64-2.7/lxml/etree.so
/usr/bin/ld: cannot find -lz
collect2: error: ld returned 1 exit status
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
Complete output from command /home/pigna/scrapers/bin/python -c "import setuptools, tokenize;__file__='/home/pigna/scrapers/build/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ikEzzn-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/pigna/scrapers/include/site/python2.7:
Building lxml version 3.5.0.
Building without Cython.
Using build configuration of libxslt 1.1.28
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/lxml
copying src/lxml/usedoctest.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/builder.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/pyclasslookup.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/cssselect.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/sax.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/__init__.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/ElementInclude.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/doctestcompare.py -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/_elementpath.py -> build/lib.linux-x86_64-2.7/lxml
creating build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/__init__.py -> build/lib.linux-x86_64-2.7/lxml/includes
creating build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/usedoctest.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/builder.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/_setmixin.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/diff.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/formfill.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/html5parser.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/_html5builder.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/__init__.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/_diffcommand.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/ElementSoup.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/soupparser.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/defs.py -> build/lib.linux-x86_64-2.7/lxml/html
copying src/lxml/html/clean.py -> build/lib.linux-x86_64-2.7/lxml/html
creating build/lib.linux-x86_64-2.7/lxml/isoschematron
copying src/lxml/isoschematron/__init__.py -> build/lib.linux-x86_64-2.7/lxml/isoschematron
copying src/lxml/lxml.etree.h -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/lxml.etree_api.h -> build/lib.linux-x86_64-2.7/lxml
copying src/lxml/includes/config.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/xinclude.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/dtdvalid.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/htmlparser.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/tree.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/etreepublic.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/xmlschema.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/c14n.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/schematron.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/uri.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/xmlparser.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/xmlerror.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/relaxng.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/xslt.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/xpath.pxd -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-2.7/lxml/includes
copying src/lxml/includes/etree_defs.h -> build/lib.linux-x86_64-2.7/lxml/includes
creating build/lib.linux-x86_64-2.7/lxml/isoschematron/resources
creating build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/rng
copying src/lxml/isoschematron/resources/rng/iso-schematron.rng -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/rng
creating build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl
copying src/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl
copying src/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl
creating build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt -> build/lib.linux-x86_64-2.7/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/src
creating build/temp.linux-x86_64-2.7/src/lxml
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -Isrc/lxml/includes -I/usr/include/python2.7 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o -w
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/src/lxml/lxml.etree.o -lxslt -lexslt -lxml2 -lz -lm -o build/lib.linux-x86_64-2.7/lxml/etree.so
/usr/bin/ld: cannot find -lz
collect2: error: ld returned 1 exit status
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
Cleaning up...
Command /home/pigna/scrapers/bin/python -c "import setuptools, tokenize;__file__='/home/pigna/scrapers/build/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-ikEzzn-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/pigna/scrapers/include/site/python2.7 failed with error code 1 in /home/pigna/scrapers/build/lxml
Storing debug log for failure in /home/pigna/.pip/pip.log
What does `warning: no previously-included files found matching '*.py'` mean?
`/usr/bin/ld: cannot find -lz` what is -lz? How to install it?
Answer: The relevant error is this:
/usr/bin/ld: cannot find -lz
...which indicates that the linker couldn't find `libz.so`, which means you
don't have zlib installed in a location in your library search path.
Install zlib; the method for doing so depends on your operating system, so
there's no generic answer. It might be something like:
sudo apt-get install zlib-dev # on a Debian derivative
sudo apt-get install zlib1g-dev # on Ubuntu 14.04 (see below)
sudo yum install zlib-devel # on a Red Hat derivative
sudo port install zlib # on a ports-based system
sudo pacman -S zlib # on Arch Linux
or any number of other things as appropriate.
* * *
Assuming you want to find the appropriate package name for a given version of
Ubuntu, one can [search for the package containing `libz.so` on
packages.ubuntu.com](http://packages.ubuntu.com/search?searchon=contents&keywords=libz.so&mode=exactfilename&suite=trusty&arch=any);
the linked results are for Trusty.
|
Webview or iframe in django python
Question: How to put an iframe, or something similar(like a webview), in my website such
that the request for the iframe is sent from server side instead of client
browser? I am using django in backend. I want to use iframes for viewing of
regular sites like google.com.
Answer: if your are trying to edit a html file and want to show iframe in it.... then
you can do this
import webbrowser
f = open('helloworld.html','w')
message = """<html>
<head></head>
<body><iframe src="#"></iframe></body>
</html>"""
f.write(message)
f.close()
webbrowser.open_new_tab('helloworld.html')enter code here
|
How to source script via python
Question: I can source bash script (without shebang) easy as bash command in terminal
but trying to do the same via python command
sourcevars = "cd /etc/openvpn/easy-rsa && . ./vars"
runSourcevars = subprocess.Popen(sourcevars, shell = True)
or
sourcevars = [". /etc/openvpn/easy-rsa/vars"]
runSourcevars = subprocess.Popen(sourcevars, shell = True)
I receive :
> Please source the vars script first (i.e. "source ./vars") Make sure you
> have edited it to reflect your configuration.
What's the matter, how to do it correctly?I've read some topics here,e.g
[here](http://stackoverflow.com/q/7040592/407651) but could not solve my
problem using given advices. Please explain with examples.
UPDATED:
# os.chdir = ('/etc/openvpn/easy-rsa')
initvars = "cd /etc/openvpn/easy-rsa && . ./vars && ./easy-rsa ..."
# initvars = "cd /etc/openvpn/easy-rsa && . ./vars"
# initvars = [". /etc/openvpn/easy-rsa/vars"]
cleanall = ["/etc/openvpn/easy-rsa/clean-all"]
# buildca = ["printf '\n\n\n\n\n\n\n\n\n' | /etc/openvpn/easy-rsa/build-ca"]
# buildkey = ["printf '\n\n\n\n\n\n\n\n\n\nyes\n ' | /etc/openvpn/easy-rsa/build-key AAAAAA"]
# buildca = "cd /etc/openvpn/easy-rsa && printf '\n\n\n\n\n\n\n\n\n' | ./build-ca"
runInitvars = subprocess.Popen(cmd, shell = True)
# runInitvars = subprocess.Popen(initvars,stdout=subprocess.PIPE, shell = True, executable="/bin/bash")
runCleanall = subprocess.Popen(cleanall , shell=True)
# runBuildca = subprocess.Popen(buildca , shell=True)
# runBuildca.communicate()
# runBuildKey = subprocess.Popen(buildkey, shell=True )
UPDATE 2
buildca = ["printf '\n\n\n\n\n\n\n\n\n' | /etc/openvpn/easy-rsa/build-ca"]
runcommands = subprocess.Popen(initvars+cleanall+buildca, shell = True)
Answer: There's absolutely nothing wrong with this in and of itself:
# What you're already doing -- this is actually fine!
sourcevars = "cd /etc/openvpn/easy-rsa && . ./vars"
runSourcevars = subprocess.Popen(sourcevars, shell=True)
# ...*however*, it won't have any effect at all on this:
runOther = subprocess.Popen('./easy-rsa build-key yadda yadda', shell=True)
However, if you **subsequently** try to run a second `subprocess.Popen(...,
shell=True)` command, you'll see that it doesn't have any of the variables set
by sourcing that configuration.
**This is entirely normal and expected behavior** : The entire point of using
`source` is to modify the state of the active shell; each time you create a
new `Popen` object with `shell=True`, it's starting a new shell -- their state
isn't carried over.
Thus, combine into a single call:
prefix = "cd /etc/openvpn/easy-rsa && . ./vars && "
cmd = "/etc/openvpn/easy-rsa/clean-all"
runCmd = subprocess.Popen(prefix + cmd, shell=True)
...such that you're using the results of sourcing the script in the same shell
invocation as that in which you actually source the script.
* * *
Alternately (and this is what I'd do), require your Python script to be
invoked by a shell which already has the necessary variables in its
environment. Thus:
# ask your users to do this
set -a; . ./vars; ./yourPythonScript
...and you can error out if people don't do so very easy:
import os, sys
if not 'EASY_RSA' in os.environ:
print >>sys.stderr, "ERROR: Source vars before running this script"
sys.exit(1)
|
Downloading a file served by a tornado web server
Question: This is how I have my tornado web server currently defined:
application = tornado.web.Application([
tornado.web.url(r"/server", MainHandler),
tornado.web.url(r"/(.*)", tornado.web.StaticFileHandler, { "path": scriptpath, "default_filename": "index.html" }),
])
index.html is the start page of a web based gui. It will communicate with the
backend server through http:///server and the requests by the gui to the
server are handled by the MainHandler function.
The directory structure looks like:
root_directory/
server.py
fileiwanttodownload.tar.gz
index.html
I would like to be able to type into the browser:
http:///data/fileiwanttodownload.tar.gz
and have the file delivered to me as a regular file download.
What I have tried to do is:
application = tornado.web.Application([
tornado.web.url(r"/server", MainHandler),
tornado.web.url(r"/data", tornado.web.StaticFileHandler, { "path": scriptpath } ),
tornado.web.url(r"/(.*)", tornado.web.StaticFileHandler, { "path": scriptpath, "default_filename": "index.html" }),
])
But this is not working for reasons that are probably obvious to those who
know the answer.
The only clue I have is the following error message:
Uncaught exception GET /data (192.168.4.168)
HTTPServerRequest(protocol='http', host='192.168.4.195:8888', method='GET', uri='/data', version='HTTP/1.1', remote_ip='192.168.4.168', headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9', 'Host': '192.168.4.195:8888', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Connection': 'keep-alive', 'Accept-Language': 'en-us'})
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 1445, in _execute
result = yield result
File "/usr/local/lib/python3.4/dist-packages/tornado/gen.py", line 1008, in run
value = future.result()
File "/usr/local/lib/python3.4/dist-packages/tornado/concurrent.py", line 232, in result
raise_exc_info(self._exc_info)
File "<string>", line 3, in raise_exc_info
File "/usr/local/lib/python3.4/dist-packages/tornado/gen.py", line 267, in wrapper
result = func(*args, **kwargs)
TypeError: get() missing 1 required positional argument: 'path'
Answer: `scriptpath` you haven't shown, is probably wrong. In `path` you should
provide root dir to the files, in URI matcher capture only the file or so.
Simple example:
import tornado.ioloop
import tornado.web
import os
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
script_path = os.path.dirname(__file__)
return tornado.web.Application([
(r"/", MainHandler),
(r"/data/(.*)", tornado.web.StaticFileHandler, {"path": script_path}),
# ^ we capture only this part
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
As you can run it works, but it is recommended to store static/data files in
separate directory, because it is possible to download everything from the app
root dir, including python one.
So put your downloadable file e.g. in data subdirectory and then
script_path = os.path.join(os.path.dirname(__file__), 'data')
More info about
[StaticFileHandler](http://www.tornadoweb.org/en/stable/web.html?highlight=staticfilehandler#tornado.web.StaticFileHandler).
**edit**
The error you are getting is because in your code `/data` route has
StaticFileHandler, but nothing is captured `()` from requested path.
|
python stream subprocess stdout and stderr zip doesnt work
Question: There are already a bunch of answers that solve how to do this general thing,
but my main question is Why doesnt this approach work?
I am trying to "live stream" the stdout and stderr from a subprocess. I can do
this by doing:
import sys
import subprocess
def run_command(cmd):
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
for out in iter(process.stdout.readline, b''):
print(out)
for err in iter(process.stderr.readline, b''):
print(err)
run_command(['echo', 'hello', 'world']) # should print hello world
run_command(['rm', 'blarg223']) # Should print to stderr (file doesnt exist)
and this works giving me the result:
b'hello world\n'
b'rm: cannot remove \xe2\x80\x98blarg223\xe2\x80\x99: No such file or directory\n'
However this causes a problem as it really only live streams the stdout, then
prints all the errors as the end. So I thought I could fix this using:
def run_command(cmd):
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
for out, err in zip(iter(process.stdout.readline, b''), iter(process.stderr.readline, b'')):
print(out)
print(b'Error: ' + err)
But, this doesnt produce any output. Why does using zip not work?
Answer: zip stops when one of the iterators is finished.
In each of the examples you gave, one stream(stdout/stderr) is empty. So zip
will produce nothing.
To fix this you should use itertools.zip_longest
|
Directory Structure for Importing Python Package using __init__.py
Question: I've got a python project (projectA), which I've included as a git submodule
in a separate project (projectB) as a subfolder. The structure is laid out as
projectB/
projectB_file.py
projectA/ (repository)
projectA/ (source code)
module1/
file1.py (contains Class1)
file2.py (contains Class2)
tests/
test_file1.py
I'm trying to figure out how to layout `__init__.py` files so in
`projectB_file.py` I can import `Class1` and `Class2` as
from projectA.module1 import Class1
from projectA import Class2
Answer: I think having the top level `projectA` part of the import will be a mistake.
That will require you to write your imports with `projectA` duplicated (e.g.
`import projectA.projectA.module1.file1`).
Instead, you should add the top `projectA` folder to the module search path in
some way (either as part of an install script for `projectB`, or with a
setting in your IDE). That way, `projectA` as a top-level name will refer to
the inner folder, which you actually intend to be the `projectA` package.
|
Plot a line graph over a histogram for residual plot in python
Question: I have created a script to plot a histogram of a NO2 vs Temperature residuals
in a dataframe called nighttime.
The histogram shows the normal distribution of the residuals from a regression
line somewhere else in the python script.
I am struggling to find a way to plot a bell curve over the histogram like
this example :
[Plot Normal distribution with
Matplotlib](http://stackoverflow.com/questions/20011494/plot-normal-
distribution-with-matplotlib)
How can I get a fitting normal distribution for my residual histogram?
plt.suptitle('NO2 and Temperature Residuals night-time', fontsize=20)
WSx_rm = nighttime['Temperature']
WSx_rm = sm.add_constant(WSx_rm)
NO2_WS_RM_mod = sm.OLS(nighttime.NO2, WSx_rm, missing = 'drop').fit()
NO2_WS_RM_mod_sr = (NO2_WS_RM_mod.resid / np.std(NO2_WS_RM_mod.resid))
#Histogram of residuals
ax = plt.hist(NO2_WS_RM_mod.resid)
plt.xlim(-40,50)
plt.xlabel('Residuals')
plt.show
Answer: Does the following work for you? (using some adapted code from the link you
gave)
import scipy.stats as stats
plt.suptitle('NO2 and Temperature Residuals night-time', fontsize=20)
WSx_rm = nighttime['Temperature']
WSx_rm = sm.add_constant(WSx_rm)
NO2_WS_RM_mod = sm.OLS(nighttime.NO2, WSx_rm, missing = 'drop').fit()
NO2_WS_RM_mod_sr = (NO2_WS_RM_mod.resid / np.std(NO2_WS_RM_mod.resid))
#Histogram of residuals
ax = plt.hist(NO2_WS_RM_mod.resid)
plt.xlim(-40,50)
plt.xlabel('Residuals')
# New Code: Draw fitted normal distribution
residuals = sorted(NO2_WS_RM_mod.resid) # Just in case it isn't sorted
normal_distribution = stats.norm.pdf(residuals, np.mean(residuals), np.std(residuals))
plt.plot(residuals, normal_distribution)
plt.show
|
Error with the function random.choice
Question: Using this code:
from PIL import Image
from PIL.ImageChops import subtract
import numpy
import math
import time
import glob
import sys
import os
import logging
import random
def GreenScreen(infile, inbg ,outfile='output.png', keyColor=None, tolerance=None):
"""
http://gc-films.com/chromakey.html
http://www.cs.utah.edu/~michael/chroma/
:param infile: Greenscreen image location
:param inbg: Background image location
:param outfile: Output file location
:param keyColor: greenscreen color; it can be any singular color
:param tolerance: tolerance of cleaning
:return:
"""
if not keyColor:
keyColor = [151,44,21] #Y,Cb, and Cr values of the greenscreen
if not tolerance:
tolerance = [100,130] #Allowed Distance from Values
#open files
inDataFG = Image.open('/home/leonardo/Scrivania/KVfnt.jpg').convert('YCbCr')
BG = random.choice(os.listdir('/home/leonardo/Scrivania/background')).convert('RGB')
[Y_key, Cb_key, Cr_key] = keyColor
[tola, tolb]= tolerance
(x,y) = inDataFG.size #get dimensions
foreground = numpy.array(inDataFG.getdata()) #make array from image
maskgen = numpy.vectorize(colorclose) #vectorize masking function
alphaMask = maskgen(foreground[:,1],foreground[:,2] ,Cb_key, Cr_key, tola, tolb) #generate mask
alphaMask.shape = (y,x) #make mask dimensions of original image
imMask = Image.fromarray(numpy.uint8(alphaMask))#convert array to image
invertMask = Image.fromarray(numpy.uint8(255-255*(alphaMask/255))) #create inverted mask with extremes
#create images for color mask
colorMask = Image.new('RGB',(x,y),tuple([0,0,0]))
allgreen = Image.new('YCbCr',(x,y),tuple(keyColor))
colorMask.paste(allgreen,invertMask) #make color mask green in green values on image
inDataFG = inDataFG.convert('RGB') #convert input image to RGB for ease of working with
cleaned = subtract(inDataFG,colorMask) #subtract greens from input
BG.paste(cleaned,imMask)#paste masked foreground over background
# BG.show() #display cleaned image
BG.save(outfile, "JPEG") #save cleaned image
def colorclose(Cb_p,Cr_p, Cb_key, Cr_key, tola, tolb):
temp = math.sqrt((Cb_key-Cb_p)**2+(Cr_key-Cr_p)**2)
if temp < tola:
z = 0.0
elif temp < tolb:
z = ((temp-tola)/(tolb-tola))
else:
z = 1.0
return 255.0*z
def check_folders(logger):
if not os.path.exists('out/'):
os.mkdir('out/')
if not os.path.exists('background/'):
os.mkdir('background/')
logger.error("Place background images in background/")
sys.exit()
if not os.path.exists('in/'):
os.mkdir('in/')
logger.error("Place input files in in/")
sys.exit()
def begin_greenbox(logger):
"""
For all backgrounds loop through all input files into the out file
"""
for bg in glob.glob('background/*'):
if not('.jpg' or '.png' in bg.lower()):
continue
bg_name = bg.split('/')[-1].lower().strip('.jpg').strip('.png').strip('.jpeg')
for picture in glob.glob('in/*'):
if not('.jpg' or '.png' in picture.lower()):
continue
pic_name = picture.split('/')[-1].lower().strip('.JPG').strip('.png').strip('.jpeg')
output_file = 'out/' + bg_name + ' ' + pic_name + '.jpg'
one_pic = time.time()
GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
one_pic_time_done = time.time()
time_arr.append(one_pic_time_done-one_pic)
logger.info(time_arr)
logger.info('done : %s' % pic_name)
def start_logging():
logging.basicConfig()
logger = logging.getLogger('greenbox')
logger.setLevel(logging.INFO)
return logger
if __name__ == '__main__':
time_start = time.time()
time_arr = []
logger = start_logging()
logger.info("Start time: %s" % time_start)
check_folders(logger)
begin_greenbox(logger)
time_end = time.time()
logger.info("End time: %s" % time_end)
I obtain this error:
INFO:greenbox:Start time: 1452730719.31
Traceback (most recent call last):
File "chromakeyy.py", line 115, in <module>
begin_greenbox(logger)
File "chromakeyy.py", line 96, in begin_greenbox
GreenScreen(infile=picture ,inbg=bg, outfile=output_file)
File "chromakeyy.py", line 33, in GreenScreen
BG = Image.open(random.choice(os.listdir('/home/leonardo/Scrivania/background'))).convert('RGB')
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2288, in open
fp = builtins.open(fp, "rb")
IOError: [Errno 2] No such file or directory: 'bai19-266x400.jpg'
Before using the command random.choice in line 33, everything was ok. What is
the problem? Why is it giving me this error? Is there another method to open a
random image from a specific folder? Thank you.
Answer: The error states that the file you are trying to open does not exist. This is
most likely because os.listdir(path) returns only the file names in 'path',
and not the full directory and filename.
In your case, it did select a random file named 'bai19-266x400.jpg', which you
then tried to open. When you should be opening
'/home/leonardo/Scrivania/background/bai19-266x400.jpg'. Something more like
this should work:
Path = '/home/leonardo/Scrivania/background'
FullPath = os.path.join(Path, random.choice(os.listdir(Path)))
BG = Image.open(FullPath).convert('RGB')
|
access host class from IronPython script (lightswitch)
Question: I'm new at this, so I hope the question is well formed enough for someone to
understand what i'm asking, if not I'm happy to add more detail. I am trying
to reference a variable defined on the server side of a lightswitch
application from a python script. The following post explains how to access a
host class from a python script.
[Access host class from IronPython
script](http://stackoverflow.com/questions/6234355/access-host-class-from-
ironpython-script)
The code on my server side is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Security.Server;
using System.IO.Ports;
using System.Threading;
using IronPython.Hosting;
namespace LightSwitchApplication
{
public partial class ApplicationDataService
{
partial void ServerCommands_Inserting(ServerCommand entity)
{
switch (entity.ClientCommand)
{
case "RunPythonScript":
var engine = Python.CreateEngine();
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\Temp");
engine.SetSearchPaths(searchPaths);
var mainfile = @"C:\Temp\script.py";
var scope = engine.CreateScope();
engine.CreateScriptSourceFromFile(mainfile).Execute(scope);
var param1 = entity.Param1;
engine.Execute(scope);
How do i reference the server side variable below from the Python script?
entity.Param1
In the python script I've attempted to import a server side class that would
allow me access to the variable
import clr
clr.AddReference("Microsoft.Lightswitch.Application")
but the .Server reference is not available...only the .Base is available.
from Microsoft.Lightswitch.Framework.Base import
I have no idea if the Framework.Server class is even the right one, just
guessing at this point. Thanks!
[](http://i.stack.imgur.com/iZgS7.png)
Answer: You could simply set `entity` as a variable of your scope. You also could pass
it to a function in `script.py`. For example:
Your python script:
class SomeClass:
def do(self, entity):
print entity.Param1
Your c# code will look like this:
var engine = Python.CreateEngine();
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\Temp");
engine.SetSearchPaths(searchPaths);
var mainfile = @"C:\Temp\script.py";
var scope = engine.CreateScope();
// Execute your code
engine.CreateScriptSourceFromFile(mainfile).Execute(scope);
// Create a class instance
var type = scope.GetVariable("SomeClass");
var instance = engine.Operations.CreateInstance(type);
// Call `do` method
engine.Operations.InvokeMember(instance, "do", entity); // PASS YOUR ENTITY HERE
After this, you can access your complete entity in the IronPython script. You
don't need `clr.AddReference("Microsoft.Lightswitch.Application")`.
Also, the second execute (`engine.Execute(scope);`) seems to be not
neccessary. Maybe this helps you.
|
How can I remove a date in the format of ##/##/#### from a string in Python?
Question: I have a text file that have strings that start with the date in the form of
##/##/#### and I want to remove the date and keep to work with the rest of the
text that is in that line. I have been look at regular expressions but cannot
figure out how to do this.
Answer: Regular expressions are a good way to go. If they're always in that format,
then the expression would be:
\d{2}/\d{2}/\d{4}
Note that it doesn't check the validity of the date, i.e., months not 1-12,
etc. an example in python:
import re
expr = re.compile('\d{2}/\d{2}/\d{4}')
line = re.sub(expr, '', input) # replace all dates with ''
This solution would not work if your file contains strings like
"145/10/24045", as it would replace it with "15".
|
re module has no attribute compile
Question: I am trying to use the following command in Python 3:
text = re.compile('attribute')
but it tells me that that 're module has no attribute compile'. Has the
command been updated in Python 3?
Answer: You can debug such scenario by using `imp.find_module()`:
import imp
imp.find_module("re")
It will tell you which `re.py` is imported.
|
beginner python web scrape issue
Question: I have the following html code:
<div class="panel panel-default box">
<div class="panel-heading">
<h2 class="panel-title">December 2015</h2>
</div>
<div class="panel-body">
<ul>
<li>December 30, 2015 - <a href="link">Report</a></li>
<li>December 23, 2015 - <a href="link">Report</a></li>
<li>December 16, 2015 - <a href="link">Report</a></li>
<li>December 9, 2015 - <a href="link">Report</a></li>
<li>December 2, 2015 - <a href="link">Report</a></li>
</ul>
</div>
</div>
I wrote the following python code to scrape some of the content above.
from bs4 import BeautifulSoup
import lxml
import requests
import textwrap
import csv
BASE_URL = "link"
response = requests.get(BASE_URL)
html = response.content
#each monthly list starts with <div class="panel-body">
soup = BeautifulSoup(html,"lxml")
list_of_links = soup.findAll('div', attrbs={'class': "panel-body"})
print list_of_links
For some reason Python keeps returning an empty "list_of_links"
Does anyone know what I'm doing wrong?
Thanks.
Answer: You seem to have a typo here:
attrbs={'class': "panel-body"})
Should be `attrs`, **not** `attrbs`.
|
execute hello world with flask "ImportError: No module named flask"
Question: I'm trying to use flask and python. I did a simple file named `hello.py`. tHis
file contains this code:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def main():
return "Welcome!"
if __name__ == "__main__":
app.run()
This is a simple hello world with flask. I want to execute it but actually, I
have a problem. In the terminal, I typed `python hello.py` and I get this
error:
File "hello.py", line 1, in <module>
from flask import Flask
ImportError: No module named flask
Even that I installed flask globally. I understand that this is a basic
question, but I'm stuck?
Answer: You don't have installed `flask`
## Linux:
Install `flask` as global package:
sudo pip install flask
Install in virtualenv
virtualenv venv
source venv
pip install flask
Install system package
* debian, ubuntu
apt-get install python-flask
* arch
pacman -S python-flask
* fedora
yum install python-flask
Install via [Anaconda](https://store.continuum.io/cshop/anaconda/)
conda install flask
## Windows:
python -m pip install flask
|
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: unexpected end of data
Question: I'm writing a code for stemming a tweet, but I'm having issues with encoding.
When I tried to apply porter stemmer it shows error.Maybe i m not able to
tokenize it properly.
My code is as follows...
import sys
import pandas as pd
import nltk
import scipy as sp
from nltk.classify import NaiveBayesClassifier
from nltk.stem import PorterStemmer
reload(sys)
sys.setdefaultencoding('utf8')
stemmer=nltk.stem.PorterStemmer()
p_test = pd.read_csv('TestSA.csv')
train = pd.read_csv('TrainSA.csv')
def word_feats(words):
return dict([(word, True) for word in words])
for i in range(len(train)-1):
t = []
#train.SentimentText[i] = " ".join(t)
for word in nltk.word_tokenize(train.SentimentText[i]):
t.append(stemmer.stem(word))
train.SentimentText[i] = ' '.join(t)
When I try to execute it returns the error:
* * *
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-10-5aa856d0307f> in <module>()
23 #train.SentimentText[i] = " ".join(t)
24 for word in nltk.word_tokenize(train.SentimentText[i]):
---> 25 t.append(stemmer.stem(word))
26 train.SentimentText[i] = ' '.join(t)
27
/usr/lib/python2.7/site-packages/nltk/stem/porter.pyc in stem(self, word)
631 def stem(self, word):
632 stem = self.stem_word(word.lower(), 0, len(word) - 1)
--> 633 return self._adjust_case(word, stem)
634
635 ## --NLTK--
/usr/lib/python2.7/site-packages/nltk/stem/porter.pyc in _adjust_case(self, word, stem)
602 for x in range(len(stem)):
603 if lower[x] == stem[x]:
--> 604 ret += word[x]
605 else:
606 ret += stem[x]
/usr/lib64/python2.7/encodings/utf_8.pyc in decode(input, errors)
14
15 def decode(input, errors='strict'):
---> 16 return codecs.utf_8_decode(input, errors, True)
17
18 class IncrementalEncoder(codecs.IncrementalEncoder):
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: unexpected end of data
anybody has any clue, wat is wrong with my code.I m stuck with this error.Any
suggestions..?
Answer: I think the key line is 604, one frame above the place which raises the error:
--> 604 ret += word[x]
Probably `ret` is an Unicode string and `word` is a byte string. And you
cannot decode UTF-8 byte by byte, as that loop is trying to do.
The problem is that `read_csv` is returning bytes, and you are trying to do
text processing on those bytes. That simply doesn't work, those bytes have to
be decoded to Unicode first. I think you can use:
pandas.read_csv(filename, encoding='utf-8')
If possible, use Python 3. Then trying to concatenate bytes and unicode will
always raise an error, making it much easier to spot these problems.
|
opencv find centre of face in facedetction
Question: I need to find the centre of a rectangle that gets put around a face when it's
detected in OpenCV. I am using Python in Visual Studio.
Here is the code I am running:
* * *
#!/usr/bin/env python
from cv2 import *
import sys
cascPath = sys.argv[1]
faceCascade = CascadeClassifier(cascPath)
video_capture = VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cvtColor(frame, COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
font = FONT_HERSHEY_SIMPLEX
# Draw text on the frame
putText(frame, 'Hayden' ,(10,100), font, 2,(255,255,255),2,LINE_AA)
# Display the resulting frame
imshow('Video', frame)
if waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
destroyAllWindows()
* * *
All I want to do is find the centre of the rectangle, any help will be greatly
appreciated!
Answer: I'm really sorry but I don't know python. The code for this in C++ is:
Point center = Point(rectangle.x + rectangle.width)/2, (rectangle.y + rectangle.height)/2);
I'd be surprised if this didn't translate almost exactly to python
|
Maya Python script to show numerical vertex translation
Question: I want to write a script for Maya in Python which allows you to see the
numerical translation of a Vertex in a headup display.
So if a pick one Vertex and move it along an axis, in the headup display
should appear the moved value since the start world position of the Vertex.
as example the world position is '20, 20 , 50' of teh vertex and I move it to
'20, 20 , 30' in the headup display should be display '0 0 20'.
I am far away but this is what I have done until now.
import maya.cmds as cmds
selection = cmds.ls(sl=True)
for obj in selection:
vertexWert = cmds.pointPosition( obj , w=True)
print vertexWert
Answer: You can get a notification about the change with an `attributeChanged`
scriptJob on the `.outMesh` attribute of the object to fire a script when the
mesh is edited. However that won't know _why_ the mesh changed: for example it
will fire if you rotate a vertex selection instead of moving it. You'll have
to store a copy of the vert positions and compare the new ones with the old
ones to get the actual difference.
Here's a very basic example which uses prints (the
[headsUpDisplay](http://download.autodesk.com/us/maya/2011help/CommandsPython/headsUpDisplay.html)
command is very wordy so I'll leave that out). I'm also using a global
variable, which in general is a bad idea but it sounds like adding classes
into the problem will make it harder to demonstrate: the 'right' thing to do
is to make a callable class that manages the mesh differences for you.
# to save the mesh positions. This does mean you can only use this code on one object at a time....
global _old_positions
_old_positions = None
# this is the callback function that gets called when the mesh is edited
def update_mesh_positions():
selected = cmds.ls(sl=True, o=True)
if selected:
selected_verts = selected[0] + ".vtx[*]"
global _old_positions
# make sure we have something to work with....
if not _old_positions:
_old_positions = cmds.xform(selected_verts, q=True, t=True, ws=True)
# gets all of the vert positions
new_positions = cmds.xform(selected_verts, q=True, t=True, ws=True)
# unpack the flat list of [x,y,z,x,y,z...] into 3 lists of [x,x], [y,y], etc...
x1 = _old_positions[::3]
y1 = _old_positions[1::3]
z1 = _old_positions[2::3]
x2 = new_positions[::3]
y2 = new_positions[1::3]
z2 = new_positions[2::3]
old_verts = zip(x1, y1, z1)
new_verts = zip(x2, y2, z2)
# compare the old positions and new positions side by side
# using enumerate() to keep track of the indices
for idx, verts in enumerate(zip (old_verts, new_verts)):
old, new = verts
if old != new:
# you'd replace this with the HUD printing code
print idx, ":", new[0] - old[0], new[1] - old[1], new[2] - old[2]
# store the new positions for next time
_old_positions = new_positions
#activate the script job and prime it
cmds.scriptJob(ac= ('pCubeShape1.outMesh', update_mesh_positions))
cmds.select('pCubeShape1')
update_mesh_positions()
# force an update so the first move is caught
This isn't really something Maya is good at doing via script: on big meshes
this will be pretty slow since you're processing a lot of numbers. For small
examples it should work though.
|
how do I disply an np.array in column with xlwings
Question: I have the following code in python with xlwings
@xlfunc
@xlarg('x', 'nparray', ndim=1)
@xlarg('y', 'nparray', ndim=1)
def test_sum(x,y):
return(x+y)
Once in excel, I submit ctrl+shift+Enter but it displays the result in a line
and not in column. How can I correct this ?
Answer: Since you are forcing your inputs to be 1-dimensional numpy arrays of the form
`np.array([1, 2, 3])`, the result is a 1-dim numpy array as well which are
(like simple lists) interpreted as row orientation when written to Excel. To
write an array in column orientation, you'll need to return two dimensional
arrays of the form `np.array([[1], [2], [3]])` or for lists: `[[1], [2],
[3]]`.
In your case, you could simply change `ndim=1` to `ndim=2`and it will be
returned in column orientation if the inputs are columns as well. If you would
like to keep the inputs in 1d (for whatever reason), then you could force the
output into column orientation e.g. by doing this:
from xlwings import xlfunc, xlarg
import numpy as np
@xlfunc
@xlarg('x', 'nparray', ndim=1)
@xlarg('y', 'nparray', ndim=1)
def test_sum(x,y):
return(x+y)[:, np.newaxis]
You're right that the [docs](http://docs.xlwings.org/udfs.html#number-of-
array-dimensions-ndim) aren't clear enough about this.
|
How to post a term with brackets with PHP to Sympy
Question: I want to post a term like
5+(x+4)
from PHP via Python to Sympy in order to simplify the expression.
For that I'm using folowing code: PHP:
$param="5+(x+4)";
$command="python $PathToPySkript $param"; //# '$param2' '$param3'";
$buffer='';
ob_start(); // prevent outputting till you are done
passthru($command);
$buffer=ob_get_contents();
ob_end_clean();
PY:
import sys
from sympy import *
from sympy.parsing.sympy_parser import *
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
transformations=(standard_transformations + (implicit_multiplication_application,) + (function_exponentiation,)+(convert_xor,))
print(latex(parse_expr(sys.argv[1], transformations=transformations)))
I'm able to post terms like
5+x+4
without any problem, retrieve the solution and display it on my website.
But for any term with brackets like ( or { or [, the processing throw errors
or I would get no notice in PHP.
I tried also to double the brackets like (( or {{ or [[ but this will have no
effekt.
Has anybody an idea how to get a solution for my problem.
Answer: Okay, I found a solution for myself! The problem was that I have set the
string like these:
PHP:
$param="5+(x+4)";
I changed this to:
$param="'5+(x+4)'";
Now it works as expected...
|
Python Permutation taken at a time
Question: I wrote nested loops to give me all posible permutations of all letter of
alphabet taken 4 letters at a time.
def permutation():
import string
alphabet = string.ascii_lowercase
perm = []
for item1 in alphabet:
for item2 in alphabet:
for item3 in alphabet:
for item4 in alphabet:
perm += [item1 + item2 + item3 + item4]
return perm
So, when I do
permutation()
I get
['aaaa',
'aaab',
'aaac',
'aaad',
'aaae',
...
'zzzz']
Although this solves my particular problem (4 digit permutation), it's not an
neat solution. Furthermore, if I'd like to make a n digit permutation (say, 10
digits), the nested loops would be a mess.
So, I was thinking I you can tell me how to implement this nested loops as
some kind of function, using recursion or something of the sort.
By the way, I know that in this particular problem (4 digit permutation), I
could use python libraries:
def permutation():
from itertools import product
import string
alphabet = string.ascii_lowercase
perm = [ ''.join(p) for p in list(product(list(alphabet),repeat = 4)) ]
return perm
and this is what I would use in real life, but here I'm trying to figure out
the algorithm of the permutation of letters of alphabet taken n letters at a
time.
Answer: First, break this down into the two basic points of recursion: degenerate step
(final condition) and recursion step. Here, our final condition is to return
the alphabet when we want strings of length 1.
For longer strings (length n), prepend each letter of the alphabet to all
permutations of length n-1.
import string
alphabet = string.ascii_lowercase
def permutation(n):
return [c for c in alphabet] if n == 1 \
else [c + n_perm for c in alphabet for n_perm in permutation(n-1)]
print permutation(1)
print permutation(2)
|
Python send a command to Xterm
Question: I have a python script that opens up file for me in emacs, and to do that it
calls a process in xterm like so
"""AutoEmacs Document"""
# imports
import sys
import os
import psutil
import subprocess
from argparse import ArgumentParser
# constants
xlaunch_config = "C:\\cygwin64\\home\\nalis\\Documents\\experiments\\emacs\\Autoemacs\\config.xlaunch"
script = "xterm -display :0 -e emacs-w32 --visit {0}"
# exception classes
# interface functions
# classes
# internal functions & classes
def xlaunch_check():
# checks if an instance of Xlaunch is running
xlaunch_state = []
for p in psutil.process_iter(): #list all running process
try:
if p.name() == 'xlaunch.exe':# once xlaunch is found make an object
xlaunch_state.append(p)
except psutil.Error: # if xlaunch is not found return false
return False
return xlaunch_state != [] #double checks that xlaunch is running
def xlaunch_run(run):
if run == False:
os.startfile(xlaunch_config)
return 0 #Launched
else:
return 1 #Already Running
def emacs_run(f):
subprocess.Popen(script.format(f))
return 0#Launched Sucessfully
def sysarg():
f = sys.argv[1]
il = f.split()
l = il[0].split('\\')
return l[(len(l) - 1)]
def main():
f = sysarg()
xlaunch_running = xlaunch_check()
xlaunch_run(xlaunch_running)
emacs_run(f)
return 0
if __name__ == '__main__':
status = main()
sys.exit(status)
`
and it works fairly fine with the occasional bug, but I want to make it a
little more versatile by having python send the Xterm console it launches
commands after it launched like "-e emacs-w32" and such based off of the input
it receives. I've already tried something like this:
# A test to send Xterm commands
import subprocess
xterm = subprocess.Popen('xterm -display :0', shell=True)
xterm.communicate('-e emacs')
but that doesn't seem to do anything. besides launch the terminal. I've done
some research on the matter but it has only left me confused. Some help would
be very much appreciated.
Answer: To open emacs in terminal emulator, use this:
Linux;
Popen(['xterm', '-e', 'emacs'])
Windows:
Popen(['cmd', '/K', 'emacs'])
For cygwin use:
Popen(['mintty', '--hold', 'error', '--exec', 'emacs'])
|
Calling C++ from python using boost python: introductory example not working
Question: I am interested in using Boost.Python to call C++ functions from my Python
scripts.
This example
[here](http://www.boost.org/doc/libs/1_60_0/libs/python/doc/html/tutorial/index.html#tutorial.quickstart)
is an introductory example on Boost python's home-pagewhich I am unable to
run. Can someone help me out with this?
This is what I tried
I created a file named hello_ext.cpp as follows
#include <boost/python.hpp>
char const* greet()
{
return "hello, world";
}
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
I then compiled it to a shared library as follows
g++ -c -Wall -Werror -fpic hello_ext.cpp -I/usr/include/python2.7
g++ -shared -o libhello_ext.so hello_ext.o
Finally firing up the ipython interpreter I tried to `import hello_ext` but
got the following error message. Where did I go wrong?
In [1]: import hello_ext
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-18c4d6548768> in <module>()
----> 1 import hello_ext
ImportError: ./hello_ext.so: undefined symbol: _ZNK5boost6python7objects21py_function_impl_base9max_arityEv
Answer: You should include some libraries in your link command,
g++ -shared -Wl,--no-undefined hello_ext.o -lboost_python -lpython2.7 -o hello_ext.so
With `-Wl,--no-undefined` linker option it will be an error if some symbols
are missing.
|
how to create a list sequence in python containing all possible pairs an equal number of times?
Question: Given the letters `x,y` is there a way to write a python function that returns
a list sequence containing all possible pairs (`[x,x], [x,y], [y,x], [y,y]`)
an equal number of times?
for example can I write a function that takes the input (eg `[x,y]`) and the
number of times each possible pair should appear (eg `2`), and then returns,
for example, the list sequence: `[x x x y y x y y x]` ?
Preferably I would like the function to generate a "random" sequence so it
could also return:
[y x y y x x x y y]
In both cases `[x,x] [x,y] [y,x]` and `[y,y]` appear exactly twice.
Ideally, I would like to find a solution that also worked with for example 4
letters `[x,y,z,w]`.
Answer: Based on your edits, the following should conduct the tour to which you were
referring.
import random
import itertools
def generate_sequence(alphabet, num_repeats):
# generate the permutations of the list of size 2
# repeated `num_repeats` times
perms = [(letter1, letter2) for letter1, letter2 in itertools.product(alphabet, alphabet) for i in xrange(num_repeats)]
# save the original length of `perm` for later
perm_len = len(perms)
# randomly choose a starting point and add it to our result
curr_s, curr_e = random.choice(perms)
result = [curr_s, curr_e]
# remove the starting point from the list... on to the next one
perms.remove((curr_s, curr_e))
# while we still have pairs in `perms`...
while len(perms):
# get all possible next pairs if the end of the current pair
# equals the beginning of the next pair
next_vals = [(s,e) for s,e in perms if s == curr_e]
# if there aren't anymore, we may have exhausted the pairs that
# start with `curr_e`, in which case choose a new random pair
if len(next_vals) != 0:
next_s, next_e = random.choice(next_vals)
else:
next_s, next_e = random.choice(perms)
# remove the next pair from `perm` and append it to the `result`
perms.remove((next_s, next_e))
result.append(next_e)
# set the current pair to the next pair and continue iterating...
curr_s, curr_e = next_s, next_e
return result
alphabet = ('x', 'y', 'z')
num_repeats = 2
print generate_sequence(alphabet, num_repeats)
This outputs
['z', 'z', 'z', 'x', 'x', 'y', 'z', 'y', 'y', 'z', 'y', 'x', 'y', 'x', 'z', 'x',
'z', 'y', 'x']
|
Python: Trying to access different dictionaries in an imported file, based on variable given
Question: I have been making a simple turn based 'board game' in python using a separate
file to hold all of the data, such as what the attributes of a space is and
the attributes of the players. All of this is stored in separate dictionaries.
My problem lies in when I need to access or change data for specific players.
So far I have been doing it like this just so I can get it working and just
focus on making it work:
def function(self): #self is the player number for that turn
if self == 1:
database.player1.update(data=0)
if self == 2:
database.player2.update(data=0)
...
and so on for all four players.
So what I tried to do instead was have something that went like this:
def function(self):
a = 'player' + (self)
database.a.update(data=a)
However unsurprisingly this won't work, but is there a way to get something
like this where I am able to determine which dictionary to access based on
self?
Answer: Use getattr
def function(self):
a = 'player'+str(self)
getattr(database,a).update(data=0)
`getattr` takes two arguments - the first is the object on which to retrieve
the attribute (in your case your `database` module), the second is the name
(string) of the attribute to retrieve (in your case `"player1"`, `"player2"`,
etc).
|
How to use trailing rows on a column for calculations on that same column | Pandas Python
Question: I'm trying to figure out how to compare the element of the previous row of a
column to a different column on the current row in a Pandas DataFrame. For
example:
data = pd.DataFrame({'a':['1','1','1','1','1'],'b':['0','0','1','0','0']})
Output:
a b
0 1 0
1 1 0
2 1 1
3 1 0
4 1 0
And now I want to make a new column that asks if (data['a'] + data['b']) is
greater then the previous value of that same column. Theoretically:
data['c'] = np.where(data['a']==( the previous row value of data['a'] ),min((data['b']+( the previous row value of data['c'] )),1),data['b'])
So that I can theoretically output:
a b c
0 1 0 0
1 1 0 0
2 1 1 1
3 1 0 1
4 1 0 1
I'm wondering how to do this because I'm trying to recreate this excel
conditional statement: =IF(A70=A69,MIN((P70+Q69),1),P70)
where data['a'] = column A and data['b'] = column P.
If anyone has any ideas on how to do this, I'd greatly appreciate your advice.
Answer: According to your statement: _'new column that asks if (data['a'] + data['b'])
is greater then the previous value of that same column'_ I can suggest you to
solve it by this way:
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'a':['1','1','1','1','1'],'b':['0','0','1','0','3']})
>>> df
a b
0 1 0
1 1 0
2 1 1
3 1 0
4 1 3
>>> df['c'] = np.where(df['a']+df['b'] > df['a'].shift(1)+df['b'].shift(1), 1, 0)
>>> df
a b c
0 1 0 0
1 1 0 0
2 1 1 1
3 1 0 0
4 1 3 1
But it doesn't looking for _'previous value of that same column'_. If you
would try to write `df['c'].shift(1)` in `np.where()`, it gonna to raise
_KeyError: 'c'_.
|
Python mechanize or any other library to login into google to read groups
Question: I am trying to read google groups so it is expecting to login into google
account.
I used Mechanize for that but I am getting SSL verification error
from mechanize import Browse
br=Browse()
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_refresh(False)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open("https groups login url") now here it hits the SSL verification error.(“SSL: CERTIFICATE_VERIFY_FAILED” Error)
1. is there anyway to avoid SSL verification issue?
2. is there any library that I can use?
Note: I tried with UrlLib2 I am able to set empty SSL context and able to
avoid this SSL certificate issue but handling login is big issue so I am
trying to use some browser behavior module.
Answer: See ["SSL: CERTIFICATE_VERIFY_FAILED"
Error](http://stackoverflow.com/questions/27835619/ssl-certificate-verify-
failed-error/27847883) for further explanation, but here's the quick fix:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
|
Nested for loops to recursive function in Python
Question: I have three lists, each one with several possible values.
probs = ([0.1,0.1,0.2], \
[0.7,0.9], \
[0.5,0.4,0.1])
I want to test all possible combinations of choosing one element from each
list. So, 3*2*3=18 possible combinations in this example. In the end, I want
to choose the most favourable combinations according to some criteria. This
is:
[<index in row 0> , <index in row 1> , <index in row 2> , <criteria value>]
I can accomplish my task by using three nested for loops (which I did).
However, in the real application of this code, I will have a variable number
of lists. Because of that, it seems the solution would be using a recursive
function with a for loop inside it (which I did as well). The code:
# three rows. Test all combinations of one element from each row
# This is [value form row0, value from row1, value from row2]
# So: 3*2*3 = 18 possible combinations
probs = ([0.1,0.1,0.2], \
[0.7,0.9], \
[0.5,0.4,0.1])
meu = [] # The list that will store the best combinations in the recursion
#######################################################
def main():
choice = [] #the list that will store the best comb in the nested for
# accomplish by nested for loops
for n0 in range(len(probs[0])):
for n1 in range(len(probs[1])):
for n2 in range(len(probs[2])):
w = probs[0][n0] * probs[1][n1] * probs[2][n2]
cmb = [n0,n1,n2,w]
if len(choice) == 0:
choice.append(cmb)
elif len(choice) < 5:
for i in range(len(choice)+1):
if i == len(choice):
choice.append(cmb)
break
if w < choice[i][3]:
choice.insert(i,cmb)
break
else:
for i in range(len(choice)):
if w < choice[i][3]:
choice.insert(i,cmb)
del choice[-1]
break
# using recursive function
combinations(0,[])
#both results
print('By loops:')
print(choice)
print('By recursion:')
print(meu)
#######################################################
def combinations(step,cmb):
# Why does 'meu' needs to be global
if step < len(probs):
for i in range(len(probs[step])):
cmb = cmb[0:step] # I guess this is the same problem I dont understand recursion
# But, unlike 'meu', here I could use this workaround
cmb.append(i)
combinations(step+1,cmb)
else:
w = 1
for n in range(len(cmb)):
w *= probs[n][cmb[n]]
cmb.append(w)
if len(meu) == 0:
meu.append(cmb)
elif len(meu) < 5:
for i in range(len(meu)+1):
if i == len(meu):
meu.append(cmb)
break
if w < meu[i][-1]:
meu.insert(i,cmb)
break
else:
for i in range(len(meu)):
if w < meu[i][-1]:
meu.insert(i,cmb)
del meu[-1]
break
return
######################################################
main()
It outputs, as I wanted:
By loops:
[[0, 0, 2, 0.006999999999999999], [1, 0, 2, 0.006999999999999999], [0, 1, 2, 0.009000000000000001], [1, 1, 2, 0.009000000000000001], [2, 0, 2, 0.013999999999999999]]
By recursion:
[[0, 0, 2, 0.006999999999999999], [1, 0, 2, 0.006999999999999999], [0, 1, 2, 0.009000000000000001], [1, 1, 2, 0.009000000000000001], [2, 0, 2, 0.013999999999999999]]
Initially, I wanted to use the 'meu' list as internal of the function,
because, I thought, it would be better to avoid global variables (perhaps
not... I'm a newbie). The problem was I could not come up with a code that
would pass both 'meu' and 'cmb' between depths to give the same effect of the
nested loops.
How could I implement a recursive function with internal 'meu' instead of
being a global list? What am I missing from recursion concept? Thanks.
++++++++++++++++++++++++++++++++++
Example of a failed function:
def combinations(choice,step,cmb):
if step < len(probs):
for i in range(len(probs[step])):
cmb = cmb[0:step] #workaroud for cmb
cmb.append(i)
choice = combinations(choice,step+1,cmb)
else:
w = 1
for n in range(len(cmb)):
w *= probs[n][cmb[n]]
cmb.append(w)
if len(choice) == 0:
choice.append(cmb)
elif len(choice) < 5:
for i in range(len(choice)+1):
if i == len(choice):
choice.append(cmb)
break
if w < choice[i][-1]:
choice.insert(i,cmb)
break
else:
for i in range(len(choice)):
if w < choice[i][-1]:
choice.insert(i,cmb)
del choice[-1]
break
return choice
Called by:
choice = combinations([],0,[])
Answer: Don't reinvent the wheel (recursively or not): use the included batteries. The
problem you are trying to solve is extremely common and so a solution is
included in Python's standard library.
What you want—every combination of every value from some number of lists—is
called the Cartesian product of those lists. `itertools.product` exists to
generate those for you.
import itertools
probs = ([0.1, 0.1, 0.2],
[0.7, 0.9],
[0.5, 0.4, 0.1])
for prob in itertools.product(*probs):
print prob
# prob is a tuple containing one combination of the variables
# from each of the input lists, do with it what you will
If you want to know what index each item comes from, the easiest way is to
just pass the indices to `product()` rather than the values. You can easily
get that using `range()`.
for indices in itertools.product(*(range(len(p)) for p in probs)):
# get the values corresponding to the indices
prob = [probs[x][indices[x]] for x in range(len(probs))]
print indices, prob
Or you could use `enumerate()` \-- this way, each item in the product is a
tuple containing its index and its values (not two separate lists the way you
get them in the above method):
for item in itertools.product(*(enumerate(p) for p in probs)):
print item
|
How to run pip of different version of python using python command?
Question: I'm now currently using Python on ubuntu 15.10
But in my OS, I have many different python version installed:
* Python (2.7.9)
* Python3 (3.4.3)
* Python3.5
* PyPy
So, I got mess about the version of their package environment, for example, if
I run:
pip3 install django
In fact I cannot import django inside `python3.5`.
Is there any efficiently way to call the relating version of `pip`?
_PS: Don't let me use virtualenv, I know about it and is finding another
solution._
Answer: Finally I found the solution myself, see the Docs:
<https://docs.python.org/3/installing/index.html?highlight=pip#work-with-
multiple-versions-of-python-installed-in-parallel>
Just call:
pythonXX -m pip install SomePackage
That would work separately for each version of installed python.
Also, according to the docs, if we want to do the same thing in windows, the
command is a bit different:
py -2 -m pip install SomePackage # default Python 2
py -2.7 -m pip install SomePackage # specifically Python 2.7
py -3 -m pip install SomePackage # default Python 3
py -3.4 -m pip install SomePackage # specifically Python 3.4
|
Preferred way to resolve package root in Python
Question: I am aware of the following way to determine the directory in which a module
is executing:
os.path.dirname(os.path.abspath(__file__))
Now let's say I have a package with some modules that need to read a text file
located in a subdirectory. Something like this:
|-- package
| |-- __init__.py
| |-- module1.py
| |-- subdirectory1
| | |-- module2.py
| |-- subdirectory2
| | |-- file.txt
Let's also say I don't want to use relative paths to the file. My intuition is
that it would be best to have a global variable defined somewhere in the
package root that gives the absolute path to the package (e.g. the above line
of code) and which could be imported by different modules whenever they needed
to reference a file inside the package. But where would this variable go? In
its own module? Or is it just better for each module to grab its own absolute
path, get the package root from that, then append on the location of the file?
Edit: another idea is to store this in `os.environ` and have the modules get
it from there. Maybe put the following line in the top level `__init__.py`:
os.environ['MY_PACKAGE_ROOT'] = os.path.dirname(os.path.abspath(__file__))
Answer: You should use the import system. `subdirectory1` and `subdirectory2` should
be packages as well (you can make them so by adding an `__init__.py` file to
them, and then you can use use Python's normal import mechanism to reference
modules:
import package.module1
import package.subdirectory1.module2
import package.subdirectory2.file
and so forth.
|
Why do imports fail in setuptools entry_point scripts, but not in python interpreter?
Question: I have the following project structure:
project
|-project.py
|-__init__.py
|-setup.py
|-lib
|-__init__.py
|-project
|-__init__.py
|-tools.py
with `project.py`:
from project.lib import *
def main():
print("main")
tool()
if __name__ == "__main__":
main()
`setup.py`:
from setuptools import setup
setup(
name = "project",
version="1.0",
packages = ["project", "project.lib"],
package_dir = {"project": ".", "project.lib": 'lib/project'},
entry_points={
'console_scripts': [
'project = project.project:main',
],
},
)
`tools.py`:
def tool():
print("tool")
If I run
import project.lib.tools
project.lib.tools.tool()
it works as expected, but running the command `project` fails with
Traceback (most recent call last):
File "/usr/local/bin/project", line 9, in <module>
load_entry_point('project==1.0', 'console_scripts', 'project')()
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 568, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2720, in load_entry_point
return ep.load()
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2380, in load
return self.resolve()
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2386, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "build/bdist.linux-x86_64/egg/project/project.py", line 3, in <module>
ImportError: No module named lib
I don't understand why the two interpreters don't have the same default import
pathes.
The reason for this setup is that I want to be able to `import
project.lib.tools`, but keep the directory structure with `lib/project`.
The complete `distutils` documentation seriously doesn't say a word on how one
can import packages after they have been distributed (the difference of
`setuptools` and `distutils` isn't less misterious - no way of knowing whether
the behavior of `distutils` is extended here or not).
I'm using `setuptools` 18.4-1 with `python` 2.7 on Ubuntu 15.10.
If I change the project structure and `setup.py` as suggested in
@AnttiHaapala's answer I'm getting
$ project
Traceback (most recent call last):
File "/usr/local/bin/project", line 9, in <module>
load_entry_point('project==1.0', 'console_scripts', 'project')()
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 568, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2720, in load_entry_point
return ep.load()
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2380, in load
return self.resolve()
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2386, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "build/bdist.linux-x86_64/egg/project/project.py", line 3, in <module>
ImportError: No module named lib
Answer: Your project structure seems to be b0rken. The standard layout for a
distribution is that the `setup.py` is on the top-level. Your project would
then have 1 (top-level) package, namely `project`, with sub-package
`project.lib`. Thus we get the following directory layout:
Project-0.42/
+- project/
| +- __init__.py
| +- lib/
| | +- __init__.py
| | +- tools.py
| +- project.py
+- setup.py
Then in your `setup.py` you can simply do
from setuptools import find_packages
setup(
...
# remove package_dir, it is unnecessary
packages=find_packages(),
...
)
The `package_dir` really does not handle top-level + sub-packages
simultaneously very well. After that `pip remove project` so many times that
you can be certain you do not have any buggy versions of it installed in the
site-packages, and then run `python setup.py develop` to link the source into
`site-packages`.
* * *
After that, the problem is that you're using Python 2 with its broken import
system which assumes relative imports. In `project.py`, your `import
project.lib` assumes a **relative** import by default, and it tries to
actually import `project.project.lib`. As this is not what you want, you
should add
from __future__ import absolute_import
at the top of that file. I seriously suggest that you add this (and why not
also the `division` import if you're using `/` operator anywhere at all), to
avoid these pitfalls and to stay Python 3 compatible.
|
SWIG wrapping issues with C++ --> python
Question: I'm trying to wrap a C++ file that depends on another C++ file (global.cpp) by
using SWIG. I was able to get the first one to work fine, but this nested
dependence seems to cause an issue. Here is my setup:
## position.i
%module position
%include global.i
%{
#include "pos.h"
%}
%include "pos.h"
%include "global.h"
... (functions declared)
# position.cpp
#include <algorithm>
#include "global.h"
#include "pos.h"
...(functions implemented)
# position.h
prototypes
I then do this.
swig -c++ -python -builtin position.i
g++ -O2 -fPIC -c position.cpp
g++ -O2 -fPIC -c -I/Users/aaron/anaconda/include/python3.5m position_wrap.cxx
I have the two object files and then I bind them with
g++ -dynamiclib -lpython position.o global.o position_wrap.o -o _position.so
I've tried a number of different ways of doing this after perusing through SO
and I have been totally stifled.
I get an error
...
"_PyUnicode_FromFormat", referenced from:
SwigPyObject_repr(SwigPyObject*) in position_wrap.o
SwigPyPacked_repr(SwigPyPacked*) in position_wrap.o
SwigPyPacked_str(SwigPyPacked*) in position_wrap.o
"_PyUnicode_FromString", referenced from:
_PyInit__position in position_wrap.o
SWIG_Python_DestroyModule(_object*) in position_wrap.o
SwigPyPacked_str(SwigPyPacked*) in position_wrap.o
"_Py_DecRef", referenced from:
SwigPyObject_repr(SwigPyObject*) in position_wrap.o
"__PyObject_New", referenced from:
_PyInit__position in position_wrap.o
...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
with compilation. I've tried different linker flags by going to the path
`python3-config --ldflags` states. I've added the `-std=libstdc++` flag. I
once somehow got the module to generate, but upon import to python was faced
with :
ImportError: dlopen(/Users/aaron/Desktop/swigdPython/src/_position.cpython-35m-darwin.so, 2):
Symbol not found: __Z10e_to_ed Referenced from:
/Users/aaron/Desktop/swigdPython/src/_position.cpython-35m-darwin.so
Expected in: dynamic lookup"
I'm at a loss trying to figure out the proper way to link these files and was
hoping someone here had some insight.
Answer: You should specify the library last on the link command line:
g++ -dynamiclib position.o global.o position_wrap.o -o _position.so -lpython
|
Downloading url content using BeautifulSoup in Python
Question: > None Type Object Has No attribute text. Line 16
from bs4 import BeautifulSoup, SoupStrainer
try:
import urllib.request as urllib2
except ImportError:
import urllib2
import re
def main():
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = 'http://www.cnn.com/2013/10/29/us/florida-shooting-cell-phone-blocks-bullet/index.html?hpt=ju_c2'
soup = BeautifulSoup(opener.open(url))
#1) Link to the website
#2) Date article published
date = soup.find("div", {"class":"cnn_strytmstmp"}).text.encode('utf-8')
#3) title of article
title = soup.find("div", {"id":"cnnContentContainer"}).find('h1').text.encode('utf-8')
#4) Text of the article
paragraphs = soup.find('div', {"class":"cnn_strycntntlft"}).find_all('p')
text = " ".join([ paragraph.text.encode('utf-8') for paragraph in paragraphs])
print (url)
print (date)
print (title)
print (text)
if __name__ == '__main__':
main()
Answer: Here is a snippet which will get the details you wanted from the page.
from bs4 import BeautifulSoup
import requests
def get_new_cnn(url):
response = requests.get(url, headers={'User-agent': 'Mozilla/5.0'})
soup = BeautifulSoup(response.text, 'html.parser')
# 1) Link to the website
print(url)
# 2) Date article published
date = soup.find("p", attrs={"class": "update-time"})
print(date.text.replace('Updated ', ''))
# 3) title of article
title = soup.find("h1", attrs={"class": "pg-headline"})
print(title.text.encode('UTF-8'))
# 4) Text of the article
paragraphs = soup.find_all('p', attrs={"class": "zn-body__paragraph"})
text = " ".join([paragraph.text for paragraph in paragraphs])
print(text.encode('UTF-8'))
src_url = 'http://www.cnn.com/2013/10/29/us/florida-shooting-cell-phone-blocks-bullet/index.html?hpt=ju_c2'
get_new_cnn(src_url)
|
Comparing two text files in python and print the difference in two files with command run on the device
Question: I am new to Python. I had written the script to fetch the data from juniper
devices and output is like:
Output contains output data from show version and this command is included as
well.I am fine until this point.I am facing issues with comparing two text
files line by line and printing the difference.
Requirement is to print the difference under every command suppose show
version if there is no difference between the file then it should print there
is no difference. if there is any thing changed in 2nd file . It should print
that difference
Thanks in advance!!
Answer: You may use [difflib](https://docs.python.org/2/library/difflib.html).
> This module provides classes and functions for comparing sequences. It can
> be used for example, for comparing files, and can produce difference
> information in various formats, including HTML and context and unified
> diffs.
`unified_diff()` may be helpful.
> `difflib.unified_diff(a, b[, fromfile][, tofile][, fromfiledate][,
> tofiledate][, n][, lineterm])`
>
> Compare a and b (lists of strings); return a delta (a generator generating
> the delta lines) in unified diff format.
import os
import difflib
with open('a.txt', 'rb') as f:
a = f.readlines()
with open('a.txt', 'rb') as f:
b = f.readlines()
print os.linesep.join(difflib.unified_diff(a,b))
Sample output, from docs
@@ -1,4 +1,4 @@
-bacon
-eggs
-ham
+python
+eggy
+hamster
guido
|
cx_freeze converted GUI-app (tkinter) crashes after presssing plot-Button
Question: I've been dealing with this for days now and hope to finde some help. I
developed a GUI-application with imported modules tkinter, numpy, scipy,
matplotlib, which runs fine in python itself. After having converted to an
*.exe everything works as expected, but NOT the matplotlib section. When I
press my defined plot-Button, the *.exe simply closes and doesn't show any
plots. So I thought to make a minimalistic example, where I simply plot a sin-
function and I'm facing the same issue: Works perfect in python, when
converting it to an *.exe it crashes when pressing the plot Button. The
minimalistic example is here:
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
class MainWindow(tk.Frame):
def __init__(self):
tk.Frame.__init__(self,bg='#9C9C9C',relief="flat", bd=10)
self.place(width=x,height=y)
self.create_widgets()
def function(self):
datax = np.arange(-50,50,0.1)
datay = np.sin(datax)
plt.plot(datax,datay)
plt.show()
def create_widgets(self):
plot = tk.Button(self, text='PLOT', command=self.function)
plot.pack()
x,y=120,300
root=tk.Tk()
root.geometry(str(x)+"x"+str(y))
app = MainWindow()
app.mainloop()
And see my corresponding "setup.py" for converting with cx_freeze.
import cx_Freeze
import matplotlib
import sys
import numpy
import tkinter
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [cx_Freeze.Executable("test.py", base=base)]
build_exe_options = {"includes": ["matplotlib.backends.backend_tkagg","matplotlib.pyplot",
"tkinter.filedialog","numpy"],
"include_files":[(matplotlib.get_data_path(), "mpl-data")],
"excludes":[],
}
cx_Freeze.setup(
name = "test it",
options = {"build_exe": build_exe_options},
version = "1.0",
description = "I test it",
executables = executables)
Any ideas that might solve the issue are highly appreciated. I'm working on a
64-bit Windows10 machine and I'm using the WinPython Distribution with Python
3.4.3.
Answer: I found a potential solution (or at least an explanation) for this problem
while testing PyInstaller with the same **test.py**. I received error message
about a dll file being missing, that file being **mkl_intel_thread.dll**.
I searched for that file and it was found inside **numpy** folder. I copied
files matching **mkl_*.dll** and also **libiomp5md.dll** to the same directory
where the **test.exe** created by `python setup.py build` was. After this the
minimal **test.exe** showed the matplotlib window when pressing the **plot**
button.
The files were located in folder **lib\site-packages\numpy\core**.
|
how to include PyOpenSSL in a python package
Question: I need to deploy an application on AWS Lambda in python . This app is based on
Google API SDK, which require a crypto library such as pyOpenSSL. But,
contrary to other libs which are included in my package by doing something
like this :
pip install myLib -t \my_path\to_my_package\
, the pyOpenSSL seems to be a part of python. It's implemented while compiling
or via
`apt-get install pyopenssl`.
I have no clue on what to do to import this lib without depending on the
python version and its modules.
Thanks in advance
Answer: The solution was to install the package "Crypto" in my package and make a :
import Crypto
That solved the problem.
|
how run pybottle in vagrant
Question: I have this Vagrant file
# encoding: utf-8
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/trusty64"
config.ssh.forward_agent = true
config.vm.boot_timeout = 300
config.vm.network "private_network", ip: "192.168.30.20"
config.vm.network :forwarded_port, guest: 8080, host: 8080
config.vm.synced_folder "", "/vagrant", type: "nfs"
config.vm.provision "shell", inline: <<-SHELL
apt-get install python-pip build-essential python-dev -y
pip install bottle
SHELL
config.vm.provider "virtualbox" do |v|
v.name = "M101P"
v.memory = 524
end
config.vm.define :M101P do |t|
config.vm.hostname = "M101P"
end
end
This is a vagrant machine for learn pybottle...
and i have this code: (hello.py)
from bottle import route, run, template
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(host='localhost', port=8080, debug=True)
But, when i tray to access to the server, after make
> python hello.py
python hello_bottle.py
Bottle v0.12.9 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.
the server its running, but if y tray to access...
curl 192.168.30.20:8080/hello/world
curl: (7) Failed to connect to 192.168.30.20 port 8080: Connection refused
what i may be doing wrong?
Answer: The server just binds to localhost which is 127.0.0.1; if You want to access
the server via the server ip You have to change
run(host='localhost', port=8080, debug=True)
to
run(host='0.0.0.0', port=8080, debug=True)
|
Where can I find the admin code for uploading an image in django?
Question: I'm currently coding an image upload in a view and I want to compare it to the
code the admin uses for uploading images. Is there code the admin generates
the file forms from? **Where can I find the python code to an admin image/file
upload?**
I'm using ubuntu 14, python 2.7 and django 1.9.
I have been searching around in here for the admin code for uploading files,
but I cannot find it:
/usr/local/lib/python2.7/dist-packages/django/
This is my image upload code in my view I want to compare to the admin image
upload code:
avatarFile=request.FILES["avatar_im"]
print(avatarFile)
for key, file in request.FILES.items():
path = file.name
path = "images/"+path
dest = open(path, 'w')
if file.multiple_chunks:
for a in file.chunks():
dest.write(a)
else:
dest.write(file.read())
dest.close()
I'm trying to understand how my admin uploads files to my _MEDIA_ROOT/images_
, and why my code uploads to my _PROJECT_ROOT/images_ folder.
PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'static_in_pro/media')
Answer: I think the code used for file uploading stays inside
`django.core.files.storage.FileSystemStorage`
and
`django.core.files.move`
If you want to upload files in the directory `MEDIA_ROOT/images/` then just
use:
import os
from django.conf import settings
...
...
path = os.path.join(settings.MEDIA_ROOT, 'images', file.name)
|
Processing objects of different classes in Python in parallel
Question: I have 6 different classes.
In main, I am creating one object of each class.
I want to call `eachObject.processFiles()` of each object parallely.
The processFiles method processes the object files by reading them,
manipulates the data, and save it in persistent object. Each processFiles call
takes around 5 minutes. If it is done sequentially then main is taking around
30 min.
I am right now doing it sequentially, but I want to speed up the 6 objects'
processing their files in minimum cpu time. All objects are independent of
each other, and I think multithreaded way would be efficient. But I haven't
done multi threading any before. So wanted to know if it would be safe to do
that, and how to do that. A code snippet would help.
How can I do it in parallel?
class system(object):
def __init__(self, leNameList):
self.files = fileNameList
def processFiles(self):
self.feeds= self.readFiles()
self.processFeeds()
class A(system):
def processFeeds(self):
""" process the feed
in A way """
class B(system):
def processFeeds(self):
""" process the feed
in B way """
def main():
aObj = A(fileList)
bObj = B(fileList2)
aObj.processFiles()
bObj.processFiles()
Answer: Use the
[`multiprocessing`](https://docs.python.org/2/library/multiprocessing.html)
module.
import multiprocessing
class system(object):
def __init__(self, fileNameList):
self.files = fileNameList
def processFiles(self):
# self.feeds= self.readFiles()
return self.processFeeds()
class A(system):
def processFeeds(self):
return ["A feed", "example data"] + self.files
class B(system):
def processFeeds(self):
return ["B feed", "hello world"] + self.files
def process_file_task(processor):
return processor.processFiles()
def main():
aObj = A(["a"])
bObj = B(["b"])
data = multiprocessing.Pool().map(process_file_task, [aObj, bObj])
print(data)
Here I've populated your code with example data, so that you can test drive
this solution out of the box, but the gist of it is:
* Instead of altering global variables or object state, return the data you generate.
* Use `multiprocessing.Pool().map` to execute the functions in different processes and return each result in order.
The drawback to this is that `multiprocessing` can be a bit finicky to work
with at times, and you have to ensure that everything passing process
boundaries can be pickled.
* * *
One more thing to check in your code is the file lists. If they have a lot of
files in common, you should separate the process of file reading out and
ensure that the same file doesn't have to be read twice.
|
How do I pass function definition to python script as string
Question: I want to pass **function definition** to a python command line script. What
is the best way to do this? I am using python 2. Suppose i have a script like
this:
#myscript.py
x = load_some_data()
my_function = load_function_definition_from_command_line()
print my_function(x)
And i want to call it like this: `python myscript.py 'def fun(x): return
len(x)'`
How do i perform the `load_function_definition_from_command_line` part ?
I imagine a workaround:
1. get the string function definition from command line
2. write it to a file with .py extension in some temp directory
3. load the definition from file using solutions from this question: [How to import a module given the full path?](http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path)
4. execute
5. cleanup
But I am sure there must be a better way.
Answer: You can use `eval` to run code defined in a string. Like so:
import sys
x = load_some_data()
function = eval("".join(sys.argv[1:]))
print(function(x))
With your specific example though you might have to use something like `lambda
x: len(x)`
As @Jan-Spurny rightly points out: "Never, never, never use eval unless you're
absolutely sure there is no other way. And even then you should stop and think
again."
In my mind the better strategy would be to turn the data loader and executor
into a module with a method that takes a function as an argument and runs the
desired code. The end result something like this:
import data_loader_and_executor
def function(x):
return len(x)
data_loader_and_executor.run(function)
|
User input from GUI in Python 3.5
Question: So, I'm pretty new to Python, but I am having trouble handling the variables
once they are placed in a class.
The following code works fine when there is no surrounding class, but once I
add it I get the error:
NameError: name 'someName' is not defined
Which occurs on the 3rd line
text = "You have entered " + someName.get()
Here's the code:
class GUI:
def changeLabel():
text = "You have entered " + someName.get()
labelText.set(text)
someName.delete(0, END)
someName.insert(0, "You've clicked!")
return
app = Tk()
app.title("GUI Test")
app.geometry('450x300')
labelText = StringVar()
labelText.set("Click when ready")
label1 = Label(app, textvariable=labelText, height=4)
label1.pack()
userInput = StringVar(None)
someName = Entry(app, textvariable=userInput)
someName.pack()
button1 = Button(app, text="Click Here", width=20,command=changeLabel)
button1.pack(side='bottom',padx=15,pady=15)
app.mainloop()
GUI #calling the class to run
Any help would be greatly appreciated.
Answer: You have a some errors in your code, and aren't using classes in the way that
you should be. I've modified your code and commented the new lines so you
understand what's happening. I've added `self` references to all the text
variables so they can be accessed properly.
from tkinter import *
class GUI:
#set these so that they are able to be used by the whole class
labelText = ""
userInput = ""
#you should have an init method for your classes and do all the setup here
def __init__(self,master):
self.labelText = StringVar()
self.userInput = StringVar()
#you should pack things into a frame
frame = Frame(master)
frame.pack()
self.labelText.set("Click when ready")
label1 = Label(frame, textvariable=self.labelText, height=4)
label1.pack()
someName = Entry(frame, textvariable=self.userInput)
someName.pack()
button1 = Button(frame, text="Click Here", width=20,command=self.changeLabel)
button1.pack(side='bottom',padx=15,pady=15)
def changeLabel(self):
text = "You have entered " + self.userInput.get()
self.labelText.set(text)
self.userInput.set("You've clicked!")
return
#create the app before you call the GUI.
app = Tk()
app.title("GUI Test")
app.geometry('450x300')
# when you create the class, you need to assign it to a variable
applet = GUI(app) #calling the class to run
app.mainloop()
|
How to replace values in an attribute table for one column?
Question: I need to replace values in an attribute table for one column (replace zeroes
in column named "label" to 100). Is this possible using ogr or python? I have
to do this for 500+ shapefiles.
Answer: In the Esri ArcGIS realm, [Update
Cursors](http://resources.arcgis.com/en/help/main/10.2/index.html#//018w00000014000000)
are typically used for this type of operation.
For example
import arcpy
# Your input feature class
fc = r'C:\path\to\your.gdb\feature_class'
# Start an update cursor and change values from 0 to 100 in a field called "your_field"
with arcpy.da.UpdateCursor(fc, "your_field") as cursor:
for row in cursor:
if row[0] == 0:
row[0] = 100
cursor.updateRow(row)
|
Python and Pandas - Removing footer in multiple files with the same break
Question: I am doing data analysis on a group of different excel files, each with a
footer. The start point of the footer changes based on the total number of
rows. The footer starts in the first column as a blank cell then has text that
is not formatted like the rest of the data in the column. I am trying to come
up with a footer length variable to drop into skip_footer when I read the
files.
df looks like
+--------------------+
| A B C |
+--------------------+
| Data Data Data |
| Data Data Data |
| [Blank] |
| This is |
| The footer |
| I need to remove |
+--------------------+
I have tried using both methods at this
[link](http://stackoverflow.com/questions/19138175/pandas-ignore-all-lines-
following-a-specific-string-when-reading-a-file-into-a), but I can't seem to
get either to work. One of the errors I am getting is invalid file. Im 99%
sure that the invalid file is coming because the file is an xlsx. I don't get
an error when I open and read the file, only when I try to run functions on
it.
Code:
import os
direct = "path"
file = open(direct, "file name"), "r")
import itertools as it
def get_footer(file_):
with open(file_) as f:
g = it.dropwhile(lambda x: x != ' ', f)
footer_len = len([i for i, _ in enumerate(g)])
return footer_len
footer_len = get_footer(file)
Answer: I was not able to figure out how to do the above, but I have a much easier
answer.
import pandas as pd
File = pd.read_excel()
NoFooter = File[:-6]
|
Python Tkinter: Have Entry receive keys while Menu is posted?
Question: I want to have an Entry with a dropdown Menu autocomplete... kind of like
Chrome's omnibar, for example.
One issue I'm having is that once the menu gets posted (displayed), it seems
to intercept all key press events, and I don't see a way to redirect them
anywhere else.
Here's some simplified code that reproduces the issue:
from Tkinter import Entry, Menu, Tk
def menuKey(event):
print('Key pressed in a menu.')
def showMenu(event):
menu = Menu(root, tearoff = 0)
menu.add_command(label = 'Just for example')
menu.bind('<KeyRelease>', menuKey)
menu.post(entry.winfo_rootx(), entry.winfo_rooty() + entry.winfo_height())
root = Tk()
entry = Entry(root, width = 50)
entry.bind('<KeyRelease>', showMenu)
entry.bind('<FocusIn>', showMenu)
entry.pack()
root.mainloop()
It shows the menu once you click on the entry. Try typing. On Windows, you
just get an error beep sound. On OS X, it highlights something in the menu.
Neither OS does what I actually want, which is to have the `menuKey` function
run.
Is there some way I can either intercept key events that are going to the
`Menu` and/or force them to go to the `Entry` instead?
Answer: You are correct: the native menus steal all of the events, and there's nothing
you can do about it. This is the price we pay for having native menus on OSX
and Windows.
The workaround is to not use a menu for the dropdown. Instead, you can create
an instance of `Toplevel`, turn on the `overrideredirect` flag, and then
manage all of the events yourself. It's a bit of a chore, but it's doable.
|
Python Multithread and PostgreSQL
Question: I want to speed up one of my tasks and I wrote a little program:
import psycopg2
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
def write_sim_to_db(all_ids2):
if all_ids1[i] != all_ids2:
c.execute("""SELECT count(*) FROM similarity WHERE prod_id1 = %s AND prod_id2 = %s""", (all_ids1[i], all_ids2,))
count = c.fetchone()
if count[0] == 0:
sim_sum = random.random()
c.execute("""INSERT INTO similarity(prod_id1, prod_id2, sim_sum)
VALUES(%s, %s, %s)""", (all_ids1[i], all_ids2, sim_sum,))
conn.commit()
conn = psycopg2.connect("dbname='db' user='user' host='localhost' password='pass'")
c = conn.cursor()
all_ids1 = list(n for n in range(1000))
all_ids2_list = list(n for n in range(1000))
for i in range(len(all_ids1)):
with ThreadPoolExecutor(max_workers=5) as pool:
results = [pool.submit(write_sim_to_db, i) for i in all_ids2_list]
For a while, the program is working correctly. But then I get an error:
Segmentation fault (core dumped)
Or
*** Error in `python3': double free or corruption (out): 0x00007fe574002270 ***
Aborted (core dumped)
If I run this program in one thread, it works great.
with ThreadPoolExecutor(max_workers=1) as pool:
Postgresql seems no time to process the transaction. But I'm not sure. In the
log file any mistakes there.
I do not know how to find the error. Help.
Answer: This is the sane approach to speed it up. It will be much faster and simpler
than your code.
tuple_list = []
for p1 in range(3):
for p2 in range(3):
if p1 == p2: continue
tuple_list.append((p1,p2,random.random()))
insert = """
insert into similarity (prod_id1, prod_id2, sim_sum)
select prod_id1, prod_id2, i.sim_sum
from
(values
{}
) i (prod_id1, prod_id2, sim_sum)
left join
similarity s using (prod_id1, prod_id2)
where s is null
""".format(',\n '.join(['%s'] * len(tuple_list)))
print cur.mogrify(insert, tuple_list)
cur.execute(insert, tuple_list)
Output:
insert into similarity (prod_id1, prod_id2, sim_sum)
select prod_id1, prod_id2, i.sim_sum
from
(values
(0, 1, 0.7316830646236253),
(0, 2, 0.36642199082207805),
(1, 0, 0.9830936499726003),
(1, 2, 0.1401200246162232),
(2, 0, 0.9921581283868096),
(2, 1, 0.47250175432277497)
) i (prod_id1, prod_id2, sim_sum)
left join
similarity s using (prod_id1, prod_id2)
where s is null
BTW there is no need for Python at all. It can all be done in a plain SQL
query.
|
How to create a new MSMQ message in IronPython with label, reply queue and other properties
Question: I'm following this example
[here](http://www.ironpython.info/index.php?title=Message_Queuing) to use MS
Message Queues with IronPython. The example works to create a message text
string without any properties.
import clr
clr.AddReference('System.Messaging')
from System.Messaging import MessageQueue
ourQueue = '.\\private$\\myqueue'
queue = MessageQueue(ourQueue)
queue.Send('Hello from IronPython')
I am trying to create an empty message and then add properties (like label, a
reply queue and a binary message body) and then send that complete message.
How can I do this in IronPython?
The documentation of the message class is
[here](https://msdn.microsoft.com/en-
US/library/system.messaging.message.message%28v=vs.80%29.aspx), but obviously
has no python sample code. I have never used .net code with python and just
installed IronPython to connect to an existing MSMQ environment, so I'm a bit
stuck in how to proceed.
Any help?
# update
See answer below, I managed to guess the systax to create a message. The
solution seems a bit hacky so I'll leave this open for a few days
Answer: I don't think that this works with IronPython classes, because serialize and
deserialize them does not work like it does for c#/.net classes.
The only thing to get this work, will be to get IronPython classes serialize-
able and deserialize-able. I think deserialization will be the hard part. But
you may proof me wrong.
|
Formatting data for hmmlearn
Question: I'm trying to fit a hidden Markov model using hmmlearn in python. I assume
that my data is not formatted correctly, however the documentation is light
for hmmlearn. Intuitively I would format the data as a 3 dimensional array of
n_observations x n_time_points x n_features, but hmmlearn seems to want a 2d
array.
import numpy as np
from hmmlearn import hmm
X = np.random.rand(10,5,3)
clf = hmm.GaussianHMM(n_components=3, n_iter=10)
clf.fit(X)
Which gives the following error:
ValueError: Found array with dim 3. Estimator expected <= 2.
Does anyone know how to format data in order to build the HMM I'm after?
Answer: **Note** : All of the following is relevant for the currently unreleased
version 0.2.0 of `hmmlearn`. The version 0.1.0 available on PyPI uses a
different API inherited from `sklearn.hmm`.
To
[fit](http://hmmlearn.readthedocs.org/en/latest/api.html#hmmlearn.base._BaseHMM.fit)
the model to multiple sequences you have to provide two arrays:
* `X` \--- a concatenation of the data from all sequences,
* `lengths` \--- an array of sequence lengths.
I'll try to illustrate these conventions with an example. Consider two 1D
sequences
X1 = [1, 2, 0, 1, 1]
X2 = [42, 42]
To pass both sequences to the `.fit` method we need to first concatenate them
into a single array and then compute an array of lengths
X = np.append(X1, X2)
lengths = [len(X1), len(X2)]
|
dictionary inside 2 loops to save to a single file
Question: I intend to write in a single file (for each function), but inside the "loop
in the loop" I got trapped.
It's working except the storage/ save part, now writes a file for each inner
loop: ## def t2(): ##
But I wish to improve and also work with the current 'dic' or 'list' in the
next pool/ funtion t'x'(): and so on, to avoid have to open the csv in the
jorney.
what's the lesson over here? :p It's my 1st data scrape, I'm new to python!
import
def t0(url): # url
soup ('http://www.foo.net')
return soup
def t1(): # 1st_pool
soup = t0()
dic = {}
with open('dic.csv', 'w') as f:
for x in range(15):
try:
collect
dic[name] = link
f.write('{0};{1}\n'.format(name, link))
except:
pass
return dic
def t2(): # 2nd_pool
dic = t1()
dic2 = {}
for k,v in dic.items():
time.sleep(3)
with open(k+'_dic.csv', 'w') as f:
for x in range(13):
try:
collect
dic2[name] = link
f.write('{0};{1}\n'.format(name, link))
except:
pass
return ###############
def t3(): ... # 3rd_pool
def t4(): ... # 4th_pool
def t5(): ... # 5th_pool
def t6(): ... # full_path /to /details
Answer: As I mention early, the "problem" resides only in the fact that was creating a
individual *.csv (to not overwrite the previous loop) for each loop, so now I
figured out how to create a single file.csv for each function:
def t2(): # 2nd_pool
dic = t1()
dic2 = {}
for k,v in dic.items():
time.sleep(3)
##
for x in range(13):
try:
collect
dic2[name] = link
##
except:
pass
##
with open('dic2.csv', 'w') as f:
for n,j in dic2.items():
f.write('{0};{1}\n'.format(n, j))
##
return dic2
I simply moved the "*.csv operation" ( ## represent the chages) to the end of
the function, outside of the "double loop", and the dictionary it's also
available in the next function # t3():# and so on.
I was trying to achieve that without write the extra loop, so if someone can
provide a better alternative, I would like to learn!
|
import wpf to IronPython app
Question: I'd like making IronPython WPF app' but VS says:
> "ImportError: No module named 'wpf' "
I tried [this link](http://stackoverflow.com/questions/27580543/importerror-
no-module-named-wpf-in-revit-environment-only-user-
interface/27599805#27599805) but it doesn't work. I am not sure about where
doing this:
import clr clr.AddReference('IronPython.Wpf') import wpf
When I write this it says
> no module named 'clr'
Answer: First you might not want to have your import and something else on the same
line. Always put your imports before whatever calls to a function your are
making!
import clr
import wpf
clr.AddReference('IronPython.wpf')
and I believe your file should be in the same directory for .Addreference() to
locate it. as far as I know, the latest IronPython 2.7 should come prepackaged
with wpf, but then again your version might differ. I would recommend to
update to the latest, or download the modules you are missing and drop them in
the IronPython repository at their appropriate location!
Hope this helps!
|
How to scrape using Python a link from a html class
Question: I am attempting to grab the link from the website. Its the sound of the word.
The website is <http://dictionary.reference.com/browse/would?s=t>
so I am using the following code to get the link but it is coming up up blank.
This is weird because I can use a similar set up and pull data from a stock.
The idea is to build a program that gives the sound of the word then I will
ask for the spelling. This is for my kids pretty much. I needed to go through
a list of words to get the links in a dictionary but having trouble getting
the link to print out. I'm using urllib and re code below.
import urllib
import re
words = [ "would","your", "apple", "orange"]
for word in words:
urll = "http://dictionary.reference.com/browse/" + word + "?s=t" #produces link
htmlfile = urllib.urlopen(urll)
htmltext = htmlfile.read()
regex = '<a class="speaker" href =>(.+?)</a>' #puts tag together
pattern = re.compile(regex)
link = re.findall(pattern, htmltext)
print "the link for the word", word, link #should print link
This is the expected output for the word would
<http://static.sfdict.com/staticrep/dictaudio/W02/W0245800.mp3>
Answer: You should fix your regular expression to grab everything inside the `href`
attribute value:
<a class="speaker" href="(.*?)"
Note that you should really consider [switching from regex to HTML
parsers](http://stackoverflow.com/questions/1732348/regex-match-open-tags-
except-xhtml-self-contained-tags), like
[`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/).
Here is how you can apply `BeautifulSoup` in this case:
import urllib
from bs4 import BeautifulSoup
words = ["would","your", "apple", "orange"]
for word in words:
urll = "http://dictionary.reference.com/browse/" + word + "?s=t" #produces link
htmlfile = urllib.urlopen(urll)
soup = BeautifulSoup(htmlfile, "html.parser")
links = [link["href"] for link in soup.select("a.speaker")]
print(word, links)
|
Python split string that have two delimited
Question: I want to know how to split a string with more then one delimiter. I have a
problem splitting if one is space?
I trying to read a text file that has this:
> 22.0;2016-01-16 00:16:18
I know how to read a text file to a variable, but when I have problem to split
even a string I can't go further.
All I have now is this code:
with open('datasource_3.txt', 'r') as f:
data = f.readlines()
for line in data:
words = line.strip().split(';')
print words
Answer: You can split with the [regular
expression](https://docs.python.org/2/library/re.html) `;|`, like so:
import re
x = '22.0;2016-01-16 00:16:18'
print re.split(';| ', x)
This prints `['22.0', '2016-01-16', '00:16:18']`.
|
how to display huge data in new excel sheet using python
Question:
from openpyxl import load_workbook
wb=load_workbook('Project_Python.xlsx')
sheet2=wb.get_sheet_by_name('Sheet2')
sheet3=wb.get_sheet_by_name('Sheet3')
sheet1=wb.get_sheet_by_name('Sheet1')
sheet3=wb.get_active_sheet()
for i in range(3,6369):
d1=(sheet1.cell(row=i,column=1).value)
for j in range(3,6369):
d2=(sheet2.cell(row=i,column=1).value)
if d1==d2:
print(i,sheet1.cell(row=i,column=1).value,"same")
else:
print(i,sheet2.cell(row=i,column=1).value,"modified")
I was comparing two excel sheets i.e sheet1 and sheet2 and i want to display
the last 2 outputs in my sheet3 on same workbook. How can i do that?
Answer: To write in a cell:
sheet3.cell(column=1, row=1, value="SOMETHING")
Put it where you want .
|
AttributeError in python3
Question: I want to adapt [this
code](http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis#Python)
to work in persian text.
I changed it as can be seen in the code bellow in which the
`english_frequency` and `ordA` are changed. But, it has an error with
`uppercase` in line:
cleaned = [ord(c) for c in input.upper() if c.isupper()].
Can you help me to adapt it?
from string import ascii_uppercase
from operator import itemgetter
def vigenere_decrypt(target_freqs, input):
nchars = len(ascii_uppercase)
ordA = ord('ا')
sorted_targets = sorted(target_freqs)
def frequency(input):
result = [[c, 0.0] for c in ascii_uppercase]
for c in input:
result[c - ordA][1] += 1
return result
def correlation(input):
result = 0.0
freq = frequency(input)
freq.sort(key=itemgetter(1))
for i, f in enumerate(freq):
result += f[1] * sorted_targets[i]
return result
cleaned = [ord(c) for c in input.upper() if c.isupper()]
best_len = 0
best_corr = -100.0
# Assume that if there are less than 20 characters
# per column, the key's too long to guess
for i in xrange(2, len(cleaned) // 20):
pieces = [[] for _ in xrange(i)]
for j, c in enumerate(cleaned):
pieces[j % i].append(c)
# The correlation seems to increase for smaller
# pieces/longer keys, so weigh against them a little
corr = -0.5 * i + sum(correlation(p) for p in pieces)
if corr > best_corr:
best_len = i
best_corr = corr
if best_len == 0:
return ("Text is too short to analyze", "")
pieces = [[] for _ in xrange(best_len)]
for i, c in enumerate(cleaned):
pieces[i % best_len].append(c)
freqs = [frequency(p) for p in pieces]
key = ""
for fr in freqs:
fr.sort(key=itemgetter(1), reverse=True)
m = 0
max_corr = 0.0
for j in xrange(nchars):
corr = 0.0
c = ordA + j
for frc in fr:
d = (ord(frc[0]) - c + nchars) % nchars
corr += frc[1] * target_freqs[d]
if corr > max_corr:
m = j
max_corr = corr
key += chr(m + ordA)
r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA)
for i, c in enumerate(cleaned))
return (key, "".join(r))
def main():
encoded = "بفعاع پهيتش غعهدد ذصلدي هزفضر کنهرظ ضذکاح يصتمد فهزگع "
english_frequences = [
14, 4.2, 0.7, 5.2, 0.1, 1.2, 0.4,
1, 1.4, 7.5, 0.1, 8.5, 2.1, 0.1,
3.3, 2.6, 0.7, 0.3, 0.6, 0.2, 1.5,
0.2, 1.6, 1.2, 3, 1.7, 2.7, 5.7, 7.1, 6, 5.7, 9.1]
(key, decoded) = vigenere_decrypt(english_frequences, encoded)
print ("Key:", key)
print ("\nText:", decoded)
main()
Answer: This is clearly a python 2 code, and you are running it using a python 3
interpreter.
Use Python 2.
Also, compared to [the
original](http://rosettacode.org/wiki/Vigen%C3%A8re_cipher/Cryptanalysis#Python),
you ruined the indentation of many blocks.
|
Python Urllib Query
Question: I am thinking through how to expand this script to get it to repeatedly
download the next 20 files but am stuck. Any hints?
import urllib
fhand = urllib.urlopen('http://ecorp.azcc.gov/Search/Details?Request.Term=1&Request.IsActive=True&Request.Type=StartsWith&Request.Category=Entity&Request.SearchMethod=BusinessEntity&Request.CurrentPageIndex=0&Request.EntityType=All&Request.PageDirection=Next')
for line in fhand:
print line #.strip()
Answer: Seems there is a `CurrentPageIndex=0` parameter in your URL that you might be
able to use to move to the next page
for i in range(0, 20):
# Put the full URL below, I've put ... to shorten it
url = 'http://ecorp.azcc.gov/...CurrentPageIndex={}...'.format(i)
fhand = urllib.urlopen(url)
# do something with fhand
|
Python script, log to screen and to file
Question: I have this script, and I want now to put the output on screen and into a log
file. Anyone who can help me on how to do this?
PS: don't mind my debug lines plz
Thx
#!/usr/bin/python
import os
import subprocess
import sys
import argparse
from subprocess import Popen, PIPE, call
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', help=' Add here the url you want to use. Example: www.google.com')
parser.add_argument('-o', '--output', help=' Add here the output file for logging')
args = parser.parse_args()
print args.url
print args.output
cmd1 = ("ping -c 4 "+args.url)
cmd2 = cmd1, args.url
print cmd2
print cmd1
p = subprocess.Popen(cmd2, shell=True, stderr=subprocess.PIPE)
Answer: You can use the logging module and communicate() method of a subprocess
process:
import logging
import argparse
import subprocess
def initLogging( args ):
formatString = '[%(levelname)s][%(asctime)s] : %(message)s' # specify a format string
logLevel = logging.INFO # specify standard log level
logging.basicConfig( format=formatString , level=logLevel, datefmt='%Y-%m-%d %I:%M:%S')
log_file = args.output
fileHandler = logging.FileHandler( log_file )
logging.root.addHandler( fileHandler ) # add file handler to logging
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', help=' Add here the url you want to use. Example: www.google.com')
parser.add_argument('-o', '--output', help=' Add here the output file for logging')
args = parser.parse_args()
initLogging( args )
cmd = [ "ping" , "-c" ,"4", args.url ]
p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
stdout_string , stderr_string = p.communicate() # receive stdout, stderr, take care, this is a blocking call,
# stdout_string or stderr_string could be of type None
logging.info( stderr_string )
logging.info( stdout_string )
This will log to stdout and to a file.
You can even add more handlers e.g. stream handlers with
logging.addHandler( logging.StreamHandler( someStreamlikeObject ) )
One other thing: You should never use shell=True unless necessary because it
is unsafe and brings some technical conditions (see subprocess documentation).
The above code is altered in a way which does not use shell=True.
|
How to scrape google?
Question: So I wanna scrape google, I have successfully scraped craigslist using this
method but I can't seam to scrape google for some reason (yes of course I
changed the class and stuff..) this is what I want to scrape:
I want to scrape websites description:
[](http://i.stack.imgur.com/AqW8u.png)
from selenium import webdriver
path = r"C:\Users\Skid\Desktop\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get("https://www.google.com/#q=python+webscape+google")
posts = driver.find_elements_by_class_name("r")
for post in posts:
print(post.text)
Answer: Solved, Add a timer (import time, time.sleep(2)) before scraping.
|
Is there a way to get function parameter names, including bound-methods excluding `self`?
Question: I can use `inspect.getargspec` to get the parameter names of any function,
including bound methods:
>>> import inspect
>>> class C(object):
... def f(self, a, b):
... pass
...
>>> c = C()
>>> inspect.getargspec(c.f)
ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=None)
>>>
However, `getargspec` includes `self` in the argument list.
Is there a universal way to get the parameter list of any function (and
preferably, any callable at all), excluding `self` if it's a method?
EDIT: Please note, I would like a solution which would on both Python 2 and 3.
Answer: [`inspect.signature`](https://docs.python.org/3/library/inspect.html#inspect.Signature)
excludes the first argument of methods:
>>> from inspect import signature
>>> list(signature(c.f).parameters)
['a', 'b']
You could also delete the first element of `args` manually:
from inspect import ismethod, getargspec
def exclude_self(func):
args = getargspec(func)
if ismethod(func):
args[0].pop(0)
return args
exclude_self(c.f) # ArgSpec(args=['a', 'b'], ...)
|
Celery (Django + Redis) task fails: "No connection could be made because the target machine actively refused it"
Question: **UPDATE:** I decided to try using Django as the broker for simplicity, as I
assumed I did something wrong in the Redis setup. However, after making the
changes described in the
[docs](http://docs.celeryproject.org/en/latest/getting-
started/brokers/django.html) I get the same error as below when attempting to
run a Celery task with `.delay()`. The Celery worker starts and shows it's
connected to Django for transport. Could this be a firewall issue?
**ORIGINAL**
I'm working on a Django project and attempting to add background tasks. I've
installed Celery and chosen Redis for the broker, and installed that as well
(I'm on a Windows machine, fyi). The celery worker starts, connects to the
Redis server, and discovers my `shared_tasks`
-------------- celery@GALACTICA v3.1.19 (Cipater)
---- **** -----
--- * *** * -- Windows-7-6.1.7601-SP1
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: proj:0x2dbf970
- ** ---------- .> transport: redis://localhost:6379/0
- ** ---------- .> results: disabled
- *** --- * --- .> concurrency: 8 (prefork)
-- ******* ----
--- ***** ----- [queues]
-------------- .> celery exchange=celery(direct) key=celery
[tasks]
. app.tasks.add
. app.tasks.mul
. app.tasks.xsum
. proj.celery.debug_task
[2016-01-16 11:53:05,586: INFO/MainProcess] Connected to redis://localhost:6379/
0
[2016-01-16 11:53:06,611: INFO/MainProcess] mingle: searching for neighbors
[2016-01-16 11:53:09,628: INFO/MainProcess] mingle: all alone
c:\python34\lib\site-packages\celery\fixups\django.py:265: UserWarning: Using se
ttings.DEBUG leads to a memory leak, never use this setting in production enviro
nments!
warnings.warn('Using settings.DEBUG leads to a memory leak, never '
[2016-01-16 11:53:14,670: WARNING/MainProcess] c:\python34\lib\site-packages\cel
ery\fixups\django.py:265: UserWarning: Using settings.DEBUG leads to a memory le
ak, never use this setting in production environments! warnings.warn('Using settings.DEBUG leads to a memory leak, never '
[2016-01-16 11:53:14,671: WARNING/MainProcess] celery@GALACTICA ready.
I'm following the intro docs so the tasks are very simple, including one
called `add`. I can run the tasks by themselves in a python shell, but when I
attempt to call `add.delay()` to have celery handle it, it appears the
connection isn't successful:
>>> add.delay(2,2)
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\kombu\utils\__init__.py", line 423, in __call__
return self.__value__
AttributeError: 'ChannelPromise' object has no attribute '__value__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\kombu\connection.py", line 436, in _ensured
return fun(*args, **kwargs)
File "C:\Python34\lib\site-packages\kombu\messaging.py", line 177, in _publish
channel = self.channel
File "C:\Python34\lib\site-packages\kombu\messaging.py", line 194, in _get_channel
channel = self._channel = channel()
File "C:\Python34\lib\site-packages\kombu\utils\__init__.py", line 425, in __call__
value = self.__value__ = self.__contract__()
File "C:\Python34\lib\site-packages\kombu\messaging.py", line 209, in <lambda>
channel = ChannelPromise(lambda: connection.default_channel) File "C:\Python34\lib\site-packages\kombu\connection.py", line 756, in default_channel
self.connection
File "C:\Python34\lib\site-packages\kombu\connection.py", line 741, in connection
self._connection = self._establish_connection()
File "C:\Python34\lib\site-packages\kombu\connection.py", line 696, in _establish_connection
conn = self.transport.establish_connection()
File "C:\Python34\lib\site-packages\kombu\transport\pyamqp.py", line 116, in establish_connection
conn = self.Connection(**opts)
File "C:\Python34\lib\site-packages\amqp\connection.py", line 165, in __init__
self.transport = self.Transport(host, connect_timeout, ssl)
File "C:\Python34\lib\site-packages\amqp\connection.py", line 186, in Transport
return create_transport(host, connect_timeout, ssl)
File "C:\Python34\lib\site-packages\amqp\transport.py", line 299, in create_transport
return TCPTransport(host, connect_timeout)
File "C:\Python34\lib\site-packages\amqp\transport.py", line 95, in __init__
raise socket.error(last_err)
OSError: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\celery\app\task.py", line 453, in delay
return self.apply_async(args, kwargs)
File "C:\Python34\lib\site-packages\celery\app\task.py", line 560, in apply_async
**dict(self._get_exec_options(), **options)
File "C:\Python34\lib\site-packages\celery\app\base.py", line 354, in send_task
reply_to=reply_to or self.oid, **options
File "C:\Python34\lib\site-packages\celery\app\amqp.py", line 305, in publish_task
**kwargs
File "C:\Python34\lib\site-packages\kombu\messaging.py", line 172, in publish
routing_key, mandatory, immediate, exchange, declare)
File "C:\Python34\lib\site-packages\kombu\connection.py", line 457, in _ensured
interval_max)
File "C:\Python34\lib\site-packages\kombu\connection.py", line 369, in ensure_connection
interval_start, interval_step, interval_max, callback)
File "C:\Python34\lib\site-packages\kombu\utils\__init__.py", line 246, in retry_over_time
return fun(*args, **kwargs)
File "C:\Python34\lib\site-packages\kombu\connection.py", line 237, in connect
return self.connection
File "C:\Python34\lib\site-packages\kombu\connection.py", line 741, in connection
self._connection = self._establish_connection()
File "C:\Python34\lib\site-packages\kombu\connection.py", line 696, in _establish_connection
conn = self.transport.establish_connection()
File "C:\Python34\lib\site-packages\kombu\transport\pyamqp.py", line 116, in establish_connection
conn = self.Connection(**opts)
File "C:\Python34\lib\site-packages\amqp\connection.py", line 165, in __init__
self.transport = self.Transport(host, connect_timeout, ssl)
File "C:\Python34\lib\site-packages\amqp\connection.py", line 186, in Transport
return create_transport(host, connect_timeout, ssl)
File "C:\Python34\lib\site-packages\amqp\transport.py", line 299, in create_transport
return TCPTransport(host, connect_timeout)
File "C:\Python34\lib\site-packages\amqp\transport.py", line 95, in __init__
raise socket.error(last_err)
OSError: [WinError 10061] No connection could be made because the target machine actively refused it
There's no output on the console with the celery worker running, so I don't
think it ever gets the task. I believe my settings.py, celery.py and tasks.py
are alright:
**settings.py**
#celery settings
BROKER_URL = 'redis://localhost:6379/0'
**celery.py**
from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')
from django.conf import settings # noqa
app = Celery('proj')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
**tasks.py**
from __future__ import absolute_import
#from proj.celery import app
from celery import shared_task
@shared_task
def add(x, y):
return x + y
@shared_task
def mul(x, y):
return x * y
@shared_task
def xsum(numbers):
return sum(numbers)
My project layout is nearly identical to the Celery example Django project
layout on GitHub, as well as the example
[here](http://michal.karzynski.pl/blog/2014/05/18/setting-up-an-asynchronous-
task-queue-for-django-using-celery-redis/). It looks like:
proj
├── proj
│ ├── celery.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── app
├── __init__.py
├── models.py
├── tasks.py
├── tests.py
└── views.py
Apologies on the other app in my project being named 'app' - it makes things a
bit confusing to read, and is the result of autogenerating the base project in
Visual Studio with PTVS installed. I probably could have changed it early on,
but i didn't realize the name was so vague.
Thanks for any thoughts- I've been stumped by this for a while.
Answer: I got around this, but I'm not sure how. I came back to this exact
configuration the next day, and tasks were making it to the celery worker.
Perhaps one of the services I restarted was the key, but I'm not sure.
If anyone else runs into this, especially on Windows: make sure your redis-
server is active and that you see the incoming connections from a ping as well
as the task. I had done that before posting this question, but it seems like
the likely candidate for being misconfigured.
|
Download a file in python with urllib2 instead of urllib
Question: I'm trying to download a tarball file and save it locally with python. With
urllib it's pretty simple:
import urllib
urllib2.urlopen(url, 'compressed_file.tar.gz')
tar = tarfile.open('compressed_file.tar.gz')
print tar.getmembers()
So my question is really simple: What's the way to achieve this using the
urllib2 library?
Answer: Quoting [docs](https://docs.python.org/2/library/urllib2.html):
> `urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[,
> context]]]]])` Open the URL url, which can be either a string or a Request
> object.
>
> _`data` may be a string specifying additional data to send to the server, or
> `None` if no such data is needed._
Nothing in `urlopen` interface documentation says, that second argument is a
name of file where response should be written.
You need to explicitly write data read from response to file:
r = urllib2.urlopen(url)
CHUNK_SIZE = 1 << 20
with open('compressed_file.tar.gz', 'wb') as f:
# line belows downloads all file at once to memory, and dumps it to file afterwards
# f.write(r.read())
# below is preferable lazy solution - download and write data in chunks
while True:
chunk = r.read(CHUNK_SIZE)
if not chunk:
break
f.write(chunk)
|
HTTP Error 406: Not Acceptable Python urllib2
Question: I get the following error with the code below.
> HTTP Error 406: Not Acceptable Python urllib2
This is my first step before I use beautifulsoup to parse the page.
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = "http://www.choicemoney.us/retail.php"
response = opener.open(url)
All help greatly appreciated.
Answer: > The resource identified by the request is only capable of generating
> response entities which have content characteristics not acceptable
> according to the accept headers sent in the request.
> [[RFC2616]](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7)
Based on the code and what the RFC describes I assume that you need to set
both the key and the value of the `User-Agent` header correctly.
These are correct examples:
* `Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11`
* `Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36`
* `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A`
Just replace the following.
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A')]
|
How do I install and use MySQLdb for Python 3 on Windows 10?
Question: My various searches seem to come up with very old posts or a mention of how to
do this under cygwin. I had python 3.5 installed and then installed Anaconda3.
I have python 3.5 (Cpython) installed in my user directory. I tried changing
the order of how things appear in my Windows Environment Variables path, so
that I could try both the Anaconda version of Python and the other version of
python that I have.
Currently, I am a bit confused as to the package name that I should use. Is it
python-mysqldb, or MySQLdb, or mysqldb, mysqlclient. I believe that when I had
Anaconda3 in my global path (and the other version of python in my user path),
I was able to install mysqlclient.
Initially, I am just trying to follow a tutorial from a training site that
covers databases and uses peewee.
So, can the mysql driver for peewee be installed for python3? Or on Windows
specifically?
It is easy enough to use sqlite3, one doesn't use that in production, is that
right?
Can someone help me? Provide some guidance?
Also, one source of confusion is when other forms of installation of a python
package are listed in the google results (many point to stack overflow), such
as using easy_install, or cloning something from git. When I see instructions
that are from 2010 and they reference easy_install, I had been thinking that
now we can just use pip instead? Also, sometimes I see use of the conda
command. Does that work the same as pip?
Thanks in advance, Bruce
Answer: You could use pymysql. "The goal of PyMySQL is to be a drop-in replacement for
MySQLdb". Check the docs [here](https://github.com/PyMySQL/PyMySQL). Install
the following libraries
> pip install mysqlclient pymysql
Once these libraries are installed, just add the lines in the `manage.py` file
in your project and use the database settings for mysql.
> import pymysql
>
> pymysql.install_as_MySQLdb()
Now any files that `import MySQLdb` will work.
|
How to get the final redirected URL which has some JavaScript's?
Question: I used urllib2 to get the final redirected url of a web-link. For eg:
<http://tbk.bz/t72qx4v3> I am getting link as
<http://taskbucks.com/artcl_out?artcl=24713df2ffb748ec8464638df61d2298> But,
browsers gave the redirected final URL like this
www.holidayiq.com/blog/6-high-octane-adventure-sports-in-india-that-will-get-
your-heart-in-your-throat-1831.html/
I wish to get this final URL in python.
Answer: The problem is that on the
<http://taskbucks.com/artcl_out?artcl=24713df2ffb748ec8464638df61d2298> page,
there is a "document ready" event listener that makes a browser submit a form
on load which would eventually redirect you to the final page:
<script type="text/javascript">
$(document).ready(function() {
$("#fsid").val(new Fingerprint().get());
$("#fsidpe").val(new Fingerprint({canvas: true}).get());
submitReport();
});
function submitReport() {
$("#articleCheck").submit();
}
</script>
`urllib2` is not a browser and would not submit a form on page load.
Instead, I would use tools like
[`Mechanize`](https://pypi.python.org/pypi/mechanize/) in order to submit this
form:
>>> import mechanize
>>>
>>> br = mechanize.Browser()
>>> br.open("http://tbk.bz/t72qx4v3")
>>> br.select_form("articleCheck")
>>> br.submit()
>>> br.geturl()
'http://www.holidayiq.com/blog/6-high-octane-adventure-sports-in-india-that-will-get-your-heart-in-your-throat-1831.html?utm_source=taskbucks&utm_medium=share&utm_campaign=referral&channel=taskbucks'
|
To gain function the button for generating values
Question: The python code I've pasted below generates the values 0 through 100 and
displays them in a textbox-like shell console. In addition to this, I added a
button deep of textbox labelled 'PRESS'. I would like the process of
generating the values 0 through 100 to begin when I click the 'PRESS' button.
I have not been able to set this up successfully. Can you help me please?
#!/usr/bin/env python
import Tkinter as tk
import sys
from threading import *
class Console(tk.Frame):
def __init__(self,parent=None):
tk.Frame.__init__(self, parent)
self.parent = parent
sys.stdout = self
sys.stderr = self
self.createWidgets()
self.consoleThread = ConsoleThread()
self.after(100,self.consoleThread.start)
def write(self,string):
self.Text.insert('end', string)
self.Text.see('end')
def createWidgets(self):
self.Text = tk.Text(self.parent, wrap='word',height=38,width=115, bg='white', fg = "blue",font="Verdana 9 bold")
self.Text.grid()
self.b = tk.Button(text="PRESS")
self.b.grid()
class ConsoleThread(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
def values():
print 'TEST'
for i in range(101):
print i
x=values()
print x
if __name__ == '__main__':
root = tk.Tk()
bas=root.title('Test')
root.geometry('1000x700')
root.config(background="light blue")
main_window = Console(root)
main_window.mainloop()
try:
if root.winfo_exists():
root.destroy()
except:
pass
Answer: To achieve what you're looking for, you need to attach the function that you'd
like to call to the button you want to use. This is called a **callback**.
Luckily, TKinter makes this pretty easy to do - when constructing a button,
instead of writing:
my_button = tk.Button(text="Click Me!")
You can pass another keyword argument to the constructor, `command`, which is
a function that will be called when the button is activated. That would look
something like this:
def callback_message():
print("I just got called back!")
my_button = tk.Button(text="Click Me!", command=callback_message)
Now, whenever you click on `my_button`, `callback_message` will run!
In your specific case, I'd also move `values()` out of `ConsoleThread.run()`;
that way, it won't be called when the `ConsoleThread` is initialized.
|
Create column of categories from a column of transactions using regular expressions within a dictionary
Question: I have a csv file containing banking information that I am importing as a
pandas DataFrame. I want to create a new column that contains the transaction
categories (e.g. income, expense, transfer), created from a dictionary
containing regular expressions to apply to the transaction descriptions.
For example,
import pandas as pd
import re
data = pd.read_csv("data/transactions.csv", parse_dates=['Date'])
Here is ouput of the `data` DataFrame:
Date Description Amount
2016-01-01 checkcard good food -12.45
2016-01-02 visa peppy lube -30.34
2016-01-05 deposit bank of me 5000.00
2016-01-05 transfer to bank 2500.00
2016-01-10 gift from aunt sally 25.00
Here are the regular expressions:
income = re.compile('.*deposit|gift.*')
expense = re.compile('good food|.*peppy lube.*')
transfer = re.compile('.*transfer.*')
And here is the dictionary:
catdict = {income: 'income',
expense: 'expense',
transfer: 'transfer'}
I want code that creates a new column named `Category` that uses the regular
expressions to assign the values of the dictionary to rows where the
`Description` column matches one of the regular expressions, so the result
would be:
Date Description Amount Category
2016-01-01 checkcard good food -12.45 expense
2016-01-02 visa peppy lube -30.34 expense
2016-01-05 deposit bank of me 5000.00 income
2016-01-05 transfer to bank 2500.00 transfer
2016-01-10 gift from aunt sally 25.00 income
Ideally, this code would also insert 'RECONCILE' in the category column for
rows where no matches are found in the regular expressions.
I am new to python, and suspect there a pythonic way to do this I am missing.
Thanks in advance
Answer: You can define a function that map a string (description) to a category
according to your `regex`'s. The first time it matches a pattern, the function
returns the name of that category. It returns 'RECONCILE' if none matches.
from collections import OrderedDict
def category(s):
catdict = OrderedDict([(income, 'income'),
(expense, 'expense'),
(transfer, 'transfer'),
])
for ptn, name in catdict.iteritems():
if ptn.search(s):
return name
return 'RECONCILE'
Then you can apply this function to the 'Description' column.
data['Category'] = data.Description.map(category)
print data
And this should give you what you want.
|
Why does the Python runtime handle warnings this way?
Question: Here's a traceback from a project I'm working on:
/usr/lib/python3/dist-packages/apport/report.py:13: PendingDeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import fnmatch, glob, traceback, errno, sys, atexit, locale, imp
Traceback (most recent call last):
...
File "./mouse16.py", line 1050, in _lit_string
rangeof = range(self.idx.v, self.idx.v + result.span()[1])
AttributeError: 'NoneType' object has no attribute 'span'
Now, there's a since-fixed bug in my code that caused the traceback itself;
whatever.
I'm interested in the first line: the `PendingDeprecationWarning` for not-my-
code. I use Ubuntu (as one can tell from `apport`'s existence in the path),
which is well-known for packaging and relying on Python for many things,
notably things like package management and bug reporting (`apport` / `ubuntu-
bug`).
[`imp` is indeed deprecated: _"Deprecated since version 3.4: The imp package
is pending deprecation in favor of
importlib."_](https://docs.python.org/3.6/library/imp.html#module-imp). My
machine runs at least Python 3.4.3+ or better and it takes time and a lot of
work to modernise and update software completely, so this warning is
understandable.
But [my program](https://github.com/catb0t/mouse16) doesn't go anywhere _near_
`imp`, `importlib` or `apport`, so my question is, why isn't a warning
deriving from `apport`'s source written to `apport`'s logs or certainly
collected by `stderr` on `apport`'s parent process?
If I had to take a guess at this, it's because the devs decided to buffer --
but never flush nor write -- `apport`'s `stderr`, and so the next time a
`python` child process on the system opens `stderr` for writing (as an error
in my program did), apport's buffered `stderr` is written too.
This isn't supported by what I (think I) know about Unix -- why would two
separate Python instances interact in this way?
* * *
Upon request, here's the best I can do for an MCVE: a list of module-level
imports.
import readline
import os
import sys
import warnings
import types
import typing
Is it because I import `warnings`? But... I still don't touch `apport`.
* * *
I think this question is more on-topic and will get better answers here on SO
than [AskUbuntu](https://askubuntu.com) or [Unix &
Linux](https://unix.stackexchange.com); flag it for migration if you feel
strongly otherwise but I think the mods will agree with me.
Answer: > so my question is, why isn't a warning deriving from apport's source written
> to apport's logs or certainly collected by stderr on apport's parent
> process?
The apport python library isn't running in a separate process here. Sure the
actual apport process is separate, but you are interacting/binding to it with
library that is local to your code/process.
Since this Python library is using a deprecated module, that is running inside
of your process, Python is correctly warning you.
As per Andrew's answer, the apport library is automatically invoked with an
uncaught exception.
|
Dictionary order causing input result to change?
Question: New here, and very new to Python. Go easy on me. I've got a .bat which allows
a user to enter an IP or hostname which if valid will ping the target and then
allow some actions to be performed. However, it's fairly inflexible and I
think I've reached the limit of what I can do with that method. I decided to
make the same script but in python to allow for a more flexible approach,
where multiple criteria could be defined via dictionarys, rather than have the
user enter them one by one which will hopefully avoid user error/typos.
I've finished the first step of the code, which is asking the user for a
keyword, checking it against one of the dictionaries, which if correct sets
some criteria and allows the user to proceed to entering their IP.
My problems are: 1\. Depending which order the dictionary prints in, will
depend what keywords are accepted. For example, if the dictionary prints in
the order;
{'TestGame': ['test', 'testing', 'tst'], 'ZestGame': ['zest', 'zesting', 'zst']}
then the script will only accept the words test, testing or tst. The opposite
will apply if 'Zestgame' prints first.
and 2. If the user enters a word that is not allowed, it should display the
message
The project or game you entered was not recognised.
Then loop round to ask them to enter a valid keyword. However it skips the
above message and immediatley asks the user to
Enter your PROJECT or GAME
Any ideas or solutions to these?
Full code:
import os, sys, ipaddress
# Allowed Project names with related keywords.
Projects = {
"ZestGame": ['zest', 'zesting', 'zst'],
"TestGame": ["test", "testing", "tst"]}
print(Projects)
# Email format tied to Project
ProjectEmails = {
"ZestGame": "zsti-zesty",
"TestGame": "tsti-testy"}
# Unique 32 character ID.
ProjectSCIDs = {
"ZestGame": "246zesty810scid12141618202224262",
"TestGame": "123testy456scid78910111213141516"}
# Step 1 Start - Set ActiveProject and associated information.
InputResult = "NOTFOUND"
while True:
if InputResult == "Valid":
break
ActiveProject = "NOTFOUND"
ActiveProject = "NOTFOUND"
ActiveSCID = "NOTFOUND"
UserInput = input("Enter your PROJECT or GAME:\n")
# Checks UserInput against Projects dictionary, loops if invalid.
for key, val in Projects.items():
if UserInput.lower() in val:
ActiveProject = key
# Sets ActiveProject, ActiveEmail and ActiveSCID if UserInput input result was OK.
for key, val in ProjectEmails.items():
if ActiveProject in key:
ActiveEmail = (val+"@email.com")
for key, val in ProjectSCIDs.items():
if ActiveProject in key:
ActiveSCID = val
InputResult = "Valid"
break
else:
print("The project or game you entered was not recognised.")
InputResult = "NOTFOUND"
print("\nThe user selected "+ActiveProject)
print(ActiveEmail+" "+ActiveSCID)
Answer: Keep in mind that Python dics are not ordered, change your code and use
[OrdererDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict)
wich uses the insertion order
Let me add an example:
>>> d = {k:v for k,v in zip("asdfghjkl", range(10))}
>>> d
{'a': 0, 'd': 2, 'g': 4, 'f': 3, 'h': 5, 'k': 7, 'j': 6, 'l': 8, 's': 1}
>>> od = OrderedDict(zip("asdfghjkl", range(10)))
>>> od
OrderedDict([('a', 0), ('s', 1), ('d', 2), ('f', 3), ('g', 4), ('h', 5), ('j', 6), ('k', 7), ('l', 8)])
Notice how the `'s'` key in the first dict is in the "last position" of it,
but in the ordered dict it is in the "second position" as it should by
insertion.
For checking if the user input is in any of the dictionaries just use
`.has_key(ActiveProject)` method in that dictionaries
Examples:
checking 1 dict:
if not Projects.has_key(ActiveProject):
print "The project or game you entered was not recognised."
checking for all dicts:
if not any(map(lambda x: x.has_key(ActiveProject), [Projects, ProjectEmails])):
print "The project or game you entered was not recognised."
else:
do whatever
|
KeyError: global not accessible through external Class
Question: I am trying to calculate the number of elements in a chemical equation. The
debugger that I have created somehow doesn't work with outside variables. I am
unsure of how to use globals in this situation.
**EDIT:** The debugger is supposed to show the variable name, and then its
value. What can I change to access the variables in my main program through
the debugger?
**EDIT:** There is a key error with `carrots` if I leave out `left`.
`Debug.py` in `site-packages`:
class Debugger(object):
def __init__(self,objs):
assert type(objs)==list,'Not a list of strings'
self.objs = objs
def __repr__(self):
return '<class Debugger>'
def show(self):
for o in self.objs:
print o,globals()[o] #EDIT
Chemical_Balancer.py:
from Debug import Debugger
def directions():
print 'Welcome to the chem Balancer.'
print 'Use the following example to guide your work:'
global left #LEFT IS GLOBAL
left = 'B^6 + C^2 + B^3 + C^3 + H^9 + O^4 + Na^1'
print left
print "#Please note to use a 'hat' when entering all elements"
print '#use only one letter elements for now'
#left = raw_input('enter formula:') #enter formula to count
directions()
chem_stats = {}
chem_names = []
chem_names = []
chem_indy = []
for c in range(len(left)):
if left[c].isalpha() and left[c].isupper():
chars = ''
if left[c+1].islower():
chars += left[c]+left[c+1]
else:
chars += left[c]
#print chars
chem_indy.append(c)
chem_names.append(chars)
carrots = [x for x in range(len(left)) if left[x]=='^']
#print chem_names
#chem_names = [left[c] for c in range(len(left)) if left[c].isalpha() and left[c].isupper()]
#chem_indy = [c for c in range(len(left)) if left[c].isalpha() and left[c].isupper()]
debug = Debugger(['carrots','chem_names','chem_indy','chem_stats']) #WITHOUT LEFT
debug.show()
Error message:
Traceback (most recent call last):
File "C:\Python27\#Files\repair\Chemical_Balancer.py", line 38, in <module>
debug.show()
File "C:\Python27\lib\site-packages\Debug.py", line 12, in show
print o,globals()[o] #EDIT
File "<string>", line 1, in <module>
KeyError: 'carrots' #EDIT
Answer: About the specific error on the `left` variable:
when you say a variable is global, python knows it has to look it up in the
global namespace when its name is used. But in the code `left` hasn't been
assigned in such namespace.
As you can see, `left` is commented out
#left = raw_input('enter formula:') #enter formula to count
Uncomment it by removing the `#` at the beginning of the line, so the line
inside the `directions` function
global left
can find it and the instructions that follow can work.
About the implementation: one solution to allow the debugger to know where to
look for the variables, i.e. in which module, can be to provide the name of
the module to it when it is created. Then the debugger object can reach the
global variables of the module that created it via
`sys.modules[module_name].__dict__`
**debugger.py**
import sys
class Debugger(object):
def __init__(self, module_name, objs):
assert type(objs)==list,'Not a list of strings'
self.objs = objs
self.module_name = module_name
def __repr__(self):
return '<class Debugger>'
def show(self):
for o in self.objs:
print o, sys.modules[self.module_name].__dict__[o]
**chemical_balancer.py**
import debugger as deb
a = 1
b = 2
d = deb.Debugger(__name__, ['a', 'b'])
print(d.objs)
d.show()
a = 10
b = 20
d.show()
which produces
['a', 'b']
a 1
b 2
a 10
b 20
As you can see, the debugger prints the current value of the variables each
time its `show` method is called
I have found [this SO Q&A](http://stackoverflow.com/questions/990422/how-to-
get-a-reference-to-current-modules-attributes-in-python) informative and
helpful.
|
python tuple with missing entry
Question: I am trying to parse a `bibtex` file with `python3`'s `bibtexparser` module.
A sample bibtex file is:
@article{ebert2013,
Title={First-principles calculation of the Gilbert damping parameter via the linear response formalism with application to magnetic transition metals and alloys},
Author={Mankovsky, S. and K{\"o}dderitzsch, D. and Woltersdorf, G and Ebert, H.},
Volume={87},
Pages={1},
Year={2013},
Journal={Phys. Rev. B}
}
@article{ebert2011,
title = {\textit{Ab Initio} Calculation of the Gilbert Damping Parameter via the Linear Response Formalism},
author = {Ebert, H. and Mankovsky, S. and K{\"o}dderitzsch, D. and Kelly, P. J.},
journal = {Phys. Rev. Lett.},
volume = {107},
pages = {066603},
month = {Aug},
publisher = {American Physical Society}
}
@article{paudyal2013,
author={Narayan Poudyal and J Ping Liu},
title={Advances in nanostructured permanent magnets research},
journal={Journal of Physics D: Applied Physics},
volume={46},
number={4},
pages={043001},
year={2013}
}
**Note** See the 2nd item does not have any `year` key.
Now, I am trying to parse this file as:
import bibtexparser
from bibtexparser.bparser import BibTexParser
# from bibtexparser.bwriter import BibTexWriter
from bibtexparser.bibdatabase import BibDatabase
db = BibDatabase()
with open('report.bib') as bibtex_file:
parser = BibTexParser()
db = bibtexparser.load(bibtex_file, parser=parser)
for i in range(0, len(db.entries)):
try:
tuples = (db.entries[i]["title"],db.entries[i]["author"],
db.entries[i]["journal"],db.entries[i]["year"])
except(KeyError):
continue
print(tuples)
Since, it does not find the `year` entry, it is skipping the 2nd element all
together; giving output as:
('First-principles calculation of the Gilbert damping parameter via the linear\nresponse formalism with application to magnetic transition metals and alloys', 'Mankovsky, S. and K{\\"o}dderitzsch, D. and Woltersdorf, G and Ebert, H.', 'Phys. Rev. B', '2013')
('Advances in nanostructured permanent magnets research', 'Narayan Poudyal and J Ping Liu', 'Journal of Physics D: Applied Physics', '2013')
But, the desired behaviour is to get the entry with a `NULL` value for the
missing item.
How I can do that?
I have actually gone through
[this](http://stackoverflow.com/questions/11708568/tuple-with-missing-value)
and [this](http://stackoverflow.com/questions/29747224/append-to-a-list-
defined-in-a-tuple-is-it-a-bug) se question among others, but have not gained
much.
Kindly help.
Answer: use `.get`, and you can remove your `try/except` for **KeyError** as well
db.entries[i].get("year")
With dictionaries, it is often recommended to use `dict.get(<key>,
default=None)`, to prevent **KeyError** exceptions, while iterating on **non-
sanitized** data.
Also have a look to `dict.pop(<key>, default)` which also prevents exceptions
but forces you to provide a default value.
|
Why am I getting TypeError: unsupported operand types for -: 'float' and 'function'?
Question: This is my code:
def concfunction(time,k):
return 0.1*exp((-k)*(time))
from scipy.optimize import curve_fit
curve_fit(concfunction,time,k,p0=[10])
Where I've already got arrays for time and concentration, and I want to find
`k` using `curve_fit`.
I get the following error:
TypeError Traceback (most recent call last)
<ipython-input-48-48cc519b697a> in <module>()
----> 1 curve_fit(concfunction,time,k,p0=[10])
C:\Users\Daisy\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, **kw)
579 # Remove full_output from kw, otherwise we're passing it in twice.
580 return_full = kw.pop('full_output', False)
--> 581 res = leastsq(func, p0, args=args, full_output=1, **kw)
582 (popt, pcov, infodict, errmsg, ier) = res
583
C:\Users\Daisy\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
369 if not isinstance(args, tuple):
370 args = (args,)
--> 371 shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
372 m = shape[0]
373 if n > m:
C:\Users\Daisy\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
18 def _check_func(checker, argname, thefunc, x0, args, numinputs,
19 output_shape=None):
---> 20 res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
21 if (output_shape is not None) and (shape(res) != output_shape):
22 if (output_shape[0] != 1):
C:\Users\Daisy\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in _general_function(params, xdata, ydata, function)
445
446 def _general_function(params, xdata, ydata, function):
--> 447 return function(xdata, *params) - ydata
448
449
TypeError: unsupported operand type(s) for -: 'float' and 'function'
Can anyone please help me resolve this?
Answer: If we assume `concfunction` returns float then time has to by of type:
function. What imports are you using? How are declared time and k? I will
guess time is a function from import or declared as function.
|
Using boto to connect to pre-existing windows instance
Question: My code is the folliwing
import boto.ec2
conn = boto.ec2.connect_to_region("us-west-2",aws_access_key_id='secret1',aws_secret_access_key='secret2')
conn.run_instances(
'i-41ffc2c0',
key_name='MyWindowsKey',
instance_type='t2.micro',
security_groups=['launch-wizard-3'])
print conn
Where launch-wizard-3 allows RDP connections with no problem.
Now when I run the above I get the following error:
Traceback (most recent call last):
File "Documents/boto_test.py", line 11, in <module>
security_groups=['launch-wizard-3'])
File "/Library/Python/2.7/site-packages/boto/ec2/connection.py", line 973, in run_instances
verb='POST')
File "/Library/Python/2.7/site-packages/boto/connection.py", line 1208, in get_object
raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidParameterValue</Code><Message>Value () for parameter groupId is invalid. The value cannot be empty</Message></Error></Errors><RequestID>e9d2cb00-a49b-4de5-a60e-178067f88119</RequestID></Response>
This is my first time connecting to this via boto.
Thanks for any pointers.
Answer: From the error message, seems only provide `security_groups` is not enough.
Please provide `security_group_ids` when create a new ec2 instance. You can
also create the instance without it, and add the security group later after
the instance is created.
**security_groups** (list of strings) – The names of the EC2 classic security
groups with which to associate instances
**security_group_ids** (list of strings) – The ID of the VPC security groups
with which to associate instances.
### Notes, maybe there is one more problem in your code. which @jarmod has
pointed it out
`i-41ffc2c0` is not ami id, it is a ec2 instance id. You need update it as
well.
|
Python write random integers to file on newline
Question: I need to make a program that generates 10 random integers between 10 and 90
and calls two separate functions to perform separate actions. The first one
(`playlist`) simply needs to print them all on one line without spaces, which
was easy. The second one (`savelist`) is giving me problems. I need to write
every number in the list `nums` to `angles.txt` with each number on a separate
line in order. No matter what I try I can't get them on separate lines and it
appears as one string on a single line. What am I missing?
import random
def main():
nums = []
# Creates empty list 'nums'
for n in range(10):
number = random.randint(10, 90)
nums.append(number)
# Adds 10 random integers to list
playlist(nums)
savelist(nums)
def playlist(numb):
index = 0
while index < len(numb):
print(numb[index], end=' ')
index += 1
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
myfile.write(str(number) + '\n')
myfile.close()
main()
Answer: In savelist(), you need to loop through the list:
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for e in number:
myfile.write(str(e))
myfile.close()
When you send "nums" to savelist(), you are sending a list. If you just try to
write "numbers" to the file, it's going to write the whole list. So, by
looping through each element in the list, you can write each line to the file.
|
Extracting raw data from a PowerPivot model using Python
Question: What seemed like a trivial task turned into a real nightmare when I had to
read some data from a PowerPivot model using Python. I believe I've researched
this very well over the last couple of days but now I hit a brick wall and
would appreciate some help from the Python/SSAS/ADO community.
Basically, all I want to do is programmatically access raw data stored in
PowerPivot models - my idea was to connect to the underlying PowerPivot (i.e.
MS Analysis Services) engine via one of the methods listed below, list the
tables contained in the model, then extract the raw data from each table using
a simple DAX query (something like "EVALUATE (table_name")). Easy peasy,
right? Well, maybe not.
# Some Background Information
As you can see, I've tried several different approaches. I'll try to document
everything as carefully as possible so that those uninitiated in PowerPivot
functionality will have a good idea of what I'd like to do.
First of all, some background on programmatic access to Analysis Services
engine (it says 2005 SQL Server, but all of it ought to still be applicable):
<https://msdn.microsoft.com/en-us/library/ms345148.aspx> and
<https://msdn.microsoft.com/en-us/library/dn141152.aspx>
Sample Excel/PowerPivot file I'll be using in the example below can be found
here: <https://www.microsoft.com/en-us/download/details.aspx?id=102>
Note that I'm using Excel 2010, so some of my code is version-specific. E.g.
> wb.Connections["PowerPivot Data"].OLEDBConnection.ADOConnection
should be
> wb.Model.DataModelConnection.ModelConnection.ADOConnection
if you're using Excel 2013.
Connection string I'll be using throughout this question is based on the
information found here:
<https://social.technet.microsoft.com/Forums/sqlserver/en-
US/0b9499f6-f80f-4dcc-8ab9-c52574b14a70/connect-to-powerpivot-engine-with-c>
Also, some of the methods apparently require some sort of initialization of
the PowerPivot model prior to data retrieval. See here:
<https://gobansaor.wordpress.com/2011/08/31/automating-powerpivot-refresh-
operation-from-vba/>
Finally, here's a couple of links showing that this should be achievable (note
however, that these links mainly refer to C#, not Python):
* [Made connection to PowerPivot DataModel, how can I fill a dataset with it?](http://stackoverflow.com/questions/24763513/made-connection-to-powerpivot-datamodel-how-can-i-fill-a-dataset-with-it)
* [Connecting to PowerPivot with C#](http://stackoverflow.com/questions/8242557/connecting-to-powerpivot-with-c-sharp)
* [2013 C# connection to PowerPivot DataModel](http://stackoverflow.com/questions/24643366/2013-c-sharp-connection-to-powerpivot-datamodel)
* <http://tableaulove.tumblr.com/post/76758976141/connecting-tableau-and-powerpivot-it-just-works> (showing that external apps can in fact read PowerPivot model data - note that the Tableau add-in installs "Interop.ADODB.dll" assembly, which I guess is what it uses to access the PowerPivot data)
# Using ADOMD
import clr
clr.AddReference("Microsoft.AnalysisServices.AdomdClient")
import Microsoft.AnalysisServices.AdomdClient as ADOMD
ConnString="Provider=MSOLAP;Data Source=$Embedded$;Locale Identifier=1033;Location=H:\\PowerPivotTutorialSample.xlsx;SQLQueryMode=DataKeys"
Connection=ADOMD.AdomdConnection(ConnString)
Connection.Open()
Here, it appears the problem is that the PowerPivot model has not been
initialized:
> AdomdConnectionException: A connection cannot be made. Ensure that the
> server is running.
# Using AMO
import clr
clr.AddReference("Microsoft.AnalysisServices")
import Microsoft.AnalysisServices as AMO
ConnString="Provider=MSOLAP;Data Source=$Embedded$;Locale Identifier=1033;Location=H:\\PowerPivotTutorialSample.xlsx;SQLQueryMode=DataKeys"
AMOServer = AMO.Server()
AMOServer.Connect(ConnString)
Same story, "the server is not running":
> ConnectionException: A connection cannot be made. Ensure that the server is
> running.
Note that AMO is technically not used for querying data, but I included it as
one of the potential ways of connecting to the PowerPivot model.
# Using ADO.NET
import clr
clr.AddReference("System.Data")
import System.Data.OleDb as ADONET
ConnString="Provider=MSOLAP;Data Source=$Embedded$;Locale Identifier=1033;Location=H:\\PowerPivotTutorialSample.xlsx;SQLQueryMode=DataKeys"
ADONETconn = ADONET.OleDbConnection()
ADONETconn.ConnectionString = ConnString
ADONETconn.Open()
This is similar to <http://stackoverflow.com/a/301746>. Unfortunately, this
also doesn't work:
> OleDbException: OLE DB error: OLE DB or ODBC error: The following system
> error occurred: The requested name is valid, but no data of the requested
> type was found.
# Using ADO via adodbapi module
import adodbapi
ConnString="Provider=MSOLAP;Data Source=$Embedded$;Locale Identifier=1033;Location=H:\\PowerPivotTutorialSample.xlsx;SQLQueryMode=DataKeys"
conn = adodbapi.connect(ConnString)
Similar to [Oppposite Workings of OLEDB/ODBC between Python and MS Access
VBA](http://stackoverflow.com/q/25951912). The error I get is:
> OperationalError: (com_error(-2147352567, 'Exception occurred.', (0,
> u'Microsoft OLE DB Provider for SQL Server 2012 Analysis Services.', u'OLE
> DB error: OLE DB or ODBC error: The following system error occurred: The
> requested name is valid, but no data of the requested type was found...
This is basically the same problem as with ADO.NET above.
# Using ADO via Excel/win32com module
from win32com.client import Dispatch
xlfile="H:\\PowerPivotTutorialSample.xlsx"
xlApp=Dispatch("Excel.Application")
wb=xlApp.Workbooks.Open(xlfile)
wb.Connections["PowerPivot Data"].Refresh()
connection=wb.Connections["PowerPivot Data"].OLEDBConnection.ADOConnection
recordset=Dispatch('ADODB.Recordset')
DAXquery="EVALUATE(dbo_DimDate)"
recordset.Open(DAXquery,connection)
The idea for this approach came from the following blog post that uses VBA:
<http://www.powerpivotblog.nl/export-a-table-or-dax-query-from-power-pivot-to-
csv-using-vba/>. Note that this approach uses an explicit Refresh command that
initializes the model ("server"). Error:
> com_error: (-2147352567, 'Exception occurred.', (0, u'ADODB.Recordset',
> u'Arguments are of the wrong type, are out of acceptable range, or are in
> conflict with one another.', u'C:\Windows\HELP\ADO270.CHM', 1240641,
> -2146825287), None)
Here it appears the ADO connection has been established:
* type(connection) returns
> instance
* print(connection) returns
> Provider=MSOLAP.5;Persist Security Info=True;Initial
> Catalog=Microsoft_SQLServer_AnalysisServices;Data Source=$Embedded$;MDX
> Compatibility=1;Safety Options=2;ConnectTo=11.0;MDX Missing Member
> Mode=Error;Subqueries=2;Optimize Response=3;Cell Error Mode=TextValue
The problem, however, seems to be in the creation of the ADODB.Recordset
object.
# Using ADO via Excel/win32com - direct use of ADODB.Connection and
ADO.Recordset
from win32com.client import Dispatch
conn = Dispatch('ADODB.Connection')
ConnString="Provider=MSOLAP;Data Source=$Embedded$;Locale Identifier=1033;Location=H:\\PowerPivotTutorialSample.xlsx;SQLQueryMode=DataKeys"
conn.Open(ConnString)
Similar to <http://stackoverflow.com/a/12761442> and
<http://code.activestate.com/recipes/196462-query-access-using-ado-in-
win32-platform/>. Unfortunately, the error Python spits out is the same as in
the two examples above:
> com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB
> Provider for SQL Server 2012 Analysis Services.', u'OLE DB error: OLE DB or
> ODBC error: The following system error occurred: The requested name is
> valid, but no data of the requested type was found. ..', None, 0,
> -2147467259), None)
# Using ADO via Excel/win32com (direct use of ADODB.Connection and
ADO.Recordset together with refreshing the PowerPivot model)
from win32com.client import Dispatch
xlfile="H:\\PowerPivotTutorialSample.xlsx"
xlApp=Dispatch("Excel.Application")
wb=xlApp.Workbooks.Open(xlfile)
wb.Connections["PowerPivot Data"].Refresh()
ConnStringInternal="Provider=MSOLAP.5;Persist Security Info=True;Initial Catalog=Microsoft_SQLServer_AnalysisServices;Data Source=$Embedded$;MDX Compatibility=1;Safety Options=2;ConnectTo=11.0;MDX Missing Member Mode=Error;Optimize Response=3;Cell Error Mode=TextValue"
conn = Dispatch('ADODB.Connection')
conn.Open(ConnStringInternal)
I was hoping I can initialize an instance of Excel, then initialize the
PowerPivot model, and then create a connection using the internal connection
string Excel uses for embedded PowerPivot data (similar to
<http://stackoverflow.com/a/33580647> \- note that the connection string is
different from the one I've used elsewhere). Unfortunately, this doesn't work
and my guess is that Python starts the ADODB.Connection process in a separate
instance (I get the same error message when I execute the last three rows
without initializing Excel, etc.):
> com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB
> Provider for SQL Server 2012 Analysis Services.', u'Either the user, ******
> (masked), does not have access to the Microsoft_SQLServer_AnalysisServices
> database, or the database does not exist.', None, 0, -2147467259), None)
Answer: The problem with getting data out of PowerPivot is that the tabular engine in
PowerPivot runs in-process inside Excel and the **only** way to connect to
that engine is to have your code running inside Excel too. (I suspect that it
may use shared memory or some other transport, but it's definitely not
listening on a TCP port or a named pipe or anything like that which would
allow an external process to connect)
We do this in Dax Studio by running a C# VSTO Excel add-in in Excel. However
that was only designed to work for testing analytic queries, not for doing
bulk data extraction. We marshal the data across from the add-in to the UI
using a string variable so the entire dataset must be less than 2Gb or the
response gets truncated and you will see an "unrecognizable response" error
(the data is serialized into an XMLA rowset which is quite verbose so may see
it break when only extracting a few hundred Mb of data)
If you wanted to build a script to automate extracting all the raw data from a
model I don't think you will be able to do it with Python as I don't believe
you can get the python interpreter running in-process inside Excel. I would
look at using a vba macro like this one <http://www.powerpivotblog.nl/export-
a-table-or-dax-query-from-power-pivot-to-csv-using-vba/>
You should find that you can query the model for a list of tables with
something like "SELECT * FROM $SYSTEM.DBSCHEMA_TABLES" - you could then loop
over each table and extract with a variation of the code in the above link.
|
MultiThreading/Optimization Python Requests?
Question: I am trying to optimize this code, as of right now it runs 340 Requests in 10
mins. I have trying to get 1800 requests in 30 mins. Since I can run a request
every second, according to amazon api. Can I use multithreading with this code
to increase the number of runs??
However, I was reading in the full data to the main function, should I split
it now, how can I figure out how many each thread should take?
def newhmac():
return hmac.new(AWS_SECRET_ACCESS_KEY, digestmod=sha256)
def getSignedUrl(params):
hmac = newhmac()
action = 'GET'
server = "webservices.amazon.com"
path = "/onca/xml"
params['Version'] = '2013-08-01'
params['AWSAccessKeyId'] = AWS_ACCESS_KEY_ID
params['Service'] = 'AWSECommerceService'
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
key_values = [(urllib.quote(k), urllib.quote(v)) for k,v in params.items()]
key_values.sort()
paramstring = '&'.join(['%s=%s' % (k, v) for k, v in key_values])
urlstring = "http://" + server + path + "?" + \
('&'.join(['%s=%s' % (k, v) for k, v in key_values]))
hmac.update(action + "\n" + server + "\n" + path + "\n" + paramstring)
urlstring = urlstring + "&Signature="+\
urllib.quote(base64.encodestring(hmac.digest()).strip())
return urlstring
def readData():
data = []
with open("ASIN.csv") as f:
reader = csv.reader(f)
for row in reader:
data.append(row[0])
return data
def writeData(data):
with open("data.csv", "a") as f:
writer = csv.writer(f)
writer.writerows(data)
def main():
data = readData()
filtData = []
i = 0
count = 0
while(i < len(data) -10 ):
if (count %4 == 0):
time.sleep(1)
asins = ','.join([data[x] for x in range(i,i+10)])
params = {'ResponseGroup':'OfferFull,Offers',
'AssociateTag':'4chin-20',
'Operation':'ItemLookup',
'IdType':'ASIN',
'ItemId':asins}
url = getSignedUrl(params)
resp = requests.get(url)
responseSoup=BeautifulSoup(resp.text)
quantity = ['' if product.amount is None else product.amount.text for product in responseSoup.findAll("offersummary")]
price = ['' if product.lowestnewprice is None else product.lowestnewprice.formattedprice.text for product in responseSoup.findAll("offersummary")]
prime = ['' if product.iseligibleforprime is None else product.iseligibleforprime.text for product in responseSoup("offer")]
for zz in zip(asins.split(","), price,quantity,prime):
print zz
filtData.append(zz)
print i, len(filtData)
i+=10
count +=1
writeData(filtData)
threading.Timer(1.0, main).start()
Answer: If you are using python 3.2 you can use `concurrent.futures` library to make
it easy to launch tasks in multiple threads. e.g. here I am simulating running
10 url parsing job in parallel, each one of which takes 1 sec, if run
synchronously it would have taken 10 seconds but with thread pool of 10 should
take about 1 seconds
import time
from concurrent.futures import ThreadPoolExecutor
def parse_url(url):
time.sleep(1)
print(url)
return "done."
st = time.time()
with ThreadPoolExecutor(max_workers=10) as executor:
for i in range(10):
future = executor.submit(parse_url, "http://google.com/%s"%i)
print("total time: %s"%(time.time() - st))
Output:
http://google.com/0
http://google.com/1
http://google.com/2
http://google.com/3
http://google.com/4
http://google.com/5
http://google.com/6
http://google.com/7
http://google.com/8
http://google.com/9
total time: 1.0066466331481934
|
What exactly does 'use_idf' do when creating a TfidfTransformer in sklearn?
Question: I am using the TfidfTransformer from the sklearn package in Python 2.7.
As I was getting comfortable with the arguments, I became a bit confused about
`use_idf`, as in:
`TfidfVectorizer(use_idf=False).fit_transform(<corpus goes here>)`
What exactly does `use_idf` do when false or true?
Since we are generating a sparse Tfidf matrix, it doesn't make sense to have
an argument to _choose_ a sparse Tfidif matrix; that seems redundant.
[This post](http://stackoverflow.com/questions/22489264/is-a-countvectorizer-
the-same-as-tfidfvectorizer-with-use-idf-false) was interesting but didn't
seem to nail it.
The [documentation](http://scikit-
learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html)
says only, `Enable inverse-document-frequency reweighting`, which isn't very
illuminating.
Any comments appreciated.
**EDIT** I think I figured it out. It's real simple:
Text --> counts
Counts --> TF, meaning we just have raw counts or Counts --> TFIDF, meaning we
have weighted counts.
What was confusing me was...since they called it `TfidfVectorizer` I didn't
realize that was true only if you chose it to be a TFIDF. You could have also
use it to create just a TF.
Answer: In Term frequency (TF) calculation, all terms are considered equally
important. Even certain terms which have no importance in determining
relevance are treaded in the calculations.
Scaling down the weights for terms with high collection frequency helps the
calculations. Inverse Document Frequency reduces the TF weight of a term by a
factor that grows with its collection frequency. So Document frequency DF of
the term is used to scale its weight.
|
Regex in lxml for python
Question: I having trouble implementing regex within xpath command. My goal here is to
download the html contents of the main page, as well as the contents of all
hyperlinks on the main page. However, the program throws exceptions because
some of the href links do not connect to anything (ex. '//:javascript', or
'#'). How would I use regex in xpath? Is there an easier way to except non-
absolute hrefs?
from lxml import html
import requests
main_pg = requests.get("http://gazetaolekma.ru/")
with open("Sample.html","w", encoding='utf-8') as doc:
doc.write(main_pg.text)
tree = html.fromstring(main_pg.content)
hrefs = tree.xpath('//a[re:findall("^(http|https|ftp):.*")]/@href')
for href in hrefs:
link_page = requests.get(href)
with open("%s.html"%href[0:9], "w", encoding ='utf-8') as href_doc:
href_doc.write(link_page.text)
Answer: According to [the documentation](http://lxml.de/xpathxslt.html), `lxml`
support EXSLT extension, which, in turn, support regex :
> lxml supports XPath 1.0, XSLT 1.0 and the EXSLT extensions through libxml2
> and libxslt in a standards compliant way.
For example, using EXSLT
[`re:test()`](http://exslt.org/regexp/functions/test/) function :
....
ns = {'re': 'http://exslt.org/regular-expressions'}
hrefs = tree.xpath('//a[re:test(@href, "^(http|https|ftp):.*\b", "i")]/@href')
.....
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.