qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
56,331,413 | I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.
```
def main():
myBook = Book([{"name": 'John ... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56331413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11563937/"
] | Use a module from the [Data Persistence](https://docs.python.org/3/library/persistence.html) section of the standard library, or save it as [json](https://docs.python.org/3/library/json.html), or as a [csv file](https://docs.python.org/3/library/csv.html). | You just convert your list to array inside in function .
```
np.save('path/to/save', np.array(your_list))
```
to load :
```
arr=np.load(''path/to/save.npy').tolist()
```
I hope it will be helpful | 14,974 |
73,542,262 | I've created 3 files, `snek.py`, `requirements.txt` and `runsnek.py`. `runsnek.py` installs all the required modules in `requirements.txt` with pip and runs `snek.py`. Everything works fine on Windows 10, but when trying to run on Ubuntu (WSL2), an error is thrown:
```
❯ python runsnek.py
Requirement already up-to-dat... | 2022/08/30 | [
"https://Stackoverflow.com/questions/73542262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17747971/"
] | It seems you are using python2 in your WSL2 instance.
In the line `os.system('python snek.py')` it should run python2 instead of python3.
To correct the problem, you can change this line of code by `os.system('python3 snek.py')`. | Your `run` file can be simplified:
```
import sys, os
print('Running with ' + sys.executable)
os.system(sys.executable + ' -m pip install --upgrade -r requirements.txt')
os.system(sys.executable +' snek.py')
```
`sys.executable` always contains the path of the python interpreter running the current script. Using `py... | 14,982 |
72,097,284 | How can you set the desktop background to a solid color programmatically in python?
The reason I want this is to make myself a utility which changes the background color depending on which of several virtual desktops I'm using. | 2022/05/03 | [
"https://Stackoverflow.com/questions/72097284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/169774/"
] | With a little help of `row_number` analytic function:
```
SQL> ALTER TABLE dummy_test_table ADD batch_id VARCHAR2 (10);
Table altered.
SQL> UPDATE dummy_test_table a
2 SET a.batch_id =
3 (WITH
4 temp
5 AS
6 (SELECT seq_no,
7 ... | One option is to use `DENSE_RANK()` analytic function within a MERGE DML statement such as
```sql
MERGE INTO dummy_test_table d1
USING (SELECT seq_no, LPAD(DENSE_RANK() OVER(ORDER BY seq_no), 3, '0') AS dr
FROM dummy_test_table) d2
ON (d1.rowid = d2.rowid)
WHEN MATCHED THEN UPDATE SET d1.batch_id = dr
``... | 14,983 |
24,027,579 | I am working on a project where I have a client server model in python. I set up a server to monitor requests and send back data. PYZMQ supports: tcp, udp, pgm, epgm, inproc and ipc. I have been using tcp for interprocess communication, but have no idea what i should use for sending a request over the internet to a ser... | 2014/06/04 | [
"https://Stackoverflow.com/questions/24027579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2383037/"
] | Any particular reason you're not using `ipc` or `inproc` for interprocess communication?
Other than that, generally, you can consider `tcp` the universal communicator; it's not always the best choice, but no matter what (so long as you actually have an IP address) it will work.
Here's what you need to know when makin... | Over the internet, TCP or UDP are the usual choices. I don't know if pyzmq has its own delivery guarantees on top of the transport protocol. If it doesn't, TCP will guarantee in-order delivery of all messages, while UDP may drop messages if the network is congested.
If you don't know what you want, TCP is the simplest... | 14,984 |
42,972,184 | I am new to python. As part of my project, I am working with python2.7. I am dealing with multiple files in python. Here I am facing a problem to use a variable of particular function from another file which was I already imported in my current file.
Please help me to achieve this.
```
file1.py
class connect():
# ... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42972184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7167331/"
] | So you have edited it quite a bit since I started writing about conventions so I have started again.
First, your return statement is out of indentation, it should be indented into the output method.
```
def output():
a = "Hello"
data = // some operations
return data
```
Second, the convention in Python ... | One option you have is to return all the data you need from the function:
file1.py
```
class connect():
# Contains different definitions
def output():
a = "Hello"
data = // some operations
return a,data # Return all the variables as a tuple
```
file2.py
```
from file1 import conne... | 14,985 |
17,438,469 | This python3.3 code on win 7, why I got error:
```
import random
guesses_made = 0
name = raw_input('Hello! What is your name?\n')
number = random.randint(1, 20)
print "Well, {0}, I am thinking of a number between 1 and 20" # error here !!!
**print "Well, {0}, I am thinking of a number between 1 and 20"
... | 2013/07/03 | [
"https://Stackoverflow.com/questions/17438469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2420472/"
] | Two things:
In python 3, `raw_input()` [has been changed](http://docs.python.org/3.0/whatsnew/3.0.html#builtins) to `input()`.
Also, [`print` is no longer a statement but a function](http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function), so you must do:
```
print("Well, {0}, I am thinking of a number bet... | I think that last line should read:
```
print("Well, {0}, I am thinking of a number between 1 and 20".format(name))
```
This was tested. I am pretty new to p3.3, so go easy on me :) | 14,986 |
5,823,163 | I'm currently in the process of programming a server which can let clients interact with a piece of hardware. For the interested readers it's a device which monitors the wavelength of a set of lasers concurrently (and controls the lasers). The server should be able to broadcast the wavelengths (a list of floats) on a r... | 2011/04/28 | [
"https://Stackoverflow.com/questions/5823163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/729885/"
] | You can start the reactor in a dedicated thread, and then issue calls to it with [`blockingCallFromThread`](http://twistedmatrix.com/documents/11.0.0/api/twisted.internet.threads.html#blockingCallFromThread) from your existing "sequential" code.
Also, I'd recommend [AMP](http://twistedmatrix.com/documents/11.0.0/api/t... | Have you tried [zeromq](http://www.zeromq.org/)?
It's a library that simplifies working with sockets. It can operate over TCP and implements several topologies, such as publisher/subscriber (for broadcasting data, such as your laser readings) and request/response (that you can use for you control scheme).
There are b... | 14,987 |
11,274,290 | I have made a `.deb` of my app using [fpm](https://github.com/jordansissel/fpm/wiki):
```
fpm -s dir -t deb -n myapp -v 9 -a all -x "*.git" -x "*.bak" -x "*.orig" \
--after-remove debian/postrm --after-install debian/postinst \
--description "Automated build." -d mysql-client -d python-virtualenv home
```
Among oth... | 2012/06/30 | [
"https://Stackoverflow.com/questions/11274290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17498/"
] | I think the example script you copied is simply wrong. `postinst` is not
supposed to be called with any `install` or `upgrade` argument, ever.
The authoritative definition of the dpkg format is the Debian Policy
Manual. The current version describes `postinst` in [chapter
6](http://www.debian.org/doc/debian-policy/ch-m... | I believe the answer provided by Alan Curry is incorrect, at least as of 2015 and beyond.
There must be some fault with the way the that your package is built or an error in the `postinst` file which is causing your problem.
You can debug your install by adding the `-D` (debug) option to your command line i.e.:
... | 14,988 |
39,103,057 | Ok So ive been able to send mail and read mail but I am now trying to attach an attachment to the mail and it doesnt seem to append the document as expected. I dont get any errors but I also dont get the mail if I attempt to add the attachment.
The library im using is [here](https://github.com/Narcolapser/python-o365)... | 2016/08/23 | [
"https://Stackoverflow.com/questions/39103057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449832/"
] | I've reproduced your attached command as a
```
public class MyBehavior : Behavior<ListBox>
{
```
to a XAML
```
<ListBox SelectedItem="SelCust" Name="MyListBox" Loaded="MyListBox_Loaded" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Name" ItemsSource="{Binding Customers}">
<i:Interaction.B... | Why not simply scroll to the last value in your collection after you set the DataContext or ItemSource? No data will render until you set your data context, and until you exit the constructor. To my understanding if you do the following to steps in sequence in the constructor, it should work as expected.
```cs
listBox... | 14,991 |
8,029,363 | I am new to django. I have version 1.3.1 installed.
I have created two projects: **projectone** and **projecttwo** using django-admin.py
And in **projectone** I have an app called **blog** created using python manage.py startapp
In **projecttwo** setings.py file when put the following in installed\_apps:
```
INSTA... | 2011/11/06 | [
"https://Stackoverflow.com/questions/8029363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614954/"
] | Look at what manage.py does:
<https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-py-and-manage-py>
It dynamically adds your apps to the python path when you use it - i.e. when you are using **runserver** during development.
You have two separate projects so when you run either one you will only hav... | You are trying to install a **Project** in your INSTALLED\_APPS on settings.py, those are different projects. Instead you need to create just one project and create differents apps.
Remember that apps are meant to be reusable so if you need the blog app in other project just reuse it.
If you are new to Django you sho... | 14,992 |
7,459,766 | I got the below failure while trying to get MySQL-python installed on my Ubuntu/Linux Box.From the below it seem like the issue is `sh: mysql_config: not found`
Could someone advice me on what to do?
```
rmicro@ubuntu:~$ pip install MySQL-python
Downloading/unpacking MySQL-python
Downloading MySQL-python-1.2.3.tar.g... | 2011/09/18 | [
"https://Stackoverflow.com/questions/7459766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618677/"
] | On Ubuntu it is advised to use the distributions repository. So installing python-mysqldb should be straight forward:
```
sudo apt-get install python-mysqldb
```
If you actually want to use pip to install, which is as mentioned before not the suggested path but possible, please have a look at this previously asked q... | In python3 with virtualenv on a Ubuntu Bionic machine the following commands worked for me:
```
sudo apt install build-essential python-dev libmysqlclient-dev
sudo apt-get install libssl-dev
pip install mysqlclient
``` | 14,993 |
21,979,134 | If I do `print(1 >> 2)` I get 0.
If I do `print(2 << 1)` I get 4.
If I do `print(9 << 3)` I get 72
If I do `print(3 >> 9)` I get 0
What do `>>` and `<<` do in python? | 2014/02/24 | [
"https://Stackoverflow.com/questions/21979134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2840324/"
] | They are bitwise shift operators. For example, 2 has the binary equivalent 00000010, so 2 << 1 is 00000010 shifted left 1 time. This yields 00000100, which is 4.
1 >> 2 is 00000001 shifted right 2 times which is 00000000 (the 1 falls off the end after the first shift though, so 1>>1 is also 0), obviously that is 0. | Bitwise shift left and bitwise shift right. They're roughly equivalent to doubling (`<<`) or halving (`>>`) just like decimal shift left is roughly equivalent to multiplying by 10 and decimal shift right is roughly equivalent to dividing by 10. | 15,003 |
1,529,002 | So, I was playing around with Python while answering [this question](https://stackoverflow.com/questions/1528932/how-to-create-inline-objects-with-properties-in-python/), and I discovered that this is not valid:
```
o = object()
o.attr = 'hello'
```
due to an `AttributeError: 'object' object has no attribute 'attr'`... | 2009/10/07 | [
"https://Stackoverflow.com/questions/1529002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14902/"
] | To support arbitrary attribute assignment, an object needs a `__dict__`: a dict associated with the object, where arbitrary attributes can be stored. Otherwise, there's nowhere to *put* new attributes.
An instance of `object` does **not** carry around a `__dict__` -- if it did, before the horrible circular dependence ... | It is simply due to optimization.
Dicts are relatively large.
```
>>> import sys
>>> sys.getsizeof((lambda:1).__dict__)
140
```
Most (maybe all) classes that are defined in C do not have a dict for optimization.
If you look at the [source code](http://svn.python.org/view/python/trunk/Objects/object.c?revision=7445... | 15,004 |
68,968,534 | In Python 2, there is a comparison function.
>
> A comparison function is any callable that accept two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than.
>
>
>
In Python 3, the comparison function is replaced with a key function.
>
> ... | 2021/08/28 | [
"https://Stackoverflow.com/questions/68968534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839733/"
] | Consider how tuples *normally* compare: element by element, going to the next element when the current values are equal (sometimes called *lexicographic order*).
Our required comparison algorithm, rewritten in steps that match that general approach, is:
* First, we want to compare the `x` values, putting them in asce... | Since the original version of this was rec'd for deletion as supposedly not actually answering the question due to it... being too long, I guess?, here's a shorter version of the exact same answer that gives less insight but uses fewer words. (Yes, it was too long. It also answered the question. "omg tl;dr" shouldn't b... | 15,014 |
62,633,601 | I want to re-implement a certain API client, which is written in Python, in JavaScript. I fail to replicate the HMAC SHA256 signing function. For some keys the output is identical, but for some it is different. It appears that the output is the same when the key consists of printable characters after decoding its Base6... | 2020/06/29 | [
"https://Stackoverflow.com/questions/62633601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447243/"
] | The base64 encoded secret you are trying to give to CryptoJs does not represent a valid UTF-8 string, which CryptoJS requires. You can use [this tool](https://onlineutf8tools.com/convert-hexadecimal-to-utf8) to check for validity. `atob()` is encoding agnostic and just converts byte by byte, and does not check if it's ... | In the third example you are using different parameters in the python and JavaScript versions.
In python:
sign\_string('xTsHZGfWUmnIpSu+TaVraECU88O3j9qVjlwTWGb/C8k=', "my message")
In JavaScript:
sign\_string('pkmNNJw3alrpIBi5t5Pxuym00M211oN86IhLZVT8', "my message") | 15,017 |
43,216,256 | I am trying to do some deep learning work. For this, I first installed all the packages for deep learning in my Python environment.
Here is what I did.
In Anaconda, I created an environment called `tensorflow` as follows
```
conda create -n tensorflow
```
Then installed the data science Python packages, like Pan... | 2017/04/04 | [
"https://Stackoverflow.com/questions/43216256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2769240/"
] | I have found a fairly simple way to do this.
Initially, through your Anaconda Prompt, you can follow the steps in this official Tensorflow site - [here](https://www.tensorflow.org/install/install_windows). You have to follow the steps as is, no deviation.
Later, you open the Anaconda Navigator. In Anaconda Navigator,... | It is better to create new environment with new name ($newenv):`conda create -n $newenv tensorflow`
Then by using anaconda navigator under environment tab you can find newenv in the middle column.
By clicking on the play button open terminal and type: `activate tensorflow`
Then install tensorflow inside the newenv b... | 15,018 |
19,151,734 | I have data in the following format:
```
user,item,rating
1,1,3
1,2,2
2,1,2
2,4,1
```
and so on
I want to convert this in matrix form
So, the out put is like this
```
Item--> 1,2,3,4....
user
1 3,2,0,0....
2 2,0,0,1
```
....and so on..
How do I do this in python?
THanks | 2013/10/03 | [
"https://Stackoverflow.com/questions/19151734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | ```
data = [
(1,1,3),
(1,2,2),
(2,1,2),
(2,4,1),
]
#import csv
#with open('data.csv') as f:
# next(f) # Skip header
# data = [map(int, row) for row in csv.reader(f)]
# # Python 3.x: map(int, row) -> tuple(map(int, row))
n = max(max(user, item) for user, item, rating in data) # Get size of mat... | a different approach from @falsetru,
do you read from file in write to file?
may be work with dictionary
```
from collections import defaultdict
valdict=defaultdict(int)
nuser=0
nitem=0
for line in infile:
eachline=line.strip().split(",")
valdict[tuple(eachline[0:2])]=eachline[2]
nuser=max(nuser,eachlin... | 15,028 |
74,165,151 | Let's say I have following python code:
```
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure()
ax=plt.axes(projection='3d')
x=y=np.linspace(1,10,100)
X,Y=np.meshgrid(x,y)
Z=np.sin(X)**3+np.cos(Y)**3
ax.plot_surface(X,Y,Z)
plt.show()
```
How do I calculate from this code the gradient and plot it? I ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12548284/"
] | gradient is a vector. It has 2 components (in this case, since we are dealing with function ℝ²→ℝ, X,Y↦Z(X,Y)), one which is ∂Z/∂X, (also a function of X and Y), another which is ∂Z/∂Y.
So, np.gradients returns both. `np.gradient(Z)`, called with a 100×100 array of Z, returns a list [∂Z/∂X, ∂Z/∂Y], both being also 100×... | Here is the practical way to achieve it with Python:
```
import numpy as np
import matplotlib.pyplot as plt
# Some scalar function of interest:
def z(x, y):
return np.power(np.sin(x), 3) + np.power(np.cos(y), 3)
# Grid for gradient:
xmin, xmax = -7, 7
x = y = np.linspace(xmin, xmax, 100)
X, Y = np.meshgrid(x, y)... | 15,029 |
60,473,135 | I am using python 3.7 on Spyder. Here is my simple code to store string elements ['a','b'] in a list L as sympy symbols. As output, I have new list L with two Symbols [a,b] in it. But when I try to use these symbols in my calculation I get an error saying a & b are not defined. Any suggestions on how can I fix this?
B... | 2020/03/01 | [
"https://Stackoverflow.com/questions/60473135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11039234/"
] | Not knowing the second template argument to `std::array<>` means your `test` class should be templated as well.
```
template <std::size_t N>
class test
{
void function(const std::array<int, N> & myarr)
{
// ...
}
};
```
By the way, it's better to pass `myarr` as `const &`. | You could use an approach like:
```
#include<array>
using namespace std;
template <size_t N>
class test
{
void function(const array<int, N> & myarr)
{
/* My code */
}
};
```
But keep in mind that `std::array` is not a dynamic array. You have to know the sizes at compile time.
If you get to know... | 15,030 |
59,410,455 | I have an application with python, flask, and flask\_mysqldb. When I execute the first query, everything works fine, but the second query always throws an error (2006, server has gone away). Everything I found on the web says this error is a timeout issue, which doesn't seem to be my case because:
1 - I run the second... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59410455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5844134/"
] | >
> I've noticed that the same data stored inside integer had reversed byte order than when stored as char
>
>
>
This implies that the file was stored with different byte endianness than what the CPU uses. In the example output, you can see that the CPU uses little-endian (least significant byte first). Given that... | As @Mat briefly explained, you're running into something called "endianness". There's "Big Endian", where the most significant bits are at the beginning?! (yes, it's a bit counter-intuitive), and "Little Endian", where the least significant bits are at the beginning.
>
> For example: Arabic numerals are big endian. "... | 15,031 |
26,266,437 | I just installed python 2.7 and also pip to the 2.7 site package.
When I get the version with:
```
pip -V
```
It shows:
```
pip 1.3.1 from /usr/lib/python2.6/site-packages (python 2.6)
```
How do I use the 2.7 version of pip located at:
```
/usr/local/lib/python2.7/site-packages
``` | 2014/10/08 | [
"https://Stackoverflow.com/questions/26266437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84885/"
] | There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
```
which pip2.7
```
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install i... | An alternative is to call the `pip` module by using python2.7, as below:
```
python2.7 -m pip <commands>
```
For example, you could run `python2.7 -m pip install <package>` to install your favorite python modules. Here is a reference: <https://stackoverflow.com/a/50017310/4256346>.
In case the pip module has not ye... | 15,032 |
64,882,005 | I have a python list shown below. I want to remove all the elements after a specific character `''`
Note1: The number of elements before `''` can vary. I am developing a generic code.
Note2: There can be multiple `''` I want to remove after the first `''`
Note3: Slice is not applicable because it supports only integ... | 2020/11/17 | [
"https://Stackoverflow.com/questions/64882005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606112/"
] | ```
list = ['a', 'b', 'c', '', 'd', 'e']
list = list[:list.index('')]
#list is now ['a', 'b', 'c']
```
Explanation: `list.index('')` finds the first instance of `''` in the list. `list[:x]` gives the first `x` elements of the list. This code will throw an exception if `''` is not in the list. | You have a list and want to delete everything after a value that meets some sort of criteria. You can enumerate the list, searching for that value and delete the remaining slice. `list.index` will tell you the index of value that exactly matches some object like `""`.
```
test = ["foo", "bar", "" "baz", "", "quux"]
tr... | 15,038 |
30,744,415 | Like many before me I don´t succeed in installing a few Python packages (mysql, pycld2, etc.) on Windows. I have a Windows 8 machine, 64-bit, and Python 3.4. At first I got the well-known error "can´t find vcvarsall.bat - install VS C++ 10.0". This I tried to solve by installing MinGW and use that as compiler. This did... | 2015/06/09 | [
"https://Stackoverflow.com/questions/30744415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2069136/"
] | I would recommend installing Ubuntu (as a Ubuntu user), you can dual-boot. However, that isn't an answer.
MySQLClient (the fork for Python3) is available a precompiled binary from here:
<http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient>
Try to find precompiled binaries for simplicity sake. As far as troubleshoo... | I grew frustrated with trying to get python and other packages to compile/play nicely on Windows as well. Switching over to Ubuntu was a breath of fresh air, for sure.
The win32com package is made specifically for Windows hosts, so that could not longer be used, but there are other ways to achieve the same thing in Ub... | 15,040 |
32,330,838 | I am new to Python. I have a code both in python 3.x & python 2.x (Actually, it is a library which has been written in 2.x). I am calling a function in python 2.x from python 3.x. The library return a HTTPResponse (from python 2.x). I am not able to parse the HTTPResponse in my code (In Python 3.x).
**My request is :... | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5268513/"
] | This should work:
```
beans = {
myBean(MyBeanImpl) { bean ->
bean.scope = 'prototype'
someProperty = 42
otherProperty = "blue"
bookService = ref("bookService")
}
}
``` | I agree with Jeff Scott Brown.
How do you know it doesn't work? We're using Grails 2.3.9.
I have this in my resources.groovy:
```
httpBuilderPool(HTTPBuilder) { bean ->
bean.scope = 'prototype' // A new service is created every time it is injected into another class
client = ref('httpClientPool')
}
...... | 15,048 |
30,364,874 | I'm trying to teach myself python and I'm quite new to parsing concepts. I'm trying to parse the output from my fire service pager, it seems to follow a consistent pattern as follows:
```
(UNIT1, UNIT2, UNIT3) 911-STRU (Box# 12345) aBusiness 12345 Street aTown (Xstr CrossStreet1/CrossStreet2) building fire, persons re... | 2015/05/21 | [
"https://Stackoverflow.com/questions/30364874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4889516/"
] | I think your best/easiest option is to use [regular expressions](https://docs.python.org/2/library/re.html), defining a pattern that will match all or parts of your input string and extract the pieces that you're interested in.
[PyParsing](http://pyparsing.wikispaces.com/) will probably work fine too. I have not used... | If you know pyparsing, then it might be easier to go with it. The `()` can always be treated as optional. Pyparsing will make certain things easier out of the box.
If you are not so familiar with pyparsing, and your main goal is learning python, then hand craft your own parser in pure python. Nothing better at learni... | 15,049 |
21,331,730 | I want to install PHP on the server. and I want to install it with Python script. Can I include PHP (some version number) in the reqirements.txt file and install it on the server?
If not, then how can I install PHP on the server using a python script? | 2014/01/24 | [
"https://Stackoverflow.com/questions/21331730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1162512/"
] | You can get the counts by using
```
df.groupby([df.index.date, 'action']).count()
```
or you can plot directly using this method
```
df.groupby([df.index.date, 'action']).count().plot(kind='bar')
```
You could also just store the results to `count` and then plot it separately. This is assuming that your index i... | Starting from
```
mydate col_name
0 2000-12-29 00:10:00 action1
1 2000-12-29 00:20:00 action2
2 2000-12-29 00:30:00 action2
3 2000-12-29 00:40:00 action1
4 2000-12-29 00:50:00 action1
5 2000-12-31 00:10:00 action1
6 2000-12-31 00:20:00 action2
7 2000-12-31 00:30:00 action2
```
You can... | 15,050 |
40,821,733 | I'm currently using vagrant and set it up to connect to my local computer's port 5000 and when I move to localhost:5000, the default ubuntu webpage appears to confirm that I'm connected.
However, it tells me to manipulate the app using the index.html in there but I already have a whole Python flask app stored somewhe... | 2016/11/26 | [
"https://Stackoverflow.com/questions/40821733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4297337/"
] | Create a static field inside class, and increment it in constructor.
something like this:
```
class A {
public:
A() : itemnumber(nextNum) { ++nextNum; }
private:
int itemnumber;
static int nextNum;
}
// in CPP file initialize it
int A::nextNum = 1;
```
Also, don't forget to increment static field in co... | with a static variable like
```
class rect{
public:
static int num;
rect(){num++;}
};
int rect::num =0;
int main(){
rect a();
cout << rect::num;
}
``` | 15,053 |
49,469,409 | I am relatively new to programming.
I'm trying to run the following:
```
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
my_map = Basemap(projection = 'ortho', lat_0=50, lon_0=-100,
resolution = 'l', area_thresh=1000.0)
my_map.drawcoastlines()
my_map.drawc... | 2018/03/24 | [
"https://Stackoverflow.com/questions/49469409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9545845/"
] | The matplotlib deprecated the get\_axis\_bgcolor. You'll need to update basemap to version 1.1.0 to fix this error. It's installable via conda-forge, via:
```
conda install -c conda-forge basemap
```
In case you'll get error like, "Unable to open boundary dataset file. Only the 'crude' and 'low', resolution datasets... | In addition to [@user45237841](https://stackoverflow.com/users/8861059/user45237841)'s answer, you can also change the `resolution` to `c` or `l` to resolve this error `Unable to open boundary dataset file. Only the 'crude' and 'low', resolution datasets are installed by default.`
```
my_map = Basemap(projection = 'or... | 15,054 |
64,641,472 | Accidentally my python script has made a table with name as "ext\_data\_content\_modec --replace" which we want to delete.
However BQ doesn't seem to recognize the table with spaces and keywords(--replace).
We have tried many variants of bq rm , as well as tried deleting the from BQ console but it doesn't work
For e... | 2020/11/02 | [
"https://Stackoverflow.com/questions/64641472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13078109/"
] | You would do something like this:
```
Map<String, B> bById = ...
Map<String, B> bByName = ...
for (A a : listA) {
B b = bById.getOrDefault(a.id, bByName.get(a.name));
if (b != null) {
a.setPersonalDetails(b.getPersonalDetails);
}
}
``` | you can use comparator to achieve this.Just a example psudo code is given below
```java
Collections.sort(listA, Comparator.comparing(A::getId)
.thenComparing(A::getName)
.thenComparing(A::getAge));
``` | 15,059 |
50,863,799 | I'm pretty new to Python, but have Python 3.6 installed, and running a few other programs perfectly. I'm trying to pull data using the pandas\_datareader module but keep running into this issue. Operating system: OSX.I've visited the other threads on similar errors and tried their methods to no avail.
Additional conc... | 2018/06/14 | [
"https://Stackoverflow.com/questions/50863799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7075311/"
] | As has been noted, `is_list_like` has been moved from `pandas.core.common` to `pandas.api.types`.
There are several paths forward for you.
1. My (highly) recommended solution: download Conda and set up an environment with a version of Pandas prior to v0.23.0.
2. You can install the development version of Pandas, with... | Small workaround is to define it like this:
```
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader
``` | 15,060 |
4,645,822 | I've been struggling with the [cutting stock problem](http://en.wikipedia.org/wiki/Cutting_stock_problem) for a while, and I need to do a funcion that given an array of values, gives me an array of array for all the possible combinations.
I trying to do this function, but (as everything in python), I think someone mus... | 2011/01/10 | [
"https://Stackoverflow.com/questions/4645822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
>>> from itertools import permutations
>>> x = range(3)
>>> list(permutations(x))
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
>>>
``` | Do you mean [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations)? | 15,061 |
22,476,489 | We can convert a `datetime` value in to decimal using following function.
```
import time
from datetime import datetime
t = datetime.now()
t1 = t.timetuple()
print time.mktime(t1)
```
Output :
```
Out[9]: 1395136322.0
```
Similarly is there a way to convert strings in to a `decimal` using python?.
Example str... | 2014/03/18 | [
"https://Stackoverflow.com/questions/22476489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461436/"
] | If you want an integer to uniquely identify a string, I'd go for hashing functions, like SHA. They return the same value for the same input.
```
import hashlib
def sha256_hash_as_int(s):
return int(hashlib.sha256(s).hexdigest(), 16)
```
If you use Python 3, you first have to encode `s` to some concrete encoding,... | You can use [hash](http://docs.python.org/2.7/library/functions.html#hash) function:
```
>>> hash("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0")
1892010093
``` | 15,063 |
37,737,098 | I have a string time coming from a third party (external to my python program), and I need to compare that time to right now. How long ago was that time?
How can I do this?
I've looked at the `datetime` and `time` libraries, as well as `pytz`, and can't find an obvious way to do this. It should automatically incorpor... | 2016/06/09 | [
"https://Stackoverflow.com/questions/37737098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6365333/"
] | Signing a commit will change the commit metadata, and thus change the underlying SHA1 commit ID. As you probably know, for Git, this has the same consequence of trying to change the contents of your history.
If you want to just re-sign your last commit you could run:
`git commit -S --amend`
If you want to re-sign a ... | If you want to sign all the existing commits on the branch without do any changes to them:
```
git rebase --exec 'git commit --amend --no-edit -n -S' -i origin/HEAD
``` | 15,064 |
22,486,519 | I am trying to create a fabric script that will install the erlang solutions R15B02 package and am having some difficulty. I have the following code in my fabric script:
```
sudo("apt-get update")
sudo("apt-get -qy install python-software-properties")
sudo('add-apt-repository "deb http://packages.erlang-soluti... | 2014/03/18 | [
"https://Stackoverflow.com/questions/22486519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232337/"
] | You can also use one of these projects for installing and managing different versions of Erlang on the same computer:
* <https://github.com/spawngrid/kerl>
* <https://github.com/metadave/erln8> | If you can find the file 'esl-erlang\_15.b.2-1~ubuntu~precise\_i386.deb' or the 64 bit version, those could be installed with dpkg. If you find these, to install both at once, extract the .deb with `dpkg -x esl-erlang_15.b.2-1~ubuntu~precise_i386.deb` and move the binaries inside somewhere else. If you can't find that ... | 15,067 |
68,076,036 | In my main directory I have two programs: `main.py` and a myfolder (which is a directory).
The `main.py` file has these 2 lines:
```
from myfolder import Adding
print(Adding.execute())
```
Inside the myfolder directory, I have 3 python files only: `__init__.py`, `abstract_math_ops.py`, and `adding.py`.
The `__ini... | 2021/06/22 | [
"https://Stackoverflow.com/questions/68076036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7705108/"
] | Your folder is a package, and you can't import sibling-submodules of a package in the way you're trying to do in `adding.py`. You either need to use an absolute import (`from myfolder.abstract_math_ops import AbstractMathOps`, which works the same anywhere), or use an explicit relative import (`from .abstract_math_ops ... | Try with:
```
from .abstract_math_ops import AbstractMathOps
```
You need to add the relative location of the file for the import to work in this case. | 15,068 |
51,156,919 | I'm currently reading a dummy.txt, the content showing as below:
```
8t1080 0.077500 0.092123 -0.079937
63mh9j 0.327872 -0.074191 -0.014623
63l2o3 0.504010 0.356935 -0.275896
64c97u 0.107409 0.021140 -0.000909
```
Now, I am reading it using python like below:
```
lines = open("dummy.txt", "r").readlines()
```
I w... | 2018/07/03 | [
"https://Stackoverflow.com/questions/51156919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8221657/"
] | You would greatly benefit from [`pandas`](https://pandas.pydata.org/) in this case:
```
import pandas as pd
df = pd.read_csv('dummy.txt', sep=' ', header=None)
>>> df.values
array([['8t1080', 0.0775, 0.092123, -0.079937],
['63mh9j', 0.327872, -0.074191, -0.014622999999999999],
['63l2o3', 0.50401000000... | In your first case it IS working, however each time the for loops the line variable is reset to the next value, and its current value is lost to recieve the next one.
```
aux=[]
for line in lines: #here the program changes the value of line
line = line.split() # here you change the value of line
for x in range... | 15,069 |
43,113,717 | I have the text file like this
```
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxx... | 2017/03/30 | [
"https://Stackoverflow.com/questions/43113717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3636467/"
] | yes, using @IdClass annotation.
```
@Entity
@IdClass(EmployeeKey.class)
public class Employee {
@Id
private int id;
@Id
private int departmendId;
}
public class EmployeeKey implements Serializable {
private int id;
private int departmendId;
}
public interface EmployeeRepository extends JpaReposit... | Even if the underlying table does not have an explicit primary key specified, I am sure there is at least one column that is defined as unique (or has a unique index specified for it).
You can add the @Id annotation to the entity field relevant to that column and that will the sufficient for the persistence provider.... | 15,071 |
30,625,787 | This might seem simple but it has flummoxed me for a day, so I'm turning to ya'll.
I have a valid Python dictionary:
```
{'numeric_int2': {'(113.7, 211.4]': 3,
'(15.023, 113.7]': 4,
'(211.4, 309.1]': 5,
'(309.1, 406.8]': 4,
'(406.8, 504.5]': 5,
'(504.5, 602.2]': 7,
'(602.2, 699.9]': 4,
'(699.9, 797.6]':... | 2015/06/03 | [
"https://Stackoverflow.com/questions/30625787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935984/"
] | **it appears both simplejson and json work as expected to me**, however
simplejson is faster than json(by quite a bit) and it seems to work fine with your data
```
import simplejson,json
print simplejson.dumps({'numeric_int2': {'(113.7, 211.4]': 3,
'(15.023, 113.7]': 4,
'(211.4, 309.1]': 5,
'(309.1, 406.8]': 4,
'(406.... | Found the answer. Here is the function that works:
```
# Count the frequency of each value
def count_by_value(df,columns):
# Selects appropriate columns for the action
numeric = [c[0] for c in columns if c[1] == 'numeric']
# Returns 0 if none of the appropriate columns exists
if len(numeric) == 0:
... | 15,072 |
59,146,674 | I have a batch file which is running a python script and in the python script, I have a subprocess function which is being ran.
I have tried `subprocess.check_output`, `subprocess.run`, `subprocess.Popen`, all of them returns me an empty string only when running it using a batch file.
If I run it manually or using an... | 2019/12/02 | [
"https://Stackoverflow.com/questions/59146674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2865368/"
] | Updated
-------
First of all, if there is a need to run `anaconda-prompt` by calling `activate.bat` file, you can simply do as follows:
```
import subprocess
def call_anaconda_venv():
subprocess.call('python -m venv virtual.env')
subprocess.call('cmd.exe /k /path/venv/Scripts/activate.bat')
if __name__ == "... | This is happening because your ide is not running in a shell that works in the way that open subprocess is expecting.
If you set SHELL=False and specify the absolute path to the batch file it will run.
you might still need the cwd if the batch file requires it. | 15,073 |
34,339,867 | I am trying to match the following strings:
```
2 match virtual-address 172.29.210.119 tcp eq www
4 match virtual-address 172.29.210.147 tcp any
```
The expected output:
```
172.29.210.119
tcp
www
172.29.210.147
tcp
any
```
I am using pattern:
```
match virtual-address (\d+\.\d+\.\d+\.\d+)\s?(\w+)?... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34339867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4611991/"
] | You can use this regex in Python:
```
\bmatch virtual-address (\d+\.\d+\.\d+\.\d+)\s?(\w+) (?:eq\s+)?(\w+)
```
[RegEx Demo](https://regex101.com/r/tX8mB2/1)
Python regex doesn't support *Atomic Group* syntax `(?>..)` like PCRE. | If you modify the flavor of regex101 for "python", you will see that you can not use `(?>eq)?`
An alternative to what you want is to use `$`, to assert position at end of a line. Using `(\w+)$` will catch the last of the string sentence.
```
import re
text = [
'2 match virtual-address 172.29.210.119 tcp eq www',... | 15,074 |
22,976,523 | I'm working on a small app that pulls data out of a list stored in a list, passes it through a class init, and then displays/allows user to work. Everything was going fine until i tried to format the original 'list' in the IDLE so it was easier to read (for me). so I'd change 9 to 09, 8 to 08. etc It was a simple forma... | 2014/04/10 | [
"https://Stackoverflow.com/questions/22976523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2584933/"
] | It's nothing to do with lists or strings. When you prefix a number with `0`, it's interpreted as [octal](http://en.wikipedia.org/wiki/Octal). And 9 is not a valid octal digit!
```
Python 2.7.6
Type "help", "copyright", "credits" or "license" for more information.
>>> 09
File "<stdin>", line 1
09
^
SyntaxEr... | It's not just Python, it's most programming languages. Starting a number with a zero signifies that the number is in octal, which means only digits `0-7` are valid. Thus,
```
5 == 05
6 == 06
7 == 07
8 == 010
9 == 011
...
15 == 017
16 == 020
...
255 == 0377
```
Similarly, prefix `0x` means the number is hexadecimal (... | 15,075 |
23,120,865 | Apologies if this is a basic question, but let us say I have a tab delimited file named `file.txt` formatted as follows:
```
Label-A [tab] Value-1
Label-B [tab] Value-2
Label-C [tab] Value-3
[...]
Label-i [tab] Value-n
```
I want [xlrd](https://pypi.python.org/pypi/xlrd) or [openpyxl](htt... | 2014/04/16 | [
"https://Stackoverflow.com/questions/23120865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3543052/"
] | Since you said you are used to working in Bash, I'm assuming you're using some kind of Unix/Linux, so here's something that will work on Linux.
Before pasting the code, I'd like to point a few things:
Working with Excel in Unix (and Python) is not that straightforward. For instance, you can't open an Excel sheet for ... | That's a job for VBA, but if I had to do it in Python I would do something like this:
```
import Excel
xl = Excel.ExcelApp(False)
wb = xl.app.Workbooks("MyWorkBook.xlsx")
wb.Sheets("Ass'y").Cells(1, 1).Value2 = "something"
wb.Save()
```
With an helper `Excel.py` class like this:
```
import win32com.client
class Ex... | 15,078 |
2,830,953 | I have a script which contains two classes. (I'm obviously deleting a lot of stuff that I don't believe is relevant to the error I'm dealing with.) The eventual task is to create a decision tree, as I mentioned in [this](https://stackoverflow.com/questions/2726167/parse-a-csv-file-using-python-to-make-a-decision-tree-l... | 2010/05/13 | [
"https://Stackoverflow.com/questions/2830953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27290/"
] | This is fairly easy.
```
var timerID;
$("#left").hover(function() {
timerID = setInterval(slideLeft, 1000);
}, function() {
clearInterval(timerID);
});
function slideLeft() {
$("#slider").animate({left: -30});
}
```
and similar for right.
You only need to use `hover()` if there's something you need to stop w... | You don't have to check where the mouse is, as the `mouseout` event will be triggered when the mouse leaves the element.
To make the movement repeat while the mouse is hovering the element, start an interval that you stop when the mouse leaves the element:
```
$(function(){
var moveInterval;
$('#moveLeft').hove... | 15,080 |
69,512,596 | I've recently started learning how to code in python. I wanted to know if there is a norm or specific rule for the position of statements while using functions.
eg:
```
def example(x):
y = 7
print("Default value is", y)
print("Value entered is", x)
a = int(input("Enter a value: "))
example(a)
```
Would... | 2021/10/10 | [
"https://Stackoverflow.com/questions/69512596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17117924/"
] | In larger programs, pretty much everything will be in functions (or methods, which are a kind of function). The only code at the top level will be a couple of lines to call the first function (often called `main`).
The question then is whether to put the `input` into the same function, or into separate functions. That... | If the result of input statement will only be used inside one function, then moving the statement into that function might be better in the future when your code becomes more complex | 15,081 |
4,646,659 | How to convert the web site develpoed in django, python into desktop application.
I am new to python and django can you please help me out
Thanks in Advance | 2011/01/10 | [
"https://Stackoverflow.com/questions/4646659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569806/"
] | I would try to replicate the Django application functionality with the [PyQt toolkit](http://www.riverbankcomputing.co.uk/software/pyqt/intro).
You can in fact embed web content in PyQt applications, with the help of QtWebKit. I would post some potentially useful links, but apparently I have too low a reputation to po... | I have `django manage.py runserver` in .bat file and a localhost bookmark bar in a browser and whola a django-desktop-app. Or make your own browser that opens localhost. [Creating a web-browser with Python and PyQT](https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/) | 15,082 |
11,170,478 | I have a command line program developed in c. Lets say, i have a parser written in C. Now i am developing a project with gui in python and i need that parser for python project. In c we can invoke a system call and redirect the output to system.out or a file. Is there are any way to do this python? I have both code and... | 2012/06/23 | [
"https://Stackoverflow.com/questions/11170478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1135245/"
] | I would not expect MySQL to give that error message, but many other databases do. In other databases you can work around it by repeating the column definition:
```
SELECT amount1 + amount2 as totalamount
FROM Donation
WHERE amount1 + amount2 > 1000
```
Or you can use a subquery to avoid the repitition:
```
S... | No way.
**WHERE** filters column while **HAVING** filters on aggregates.
See [SQL Having](http://www.w3schools.com/sql/sql_having.asp) | 15,092 |
6,418,199 | I was looking up the pypy project (Python in Python), and started pondering the issue of what is running the outer layer of python? Surely, I conjectured, it can't be as the old saying goes "turtles all the way down"! Afterall, python is not valid x86 assembly!
Soon I remembered the concept of bootstrapping, and look... | 2011/06/20 | [
"https://Stackoverflow.com/questions/6418199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322900/"
] | >
> In the interest of performance, I'm sure C compilers are just built up from assembly.
>
>
>
C compilers are, nowadays, (almost?) completely written in C (or higher-level languages - Clang is C++, for instance). Compilers gain little to nothing from including hand-written assembly code. The things that take mo... | If you buy a new machine with a pre-installed OS, it doesn't even need to include a compiler anywhere, because all the executable code has been compiled on some other machine, by whoever provides the OS - your machine doesn't need to compile anything itself.
How do you get to this point if you have a completely new CP... | 15,095 |
37,959,217 | I'm using PM2 to run a Python program in the background like so
`pm2 start helloworld.py`
and it works perfectly fine. However, within `helloworld.py` I have several print statements that act as logs. For example, when a network request comes in or if a database value is updated. When I run `helloworld.py` like so:
... | 2016/06/22 | [
"https://Stackoverflow.com/questions/37959217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896112/"
] | This question is a few months old, so maybe you figured this out a while ago, but it was one of the top google hits when I was having the same problem so I thought I'd add what I found.
Seems like it's an issue with how python buffers sys.stdout. In some platforms/instances, when called by say pm2 or nohup, the sys.st... | Check the folder #HOME/.pm2/logs
See for example the folder structure section here: <http://pm2.keymetrics.io/docs/usage/quick-start/>
Also consider using a configuration file with an explicit logs folder that is relative to your scripts. (Note this folder must exist before pm2 can use it.) See <http://pm2.keymetrics... | 15,098 |
41,247,600 | For the following two dataframes:
```
df1 = pd.DataFrame({'name': pd.Series(["A", "B", "C"]), 'value': pd.Series([1., 2., 3.])})
name value
0 A 1.0
1 B 2.0
2 C 3.0
df2 = pd.DataFrame({'name': pd.Series(["A", "C", "D"]), 'value': pd.Series([1., 3., 5.])})
name value
0 A 1.0
1 C... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41247600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424484/"
] | You can use [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html):
```
print (df2[df2["name"].isin(df1["name"])])
name value
0 A 1.0
1 C 3.0
```
Another faster solution with [`numpy.intersect1d`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.intersect1d.h... | Slightly different method that might be useful on your actual data, you could use an "inner join" (the intersection) a la SQL. More useful if your columns aren't duplicated in both data frames (e.g. merging two different data sets with some common key)
```
df1 = pd.DataFrame({'name': pd.Series(["A", "B", "C"]), 'value... | 15,099 |
70,026,043 | I'm trying to figure out why I'm getting this error message.
I'm running the webdriver.Chrome() with selenium in a Windows environment.
When I run:
```
driver.get("http://www.google.com")
```
Or any url for that matter, python returns an HTML doc to the terminal saying;
```
Access denied, your system policy has d... | 2021/11/18 | [
"https://Stackoverflow.com/questions/70026043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16909626/"
] | An alternative to using `upvar` is to use `set <var_name>` to retrieve the value of var\_name. When <var\_name> is `${mod}_sig`, then you can use `set` to retrieve the value of the variable without the possibility of altering the value of the original variable (like `upvar`)
```
set modules {moduleA moduleB moduleC}
... | This is where you want the [`upvar`](https://www.tcl-lang.org/man/tcl8.6/TclCmd/upvar.htm) command
to "alias" one variable to another.
```
set modules {moduleA moduleB moduleC}
set moduleA_sig {1 2 3 4}
set moduleB_sig {11 22 33 44}
set moduleC_sig {111 222 333 444}
foreach mod $modules {
upvar 0 ${mod}_sig this... | 15,100 |
41,789,133 | Tensorflow r0.12's documentation for tf.nn.rnn\_cell.LSTMCell describes this as the init:
```
tf.nn.rnn_cell.LSTMCell.__call__(inputs, state, scope=None)
```
where `state` is as follows:
>
> state: if state\_is\_tuple is False, this must be a state Tensor, 2-D, batch x state\_size. If state\_is\_tuple is True, thi... | 2017/01/22 | [
"https://Stackoverflow.com/questions/41789133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5299052/"
] | I've stumbled upon same question, here's how I understand it! Minimalistic LSTM example:
```
import tensorflow as tf
sample_input = tf.constant([[1,2,3]],dtype=tf.float32)
LSTM_CELL_SIZE = 2
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(LSTM_CELL_SIZE, state_is_tuple=True)
state = (tf.zeros([1,LSTM_CELL_SIZE]),)*2
outp... | Maybe this excerpt from the code will help
```
def __call__(self, inputs, state, scope=None):
"""Long short-term memory cell (LSTM)."""
with vs.variable_scope(scope or type(self).__name__): # "BasicLSTMCell"
# Parameters of gates are concatenated into one multiply for efficiency.
if self._state_is_tuple:
... | 15,102 |
71,524,462 | I'm coding a little tool that displays the key presses on the screen with Tkinter, useful for screen recording.
**Is there a way to get a listener for all key presses of the system *globally* with Tkinter?** (for every keystroke including `F1`, `CTRL`, ..., even when the Tkinter window does not have the focus)
I curr... | 2022/03/18 | [
"https://Stackoverflow.com/questions/71524462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422096/"
] | **Solution 1**: if you need to catch keyboard events in your current window, you can use:
```
from tkinter import *
def key_press(event):
key = event.char
print(f"'{key}' is pressed")
root = Tk()
root.geometry('640x480')
root.bind('<Key>', key_press)
mainloop()
```
**Solution 2**: if you want to capture ke... | As suggested in [tkinter using two keys at the same time](https://stackoverflow.com/questions/39606019/tkinter-using-two-keys-at-the-same-time), you can detect all key pressed at the same time with the following:
```py
history = []
def keyup(e):
print(e.keycode)
if e.keycode in history :
history.pop(... | 15,108 |
56,600,918 | When you call DataFrame.to\_numpy(), pandas will find the NumPy dtype that can hold all of the dtypes in the DataFrame. But how to perform the reverse operation?
I have an 'numpy.ndarray' object 'pred'. It looks like this:
>
> [[0.00599913 0.00506044 0.00508315 ... 0.00540191 0.00542058 0.00542058]]
>
>
>
I am t... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56600918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11376406/"
] | `pred` is an `ndarray`. It does not have a `to_csv` method. That's something a `pandas` `DataFrame` has.
But lets look at the first stuff.
Copying your array display, adding commas, lets me make a list:
```
In [1]: alist = [[0.00599913, 0.00506044, 0.00508315, 0.00540191, 0.00542058, 0.
...: 00542058]] ... | ```py
import numpy as np
import pandas as pd
x = [1,2,3,4,5,6,7]
x = np.array(x)
y = pd.Series(x)
print(y)
y.to_csv('a.csv')
``` | 15,109 |
56,651,258 | I am trying to install the **owlready2** lib in Ubuntu by following the method below but I face a problem.
* I updated the system and applications
* Installed Python 3 and made it the working version (default)
* Installed pip3
* Used pip and pip3 to install the owlready2 lib
But I faced the below problem which seems ... | 2019/06/18 | [
"https://Stackoverflow.com/questions/56651258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851759/"
] | Try to install your package with the following command:
```
python3 -m pip install -I owlready2
```
If pip3 does not work, you also install Owlready2 manually : download the sources, then run in a terminal:
```
cd /path/to/Owlready2
python setup.py build
python setup.py install # as root
```
Also, that would b... | I encountered the same problem.
It seems that the issue might lie in something that was added in version 0.14 (at the time of writing the newest version is 0.19). If the owlready2 version is newer than 0.13 then you will encounter the problem.
I have tested these Python versions - 3.7.3 (works), 3.6.8(works), 3.5.2... | 15,112 |
12,199,819 | I'm a beginner programmer, and i've been trying to use the python markdown library in my web app. everything works fine, except the nl2br extension.
When I tried to convert text file to html using md.convert(text), it doesn't see to convert newlines to `<br>`.
for example, before I convert, the text is:
```
Puerto R... | 2012/08/30 | [
"https://Stackoverflow.com/questions/12199819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623886/"
] | Try adding two or more white spaces at the end of a line to insert `<br/>` tags
Example:
```
hello
world
```
results in
```
<p>hello <br>
world</p>
```
Notice that there are two spaces after the word hello. This only works if you have some text before the two spaces at the end of a line. But this has nothing t... | Found this question looking for a clarification myself. Hence adding an update despite being 7 years late.
---
Reference thread on the Python Markdown Project: <https://github.com/Python-Markdown/markdown/issues/707>
Turns out that this is indeed the expected behaviour, and hence, the `nl2br` extension converts onl... | 15,113 |
44,548,111 | I am working on a **SaaS** solution currently provisioning **sonarqube and gerrit** applications on kubernetes.
As part of that I want to create a new schema in my postgres database for every new application that I provision. Application is connecting using following connection string, (i.e., instance1, instance2, ins... | 2017/06/14 | [
"https://Stackoverflow.com/questions/44548111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4189388/"
] | for those kind of operation it would be better to use collections,
the method [removeAll()](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#removeAll-java.util.Collection-) will filter the data containers, from the doc:
>
> Removes from this list all of its elements that are contained in the
> specifi... | You may try this:
```
a.removeAll(b);
``` | 15,114 |
70,545,797 | I have this image for a treeline crop. I need to find the general direction in which the crop is aligned. I'm trying to get the Hough lines of the image, and then find the mode of distribution of angles.[](https://i.stack.imgur.com/8GWAX.jpg)
I've been following [t... | 2021/12/31 | [
"https://Stackoverflow.com/questions/70545797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15230180/"
] | You can use a **2D FFT** to find the general direction in which the crop is aligned (as proposed by mozway in the comments). The idea is that the general direction can be easily extracted from *centred beaming rays appearing in the magnitude spectrum* when the input contains many lines in the same direction. You can fi... | Just for completeness I would like to post the Sobel Gradient Angle way as well.
General idea:
1. for every pixel, compute X and Y gradient (e.g. with Sobel)
2. Compute the angle from the X and Y gradient information and their distribution
3. find the modes e.g. with a histogram and select the highest one
Written in... | 15,119 |
10,308,340 | I have a list of rules for a given input file for my function. If any of them are violated in the file given, I want my program to return an error message and quit.
* Every gene in the file should be on the same chromosome
Thus for a lines such as:
NM\_001003443 chr11 + 5997152 5927598 5921052 5926098 1 5928752,5925... | 2012/04/25 | [
"https://Stackoverflow.com/questions/10308340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1348509/"
] | Just read the file and have a while loop check each line to make sure it contains `chr11`. There are string functions to search for substrings in a string. As soon as you find a line that returns false (does not contain `chr11`) then break out of the loop and set a flag `valid = false`.
```
import re
fp = open(infile... | Is it safe to assume that the first chr is the correct one? If so, use this:
```
import re
chrlist = re.findall("chr[0-9]+", open('file').read())
# ^ this is a list with all chr(whatever numbers)
for chr in chrlist:
if chr != chrlist[0]
print("Chr does not match")
break
``` | 15,120 |
71,186,021 | I´m new into python, so I apreciate any help.
I´m trying to develope a code that can search for a specific word in a csv file, but I don´t why he doesn´t recognize a word that I know it is in the program. I'm always getting "Não encontrei".
My code:
```
#Definir perfis
def pilar():
pilar = input("Perfil do pilar... | 2022/02/19 | [
"https://Stackoverflow.com/questions/71186021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | An enum without associated values conforms implicitly to Equatable **and** Hashable.
From the documentation:
[Hashable](https://developer.apple.com/documentation/swift/hashable/)
>
> When you define an enumeration without associated values, it gains Hashable conformance automatically, and you can add Hashable confo... | To chime in:
If you *did* want to implement `==` yourself, the way to do it would be with pattern matching. Surprisingly (to me), the code below seems to call neither `~=` nor `==`.
```
enum TestEnum: Equatable {
case one, two, three, four, five
static func ==(lhs: TestEnum, rhs: TestEnum) -> Bool {
... | 15,123 |
66,396,659 | I am using imbalanced dataset(54:38:7%) with RFECV for feature selection like this:
```
# making a multi logloss metric
from sklearn.metrics import log_loss, make_scorer
log_loss_rfe = make_scorer(score_func=log_loss, greater_is_better=False)
# initiating Light GBM classifier
lgb_rfe = LGBMClassifier(objective='multi... | 2021/02/27 | [
"https://Stackoverflow.com/questions/66396659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11814996/"
] | Log-loss needs the probability predictions, not the class predictions, so you should add
```py
log_loss_rfe = make_scorer(score_func=log_loss, needs_proba=True, greater_is_better=False)
```
The error is because without that, the passed `y_pred` is one-dimensional (classes 0,1,2) and `sklearn` [assumes it's a binary ... | Consider applying *stratified* cross-validation, which will try to preserve the fraction of samples for each class. Experiment with one of these scikit-learn cross-validators:
[`sklearn.model_selection.StratifiedKFold`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedKFold.html?highl... | 15,124 |
73,251,418 | I'd like to filter a `df` by date. But I would like all the values with any date before today's date (python).
For example from the table below, I'd like the rows that have a date before today's date (i.e. row 1 to row 3).
| ID | date |
| --- | --- |
| 1 | 2022-03-25 06:00:00 |
| 2 | 2022-04-25 06:00:00 |
| 3 | 2022-... | 2022/08/05 | [
"https://Stackoverflow.com/questions/73251418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18028924/"
] | You can try this?
```
from datetime import datetime
df[df['date'] < datetime.now()]
```
Output:
```
ID date
0 1 2022-03-25 06:00:00
1 2 2022-04-25 06:00:00
2 3 2022-05-25 06:00:00
``` | This will work
```
#convert column to datetime object
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True, errors='coerce')
#filter column
df.loc[df['date'] < datetime.now()]
``` | 15,125 |
40,780,004 | What's the result of returning `NotImplemented` from `__eq__` special method in python 3 (well 3.5 if it matters)?
The documentation isn't clear; the [only relevant text I found](https://docs.python.org/3/library/constants.html#NotImplemented) only vaguely refers to "some other fallback":
>
> When `NotImplemented` i... | 2016/11/24 | [
"https://Stackoverflow.com/questions/40780004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336527/"
] | Actually the `==` and `!=` check work identical to the ordering comparison operators (`<` and similar) except that they don't raise the **appropriate exception** but fall-back to identity comparison. That's the only difference.
This can be easily seen in the [CPython source code (version 3.5.10)](https://github.com/py... | Not sure where (or if) it is in the docs, but the basic behavior is:
* try the operation: `__eq__(lhs, rhs)`
* if result is not `NotImplemented` return it
* else try the reflected operation: `__eq__(rhs, lhs)`
* if result is not `NotImplemented` return it
* otherwise use appropriate fall back:
eq -> same objects? -> ... | 15,126 |
16,480,625 | A variable `AA` is in `aaa.py`. I want to use this variable in my other python file `bbb.py`
How do I access this variable? | 2013/05/10 | [
"https://Stackoverflow.com/questions/16480625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351602/"
] | You're looking for [modules!](http://docs.python.org/2/tutorial/modules.html)
In `aaa.py`:
```
AA = 'Foo'
```
In `bbb.py`:
```
import aaa
print aaa.AA # Or print(aaa.AA) for Python 3
# Prints Foo
```
Or this works as well:
```
from aaa import AA
print AA
# Prints Foo
``` | You can import it; this will execute the whole script though.
```
from aaa import AA
``` | 15,127 |
54,849,211 | I have two lists:
```
providers = ["a", "b", "c", "d", "e"]
ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]
```
I want the output to look like:
```
[{'provider_name':'a', 'server':'100.12.23.34'},.....]
```
How do i do this in python using for loop? | 2019/02/24 | [
"https://Stackoverflow.com/questions/54849211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11082580/"
] | Here is an easy to follow solution. For more reading on the zip method if necessary [click here](https://www.programiz.com/python-programming/methods/built-in/zip).
```
new = []
for i, j in zip(providers, ips):
new.append({"provider_name": i, "server": j})
``` | Use:
```
>>> providers = ["a", "b", "c", "d", "e"]
>>> ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]
>>> [{'provider_name':x, 'server':y} for x,y in zip(providers,ips)]
[{'provider_name': 'a', 'server': '100.12.23.34'}, {'provider_name': 'b', 'server': '199.134.3.01'}, {'provider_name': 'c', '... | 15,132 |
56,022,332 | I have been trying to upload a Pandas dataframe to a JSON object in Cloud Storage using Cloud Function. Follwing is my code -
```
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucke... | 2019/05/07 | [
"https://Stackoverflow.com/questions/56022332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4853331/"
] | You are passing a string to [blob.upload\_from\_file()](https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html#google.cloud.storage.blob.Blob.upload_from_file), but this method requires a file object. You probably want to use [blob.upload\_from\_filename()](https://googleapis.github.io/google-cloud-... | Use a bucket object instead of string
something like `upload_blob(conn.get_bucket(mybucket),'/tmp/abc.json','abc.json')}` | 15,134 |
39,040,250 | I have scraped a website with scrapy and stored the data in a json file.
Link to the json file: <https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing>
But the json isn't standard json and gives errors:
```
>>> import json
>>> with open("/root/code/itjuzi/itjuzi/investorinfo.json") as file:... | 2016/08/19 | [
"https://Stackoverflow.com/questions/39040250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672481/"
] | try this:
```
import json
with open('data.json') as data_file:
data = json.load(data_file)
```
This has the advantage of dealing well with large JSON files that do not fit in memory
EDIT:
Your data is not valid JSON.
Delete the following in the first 3 lines and it will validate:
```
[{
"website": ["\u5341... | Try following codes: (you are missing one something)
```
>>> import json
>>> with open("/root/code/itjuzi/itjuzi/investorinfo.json") as file:
... data = json.load(file.read())
``` | 15,135 |
5,852,199 | I'm writing a web application (<http://www.checkio.org/>) which allows users to write python code. As one feedback metric among many, I'd like to enable profiling while running checks on this code. This is to allow users to get a very rough idea of the relative efficiency of various solutions.
I need the profile to b... | 2011/05/01 | [
"https://Stackoverflow.com/questions/5852199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146821/"
] | Python's standard profiler module provides [deterministic profiling](http://docs.python.org/library/profile.html#what-is-deterministic-profiling). | I also suggest giving a try to yappi. (http://code.google.com/p/yappi/) In v0.62, it supports CPU time profiling and you can stop the profiler at any time you want... | 15,136 |
45,363,629 | Let's say I have a list l1 = [a,b,c,d,e] and I want to map it to a dictionary that would contain the following {a:1, b:2, c:3, d:4, e:5}
I know how to do it in a very naive way, but I would like something more 'pythonic'
The naive way:
```
dic = {}
j = 1
for i in list1:
dic[i] = j
j += 1
``` | 2017/07/28 | [
"https://Stackoverflow.com/questions/45363629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4369996/"
] | How about using a dictionary comprehension:
```
>>> {v: k for k, v in enumerate(l1, 1)}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
``` | Just to make up for the flub earlier... You can use the `dict` type constructor with `itertools.count` and `zip`:
```
>>> L1 = ['a','b','c','d']
>>> from itertools import count
>>> dict(zip(L1, count(1)))
{'c': 3, 'b': 2, 'a': 1, 'd': 4}
``` | 15,137 |
65,056,382 | I created a script that runs perfectly fine in visual studio code but I'm now trying to automate the script, which is proving to be a little tricky. I've turned the file into a Unix executable file for the automation but when I click on my script, the code that I’ve implemented doesn’t do what I want it to.
I’ve got a... | 2020/11/29 | [
"https://Stackoverflow.com/questions/65056382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You just need to escape the backslash `\`, so it turns into two backslashes `\\`
```js
console.log(JSON.parse('{"x":"Hello \\" test"}'))
``` | ```js
let mydata = `{"x":"Hello \" test "}`
let escapeJsonFunc = function(str) {
return str.replace(/\\/g,'\\');
};
console.log( escapeJsonFunc(mydata) )
``` | 15,138 |
57,728,801 | I have a large (around 200Mb) single-line json file and I want to convert this to a more readable multi-line json (or txt) file.
I tried to open the file with text editors like sublime text and it takes forever to open. So, I would like to make the conversion without opening the file.
Therefore, I cannot use the int... | 2019/08/30 | [
"https://Stackoverflow.com/questions/57728801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8889727/"
] | The simplest method would be using `jq` to pretty print the json:
```
jq . myjsonfile.json > pretty.json
```
But from the python output, I suspect the json file may be ill-formed. | if you can identify a character sequence that ends a line (e.g. a curly bracket followed by a semicolon) you can use sed for it
```
$ sed 's/};/\n/g' <<< "my};test};string"
my
test
string
``` | 15,139 |
17,507,799 | I've built a little app engine app that lets users upload short recordings. Some of the recordings are done in-browser with <https://github.com/mattdiamond/Recorderjs>, which creates wav files. To save space, I'd like to convert those to ogg before writing them to the app engine datastore, so that I use less of my outg... | 2013/07/06 | [
"https://Stackoverflow.com/questions/17507799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610668/"
] | Pymedia isn't pure python so you won't be able to use it on app engine.
You probably want to build something on Compute Engine to do this. | Provided it's possible to replace Matt Diamond's recorderjs with its fork, [chris-rudmin/Recorderjs](https://github.com/chris-rudmin/Recorderjs) ([demo page](https://rawgit.com/chris-rudmin/Recorderjs/master/example.html)) in AppEngine, this should be feasible. Or first encode to WAV and use [opusenc.js](https://github... | 15,142 |
20,423,599 | If I write the following in python, I get a syntax error, why so?
```
a = 1
b = (a+=1)
```
I am using python version 2.7
what I get when I run it, the following:
```
>>> a = 1
>>> b = (a +=1)
File "<stdin>", line 1
b = (a +=1)
^
SyntaxError: invalid syntax
>>>
``` | 2013/12/06 | [
"https://Stackoverflow.com/questions/20423599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1932405/"
] | Unlike in some other languages, assignment (including augmented assignment, like `+=`) in Python is *not* an expression. This also affects things like this:
```
(a=1) > 2
```
which is legal in C, and several other languages.
The reason generally given for this is because it helps to prevent a class of bugs like th... | `a +=1` is a statement in Python and you can't assign a statement to a variable. Though it is a valid syntax in languages like C, PHP, etc but not Python.
```
b = (a+=1)
```
An equivalent version will be:
```
>>> a = 1
>>> a += 1
>>> b = a
``` | 15,143 |
1,423,214 | I have this python code for opening a .cfg file, writing to it and saving it:
```
import ConfigParser
def get_lock_file():
cf = ConfigParser.ConfigParser()
cf.read("svn.lock")
return cf
def save_lock_file(configurationParser):
cf = configurationParser
config_file = ope... | 2009/09/14 | [
"https://Stackoverflow.com/questions/1423214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128508/"
] | Just to note that configuration file handling is simpler with ConfigObj.
To read and then write a config file:
```
from configobj import ConfigObj
config = ConfigObj(filename)
value = config['entry']
config['entry'] = newvalue
config.write()
``` | Looks good to me.
If both places call `get_lock_file`, then `cf.set(...)`, and then `save_lock_file`, and no exceptions are raised, this should work.
If you have different threads or processes accessing the same file you could have a race condition:
1. thread/process A reads the file
2. thread/process B reads the fi... | 15,148 |
64,436,875 | I have a python package project 'webapi' and I want to set up in a way so that other people can "pip install webapi". If I want to put it on a private server with a specific ip: xx.xx.xx.xx.
So other people with the access right don't need to git clone the project and install it locally into their virtual environment. ... | 2020/10/20 | [
"https://Stackoverflow.com/questions/64436875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3943868/"
] | I guess the question is unclear, if you want to upload your webapi package to PyPi you can read [this article](https://medium.com/@joel.barmettler/how-to-upload-your-python-package-to-pypi-65edc5fe9c56). But this will make your package public and i'm not quite sure that's what you want.
If what you want is a private py... | It seems like you need a software repository management application such as [Pulp](https://pulpproject.org/) take a look at [their plugin section](https://pulpproject.org/content-plugins/) and their documentation is [here](https://pulp-python.readthedocs.io/en/latest/). I use it as a private python repository for syste... | 15,150 |
2,726,171 | I am trying to change the font size using python's ImageDraw library.
You can do something like [this](http://infohost.nmt.edu/tcc/help/pubs/pil/image-font.html):
```
fontPath = "/usr/share/fonts/dejavu-lgc/DejaVuLGCSansCondensed-Bold.ttf"
sans16 = ImageFont.truetype ( fontPath, 16 )
im = Image.new ( "RGB", (20... | 2010/04/28 | [
"https://Stackoverflow.com/questions/2726171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | Per [PIL's docs](http://www.pythonware.com/library/pil/handbook/imagedraw.htm), `ImageDraw`'s default font is a bitmap font, and therefore it cannot be scaled. For scaling, you need to select a true-type font. I hope it's not difficult to find a nice truetype font that "looks kinda like" the default font in your desire... | Just do this
```
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def image_char(char,image_size, font_size):
img = Image.new("RGB", (image_size, image_size), (255,255,255))
print img.getpixel((0,0))
draw = ImageDraw.Draw(img)
font_path = "/Users/admin/Library/... | 15,152 |
24,701,171 | I want to stream an "infinite" (i.e. continuous) amount of data using HTTP Post. Basically, I want to send the POST request header and then stream the content (where the content length is unknown). I looked through <http://docs.python-requests.org/en/latest/user/advanced/> and it seems to have the facility. The one que... | 2014/07/11 | [
"https://Stackoverflow.com/questions/24701171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2932861/"
] | Just wanted to give you an answer so you could close your question:
It sounds like what you're really looking for is python websockets. Internally, you make a HTTP request to upgrade the connection to a websocket, and after the handshake you are free to stream data both ways. Python makes this easy, [for example](http... | A file-like object is an object with a "read" method that accept a size and returns a binary data buffer for the next chunk of data.
One example that looks like that is indeed, the file object, if you want to read from the filesystem.
Another common case is the [StringIO](https://docs.python.org/2/library/stringio.ht... | 15,155 |
36,270,161 | I want to get every value of 'Lemma' in this json:
```
{'sentences':
[{'indexeddependencies': [], 'words':
[
['Cinnamomum', {'CharacterOffsetBegin': '0', 'CharacterOffsetEnd': '10', 'Lemma': 'Cinnamomum', 'PartOfSpeech': 'NNP', 'NamedEntityTag': 'O'}],
['.', {'CharacterOffsetBegin': '14', 'C... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36270161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6125957/"
] | I'm not sure why do you have this data structure - assuming you cannot change/reshape it to better suit your queries and use cases and that `Lemma` key would always be present:
```
>>> [word[1]['Lemma']
for sentence in data['sentences']
for word in sentence['words']]
['Cinnamomum', '.', 'specific', 'immuno... | this simple code traverses everything and finds all Lemma values (btw. your json should have " instead of ' as string quotes, I guess:
```
import json
with open('lemma.json') as f:
data = json.load(f)
def traverse(node):
for key in node:
if isinstance(node, list):
traverse(key)
el... | 15,156 |
48,409,243 | I tried to install google cloud module on Ubuntu 16.04 for python 3 but it shows `permission error 13`
this error is shown many times during installations for my python environment `PermissionError: [Errno 13] Permission denied: /usr/lib/python3/dist-packages/httplib2-0.9.1.egg-info` | 2018/01/23 | [
"https://Stackoverflow.com/questions/48409243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9177827/"
] | These are documented well enough in the common literature:
[location](https://en.wikipedia.org/wiki/Location_parameter), [mu](https://en.wikipedia.org/wiki/Poisson_distribution), and the page you cited -- "well enough" is assuming that you're familiar enough with the field's vocabulary to work your way through the tech... | UHXW is asking what do these arguments mean in simple terms. Prune's answers could be simplified.
The loc is like the lowest x value of your distribution the mu is like the middle of your distribution. Look at
<https://www.datacamp.com/community/tutorials/probability-distributions-python>
The uniform function genera... | 15,160 |
18,478,287 | The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to `json.dumps()`.
It usually looks like this:
```
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Foo):
return obj.to_json()
... | 2013/08/28 | [
"https://Stackoverflow.com/questions/18478287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845169/"
] | I suggest putting the hack into the class definition. This way, once the class is defined, it supports JSON. Example:
```
import json
class MyClass( object ):
def _jsonSupport( *args ):
def default( self, xObject ):
return { 'type': 'MyClass', 'name': xObject.name() }
def objectHook(... | For production environment, prepare rather own module of `json` with your own custom encoder, to make it clear that you overrides something.
Monkey-patch is not recommended, but you can do monkey patch in your testenv.
For example,
```
class JSONDatetimeAndPhonesEncoder(json.JSONEncoder):
def default(self, obj):
... | 15,161 |
55,200,708 | I am getting started on using Zappa. However, I already had installed python 3.7 on my computer while Zappa uses 3.6. I installed python 3.6.8, but when I try to use zappa in the cmd (zappa init) it uses python 3.7 by default. How can I direct zappa to use 3.6 instead? | 2019/03/16 | [
"https://Stackoverflow.com/questions/55200708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11116762/"
] | As mentioned in Zappa [README](https://github.com/Miserlou/Zappa#installation-and-configuration):
>
> Please note that Zappa must be installed into your project's virtual environment.
>
>
>
You should use something like `virtualenv` to create a virtual environment, which makes it easy to switch Python version.
... | I don't know about Zappa, but if you want use a specific version of python can do:
```
python3.6 my_program.py
```
and if whant use the command *python* with a specific version permanently, in **linux** modify the file */home/[user\_name]/.bashrc* and add the next line:
```
alias python=python3.6
``` | 15,171 |
69,654,700 | So I'm trying to achieve something like this
```
from enum import Enum
tabulate_formats = ['fancy_grid', 'fancy_outline', 'github', 'grid']
class TableFormat(str, Enum):
for item in tabulate_formats:
exec(f"{item} = '{item}'")
```
Though i get this error
```
Traceback (most recent call last):
File "... | 2021/10/21 | [
"https://Stackoverflow.com/questions/69654700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3709060/"
] | What you want to do doesn't involve editing an array, only editing the property of that array. [Array.prototype.push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) and [Array.prototype.splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects... | You can work with append `parking` property to object as below:
```js
this.houseList.splice(i, 0, {
...this.houseList[i],
parking: this.ParkingIsTrue,
});
```
[Sample Solution on StackBlitz](https://stackblitz.com/edit/angular-ivy-zggwz7?file=src/app/app.component.html)
---
References
----------
[JavaScript E... | 15,173 |
39,517,921 | So I'm using tkinter python and I have an entry widget with Name text in it. I want to delete the text only when the widget is clicked on. This is what I have so far:
```
#Import tkinter to make gui
from tkinter import *
from tkinter import ttk#Sets title and creates gui
root = Tk()
root.title("Identity Form")
#Confi... | 2016/09/15 | [
"https://Stackoverflow.com/questions/39517921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6570334/"
] | If you're expecting a socket to stay open for minutes at a time, you're in for a world of hurt. That might work on Wi-Fi, but on cellular, there's a high probability of the connection glitching because of tower switching or some other random event outside your control. When that happens, the connection drops, and there... | I faced this issue and spend more than 1 week to fix this. AND i just solved this issue by changing Wifi connection. | 15,174 |
40,009,358 | I'm a 1st year CS student been struggling over the past few days on this lab task I received for python(2.7):
---
Write a Python script named higher-lower.py which:
first reads exactly one integer from standard input (10, in the example below),
then reads exactly five more integers from standard input and
for each of... | 2016/10/12 | [
"https://Stackoverflow.com/questions/40009358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7010470/"
] | Given your description, I suspect that the validation program wants to see a single result after each additional input. Have you tried that?
```
while s <= 5:
curr = input()
if prev < curr:
print "higher"
elif curr < prev:
print "lower"
else:
print "equal"
s = s + 1
prev = curr
`... | ```
magic_number = 3
# Your code here...
while True:
guess = int(input("Guess my number: "))
if guess == magic_number:
print "Correct!"
break
elif guess > magic_number:
print "Too high!"
else:
print "Too low!"
print "Great job guessing my number!"
``` | 15,180 |
53,881,731 | How can I define an xpath command in python (scrapy) to accept any number at the place indicated in the code. I have already tried to put an `*` or `any()` at the position.
```
table = response.xpath('//*[@id="olnof_**here I want to accept any value**_altlinesodd"]/tr[1]/TD[1]/A[1]')
``` | 2018/12/21 | [
"https://Stackoverflow.com/questions/53881731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10819357/"
] | You can do this using [regular expressions](https://doc.scrapy.org/en/latest/topics/selectors.html#regular-expressions):
```
table = response.xpath('//*[re:test(@id, "^olnof_.+_altlinesodd$")]/tr[1]/TD[1]/A[1]')
``` | You can try below workaround:
```
'//*[starts-with(@id, "olnof_") and contains(@id, "_altlinesodd")]/tr[1]/TD[1]/A[1]'
```
`ends-with(@id, "_altlinesodd")` suites better in this case, but Scrapy doesn't support `ends-with` syntax, so `contains` used instead | 15,181 |
22,291,337 | I know this one has been covered before, and perhaps isn't the most pythonic way of constructing a class, but I have a lot of different maya node classes with a lot @properties for retrieving/setting node data, and I want to see if procedurally building the attributes cuts down on overhead/mantinence.
I need to re-imp... | 2014/03/10 | [
"https://Stackoverflow.com/questions/22291337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395409/"
] | This worked for me:
```
class Transform(object):
def __getattribute__(self, name):
if name in attrKeys:
return externalData[name]
return super(Transform, self).__getattribute__(name)
def __setattr__(self, name, value):
if name in attrKeys:
externalData[name] = val... | Why not also do the same thing in `__getattribute__`?
```
def __getattribute__(self, name):
print 'Getting --->', name
if name in attrKeys:
return externalData[name]
else:
# raise AttributeError("No attribute named [%s]" %name)
return super(Transform, sel... | 15,184 |
52,458,158 | I am dealing with the dataset **titanic** from [*seaborn*].
```
titanic = seaborn.load_dataset('titanic')
```
I cut the age column into categorical bins.
```
age = pd.cut(titanic['age'], [0, 18, 80])
```
Then the problem comes, the groupby and pivot\_table give totally different results:
```
titanic.groupby(['se... | 2018/09/22 | [
"https://Stackoverflow.com/questions/52458158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10401026/"
] | It seems to work best when the object's key is a single class.
You can instead do something like this:
```
class="fa" [ngClass]="{'fa-paper-plane': true, 'fa-spinner': false, 'fa-spin': false }"
```
Because the `fa` class should always apply, it's being done in a normal `class` attribute | When a expression is evaluated to true the classes passed in ngClass are added to the classList for the element and when expression is evaluated to false the classes passed in ngClass are removed from the classList for the element. Example :
```
<div>
<p>
<i [ngClass]="{'fa fa-spinner fa-spin': false, 'fa fa-tel... | 15,189 |
45,619,018 | I'm trying to use OpenCV to segment a bent rod from it's background then find the bends in it and calculate the angle between each bend.
The first part luckily is trivial with a enough contrast between the foreground and background.
A bit of erosion/dilation takes care of reflections/highlights when segmenting.
The s... | 2017/08/10 | [
"https://Stackoverflow.com/questions/45619018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89766/"
] | It may be convenient to use curvature to find line segments. Here [example](http://www.morethantechnical.com/2012/12/07/resampling-smoothing-and-interest-points-of-curves-via-css-in-opencv-w-code/) of splitting contour by minimal curvature points, it may be better to use maximal curvature points in your case. B You can... | Once you have the contour, you can analyze it using a method like the one proposed in this paper: <https://link.springer.com/article/10.1007/s10032-011-0175-3>
Basically, the contour is tracked calculating the curvature at each point.
Then you can use a curvature threshold to segment the contour into straight and curv... | 15,190 |
21,889,795 | I couldn't find the right search terms for this question, so please apologize if this question has already been asked before.
Basically, I want to create a python function that allows you to name the columns (as a function parameter) that you will do certain kinds of analyses on.
For instance see below. Obviously thi... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21889795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314418/"
] | If I understand you, `df[yearattribute].unique()` should work. You can index into DataFrame columns like a dictionary.
Aside #1: `totaldf = df` only makes `totaldf` a new name for `df`, it doesn't make a copy, and you don't use it anyway.
Aside #2: you're not returning anything. | You can use [`getattr`](http://docs.python.org/3/library/functions.html#getattr) here:
```
yearlist = list(np.unique(getattr(df, yearattribute)))
```
`getattr` allows you to access an attribute via a string representation of its name.
Below is a demonstration:
```
>>> class Foo:
... def __init__(self):
... ... | 15,192 |
2,492,508 | is there a python library for supporting OpenType features? where can i get it?
please do not guide to fontforge, i live in Iran , so i can not download anything from them. | 2010/03/22 | [
"https://Stackoverflow.com/questions/2492508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275221/"
] | The [Python Imaging Library (PIL)](http://www.pythonware.com/products/pil/) supports OpenType. | If you refer OpenType Fonts, there is python library for fontforge
<http://fontforge.sourceforge.net/python.html> | 15,193 |
70,422,733 | Suppose you have a string:
```
text = "coding in python is a lot of fun"
```
And character positions:
```
positions = [(0,6),(10,16),(29,32)]
```
These are intervals, which cover certain words within text, i.e. coding, python and fun, respectively.
Using the character positions, how could you split the text on t... | 2021/12/20 | [
"https://Stackoverflow.com/questions/70422733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6515530/"
] | I'd flatten `positions` to be `[0,6,10,16,29,32]` and then do something like
```py
positions.append(-1)
prev_positions = [0] + positions
words = []
for begin, end in zip(prev_positions, positions):
words.append(text[begin:end])
```
This exact code produces `['', 'coding', ' in ', 'python', ' is a lot of ', 'fun'... | Below code works as expected
```
text = "coding in python is a lot of fun"
positions = [(0,6),(10,16),(29,32)]
textList = []
lastIndex = 0
for indexes in positions:
s = slice(indexes[0], indexes[1])
if positions.index(indexes) > 0:
print(lastIndex)
textList.append(text[lastIndex: indexes[0]])
... | 15,196 |
63,842,868 | ```
import pyautogui as py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import keyboard
driver = webdriver.Chrome()
driver.get('https://www.youtube.com/watch?v=pcel9QTPx_g&list=RDpcel9QTPx_g&start_radio=1&t=11&ab_channel=%E5%BE%AE%E7%B3%96%E9%80%A2')
elem = driver.find_elements_by_id('... | 2020/09/11 | [
"https://Stackoverflow.com/questions/63842868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13781869/"
] | ```
import pyautogui as py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import keyboard
driver = webdriver.Chrome()
driver.get('https://www.youtube.com/watch?v=pcel9QTPx_g&list=RDpcel9QTPx_g&start_radio=1&t=11&ab_channel=%E5%BE%AE%E7%B3%96%E9%80%A2')
elem = driver.find_elements_by_id('... | I would also suggest you to use another key instead of f12 because it will disrupt your code when you are running it from chrome, it will open developer mode! | 15,197 |
39,845,636 | I have the latest version of pip 8.1.1 on my ubuntu 16.
But I am not able to install any modules via pip as I get this error all the time.
```
File "/usr/local/bin/pip", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2927, in <... | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5474316/"
] | I repaired mine this with command:
>
> easy\_install pip
>
>
> | Delete all of the pip/pip3 stuff under .local including the packages.
```
sudo apt-get purge python-pip python3-pip
```
Now remove all pip3 files from local
```
sudo rm -rf /usr/local/bin/pip3
```
you can check which pip is installed other wise execute below one to remove all (No worries)
```
sudo rm -rf /usr/lo... | 15,198 |
63,835,086 | If I have a dataframe with the following layout:
```
ID# Response
1234 Covid-19 was a disaster for my business
3456 The way you handled this pandemic was awesome
```
I want to be able to count frequency of specific words from a list.
```
list=['covid','COVID','Covid-19','pandemic','coronavirus']
```
... | 2020/09/10 | [
"https://Stackoverflow.com/questions/63835086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13000877/"
] | For each string, find number of matches.
```
dict((s, df['response'].str.count(s).fillna(0).sum()) for s in list_of_strings)
```
Note that `Series.str.count` takes a regex input. You may want to append `(?=\b)` for positive look-ahead word-endings.
`Series.str.count` returns `NA` when counting `NA`, thus, fill with... | ```
import pandas as pd
import numpy as np
df = pd.DataFrame({'sheet':['sheet1', 'sheet2', 'sheet3', 'sheet2'],
'tokenized_text':[['efcc', 'fficial', 'billiontwits', 'since', 'covid', 'landed'], ['when', 'people', 'say', 'the', 'fatality', 'rate', 'of', 'coronavirus', 'is'], ['in', 'the', 'coronavirus-induced', 'c... | 15,208 |
9,377,801 | I would like to know how practical it would be to create a program which takes handwritten characters in some form, analyzes them, and offers corrections to the user. The inspiration for this idea is to have elementary school students in other countries or University students in America learn how to write in languages ... | 2012/02/21 | [
"https://Stackoverflow.com/questions/9377801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1223327/"
] | Character Recognition is usually implemented using Artificial Neural Networks ([ANNs](http://en.wikipedia.org/wiki/Artificial_neural_network)). It is not a straightforward task to implement seeing that there are usually lots of ways in which different people write the same character.
The good thing about neural netwo... | Have you seen <http://www.skritter.com>? They do this in combination with spaced recognition scheduling.
I guess you want to classify features such as curves in your strokes (http://en.wikipedia.org/wiki/CJK\_strokes), then as a next layer identify componenents, then estimate the most likely character. All the while s... | 15,214 |
26,743,269 | From the [Python docs](https://docs.python.org/2/library/heapq.html):
>
> The latter two functions [heapq.nlargest and heapq.nsmallest] perform best for smaller values of n. For
> larger values, it is more efficient to use the sorted() function.
> Also, when n==1, it is more efficient to use the built-in min() and
... | 2014/11/04 | [
"https://Stackoverflow.com/questions/26743269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032973/"
] | The `nsmallest` and `nlargest` methods available from `heapq` do not assume that the argument passed to them is already in heap format. Instead, they seek to "heapify" the argument as they traverse it, which will be more efficient than outright sorting for the top-k elements for small values of k, but for k exactly equ... | If you need just to pick one minimum element on a heapified list just do list[0]:
```
import heapq
lst = [1,-1,100,200]
heapq.heapify(lst)
min_value = lst[0]
```
Doc above refers to getting n smallest numbers, and heap is not the most efficient data structure to do that if n is large. | 15,216 |
44,773,983 | I have two following files:
**testcase\_module.py**
```
import boto3
ec2 = boto3.resource('ec2')
def f():
return ec2.instances.all()
```
**testcase\_test.py**
```
import testcase_module
import unittest.mock
class MainTest(unittest.TestCase):
@unittest.mock.patch('testcase_module.ec2', spec_set=['instanc... | 2017/06/27 | [
"https://Stackoverflow.com/questions/44773983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1906088/"
] | Try using `mock_add_spec`.
`ec2_mock.instances.mock_add_spec(['all'], spec_set=True)`
Link: <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec> | What about doing it like this:
```
@unittest.mock.patch('testcase_module.boto3.resource', autospec=True)
def test_f(self, ec2_resource_mock):
class InstanceStub(object):
def all(self):
return [...]
ec2_resource_mock.return_value = mock.create_autospec(
EC2InstanceType, instances=Ins... | 15,217 |
71,957,239 | How can I get the largest key with the largest value in python dictionary. In the below example you can see 1 and 2 have same frequency. But i want to return the larger key.
```
nums = [1,2,2,3,1]
frq = {}
for i in nums:
if i not in frq:
frq[i] = 1
else:
... | 2022/04/21 | [
"https://Stackoverflow.com/questions/71957239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11416278/"
] | Have your `key` function return a tuple of the value and the associated key. The first element of the tuple is compared first, the second will break ties.
```
>>> from collections import Counter
>>> nums = [1, 2, 2, 3, 1]
>>> frq = Counter(nums)
>>> max(frq, key=lambda n: (frq[n], n))
2
```
Note that `collections.Co... | You can use tuple comparison for the keys to compare keys based on their frequencies, and then tiebreak based on the actual value of the key only if the frequencies are the same:
```py
frequency = max(frq, key=lambda x: (frq.get(x), x))
```
With this change, this outputs:
```py
2
``` | 15,218 |
38,506,250 | i want to take input from user in and each value of the input is on consecutive line.this is to be implemented in python
```
while x=int(raw_input()): ##<=showing error at this line
print(x)
gollum(x)
#the function gollum() has to be called if the input is present
``` | 2016/07/21 | [
"https://Stackoverflow.com/questions/38506250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6590204/"
] | There are no other ways with HTTP (except what HTTP allows, as already mentioned).
But there are many other ways to transfer data from server to server, like FTP or establishing a direct socket connection.
Note that you will need install/configure such additional ways, and maybe not only on the server (for communica... | **Session :**
A session is stored on the server and cannot be accessed by the user (client). It is used to store information across the site such as login sessions. It can be used to store information in the server side, and pass between different php scripts
Note that session creates a session cookie for identificat... | 15,220 |
13,620,633 | Given the URL <http://www.smartmoney.com/quote/FAST/?story=financials&timewindow=1&opt=YB&isFinprint=1&framework.view=smi_emptyView> , how would you capture and print the contents of an entire row of data?
For example, what would it take to get an output that looked something like:
"Cash & Short Term Investments 144,... | 2012/11/29 | [
"https://Stackoverflow.com/questions/13620633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776739/"
] | ```
In [18]: doc.xpath(u'.//th[div[text()="Cash & Short Term Investments"]]/following-sibling::td/text()')
Out[18]: [' 144,841', ' 169,760', ' 189,252', ' 86,743', ' 57,379']
```
or you can define a little function to get the rows by text:
```
In [19]: def func(doc,txt):
...: exp=u'.//th[div[text... | let html holds the html source code:
```
import lxm.html
doc = lxml.html.document_fromstring(html)
rows_element = doc.xpath('/html/body/div/div[2]/div/div[5]/div/div/table/tbody/tr')
for row in rows_element:
print row.text_content()
```
not tested but should work
P.S.Install xpath cheker or firefinder in firef... | 15,222 |
17,669,095 | I'm trying find exactly what's wrong with a larger job that I'm trying to schedule with launchd for the first time. So I made the simplest python file I could think of, `print 'running test'`, titled it `com.schedulertest.plist` and then made a plist file like so:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE p... | 2013/07/16 | [
"https://Stackoverflow.com/questions/17669095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1844086/"
] | So the answer was not a big deal, but it might help others to share the solution. I had simply forgotten, as we will when moving around several virtualenvs, which python I was in. If you're having trouble and your `.plist` and script seem well-formed, it won't hurt to run `which python` etc, and check the result agains... | ### Troubleshooting
* To debug `.plist`, you can check the log for any error, e.g.
```
tail -f /var/log/system.log
```
To specify custom log, use:
```
<key>StandardOutPath</key>
<string>/var/log/myjob.log</string>
<key>StandardErrorPath</key>
<string>/var/log/myjob.log</string>
```
* To find the latest exit statu... | 15,223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.