qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
26,575,303 | Hello people I hope you an help me out with this problem:
I am currently implementing an interpreter for a scripting language. The language needs a native call interface to C functions, like java has JNI. My problem is, that i want to call the original C functions without writing a wrapper function, which converts the... | 2014/10/26 | [
"https://Stackoverflow.com/questions/26575303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180673/"
] | Yes we can. No FFI library needed, no restriction to C calls, only pure C++11.
```
#include <iostream>
#include <list>
#include <iostream>
#include <boost/any.hpp>
template <typename T>
auto fetch_back(T& t) -> typename std::remove_reference<decltype(t.back())>::type
{
typename std::remove_reference<decltype(t.ba... | **In pure standard C++** (or C; see [n1570](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) or [n3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) or some newer standard specification, a document written in English), **the set of functions is fixed** -so cannot change-, and given by th... |
26,575,303 | Hello people I hope you an help me out with this problem:
I am currently implementing an interpreter for a scripting language. The language needs a native call interface to C functions, like java has JNI. My problem is, that i want to call the original C functions without writing a wrapper function, which converts the... | 2014/10/26 | [
"https://Stackoverflow.com/questions/26575303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4180673/"
] | Yes we can. No FFI library needed, no restriction to C calls, only pure C++11.
```
#include <iostream>
#include <list>
#include <iostream>
#include <boost/any.hpp>
template <typename T>
auto fetch_back(T& t) -> typename std::remove_reference<decltype(t.back())>::type
{
typename std::remove_reference<decltype(t.ba... | Many ways to do this.
1. Use boost (see first answer)
2. Use std::bind. Similar to boost but more simple
3. Use C function pointer.
example
```
#define DYNAMIC(p,arg,n) {\
if(0==n) ((void (*)())p)();\
else if(1==n) ((void (*)(int))p)(arg[0]);\
else if(2==n) ((void (*)(int, int))p)(arg[0], arg[1]);\
else if(3==n) ((v... |
36,655,197 | i have problem running Django server in Intellij / Pycharm (I tried in both).
There is that red cross:
[](https://i.stack.imgur.com/ssyv5.jpg)
And this is the error i get:
[.
If you us... | Try adding `DJANGO_SETTINGS_MODULE=untitled.settings` to the environment variables listed in the configuration menu by clicking the dropdown titled 'Django' in your first photo. |
36,655,197 | i have problem running Django server in Intellij / Pycharm (I tried in both).
There is that red cross:
[](https://i.stack.imgur.com/ssyv5.jpg)
And this is the error i get:
[.
There is that red cross:
[](https://i.stack.imgur.com/ssyv5.jpg)
And this is the error i get:
[.
If you us... | Problem Analysis in IntelliJ
----------------------------
The problem is whenever you import a python project in IntelliJ. It will load as java project and adjust itself into python language without changing the project type to python. So, IntelliJ thinks you are in java project even you are running python code in it ... |
63,412,757 | I am training a variational autoencoder, using pytorch-lightning. My pytorch-lightning code works with a Weights and Biases logger. I am trying to do a parameter sweep using a W&B parameter sweep.
The hyperparameter search procedure is based on what I followed from [this repo.](https://github.com/borisdayma/lightning-... | 2020/08/14 | [
"https://Stackoverflow.com/questions/63412757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10290585/"
] | The problem is that the structure of my code and the way that I was running the wandb commands was not in the correct order. Looking at [this pytorch-ligthning](https://github.com/AyushExel/COVID19WB/blob/master/main.ipynb) with `wandb` is the correct structure to follow.
Here is my refactored code:
```
#!/usr/bin/en... | Do you launch python in your shell by typing `python` or `python3`?
Your script could be calling python 2 instead of python 3.
If this is the case, you can explicitly tell wandb to use python 3. See [this section of documentation](https://docs.wandb.com/sweeps/faq#sweep-with-custom-commands), in particular "Running Sw... |
44,737,199 | I've written a script to select certain field from a webpage using python with selenium. There is a dropdown on that page from which I want to select "All". However, i tried many different ways with my script to make it but could not.
Here is how the dropdown look like.
[)
select_obj.select_by_visible_text('All')
#option2
select_obj = Select(driver.find_element_by_id('ctl00_body_MedicineSummaryControl_cmbPageSelection'))
select_obj.... | I initially thought of suggesting that you try to tab from an element that is before the dropdown select, similar to the concept in this code:
```
driver.find_element_by_id('<id of element before the dropdown select>').send_keys(Keys.TAB)
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPa... |
44,737,199 | I've written a script to select certain field from a webpage using python with selenium. There is a dropdown on that page from which I want to select "All". However, i tried many different ways with my script to make it but could not.
Here is how the dropdown look like.
[)
select_obj.select_by_visible_text('All')
#option2
select_obj = Select(driver.find_element_by_id('ctl00_body_MedicineSummaryControl_cmbPageSelection'))
select_obj.... | Found the workaround finally. Here is what I did:
```
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pum... |
44,737,199 | I've written a script to select certain field from a webpage using python with selenium. There is a dropdown on that page from which I want to select "All". However, i tried many different ways with my script to make it but could not.
Here is how the dropdown look like.
[
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pum... | I initially thought of suggesting that you try to tab from an element that is before the dropdown select, similar to the concept in this code:
```
driver.find_element_by_id('<id of element before the dropdown select>').send_keys(Keys.TAB)
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPa... |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I st... | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.co... | As a step up to other GUI toolkits, sure. If you know other toolkits then you already understand TkInter and can leave it until you actually need it. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I st... | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | As a step up to other GUI toolkits, sure. If you know other toolkits then you already understand TkInter and can leave it until you actually need it. | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I st... | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.co... | You might want to take a look at [this(wxPython)](http://www.wxpython.org/quotes.php).
>
> wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first.
> -- Guido van Rossum
>
>
> |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I st... | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.co... | Why not go for [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? You apparently are already familiar with Qt, so it should be relatively easy to learn. In my opinion it looks better than Tkinter, and it sure is better documented. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I st... | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | The answer to your question is a resounding **yes**.
Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.co... | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I st... | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | You might want to take a look at [this(wxPython)](http://www.wxpython.org/quotes.php).
>
> wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first.
> -- Guido van Rossum
>
>
> | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
2,361,328 | I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more.
Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier.
So is it worth learning or should I st... | 2010/03/02 | [
"https://Stackoverflow.com/questions/2361328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105066/"
] | Why not go for [PyQT](http://www.riverbankcomputing.co.uk/software/pyqt/intro)? You apparently are already familiar with Qt, so it should be relatively easy to learn. In my opinion it looks better than Tkinter, and it sure is better documented. | I used Qt with C++, but decided to have a go with Tkinter with Python. I had a bit of trouble installing the latest version of Tcl/Tk, but got there eventually. I did it all with the help of [this tkdocs.com tutorial](http://www.tkdocs.com/tutorial/), which is great. |
60,144,779 | My formatting is terrible. Screenshot is here:
[](https://i.stack.imgur.com/KrTnL.png)
```py
n = int(input("enter the number of Fibonacci sequence you want. ")
n1 = 0
n2 = 1
count = 0
if n <= 0:
print("please enter a postive integer")
elif n == 1:... | 2020/02/10 | [
"https://Stackoverflow.com/questions/60144779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870387/"
] | A ')' is missing in first line i guess, that's an issue. | When such error arises, do check for the preceding line also. There are very high chances of error being in the preceding line, as in this case. There's a `)` missing in the input line. You closed 1 `)` for the input() function, but did not close for `int` constructor. |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.a... | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | there is an issue in your style code.if you remove it than works smoothly
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs... | for navigation design add these style to your code
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/s... |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.a... | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | there is an issue in your style code.if you remove it than works smoothly
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs... | ```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
... |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.a... | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | there is an issue in your style code.if you remove it than works smoothly
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs... | I want to answer simply to this question:
remove margin between slides and if you want to space between them use padding instead.
In most of the cases that we use card-like components in our front-end codes, do not use margin. |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.a... | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | ```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
... | for navigation design add these style to your code
```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/s... |
70,709,117 | i'm using this code to open edge with the defaut profile settings:
```
from msedge.selenium_tools import Edge, EdgeOptions
edge_options = EdgeOptions()
edge_options.use_chromium = True
edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default")
edge_options.a... | 2022/01/14 | [
"https://Stackoverflow.com/questions/70709117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17603014/"
] | ```html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css">
<!-- Bootstrap core CSS -->
... | I want to answer simply to this question:
remove margin between slides and if you want to space between them use padding instead.
In most of the cases that we use card-like components in our front-end codes, do not use margin. |
30,078,967 | I want to create new form view associated to new data model, I create a new menu item "menu1" that has a submenu "menus" and then, I want to customize the action view. This is my code:
**My xml file:**
**My data model:**
```python
from openerp.osv import fields, osv
class hr_cutomization(osv.osv):
_inherit = "hr.... | 2015/05/06 | [
"https://Stackoverflow.com/questions/30078967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018649/"
] | Manage to sort it out with the following.
```
Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Origin';value='*'}
Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sit... | I think your XPath expression doesn't match the node you're trying to manipulate. Try this:
```
Add-WebConfigurationProperty -PSPath $sitePath `
-Filter 'system.webServer/httpProtocol/customHeaders/add[@name="Access-Control-Allow-Origin"]' `
-Name 'value' -Value '*' -Force
``` |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ... | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | This is what you want:
```
df1.groupby('User').apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/C1B60.png)
Without the extra index:
```
df1.groupby('User', group_keys=False).apply(lambda df: df.sample(1))
```
[![enter image descri... | ```
df1_user_sample_one = df1.groupby('User').apply(lambda x:x.sample(1))
```
Using DataFrame.groupby.apply and lambda function to sample 1 |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ... | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | This is what you want:
```
df1.groupby('User').apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/C1B60.png)
Without the extra index:
```
df1.groupby('User', group_keys=False).apply(lambda df: df.sample(1))
```
[![enter image descri... | Based on number of rows per user this might be faster:
```
df.sample(frac=1).drop_duplicates(['User'])
``` |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ... | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | This is what you want:
```
df1.groupby('User').apply(lambda df: df.sample(1))
```
[](https://i.stack.imgur.com/C1B60.png)
Without the extra index:
```
df1.groupby('User', group_keys=False).apply(lambda df: df.sample(1))
```
[![enter image descri... | `.drop_duplicates` should work just fine:
```
df1.drop_duplicates(subset='User')
```
This will keep each first occurrence of a value in the column 'User' and return the respective row. |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ... | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | Based on number of rows per user this might be faster:
```
df.sample(frac=1).drop_duplicates(['User'])
``` | ```
df1_user_sample_one = df1.groupby('User').apply(lambda x:x.sample(1))
```
Using DataFrame.groupby.apply and lambda function to sample 1 |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ... | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | ```
df1_user_sample_one = df1.groupby('User').apply(lambda x:x.sample(1))
```
Using DataFrame.groupby.apply and lambda function to sample 1 | `.drop_duplicates` should work just fine:
```
df1.drop_duplicates(subset='User')
```
This will keep each first occurrence of a value in the column 'User' and return the respective row. |
38,390,242 | I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user.
My current solution seems not efficient:
```
df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'],
'B': ... | 2016/07/15 | [
"https://Stackoverflow.com/questions/38390242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358785/"
] | Based on number of rows per user this might be faster:
```
df.sample(frac=1).drop_duplicates(['User'])
``` | `.drop_duplicates` should work just fine:
```
df1.drop_duplicates(subset='User')
```
This will keep each first occurrence of a value in the column 'User' and return the respective row. |
54,727,804 | I have a generator function which reads lines from a file and parses them to objects. The files are far too large to consider processing the entire file into a list which is why I've used the generator and not a list.
I'm concerned because when calling the generator, my code will sometimes break. if it finds what it i... | 2019/02/16 | [
"https://Stackoverflow.com/questions/54727804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453851/"
] | This only releases resources promptly on CPython. To really be careful about resource release in this situation, you'd have to do something like
```
with contextlib.closing(read_massive_file(my_file)) as gen:
for entry in gen:
...
```
but I've never seen anyone do it.
---
When a generator is discarded ... | You never save the return value of `read_massive_file`; the only reference is held internally by the code generated by the `for` loop. As soon as that loop completes, the generator should be garbage collected.
It would be different if you had written
```
foo = read_massive_file(my_file):
for entry in foo:
...
els... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/... | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl res... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl res... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | In my case this was due to that I installed apache2 after the fact and then proper php mods hadn't been linked and thus activated. What you need to do:
```
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/php7.2.conf
sudo ln -s ../mods-available/php7.2.load
```
Then you just do a restart of the server by ex... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl res... | ```
sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart
```
after that
gedit /etc/apache2/apache2.conf
add the following line
**Include /etc/phpmyadmin/apache.conf**
service apache2 restart
**libapache2-mod-php server-s... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/... | If all other PHP pages are working fine, then this is probably not a PHP related issue.
Since only the phpmyadmin login page is showing php code rather than the actual login page, chances are that your **symbolic link** in your apache web root directory `/var/www/html/phpmyadmin` is referencing the phpmyadmin index fi... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | ```
sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart
```
after that
gedit /etc/apache2/apache2.conf
add the following line
**Include /etc/phpmyadmin/apache.conf**
service apache2 restart
**libapache2-mod-php server-s... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | Try this
```
sudo apt-get install libapache2-mod-php7.0
```
This installs the library for apache2 to use php7.0 | If all other PHP pages are working fine, then this is probably not a PHP related issue.
Since only the phpmyadmin login page is showing php code rather than the actual login page, chances are that your **symbolic link** in your apache web root directory `/var/www/html/phpmyadmin` is referencing the phpmyadmin index fi... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | please check below things, have found for you from some diff links:
```
1. Make sure that PHP is installed. This sounds silly, but you never
know.
2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like
LoadModule php5_module "c:/php/... | In my case this was due to that I installed apache2 after the fact and then proper php mods hadn't been linked and thus activated. What you need to do:
```
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/php7.2.conf
sudo ln -s ../mods-available/php7.2.load
```
Then you just do a restart of the server by ex... |
20,739,353 | Recently, I've found plot.ly site and am trying to use it.
But, When I use Perl API, I can't success.
My steps are same below.
1. I sign up plot.ly with google account
2. Installed Perl module(WebService::Plotly)
3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>")
..skip..
```
use WebService::Plotl... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20739353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128831/"
] | I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02.
The file `usr/share/phpmyadmin/index.php` was not interpreted.
After verifying all the manual installation I ran the following commands:
```
apt-get update
apt-get install libapache2-mod-php7.3
systemctl res... | If all other PHP pages are working fine, then this is probably not a PHP related issue.
Since only the phpmyadmin login page is showing php code rather than the actual login page, chances are that your **symbolic link** in your apache web root directory `/var/www/html/phpmyadmin` is referencing the phpmyadmin index fi... |
55,619,345 | I am making a card game in python. I used the code for a class of a stack that I found online :
```
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.insert(0,item)
def pop(self):
return self.items.pop(0)
... | 2019/04/10 | [
"https://Stackoverflow.com/questions/55619345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7193131/"
] | After declaring `Cards` to be an instance of `Stack`, you don't need to refer to `Stack` anymore. Just use `Cards`.
```
Cards = Stack()
Cards.push(15)
x = Cards.peek()
y = Cards.pop()
```
Also, the first line of code `Cards = []` is useless, as you immediately reassign `Cards` to be something else. | You shouldn't reassign `Cards` on each line. `Cards` is the `Stack` object, it needs to stay the same. It should be used as the variable with which you call all the other methods.
```
Cards = Stack()
Cards.push(15)
item = Cards.peek()
item2 = Cards.pop() # item == item2
``` |
37,738,498 | I'm running into a problem I've never encountered before, and it's frustrating the hell out of me. I'm using `rpy2` to interface with `R` from within a python script and normalize an array. For some reason, when I go to piece my output together and print to a file, it takes **ages** to print. It also slows down as it p... | 2016/06/10 | [
"https://Stackoverflow.com/questions/37738498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4438552/"
] | If I am understanding this correctly everything is running fine and with good performance up to (and including) the line:
```
normalized_matrix = np.array(Rnormalized_matrix)
```
At that line the resulting matrix is turned into a numpy array (literally - it can be even faster when avoiding to copy the data, as in <h... | For one thing, I usually use a generator to avoid the temporary list of many tiny strings.
```
out_data = "\t".join("{0:.2f}".format(piece) for piece in norm_data)
```
But it's hard to tell if this part was the slow one. |
64,334,348 | **Question:**
What is the difference between `open(<name>, "w", encoding=<encoding>)` and `open(<name>, "wb") + str.encode(<encoding>)`? They seem to (sometimes) produce different outputs.
**Context:**
While using [PyFPDF](https://pypi.org/project/fpdf/) (version 1.7.2), I subclassed the `FPDF` class, and, among... | 2020/10/13 | [
"https://Stackoverflow.com/questions/64334348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5278549/"
] | You can only have a single transaction in progress at a time with a producer instance.
If you have multiple threads doing separate processing and they all need exactly once semantics, you should have a producer instance per thread. | Not sure if this was resolved.
you can use apache common pool2 to create a producer instance pool.
In the create() method of the factory implementation you can generate and assign a unique transactionalID to avoid a conflict (ProducerFencedException) |
50,026,785 | I need to download a package using pip. I ran `pip install <package>` but got the following error:
```
[user@server ~]$ pip install sistr_cmd
Collecting sistr_cmd
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.c... | 2018/04/25 | [
"https://Stackoverflow.com/questions/50026785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8967045/"
] | ```
myzipWith :: (a->b->c) -> [a] -> [b] ->[c]
myzipWith func [] [] = []
myzipWith func (headA:restA) (headB:restB) =
[func headA headB] ++ myzipWith func restA restB
```
But note the append (`++`) isn't necessary. This would be more idiomatic (and efficient):
```
func headA headB : myzipWith func restA rest... | ```
myzipWith func (a:as) (b:bs) = [func a b] ++ (myzipWith func as bs)
```
The syntax `function (x:xs)` splits the list passed to `function` into two parts: the first element `x` and the rest of the list `xs`. |
25,296,807 | Is it possible in python to create an un-linked copy of a function? For example, if I have
```
a = lambda(x): x
b = lambda(x): a(x)+1
```
I want `b(x)` to always `return x+1`, regardless if `a(x)` is modified not. Currently, if I do
```
a = lambda(x): x
b = lambda(x): a(x)+1
print a(1.),b(1.)
a = lambda(x): x*0
pri... | 2014/08/13 | [
"https://Stackoverflow.com/questions/25296807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3939154/"
] | You could define b like this:
```
b = lambda x, a=a: a(x)+1
```
This makes `a` a parameter of `b`, and therefore a local variable. You default it to the value of `a` in the current environment, so `b` will hold onto that value. You don't need to copy `a`, just keep its current value, so that if a new value is create... | I might need to know a little more about your constraints before I can give a satisfactory answer. Why couldn't you do something like
```
a = lambda(x): x
c = a
b = lambda(x): c(x)+1
```
Then no matter what happens to `a`, `b` will stay the same. This works because of the somewhat unusual way that assignment works i... |
62,707,514 | As we all know, filling out the web forms automatically is possible using JavaScript. Basically, We find the ID of related element using Inspect (Ctrl + I) in i.e Chrome and write a javascript code in the chrome console to automate what we want to do by code.
Just like that, is it possible to automate desktop apps usi... | 2020/07/03 | [
"https://Stackoverflow.com/questions/62707514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13177703/"
] | You can do this in python using **selenium**. Selenium is an open-source testing tool, used for functional testing and also compatible with non-functional testing.
You can refer to this [link](https://www.guru99.com/selenium-python.html) to get started. | [Pywinauto](https://pywinauto.github.io/) is a GUI automation library written in pure Python and well developed for Windows GUI. |
48,949,121 | i have a python script that read from CSV file and check if the records meet the conditions.
* if yes the system display the result
* if no the system raise Exception based on the Error.
the csv file includes a filed that has **float values** but some of these records may not have any value so will be empty.
the pro... | 2018/02/23 | [
"https://Stackoverflow.com/questions/48949121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9162690/"
] | That behaviour is often caused by an updated installation of MongoDB. There is a "feature compatibility level" switch built into MongoDB which allows for updates to a newer version that do not alter (some of) the behaviour of the old version in a non-expected (oh well) way. The [documentation](https://docs.mongodb.com/... | To everyone in the same case, the solution dnickless gave works for me:
>
> In case you've upgrade from an older version try running this:
>
>
> `db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } )`
>
>
> |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of th... | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/mod... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/mod... | Before doing boolean encoding using the 1-of-K encoding suggested by @ogrisel, you may try enriching your data and playing with the number of features that you can extract from the datetime-type, i.e. day of week, day of month, day of year, week of year, quarter, etc.
See for example <https://pandas.pydata.org/pandas-... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/mod... | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - ... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function.
Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/mod... | I usually turn the DateTime to features of interest such as Year, Month, Day, Hour, Minute.
```
df['Year'] = df['Timestamp'].apply(lambda time: time.year)
df['Month'] = df['Timestamp'].apply(lambda time: time.month)
df['Day'] = df['Timestamp'].apply(lambda time: time.day)
df['Hour'] = df['Timestamp'].apply(lambda t... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of th... | Before doing boolean encoding using the 1-of-K encoding suggested by @ogrisel, you may try enriching your data and playing with the number of features that you can extract from the datetime-type, i.e. day of week, day of month, day of year, week of year, quarter, etc.
See for example <https://pandas.pydata.org/pandas-... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of th... | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - ... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date:
* hour of th... | I usually turn the DateTime to features of interest such as Year, Month, Day, Hour, Minute.
```
df['Year'] = df['Timestamp'].apply(lambda time: time.year)
df['Month'] = df['Timestamp'].apply(lambda time: time.month)
df['Day'] = df['Timestamp'].apply(lambda time: time.day)
df['Hour'] = df['Timestamp'].apply(lambda t... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | Before doing boolean encoding using the 1-of-K encoding suggested by @ogrisel, you may try enriching your data and playing with the number of features that you can extract from the datetime-type, i.e. day of week, day of month, day of year, week of year, quarter, etc.
See for example <https://pandas.pydata.org/pandas-... | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - ... |
16,453,644 | I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error.
What is the proper way to take the `da... | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741099/"
] | I usually turn the DateTime to features of interest such as Year, Month, Day, Hour, Minute.
```
df['Year'] = df['Timestamp'].apply(lambda time: time.year)
df['Month'] = df['Timestamp'].apply(lambda time: time.month)
df['Day'] = df['Timestamp'].apply(lambda time: time.day)
df['Hour'] = df['Timestamp'].apply(lambda t... | Often it's better to keep the amount of features low and there is not much information necessary from the timestamp. In my case it was enough to keep the date as a day-difference from the initial timestamp. This keeps the order and will leave you with only one (ordinal) feature.
```
df['DAY_DELTA'] = (df.TIMESTAMP - ... |
46,191,793 | I followed the guide here:
<https://plot.ly/python/filled-chord-diagram/>
And I produced this:
[](https://i.stack.imgur.com/wVzNc.png)
In the guide, I followed the `ribbon_info` code to add hoverinfo to the connecting ribbons but nothing shows. I c... | 2017/09/13 | [
"https://Stackoverflow.com/questions/46191793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6593031/"
] | just apply `json.dumps()` to this native python dictionary composed in one-line:
```
{k.replace(" ","_"):v.strip() for k,v in (x.split(":") for x in ["Passanger status:\n passanger cfg086d96 is unknown\n\n"])}
```
the inner generator comprehension avoids to call `split` for each part of the dict key/value. The value... | You can try this one also
```
data_dic = dict()
data = "Passanger status:\n passanger cfg086d96 is unknown\n\n"
x1 , x2 = map(str,data.split(":"))
data_dic[x1] = x2
print data_dic
```
If you find it simple
Output :
```
{'Passanger status': '\n passanger cfg086d96 is unknown\n\n'}
```
and for space to underscore... |
73,935,930 | How (in python) can I change numbers to be going up. For example, 1 (time.sleep(0.05)) then it changes to two, and so on. But there will be text already above it, so you can't use a simple `os.system('clear')`
So like this:
>
> print("how much money do you want to make?")<
> 'number going up without deleting the "ho... | 2022/10/03 | [
"https://Stackoverflow.com/questions/73935930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20149657/"
] | Like this:
```
import sys
import time
for i in range(10):
time.sleep(0.3)
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()
```
Edit: This was taken from [Replace console output in Python](https://stackoverflow.com/questions/6169217/replace-console-output-in-python) | The question is very unclear, but maybe you mean the following:
```py
import time
for item in [0.05,2,3]:
time.sleep(item)
```
and
```py
number = 3
print("how much money do you want to make? {}".format(number))
``` |
73,935,930 | How (in python) can I change numbers to be going up. For example, 1 (time.sleep(0.05)) then it changes to two, and so on. But there will be text already above it, so you can't use a simple `os.system('clear')`
So like this:
>
> print("how much money do you want to make?")<
> 'number going up without deleting the "ho... | 2022/10/03 | [
"https://Stackoverflow.com/questions/73935930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20149657/"
] | I am assuming that you want it to sleep for 1 second the first time, 2 seconds for the second time, and so on. You could create a function.
```
counter = 0
def my_function():
global counter
sleep(counter)
counter = counter + 1
for i in range(3):
my_function()
```
This is an example of what you can do.Chan... | The question is very unclear, but maybe you mean the following:
```py
import time
for item in [0.05,2,3]:
time.sleep(item)
```
and
```py
number = 3
print("how much money do you want to make? {}".format(number))
``` |
36,115,429 | I faced a compile error in my python script as following:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start, end])
```
the output is:
```
ASD 0 2 <class 'int'> <class 'int'>
Traceback (most recent call last):
File "test.py", line 5, in <module>
print(... | 2016/03/20 | [
"https://Stackoverflow.com/questions/36115429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3001445/"
] | The syntax to slice is with `:` not with `,`
```
>>> print(formula[start:end])
AS
``` | You seem to be performing a slicing operation, in order to do this you need to use `:` and not `,`:
```
formula[start:end]
```
Demo:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start:end])
```
output:
```
ASD 0 2 <class 'int'> <class 'int'>
AS
``` |
36,115,429 | I faced a compile error in my python script as following:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start, end])
```
the output is:
```
ASD 0 2 <class 'int'> <class 'int'>
Traceback (most recent call last):
File "test.py", line 5, in <module>
print(... | 2016/03/20 | [
"https://Stackoverflow.com/questions/36115429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3001445/"
] | As others have said, slicing is written like
```
formula[start:end]
```
The error in your original code is because
```
formula[start, end]
```
is being interpreted as
```
formula[(start, end)]
```
So the string index is a tuple, instead of an `int` or slice. | You seem to be performing a slicing operation, in order to do this you need to use `:` and not `,`:
```
formula[start:end]
```
Demo:
```
formula = "ASD"
start = 0
end = 2
print(formula, start, end, type(start), type(end))
print(formula[start:end])
```
output:
```
ASD 0 2 <class 'int'> <class 'int'>
AS
``` |
17,528,976 | I am working on an anonymizer program which sensors the given words in the list. This is what i have so far. I am new to python so not sure how can i achieve this.
```
def isAlpha(c):
if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9'):
return True
else:
return False
def ... | 2013/07/08 | [
"https://Stackoverflow.com/questions/17528976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2559375/"
] | You have several problems with your code:
1. There already exists an `islpha` function; it is a `str` method (see example below).
2. Your `trucatedInput` is a `str`, which is an immutable type. You can't reassign parts of an immutable type; i.e. `myStr[3]='x'` would normally fail. If you really want to do this, you're... | You could use [string.replace()](http://docs.python.org/2/library/string.html#string.replace)
```
truncatedInput.replace('DRAT', 'xxxx')
```
This will replace the first occurence of DRAT with xxxx, even if it is part of a longer sentence. If you want different functionality let me know. |
17,528,976 | I am working on an anonymizer program which sensors the given words in the list. This is what i have so far. I am new to python so not sure how can i achieve this.
```
def isAlpha(c):
if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9'):
return True
else:
return False
def ... | 2013/07/08 | [
"https://Stackoverflow.com/questions/17528976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2559375/"
] | You have several problems with your code:
1. There already exists an `islpha` function; it is a `str` method (see example below).
2. Your `trucatedInput` is a `str`, which is an immutable type. You can't reassign parts of an immutable type; i.e. `myStr[3]='x'` would normally fail. If you really want to do this, you're... | You're iterating over the characters in a string and comparing them to 'DRAT'. Since that's multiple characters, the comparison always fails. If you want to iterate over the string by word you must first break it into a list of words using str.split() and iterate over the list. |
67,756,936 | I have this:
```py
def f(message):
l = []
for c in message:
l.append(c)
l.append('*')
return "".join(l)
```
It works but how do I make it so that it doesn't add "\*" at the end. I only want it to be between the inputted word. I'm new to python and was just trying new things. | 2021/05/30 | [
"https://Stackoverflow.com/questions/67756936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16072743/"
] | May be you can try this. It uses list comprehension
```
input_str = 'dog'
def f(x):
return '*'.join(x)
print(f('dog')) #ouput d*o*g
print(f(input_str)) #ouput d*o*g
``` | Well, technically you could just slice the returned string cutting off the last astrix.
```
message="dog"
def f(message):
l = []
for c in message:
l.append(c)
l.append('*')
return "".join(l[:-1])
print(f(message))
```
this way it returns
```
d*o*g
... |
24,736,813 | I want to extend the datetime.date class adding it an attribute called `status` that represents if the date is a work day, an administrative non-work day, courts closed day,...
I've read from [How to extend a class in python?](https://stackoverflow.com/questions/15526858/how-to-extend-a-class-in-python), [How to exten... | 2014/07/14 | [
"https://Stackoverflow.com/questions/24736813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3160820/"
] | `datetime.date` is an immutable type, meaning you need to override the [`__new__` method](https://docs.python.org/3/reference/datamodel.html#object.__new__) instead:
```
class Fecha(datetime.date):
def __new__(cls, year, month, day, status):
instance = super(Fecha, cls).__new__(cls, year, month, day)
... | problem is in super call
```
super(Fecha, self).__init__(year, month, day)
```
Try this. |
55,739,404 | I have a Python 3.6 script that calls out to a third-party tool using subprocess.
`main_script.py:`
```
#!/usr/bin/env python
import subprocess
result = subprocess.run(['third-party-tool', '-arg1'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
```
The problem is, `main_script.py` must be run from wi... | 2019/04/18 | [
"https://Stackoverflow.com/questions/55739404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3638628/"
] | From the documentation of subprocess:
<https://docs.python.org/3/library/subprocess.html>
The accepted args are
```
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
capture_output=False, shell=False, cwd=None, timeout=None, check=False,
encoding=None, errors=None, text=None, env=None... | Thanks for your help, nullUser; your solution is a concise and correct answer to my question.
However, when I tried it out, my third-party-tool now fails for some other (unknown) reason. There was probably some other environment variable I don't know about that's getting lost with the new shell. Fortunately, I found a... |
13,661,723 | How can I run online python code that owns/requires a set of modules? (e.g. numpy, matplotlib) Answers/suggestions to questions [2737539](https://stackoverflow.com/questions/2737539/python-3-online-interpreter-shell) and [3356390](https://stackoverflow.com/questions/3356390/is-there-an-online-interpreter-for-python-3) ... | 2012/12/01 | [
"https://Stackoverflow.com/questions/13661723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I found one that supports multiple modules, i checked `numpy, scipy, psutil, matplotlib, etc` and all of them are supported. Check out pythonanyware compiler, a sample console is [here](https://www.pythonanywhere.com/try-ipython/), however you can signup for accounts [here](https://www.pythonanywhere.com/pricing/), i b... | You may try this as sandbox, it support numpy as well: <http://ideone.com> |
46,027,022 | I need to create a script that calculates the distance between two coordinates. The issue I'm having though is when I assign the coordinate to object one, it is stored as a string and am unable to convert it to a list or integer/float. How can I convert this into either a list or integer/float? The script and error I g... | 2017/09/03 | [
"https://Stackoverflow.com/questions/46027022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5874828/"
] | You have to convert the entered string to int/float by first splitting the string into the point components, then casting to the appropriate type:
```
x, y = map(float, one.split(','))
```
To keep the entered values as a single custom datatype, named `Point` for example, you can use a [`namedtuple`](https://docs.pyt... | Convert the input into the specific type as int or float
Into a list:
```
_list = list(map(int, input("Enter an x,y coordinate.").split(",")))
```
or into variables:
```
a, b = map(int, input("Enter an x,y coordinate.").split(","))
``` |
46,027,022 | I need to create a script that calculates the distance between two coordinates. The issue I'm having though is when I assign the coordinate to object one, it is stored as a string and am unable to convert it to a list or integer/float. How can I convert this into either a list or integer/float? The script and error I g... | 2017/09/03 | [
"https://Stackoverflow.com/questions/46027022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5874828/"
] | You have to convert the entered string to int/float by first splitting the string into the point components, then casting to the appropriate type:
```
x, y = map(float, one.split(','))
```
To keep the entered values as a single custom datatype, named `Point` for example, you can use a [`namedtuple`](https://docs.pyt... | After this `one=input("Enter an x,y coordinate.")` the variable **one** contains a string that looks like this `'x, y'` which cannot be converted to `int` as is.
You need to first split the string using `str.split(',')` which will yield a list `[x,y]` then you can iterate through the list and convert each of `x` and ... |
22,225,666 | Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list.
In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` me... | 2014/03/06 | [
"https://Stackoverflow.com/questions/22225666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282614/"
] | In between those two options the first one is clearly better as no Python for loop is involved.
```
>>> %timeit [None] * 100
1000000 loops, best of 3: 469 ns per loop
>>> %timeit [None for x in range(100)]
100000 loops, best of 3: 4.8 us per loop
```
**Update:**
And `list.append` has an [`O(1)` complexity](https:/... | When you append an item to a list, Python 'over-allocates', see the [source-code](http://svn.python.org/projects/python/trunk/Objects/listobject.c) of the list object. This means that for example when adding 1 item to a list of 8 items, it actually makes room for 8 new items, and uses only the first one of those. The n... |
22,225,666 | Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list.
In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` me... | 2014/03/06 | [
"https://Stackoverflow.com/questions/22225666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282614/"
] | When you append an item to a list, Python 'over-allocates', see the [source-code](http://svn.python.org/projects/python/trunk/Objects/listobject.c) of the list object. This means that for example when adding 1 item to a list of 8 items, it actually makes room for 8 new items, and uses only the first one of those. The n... | Obviously, the first version. Let me explain why.
1. When you do `[None] * n`, Python internally creates a list object of size `n` and it **copies the the same object** (here `None`) (*this is the reason, you should use this method only when you are dealing with immutable objects*) to all the memory locations. So memo... |
22,225,666 | Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list.
In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` me... | 2014/03/06 | [
"https://Stackoverflow.com/questions/22225666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/282614/"
] | In between those two options the first one is clearly better as no Python for loop is involved.
```
>>> %timeit [None] * 100
1000000 loops, best of 3: 469 ns per loop
>>> %timeit [None for x in range(100)]
100000 loops, best of 3: 4.8 us per loop
```
**Update:**
And `list.append` has an [`O(1)` complexity](https:/... | Obviously, the first version. Let me explain why.
1. When you do `[None] * n`, Python internally creates a list object of size `n` and it **copies the the same object** (here `None`) (*this is the reason, you should use this method only when you are dealing with immutable objects*) to all the memory locations. So memo... |
37,254,610 | ipdb is triggering an import error for me when I run my Django site locally. I'm working on Python 2.7 and within a virtual environment.
`which ipdb` shows the path `(/usr/local/bin/ipdb)`, as does `which ipython`, which surprised me since I thought it should show my venv path (but shouldn't it work if it's global, an... | 2016/05/16 | [
"https://Stackoverflow.com/questions/37254610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695507/"
] | You have Code like below. What ever you don't need just remove it.
```
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCod... | You appears to be using the Javascript version of the Google Places API. Let me know if I've guessed incorrectly!
All you need to do is add `®ion=US` when you load the Google Maps API. E.g.:
```
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places®ion=US">
```
Note that this ... |
63,012,839 | I'm looking for a fast way to fill a QTableModel with over 10000 rows of data in python.
Iterating over the items in a double for-loop takes over 40 seconds. | 2020/07/21 | [
"https://Stackoverflow.com/questions/63012839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6796677/"
] | You don't need to explicitly add items to a QTableModel, you can build your own model around an existing data structure like a list of lists or a numpy array like below.
```
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
from PyQt5.QtCore import QModelIndex, Qt
import numpy as np
class MyTableModel(QtCore.QAbs... | I would recommend creating a numpy array of QStandardItem and filling the Model using the appendColumn function:
```
start = time.time()
data = np.empty(rows, cols, dtype=object) # generate empty data-Array
#### Fill the data array with strings here ###
items = np.vectorize(QStandardItem)(data) ... |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg... | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
> ... | The requirement for braces lies in the Python interpreter and not in the code for the `print` method (or any other method) itself.
(And as eph points out in the comments, `print` is a statement not a method.) |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg... | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
> ... | As you've already been told, the `print` in Python 2.x was not a function, but a statement, like `if` or `for`. It was a "1st class" citizen, with its own special syntax. You are not allowed to create any statement, and all functions must use parentheses (both in Python 2.x and in 3.x). |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg... | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
> ... | No. Function call needs parentheses and two directly consecutive identifiers (that excludes reserved words) are a syntax error. That's set in stone in the grammar and won't change. The only way you could support this is making your own language implementation, at least the frontend of one - that's likely more trouble t... |
7,243,364 | Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers.
What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with:
```
>>>my_function arg1, arg2
```
instead of
```
>>>my_function(arg... | 2011/08/30 | [
"https://Stackoverflow.com/questions/7243364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/581732/"
] | You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure.
>
> >>> import this
>
> The Zen of Python, by Tim Peters
>
>
> Beautiful is better than ugly.
>
> **Explicit is better than implicit.**
>
> Simple is better than complex.
> ... | What are you trying to do? If you are trying to embed this code into another program (non-python) or invoke from the interpreter somehow, can you use `sys.argv` as an alternative instead? Here is an example of how [sys.argv](http://diveintopython.net/scripts_and_streams/command_line_arguments.html) works. |
48,247,921 | I'm attempting to get the TensorFlow Object Detection API
<https://github.com/tensorflow/models/tree/master/research/object_detection>
working on Windows by following the install instructions
<https://github.com/tensorflow/models/tree/master/research/object_detection>
Which seem to be for Linux/Mac. I can only get ... | 2018/01/14 | [
"https://Stackoverflow.com/questions/48247921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835204/"
] | As mentioned in the comment, `utils` is a submodule so you actually need to add `object_detection` to `PYTHONPATH`, not `object_detection/utils`.
I'm glad it worked for you. | cd Research/Object\_Detection
cd ..
Research
1. export PATH=~/anaconda3/bin:$PATH
RESEARCH
2. git clone <https://github.com/tensorflow/models.git>
RESEARCH
3.export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
4.protoc object\_detection/protos/string\_int\_label\_map.proto --python\_out=.
CD OBJECT\_DETECTION
5. ... |
48,247,921 | I'm attempting to get the TensorFlow Object Detection API
<https://github.com/tensorflow/models/tree/master/research/object_detection>
working on Windows by following the install instructions
<https://github.com/tensorflow/models/tree/master/research/object_detection>
Which seem to be for Linux/Mac. I can only get ... | 2018/01/14 | [
"https://Stackoverflow.com/questions/48247921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835204/"
] | As mentioned in the comment, `utils` is a submodule so you actually need to add `object_detection` to `PYTHONPATH`, not `object_detection/utils`.
I'm glad it worked for you. | The following command does not work on Windows:
```
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
```
Instead, I followed the directions of this [tutorial](https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10), which recommends setting the path variables for ... |
48,247,921 | I'm attempting to get the TensorFlow Object Detection API
<https://github.com/tensorflow/models/tree/master/research/object_detection>
working on Windows by following the install instructions
<https://github.com/tensorflow/models/tree/master/research/object_detection>
Which seem to be for Linux/Mac. I can only get ... | 2018/01/14 | [
"https://Stackoverflow.com/questions/48247921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835204/"
] | As mentioned in the comment, `utils` is a submodule so you actually need to add `object_detection` to `PYTHONPATH`, not `object_detection/utils`.
I'm glad it worked for you. | Make sure you have a `__init__.py` file in your research/object\_detection/protos folder! The `__init__.py` file is empty but needs to exist for the protos module to be created correctly. |
19,819,443 | I'm writing a code in Python. Within the code, a blackbox application written in c++ is called. Sometimes this c++ application does not converge and an error message come up. This error does not terminate the Python code, but it pause the run. After clicking ok for the error message, the python code continues running t... | 2013/11/06 | [
"https://Stackoverflow.com/questions/19819443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961551/"
] | I believe that in your case Python program doesn't actually continue the execution, unless the program started as a subprocess completes - this is the behaviour or [subprocess.check\_call](http://docs.python.org/2/library/subprocess.html#subprocess.check_call) which you say is used to start the subprocess.
As long as ... | Timur is correct. Unless the C++ program explicitly provides a way for you to check the status, respond to the dialog, or make it run without showing the dialog, there is nothing built into python that can solve this problem as far as i know.
There are some workarounds that might work for you, though. Depending on you... |
15,106,713 | I've searched the databases and cookbooks but can't seem to find the right answer. I have a very simple python code which sums up self powers in a range. I need the last ten digits of this very, very large number and I've tried the getcontext().prec however I'm still hitting a limit.
Here's the code:
```
def SelfPowe... | 2013/02/27 | [
"https://Stackoverflow.com/questions/15106713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2082350/"
] | If you want the *last ten digits* of a number, don't compute the whole thing (it will take too much memory and time).
Instead, consider using the "three-argument" form of `pow` to compute powers mod a specific base, and you will find the problem is much easier. | Testing on Python 3.2 I was able to
```
print(SelfPowers(10000))
```
though it took some seconds. How large a number were you thinking?
**Edit:** It looks like you want to use `1000`? In such case, upgrade to Python 3 and you should be fine. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think I find a solution, but If there something better pls, let me know...
I add `this.dialogRef.closeAll()`
```
class UserEffects {
constructor(
private actions$: Actions,
private dialogRef: MatDialog,
private notificationService: NotificationService,
) {}
@Effect()
addNewUser$ = this.actio... | In the constructor of your `@Effect`, you need to provide the dependency:
```
private dialogRef: MatDialogRef<MyDialogComponentToClose>
```
And you need to import `MatDialogModule` inside your module where your effect is. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } | In the constructor of your `@Effect`, you need to provide the dependency:
```
private dialogRef: MatDialogRef<MyDialogComponentToClose>
```
And you need to import `MatDialogModule` inside your module where your effect is. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think the best solution to closing dialog is subscribing to the effect variable
ie
```
// close the dialog
// Inside the dialog component
this.userEffects.addNewUser$.pipe(
ofType(Actions.LoadUsers)
).subscribe(_ => this.matDialogRef.close());
``` | In the constructor of your `@Effect`, you need to provide the dependency:
```
private dialogRef: MatDialogRef<MyDialogComponentToClose>
```
And you need to import `MatDialogModule` inside your module where your effect is. |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think I find a solution, but If there something better pls, let me know...
I add `this.dialogRef.closeAll()`
```
class UserEffects {
constructor(
private actions$: Actions,
private dialogRef: MatDialog,
private notificationService: NotificationService,
) {}
@Effect()
addNewUser$ = this.actio... | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think I find a solution, but If there something better pls, let me know...
I add `this.dialogRef.closeAll()`
```
class UserEffects {
constructor(
private actions$: Actions,
private dialogRef: MatDialog,
private notificationService: NotificationService,
) {}
@Effect()
addNewUser$ = this.actio... | You could listen to `actions$: Actions` in your dialog component, subscribe to it and close the dialog when the action is triggered, without recurring to NgRx effects and needing to inject all the dialogs references.
Your dialog component's constructor would include, among other things:
```js
constructor(
pub... |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } | You could listen to `actions$: Actions` in your dialog component, subscribe to it and close the dialog when the action is triggered, without recurring to NgRx effects and needing to inject all the dialogs references.
Your dialog component's constructor would include, among other things:
```js
constructor(
pub... |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think the best solution to closing dialog is subscribing to the effect variable
ie
```
// close the dialog
// Inside the dialog component
this.userEffects.addNewUser$.pipe(
ofType(Actions.LoadUsers)
).subscribe(_ => this.matDialogRef.close());
``` | regarding your 'dispatched an invalid action: undefined'
every effect must dispatch an action, unless you specify:
{ dispatch: false } |
58,850,484 | I want to save list below output onto a text file
```
with open("selectedProd.txt", 'w') as f:
for x in myprod["prod"]:
if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" :
f.write(x["name"],x["id"], x["price"])
```
I'm getting error
```
f.write(x["name"],x["id"], x["price"])
... | 2019/11/14 | [
"https://Stackoverflow.com/questions/58850484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10411973/"
] | I think the best solution to closing dialog is subscribing to the effect variable
ie
```
// close the dialog
// Inside the dialog component
this.userEffects.addNewUser$.pipe(
ofType(Actions.LoadUsers)
).subscribe(_ => this.matDialogRef.close());
``` | You could listen to `actions$: Actions` in your dialog component, subscribe to it and close the dialog when the action is triggered, without recurring to NgRx effects and needing to inject all the dialogs references.
Your dialog component's constructor would include, among other things:
```js
constructor(
pub... |
49,440,741 | I have a python code base where I have refactored a module (file) into a package (directory) as the file was getting a bit large and unmanageable. However, I cannot get my unit tests running as desired with the new structure.
I place my unit test files directly alongside the code it tests (this is a requirement and ca... | 2018/03/23 | [
"https://Stackoverflow.com/questions/49440741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23744/"
] | You can invoke the `unittest` module from the command line with arguments:
```
python -m unittest model.square_test
```
If you are using python3 you can use file names too:
```
python3 -m unittest model/square_test.py
``` | suggestions:
add `app/__init__.py`, and treat `app` as package instead of `model`
one way is for all tests, using explicit `from app.model.square import Square`
The relative import should be fine, as long as using `nosetests -vw .` in `app/` directory.
These all under the price of removing `app/test.py`
Another co... |
30,314,368 | I have a CSV file that looks something like this:
```
2014-6-06 08:03:19, 439105, 1053224, Front Entrance
2014-6-06 09:43:21, 439105, 1696241, Main Exit
2014-6-06 10:01:54, 1836139, 1593258, Back Archway
2014-6-06 11:34:26, 845646, external, Exit
2014-6-06 04:45:13, 1464748, 439105, Side Exit
``... | 2015/05/18 | [
"https://Stackoverflow.com/questions/30314368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4573703/"
] | It looks like you are grabbing the first element after you split the line. That is going to give you the date, according to your example CSV file.
What you probably want instead (again, assuming the example is the way it will always work) is to grab the 3rd element, so something like this:
```
csv_domain = line.split... | if you can go with something else then python, grep would work like this:
```
grep file.csv "some regex" > newfile.csv
```
would give you ONLY the lines that match the regex, while:
```
grep -v file.csv "some regex" > newfile.csv
```
gives everything BUT the lines matching the regex |
30,314,368 | I have a CSV file that looks something like this:
```
2014-6-06 08:03:19, 439105, 1053224, Front Entrance
2014-6-06 09:43:21, 439105, 1696241, Main Exit
2014-6-06 10:01:54, 1836139, 1593258, Back Archway
2014-6-06 11:34:26, 845646, external, Exit
2014-6-06 04:45:13, 1464748, 439105, Side Exit
``... | 2015/05/18 | [
"https://Stackoverflow.com/questions/30314368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4573703/"
] | It looks like you are grabbing the first element after you split the line. That is going to give you the date, according to your example CSV file.
What you probably want instead (again, assuming the example is the way it will always work) is to grab the 3rd element, so something like this:
```
csv_domain = line.split... | Redirect output to a new file. It will give you every line, except those that contain "external"
```
import sys
import re
f = open('sum.csv', "r")
lines = f.readlines()
p = re.compile('external')
for line in lines:
if(p.search(line)):
continue
else:
sys.stdout.write(line)
``` |
52,870,674 | When I execute the following command I get the below error from Tensorflow "missing file or folder". I've checked all online solutions for this error, but nothing is resolving my error.
`python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record`
**The error:**... | 2018/10/18 | [
"https://Stackoverflow.com/questions/52870674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9933958/"
] | I resolved the problem
If you are making `.CSV file` using a `xml_to_csv file.py`,
you have to check the file extension such as .jpg, .png, .jpeg in `train_labels.csv` file.
In my case, the xtension names won't be there !
[](https://i.stack.imgur.... | My csv-file contained imagenames with jpg extension and I still had this error OP posted. I tried solving it with:
```
python3 generate_tf_record.py --csv_input=data/train_labels.csv --output_path=train.record
python3 generate_tf_record.py --csv_input=data/test_labels.csv --output_path=test.record
```
All images we... |
52,870,674 | When I execute the following command I get the below error from Tensorflow "missing file or folder". I've checked all online solutions for this error, but nothing is resolving my error.
`python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record`
**The error:**... | 2018/10/18 | [
"https://Stackoverflow.com/questions/52870674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9933958/"
] | I resolved the problem
If you are making `.CSV file` using a `xml_to_csv file.py`,
you have to check the file extension such as .jpg, .png, .jpeg in `train_labels.csv` file.
In my case, the xtension names won't be there !
[](https://i.stack.imgur.... | i was running into the same issue, and no amount of checking the file path (relative or absolute) was working for me. my directory was organized to have images files and xmls in the same folder. the problem came down to the return statement of the split function inside generate\_tfrecord.py not having a file extension ... |
52,870,674 | When I execute the following command I get the below error from Tensorflow "missing file or folder". I've checked all online solutions for this error, but nothing is resolving my error.
`python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record`
**The error:**... | 2018/10/18 | [
"https://Stackoverflow.com/questions/52870674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9933958/"
] | My csv-file contained imagenames with jpg extension and I still had this error OP posted. I tried solving it with:
```
python3 generate_tf_record.py --csv_input=data/train_labels.csv --output_path=train.record
python3 generate_tf_record.py --csv_input=data/test_labels.csv --output_path=test.record
```
All images we... | i was running into the same issue, and no amount of checking the file path (relative or absolute) was working for me. my directory was organized to have images files and xmls in the same folder. the problem came down to the return statement of the split function inside generate\_tfrecord.py not having a file extension ... |
51,505,249 | ```
list = [1,2,,3,4,5,6,1,2,56,78,45,90,34]
range = ["0-25","25-50","50-75","75-100"]
```
I am coding in python. I want to sort a list of integers in range of numbers and store them in differrent lists.How can i do it?
I have specified my ranges in the the range list. | 2018/07/24 | [
"https://Stackoverflow.com/questions/51505249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10033784/"
] | Create a dictionary with max-value of each *bin* as key. Iterate through your numbers and append them to the list that's the value of each *bin-key*:
```
l = [1,2,3,4,5,6,1,2,56,78,45,90,34]
# your range covers 25 a piece - and share start/endvalues.
# I presume [0-25[ ranges
def inRanges(data,maxValues):
"""So... | Another stable bin approach for your special case (regular intervaled bins) would be to use a calculated key - this would get rid of the key-search in each step.
Stable search means the order of numbers in the list is the same as in the input data:
```
def inRegularIntervals(data, interval):
"""Sorts elements of ... |
30,513,482 | I'm trying to export two overloaded functions to Python. So I first define the pointers to these functions and then I use them to expose the functions to Python.
```
BOOST_PYTHON_MODULE(mylib){
// First define pointers to overloaded function
double (*expt_pseudopot02_v1)(double,double,double,const VECTOR&,
... | 2015/05/28 | [
"https://Stackoverflow.com/questions/30513482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938720/"
] | In short, the functions being exposed exceed the default maximum arity of 15. As noted in the [configuration documentation](http://www.boost.org/doc/libs/1_58_0/libs/python/doc/v2/configuration.html), one can define `BOOST_PYTHON_MAX_ARITY` to control the maximum allowed arity of any function, member function, or const... | As @bogdan pointed the function returning boost::python::list is having 16 parameters and max boost python arity by default is set to 15. Use `#define BOOST_PYTHON_MAX_ARITY 16` to increase the limit or (better) consider wrapping parameters into struct. |
20,997,283 | Does anyone know of some `Python` package or function that can upload a Pandas `DataFrame` (or simply a `.csv`) to a PostgreSQL table, **even if the table doesn't yet exist**?
(i.e. it runs a CREATE TABLE with the appropriate column names and columns types based on a mapping between the python data types and closest ... | 2014/01/08 | [
"https://Stackoverflow.com/questions/20997283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/176995/"
] | Since pandas 0.14, the sql functions also support postgresql (via SQLAlchemy, so all database flavors supported by SQLAlchemy work). So you can simply use `to_sql` to write a pandas DataFrame to a PostgreSQL database:
```
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
engine = create_engine('... | They just made a package for this. <https://gist.github.com/catawbasam/3164289> Not sure how well it works. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.