qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
55,233,846 | I'm trying to send HTTP post rest API call to the flask server. I'm able to do it in postman but How can I call it using python requests module?
payloads are key-project value-daynight and key-file value-
postman request is as shown in the image
[postman](https://i.stack.imgur.com/i8ZMT.png)
when I tried I ended up getting an internal server error . Problem is with payload i was passing . How can I call it successfully and get a proper response | 2019/03/19 | [
"https://Stackoverflow.com/questions/55233846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865641/"
] | Just recently ran into this. One thing to look out for is to ensure nodeIntegration is set to true when creating your renderer windows.
```
mainWindow = new electron.BrowserWindow({
width: width,
height: height,
webPreferences: {
nodeIntegration: true
}
});
``` | AFAIU the recommended way is to use `contextBridge` module (in the `preload.js` script). It allows you to keep the context isolation enabled but safely expose your APIs to the context the website is running in.
<https://www.electronjs.org/docs/latest/tutorial/context-isolation>
Following this way, I also found that it was no longer necessary to specify `target` property in the Webpack config. |
55,233,846 | I'm trying to send HTTP post rest API call to the flask server. I'm able to do it in postman but How can I call it using python requests module?
payloads are key-project value-daynight and key-file value-
postman request is as shown in the image
[postman](https://i.stack.imgur.com/i8ZMT.png)
when I tried I ended up getting an internal server error . Problem is with payload i was passing . How can I call it successfully and get a proper response | 2019/03/19 | [
"https://Stackoverflow.com/questions/55233846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865641/"
] | Also faced this issue, new answer:
```js
mainWindow = new electron.BrowserWindow({
width: width,
height: height,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
``` | AFAIU the recommended way is to use `contextBridge` module (in the `preload.js` script). It allows you to keep the context isolation enabled but safely expose your APIs to the context the website is running in.
<https://www.electronjs.org/docs/latest/tutorial/context-isolation>
Following this way, I also found that it was no longer necessary to specify `target` property in the Webpack config. |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?
I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP. | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment.
On Windows, the [PyHook](http://pypi.python.org/pypi/pyHook/1.4/) library would give you the functionality you need.
On Linux, you can use the [Python X Library](http://python-xlib.sourceforge.net/) (assuming you are running a graphical desktop).
Both of these are used to good effect by [pykeylogger](http://pykeylogger.wiki.sourceforge.net/). You'd be best off downloading the source (see e.g. pyxhook.py) to see specific examples of how key press events are captured. It should be trivial to modify this to sum the distribution of keys rather than recording the ordering. | Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program [Workrave](http://www.workrave.org/) is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unless you want very detailed/more specific statistics). In worst case you could look at the source (C++) to find how it is done. |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?
I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP. | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | It looks like you need <http://patorjk.com/keyboard-layout-analyzer/>
This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.
To answer your original question, on Linux you can read from /dev/event\* for local keyboard, mouse and joystick events. I believe you could for example simply `cat /dev/event0 > keylogger`. The events are instances of `struct input_event`. See also <http://www.linuxjournal.com/article/6429>.
Python's [struct](http://docs.python.org/library/struct.html) module is a convenient way to parse binary data.
For OSX, take a look at the source code to logkext. <http://code.google.com/p/logkext/> | Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program [Workrave](http://www.workrave.org/) is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unless you want very detailed/more specific statistics). In worst case you could look at the source (C++) to find how it is done. |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?
I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP. | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | As the current X server's *Record* extension seems to be broken, using `pykeylogger` for Linux doesn't really help. Take a look at [`evdev`](http://svn.navi.cx/misc/trunk/python/evdev/) and its `demo` function, instead. The solution is nastier, but it does at least work.
It comes down to setting up a hook to the device
```
import evdev
keyboard_location = '/dev/input/event1' # get the correct one from HAL or so
keyboard_device = evdev.Device(keyboard_location)
```
Then, regularly poll the device to get the status of keys and other information:
```
keyboard_device.poll()
``` | Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program [Workrave](http://www.workrave.org/) is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unless you want very detailed/more specific statistics). In worst case you could look at the source (C++) to find how it is done. |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?
I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP. | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | It looks like you need <http://patorjk.com/keyboard-layout-analyzer/>
This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.
To answer your original question, on Linux you can read from /dev/event\* for local keyboard, mouse and joystick events. I believe you could for example simply `cat /dev/event0 > keylogger`. The events are instances of `struct input_event`. See also <http://www.linuxjournal.com/article/6429>.
Python's [struct](http://docs.python.org/library/struct.html) module is a convenient way to parse binary data.
For OSX, take a look at the source code to logkext. <http://code.google.com/p/logkext/> | Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment.
On Windows, the [PyHook](http://pypi.python.org/pypi/pyHook/1.4/) library would give you the functionality you need.
On Linux, you can use the [Python X Library](http://python-xlib.sourceforge.net/) (assuming you are running a graphical desktop).
Both of these are used to good effect by [pykeylogger](http://pykeylogger.wiki.sourceforge.net/). You'd be best off downloading the source (see e.g. pyxhook.py) to see specific examples of how key press events are captured. It should be trivial to modify this to sum the distribution of keys rather than recording the ordering. |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and if so what python modules should I look at? Has this already been done?
I'm on OSX but would also be interested in doing this on an Ubuntu box and Windows XP. | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | It looks like you need <http://patorjk.com/keyboard-layout-analyzer/>
This handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.
To answer your original question, on Linux you can read from /dev/event\* for local keyboard, mouse and joystick events. I believe you could for example simply `cat /dev/event0 > keylogger`. The events are instances of `struct input_event`. See also <http://www.linuxjournal.com/article/6429>.
Python's [struct](http://docs.python.org/library/struct.html) module is a convenient way to parse binary data.
For OSX, take a look at the source code to logkext. <http://code.google.com/p/logkext/> | As the current X server's *Record* extension seems to be broken, using `pykeylogger` for Linux doesn't really help. Take a look at [`evdev`](http://svn.navi.cx/misc/trunk/python/evdev/) and its `demo` function, instead. The solution is nastier, but it does at least work.
It comes down to setting up a hook to the device
```
import evdev
keyboard_location = '/dev/input/event1' # get the correct one from HAL or so
keyboard_device = evdev.Device(keyboard_location)
```
Then, regularly poll the device to get the status of keys and other information:
```
keyboard_device.poll()
``` |
14,001,578 | What's the correct way to specify a hg dependency in `tox.ini`. e.g.
```
[testenv]
deps =
hg+https://code.google.com/p/python-progressbar/
```
Unfortunately this does not work, and the following is spewed out:
```
ERROR: invocation failed, logfile: /Users/brad/project/.tox/py33-dj/log/py33-dj-1.log
ERROR: actionid=py33-dj
msg=getenv
cmdargs=[local('/Users/brad/project/.tox/py33-dj/bin/pip'), 'install', '--download-cache=/Users/brad/.pip/downloads', 'hg+https://code.google.com/p/python-progressbar/', 'https://github.com/dag/attest/tarball/master', 'django-attest', 'django-celery', 'coverage', 'https://github.com/django/django/tarball/master']
env={'PYTHONIOENCODING': 'utf_8', 'TERM_PROGRAM_VERSION': '309', 'LOGNAME': 'brad', 'USER': 'brad', 'PATH': '/Users/brad/project/.tox/py33-dj/bin:/usr/local/share/python:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/texbin', 'HOME': '/Users/brad', 'DISPLAY': '/tmp/launch-zayh2U/org.macosforge.xquartz:0', 'TERM_PROGRAM': 'Apple_Terminal', 'LANG': 'en_AU.UTF-8', 'TERM': 'xterm-256color', 'SHLVL': '1', '_': '/usr/local/share/python/tox', 'TERM_SESSION_ID': 'E8FC4113-C18B-4DB4-9594-C0909A132D76', 'SSH_AUTH_SOCK': '/tmp/launch-kia8RP/Listeners', 'SHELL': '/bin/bash', 'TMPDIR': '/var/folders/zr/m_ys6vwd1z19rqh73jd8z88w0000gn/T/', '__CF_USER_TEXT_ENCODING': '0x1F5:0:15', 'PWD': '/Users/brad/project', 'PIP_DOWNLOAD_CACHE': '/Users/brad/.pip/downloads', 'COMMAND_MODE': 'unix2003'}
abort: couldn't find mercurial libraries in [/usr/local/Cellar/mercurial/2.4.1/libexec /Users/brad/project/.tox/py33-dj/lib/python3.3/site-packages/distribute-0.6.31-py3.3.egg /Users/brad/project/.tox/py33-dj/lib/python3.3/site-packages/pip-1.2.1-py3.3.egg /Users/brad/project/.tox/py33-dj/lib/python33.zip /Users/brad/project/.tox/py33-dj/lib/python3.3 /Users/brad/project/.tox/py33-dj/lib/python3.3/plat-darwin /Users/brad/project/.tox/py33-dj/lib/python3.3/lib-dynload /usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3 /usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/lib/python3.3/plat-darwin /Users/brad/project/.tox/py33-dj/lib/python3.3/site-packages]
(check your install and PYTHONPATH)
Downloading/unpacking hg+https://code.google.com/p/python-progressbar/
Cloning hg https://code.google.com/p/python-progressbar/ to /var/folders/zr/m_ys6vwd1z19rqh73jd8z88w0000gn/T/pip-88u_g0-build
Complete output from command /usr/local/bin/hg clone --noupdate -q https://code.google.com/p/python-progressbar/ /var/folders/zr/m_ys6vwd1z19rqh73jd8z88w0000gn/T/pip-88u_g0-build:
----------------------------------------
Command /usr/local/bin/hg clone --noupdate -q https://code.google.com/p/python-progressbar/ /var/folders/zr/m_ys6vwd1z19rqh73jd8z88w0000gn/T/pip-88u_g0-build failed with error code 255 in None
Storing complete log in /Users/brad/.pip/pip.log
ERROR: could not install deps [hg+https://code.google.com/p/python-progressbar/]
_________________________________________ summary _________________________________________
ERROR: py33-dj: could not install deps [hg+https://code.google.com/p/python-progressbar/]
```
The last line in `pip.log` is:
```
pip.exceptions.InstallationError: Command /usr/local/bin/hg clone --noupdate -q https://code.google.com/p/python-progressbar/ /var/folders/zr/m_ys6vwd1z19rqh73jd8z88w0000gn/T/pip-dakkvs-build failed with error code 255 in None
```
However running `pip install hg+https://code.google.com/p/python-progressbar/` works.
The tox test environment is targeting Python 3.3. | 2012/12/22 | [
"https://Stackoverflow.com/questions/14001578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253686/"
] | It's possible to specify the mercurial dependency in two ways within `deps = …`:
* `-ehg+https://code.google.com/p/python-progressbar/#egg=progressbar` (no space)
* `hg+https://code.google.com/p/python-progressbar/`
tox treats each line in `deps` as a single argument to `pip install` (whitespace included).
pip supports `-e` as either a standalone argument followed by a URL, or the prefix of a single argument, i.e.:
* `['pip', 'install', '-e', 'hg+https://...']`
* `['pip', 'install', '-ehg+https://...']`
but will not handle `['pip', 'install', '-e hg+https://...']` (because the URL is parsed to include a space character)
So why didn't it work?
======================
Mercurial was installed under Python 2.7. When tox runs `pip install`, it sets the `PATH` env variable to refer to the Python 3.3 env it created. If you look carefully through the error message you'll see the line:
```
abort: couldn't find mercurial libraries in …
```
which is printed by the `/usr/local/bin/hg` script when `import mercurial` fails. Typically the solution would be to install the library (mercurial) for Python 3.3. Unfortunately mercurial does not support Python 3. | typically this is a artifact of a broken mercurial installation that refers to env python
in virtualenv for python 3 the env python is simply the worst thing to work with |
50,617,233 | I have a dataset (Product\_ID,date\_time, Sold) which has products sold on various dates. The dates are not consistent and are given for 9 months with random 13 days or more from a month. I have to segregate the data in a such a way that the for each product how many products were sold on 1-3 given days, 4-7 given days, 8-15 given days and >16 given days. . So how can I code this in python using pandas and other packages
`PRODUCT_ID DATE_LOCATION Sold
0E4234 01-08-16 0:00 2
0E4234 02-08-16 0:00 7
0E4234 04-08-16 0:00 3
0E4234 08-08-16 0:00 1
0E4234 09-08-16 0:00 2
.
. (same product for 9 months sold data)
.
0G2342 02-08-16 0:00 1
0G2342 03-08-16 0:00 2
0G2342 06-08-16 0:00 1
0G2342 09-08-16 0:00 1
0G2342 11-08-16 0:00 3
0G2342 15-08-16 0:00 3
.
.
.(goes for 64 products each with 9 months of data)
.`
I don't know even how to code for this in python
The output needed is
```
PRODUCT_ID Days Sold
0E4234 1-3 9
4-7 3
8-15 16
>16 (remaing values sum)
0G2342 1-3 3
4-7 1
8-15 7
>16 (remaing values sum)
.
.(for 64 products)
.
```
Would be happy if at least someone posted a link to where to start | 2018/05/31 | [
"https://Stackoverflow.com/questions/50617233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9846590/"
] | You can first convert dates to dtetimes and get days by [`dt.day`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.day.html):
```
df['DATE_LOCATION'] = pd.to_datetime(df['DATE_LOCATION'], dayfirst=True)
days = df['DATE_LOCATION'].dt.day
```
Then binning by [`cut`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html):
```
rng = pd.cut(days, bins=[0,3,7,15,31], labels=['1-3', '4-7','8-15', '>=16'])
print (rng)
0 1-3
1 1-3
2 4-7
3 8-15
4 8-15
5 1-3
6 1-3
7 4-7
8 8-15
9 8-15
10 8-15
Name: DATE_LOCATION, dtype: category
Categories (4, object): [1-3 < 4-7 < 8-15 < >=16]
```
And aggregate `sum` by product and binned `Series`:
```
df = df.groupby(["PRODUCT_ID",rng])['Sold'].sum()
print (df)
PRODUCT_ID DATE_LOCATION
0E4234 1-3 9
4-7 3
8-15 3
0G2342 1-3 3
4-7 1
8-15 7
Name: Sold, dtype: int64
```
If need also count per `year`s:
```
df = df.groupby([df['DATE_LOCATION'].dt.year.rename('YEAR'), "PRODUCT_ID",rng])['Sold'].sum()
print (df)
YEAR PRODUCT_ID DATE_LOCATION
2016 0E4234 1-3 9
4-7 3
8-15 3
0G2342 1-3 3
4-7 1
8-15 7
Name: Sold, dtype: int64
``` | Assume your dataframe named df.
```
df["DATE_LOCATION"] = pd.to_datetime(df.DATE_LOCATION)
df["DAY"] = df.DATE_LOCATION.dt.day
def flag(x):
if 1<=x<=3:
return '1-3'
elif 4<=x<=7:
return '4-7'
elif 8<=x<=15:
return '8-15'
else:
return '>16' # maybe you mean '>=16'.
df["Days"] = df.DAY.apply(flag)
df.groupby(["PRODUCT_ID","Days"]).Sold.sum()
``` |
1,062,562 | I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing this script and the previous line it hangs forever.
In contrast when I manually type my script line for line in the python command line I can go on to my next line after pressing enter a second time on the non-returning function call line.
So how to solve the issue when executing the script?
Thanks!!
Edit:
My python interpreter is embedded in an application. I want to write an extension for this application as a separate Qt4 window. All the python stuff is only for make my graphical plugin accessible per script (per boost.python wrapping).
My python script:
```
import imp
import os
Plugin = imp.load_dynamic('Plugin', os.getcwd() + 'Plugin.dll')
qt = Plugin.StartQt4() # it hangs here when executing as script
pl = PluginCPP.PluginCPP() # Creates a QMainWindow
pl.ShowWindow() # shows the window
```
The C++ code for the Qt start function looks like this:
```
class StartQt4
{
public:
StartQt4()
{
int i = 0;
QApplication* qapp = new QApplication(i, NULL);
qapp->exec();
}
};
``` | 2009/06/30 | [
"https://Stackoverflow.com/questions/1062562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80480/"
] | Use a thread ([longer example here](http://www.wellho.net/solutions/python-python-threads-a-first-example.html)):
```
from threading import Thread
class WindowThread(Thread):
def run(self):
callCppFunctionHere()
WindowThread().start()
``` | QApplication::exec() starts the main loop of the application and will only return after the application quits. If you want to run code after the application has been started, you should resort to Qt's event handling mechanism.
From <http://doc.trolltech.com/4.5/qapplication.html#exec> :
>
> To make your application perform idle
> processing, i.e. executing a special
> function whenever there are no pending
> events, use a QTimer with 0 timeout.
> More advanced idle processing schemes
> can be achieved using processEvents().
>
>
> |
1,062,562 | I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing this script and the previous line it hangs forever.
In contrast when I manually type my script line for line in the python command line I can go on to my next line after pressing enter a second time on the non-returning function call line.
So how to solve the issue when executing the script?
Thanks!!
Edit:
My python interpreter is embedded in an application. I want to write an extension for this application as a separate Qt4 window. All the python stuff is only for make my graphical plugin accessible per script (per boost.python wrapping).
My python script:
```
import imp
import os
Plugin = imp.load_dynamic('Plugin', os.getcwd() + 'Plugin.dll')
qt = Plugin.StartQt4() # it hangs here when executing as script
pl = PluginCPP.PluginCPP() # Creates a QMainWindow
pl.ShowWindow() # shows the window
```
The C++ code for the Qt start function looks like this:
```
class StartQt4
{
public:
StartQt4()
{
int i = 0;
QApplication* qapp = new QApplication(i, NULL);
qapp->exec();
}
};
``` | 2009/06/30 | [
"https://Stackoverflow.com/questions/1062562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80480/"
] | Use a thread ([longer example here](http://www.wellho.net/solutions/python-python-threads-a-first-example.html)):
```
from threading import Thread
class WindowThread(Thread):
def run(self):
callCppFunctionHere()
WindowThread().start()
``` | I assume you're already using [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? |
1,062,562 | I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing this script and the previous line it hangs forever.
In contrast when I manually type my script line for line in the python command line I can go on to my next line after pressing enter a second time on the non-returning function call line.
So how to solve the issue when executing the script?
Thanks!!
Edit:
My python interpreter is embedded in an application. I want to write an extension for this application as a separate Qt4 window. All the python stuff is only for make my graphical plugin accessible per script (per boost.python wrapping).
My python script:
```
import imp
import os
Plugin = imp.load_dynamic('Plugin', os.getcwd() + 'Plugin.dll')
qt = Plugin.StartQt4() # it hangs here when executing as script
pl = PluginCPP.PluginCPP() # Creates a QMainWindow
pl.ShowWindow() # shows the window
```
The C++ code for the Qt start function looks like this:
```
class StartQt4
{
public:
StartQt4()
{
int i = 0;
QApplication* qapp = new QApplication(i, NULL);
qapp->exec();
}
};
``` | 2009/06/30 | [
"https://Stackoverflow.com/questions/1062562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80480/"
] | QApplication::exec() starts the main loop of the application and will only return after the application quits. If you want to run code after the application has been started, you should resort to Qt's event handling mechanism.
From <http://doc.trolltech.com/4.5/qapplication.html#exec> :
>
> To make your application perform idle
> processing, i.e. executing a special
> function whenever there are no pending
> events, use a QTimer with 0 timeout.
> More advanced idle processing schemes
> can be achieved using processEvents().
>
>
> | I assume you're already using [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? |
32,867,501 | I have a python program that takes a .txt file with a list of information. Then the program proceeds to number every line, then remove all returns. Now I want to add returns to the lines that are numbered without double spacing so I can continue to edit the file. Here is my program.
```
import sys
from time import sleep
# request for filename
f = raw_input('filename > ')
print ''
# function for opening file load
def open_load(text):
for c in text:
print c,
sys.stdout.flush()
sleep(0.5)
print "Opening file",
open_load('...')
sleep(0.1)
# loading contents into global variable
f_ = open(f)
f__ = f_.read()
# contents are now contained in variable 'f__' (two underscores)
print f__
raw_input("File opened. Press enter to number the lines or CTRL+C to quit. ")
print ''
print "Numbering lines",
open_load('...')
sleep(0.1)
# set below used to add numbers to lines
x = f
infile=open(x, 'r')
lines=infile.readlines()
outtext = ['%d %s' % (i, line) for i, line in enumerate (lines)]
f_o = (str("".join(outtext)))
print f_o
# used to show amount of lines
with open(x) as f:
totallines = sum(1 for _ in f)
print "total lines:", totallines, "\n"
# -- POSSIBLE MAKE LIST OF AMOUNT OF LINES TO USE LATER TO INSERT RETURNS? --
raw_input("Lines numbered. Press enter to remove all returns or CTRL+C to quit. ")
print ''
print "Removing returns",
open_load('...')
sleep(0.1)
# removes all instances of a return
f_nr = f_o.replace("\n", "")
# newest contents are now located in variable f_nr
print f_nr
print ''
raw_input("Returns removed. Press enter to add returns on lines or CTRL+C to quit. ")
print ''
print "Adding returns",
open_load('...')
sleep(0.1)
```
Here is an example of what I need. In my code, here are no returns (\n) in this below. I have the terminal set to where the lines are in order without having returns (\n).
```
1 07/07/15 Mcdonalds $20 1 123 12345
2 07/07/15 Mcdonalds $20 1 123 12345
3 07/07/15 Mcdonalds $20 1 123 12345
4 07/07/15 Mcdonalds $20 1 123 12345
5 07/07/15 Mcdonalds $20 1 123 12345
```
The numbering, 1-5, needs to be replaced with returns so each row is it's own line. This is what it would look like in after being edited
```
# the numbering has been replaced with returns (no double spacing)
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345
07/07/15 Mcdonalds $20 1 123 12345
``` | 2015/09/30 | [
"https://Stackoverflow.com/questions/32867501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5391570/"
] | You can inject the `$location` service if you are using html5 mode.
Because you are using URLs without a base root (such as a ! or a #), you need to explicitly add a `<base>` tag that defines the "root" of your application OR you can configure `$locationProvider` to not require a base tag.
HTML:
```
<head>
<base href="/">
...
</head>
<body>
<div ng-controller="ParamsCtrl as vm">
...
</div>
</body>
```
JS:
```
app.config(['$locationProvider', function($locationProvider){
$locationProvider.html5Mode(true);
// or
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}]);
app.controller("TestCtrl", ['$location', function($location) {
var params = $location.search();
alert('Foo is: ' + params.foo + ' and bar is: ' + params.bar);
});
```
It is worth noting that you can add a router library such as ngRoute, ui-router or the new, unfinished component router. These routers rely on a base route off of a symbol (! or #) and define everything after the symbol as a client-side route which gets controlled by the router. This will allow your Angular app to function as a Single Page App and will give you access to $routeParams or the ui-router equivalent. | You can use `$location.search()`.
```
var parameters = $location.search();
console.log(parameters);
-> object{
foo: foovalue,
bar: barvalue
}
```
SO these values will be accessible with `parameters.foo` and `parameters.bar` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
```
or
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys(r"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg")
``` | If I run the following lines from the IDE it works just fine, it uploads the file.
```
Command | Target | Value
_____________________________________________________________
open | /upload |
click | id=start-upload-button-single |
type | css=input[type="file"] | C:\\Documents and Settings\\cristian\\Desktop\\ffdl\\MyWork.avi
```
But when I export it for Python webdriver it just doesn't upload it, I have tried everything.
The last resort is to make it work with AutoHotKey, but I want it to work.
What I have done is tested the solutions that I have found with/on other sites to see if the problem is only on the site that i am trying to make the upload(youtube), the solutions work(EX: <http://dev.sencha.com/deploy/ext-4.0.0/examples/form/file-upload.html>) they are valid, you can upload a file to most servers, it just doesn't work on it.
Thank you for your help. |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
```
or
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys(r"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg")
``` | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
```
or
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys(r"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg")
``` | This works for me:
```
# Upload file
elem = driver.find_element_by_name("File")
elem.send_keys(r"D:\test\testfile04.txt")
elem = driver.find_element_by_partial_link_text("Upload File")
elem.click()
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
```
or
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys(r"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg")
``` | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", with_spaces=True)
app['Open'].click() # About `Open`, checkout upload Button name
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` | If I run the following lines from the IDE it works just fine, it uploads the file.
```
Command | Target | Value
_____________________________________________________________
open | /upload |
click | id=start-upload-button-single |
type | css=input[type="file"] | C:\\Documents and Settings\\cristian\\Desktop\\ffdl\\MyWork.avi
```
But when I export it for Python webdriver it just doesn't upload it, I have tried everything.
The last resort is to make it work with AutoHotKey, but I want it to work.
What I have done is tested the solutions that I have found with/on other sites to see if the problem is only on the site that i am trying to make the upload(youtube), the solutions work(EX: <http://dev.sencha.com/deploy/ext-4.0.0/examples/form/file-upload.html>) they are valid, you can upload a file to most servers, it just doesn't work on it.
Thank you for your help. |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | If I run the following lines from the IDE it works just fine, it uploads the file.
```
Command | Target | Value
_____________________________________________________________
open | /upload |
click | id=start-upload-button-single |
type | css=input[type="file"] | C:\\Documents and Settings\\cristian\\Desktop\\ffdl\\MyWork.avi
```
But when I export it for Python webdriver it just doesn't upload it, I have tried everything.
The last resort is to make it work with AutoHotKey, but I want it to work.
What I have done is tested the solutions that I have found with/on other sites to see if the problem is only on the site that i am trying to make the upload(youtube), the solutions work(EX: <http://dev.sencha.com/deploy/ext-4.0.0/examples/form/file-upload.html>) they are valid, you can upload a file to most servers, it just doesn't work on it.
Thank you for your help. | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", with_spaces=True)
app['Open'].click() # About `Open`, checkout upload Button name
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` | This works for me:
```
# Upload file
elem = driver.find_element_by_name("File")
elem.send_keys(r"D:\test\testfile04.txt")
elem = driver.find_element_by_partial_link_text("Upload File")
elem.click()
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Did you tried this single piece of code:
```
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\Documents and Settings\\pcname\\Desktop\\ffdlt\\test.jpeg")
``` | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", with_spaces=True)
app['Open'].click() # About `Open`, checkout upload Button name
``` |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector("input[type=\"file\"]").clear()
driver.find_element_by_css_selector("input[type=\"file\"]").send_keys("C:\\\\Documents and Settings\\\\pcname\\\\Desktop\\\\ffdlt\\\\test.jpeg")
```
I searched for solutions but I haven't found any except integrating it with AutoIt or AutoHotKey...
The first line opens the File Upload Box of Firefox. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | This works for me:
```
# Upload file
elem = driver.find_element_by_name("File")
elem.send_keys(r"D:\test\testfile04.txt")
elem = driver.find_element_by_partial_link_text("Upload File")
elem.click()
``` | Using [Pyautowin](https://pywinauto.github.io/)
```
from pywinauto import Desktop
driver.find_element_by_id("start-upload-button-single").click()
app = Desktop()['Open'] # About `Open`, checkout upload Dialog title
app.wait('visible')
app.Edit.type_keys(R"C:\Documents and Settings\pcname\Desktop\ffdlt\test.jpeg", with_spaces=True)
app['Open'].click() # About `Open`, checkout upload Button name
``` |
16,504,990 | How is it possible I am getting a permission denied using the below? I am using python 2.7 and ubuntu 12.04
Below is my mapper.py file
```
import sys
import json
for line in sys.stdin:
line = json.loads(line)
key = "%s:%s" % (line['user_key'],line['item_key'])
value = 1
sys.stdout.write('%s\t%s\n' % (key,value))
```
Below is my data file
```
{"action": "show", "user_key": "heythat:htuser:32", "utc": 1368339334.568242, "id": "d518b7c5-a180-439b-8036-2bb40ca080cd", "item_key": "heythat:htitem:1000"}
{"action": "click", "user_key": "heythat:htuser:32", "utc": 1368339334.573988, "id": "cc8c35ec-9e67-4ef8-a189-6116c7d0336a", "item_key": "heythat:htitem:1001"}
{"action": "click", "user_key": "heythat:htuser:32", "utc": 1368339334.575226, "id": "6c457f9a-afc2-4b61-be2f-d4ea2863aa69", "item_key": "heythat:htitem:1002"}
{"action": "show", "user_key": "heythat:htuser:32", "utc": 1368339334.575315, "id": "e0b08c30-459b-4f77-b9a4-05939457ab99", "item_key": "heythat:htitem:1000"}
{"action": "click", "user_key": "heythat:htuser:32", "utc": 1368339334.57538, "id": "90084ea2-75c6-4b8a-bc22-9d9f2da1c0de", "item_key": "heythat:htitem:1002"}
{"action": "show", "user_key": "heythat:htuser:32", "utc": 1368339334.57538, "id": "2f76a861-2b66-430a-b70d-2af6e1b9f365", "item_key": "heythat:htitem:1001"}
{"action": "show", "user_key": "heythat:htuser:32", "utc": 1368339334.57538, "id": "282eec8a-7f6d-4ad3-917a-aae049062d87", "item_key": "heythat:htitem:1002"}
{"action": "show", "user_key": "heythat:htuser:32", "utc": 1368339334.575447, "id": "bc48a6bc-f8f8-420e-9b80-0bd0c2bbde0d", "item_key": "heythat:htitem:1000"}
{"action": "show", "user_key": "that:htuser:32", "utc": 1368339334.575513, "id": "14b49763-e2fe-4beb-bff6-f4b34b3d2ef3", "item_key": "that:htitem:1001"}
{"action": "show", "user_key": "that:htuser:32", "utc": 1368339334.575596, "id": "983cbcf3-4375-4b3b-86ed-a8fbc86ff4b3", "item_key": "that:htitem:1002"}
```
Below is my error
```
cat /home/ubuntu/workspace/logging/data.txt | /home/ubuntu/workspace/logging/mapper.py
bash: /home/ubuntu/workspace/logging/mapper.py: Permission denied
``` | 2013/05/12 | [
"https://Stackoverflow.com/questions/16504990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203556/"
] | Your `mapper.py` file needs to be executable (on some executable partition) so `chmod a+x mapper.py`
The underlying [execve(2)](http://man7.org/linux/man-pages/man2/execve.2.html) syscall is failing with
```
EACCES Execute permission is denied for the file or a script or ELF
interpreter.
EACCES The file system is mounted noexec.
``` | you can add 'python' to the command, like so
```
cat /home/ubuntu/workspace/logging/data.txt | python /home/ubuntu/workspace/logging/mapper.py
``` |
65,647,986 | I am trying to interface a micropython board with python on my computer using serial read and write, however I can't find a way to read usb serial data in micropython that is non-blocking.
Basicly I want to call the input function without requiring an input to move on. (something like <https://github.com/adafruit/circuitpython/pull/1186> but for usb)
I have tried using [tasko](https://github.com/WarriorOfWire/tasko), uselect (it failed to import the library and I can't find a download), and await functions. I'm not sure it there is a way to do this, but any help would be appreciated. | 2021/01/09 | [
"https://Stackoverflow.com/questions/65647986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13016068/"
] | Instead of typing xlsx, type xlsx like this:
```
import xlsxwriter
import pandas as pd
from pandas import DataFrame
path = ('mypath.xlsx')
xl = pd.ExcelFile(path)
print(xl.sheet_names)
```
It'll work. | The module name is xlsxwriter not xlxswriter, so replace that line with:
```
import xlsxwriter
``` |
26,856,793 | I am trying to load as a pandas dataframe a file that has Chinese characters in its name.
I've tried:
```
df=pd.read_excel("url/某物2008.xls")
```
and
```
import sys
df=pd.read_excel("url/某物2008.xls", encoding=sys.getfilesystemencoding())
```
But the response is something like: "no such file or directory "url/\xa1\xa92008.xls"
I've also tried changing the names of the files using os.rename, but the filenames aren't even read properly (asking python to just print the filenames yields only question marks or squares). | 2014/11/11 | [
"https://Stackoverflow.com/questions/26856793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2827060/"
] | ```
df=pd.read_excel(u"url/某物2008.xls", encoding=sys.getfilesystemencoding())
```
may work... but you may have to declare an encoding type at the top of the file | try this for unicode conversion:
`df=pd.read_excel(u"url/某物2008.xls", encoding='utf-8')` |
11,204,053 | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible ?
ps yes, I read [this](https://stackoverflow.com/questions/5647118/is-it-possible-to-do-partial-inheritance-with-python)
Important NOTE: And I can modify only Child class (in the parent class of all possible should be left as is) | 2012/06/26 | [
"https://Stackoverflow.com/questions/11204053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438882/"
] | ```
class Child(Parent):
def __getattribute__(self, attr):
if attr == 'goodbye':
raise AttributeError()
return super(Child, self).__getattribute__(attr)
``` | This Python example shows how to design classes to achieve child class inheritance:
```
class HelloParent(object):
def hello(self):
print 'Hello world'
class Parent(HelloParent):
def goodbye(self):
print 'Goodbye world'
class Child(HelloParent):
pass
``` |
11,204,053 | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible ?
ps yes, I read [this](https://stackoverflow.com/questions/5647118/is-it-possible-to-do-partial-inheritance-with-python)
Important NOTE: And I can modify only Child class (in the parent class of all possible should be left as is) | 2012/06/26 | [
"https://Stackoverflow.com/questions/11204053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438882/"
] | The solution depends on why you want to do it. If you want to be safe from future erroneous use of the class, I'd do:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
def goodbye(self):
raise NotImplementedError
```
This is explicit and you can include explanation in the exception message.
If you don't want to use a lot of methods from the parent class a better style would be to use composition instead of inheritance:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child:
def __init__(self):
self.buddy = Parent()
def hello(self):
return self.buddy.hello()
``` | This Python example shows how to design classes to achieve child class inheritance:
```
class HelloParent(object):
def hello(self):
print 'Hello world'
class Parent(HelloParent):
def goodbye(self):
print 'Goodbye world'
class Child(HelloParent):
pass
``` |
11,204,053 | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible ?
ps yes, I read [this](https://stackoverflow.com/questions/5647118/is-it-possible-to-do-partial-inheritance-with-python)
Important NOTE: And I can modify only Child class (in the parent class of all possible should be left as is) | 2012/06/26 | [
"https://Stackoverflow.com/questions/11204053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438882/"
] | The solution depends on why you want to do it. If you want to be safe from future erroneous use of the class, I'd do:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
def goodbye(self):
raise NotImplementedError
```
This is explicit and you can include explanation in the exception message.
If you don't want to use a lot of methods from the parent class a better style would be to use composition instead of inheritance:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child:
def __init__(self):
self.buddy = Parent()
def hello(self):
return self.buddy.hello()
``` | ```
class Child(Parent):
def __getattribute__(self, attr):
if attr == 'goodbye':
raise AttributeError()
return super(Child, self).__getattribute__(attr)
``` |
67,350,490 | I am trying to make a simple flask app using putty but it is not working
here is my hello.py file:
```
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World'
```
command I am running in putty (when in the file directory of hello.py)
pip install flask
python -c "import flask; print(flask.**version**)"
Output:1.1.2
export FLASK\_APP=hello
export FLASK\_ENV=development
flask run
when I go to the ip address: <http://127.0.0.1:5000/>
I get this
[enter image description here](https://i.stack.imgur.com/rMjbu.png)
also here is the link of the instruction I am following/did:
<https://www.digitalocean.com/community/tutorials/how-to-make-a-web-application-using-flask-in-python-3>
if someone could let me know how to make it work would be great!
thank you! | 2021/05/01 | [
"https://Stackoverflow.com/questions/67350490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12333529/"
] | I used my terminal on my window machine instead of putty which is a remote machine | Check your wlan0 inet adress by typing ifconfig in bash and use it, also try to add the following code in your flask app:
```
if __name__ == '__main__':
app.run(debug=True, port=5000, host='wlan0 IP Add')
```
Run the application by typing >>sudo python3 hello.py
Did this work? |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
```
>>> sample={'first_value':0123456}
>>> sample
{'first_value': 42798}
``` | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero is telling Python to interpret it as an octal number. | When you write 0123456, it gets interpreted as base-8, which is 42798 decimal |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
```
>>> sample={'first_value':0123456}
>>> sample
{'first_value': 42798}
``` | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero is telling Python to interpret it as an octal number. | Numbers starting with `0` are considered [octal](http://en.wikipedia.org/wiki/Octal). You'll either need to wrap the number temporarily in a string or format `123456` with a leading zero when used; both times you can't get an integer with leading zeros (just a numeric string).
Option 1:
```
>>> sample={ 'first_value' : '0123456' }
>>> sample['first_value']
'0123456'
```
Option 2:
```
>>> sample={ 'first_value' : 123456 }
>>> '{0:07}'.format(sample['first_value'])
'0123456'
``` |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
```
>>> sample={'first_value':0123456}
>>> sample
{'first_value': 42798}
``` | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero is telling Python to interpret it as an octal number. | The leading zero makes the value an [octal number](http://en.wikipedia.org/wiki/Octal). |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
```
>>> sample={'first_value':0123456}
>>> sample
{'first_value': 42798}
``` | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | Numbers starting with `0` are considered [octal](http://en.wikipedia.org/wiki/Octal). You'll either need to wrap the number temporarily in a string or format `123456` with a leading zero when used; both times you can't get an integer with leading zeros (just a numeric string).
Option 1:
```
>>> sample={ 'first_value' : '0123456' }
>>> sample['first_value']
'0123456'
```
Option 2:
```
>>> sample={ 'first_value' : 123456 }
>>> '{0:07}'.format(sample['first_value'])
'0123456'
``` | When you write 0123456, it gets interpreted as base-8, which is 42798 decimal |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
```
>>> sample={'first_value':0123456}
>>> sample
{'first_value': 42798}
``` | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero makes the value an [octal number](http://en.wikipedia.org/wiki/Octal). | When you write 0123456, it gets interpreted as base-8, which is 42798 decimal |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begins by 0. However, after I create dictionary value has changing. What I do wrong?
```
>>> sample={'first_value':0123456}
>>> sample
{'first_value': 42798}
``` | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | Numbers starting with `0` are considered [octal](http://en.wikipedia.org/wiki/Octal). You'll either need to wrap the number temporarily in a string or format `123456` with a leading zero when used; both times you can't get an integer with leading zeros (just a numeric string).
Option 1:
```
>>> sample={ 'first_value' : '0123456' }
>>> sample['first_value']
'0123456'
```
Option 2:
```
>>> sample={ 'first_value' : 123456 }
>>> '{0:07}'.format(sample['first_value'])
'0123456'
``` | The leading zero makes the value an [octal number](http://en.wikipedia.org/wiki/Octal). |
41,782,396 | I am trying to deploy a [sample app](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/django_cloudsql) to the Google App Engine Flexible Environment based on [this](https://cloud.google.com/python/django/flexible-environment) tutorial. The deployment works, however, the application cannot start up. I get the following error message:
```
Updating service [default]...failed.
ERROR: (gcloud.app.deploy) Error Response: [9]
Application startup error:
[2017-01-21 17:01:14 +0000] [5] [INFO] Starting gunicorn 19.6.0
[2017-01-21 17:01:14 +0000] [5] [INFO] Listening at: http://0.0.0.0:8080 (5)
[2017-01-21 17:01:14 +0000] [5] [INFO] Using worker: sync
[2017-01-21 17:01:14 +0000] [8] [INFO] Booting worker with pid: 8
[2017-01-21 17:01:14 +0000] [8] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/env/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
worker.init_process()
File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process
self.load_wsgi()
File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
self.wsgi = self.app.wsgi()
File "/env/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
return self.load_wsgiapp()
File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
return util.import_app(self.app_uri)
File "/env/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app
__import__(module)
ImportError: No module named 'mysite'
[2017-01-21 17:01:14 +0000] [8] [INFO] Worker exiting (pid: 8)
[2017-01-21 17:01:14 +0000] [5] [INFO] Shutting down: Master
[2017-01-21 17:01:14 +0000] [5] [INFO] Reason: Worker failed to boot.
```
As you can see on GitHub (see link above), the **/app.yaml** file looks like this:
```
# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT mysite.wsgi
beta_settings:
cloud_sql_instances: <your-cloudsql-connection-string>
runtime_config:
python_version: 3
# [END runtime]
```
And the **/mysite/wsgi.py** file like this:
```
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
```
Since the Flexible Environment is in beta, I am not sure if this might be a bug. However, I am using the original app from GitHub without any changes following the official documentation, so I would expect it to work.
I appreciate your help. | 2017/01/21 | [
"https://Stackoverflow.com/questions/41782396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373359/"
] | `setf` returns the original flag value, so you can simply store that then put it back when you're done.
The same is true of `precision`.
So:
```
// Change flags & precision (storing original values)
const auto original_flags = std::cout.setf(std::ios::fixed | std::ios::showpoint);
const auto original_precision = std::cout.precision(2);
// Do your I/O
std::cout << someValue;
// Reset the precision, and affected flags, to their original values
std::cout.setf(original_flags, std::ios::fixed | std::ios::showpoint);
std::cout.precision(original_precision);
```
Read [some documentation](http://en.cppreference.com/w/cpp/io/ios_base/setf). | You can use flags() method to save and restore all flags or unsetf() the one returned by setf
```
std::ios::fmtflags oldFlags( cout.flags() );
cout.setf(std::ios::fixed);
cout.setf(std::ios::showpoint);
std::streamsize oldPrecision(cout.precision(2));
// output whatever you should.
cout.flags( oldFlags );
cout.precision(oldPrecision)
``` |
41,782,396 | I am trying to deploy a [sample app](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/django_cloudsql) to the Google App Engine Flexible Environment based on [this](https://cloud.google.com/python/django/flexible-environment) tutorial. The deployment works, however, the application cannot start up. I get the following error message:
```
Updating service [default]...failed.
ERROR: (gcloud.app.deploy) Error Response: [9]
Application startup error:
[2017-01-21 17:01:14 +0000] [5] [INFO] Starting gunicorn 19.6.0
[2017-01-21 17:01:14 +0000] [5] [INFO] Listening at: http://0.0.0.0:8080 (5)
[2017-01-21 17:01:14 +0000] [5] [INFO] Using worker: sync
[2017-01-21 17:01:14 +0000] [8] [INFO] Booting worker with pid: 8
[2017-01-21 17:01:14 +0000] [8] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/env/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
worker.init_process()
File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process
self.load_wsgi()
File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
self.wsgi = self.app.wsgi()
File "/env/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
return self.load_wsgiapp()
File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
return util.import_app(self.app_uri)
File "/env/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app
__import__(module)
ImportError: No module named 'mysite'
[2017-01-21 17:01:14 +0000] [8] [INFO] Worker exiting (pid: 8)
[2017-01-21 17:01:14 +0000] [5] [INFO] Shutting down: Master
[2017-01-21 17:01:14 +0000] [5] [INFO] Reason: Worker failed to boot.
```
As you can see on GitHub (see link above), the **/app.yaml** file looks like this:
```
# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT mysite.wsgi
beta_settings:
cloud_sql_instances: <your-cloudsql-connection-string>
runtime_config:
python_version: 3
# [END runtime]
```
And the **/mysite/wsgi.py** file like this:
```
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
```
Since the Flexible Environment is in beta, I am not sure if this might be a bug. However, I am using the original app from GitHub without any changes following the official documentation, so I would expect it to work.
I appreciate your help. | 2017/01/21 | [
"https://Stackoverflow.com/questions/41782396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373359/"
] | `setf` returns the original flag value, so you can simply store that then put it back when you're done.
The same is true of `precision`.
So:
```
// Change flags & precision (storing original values)
const auto original_flags = std::cout.setf(std::ios::fixed | std::ios::showpoint);
const auto original_precision = std::cout.precision(2);
// Do your I/O
std::cout << someValue;
// Reset the precision, and affected flags, to their original values
std::cout.setf(original_flags, std::ios::fixed | std::ios::showpoint);
std::cout.precision(original_precision);
```
Read [some documentation](http://en.cppreference.com/w/cpp/io/ios_base/setf). | Your problem is that you share the formatting state with someone else. Obviously you can decide to track the changes and to correct them. But there is a saying: The best way to solve a problem is to prevent it from happening.
In your case, you need to have your own formatting state and to not share it with anyone else. You can have your own formatting state by using an instance of `std::ostream` with the same underlying streambuf than `std::cout`.
```
std::ostream my_fmt(std::cout.rdbuf());
my_fmt.setf(std::ios::fixed);
my_fmt.setf(std::ios::showpoint);
my_fmt.precision(2);
// output that could modify fmt flags
std::cout.setf(std::ios::scientific);
std::cout.precision(1);
// ----
// output some floats with my format independently of what other code did
my_fmt << "my format: " << 1.234 << "\n";
// output some floats with the format that may impacted by other code
std::cout << "std::cout format: " << 1.234 << "\n";
```
This will output:
```
my format: 1.23
std::cout format: 1.2e+00
```
See a live example there: [live](http://coliru.stacked-crooked.com/a/e82ebe6c1df1e157) |
41,782,396 | I am trying to deploy a [sample app](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/django_cloudsql) to the Google App Engine Flexible Environment based on [this](https://cloud.google.com/python/django/flexible-environment) tutorial. The deployment works, however, the application cannot start up. I get the following error message:
```
Updating service [default]...failed.
ERROR: (gcloud.app.deploy) Error Response: [9]
Application startup error:
[2017-01-21 17:01:14 +0000] [5] [INFO] Starting gunicorn 19.6.0
[2017-01-21 17:01:14 +0000] [5] [INFO] Listening at: http://0.0.0.0:8080 (5)
[2017-01-21 17:01:14 +0000] [5] [INFO] Using worker: sync
[2017-01-21 17:01:14 +0000] [8] [INFO] Booting worker with pid: 8
[2017-01-21 17:01:14 +0000] [8] [ERROR] Exception in worker process
Traceback (most recent call last):
File "/env/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker
worker.init_process()
File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process
self.load_wsgi()
File "/env/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi
self.wsgi = self.app.wsgi()
File "/env/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load
return self.load_wsgiapp()
File "/env/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp
return util.import_app(self.app_uri)
File "/env/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app
__import__(module)
ImportError: No module named 'mysite'
[2017-01-21 17:01:14 +0000] [8] [INFO] Worker exiting (pid: 8)
[2017-01-21 17:01:14 +0000] [5] [INFO] Shutting down: Master
[2017-01-21 17:01:14 +0000] [5] [INFO] Reason: Worker failed to boot.
```
As you can see on GitHub (see link above), the **/app.yaml** file looks like this:
```
# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT mysite.wsgi
beta_settings:
cloud_sql_instances: <your-cloudsql-connection-string>
runtime_config:
python_version: 3
# [END runtime]
```
And the **/mysite/wsgi.py** file like this:
```
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
application = get_wsgi_application()
```
Since the Flexible Environment is in beta, I am not sure if this might be a bug. However, I am using the original app from GitHub without any changes following the official documentation, so I would expect it to work.
I appreciate your help. | 2017/01/21 | [
"https://Stackoverflow.com/questions/41782396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373359/"
] | You can use flags() method to save and restore all flags or unsetf() the one returned by setf
```
std::ios::fmtflags oldFlags( cout.flags() );
cout.setf(std::ios::fixed);
cout.setf(std::ios::showpoint);
std::streamsize oldPrecision(cout.precision(2));
// output whatever you should.
cout.flags( oldFlags );
cout.precision(oldPrecision)
``` | Your problem is that you share the formatting state with someone else. Obviously you can decide to track the changes and to correct them. But there is a saying: The best way to solve a problem is to prevent it from happening.
In your case, you need to have your own formatting state and to not share it with anyone else. You can have your own formatting state by using an instance of `std::ostream` with the same underlying streambuf than `std::cout`.
```
std::ostream my_fmt(std::cout.rdbuf());
my_fmt.setf(std::ios::fixed);
my_fmt.setf(std::ios::showpoint);
my_fmt.precision(2);
// output that could modify fmt flags
std::cout.setf(std::ios::scientific);
std::cout.precision(1);
// ----
// output some floats with my format independently of what other code did
my_fmt << "my format: " << 1.234 << "\n";
// output some floats with the format that may impacted by other code
std::cout << "std::cout format: " << 1.234 << "\n";
```
This will output:
```
my format: 1.23
std::cout format: 1.2e+00
```
See a live example there: [live](http://coliru.stacked-crooked.com/a/e82ebe6c1df1e157) |
68,403,642 | I need to share well described data and want to do this in a modern way that avoids managing bureaucratic documentation no one will read. Fields require some description or note (eg. "values don't include ABC because XYZ") which I'd like to associate to columns that'll be saved with `pd.to_<whatever>()`, but I don't know of such functionality in pandas.
The format can't [present security concerns](https://docs.python.org/3/library/pickle.html#module-pickle), and should have a practical compromise between data integrity, performance, and file size. [Looks like JSON without index might suit](https://stackoverflow.com/a/33570065/4107349).
[JSON documentation writes of schema annotations](http://json-schema.org/understanding-json-schema/reference/generic.html#annotations), which supports pairing keywords like `description` with strings, but I can't figure out how to use this with options described in [pandas `to_json` documentation](https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.to_json.html).
Example df:
```
df = pd.DataFrame({"numbers": [6, 2],"strings": ["foo", "whatever"]})
df.to_json('temptest.json', orient='table', indent=4, index=False)
```
We can edit the JSON to include `description`:
```
"schema":{
"fields":[
{
"name":"numbers",
"description": "example string",
"type":"integer"
},
...
```
We can then `df = pd.read_json("temptest.json", orient='table')` but descriptions seem ignored and are lost upon saving.
The [only other answer I found saves separate dicts and dfs](https://stackoverflow.com/a/33113390/4107349) into a single JSON, but I couldn't replicate this without "ValueError: Trailing data". I need something less cumbersome and error prone, and files requiring custom instructions on how to open them aren't appropriate.
How can we can work with and save brief data descriptions with JSON or another format? | 2021/07/16 | [
"https://Stackoverflow.com/questions/68403642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4107349/"
] | Would the following rough sketch be something you could live with:
**Step 1**: Create json structure out of `df` like you did
```
df.to_json('temp.json', orient='table', indent=4, index=False)
```
**Step 2**: Add the column description to the so produced json-file as you already did (could be done easily in a structured/programatically manner):
```
{
"schema":{
"fields":[
{
"name":"numbers",
"type":"integer",
"description": "example number"
},
{
"name":"strings",
"type":"string",
"description": "example string"
}
],
"pandas_version":"0.20.0"
},
"data":[...]
}
```
One way to do that would be to write a little function that uses Pandas `.to_json` as a base output and then adds the desired descriptions to the Pandas json-dump (this is step 1 & 2 together):
```
import json
def to_json_annotated(filepath, df, annotations):
df_json = json.loads(df.to_json(orient='table', index=False))
for field in df_json['schema']['fields']:
field['description'] = annotations.get(field['name'], None)
with open(filepath, 'w') as file:
json.dump(df_json, file)
```
As in the example above:
```
annotations = {'numbers': 'example number',
'strings': 'example string'}
to_json_annotated('temp.json', df, annotations)
```
**Step 3**: Reading the information back into Pandas-format:
```
import json
with open('temp.json', 'r') as file:
json_df = json.load(file)
df_data = pd.json_normalize(json_df, 'data') # pd.read_json('temp.json', orient='table') works too
df_meta = pd.json_normalize(json_df, ['schema', 'fields'])
```
with the results:
```
df_data:
numbers strings
0 6 foo
1 2 whatever
```
```
df_meta:
name type description
0 numbers integer example number
1 strings string example string
``` | I didn't see that there will be such an option but I think you can just add a description inside of each variable:
```
schema = {'first':{'Variable':'x',"description": "example string","value": 2},"second":{"Variable":"y","description": "example string","value": 3}}
```
It creates a table:
```
first second
Variable x y
description example string example string
value 2 3
``` |
53,340,120 | I would like to install the package : newsapi in Python
I run the command
```
pip3 install newsapi-python
```
The package was succefully installed. But I import him in Anaconda :
```
from newsapi import NewsApiClient
>> ModuleNotFoundError: No module named 'newsapi'
```
I would like to know how to solve this kind of problem. I think that is linked to some path, but I am not sure | 2018/11/16 | [
"https://Stackoverflow.com/questions/53340120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10651723/"
] | I think the issue is you aren't importing vue-router into your app. Only into router.js and then you don't import all of router.js into your app, only the createRouter function. Try this:
```
//routes.js
import Home from "../components/Home/Home.vue";
import About from "../components/About.vue";
import FallBackPage from "../components/FallBackPage/FallBackPage.vue";
import MyOrders from "../components/MyOrders/MyOrders.vue";
export const routes [
{ path: "/", component: Home },
{ path: "/about", component: About },
{ path: "/myorders", component: MyOrders },
{ path: "/*", component: FallBackPage }
]
//main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import {routes} from './routes'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
```
Then in your component you use `this.$router.push("/")` | To change route
```
this.$router.push({ path: '/' })
this.$router.push({ name: 'Home' })
```
//main.js
```
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import { routes } from "./router/router";
Vue.use(VueRouter);
export function createApp() {
const router = new VueRouter({
mode: "history",
routes
});
const app = new Vue({
router,
render: h => h(App)
}).$mount("#app");
return { app, router };
}
```
//routes.js
```
import Home from "../components/Home/Home.vue";
import About from "../components/About.vue";
import FallBackPage from "../components/FallBackPage/FallBackPage.vue";
import MyOrders from "../components/MyOrders/MyOrders.vue";
export const routes = [
{ path: "/", component: Home },
{ path: "/about", component: About },
{ path: "/myorders", component: MyOrders },
{ path: "/*", component: FallBackPage }
]
```
on top of main.js changes to change route we need to use the following
```
this.$router.push({ path: '/' })
this.$router.push({ name: 'Home' })
``` |
51,605,651 | I'm looking to find the max run of consecutive zeros in a DataFrame with the result grouped by user. I'm interested in running the RLE on usage.
### sample input:
user--day--usage
A-----1------0
A-----2------0
A-----3------1
B-----1------0
B-----2------1
B-----3------0
### Desired output
user---longest\_run
a - - - - 2
b - - - - 1
```
mydata <- mydata[order(mydata$user, mydata$day),]
user <- unique(mydata$user)
d2 <- data.frame(matrix(NA, ncol = 2, nrow = length(user)))
names(d2) <- c("user", "longest_no_usage")
d2$user <- user
for (i in user) {
if (0 %in% mydata$usage[mydata$user == i]) {
run <- rle(mydata$usage[mydata$user == i]) #Run Length Encoding
d2$longest_no_usage[d2$user == i] <- max(run$length[run$values == 0])
} else {
d2$longest_no_usage[d2$user == i] <- 0 #some users did not have no-usage days
}
}
d2 <- d2[order(-d2$longest_no_usage),]
```
this works in R but I want to do the same thing in python, I'm totally stumped | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10158469/"
] | Use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html) by columns `user`, `usage` and helper `Series` for consecutive values first:
```
print (df)
user day usage
0 A 1 0
1 A 2 0
2 A 3 1
3 B 1 0
4 B 2 1
5 B 3 0
6 C 1 1
df1 = (df.groupby([df['user'],
df['usage'].rename('val'),
df['usage'].ne(df['usage'].shift()).cumsum()])
.size()
.to_frame(name='longest_run'))
print (df1)
longest_run
user val usage
A 0 1 2
1 2 1
B 0 3 1
5 1
1 4 1
C 1 6 1
```
Then filter only `zero` rows, get `max` and add [`reindex`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html) for append non `0` groups:
```
df2 = (df1.query('val == 0')
.max(level=0)
.reindex(df['user'].unique(), fill_value=0)
.reset_index())
print (df2)
user longest_run
0 A 2
1 B 1
2 C 0
```
**Detail**:
```
print (df['usage'].ne(df['usage'].shift()).cumsum())
0 1
1 1
2 2
3 3
4 4
5 5
6 6
Name: usage, dtype: int32
``` | I think the following does what you are looking for, where the `consecutive_zero` function is an adaptation of the top answer [here](https://codereview.stackexchange.com/questions/138550/count-consecutive-ones-in-a-binary-list).
Hope this helps!
```
import pandas as pd
from itertools import groupby
df = pd.DataFrame([['A', 1], ['A', 0], ['A', 0], ['B', 0],['B',1],['C',2]],
columns=["user", "usage"])
def len_iter(items):
return sum(1 for _ in items)
def consecutive_zero(data):
x = list((len_iter(run) for val, run in groupby(data) if val==0))
if len(x)==0: return 0
else: return max(x)
df.groupby('user').apply(lambda x: consecutive_zero(x['usage']))
```
Output:
```
user
A 2
B 1
C 0
dtype: int64
``` |
51,605,651 | I'm looking to find the max run of consecutive zeros in a DataFrame with the result grouped by user. I'm interested in running the RLE on usage.
### sample input:
user--day--usage
A-----1------0
A-----2------0
A-----3------1
B-----1------0
B-----2------1
B-----3------0
### Desired output
user---longest\_run
a - - - - 2
b - - - - 1
```
mydata <- mydata[order(mydata$user, mydata$day),]
user <- unique(mydata$user)
d2 <- data.frame(matrix(NA, ncol = 2, nrow = length(user)))
names(d2) <- c("user", "longest_no_usage")
d2$user <- user
for (i in user) {
if (0 %in% mydata$usage[mydata$user == i]) {
run <- rle(mydata$usage[mydata$user == i]) #Run Length Encoding
d2$longest_no_usage[d2$user == i] <- max(run$length[run$values == 0])
} else {
d2$longest_no_usage[d2$user == i] <- 0 #some users did not have no-usage days
}
}
d2 <- d2[order(-d2$longest_no_usage),]
```
this works in R but I want to do the same thing in python, I'm totally stumped | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10158469/"
] | Use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html) by columns `user`, `usage` and helper `Series` for consecutive values first:
```
print (df)
user day usage
0 A 1 0
1 A 2 0
2 A 3 1
3 B 1 0
4 B 2 1
5 B 3 0
6 C 1 1
df1 = (df.groupby([df['user'],
df['usage'].rename('val'),
df['usage'].ne(df['usage'].shift()).cumsum()])
.size()
.to_frame(name='longest_run'))
print (df1)
longest_run
user val usage
A 0 1 2
1 2 1
B 0 3 1
5 1
1 4 1
C 1 6 1
```
Then filter only `zero` rows, get `max` and add [`reindex`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html) for append non `0` groups:
```
df2 = (df1.query('val == 0')
.max(level=0)
.reindex(df['user'].unique(), fill_value=0)
.reset_index())
print (df2)
user longest_run
0 A 2
1 B 1
2 C 0
```
**Detail**:
```
print (df['usage'].ne(df['usage'].shift()).cumsum())
0 1
1 1
2 2
3 3
4 4
5 5
6 6
Name: usage, dtype: int32
``` | If you have a large dataset and speed is essential, you might want to try the high-performance [pyrle](https://github.com/pyranges/pyrle) library.
Setup:
```
# pip install pyrle
# or
# conda install -c bioconda pyrle
import numpy as np
np.random.seed(0)
import pandas as pd
from pyrle import Rle
size = int(1e7)
number = np.random.randint(2, size=size)
user = np.random.randint(5, size=size)
df = pd.DataFrame({"User": np.sort(user), "Number": number})
df
# User Number
# 0 0 0
# 1 0 1
# 2 0 1
# 3 0 0
# 4 0 1
# ... ... ...
# 9999995 4 1
# 9999996 4 1
# 9999997 4 0
# 9999998 4 0
# 9999999 4 1
#
# [10000000 rows x 2 columns]
```
Execution:
```
for u, udf in df.groupby("User"):
r = Rle(udf.Number)
is_0 = r.values == 0
print("User", u, "Max", np.max(r.runs[is_0]))
# (Wall time: 1.41 s)
# User 0 Max 20
# User 1 Max 23
# User 2 Max 20
# User 3 Max 22
# User 4 Max 23
``` |
51,605,651 | I'm looking to find the max run of consecutive zeros in a DataFrame with the result grouped by user. I'm interested in running the RLE on usage.
### sample input:
user--day--usage
A-----1------0
A-----2------0
A-----3------1
B-----1------0
B-----2------1
B-----3------0
### Desired output
user---longest\_run
a - - - - 2
b - - - - 1
```
mydata <- mydata[order(mydata$user, mydata$day),]
user <- unique(mydata$user)
d2 <- data.frame(matrix(NA, ncol = 2, nrow = length(user)))
names(d2) <- c("user", "longest_no_usage")
d2$user <- user
for (i in user) {
if (0 %in% mydata$usage[mydata$user == i]) {
run <- rle(mydata$usage[mydata$user == i]) #Run Length Encoding
d2$longest_no_usage[d2$user == i] <- max(run$length[run$values == 0])
} else {
d2$longest_no_usage[d2$user == i] <- 0 #some users did not have no-usage days
}
}
d2 <- d2[order(-d2$longest_no_usage),]
```
this works in R but I want to do the same thing in python, I'm totally stumped | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10158469/"
] | Use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html) by columns `user`, `usage` and helper `Series` for consecutive values first:
```
print (df)
user day usage
0 A 1 0
1 A 2 0
2 A 3 1
3 B 1 0
4 B 2 1
5 B 3 0
6 C 1 1
df1 = (df.groupby([df['user'],
df['usage'].rename('val'),
df['usage'].ne(df['usage'].shift()).cumsum()])
.size()
.to_frame(name='longest_run'))
print (df1)
longest_run
user val usage
A 0 1 2
1 2 1
B 0 3 1
5 1
1 4 1
C 1 6 1
```
Then filter only `zero` rows, get `max` and add [`reindex`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html) for append non `0` groups:
```
df2 = (df1.query('val == 0')
.max(level=0)
.reindex(df['user'].unique(), fill_value=0)
.reset_index())
print (df2)
user longest_run
0 A 2
1 B 1
2 C 0
```
**Detail**:
```
print (df['usage'].ne(df['usage'].shift()).cumsum())
0 1
1 1
2 2
3 3
4 4
5 5
6 6
Name: usage, dtype: int32
``` | get max number of consecutive zeros on series:
```
def max0(sr):
return (sr != 0).cumsum().value_counts().max() - (0 if (sr != 0).cumsum().value_counts().idxmax()==0 else 1)
max0(pd.Series([1,0,0,0,0,2,3]))
```
>
> 4
>
>
> |
69,339,582 | I would like to compute the **hash of the contents (sequence of *bits*)** of a file (whose length could be any number of bits, and so not necessarily a multiple of the *trendy* eight) and send that file to a friend along with the hash-value. My friend should be able to compute the same hash from the file contents. I want to use Python 3 to compute the hash, but my friend can't use Python 3 (because I'll wait till next year to send the file and by then Python 3 will be out of style, and he'll want to be using Python++ or whatever). All I can guarantee is that my friend will know how to compute the hash, in a mathematical sense---he might have to write his own code to run on his implementation of the [MIX](https://en.wikipedia.org/wiki/MIX) machine (which he will know how to do).
**What hash do I use**, and, more importantly, **what do I take the hash of**? For example, do I hash the `str` returned from a `read` on the file opened for reading as *text*? Do I hash some `bytes`-like object returned from a *binary* `read`? What if the file has weird end-of-line markers? Do I pad the tail end first so that the thing I am hashing is an appropriate size?
```
import hashlib
FILENAME = "filename"
# Now, what?
```
**I say "sequence of *bits*"** because not all computers are based on the 8-bit byte, and saying "sequence of bytes" is therefore too ambiguous. For example, [GreenArrays, Inc.](http://www.greenarraychips.com/) has designed a [supercomputer on a chip](http://www.greenarraychips.com/home/products/index.html), where each computer has 18-bit (eighteen-bit) words (when these words are used for encoding native instructions, they are composed of three 5-bit "bytes" and one 3-bit byte each). I also understand that before the 1970's, a variety of byte-sizes were used. Although the 8-bit byte may be the most common choice, and may be optimal in some sense, the choice of 8 bits per byte is arbitrary.
See Also
--------
[Is python's hash() portable?](https://stackoverflow.com/questions/31170783/is-pythons-hash-portable) | 2021/09/26 | [
"https://Stackoverflow.com/questions/69339582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8341274/"
] | First of all, the `hash()` function in Python is not the same as **cryptographic hash functions** in general. Here're the differences:
### `hash()`
>
> A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.
>
>
>
>
> Note that the hash of a value only needs to be the same for one run of Python. In Python 3.3 they will in fact change for every new run of Python
>
>
>
[What does hash do in python?](https://stackoverflow.com/questions/17585730/what-does-hash-do-in-python)
### Cryptographic hash functions
>
> A cryptographic hash function (CHF) is a mathematical algorithm that maps data of an arbitrary size (often called the "message") to a bit array of a fixed size
>
>
>
>
> It is deterministic, meaning that the same message always results in the same hash.
>
>
>
<https://en.wikipedia.org/wiki/Cryptographic_hash_function>
---
Now let's come back to your question:
>
> I would like to compute the hash of the contents (sequence of bits) of a file (whose length could be any number of bits, and so not necessarily a multiple of the trendy eight) and send that file to a friend along with the hash-value. My friend should be able to compute the same hash from the file contents.
>
>
>
What you're looking for is one of the **cryptographic hash functions**. Typically, to calculate the file hash, MD5, SHA-1, SHA-256 are used. You want to open the file as **binary** and hash the binary bits, and finally digest it & encode it in hexadecimal form.
```
import hashlib
def calculateSHA256Hash(filePath):
h = hashlib.sha256()
with open(filePath, "rb") as f:
data = f.read(2048)
while data != b"":
h.update(data)
data = f.read(2048)
return h.hexdigest()
print(calculateSHA256Hash(filePath = 'stackoverflow_hash.py'))
```
The above code takes itself as an input, hence it produced an SHA-256 hash for itself, being `610e15155439c75f6b63cd084c6a235b42bb6a54950dcb8f2edab45d0280335e`. This remains consistent as long as the code is not changed.
Another example would be to hash a txt file, `test.txt` with content `Helloworld`.
This is done by simply changing the last line of the code to "test.txt"
```
print(calculateSHA256Hash(filePath = 'text.txt'))
```
This gives a SHA-256 hash of `5ab92ff2e9e8e609398a36733c057e4903ac6643c646fbd9ab12d0f6234c8daf`. | I arrived at `sha256hexdigestFromFile`, an alternative to @Lincoln Yan 's `calculateSHA256Hash`, after reviewing the [standard](http://dx.doi.org/10.6028/NIST.FIPS.180-4) for SHA-256.
This is also a response to my comment about `2048`.
```
def sha256hexdigestFromFile(filePath, blocks = 1):
'''Return as a str the SHA-256 message digest of contents of
file at filePath.
Reference: Introduction of NIST (2015) Secure Hash
Standard (SHS), FIPS PUB 180-4. DOI:10.6028/NIST.FIPS.180-4
'''
assert isinstance(blocks, int) and 0 < blocks, \
'The blocks argument must be an int greater than zero.'
with open(filePath, 'rb') as MessageStream:
from hashlib import sha256
from functools import reduce
def hashUpdated(Hash, MESSAGE_BLOCK):
Hash.update(MESSAGE_BLOCK)
return Hash
def messageBlocks():
'Return a generator over the blocks of the MessageStream.'
WORD_SIZE, BLOCK_SIZE = 4, 512 # PER THE SHA-256 STANDARD
BYTE_COUNT = WORD_SIZE * BLOCK_SIZE * blocks
yield MessageStream.read(BYTE_COUNT)
return reduce(hashUpdated, messageBlocks(), sha256()).hexdigest()
``` |
51,797,321 | I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
del_list = [0, 4, 11]
desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]
```
Here is what I have done
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
index_list = [0, 4, 11]
for element in index_list:
del x[element]
print(x)
```
I get this error. **I can figure out that because of deleting elements the list shortens and the index goes out of range**. But i am not sure how to do it
```
Traceback (most recent call last):
IndexError: list assignment index out of range
``` | 2018/08/11 | [
"https://Stackoverflow.com/questions/51797321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10211342/"
] | This question already has an answer here. [How to delete elements from a list using a list of indexes?](https://stackoverflow.com/questions/38647439/how-to-delete-elements-from-a-list-using-a-list-of-indexes).
BTW this will do for you
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
index_list = [0, 4, 11]
value_list = []
for element in index_list:
value_list.append(x[element])
for element in value_list:
x.remove(element)
print(x)
``` | You can sort the `del_list` list in descending order and then use the `list.pop()` method to delete specified indexes:
```
for i in sorted(del_list, reverse=True):
x.pop(i)
```
so that `x` would become:
```
[45, 55, 6, 37, 656, 78, 8, 99, 9]
``` |
51,797,321 | I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
del_list = [0, 4, 11]
desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]
```
Here is what I have done
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
index_list = [0, 4, 11]
for element in index_list:
del x[element]
print(x)
```
I get this error. **I can figure out that because of deleting elements the list shortens and the index goes out of range**. But i am not sure how to do it
```
Traceback (most recent call last):
IndexError: list assignment index out of range
``` | 2018/08/11 | [
"https://Stackoverflow.com/questions/51797321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10211342/"
] | You could also use enumerate:
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
index_list = [0, 4, 11]
new_x = []
for index, element in enumerate(x):
if index not in index_list:
new_x.append(element)
print(new_x)
``` | You can sort the `del_list` list in descending order and then use the `list.pop()` method to delete specified indexes:
```
for i in sorted(del_list, reverse=True):
x.pop(i)
```
so that `x` would become:
```
[45, 55, 6, 37, 656, 78, 8, 99, 9]
``` |
53,501,778 | I have installed `mysql connector` , which already has a built in sql adapter, i also don't need to install `mysqlclient` as i have mysql connector. But when i start python manage.py migrate, it is asking me to download mysqlclient. But i can not install `mysqlclient`. Can anyone help me how to fix the problem. Thanks
error:
```
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\models\base.py", line 101, in __new__
new_class.add_to_class('_meta', Options(meta, app_label))
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\models\base.py", line 305, in add_to_class
value.contribute_to_class(cls, name)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\models\options.py", line 203, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\utils.py", line 202, in __getitem__
backend = load_backend(db['ENGINE'])
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\utils.py", line 110, in load_backend
return import_module('%s.base' % backend_name)
File "C:\Program Files (x86)\Python37-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\mysql\base.py", line 20, in <module>
) from err
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?
``` | 2018/11/27 | [
"https://Stackoverflow.com/questions/53501778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Maybe you need to install mysql-connector-c connector and after:
```
pip install mysqlclient==1.3.13
``` | [There are two backends](https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers) for using MySQL with python
* mysqlclient - recommended by the docs, but can be tricky to install on Windows
* mysql connector - doesn't always support the latest Django version.
First you need to decide which backend you want to use.
If you want to use mysql connector, then you don't need to install `mysqlclient`. You do need to change `ENGINES` in your `DATABASES` setting to use the connector backend.
```
DATABASES = {
'default': {
'NAME': 'user_data',
'ENGINE': 'mysql.connector.django',
...
},
...
}
```
If you make this change, it should stop the *did you install mysqlclient* error messages. See [the docs](https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html) for more info about using mysql connector.
If you want to use `mysqlclient`, then leave the ENGINE as `'django.db.backends.mysql'` in your `DATABASES` setting. Installing `mysqlclient` on Windows can be tricky, you have a few different options:
1. Install an official wheel. As of December 2018, there are wheels for the latest release mysqlclient 1.3.14 for Python 3.6 and Python 3.7. Install mysqlclient with:
```
pip install mysqlclient==1.3.14
```
2. Install one of the [unofficial wheels](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient). This will allow you to use Python 3.7 and a more up-to-date version of mysqlclient.
3. Install mysqlclient from source. This can be tricky on Windows, and I can't offer any tips on how to do that. |
13,578,923 | Can anybody figure out how the python code below works and give me a possible way to port it to Objective-C (iOS) to work in my own project?
`month_id = calendar.timegm(datetime(year, month, 1, hour, 0, 0).timetuple()) * 1000`
Thanks a ton! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13578923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981575/"
] | calendar.timegm converts the given time to time in seconds since epoch of 1970. More information at <http://docs.python.org/3/library/calendar.html?highlight=calendar.timegm#calendar.timegm> | open a python interpreter, then enter this:
```
>>> import calendar
>>> from datetime import datetime
```
then input your line of code, and you should be able to get a pretty good idea. |
40,514,205 | I am developing a slack bot with plugins using entry points. I want to dynamically add a plugin during runtime.
I have a project with this structure:
```
+ ~/my_project_dir/
+ my_projects_python_code/
+ plugins/
- plugin1.py
- plugin2.py
- ...
- pluginN.py
- setup.py
- venv/
- install.sh
```
My `setup.py` file looks like this:
```
from setuptools import setup, find_packages
setup(
name="My_Project_plugins",
version="1.0",
packages=['plugins'],
entry_points="""
[my_project.plugins]
plugin1 = plugins.plugin1:plugin1_class
plugin2 = plugins.plugin2:plugin2_class
...
pluginN = plugins.pluginN:pluginN_class
"""
)
```
Running `sudo install.sh` does the following:
1. Copies the needed files to `/usr/share/my_project_dir/`
2. Activate virtualenv at `/usr/share/my_project_dir/venv/bin/activate`
3. Run: `python setup.py develop`
This works as expected and sets up my entry points correctly so that I can use them through the bot.
But I want to be able to add a plugin to `setup.py` and be able to use it while the bot is running. So I want to add a line: `pluginN+1 = plugins.pluginN+1:pluginN+1_class` and have pluginN+1 available to use.
What I've tried/learned:
* After `/usr/share/my_project_dir/venv/bin/activate` I open a Python interactive shell and iterate through `pkg_resources.iter_entry_points()`, which lists everything that was loaded from the initial state of setup.py (i.e. plugin1 through pluginN)
* If I add a line to `setup.py` and run `sudo python setup.py develop` and iterate again with the same Python shell, it doesn't pick up the new plugin but if I exit the shell and reopen it, the new plugin gets picked up.
* I noticed that when I install the bot, part of the output says:
+ `Copying My_Project_plugins-1.0-py2.7.egg to /usr/share/my_project-dir/venv/lib/python2.7/site-packages`
* When I `cd /usr/share/my_project_dir/`, activate my virtualenv, and run `setup.py` from the shell it says:
+ `Creating /usr/local/lib/python2.7/dist-packages/My_Project-plugins.egg-link (link to .)
My_Project-plugins 1.0 is already the active version in easy-install.pth` | 2016/11/09 | [
"https://Stackoverflow.com/questions/40514205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496918/"
] | I needed to do something similar to load a dummy plugin for test purposes. This differs slightly from your use-case in that I was specifically trying to avoid needing to define the entry points in the package (as it is just test code).
I found I could dynamically insert entries into the pkg\_resources data structures as follows:
```
import pkg_resources
# Create the fake entry point definition
ep = pkg_resources.EntryPoint.parse('dummy = dummy_module:DummyPlugin')
# Create a fake distribution to insert into the global working_set
d = pkg_resources.Distribution()
# Add the mapping to the fake EntryPoint
d._ep_map = {'namespace': {'dummy': ep}}
# Add the fake distribution to the global working_set
pkg_resources.working_set.add(d, 'dummy')
```
This, at run time, added an entry point called 'dummy' to 'namespace', which would be the class 'DummyPlugin' in 'dummy\_module.py'.
This was determined through use of the setuptools docs, and dir() on the objects to get more info as needed.
Docs are here: <http://setuptools.readthedocs.io/en/latest/pkg_resources.html>
You might especially look at <http://setuptools.readthedocs.io/en/latest/pkg_resources.html#locating-plugins> if all you need to do is load a plugin that you have just stored to your local filesystem. | It's more than at least 5 years, since the time when I first asked myself almost the same question, and your question now is an impulse to finally find it out.
For me it was as well interesting, if one can add entry points from the same directory as the script without installation of a package. Though I always knew that the only contents of the package might be some meta with entry points looking at some other packages.
Anyway, here is some setup of my directory:
```
ep_test newtover$ tree
.
├── foo-0.1.0.dist-info
│ ├── METADATA
│ └── entry_points.txt
└── foo.py
1 directory, 3 files
```
Here is the contents of `foo.py`:
```
ep_test newtover$ cat foo.py
def foo1():
print 'foo1'
def foo2():
print 'foo2'
```
Now let's open `ipython`:
```
In [1]: def write_ep(lines): # a helper to update entry points file
...: with open('foo-0.1.0.dist-info/entry_points.txt', 'w') as f1:
...: print >> f1, '\n'.join(lines)
...:
In [2]: write_ep([ # only one entry point under foo.test
...: "[foo.test]",
...: "foo_1 = foo:foo1",
...: ])
In [3]: !cat foo-0.1.0.dist-info/entry_points.txt
[foo.test]
foo1 = foo:foo1
In [4]: import pkg_resources
In [5]: ws = pkg_resources.WorkingSet() # here is the answer on the question
In [6]: list(ws.iter_entry_points('foo.test'))
Out[6]: [EntryPoint.parse('foo_1 = foo:foo1')]
In [7]: write_ep([ # two entry points
...: "[foo.test]",
...: "foo_1 = foo:foo1",
...: "foo_2 = foo:foo2"
...: ])
In [8]: ws = pkg_resources.WorkingSet() # a new instance of WorkingSet
```
With default parameters `WorkingSet` just revisits each entry in sys.path, but you can narrow the list. `pkg_resources.iter_entry_points` is bound to a global instance of `WorkingSet`.
```
In [9]: list(ws.iter_entry_points('foo.test')) # both are visible
Out[9]: [EntryPoint.parse('foo_1 = foo:foo1'), EntryPoint.parse('foo_2 = foo:foo2')]
In [10]: foos = [ep.load() for ep in ws.iter_entry_points('foo.test')]
In [11]: for func in foos: print 'name is {}'.format(func.__name__); func()
name is foo1
foo1
name is foo2
foo2
```
And the contents of METADATA as well:
```
ep_test newtover$ cat foo-0.1.0.dist-info/METADATA
Metadata-Version: 1.2
Name: foo
Version: 0.1.0
Summary: entry point test
```
**UPD1**: I thought it over once again and now understand that you need an additional step before using the new plugins: you need to reload the modules.
This might be as easy as:
```
In [33]: modules_to_reload = {ep1.module_name for ep1 in ws.iter_entry_points('foo.test')}
In [34]: for module_name in modules_to_reload:
....: reload(__import__(module_name))
....:
```
But if a new version of your plugins package is based on significant changes in other used modules, you might need a particular order of reloading and reloading of those changed modules. This might become a cumbersome task, so that restarting the bot would be the only way to go. |
40,514,205 | I am developing a slack bot with plugins using entry points. I want to dynamically add a plugin during runtime.
I have a project with this structure:
```
+ ~/my_project_dir/
+ my_projects_python_code/
+ plugins/
- plugin1.py
- plugin2.py
- ...
- pluginN.py
- setup.py
- venv/
- install.sh
```
My `setup.py` file looks like this:
```
from setuptools import setup, find_packages
setup(
name="My_Project_plugins",
version="1.0",
packages=['plugins'],
entry_points="""
[my_project.plugins]
plugin1 = plugins.plugin1:plugin1_class
plugin2 = plugins.plugin2:plugin2_class
...
pluginN = plugins.pluginN:pluginN_class
"""
)
```
Running `sudo install.sh` does the following:
1. Copies the needed files to `/usr/share/my_project_dir/`
2. Activate virtualenv at `/usr/share/my_project_dir/venv/bin/activate`
3. Run: `python setup.py develop`
This works as expected and sets up my entry points correctly so that I can use them through the bot.
But I want to be able to add a plugin to `setup.py` and be able to use it while the bot is running. So I want to add a line: `pluginN+1 = plugins.pluginN+1:pluginN+1_class` and have pluginN+1 available to use.
What I've tried/learned:
* After `/usr/share/my_project_dir/venv/bin/activate` I open a Python interactive shell and iterate through `pkg_resources.iter_entry_points()`, which lists everything that was loaded from the initial state of setup.py (i.e. plugin1 through pluginN)
* If I add a line to `setup.py` and run `sudo python setup.py develop` and iterate again with the same Python shell, it doesn't pick up the new plugin but if I exit the shell and reopen it, the new plugin gets picked up.
* I noticed that when I install the bot, part of the output says:
+ `Copying My_Project_plugins-1.0-py2.7.egg to /usr/share/my_project-dir/venv/lib/python2.7/site-packages`
* When I `cd /usr/share/my_project_dir/`, activate my virtualenv, and run `setup.py` from the shell it says:
+ `Creating /usr/local/lib/python2.7/dist-packages/My_Project-plugins.egg-link (link to .)
My_Project-plugins 1.0 is already the active version in easy-install.pth` | 2016/11/09 | [
"https://Stackoverflow.com/questions/40514205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496918/"
] | I needed to do something similar to load a dummy plugin for test purposes. This differs slightly from your use-case in that I was specifically trying to avoid needing to define the entry points in the package (as it is just test code).
I found I could dynamically insert entries into the pkg\_resources data structures as follows:
```
import pkg_resources
# Create the fake entry point definition
ep = pkg_resources.EntryPoint.parse('dummy = dummy_module:DummyPlugin')
# Create a fake distribution to insert into the global working_set
d = pkg_resources.Distribution()
# Add the mapping to the fake EntryPoint
d._ep_map = {'namespace': {'dummy': ep}}
# Add the fake distribution to the global working_set
pkg_resources.working_set.add(d, 'dummy')
```
This, at run time, added an entry point called 'dummy' to 'namespace', which would be the class 'DummyPlugin' in 'dummy\_module.py'.
This was determined through use of the setuptools docs, and dir() on the objects to get more info as needed.
Docs are here: <http://setuptools.readthedocs.io/en/latest/pkg_resources.html>
You might especially look at <http://setuptools.readthedocs.io/en/latest/pkg_resources.html#locating-plugins> if all you need to do is load a plugin that you have just stored to your local filesystem. | I had to change a bit solution by @j3p0uk to work for me. I wanted to use this inside an unit test (`unittest` framework). What I did is:
```
def test_entry_point(self):
distribution = pkg_resources.Distribution(__file__)
entry_point = pkg_resources.EntryPoint.parse('plugin1 = plugins.plugin1:plugin1_class', dist=distribution)
distribution._ep_map = {'my_project.plugins': {'plugin1': entry_point}}
pkg_resources.working_set.add(distribution)
```
This made also `entry_point.load()` work for me the in the code which is being tested, to really load the symbol referenced by the entry point. In my test I also have `my_project.plugins` having the name of the test file, and then the symbol to load is at the global scope of that file. |
51,004,898 | I'm trying to programmatically retrieve ASIN numbers for over 500+ books.
example: Product Catch-22 by Joseph Heller
Amazon URL: [https://www.amazon.com/Catch-22-Joseph-Heller/dp/3866155239](https://rads.stackoverflow.com/amzn/click/com/3866155239)
I can get the product numbers manually by searching for each product through a browser however that's not efficient. I would like to use an API or wget/curl at the worst case, but I'm hitting some stumbling blocks.
The Amazon API is not exactly the easiest to use...(I've been hitting my head against the wall trying to get the Signature Request Hash correct with python to no avail..)
Then I thought googler may be another option however after 15 request (even with time.sleep(30) google locks me out for a few hours [coming from multiple IP sources as well]).
How about bing...well they don't show any Amazon results via the API...which is really odd...
I tried writing my own Google Parser with wget but then I would have to import all that into BeautifulSoup and reparse...my sed and awk skills leave a lot to be desired...
Basically...Has anyone come across an easier way of obtaining the ASIN number for a product programmatically? | 2018/06/23 | [
"https://Stackoverflow.com/questions/51004898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9751133/"
] | <https://isbndb.com/> charges for the API :(
so...
Went the Google Web Scrape Route
```
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup
import requests
import time
def get_amazon_link(book_title):
url = 'https://www.google.com/search?q=amazon+novel+'+book_title
print(url)
url = Request(url)
url.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(url) as f:
data = f.readlines()
page_soup = soup(str(data), 'html.parser')
for line in page_soup.findAll('h3',{'class':'r'}):
for item in line.findAll('a', href=True):
item = item['href'].split('=')[1]
item = item.split('&')[0]
return item
def get_wiki_link(book_title):
url = 'https://www.google.com/search?q=wiki+novel+'+book_title
print(url)
url = Request(url)
url.add_header('User-Agent', 'Mozilla/5.0')
with urlopen(url) as f:
data = f.readlines()
page_soup = soup(str(data), 'html.parser')
for line in page_soup.findAll('h3',{'class':'r'}):
for item in line.findAll('a', href=True):
item = item['href'].split('=')[1]
item = item.split('&')[0]
return item
a = open('amazonbookslinks','w')
w = open('wikibooklinks','w')
with open('booklist') as b:
books = b.readlines()
for book in books:
book_title = book.replace(' ','+')
amazon_result = get_amazon_link(book_title)
amazon_msg = book +'@'+ amazon_result
a.write(amazon_msg + '\n')
time.sleep(5)
wiki_result = get_wiki_link(book_title)
wiki_msg = book +'@'+ wiki_result
w.write(wiki_msg + '\n')
time.sleep(5)
a.close()
w.close()
```
Not Pretty but it worked :) | According to Amazon's customer service page:
<https://www.amazon.co.uk/gp/help/customer/display.html?nodeId=898182>
>
> ASIN stands for Amazon Standard Identification Number. Almost every
> product on our site has its own ASIN, a unique code we use to identify
> it. For books, the ASIN is the same as the ISBN number, but for all
> other products a new ASIN is created when the item is uploaded to our
> catalogue.
>
>
>
This means that for the book 'Catch 22', its ISBN-10 is `3866155239`.
I suggest that you use a website like <https://isbndb.com/> to find ISBNs for books which will automatically give you the ASINs you are looking for. It also comes with a REST API which you can read about at <https://isbndb.com/apidocs>. |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives 0
second print gives p
I can't work out why, if you could give an explanation it would be much appreciated.
Thank you to those who help :) | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```
It's `bships[4-1][1-1]` which is `bships[3][0]` which is `['0','0','0','0'][0]` which is `0` | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == bships[4-2][1-1] == bships[2][0]
```
so first cell of the second-last row, `['p','p','0','s']` is a `'p'`.
Note that in Python, you can use negative indices without calculating the `len()` first; remove the `c` from your function and it'll all work just the same:
```
>>> battleships = [['0','p','0','s'],
... ['0','p','0','s'],
... ['p','p','0','s'],
... ['0','0','0','0']]
>>> def fun(a,b,bships):
... return bships[-b][a-1]
...
>>> print(fun(1,1,battleships))
0
>>> print(fun(1,2,battleships))
p
```
That is because Python treats negative indices as counting from the end; internally it'll use the length of the sequence (which is stored with the sequence) to calculate just the same thing but faster. |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives 0
second print gives p
I can't work out why, if you could give an explanation it would be much appreciated.
Thank you to those who help :) | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```
It's `bships[4-1][1-1]` which is `bships[3][0]` which is `['0','0','0','0'][0]` which is `0` | ```
>>> battleships = [['0','p','0','s'],
... ['0','p','0','s'],
... ['p','p','0','s'],
... ['0','0','0','0']]
>>>
>>> a = 1
>>> b = 1
>>> c = len(battleships)
>>> c-b,a-1
(3, 0)
```
Now `battleships[c-b][a-1]` can be broken into two parts:
`battleships[c-b]` and `[a-1]`
Python first calls `battleships[c-b]` as `c-b` is `3` so it returns the last list(4th item) from battleships. i.e `['0','0','0','0']` (indexing starts at `0`)
Now comes the second part :`[a-1]`
Now `[a-1]` is called on that returned list, i.e `['0','0','0','0']`
`['0','0','0','0'][a-1]` as `a-1` is `0` so python returns the first item from this list.
so you got '0'.
Same is applied for the different values of `a`,`b`:
```
>>> a = 1
>>> b = 2
>>> c-b,a-1
(2, 0)
>>> battleships[c-b]
['p', 'p', '0', 's']
>>> battleships[c-b][a-1] #calls ['p', 'p', '0', 's'][0]
'p'
``` |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives 0
second print gives p
I can't work out why, if you could give an explanation it would be much appreciated.
Thank you to those who help :) | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```
It's `bships[4-1][1-1]` which is `bships[3][0]` which is `['0','0','0','0'][0]` which is `0` | When you are having problem understanding any new thing in programming change the program a bit.
I'll give you an example. I changed it a bit.
```
battleships = [['0','p','0','s','3'],
['0','p','0','s','8'],
['p','p','0','s','2']]
print "len(battleships) =",len(battleships)
print "battleships[0] =",battleships[0]
print "battleships[1] =",battleships[1]
print "battleships[2] =",battleships[2]
print "len(battleships[0]) =", len(battleships[0])
```
When I run it the output is
```
len(battleships) = 3
battleships[0] = ['0', 'p', '0', 's', '3']
battleships[1] = ['0', 'p', '0', 's', '8']
battleships[2] = ['p', 'p', '0', 's', '2']
len(battleships[0]) = 5
```
Match the output statements with the print statements. That will help.
Try `print battleships[0][1]` etc.
---
One more suggestion. Search google for Python and install it on your computer. If I am correct this is from codecademy. Using only codecademy won't be enough. You will need to write Python scripts, run them and see their outputs. Only after that you'll be able to learn. Try [this](http://learnpythonthehardway.org/book/) out. They are better than codecademy at teaching programming. |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives 0
second print gives p
I can't work out why, if you could give an explanation it would be much appreciated.
Thank you to those who help :) | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == bships[4-2][1-1] == bships[2][0]
```
so first cell of the second-last row, `['p','p','0','s']` is a `'p'`.
Note that in Python, you can use negative indices without calculating the `len()` first; remove the `c` from your function and it'll all work just the same:
```
>>> battleships = [['0','p','0','s'],
... ['0','p','0','s'],
... ['p','p','0','s'],
... ['0','0','0','0']]
>>> def fun(a,b,bships):
... return bships[-b][a-1]
...
>>> print(fun(1,1,battleships))
0
>>> print(fun(1,2,battleships))
p
```
That is because Python treats negative indices as counting from the end; internally it'll use the length of the sequence (which is stored with the sequence) to calculate just the same thing but faster. | ```
>>> battleships = [['0','p','0','s'],
... ['0','p','0','s'],
... ['p','p','0','s'],
... ['0','0','0','0']]
>>>
>>> a = 1
>>> b = 1
>>> c = len(battleships)
>>> c-b,a-1
(3, 0)
```
Now `battleships[c-b][a-1]` can be broken into two parts:
`battleships[c-b]` and `[a-1]`
Python first calls `battleships[c-b]` as `c-b` is `3` so it returns the last list(4th item) from battleships. i.e `['0','0','0','0']` (indexing starts at `0`)
Now comes the second part :`[a-1]`
Now `[a-1]` is called on that returned list, i.e `['0','0','0','0']`
`['0','0','0','0'][a-1]` as `a-1` is `0` so python returns the first item from this list.
so you got '0'.
Same is applied for the different values of `a`,`b`:
```
>>> a = 1
>>> b = 2
>>> c-b,a-1
(2, 0)
>>> battleships[c-b]
['p', 'p', '0', 's']
>>> battleships[c-b][a-1] #calls ['p', 'p', '0', 's'][0]
'p'
``` |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives 0
second print gives p
I can't work out why, if you could give an explanation it would be much appreciated.
Thank you to those who help :) | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == bships[4-2][1-1] == bships[2][0]
```
so first cell of the second-last row, `['p','p','0','s']` is a `'p'`.
Note that in Python, you can use negative indices without calculating the `len()` first; remove the `c` from your function and it'll all work just the same:
```
>>> battleships = [['0','p','0','s'],
... ['0','p','0','s'],
... ['p','p','0','s'],
... ['0','0','0','0']]
>>> def fun(a,b,bships):
... return bships[-b][a-1]
...
>>> print(fun(1,1,battleships))
0
>>> print(fun(1,2,battleships))
p
```
That is because Python treats negative indices as counting from the end; internally it'll use the length of the sequence (which is stored with the sequence) to calculate just the same thing but faster. | When you are having problem understanding any new thing in programming change the program a bit.
I'll give you an example. I changed it a bit.
```
battleships = [['0','p','0','s','3'],
['0','p','0','s','8'],
['p','p','0','s','2']]
print "len(battleships) =",len(battleships)
print "battleships[0] =",battleships[0]
print "battleships[1] =",battleships[1]
print "battleships[2] =",battleships[2]
print "len(battleships[0]) =", len(battleships[0])
```
When I run it the output is
```
len(battleships) = 3
battleships[0] = ['0', 'p', '0', 's', '3']
battleships[1] = ['0', 'p', '0', 's', '8']
battleships[2] = ['p', 'p', '0', 's', '2']
len(battleships[0]) = 5
```
Match the output statements with the print statements. That will help.
Try `print battleships[0][1]` etc.
---
One more suggestion. Search google for Python and install it on your computer. If I am correct this is from codecademy. Using only codecademy won't be enough. You will need to write Python scripts, run them and see their outputs. Only after that you'll be able to learn. Try [this](http://learnpythonthehardway.org/book/) out. They are better than codecademy at teaching programming. |
56,434,745 | I'm trying to load MySQL JDBC driver from a python app. I'm not invoking 'bin/pyspark' or 'spark-submit' program; instead I have a Python script in which I'm initializing 'SparkContext' and 'SparkSession' objects.
I understand that we can pass '--jars' option when invoking 'pyspark', but how do I load and specify jdbc driver in my python app? | 2019/06/03 | [
"https://Stackoverflow.com/questions/56434745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208108/"
] | I think you want do something like this
```py
from pyspark.sql import SparkSession
# Creates spark session with JDBC JAR
spark = SparkSession.builder \
.appName('stack_overflow') \
.config('spark.jars', '/path/to/mysql/jdbc/connector') \
.getOrCreate()
# Creates your DataFrame with spark session with JDBC
df = spark.createDataFrame([
(1, 'Hello'),
(2, 'World!')
], ['Index', 'Value'])
df.write.jdbc('jdbc:mysql://host:3306/my_db', 'my_table',
mode='overwrite',
properties={'user': 'db_user', 'password': 'db_pass'})
``` | Answer is to create SparkContext like this:
```py
spark_conf = SparkConf().set("spark.jars", "/my/path/mysql_jdbc_driver.jar")
sc = SparkContext(conf=spark_conf)
```
This will load mysql driver into classpath. |
5,835,043 | I'm trying to use the ipy.vim script to set up a small python dev environment, but I'm running into a connection problem. When I type ipy\_vimserver.setup("demo") I get this error:
```
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/usr/lib/pymodules/python2.6/IPython/Extensions/ipy_vimserver.py", line 109, in serve_me
self.listen()
File "/usr/lib/pymodules/python2.6/IPython/Extensions/ipy_vimserver.py", line 93, in listen
self.socket.bind(self.__sname)
File "<string>", line 1, in bind
error: [Errno 98] Address already in use
```
When I type it a second time, everything is fine but when I launch gvim the F4/F5 command do nothing and state that they can't connect to the Ipython server.
any suggestion? | 2011/04/29 | [
"https://Stackoverflow.com/questions/5835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731470/"
] | I found it ! Thank you Anders
```
function UnixToDateTime(USec: Longint): TDateTime;
const
// Sets UnixStartDate to TDateTime of 01/01/1970
UnixStartDate: TDateTime = 25569.0;
begin
Result := (USec / 86400) + UnixStartDate;
end;
``` | That is the [unix timestamp](http://en.wikipedia.org/wiki/Unix_time) for Fri, 29 Apr 2011 11:42:31 GMT.
**Edit**
According to [IBS](http://ibs.sourceforge.net/documentation.html#introduction), it uses postgresql as its backend database. You should be able to convert it using [to\_timestamp](http://www.postgresql.org/docs/8.4/interactive/functions-formatting.html). |
39,190,714 | Sorry if this has already been answered using terminology I don't know to search for.
I have one project:
```
project1/
class1.py
class2.py
```
Where `class2` imports some things from `class1`, but each has its own `if __name__ == '__main__'` that uses their respective classes I run frequently. But then, I have a second project which creates a subclass of each of the classes from `project1`. So I would like `project1` to be a package, so that I can import it into `project2` nicely:
```
project2/
project1/
__init__.py
class1.py
class2.py
subclass1.py
subclass2.py
```
However, I'm having trouble with the importing with this. If I make `project1` a package then inside `class2.py` I would want to import `class1.py` code using `from project1.class1 import class1`. This makes `project2` code run correctly. But now when I'm trying to use `project1` not as a package, but just running code from directly within that directory, the `project1` code fails (since it doesn't know what `project1` is). If I set it up for `project1` to work directly within that directory (i.e. the import in `class2` is `from class1 import Class1`), then this import fails when trying to use `project1` as a package from `project2`.
Is there a way to have it both ways (use `project1` both as a package and not as a package)? If there is a way, is it a discouraged way and I should be restructuring my code anyway? Other suggestions on how I should be handling this? Thanks!
**EDIT**
Just to clarify, the problem arrises because `subclass2` imports `class2` which in turn imports `class1`. Depending on which way `class2` imports `class1` the import will fail from `project2` or from `project1` because one sees `project1` as a package while the other sees it as the working directory.
**EDIT 2**
I'm using Python 3.5. Apparently this works in Python 2, but not in my current version of python. | 2016/08/28 | [
"https://Stackoverflow.com/questions/39190714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191812/"
] | EDIT 2: Added code to class2.py to attach the parent directory to the PYTHONPATH to comply with how Python3 module imports work.
```
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
```
Removed relative import of Class1.
Folder structure:
```
project2
- class3.py
- project1
- __init__.py
- class1.py
- class2.py
```
*project2/project1/class1.py*
```
class Class1(object):
def __init__(self):
super(Class1, self).__init__()
self.name = "DAVE!"
def printname(self):
print(self.name)
def run():
thingamy = Class1()
thingamy.printname()
if __name__ == "__main__":
run()
```
*project2/project1/class2.py*
```
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from class1 import Class1
class Class2(Class1):
def childMethod(self):
print('Calling child method')
def run():
thingamy = Class2()
thingamy.printname()
thingamy.childMethod()
if __name__ == "__main__":
run()
```
*project2/class3.py*
```
from project1.class2 import Class2
from project1.class1 import Class1
class Class3(Class2):
def anotherChildMethod(self):
print('Calling another child method')
def run():
thingamy = Class3()
thingamy.printname()
thingamy.anotherChildMethod()
if __name__ == "__main__":
run()
```
With this setup each of class1, 2 and 3 can be run as standalone scripts. | You could run `class2.py` from inside the `project2` folder, i.e. with the current working directory set to the `project2` folder:
```
user@host:.../project2$ python project1/class2.py
```
On windows that would look like this:
```
C:\...project2> python project1/class2.py
```
Alternatively you could modify the python path inside of `class2.py`:
```
import sys
sys.path.append(".../project2")
from project1.class1 import class1
```
Or modify the `PYTHONPATH` environment variable similarly.
To be able to extend your project and import for example something in `subclass1.py` from `subclass2.py` you should consider starting the import paths always with `project2`, for example in `class2.py`:
```
from project2.project1.class1 import class1
```
Ofcourse you would need to adjust the methods I just showed to match the new path. |
63,994,247 | I'm new to Docker. I'm trying to create a dockerfile which basically sets kubectl (Kubernetes client), helm 3 and Python 3.7. I used:
```
FROM python:3.7-alpine
COPY ./ /usr/src/app/
WORKDIR /usr/src/app
```
Now I'm trying to figure out how to add `kubectl` and `helm`. What would be the best way to install those two? | 2020/09/21 | [
"https://Stackoverflow.com/questions/63994247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808098/"
] | Working Dockerfile. This will install the latest and stable versions of `kubectl` and `helm-3`
```
FROM python:3.7-alpine
COPY ./ /usr/src/app/
WORKDIR /usr/src/app
RUN apk add curl openssl bash --no-cache
RUN curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl" \
&& chmod +x ./kubectl \
&& mv ./kubectl /usr/local/bin/kubectl \
&& curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 \
&& chmod +x get_helm.sh && ./get_helm.sh
``` | Python should be available from a python base image I guess.
My take would be s.th like
```
ENV K8S_VERSION=v1.18.X
ENV HELM_VERSION=v3.X.Y
ENV HELM_FILENAME=helm-${HELM_VERSION}-linux-amd64.tar.gz
```
and then in the Dockerfile
```
RUN curl -L https://storage.googleapis.com/kubernetes-release/release/${K8S_VERSION}/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl \
&& curl -L https://storage.googleapis.com/kubernetes-helm/${HELM_FILENAME} | tar xz && mv linux-amd64/helm /bin/helm && rm -rf linux-amd64
```
But be aware of the availability of curl or wget in the baseimage, maybe these or other tools and programs have to be installed before you can use it in the Dockerfile. This always depends on the baseimage used |
61,856,478 | I'm developing a python script to deploy an Azure Function App. For this reason I can't use another Python version to make this easier.
In azure portal I get this error:
[Azure Function app pyarrow module not found](https://i.stack.imgur.com/QM50w.png)
When I try to install it via VS Code with pip I get this error: [Error installing Pyarrow](https://i.stack.imgur.com/Hv7dV.png)
I managed to make this work using anaconda environment but since my goal is to make it run in an azure function I don't know how to solve this situation.
This is my requirements.txt:
```
arrow-cpp==0.17.*
pyarrow=0.17.*
adal==1.2.2
astroid==2.3.3
attrs==19.3.0
Automat==20.2.0
azure-applicationinsights==0.1.0
azure-batch==4.1.3
azure-common==1.1.24
azure-core==1.5.0
azure-cosmosdb-nspkg==2.0.2
azure-cosmosdb-table==1.0.6
azure-eventgrid==1.3.0
azure-functions==1.2.0
azure-graphrbac==0.40.0
azure-keyvault==1.1.0
azure-loganalytics==0.1.0
azure-mgmt==4.0.0
azure-mgmt-advisor==1.0.1
azure-mgmt-applicationinsights==0.1.1
azure-mgmt-authorization==0.50.0
azure-mgmt-batch==5.0.1
azure-mgmt-batchai==2.0.0
azure-mgmt-billing==0.2.0
azure-mgmt-cdn==3.1.0
azure-mgmt-cognitiveservices==3.0.0
azure-mgmt-commerce==1.0.1
azure-mgmt-compute==4.6.2
azure-mgmt-consumption==2.0.0
azure-mgmt-containerinstance==1.5.0
azure-mgmt-containerregistry==2.8.0
azure-mgmt-containerservice==4.4.0
azure-mgmt-cosmosdb==0.4.1
azure-mgmt-datafactory==0.6.0
azure-mgmt-datalake-analytics==0.6.0
azure-mgmt-datalake-nspkg==3.0.1
azure-mgmt-datalake-store==0.5.0
azure-mgmt-datamigration==1.0.0
azure-mgmt-devspaces==0.1.0
azure-mgmt-devtestlabs==2.2.0
azure-mgmt-dns==2.1.0
azure-mgmt-eventgrid==1.0.0
azure-mgmt-eventhub==2.6.0
azure-mgmt-hanaonazure==0.1.1
azure-mgmt-iotcentral==0.1.0
azure-mgmt-iothub==0.5.0
azure-mgmt-iothubprovisioningservices==0.2.0
azure-mgmt-keyvault==1.1.0
azure-mgmt-loganalytics==0.2.0
azure-mgmt-logic==3.0.0
azure-mgmt-machinelearningcompute==0.4.1
azure-mgmt-managementgroups==0.1.0
azure-mgmt-managementpartner==0.1.1
azure-mgmt-maps==0.1.0
azure-mgmt-marketplaceordering==0.1.0
azure-mgmt-media==1.0.0
azure-mgmt-monitor==0.5.2
azure-mgmt-msi==0.2.0
azure-mgmt-network==2.7.0
azure-mgmt-notificationhubs==2.1.0
azure-mgmt-nspkg==3.0.2
azure-mgmt-policyinsights==0.1.0
azure-mgmt-powerbiembedded==2.0.0
azure-mgmt-rdbms==1.9.0
azure-mgmt-recoveryservices==0.3.0
azure-mgmt-recoveryservicesbackup==0.3.0
azure-mgmt-redis==5.0.0
azure-mgmt-relay==0.1.0
azure-mgmt-reservations==0.2.1
azure-mgmt-resource==2.2.0
azure-mgmt-scheduler==2.0.0
azure-mgmt-search==2.1.0
azure-mgmt-servicebus==0.5.3
azure-mgmt-servicefabric==0.2.0
azure-mgmt-signalr==0.1.1
azure-mgmt-sql==0.9.1
azure-mgmt-storage==2.0.0
azure-mgmt-subscription==0.2.0
azure-mgmt-trafficmanager==0.50.0
azure-mgmt-web==0.35.0
azure-nspkg==3.0.2
azure-servicebus==0.21.1
azure-servicefabric==6.3.0.0
azure-servicemanagement-legacy==0.20.6
azure-storage==0.36.0
azure-storage-blob==12.3.1
azure-storage-common==1.4.2
azure-storage-file==1.4.0
azure-storage-file-datalake==12.0.1
azure-storage-queue==1.4.0
beautifulsoup4==4.8.1
bs4==0.0.1
certifi==2019.11.28
cffi==1.14.0
chardet==3.0.4
colorama==0.4.3
constantly==15.1.0
cryptography==2.8
cssselect==1.1.0
hyperlink==19.0.0
idna==2.7
incremental==17.5.0
isodate==0.6.0
isort==4.3.21
lazy-object-proxy==1.4.3
llvmlite==0.32.0
lxml==4.5.0
mccabe==0.6.1
msrest==0.6.11
msrestazure==0.6.2
numba==0.49.0
numpy==1.18.1
oauthlib==3.1.0
pandas==1.0.1
parsel==1.5.2
Protego==0.1.16
proxyscrape==0.3.0
pycparser==2.19
PyHamcrest==2.0.1
PyJWT==1.7.1
pylint==2.4.4
pyOpenSSL==19.1.0
python-dateutil==2.8.1
pytz==2019.3
requests==2.23.0
requests-oauthlib==1.3.0
six==1.14.0
soupsieve==1.9.5
thrift==0.13.0
urllib3==1.23
w3lib==1.21.0
wrapt==1.11.2
zope.interface==4.7.1
``` | 2020/05/17 | [
"https://Stackoverflow.com/questions/61856478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13562280/"
] | As you use `conda` as the package manager, you should also use it to install `pyarrow` and `arrow-cpp` using it. In your above output VSCode uses `pip` for the package management. You should consider reporting this as a bug to VSCode. Your current environment is detected as `venv` and not as `conda` environment as you can see in the Python environment box in the lower left.
The best workaround for now is to go to the terminal and manually type in `conda install pyarrow=0.17 arrow-cpp=0.17`. Note that you don't actually need to supply `0.17.*` as `conda` automatically expands `0.17` to `0.17.*`. | Thank you for your answer.
In fact, I think I can't change the environment because this `venv` is actually the environment used by Azure Functions. Is there any way I can use `conda` installed packages in the azure function |
36,465,337 | I am using a Dymo USB scale with PyUSB and everything is really great apart from the scale's automatic shutdown after three minutes. I would like to keep it running as long as my python program is running. Is there any way to do this using python?
I am new to PyUSB and have followed this tutorial successfully so far: <http://steventsnyder.com/reading-a-dymo-usb-scale-using-python/>.
The auto shutdown can be disabled manually as said here:
<http://www.manualslib.com/manual/472133/Dymo-S100.html?page=7>
but this must be performed every single time which is a problem.
Many thanks in advance for any suggestions! | 2016/04/07 | [
"https://Stackoverflow.com/questions/36465337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4083055/"
] | As Ignacio said, there doesn't seem to be any computing way to do this. We eventually managed to stop the automatic shutdown by wiring a timer directly to the button which changes the units mode from grams to ounces. "Pressing" this every few seconds prevents the shutdown, and a little bit of extra coding allows for reading the mass from either mode correctly.
Not as simple a solution as I'd hoped for, but perhaps the idea will help anyone with a weirdly-specific problem similar to this. | Here is a hardware description to open/modify and code to toggle the scale button of DYMO (to avoid auto-shutdown)
<https://learn.adafruit.com/data-logging-iot-weight-scale/code-walkthrough> |
16,114,358 | is there a way to trace all the calls made by a web page when loading it? Say for example I went in a video watching site, I would like to trace all the GET calls recursively until I find an mp4/flv file. I know a way to do that would be to follow the URLs recursively, but this solution is not always suitable and quite limitative( say there's a few thousand links, or the links are in a file which can't be read). Is there a way to do this? Ideally, the implementation could be in python, but PHP as well as C is fine too | 2013/04/19 | [
"https://Stackoverflow.com/questions/16114358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300843/"
] | The following code may be what you are looking for. The object should flash for the total amount of `time` changing its color after `intervalTime`
```
using UnityEngine;
using System.Collections;
public class FlashingObject : MonoBehaviour {
private Material mat;
private Color[] colors = {Color.yellow, Color.red};
public void Awake()
{
mat = GetComponent<MeshRenderer>().material;
}
// Use this for initialization
void Start () {
StartCoroutine(Flash(5f, 0.05f));
}
IEnumerator Flash(float time, float intervalTime)
{
float elapsedTime = 0f;
int index = 0;
while(elapsedTime < time )
{
mat.color = colors[index % 2];
elapsedTime += Time.deltaTime;
index++;
yield return new WaitForSeconds(intervalTime);
}
}
}
``` | The answer above is great, but it does not stop flashing, because it takes far too long for the float to reach 5f.
The trick is to set the first parameter in the **Flash** function to something smaller, like 1f, instead of 5f. Take this script, and attach it to any game object. It will flash between yellow and red for about 2.5 seconds, then stop.
```
using UnityEngine;
using System.Collections;
public class FlashingObject : MonoBehaviour
{
private Material _mat;
private Color[] _colors = { Color.yellow, Color.red };
private float _flashSpeed = 0.1f;
private float _lengthOfTimeToFlash = 1f;
public void Awake()
{
this._mat = GetComponent<MeshRenderer>().material;
}
// Use this for initialization
void Start()
{
StartCoroutine(Flash(this._lengthOfTimeToFlash, this._flashSpeed));
}
IEnumerator Flash(float time, float intervalTime)
{
float elapsedTime = 0f;
int index = 0;
while (elapsedTime < time)
{
_mat.color = _colors[index % 2];
elapsedTime += Time.deltaTime;
index++;
yield return new WaitForSeconds(intervalTime);
}
}
}
``` |
64,354,599 | What is the best way to create software client (service) that installs and then runs in the background. When you turn on the device (where the service is installed), this service will automatically send network availability information of device to web server. On web server will be only state of devices on network. (on/off)
So what is the optimal solution for create software client? Using powershell, python or other?
Do you have anyone experience with similar problem? | 2020/10/14 | [
"https://Stackoverflow.com/questions/64354599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14449220/"
] | Use
```
(?m)^<hr>\r?\nBitmap:[\s\S]*?(?=^<hr>$|\Z)
```
See [proof](https://regex101.com/r/i64K0W/4).
**Explanation**
```
--------------------------------------------------------------------------------
(?m) set flags for this block (with ^ and $
matching start and end of line) (case-
sensitive) (with . not matching \n)
(matching whitespace and # normally)
--------------------------------------------------------------------------------
^ the beginning of a "line"
--------------------------------------------------------------------------------
<hr> '<hr>'
--------------------------------------------------------------------------------
\r? '\r' (carriage return) (optional (matching
the most amount possible))
--------------------------------------------------------------------------------
\n '\n' (newline)
--------------------------------------------------------------------------------
Bitmap: 'Bitmap:'
--------------------------------------------------------------------------------
[\s\S]*? any character of: whitespace (\n, \r, \t,
\f, and " "), non-whitespace (all but \n,
\r, \t, \f, and " ") (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
^ the beginning of a "line"
--------------------------------------------------------------------------------
<hr> '<hr>'
--------------------------------------------------------------------------------
$ before an optional \n, and the end of a
"line"
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\Z the end of the string
--------------------------------------------------------------------------------
) end of look-ahead
``` | This works: `<hr>\nBitmap:.*\n(?:.*\n){1,2}`
See: <https://regex101.com/r/i64K0W/3>
The problem in your regex was the `*`, which is greedy. |
60,907,340 | Try to open file that exists with visual Studio Code 1.43.2
This is the py file:
```
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
```
This is the result:
```
PS C:\Users\Osori> & C:/Python/Python38-32/python.exe "c:/Users/Osori/Desktop/python_work/9_files and exceptions/file_reader.py"
Traceback (most recent call last):
File "c:/Users/Osori/Desktop/python_work/9_files and exceptions/file_reader.py", line 1, in <module>
with open('pi_digits.txt') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
```

The files exists and the spelling is correct. if the file\_reader.py is run with IDLE runs just fine.
 | 2020/03/28 | [
"https://Stackoverflow.com/questions/60907340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143836/"
] | Below is for BigQuery Standard SQL
```
#standardSQL
SELECT *,
COUNTIF(New_Session_Flag = 1) OVER(PARTITION BY Fullvisitorid ORDER BY Visitid) Rank_Session_Order
FROM `project.dataset.table`
``` | The answer by Mikhail Berlyant using a conditional window count is corret and works. I am answering because I find that a window sum is even simpler (and possibly more efficient on a large dataset):
```
select
t.*,
sum(new_session_flag) over(partition by fullvisitorid order by visid_id) rank_session_order
from mytable t
```
This works because the `new_session_flag` contains `0`s and `1`s only; so counting the `1`s is actually equivalent to suming all values. |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | If you want to ensure pip installed for python 3.7, try something like this:
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.7 get-pip.py
``` | Maybe you're using an older version of Brew?
In that case run
brew postinstall python3 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Maybe you're using an older version of Brew?
In that case run
brew postinstall python3 | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/local/bin|grep pip
lrwxr-xr-x 1 abhinav admin 33 May 8 03:32 pip3.6 -> ../Cellar/python/3.6.5/bin/pip3.6
lrwxr-xr-x 1 abhinav admin 31 May 8 03:32 pip3 -> ../Cellar/python/3.6.5/bin/pip3
lrwxr-xr-x 1 abhinav admin 36 May 8 03:32 pip2.7 -> ../Cellar/python@2/2.7.15/bin/pip2.7
lrwxr-xr-x 1 abhinav admin 34 May 8 03:32 pip2 -> ../Cellar/python@2/2.7.15/bin/pip2
```
Now if I do
```
pip2 --version
pip 18.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)
pip3 --version
pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip (python 3.6)
```
As you can see in the above output, the path shown to you is dependent on where the executable is pointing.
So make sure your `pip` is not pointing to python 2.7 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Ok, so I still don't quite understand what's going on with pip3 in my device, but I found a way to install packages with pip in the right Python version:
```
python3 -m pip install [package]
```
It worked to install numpy which was my primary objective. | Maybe you're using an older version of Brew?
In that case run
brew postinstall python3 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | If you want to ensure pip installed for python 3.7, try something like this:
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.7 get-pip.py
``` | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/local/bin|grep pip
lrwxr-xr-x 1 abhinav admin 33 May 8 03:32 pip3.6 -> ../Cellar/python/3.6.5/bin/pip3.6
lrwxr-xr-x 1 abhinav admin 31 May 8 03:32 pip3 -> ../Cellar/python/3.6.5/bin/pip3
lrwxr-xr-x 1 abhinav admin 36 May 8 03:32 pip2.7 -> ../Cellar/python@2/2.7.15/bin/pip2.7
lrwxr-xr-x 1 abhinav admin 34 May 8 03:32 pip2 -> ../Cellar/python@2/2.7.15/bin/pip2
```
Now if I do
```
pip2 --version
pip 18.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)
pip3 --version
pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip (python 3.6)
```
As you can see in the above output, the path shown to you is dependent on where the executable is pointing.
So make sure your `pip` is not pointing to python 2.7 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | If you want to ensure pip installed for python 3.7, try something like this:
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.7 get-pip.py
``` | For python 3.x, the command is `pip3` |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | For python 3.x, the command is `pip3` | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/local/bin|grep pip
lrwxr-xr-x 1 abhinav admin 33 May 8 03:32 pip3.6 -> ../Cellar/python/3.6.5/bin/pip3.6
lrwxr-xr-x 1 abhinav admin 31 May 8 03:32 pip3 -> ../Cellar/python/3.6.5/bin/pip3
lrwxr-xr-x 1 abhinav admin 36 May 8 03:32 pip2.7 -> ../Cellar/python@2/2.7.15/bin/pip2.7
lrwxr-xr-x 1 abhinav admin 34 May 8 03:32 pip2 -> ../Cellar/python@2/2.7.15/bin/pip2
```
Now if I do
```
pip2 --version
pip 18.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)
pip3 --version
pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip (python 3.6)
```
As you can see in the above output, the path shown to you is dependent on where the executable is pointing.
So make sure your `pip` is not pointing to python 2.7 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Ok, so I still don't quite understand what's going on with pip3 in my device, but I found a way to install packages with pip in the right Python version:
```
python3 -m pip install [package]
```
It worked to install numpy which was my primary objective. | I think you should be using `pip3 --version` instead of `pip --version`,provided `pip3` was installed successfully.
Check all versions of `pip` installed on your machine using `ls -ltr /usr/local/bin|grep pip`
Then use the correct executable to query the version.
For example on my machine I get:
```
ls -ltr /usr/local/bin|grep pip
lrwxr-xr-x 1 abhinav admin 33 May 8 03:32 pip3.6 -> ../Cellar/python/3.6.5/bin/pip3.6
lrwxr-xr-x 1 abhinav admin 31 May 8 03:32 pip3 -> ../Cellar/python/3.6.5/bin/pip3
lrwxr-xr-x 1 abhinav admin 36 May 8 03:32 pip2.7 -> ../Cellar/python@2/2.7.15/bin/pip2.7
lrwxr-xr-x 1 abhinav admin 34 May 8 03:32 pip2 -> ../Cellar/python@2/2.7.15/bin/pip2
```
Now if I do
```
pip2 --version
pip 18.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)
pip3 --version
pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip (python 3.6)
```
As you can see in the above output, the path shown to you is dependent on where the executable is pointing.
So make sure your `pip` is not pointing to python 2.7 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not in the python 3.7.
Currently when I call
```
pip --version
```
I get
```
pip 18.1 from /Library/Python/2.7/site-packages/pip (python 2.7)
```
And pip3 seems not to exist.
How can I get pip3 installed in the python 3.7 folder? Thanks! | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | Ok, so I still don't quite understand what's going on with pip3 in my device, but I found a way to install packages with pip in the right Python version:
```
python3 -m pip install [package]
```
It worked to install numpy which was my primary objective. | For python 3.x, the command is `pip3` |
40,219,946 | I have a large data set (millions of rows) in memory, in the form of **numpy arrays** and **dictionaries**.
Once this data is constructed I want to store them into files;
so, later I can load these files into memory quickly, without reconstructing this data from the scratch once again.
**np.save** and **np.load** functions does the job smoothly for numpy arrays.
But I am facing problems with dict objects.
See below sample. d2 is the dictionary which was loaded from the file. **See #out[28] it has been loaded into d2 as a numpy array, not as a dict.** So further dict operations such as get are not working.
Is there a way to load the data from the file as dict (instead of numpy array) ?
```
In [25]: d1={'key1':[5,10], 'key2':[50,100]}
In [26]: np.save("d1.npy", d1)
In [27]: d2=np.load("d1.npy")
In [28]: d2
Out[28]: array({'key2': [50, 100], 'key1': [5, 10]}, dtype=object)
In [30]: d1.get('key1') #original dict before saving into file
Out[30]: [5, 10]
In [31]: d2.get('key2') #dictionary loaded from the file
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-31-23e02e45bf22> in <module>()
----> 1 d2.get('key2')
AttributeError: 'numpy.ndarray' object has no attribute 'get'
``` | 2016/10/24 | [
"https://Stackoverflow.com/questions/40219946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2101900/"
] | It's a structured array. Use `d2.item()` to retrieve the actual dict object first:
```
import numpy as np
d1={'key1':[5,10], 'key2':[50,100]}
np.save("d1.npy", d1)
d2=np.load("d1.npy")
print d1.get('key1')
print d2.item().get('key2')
```
result:
```
[5, 10]
[50, 100]
``` | [pickle](https://docs.python.org/3/library/pickle.html) module can be used. Example code:
```
from six.moves import cPickle as pickle #for performance
from __future__ import print_function
import numpy as np
def save_dict(di_, filename_):
with open(filename_, 'wb') as f:
pickle.dump(di_, f)
def load_dict(filename_):
with open(filename_, 'rb') as f:
ret_di = pickle.load(f)
return ret_di
if __name__ == '__main__':
g_data = {
'm':np.random.rand(4,4),
'n':np.random.rand(2,2,2)
}
save_dict(g_data, './data.pkl')
g_data2 = load_dict('./data.pkl')
print(g_data['m'] == g_data2['m'])
print(g_data['n'] == g_data2['n'])
```
You may also save multiple python objects in a single pickled file. Each `pickle.load` call will load a single object in that case. |
44,696,676 | Once I have installed miniconda, I am permanently inside the root miniconda environment eg:
```
luc@montblanc:~$ conda info --envs
# conda environments:
#
bunnies /home/luc/miniconda3/envs/bunnies
expose /home/luc/miniconda3/envs/expose
testano /home/luc/miniconda3/envs/testano
testcondaenv /home/luc/miniconda3/envs/testcondaenv
root * /home/luc/miniconda3
```
Which results on the use of this environment python3 executable:
```
luc@montblanc:~$ which python3
/home/luc/miniconda3/bin/python3
```
How can I get out of this root environment without actually uninstalling python. E.g. I want
```
luc@montblanc:~$ which python3
/usr/bin/python3
```
and refer to the miniconda distribution of python explicitly (using full path `/home/luc/miniconda3/bin/python3`) when I need it.
I don't want to achieve any final goal doing this, I just want to understand what is happening and how it works. | 2017/06/22 | [
"https://Stackoverflow.com/questions/44696676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803860/"
] | See your .bashrc file. Miniconda adds their paths and change the default, find this file and then change or add the path you want, or remove the anaconda/miniconda path.
In your .bashrc (probably ~/.bashrc) you will see something like:
```
# added by Miniconda3 4.3.14 installer
export PATH="/path/to/miniconda3/bin:$PATH"
```
Add your path after this line, change this path or, for temporarily, use `export` on command line.
**Obs.**
* After this, probably you will have to use miniconda call by full
path.
* Restart your session after changes in .bashrc. | Here is a way to do this on the fly without editing one's init files:
```
(base) ➜ ~ which python
/home/xxx/anaconda3/bin/python
(base) ➜ ~ echo $PATH
/home/xxx/anaconda3/bin:/home/xxx/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
(base) ➜ ~ export PATH=$(echo ${PATH} | awk -v RS=: -v ORS=: '/conda/ {next} {print}' | sed 's/:*$//')
(base) ➜ ~ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
(base) ➜ ~ which python
/usr/bin/python
(base) ➜ ~
``` |
44,696,676 | Once I have installed miniconda, I am permanently inside the root miniconda environment eg:
```
luc@montblanc:~$ conda info --envs
# conda environments:
#
bunnies /home/luc/miniconda3/envs/bunnies
expose /home/luc/miniconda3/envs/expose
testano /home/luc/miniconda3/envs/testano
testcondaenv /home/luc/miniconda3/envs/testcondaenv
root * /home/luc/miniconda3
```
Which results on the use of this environment python3 executable:
```
luc@montblanc:~$ which python3
/home/luc/miniconda3/bin/python3
```
How can I get out of this root environment without actually uninstalling python. E.g. I want
```
luc@montblanc:~$ which python3
/usr/bin/python3
```
and refer to the miniconda distribution of python explicitly (using full path `/home/luc/miniconda3/bin/python3`) when I need it.
I don't want to achieve any final goal doing this, I just want to understand what is happening and how it works. | 2017/06/22 | [
"https://Stackoverflow.com/questions/44696676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803860/"
] | See your .bashrc file. Miniconda adds their paths and change the default, find this file and then change or add the path you want, or remove the anaconda/miniconda path.
In your .bashrc (probably ~/.bashrc) you will see something like:
```
# added by Miniconda3 4.3.14 installer
export PATH="/path/to/miniconda3/bin:$PATH"
```
Add your path after this line, change this path or, for temporarily, use `export` on command line.
**Obs.**
* After this, probably you will have to use miniconda call by full
path.
* Restart your session after changes in .bashrc. | Or you can also just use conda deactivate. For a regular python environment, deactivate or source deactivate should work, but if you try that, you get a hint to use conda deactivate instead.
```
(base) mooreb@ubtest2:~$ deactivate
DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.
(base) mooreb@ubtest2:~$ conda deactivate
mooreb@ubtest2:~$
``` |
44,696,676 | Once I have installed miniconda, I am permanently inside the root miniconda environment eg:
```
luc@montblanc:~$ conda info --envs
# conda environments:
#
bunnies /home/luc/miniconda3/envs/bunnies
expose /home/luc/miniconda3/envs/expose
testano /home/luc/miniconda3/envs/testano
testcondaenv /home/luc/miniconda3/envs/testcondaenv
root * /home/luc/miniconda3
```
Which results on the use of this environment python3 executable:
```
luc@montblanc:~$ which python3
/home/luc/miniconda3/bin/python3
```
How can I get out of this root environment without actually uninstalling python. E.g. I want
```
luc@montblanc:~$ which python3
/usr/bin/python3
```
and refer to the miniconda distribution of python explicitly (using full path `/home/luc/miniconda3/bin/python3`) when I need it.
I don't want to achieve any final goal doing this, I just want to understand what is happening and how it works. | 2017/06/22 | [
"https://Stackoverflow.com/questions/44696676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803860/"
] | Or you can also just use conda deactivate. For a regular python environment, deactivate or source deactivate should work, but if you try that, you get a hint to use conda deactivate instead.
```
(base) mooreb@ubtest2:~$ deactivate
DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'.
(base) mooreb@ubtest2:~$ conda deactivate
mooreb@ubtest2:~$
``` | Here is a way to do this on the fly without editing one's init files:
```
(base) ➜ ~ which python
/home/xxx/anaconda3/bin/python
(base) ➜ ~ echo $PATH
/home/xxx/anaconda3/bin:/home/xxx/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
(base) ➜ ~ export PATH=$(echo ${PATH} | awk -v RS=: -v ORS=: '/conda/ {next} {print}' | sed 's/:*$//')
(base) ➜ ~ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
(base) ➜ ~ which python
/usr/bin/python
(base) ➜ ~
``` |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object has no attribute '__file__'
```
How can I get the meaning of partial (from \_functools import partial) if I can't read C code? | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is generally best (far less hard than actually productively *coding* in C;-). However, often you'll find (suggestive, non-authoritative) "sample Python implementations" of C-coded functionality, and you can study *those*.
A particularly fruitful repository of Python-coded equivalents to Python standard library functionality that's normally coded in C is the [pypy](http://codespeak.net/pypy/dist/pypy/doc/) project (which does Python implementations coded in Python) -- its sources are browseable [here](http://codespeak.net/svn/pypy/trunk/) and of course you can download and peruse them on your machine.
In particular, this is pypy's [\_functools.py](http://codespeak.net/svn/pypy/trunk/pypy/lib/_functools.py) implementation:
```
""" Supplies the internal functions for functools.py in the standard library """
class partial:
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots__ = ['func', 'args', 'keywords']
def __init__(self, func, *args, **keywords):
if not callable(func):
raise TypeError("the first argument must be callable")
self.func = func
self.args = args
self.keywords = keywords
def __call__(self, *fargs, **fkeywords):
newkeywords = self.keywords.copy()
newkeywords.update(fkeywords)
return self.func(*(self.args + fargs), **newkeywords)
```
Pretty trivial to read and understand, I hope! | please be more clear when asking questions next time. I assume you want this
```
>>> import _functools
>>> _functools.__file__
'/usr/lib/python2.6/lib-dynload/_functools.so'
``` |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object has no attribute '__file__'
```
How can I get the meaning of partial (from \_functools import partial) if I can't read C code? | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is generally best (far less hard than actually productively *coding* in C;-). However, often you'll find (suggestive, non-authoritative) "sample Python implementations" of C-coded functionality, and you can study *those*.
A particularly fruitful repository of Python-coded equivalents to Python standard library functionality that's normally coded in C is the [pypy](http://codespeak.net/pypy/dist/pypy/doc/) project (which does Python implementations coded in Python) -- its sources are browseable [here](http://codespeak.net/svn/pypy/trunk/) and of course you can download and peruse them on your machine.
In particular, this is pypy's [\_functools.py](http://codespeak.net/svn/pypy/trunk/pypy/lib/_functools.py) implementation:
```
""" Supplies the internal functions for functools.py in the standard library """
class partial:
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots__ = ['func', 'args', 'keywords']
def __init__(self, func, *args, **keywords):
if not callable(func):
raise TypeError("the first argument must be callable")
self.func = func
self.args = args
self.keywords = keywords
def __call__(self, *fargs, **fkeywords):
newkeywords = self.keywords.copy()
newkeywords.update(fkeywords)
return self.func(*(self.args + fargs), **newkeywords)
```
Pretty trivial to read and understand, I hope! | It is a shared object `_functools.so`, written in C. I guess, it is imported by the actual `functools` module. Why are you trying to import from it? Sure, it is possible, however, you can just as well `from functools import partial`. |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object has no attribute '__file__'
```
How can I get the meaning of partial (from \_functools import partial) if I can't read C code? | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is generally best (far less hard than actually productively *coding* in C;-). However, often you'll find (suggestive, non-authoritative) "sample Python implementations" of C-coded functionality, and you can study *those*.
A particularly fruitful repository of Python-coded equivalents to Python standard library functionality that's normally coded in C is the [pypy](http://codespeak.net/pypy/dist/pypy/doc/) project (which does Python implementations coded in Python) -- its sources are browseable [here](http://codespeak.net/svn/pypy/trunk/) and of course you can download and peruse them on your machine.
In particular, this is pypy's [\_functools.py](http://codespeak.net/svn/pypy/trunk/pypy/lib/_functools.py) implementation:
```
""" Supplies the internal functions for functools.py in the standard library """
class partial:
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots__ = ['func', 'args', 'keywords']
def __init__(self, func, *args, **keywords):
if not callable(func):
raise TypeError("the first argument must be callable")
self.func = func
self.args = args
self.keywords = keywords
def __call__(self, *fargs, **fkeywords):
newkeywords = self.keywords.copy()
newkeywords.update(fkeywords)
return self.func(*(self.args + fargs), **newkeywords)
```
Pretty trivial to read and understand, I hope! | For Python2.6,
The `_functools` module is a builtin. You can see that if you simply type `import _functools ; repr(_functools)` and hit enter at your interpreter prompt.
If you want to see the C source of the module, check out <http://hg.python.org/cpython/file/d7e85ddb1336/Modules/_functoolsmodule.c>
This `_functools` module doesn't have a `__file__` attribute (see next paragraph) since it's compiled into the interpreter.
For Python2.5,
The `_functools` module is a standard library module implemented in C and is available at <http://hg.python.org/cpython/file/a78381ead4cf/Modules/_functoolsmodule.c> if you want to see it. You can see the location from where the module is loaded up by typing `import _functools ; print _functools.__file__` at your interpreter prompt |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object has no attribute '__file__'
```
How can I get the meaning of partial (from \_functools import partial) if I can't read C code? | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is generally best (far less hard than actually productively *coding* in C;-). However, often you'll find (suggestive, non-authoritative) "sample Python implementations" of C-coded functionality, and you can study *those*.
A particularly fruitful repository of Python-coded equivalents to Python standard library functionality that's normally coded in C is the [pypy](http://codespeak.net/pypy/dist/pypy/doc/) project (which does Python implementations coded in Python) -- its sources are browseable [here](http://codespeak.net/svn/pypy/trunk/) and of course you can download and peruse them on your machine.
In particular, this is pypy's [\_functools.py](http://codespeak.net/svn/pypy/trunk/pypy/lib/_functools.py) implementation:
```
""" Supplies the internal functions for functools.py in the standard library """
class partial:
"""
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
"""
__slots__ = ['func', 'args', 'keywords']
def __init__(self, func, *args, **keywords):
if not callable(func):
raise TypeError("the first argument must be callable")
self.func = func
self.args = args
self.keywords = keywords
def __call__(self, *fargs, **fkeywords):
newkeywords = self.keywords.copy()
newkeywords.update(fkeywords)
return self.func(*(self.args + fargs), **newkeywords)
```
Pretty trivial to read and understand, I hope! | The behaviour of the `functools.partial()` function is described in [PEP 309](http://www.python.org/dev/peps/pep-0309/) in which it was defined. The although the actual implementations of built-ins are often in C PEP's including this one usually contain [example implementations in Python](http://www.python.org/dev/peps/pep-0309/#example-implementation).
This example code should be sufficient for you to understand the behaviour of `functools.partial()`. If there is a specific issue about the C implementation that is concerning you are going to have to read the C code. Or perhaps describe it in your question and someone might know the answer. |
9,916,367 | I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around *everything* defined in this expensive dll? That way I can add functionality, fix bugs (that CorpFUBAR won't fix), add logging, etc?
Literally, I want output that looks like this
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
public SubClass() {
this._originalSubClass = new ExpensiveAndLargeObfuscatedFoo.SubClass ();
}
public string StupidBuggyMethod(string param1,int param2) {
return _originalSubClass.StupidBuggyMethod(param1, param2);
}
}
}
```
It would have to handle custom return types as well as primitives
```
namespace easytoread {
public class SubFooClass {
private ExpensiveAndLargeObfuscatedFoo.SubFooClass _originalSubFooClass;
public SubFooClass() {
this._originalSubFooClass= new ExpensiveAndLargeObfuscatedFoo.SubFooClass ();
}
private SubFooClass(ExpensiveAndLargeObfuscatedFoo.SubFooClass orig) {
this._originalSubFooClass = orig;
}
public SubFooClass StupidBuggyMethod(string param1,int param2) {
return new SubFooClass(_originalSubFooClass.StupidBuggyMethod(param1, param2));
}
}
}
```
And so on and so forth for every single defined class.
Basically, poor mans dynamic proxy? (yay, Castle Project is awesome!)
We'd also like to rename some of our wrapper classes, but the tool doesn't need to do that.
Without renaming, we'd be able to replace the old assembly with our new generated one, change using statements and continue on like nothing happened (except the bugs were fixed!)
It just needs to examine the dll and do code generation. the generated code can even be VB.NET, or ironpython, or anything CLR.
This is a slippery slope and I'm not happy that I ended up here, but this seems to be the way to go. I looked at the Castle Project, but unless I'm mistaken that won't work for two reasons: 1) I can't rename anything (don't ask), 2) none of the assemblies methods are declared virtual or even overridable. Even if they were, there's hundreds of types I'd have to override manually, which doesn't sound fun. | 2012/03/28 | [
"https://Stackoverflow.com/questions/9916367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346272/"
] | [ReSharper](http://www.jetbrains.com/resharper/) can do much of the work for you.
You will need to declare a basic class:
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
}
}
```
Then, choose ReSharper > Edit > Generate Code (Alt+Ins), select "Delegating Members", select all, and let it generate the code.
It won't wrap return values with custom classes (it will return the original type), so that would still have to be added manually. | 1. If you have access to the source code, rename and fix in the source
code.
2. If you don't have access (and you can do it legally) use some
tool like Reflector or [dotPeek](http://www.jetbrains.com/decompiler/) to get the source code and then,
goto to the first point. |
9,916,367 | I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around *everything* defined in this expensive dll? That way I can add functionality, fix bugs (that CorpFUBAR won't fix), add logging, etc?
Literally, I want output that looks like this
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
public SubClass() {
this._originalSubClass = new ExpensiveAndLargeObfuscatedFoo.SubClass ();
}
public string StupidBuggyMethod(string param1,int param2) {
return _originalSubClass.StupidBuggyMethod(param1, param2);
}
}
}
```
It would have to handle custom return types as well as primitives
```
namespace easytoread {
public class SubFooClass {
private ExpensiveAndLargeObfuscatedFoo.SubFooClass _originalSubFooClass;
public SubFooClass() {
this._originalSubFooClass= new ExpensiveAndLargeObfuscatedFoo.SubFooClass ();
}
private SubFooClass(ExpensiveAndLargeObfuscatedFoo.SubFooClass orig) {
this._originalSubFooClass = orig;
}
public SubFooClass StupidBuggyMethod(string param1,int param2) {
return new SubFooClass(_originalSubFooClass.StupidBuggyMethod(param1, param2));
}
}
}
```
And so on and so forth for every single defined class.
Basically, poor mans dynamic proxy? (yay, Castle Project is awesome!)
We'd also like to rename some of our wrapper classes, but the tool doesn't need to do that.
Without renaming, we'd be able to replace the old assembly with our new generated one, change using statements and continue on like nothing happened (except the bugs were fixed!)
It just needs to examine the dll and do code generation. the generated code can even be VB.NET, or ironpython, or anything CLR.
This is a slippery slope and I'm not happy that I ended up here, but this seems to be the way to go. I looked at the Castle Project, but unless I'm mistaken that won't work for two reasons: 1) I can't rename anything (don't ask), 2) none of the assemblies methods are declared virtual or even overridable. Even if they were, there's hundreds of types I'd have to override manually, which doesn't sound fun. | 2012/03/28 | [
"https://Stackoverflow.com/questions/9916367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346272/"
] | It seems the best answer is "There is no such tool". So, I'll be taking a stab at writing my own later as an off-hours project. If I ever get something useful working I'll github it and update here.
UPDATE
Visual Studio 2012 Fakes seem to be promising. <http://msdn.microsoft.com/en-us/library/tfs/hh549175(v=vs.110).aspx> - we've moved on but I might try creating a fake and then dropping it in as a replacement dll sometime in the future | 1. If you have access to the source code, rename and fix in the source
code.
2. If you don't have access (and you can do it legally) use some
tool like Reflector or [dotPeek](http://www.jetbrains.com/decompiler/) to get the source code and then,
goto to the first point. |
9,916,367 | I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around *everything* defined in this expensive dll? That way I can add functionality, fix bugs (that CorpFUBAR won't fix), add logging, etc?
Literally, I want output that looks like this
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
public SubClass() {
this._originalSubClass = new ExpensiveAndLargeObfuscatedFoo.SubClass ();
}
public string StupidBuggyMethod(string param1,int param2) {
return _originalSubClass.StupidBuggyMethod(param1, param2);
}
}
}
```
It would have to handle custom return types as well as primitives
```
namespace easytoread {
public class SubFooClass {
private ExpensiveAndLargeObfuscatedFoo.SubFooClass _originalSubFooClass;
public SubFooClass() {
this._originalSubFooClass= new ExpensiveAndLargeObfuscatedFoo.SubFooClass ();
}
private SubFooClass(ExpensiveAndLargeObfuscatedFoo.SubFooClass orig) {
this._originalSubFooClass = orig;
}
public SubFooClass StupidBuggyMethod(string param1,int param2) {
return new SubFooClass(_originalSubFooClass.StupidBuggyMethod(param1, param2));
}
}
}
```
And so on and so forth for every single defined class.
Basically, poor mans dynamic proxy? (yay, Castle Project is awesome!)
We'd also like to rename some of our wrapper classes, but the tool doesn't need to do that.
Without renaming, we'd be able to replace the old assembly with our new generated one, change using statements and continue on like nothing happened (except the bugs were fixed!)
It just needs to examine the dll and do code generation. the generated code can even be VB.NET, or ironpython, or anything CLR.
This is a slippery slope and I'm not happy that I ended up here, but this seems to be the way to go. I looked at the Castle Project, but unless I'm mistaken that won't work for two reasons: 1) I can't rename anything (don't ask), 2) none of the assemblies methods are declared virtual or even overridable. Even if they were, there's hundreds of types I'd have to override manually, which doesn't sound fun. | 2012/03/28 | [
"https://Stackoverflow.com/questions/9916367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346272/"
] | It seems the best answer is "There is no such tool". So, I'll be taking a stab at writing my own later as an off-hours project. If I ever get something useful working I'll github it and update here.
UPDATE
Visual Studio 2012 Fakes seem to be promising. <http://msdn.microsoft.com/en-us/library/tfs/hh549175(v=vs.110).aspx> - we've moved on but I might try creating a fake and then dropping it in as a replacement dll sometime in the future | [ReSharper](http://www.jetbrains.com/resharper/) can do much of the work for you.
You will need to declare a basic class:
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
}
}
```
Then, choose ReSharper > Edit > Generate Code (Alt+Ins), select "Delegating Members", select all, and let it generate the code.
It won't wrap return values with custom classes (it will return the original type), so that would still have to be added manually. |
40,254,007 | I am looking for a way to store multiple values for each key (just like we can in python using dictionary) using Go.
Is there a way this can be achieved in Go? | 2016/10/26 | [
"https://Stackoverflow.com/questions/40254007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902984/"
] | Based on your response in comments I would suggest something like the following using a struct (though if you are only interested in a single value like `name` for each item in your slice then you could just use a `map[int][]string{}`
```
type Thing struct {
name string
age int
}
myMap := map[int][]Thing{}
```
If you want to add things then you just do...
```
myMap[100] = append(myMap[100], Thing{"sberry": 37})
```
Or if you want to create it in place:
```
myMap := map[int][]Thing{
100: []Thing{Thing{"sberry", 37}},
2: []Thing{Thing{"johndoe", 22}},
}
```
**EDIT:** Adding a "nameIn" function based on comments as demo:
```
func nameIn(things []Thing, name string) bool {
for _, thing := range things {
if thing.name == name {
return true
}
}
return false
}
if nameIn(myMap[100], "John") {
...
```
If the slices are really big and speed is concern then you could keep a reverse lookup map like `map[string]int` where an entry would be `John: 100`, but you will need to most likely use some user defined functions to do your map modifications so it can change the reverse lookup as well. This also limits you by requiring unique names.
Most likely the `nameIn` would work just fine. | In go, the key/value collection is called a `map`. You create it with `myMap := map[keyType]valType{}`
Usually something like `mapA := map[string]int{}`. If you want to store multiple values per key, perhaps something like:
`mapB := map[string][]string{}` where each element is itself a slice of strings. You can then add members with something like:
`mapB["foo"] = append(mapB["foo"], "fizzbuzz")`
For a great read see [Go maps in action](https://blog.golang.org/go-maps-in-action) |
61,496,129 | I need to run selenium-side-runner in docker.I wrote in the dockerfile to install Google Chrome and googledrive. But when the code is executed, the error is as follows:
```
WebDriverError: unknown error: Chrome failed to start: exited abnormally.
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
at Object.throwDecodedError (../../usr/lib/node_modules/selenium-side-runner/node_modules/selenium-webdriver/lib/error.js:550:15)
at parseHttpResponse (../../usr/lib/node_modules/selenium-side-runner/node_modules/selenium-webdriver/lib/http.js:560:13)
at Executor.execute (../../usr/lib/node_modules/selenium-side-runner/node_modules/selenium-webdriver/lib/http.js:486:26)
```
this is my dockerfile
```
FROM python:3.6-stretch
# install google chrome
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >>
/etc/apt/sources.list.d/google-chrome.list'
RUN apt-get -y update
RUN apt-get install -y google-chrome-stable
# install chromedriver
RUN apt-get install -yqq unzip
RUN wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS
chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip
RUN unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/
# set display port to avoid crash
ENV DISPLAY=:99
RUN apt-get update
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash
RUN apt-get install -y nodejs
RUN apt-get install -y npm
RUN npm install -g selenium-side-runner
WORKDIR /app
ENTRYPOINT ["/entrypoint.sh"]
```
this is my code:
```
for ind, file in enumerate(test_file_list):
file_path = os.path.join(self.save_path, file)
start_time = timezone.now()
result = subprocess.run(
['selenium-side-runner', '-c', "goog:chromeOptions.args=[--headless,--nogpu]
browserName=chrome",file_path])
end_time = timezone.now()
result_code = result.returncode
``` | 2020/04/29 | [
"https://Stackoverflow.com/questions/61496129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13054579/"
] | A hack
======
Instead of installing a browser by hand, I would recommend using already available images like <https://github.com/SeleniumHQ/docker-selenium>.
A solution (recommended)
========================
From an architectural point of view, each Docker container should have only one purpose. In your case, the container is responsible for running a browser and tests. That's why I propose to split the solution into two containers:
* the first container with `selenium-side-runner` and `.side` files that will run tests
* the second container runs a browser
Based on [the docs](https://www.seleniumhq.org/selenium-ide/docs/en/introduction/command-line-runner/#running-on-selenium-grid), `selenium-side-runner` can work with a Selenium Grid.
So, the solution will look like
1. Prepare `Dockerfile` that installs `selenium-side-runner`, adds `.side` files, and configures an `ENTRYPOINT`. Here you can also set a default URL to Selenium Grid like `selenium-side-runner -w 10 --server http://selenium-browsers:4444/wd/hub` where `selenium-browsers` will be a name of the container with a browser or Selenium Grid.
2. Build your custom Docker image
3. Create Docker network with `docker network create selenium-tests`
4. Run a browser or Selenium Grid
* Option 1: a browser. `docker run -id --shm-size=2g --network selenium-tests --name selenium-browsers selenium/standalone-chrome:3.141.59-2020040` based on [SeleniumHQ/docker-selenium](https://github.com/SeleniumHQ/docker-selenium#running-the-images)
* Option 2: Selenium Grid. [SeleniumHQ/docker-selenium](https://github.com/SeleniumHQ/docker-selenium) provides instructions how to do this. Also, you may look at [Zalenium](https://opensource.zalando.com/zalenium/) or [Selenoid](https://aerokube.com/selenoid/latest/) that provide additional features as video recordings, test execution preview, etc.
5. Run your container with `docker run -it --network selenium-tests --name my-tests <your custom image>`
As both containers are in the same custom network `selenium-tests`, both containers can communicate through the container names. So, `my-tests` container can send the requests to `selenium-browsers` container (see #1 and `--server` option).
If needed, you can create [docker-compose.yaml](https://docs.docker.com/compose/compose-file/) file later to simplify the usage of the solution. | You could use [this project](https://github.com/nixel2007/docker-selenium-side-runner), put your .side files in side directory and run `docker-composer up` |
40,314,960 | I have a csv file with columns id, name, address, phone. I want to read each row such that I store the data in two variables, `key` and `data`, where data contains name, address and phone. I want to do this because I want to append another column country in each row in a new csv. Can anyone help me with the code in python. I tried this but it didn't work:
```
dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
key, *data = row
dict[key] = ','.join(data)
``` | 2016/10/29 | [
"https://Stackoverflow.com/questions/40314960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2433565/"
] | `key, *data = row` is Python 3 syntax. For Python 2 you can do this:
```
key, data = row[0], row[1:]
``` | You can try the code below. I have put two option one is to make a list for each row, and other is comma separated. Based on the usage you can use either one.
```
import csv
dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
data = []
print row
key,data = row[0],row[1:]
dict[key] = data
# dict[key] = ','.join(data)
print dict
``` |
38,290,965 | I am a beginner in Python.
I use Python 2.7 with ElementTree to parse XML files.
I have a big XML file (~700 MB), which contains multiple root instances, for example:
```
<?xml version="1.0" ?> <foo> <bar> <sometag> Mehdi </sometag> <someothertag> blahblahblah </someothertag> . . . </bar> </foo>
<?xml version="1.0" ?> <foo> <bar> <sometag> Hamidi </sometag> <someothertag> blahblahblah </someothertag> . . . </bar> </foo>
...
...
```
each xml instance is placed in one line.
I need to parse such file in python. I used ElementTree this way:
```
import xml.etree.ElementTree as ET
tree = ET.parse('filename.xml')
root = tree.getroot()
```
but it seems it just can access to the first root XML instance line.
What is the proper way to parse all XML instances in this type of file? | 2016/07/10 | [
"https://Stackoverflow.com/questions/38290965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811059/"
] | You can try [this](https://jsfiddle.net/loginshivam/jq4c4wg7/2/)
```
<input value="0" id="id">
```
give a id to input field
on button click call a function
```
<button onclick="myFunction()">Add +10</button>
<script>
function myFunction() {
document.getElementById("id").value = parseInt(document.getElementById("id").value) +10;
}
</script>
``` | You can use a click counter like [this](https://stackoverflow.com/questions/22402777/html-javascript-button-click-counter)
and edit it replacing `+= 1` with `+= 10`.
Here my code,
```js
var input = document.getElementById("valor"),
button = document.getElementById("buttonvalue");
var clicks = 0;
button.addEventListener("click", function()
{
clicks += 10;
input.value = clicks;
});
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Script</title>
</head>
<body>
<input id="valor" value="0">
<button id="buttonvalue">10</button>
</body>
</html>
``` |
38,290,965 | I am a beginner in Python.
I use Python 2.7 with ElementTree to parse XML files.
I have a big XML file (~700 MB), which contains multiple root instances, for example:
```
<?xml version="1.0" ?> <foo> <bar> <sometag> Mehdi </sometag> <someothertag> blahblahblah </someothertag> . . . </bar> </foo>
<?xml version="1.0" ?> <foo> <bar> <sometag> Hamidi </sometag> <someothertag> blahblahblah </someothertag> . . . </bar> </foo>
...
...
```
each xml instance is placed in one line.
I need to parse such file in python. I used ElementTree this way:
```
import xml.etree.ElementTree as ET
tree = ET.parse('filename.xml')
root = tree.getroot()
```
but it seems it just can access to the first root XML instance line.
What is the proper way to parse all XML instances in this type of file? | 2016/07/10 | [
"https://Stackoverflow.com/questions/38290965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811059/"
] | Try this or [fiddleLink](http://jsfiddle.net/AyanGhatak/dpa8ctwz).
ParseInt helps in converting the string value to numbers and add them instead of concatenating. Let me know if you still have some trouble.
```js
var tag1Elem = document.getElementById("tag1");
// The callback function to increse the value.
function clickFN() {
tag1Elem.value = parseInt(tag1Elem.value, 10) + 10;
}
// Reset the value back to 0
function resetFN() {
tag1Elem.value = 0;
}
// Callbacks can be attached dynamically using addEventListener
document.getElementById("btn").addEventListener("click", clickFN);
document.getElementById("reset").addEventListener("click", resetFN);
```
```css
#wrapper {
margin: 20px;
}
```
```html
<p>This is a basic tag input:
<input id="tag1" value="0" />
<button type="button" id="btn">Add +10</button>
<button type="button" id="reset">Reset</button>
</p>
``` | You can use a click counter like [this](https://stackoverflow.com/questions/22402777/html-javascript-button-click-counter)
and edit it replacing `+= 1` with `+= 10`.
Here my code,
```js
var input = document.getElementById("valor"),
button = document.getElementById("buttonvalue");
var clicks = 0;
button.addEventListener("click", function()
{
clicks += 10;
input.value = clicks;
});
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Script</title>
</head>
<body>
<input id="valor" value="0">
<button id="buttonvalue">10</button>
</body>
</html>
``` |
61,679,525 | **Is it possible to have a variable that is defined in a python file be passed through to a html file in the same directory and used in a 'script' tag?**
Synopsis:
Im producing a flask website that pulls data from a database and uses it to create a line chart in chartjs. Flask uses jijna to manage templates. The data in the databse has been normalised so that it can be read by the chart script (label is in a list, data as a tuple). So far I have produced routes so that each page can be accessed and passed the value into the return\_template parameter as shown here:
```
@app.route('/room2')
def room2():
return render_template('room2.html', title = 'Room2', time = newLabel, count = newData )
```
with the html for the room being called along with the title which is accessed here:
```
{% if title %}
<title>Website title - {{ title }}</title>
{% else%}
<title>Website</title>
{% endif %}
```
The chart is being generated in the html file, and I want to take the data (time and count) and use it in the script the same way the title is used. However the script for chart.js doesnt take {{ }} (which is essentially a print function anyway). So far ive managed to get the data i want INTO the required html file, which is proven by the data being printed out onto the page itself but im not sure how to translate it into a variable to be used by chartjs.
Any suggestions?
(NOTE: using routes like this may be the wrong starting point but it's one that makes logical sense and hasn't produced any errors beside logical)
Files:
* data.py: Takes information from database and converts it into two variables;
```
label = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00']
data = ['4,7,2,3,9,9,5]
```
* routes.py: holds the routes to all the pages,
* layout.html: holds overarching html code for website,
* room.html: holds graph, extends from layout | 2020/05/08 | [
"https://Stackoverflow.com/questions/61679525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13486528/"
] | For beginners who try to put Flask and ChartJS together, a common approach seems to be to write Jinja code which uses loops to output Javascript, or manually uses Jinja expressions within the JS. This can quick become a maintenence nightmare.
Here's my approach which lets you define the data you want charted in Python, place a canvas in your template with some minimal JS, then dynamically update the chart using the Javascript Fetch API.
You can clone the repo [flask-chartjs](https://github.com/vulcan25/flask-chartjs/tree/0.0.1).
You can have one route which renders the page containing the chart:
```
@app.route('/')
def index():
return render_template('index.html', CHART_ENDPOINT = url_for('data'))
```
`CHART_ENDPOINT` in this case will be `/data` which corresponds to another route which returns the JSON. I also have a helper function which converts epoch times to a ISO 8601 compatible format, which works with moment.
```
import datetime as DT
def conv(epoch):
return DT.datetime.utcfromtimestamp(epoch).isoformat()
@app.route('/data')
def data():
d = {'datasets':
[
{'title': 'From Dict',
'data': [ {'x': conv(1588745371), 'y': 400},
{'x': conv(1588845371), 'y': 500},
{'x': conv(1588946171), 'y': 800} ]
},
]
}
return jsonify(d)
```
Now in the template you can place the chart's canvas element with `data-endpoint` attribute:
```
<canvas id="canvas" data-endpoint='{{CHART_ENDPOINT}}'></canvas>
```
Then I've implemented two JS functions which in that same template allow you to create the chart, and load the data from the provided endpoint:
```
<script type='text/javascript'>
var ctx = document.getElementById('canvas');
myChart = create_chart(ctx);
window.onload = function () {
load_data(myChart)
};
</script>
```
In the [`create_chart` function](https://github.com/vulcan25/flask-chartjs/blob/fe54a7278808ceca635b5ad5ab8801ea09799c32/static/flask_chart.js#L47-L58) the endpoint is obtained from the `data-endpoint` attrib, and added to the `config` object before it is assigned to that chart [(credit)](https://stackoverflow.com/a/44840756/2052575):
>
>
> ```
> config.endpoint = ctx.dataset.endpoint;
> return new Chart(ctx.getContext('2d'), config);
>
> ```
>
>
The `load_data` function then accesses the endpoint from `chart.config.endpoint` meaning it always grabs the correct data for the provided chart.
---
You can also set the [time units](https://www.chartjs.org/docs/latest/axes/cartesian/time.html#time-units) when creating the chart:
```
myChart = create_chart(ctx, 'hour') # defaults to 'day'
```
I've found this usually needs to be tweaked depending on your data range.
It would be trivial to modify that code to obtain this in the same manner as the endpoint, within the `create_chart` function. Something like `config.options.scales.xAxes[0].time.unit = ctx.datasets.unit` if the attribute was `data-unit`. This could also be done for other variables.
---
You can also pass a string from the frontend when loading data (say `dynamicChart` is another chart, created with the method above):
```
load_data(dynamicChart, 'query_string')
```
This would make `'query_string'` available in the flask function as `request.args.get('q')`
This is useful if you want to implement (for example) a text input field which sends the string to the backend, so the backend can process it somehow and return a customised dataset which is rendered on the chart. The `/dynamic` route in the repo kind of demonstrates this.
Here's what it looks like rendered:
[](https://i.stack.imgur.com/c6ABc.png)
As you can see it's possible then to have multiple charts on one page also. | You can use the same jinja templating feature to access your Variable in js too.
Maybe if you want strings you should enclose them like this `"{{variable}}"` |
19,351,060 | What is the most pythonic way to iterate a dictionary and conditionally execute a method on values.
e.g.
```
if dict_key is "some_key":
method_1(dict_keys_value)
else
method_2(dict_keys_value)
```
It can't be a dict comprehension because I am not trying to create a dictionary from the result. It is just iterating a dictionary and executing some method on values of the dictionary. | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462455/"
] | What you have is perfectly fine, and you can iterate with something like:
```
for key, value in my_dict.items(): # use `iteritems()` in Python 2.x
if key == "some_key": # use `==`, not `is`
method_1(value)
else:
method_2(value)
```
See: [`dict.items()`](http://docs.python.org/3/library/stdtypes.html#dict.items)
---
For your enlightenment, it is possible to condense that into two lines:
```
for key, value in my_dict.items():
(method_1 if key == "some_key" else method_2)(value)
```
but I don't think this gains you anything... it just makes it more confusing. I would *by far* prefer the first approach. | Why not create a dict with lambda functions?
```
methods = {
'method1': lambda val: val+1,
'method2': lambda val: val+2,
}
for key, val in dict.iteritems():
methods[key](val)
``` |
19,351,060 | What is the most pythonic way to iterate a dictionary and conditionally execute a method on values.
e.g.
```
if dict_key is "some_key":
method_1(dict_keys_value)
else
method_2(dict_keys_value)
```
It can't be a dict comprehension because I am not trying to create a dictionary from the result. It is just iterating a dictionary and executing some method on values of the dictionary. | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462455/"
] | What you have is perfectly fine, and you can iterate with something like:
```
for key, value in my_dict.items(): # use `iteritems()` in Python 2.x
if key == "some_key": # use `==`, not `is`
method_1(value)
else:
method_2(value)
```
See: [`dict.items()`](http://docs.python.org/3/library/stdtypes.html#dict.items)
---
For your enlightenment, it is possible to condense that into two lines:
```
for key, value in my_dict.items():
(method_1 if key == "some_key" else method_2)(value)
```
but I don't think this gains you anything... it just makes it more confusing. I would *by far* prefer the first approach. | One way to do this is to have a dictionary of functions to call, and then use the key to locate the actual function that you wish to call:
```
function_table = { "key_1": function_1, "key_2": function_2 }
for key, value in my_dict.items():
f = function_table .get(key, None)
if f is not None:
f(value)
```
If you have a lot of functions / keys, this makes the code a lot easier to read and maintain. |
19,351,060 | What is the most pythonic way to iterate a dictionary and conditionally execute a method on values.
e.g.
```
if dict_key is "some_key":
method_1(dict_keys_value)
else
method_2(dict_keys_value)
```
It can't be a dict comprehension because I am not trying to create a dictionary from the result. It is just iterating a dictionary and executing some method on values of the dictionary. | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462455/"
] | What you have is perfectly fine, and you can iterate with something like:
```
for key, value in my_dict.items(): # use `iteritems()` in Python 2.x
if key == "some_key": # use `==`, not `is`
method_1(value)
else:
method_2(value)
```
See: [`dict.items()`](http://docs.python.org/3/library/stdtypes.html#dict.items)
---
For your enlightenment, it is possible to condense that into two lines:
```
for key, value in my_dict.items():
(method_1 if key == "some_key" else method_2)(value)
```
but I don't think this gains you anything... it just makes it more confusing. I would *by far* prefer the first approach. | Just to complicate things, if you are always going to have two methods that you are going to call then something like this will work:
```py
# Here are my two functions
func_list=[lambda x: x*2,lambda x:x*3]
# Here is my dictionary
my_dict = {'item1':5,'item2':2}
# Now the fun part:
for key,value in my_dict.items():
funct_list[key=="item1"](value)
```
As you can see from all the answers there are plenty of ways to do this, but do yourself and anyone else who will be reading your code and keep it simple. |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TABLE "xyz_test" (
"data" text NOT NULL
)
;
```
I still tried to insert json data into that field but its giving error as :
```
ERROR: value too long for type character varying(15)
```
someone please help. Thanks in Advance. | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | In the background [JSONField actually is a TextField](https://github.com/dmkoch/django-jsonfield/blob/master/jsonfield/fields.py#L154), so that output from sqlall is not a problem, that's the expected behavior.
Further, I recreated your model and it worked just fine, both when entering the value as a string and as a python dictionary, no character limitation whatsoever. So my best guess it that the issue is a completely unrelated field that *does* have a 15 chars limit. | A JSONField data type has been added to Django for certain databases to improve handling of JSON. More info is available in this post: [Django 1.9 - JSONField in Models](https://stackoverflow.com/questions/37007109/django-1-9-jsonfield-in-models) |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TABLE "xyz_test" (
"data" text NOT NULL
)
;
```
I still tried to insert json data into that field but its giving error as :
```
ERROR: value too long for type character varying(15)
```
someone please help. Thanks in Advance. | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | In the background [JSONField actually is a TextField](https://github.com/dmkoch/django-jsonfield/blob/master/jsonfield/fields.py#L154), so that output from sqlall is not a problem, that's the expected behavior.
Further, I recreated your model and it worked just fine, both when entering the value as a string and as a python dictionary, no character limitation whatsoever. So my best guess it that the issue is a completely unrelated field that *does* have a 15 chars limit. | You can try this:
```py
from django.contrib.postgres.fields import JSONField
class Test(models.Model):
data = models.JSONField()
``` |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TABLE "xyz_test" (
"data" text NOT NULL
)
;
```
I still tried to insert json data into that field but its giving error as :
```
ERROR: value too long for type character varying(15)
```
someone please help. Thanks in Advance. | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | In the background [JSONField actually is a TextField](https://github.com/dmkoch/django-jsonfield/blob/master/jsonfield/fields.py#L154), so that output from sqlall is not a problem, that's the expected behavior.
Further, I recreated your model and it worked just fine, both when entering the value as a string and as a python dictionary, no character limitation whatsoever. So my best guess it that the issue is a completely unrelated field that *does* have a 15 chars limit. | First install `django-jsonfield` pypi package:
```
pip install django-jsonfield
```
Then simply use it:
```
from jsonfield import JSONField
class MyModel(models.Model):
custom_field = JSONField(
default=dict
)
``` |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TABLE "xyz_test" (
"data" text NOT NULL
)
;
```
I still tried to insert json data into that field but its giving error as :
```
ERROR: value too long for type character varying(15)
```
someone please help. Thanks in Advance. | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | A JSONField data type has been added to Django for certain databases to improve handling of JSON. More info is available in this post: [Django 1.9 - JSONField in Models](https://stackoverflow.com/questions/37007109/django-1-9-jsonfield-in-models) | First install `django-jsonfield` pypi package:
```
pip install django-jsonfield
```
Then simply use it:
```
from jsonfield import JSONField
class MyModel(models.Model):
custom_field = JSONField(
default=dict
)
``` |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TABLE "xyz_test" (
"data" text NOT NULL
)
;
```
I still tried to insert json data into that field but its giving error as :
```
ERROR: value too long for type character varying(15)
```
someone please help. Thanks in Advance. | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | You can try this:
```py
from django.contrib.postgres.fields import JSONField
class Test(models.Model):
data = models.JSONField()
``` | First install `django-jsonfield` pypi package:
```
pip install django-jsonfield
```
Then simply use it:
```
from jsonfield import JSONField
class MyModel(models.Model):
custom_field = JSONField(
default=dict
)
``` |
38,043,683 | I'm writing a git pre-commit hook, but it requires user input and hooks don't run in an interactive terminal. With Python I could do something like this to get access to user input:
```
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically supposed to have access to stdin.
# This hack works on MaxOS and Linux. Mileage may vary on Windows.
sys.stdin = open('/dev/tty')
result = input("Gimme some input: ")
```
What is the appropriate way to do this in Crystal? | 2016/06/26 | [
"https://Stackoverflow.com/questions/38043683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13973/"
] | You may try:
```
STDIN.reopen("/dev/tty")
``` | This seems to work:
```
file = File.open("/dev/tty")
line = file.gets
p line
```
You can't reassign STDIN and we don't have a reassignable global variable for it. I don't know much about this, maybe reopen and dup can be used for that. But otherwise you can use that `file` instead of `STDIN` in your program, I guess. |
38,043,683 | I'm writing a git pre-commit hook, but it requires user input and hooks don't run in an interactive terminal. With Python I could do something like this to get access to user input:
```
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically supposed to have access to stdin.
# This hack works on MaxOS and Linux. Mileage may vary on Windows.
sys.stdin = open('/dev/tty')
result = input("Gimme some input: ")
```
What is the appropriate way to do this in Crystal? | 2016/06/26 | [
"https://Stackoverflow.com/questions/38043683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13973/"
] | by combining @julian-portalier's answer and @asterite's we have working way to redefine stdin:
```
STDIN.reopen(File.open("/dev/tty", "a+"))
```
Which, I believe, is just [FileDescriptor#reopen](http://crystal-lang.org/api/IO/FileDescriptor.html#reopen)
`STDIN`, `STDOUT`, and `STDERR` can all be reopened this way. | This seems to work:
```
file = File.open("/dev/tty")
line = file.gets
p line
```
You can't reassign STDIN and we don't have a reassignable global variable for it. I don't know much about this, maybe reopen and dup can be used for that. But otherwise you can use that `file` instead of `STDIN` in your program, I guess. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.