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 |
|---|---|---|---|---|---|
8,077,756 | in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do so... | 2011/11/10 | [
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] | having the soft keyboard disabled (only external keyboards enabled), I fixed it by moving the cursors at the end on the EditText:
```
editText.setSelection(editText.getText().length)
``` | `edittext.requestFocus()` works for me in my `Activity` and `Fragment` |
8,077,756 | in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do so... | 2011/11/10 | [
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] | It has worked for me as follows.
```
ed1.requestFocus();
return; //Faça um return para retornar o foco
``` | `edittext.requestFocus()` works for me in my `Activity` and `Fragment` |
8,077,756 | in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do so... | 2011/11/10 | [
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] | Yes, I got the answer.. just simply edit the `manifest` file as:
```
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
```
and set `EditText.requestFocus()` in `onCreate()`..
Thanks.. | `edittext.requestFocus()` works for me in my `Activity` and `Fragment` |
8,077,756 | in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do so... | 2011/11/10 | [
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] | Programatically:
```
edittext.requestFocus();
```
Through xml:
```
<EditText...>
<requestFocus />
</EditText>
```
Or call onClick method manually. | I know its too late but only solution is working for me is
```
edittext.requestFocus()
edittext.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN,0f,0f,0))
edittext.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.upti... |
8,077,756 | in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do so... | 2011/11/10 | [
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] | Programatically:
```
edittext.requestFocus();
```
Through xml:
```
<EditText...>
<requestFocus />
</EditText>
```
Or call onClick method manually. | Set to the Activity in Manifest:
```
android:windowSoftInputMode="adjustResize"
```
Set focus, when a view is ready:
```
fun setFocus(view: View, showKeyboard: Boolean = true){
view.post {
if (view.requestFocus() && showKeyboard)
activity?.openKeyboard() // call extension function
}
}
`... |
8,077,756 | in my views.py i obtain 5 dicts, which all are something like {date:value}
all 5 dicts have the same length and in my template i want to obtain some urls based on these dicts, with the common field being the date - as you would do in an sql query when joining 5 tables based on a common column
in python you would do so... | 2011/11/10 | [
"https://Stackoverflow.com/questions/8077756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023857/"
] | Yes, I got the answer.. just simply edit the `manifest` file as:
```
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
```
and set `EditText.requestFocus()` in `onCreate()`..
Thanks.. | `youredittext.requestFocus()` call it from activity
```
oncreate();
```
and use the above code there |
34,169,770 | I am trying to select sensors by placing a box around their geographic coordinates:
```
In [1]: lat_min, lat_max = lats(data)
lon_min, lon_max = lons(data)
print(np.around(np.array([lat_min, lat_max, lon_min, lon_max]), 5))
Out[1]: [ 32.87248 33.10181 -94.37297 -94.21224]
In [2]: select_sens = sens[... | 2015/12/09 | [
"https://Stackoverflow.com/questions/34169770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765319/"
] | I'm not familiar with NumPy nor Pandas, but the error is saying that one of the objects in the comparison `if len(self) != len(other)` does not have a `__len__` method and therefore has no length.
Try doing `print(sens_data)` to see if you get a similar error. | I found a similar issue and think the problem may be related to the Python version you are using.
I wrote my code in Spyder
**Python 3.6.1 |Anaconda 4.4.0 (64-bit)**
but then passed it to someone using Spyder but
**Python 3.5.2 |Anaconda 4.2.0 (64-bit)**
I had one numpy.float64 object (as far as i understand, simila... |
26,593,344 | I'm writing a pandas Dataframe to a Postgres database:
```
from sqlalchemy import create_engine, MetaData
engine = create_engine(r'postgresql://user:password@localhost:5432/db')
meta = MetaData(engine, schema='data_quality')
meta.reflect(engine, schema='data_quality')
pdsql = pd.io.sql.PandasSQLAlchemy(engine, meta=me... | 2014/10/27 | [
"https://Stackoverflow.com/questions/26593344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3591836/"
] | I suppose you are using pandas 0.15. `PandasSQLAlchemy` was not yet really public, and was renamed in pandas 0.15 to `SQLDatabase`. So if you replace that in your code, it should work (so `pdsql = pd.io.sql.SQLDatabase(engine, meta=meta)`).
However, starting from pandas 0.15, there is also schema support in the `read_... | I have encountered this error recently and it was solved my removing the .pyc files located in the same directory as .py files. These files (.pyc) holds the previous version information and time, date. |
67,220,607 | I'm trying to save a loop output into a text file with python. However, when I try to do so only the first line of the result gets printed on the file.
This is the line I want to print the result of:
```
with open('myfile.txt','w') as f_output:
f_output.write(
for k, v in mydic.items():
... | 2021/04/22 | [
"https://Stackoverflow.com/questions/67220607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12763792/"
] | Write in append mode with `a`:
```py
mydic = {'1': [22, 23], '2': [33,24], '3': [44,25]}
with open('myfile.txt','a') as f_output:
for k, v in mydic.items():
# Also need `\n` for newlines:
f_output.write(f"{k:11}{v[0]}{v[1]:12}\n")
```
Output:
```
1 22 23
2 33 ... | Change the argument from 'w' (write) to 'a' (append).
```py
mydic = {'1': [22, 23], '2': [33, 24], '3': [44, 25]}
with open('myfile.txt','a') as f_output:
for k, v in mydic.items():
res=f"{k:11}{v[0]}{v[1]:12}"
f_output.write(f"{res}\n")
print(res)
``` |
45,317,767 | ```
def generate_n_chars(n,s="."):
res=""
count=0
while count < n:
count=count+1
res=res+s
return res
print generate_n_chars(raw_input("Enter the integer value : "),raw_input("Enter the character : "))
```
I am beginner in python and I don't know why this loop going to infinity. Plea... | 2017/07/26 | [
"https://Stackoverflow.com/questions/45317767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7504540/"
] | I personally have another mental model which doesn't deal directly with identity and memory and whatnot.
`prvalue` comes from "pure rvalue" while `xvalue` comes from "expiring value" and is this information I use in my mental model:
**Pure rvalue** refers to an object that is a temporary in the "pure sense": an expre... | When calling a `func(T&& t)` the caller is saying "there's a t here" and also "I don't care what you do to it". C++ does not specify the nature of "here".
On a platform where reference parameters are implemented as addresses, this means there must be an object present somewhere. On that platform identity == address. H... |
25,618,016 | I have the following script which just isnt working for me :(. I essentially want to create 10 threads to port scan a range of 100 ports. It should seem simple but I dont know where I am going wrong. Im new to python and have been looking at how to get this working for the past two weeks and I know give up. When execut... | 2014/09/02 | [
"https://Stackoverflow.com/questions/25618016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3999393/"
] | You have an extra space after resource, have you tried removing that?
```
'resource ': {
``` | It looks like you're doing extra encoding of the inserted rows. They should be sent as raw json, rather than encoding the whole row as a string. That is, something like this:
```
'rows': [
{
'insertId': 123456,
'json': {'id': 123,'name':'test1'}
}
]
```
(note the difference from what you have above is ju... |
70,943,395 | I did the following in google colab notebook and get an error. Any idea?
```
%pip install pyenchant
import enchant
```
and get the following error:
ImportError Traceback (most recent call last)
in ()
----> 1 import enchant
1 frames
/usr/local/lib/python3.7/dist-packages/enchant/\_enchant.py in ()
159 """
160 )
--... | 2022/02/01 | [
"https://Stackoverflow.com/questions/70943395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18092070/"
] | After lots of research, I found the solution [here](https://github.com/googlecolab/colabtools/issues/441).
Run this code on goggle colab before `import enchant`
```
!apt update
!apt install enchant --fix-missing
!apt install -qq enchant
!pip install pyenchant
``` | Yes enchant doesnt work on Google colab because of C libraries. You can use Jupyter notebook for this library and it will work just fine. |
43,094,861 | I would like to split a string into separated, single strings and save each in a new variable. That's the use case:
* Direct user input with `BC1 = input("BC1: ")` in the following format: `'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'`
* Now I want each number - and just the... | 2017/03/29 | [
"https://Stackoverflow.com/questions/43094861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6051700/"
] | Look into [re](https://docs.python.org/2/library/re.html#re.findall)
```
import re
input = "'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'"
matches = re.findall('(\d+)', input)
# matches = ['17899792270101010000000000', '17899792270102010000000000', '1789979227010301000000... | if it's already "format" at the input :
```
>>> BC1 = input("BC1: ")
BC1: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'
>>> a=int(BC1[0])
>>> b=int(BC1[1])
>>> c=int(BC1[2])
>>> a
17899792270101010000000000
>>> b
17899792270102010000000000
>>> c
17899792270103010000000000
``... |
43,094,861 | I would like to split a string into separated, single strings and save each in a new variable. That's the use case:
* Direct user input with `BC1 = input("BC1: ")` in the following format: `'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'`
* Now I want each number - and just the... | 2017/03/29 | [
"https://Stackoverflow.com/questions/43094861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6051700/"
] | Look into [re](https://docs.python.org/2/library/re.html#re.findall)
```
import re
input = "'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'"
matches = re.findall('(\d+)', input)
# matches = ['17899792270101010000000000', '17899792270102010000000000', '1789979227010301000000... | If I understand you correctly, this should do the trick
```
BC1 = input("BC1: ")
numbers = [int(x.strip(' \'')) for x in BC1.split(',')]
```
And now your desired numbers are
```
numbers[0] == a # 17899792270101010000000000
numbers[1] == b # 17899792270102010000000000
numbers[2] == c # 17899792270103010000000000
``... |
43,094,861 | I would like to split a string into separated, single strings and save each in a new variable. That's the use case:
* Direct user input with `BC1 = input("BC1: ")` in the following format: `'17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'`
* Now I want each number - and just the... | 2017/03/29 | [
"https://Stackoverflow.com/questions/43094861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6051700/"
] | If I understand you correctly, this should do the trick
```
BC1 = input("BC1: ")
numbers = [int(x.strip(' \'')) for x in BC1.split(',')]
```
And now your desired numbers are
```
numbers[0] == a # 17899792270101010000000000
numbers[1] == b # 17899792270102010000000000
numbers[2] == c # 17899792270103010000000000
``... | if it's already "format" at the input :
```
>>> BC1 = input("BC1: ")
BC1: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'
>>> a=int(BC1[0])
>>> b=int(BC1[1])
>>> c=int(BC1[2])
>>> a
17899792270101010000000000
>>> b
17899792270102010000000000
>>> c
17899792270103010000000000
``... |
38,550,322 | Hello everyone!
I'm new to python networking programming.
My development environments are as below.
* Windows 7
* Python 3.4
I am studying with "Python Network Programming Cookbook". In this book, there's an example of **ThreadingMixIn** socket server application.
This book's code is written in Python 2.7. So I've... | 2016/07/24 | [
"https://Stackoverflow.com/questions/38550322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6192555/"
] | Your program exits because your server thread is a daemon:
```
# Exit the server thread when the main thread exits
server_thread.daemon = True
```
You can either remove that line or add `server_thread.join()` at the bottom of the code to prevent the main thread from exiting early. | You will have to run on an infinite loop and on each loop wait for some data to come from client. This way the connection will be kept alive.
Same infinite loop for the server to accept more clients.
However, you will have to somehow detect when a client closes the connection with the server because in most times the... |
53,312,339 | I need to install COCOAPI for Python 3.5 on my linux machine but when I do "make" it automatically installs it for 2.7. Is there an option to choose for a python version while using "make" ?
**EDIT 1 :**
Going to PythonAPI folder and installing it via python3 setup.py install gives the following error.
```
sudo py... | 2018/11/15 | [
"https://Stackoverflow.com/questions/53312339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715275/"
] | Clone the repo using `git clone https://github.com/cocodataset/cocoapi.git` then enter the dir where it is located and type `python3 setup.py install` which should install using python3.
If the above doesn't work, try `pip3 install cython` followed by `pip3 install pycocotools` (you can add the `--user` flag to all of... | You can make sure the default `python` resolves in the one you are interested in, for example by symbolically linking `python` to `python2` wherever it is defined (possibly `/usr/bin`) |
70,909,920 | I'm trying to write a code that will search for specific data from multiple report files, and write them into columns in a single csv.
The report file lines i'm looking for aren't always on the same line, so i'm looking for the data associated on the lines below:
Estimate file: pog\_example.bef
Estimate ID: o1\_p1
... | 2022/01/29 | [
"https://Stackoverflow.com/questions/70909920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17361896/"
] | Liquid is not going to work on JSON like this. If you want to iterate through an array of JSON objects, use Javascript. | As lov2code points out by adding (-) it trims the output for any unnecessary white space, which enables you to traverse the JSON array. |
70,909,920 | I'm trying to write a code that will search for specific data from multiple report files, and write them into columns in a single csv.
The report file lines i'm looking for aren't always on the same line, so i'm looking for the data associated on the lines below:
Estimate file: pog\_example.bef
Estimate ID: o1\_p1
... | 2022/01/29 | [
"https://Stackoverflow.com/questions/70909920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17361896/"
] | For some reason when it is a multidimensional JSON array it acts weird. There is a simple fix for it, just add (-) at the end of your assigned variable:
```
{%- assign releases = product.metafields.artist.releases.value -%}
{% for release in releases.releases %}
{{ release.releaseName }}
{%- endfor -%}
```... | As lov2code points out by adding (-) it trims the output for any unnecessary white space, which enables you to traverse the JSON array. |
28,228,238 | Hello guys I am really new to python and I am trying to sort the /etc/passwd file using PYTHON 3.4 based on the following criteria:
Input (regular /etc/passwd file on linux system:
```
raj:x:501:512::/home/raj:/bin/ksh
ash:x:502:502::/home/ash:/bin/zsh
jadmin:x:503:503::/home/jadmin:/bin/sh
jwww:x:504:504::/htdocs/h... | 2015/01/30 | [
"https://Stackoverflow.com/questions/28228238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214003/"
] | You can open the file, throw it into a list and then throw all the users into some kinda hash table
```
with open("/etc/passwd") as f:
lines = f.readlines()
group_dict = {}
for line in lines:
split_line = line.split(":")
user = split_line[0]
gid = split_line[3]
# If the group id is not in the dict... | This should loop through your `/etc/passwd` and sort users by group. You don't have to do anything fancy to solve this problem.
```
with open('/etc/passwd', 'r') as f:
res = {}
for line in f:
parts = line.split(':')
try:
name, gid = parts[0], int(parts[3])
except IndexErro... |
26,643,705 | So, I have tried this problem for what it seems like a hundred times this week alone.
It's filling in the blank for the following program...
You entered jackson and ville.
When these are combined, it makes jacksonville.
Taking every other letter gives us jcsnil.
The blanks I have filled are fine, but the rest of th... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26643705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196499/"
] | Assuming that each word is on it's own line, you should be reading the file more like...
```
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
```
Remember, if you open a resour... | Set a two counters and a variable that holds the current longest word found before you start reading in with your while loop. To find the average have one counter be incremented by one each time the line is read and have the second counter add up the total number of characters in each word (obviously the total number o... |
26,643,705 | So, I have tried this problem for what it seems like a hundred times this week alone.
It's filling in the blank for the following program...
You entered jackson and ville.
When these are combined, it makes jacksonville.
Taking every other letter gives us jcsnil.
The blanks I have filled are fine, but the rest of th... | 2014/10/30 | [
"https://Stackoverflow.com/questions/26643705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196499/"
] | Assuming that each word is on it's own line, you should be reading the file more like...
```
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
```
Remember, if you open a resour... | May be this could help
```
String words = "Rookie never dissappoints, dont trust any Rookie";
// read your file to string if you get string while reading then you can use below code to do that.
String ss[] = words.split(" ");
List<String> list = Arrays.asList(ss);
Map<Integer,Strin... |
61,160,595 | I'm trying to write a function that takes in a list and returns true if it contains the numbers 0,0,7 in that order. When I run this code:
```
def prob11(abc):
if 7 and 0 and 0 not in abc:
return False
x = abc.index(0)
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
retur... | 2020/04/11 | [
"https://Stackoverflow.com/questions/61160595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13201582/"
] | Your screenshot is showing data in Realtime Database, but your code is querying Firestore. They are completely different databases with different APIs. You can't use the Firestore SDK to query Realtime Database. If you want to work with Realtime Database, use the documentation [here](https://firebase.google.com/docs/da... | There is `author` between `posts` and `username` field in your data structure.
Your code means that right under some specific post there is `username` field.
So such code will work because `date` right undes post:
```
db.collection("posts").whereField("date", isEqualTo: "some-bla-bla-date")
```
In your case you hav... |
61,160,595 | I'm trying to write a function that takes in a list and returns true if it contains the numbers 0,0,7 in that order. When I run this code:
```
def prob11(abc):
if 7 and 0 and 0 not in abc:
return False
x = abc.index(0)
elif 7 and 0 and 0 in abc and abc[x + 1] == 0 and abc[x + 2] == 7:
retur... | 2020/04/11 | [
"https://Stackoverflow.com/questions/61160595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13201582/"
] | Your screenshot is showing data in Realtime Database, but your code is querying Firestore. They are completely different databases with different APIs. You can't use the Firestore SDK to query Realtime Database. If you want to work with Realtime Database, use the documentation [here](https://firebase.google.com/docs/da... | So I changed my code to:
```
func loadData(url: URL){
let ref = Database.database().reference().child("posts")
let user = UserService.currentUserProfile!
ref.queryOrdered(byChild: "author/username").queryEqual(toValue: user.username).observe(.value, with: { snapshot in
if var post = snapshot.valu... |
34,271,807 | I am trying to write a python script with several text files inside a subdirectory, e.g.
```
python script.py --inputdir ~/subdirectory
```
which will execute each file inside this subdirectory. How can one use argparse to do this? Should you write a function to access and open each file?
```
import argparse
parse... | 2015/12/14 | [
"https://Stackoverflow.com/questions/34271807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4596596/"
] | I think your a mixing up the return value of setInterval.
setInterval returns an handle to the function scheduled, so you can call clearInterval().
From Mdn:
<https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval>
```
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);... | [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval) returns a reference to the interval you have just created, so that later you can stop the interval.
```
var myRef = setInterval(...);
clearInterval(myRef);
```
Every time `moveBall()` is called and you run this
```
startTime ... |
7,513,133 | From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
```
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
``` | 2011/09/22 | [
"https://Stackoverflow.com/questions/7513133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] | From Python, run bash with `os.system`, `os.popen` or `subprocess` and pass the appropriate command-line arguments.
```
os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')
``` | Bash should accept a command from args when using the -c flag:
```
C:\cygwin\bin\bash.exe -c "somecommand"
```
Combine that with C++'s [`exec`](http://linux.about.com/library/cmd/blcmdl3_execvp.htm) or python's `os.system` to run the command. |
7,513,133 | From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
```
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
``` | 2011/09/22 | [
"https://Stackoverflow.com/questions/7513133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] | From Python, run bash with `os.system`, `os.popen` or `subprocess` and pass the appropriate command-line arguments.
```
os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')
``` | The following function will run Cygwin's Bash program while making sure the bin directory is in the system path, so you have access to non-built-in commands. This is an alternative to using the login (-l) option, which may redirect you to your home directory.
```py
def cygwin(command):
"""
Run a Bash command w... |
7,513,133 | From a windows application written on C++ or python, how can I execute arbitrary shell commands?
My installation of Cygwin is normally launched from the following bat file:
```
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
``` | 2011/09/22 | [
"https://Stackoverflow.com/questions/7513133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] | The following function will run Cygwin's Bash program while making sure the bin directory is in the system path, so you have access to non-built-in commands. This is an alternative to using the login (-l) option, which may redirect you to your home directory.
```py
def cygwin(command):
"""
Run a Bash command w... | Bash should accept a command from args when using the -c flag:
```
C:\cygwin\bin\bash.exe -c "somecommand"
```
Combine that with C++'s [`exec`](http://linux.about.com/library/cmd/blcmdl3_execvp.htm) or python's `os.system` to run the command. |
67,915,835 | I and my colleague is working on a django (python) project and pushing our code on same branch(lets say branch1), as a beginner i know how to push the code on a particular branch but have no idea how pull and merge can be done. what should i do if i want full project including his codes and my codes together without ov... | 2021/06/10 | [
"https://Stackoverflow.com/questions/67915835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13963543/"
] | For node.js subprocesses there is the [cluster module](https://nodejs.org/api/cluster.html) and I strongly recommend using this. For general subprocesses (e.g. bash scripts as you mentioned) you have to use `child_process` (-> execa). Communication between processes may then be accomplished via grpc. Your approach is f... | I decided to go full with `pm2` for the time being, as they have an excellent [programmatic API](https://pm2.keymetrics.io/docs/usage/pm2-api/) - also (which I only just learned about) you can specify [different interpreters](https://pm2.keymetrics.io/docs/usage/process-management/#start-any-process-type) to run your s... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | `int &foo();` declares a function called `foo()` with return type `int&`. If you call this function without providing a body then you are likely to get an undefined reference error.
In your second attempt you provided a function `int foo()`. This has a different return type to the function declared by `int& foo();`. S... | In that context the & means a reference - so foo returns a reference to an int, rather than an int.
I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory wh... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | All the other answers declare a static inside the function. I think that might confuse you, so take a look at this:
```
int& highest(int & i, int & j)
{
if (i > j)
{
return i;
}
return j;
}
int main()
{
int a{ 3};
int b{ 4 };
highest(a, b) = 11;
return 0;
}
```
Because `hig... | The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the sig... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | `int& foo();` is a function returning a reference to `int`. Your provided function returns `int` without reference.
You may do
```
int& foo()
{
static int i = 42;
return i;
}
int main()
{
int& foo();
foo() = 42;
}
``` | The function you have, foo(), is a function that returns a reference to an integer.
So let's say originally foo returned 5, and later on, in your main function, you say `foo() = 10;`, then prints out foo, it will print 10 instead of 5.
I hope that makes sense :)
I'm new to programming as well. It's interesting to se... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | `int &foo();` declares a function called `foo()` with return type `int&`. If you call this function without providing a body then you are likely to get an undefined reference error.
In your second attempt you provided a function `int foo()`. This has a different return type to the function declared by `int& foo();`. S... | `int& foo();` is a function returning a reference to `int`. Your provided function returns `int` without reference.
You may do
```
int& foo()
{
static int i = 42;
return i;
}
int main()
{
int& foo();
foo() = 42;
}
``` |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | The explanation is assuming that there is some reasonable implementation for `foo` which returns an lvalue reference to a valid `int`.
Such an implementation might be:
```
int a = 2; //global variable, lives until program termination
int& foo() {
return a;
}
```
Now, since `foo` returns an lvalue reference, w... | ```
int& foo();
```
Declares a function named foo that returns a reference to an `int`. What that examples fails to do is give you a definition of that function that you could compile. If we use
```
int & foo()
{
static int bar = 0;
return bar;
}
```
Now we have a function that returns a reference to `bar`... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | `int & foo();` means that `foo()` returns a reference to a variable.
Consider this code:
```
#include <iostream>
int k = 0;
int &foo()
{
return k;
}
int main(int argc,char **argv)
{
k = 4;
foo() = 5;
std::cout << "k=" << k << "\n";
return 0;
}
```
This code prints:
$ ./a.out
k=5
Because `f... | The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the sig... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | ```
int& foo();
```
Declares a function named foo that returns a reference to an `int`. What that examples fails to do is give you a definition of that function that you could compile. If we use
```
int & foo()
{
static int bar = 0;
return bar;
}
```
Now we have a function that returns a reference to `bar`... | `int & foo();` means that `foo()` returns a reference to a variable.
Consider this code:
```
#include <iostream>
int k = 0;
int &foo()
{
return k;
}
int main(int argc,char **argv)
{
k = 4;
foo() = 5;
std::cout << "k=" << k << "\n";
return 0;
}
```
This code prints:
$ ./a.out
k=5
Because `f... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | ```
int& foo();
```
Declares a function named foo that returns a reference to an `int`. What that examples fails to do is give you a definition of that function that you could compile. If we use
```
int & foo()
{
static int bar = 0;
return bar;
}
```
Now we have a function that returns a reference to `bar`... | The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the sig... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | All the other answers declare a static inside the function. I think that might confuse you, so take a look at this:
```
int& highest(int & i, int & j)
{
if (i > j)
{
return i;
}
return j;
}
int main()
{
int a{ 3};
int b{ 4 };
highest(a, b) = 11;
return 0;
}
```
Because `hig... | In that context the & means a reference - so foo returns a reference to an int, rather than an int.
I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory wh... |
36,477,552 | I've got a python script that's being run from the **if-up** script that's called by the **ppp** program on Linux when the PPP connection is established. The python script basically calls a command line program, parses the result and returns it:
```
import subprocess
result = subprocess.check_output(["fw_printenv", "... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36477552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286701/"
] | The explanation is assuming that there is some reasonable implementation for `foo` which returns an lvalue reference to a valid `int`.
Such an implementation might be:
```
int a = 2; //global variable, lives until program termination
int& foo() {
return a;
}
```
Now, since `foo` returns an lvalue reference, w... | The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, `foo` is clearly returning an lvalue based on the sig... |
39,637,164 | How can i used the rt function, as i understand leading & trailing underscores `__and__()` is available for native python objects or you wan't to customize behavior in specific situations. how can the user take advantages of it . For ex: in the below code can i use this function at all,
```
class A(object):
def __rt... | 2016/09/22 | [
"https://Stackoverflow.com/questions/39637164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277603/"
] | Python doesn't translate one name into another. Specific operations will *under the covers* call a `__special_method__` if it has been defined. For example, the `__and__` method is called by Python to hook into the `&` operator, because the Python interpreter *explicitly looks for that method* and documented how it sho... | Because there are builtin methods that you can overriden and then you can use them, ex `__len__` -> `len()`, `__str__` -> `str()` and etc.
Here is the [list of these functions](https://docs.python.org/3/reference/datamodel.html#basic-customization)
>
> The following methods can be defined to customize the meaning of... |
65,571,031 | I am trying to install a package on a python project but having some issues with python-Levenshtein library. I'm using a virtual environment on PyCharm which is running with Python3.8 and installed all libraries in requirements.txt with pip. However I am not able to install this library.
What I've tried so far:
1. tr... | 2021/01/04 | [
"https://Stackoverflow.com/questions/65571031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5331231/"
] | That index could be used if you wrote the query like this:
```
select rh."EventHistory"
from "RemittanceHistory" rh join "ClaimPaymentHistory" ph
on ph."EventHistory" @> jsonb_build_array(jsonb_build_object('rk',rh."RemittanceRefKey"))
where ph."ClaimRefKey" = 5;
```
However, this unlikely to have good performan... | I wound up refactoring the table structure. Instead of a join through `RemittanceRefKey` I added a JSONB column to `RemittanceHistory` called `ClaimRefKeys`. This is simply an array of integer values and now I can lookup the desired rows with:
```
select "EventHistory" from "RemittanceHistory" where "ClaimRefKeys" @> ... |
57,593,041 | ```
>>> x = 1
>>> def f():
... print x
...
>>> f()
1
>>> x = 1
>>> def f():
... x = 3
... print x
...
>>> f()
3
>>> x
1
>>> x = 1
>>> def f():
... print x
... x = 5
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local va... | 2019/08/21 | [
"https://Stackoverflow.com/questions/57593041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335601/"
] | >
> In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
>
>
>
[Source.](https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-lo... | The behaviour is already what you want. The presence of `x =` inside the function body makes `x` a local variable which entirely shadows the outer variable. You're merely trying to print it before you assign any value to it, which is causing an error. This would cause an error under any other circumstance too; you can'... |
56,184,013 | Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If `tensorflow-gpu` is installed and `tensorflow.lite.python.interpreter` is imported, will GPU be used automatically? | 2019/05/17 | [
"https://Stackoverflow.com/questions/56184013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349476/"
] | According to [this](https://github.com/tensorflow/tensorflow/issues/31377) thread, it is not. | You can force the computation to take place on a GPU:
```
import tensorflow as tf
with tf.device('/gpu:0'):
for i in range(10):
t = np.random.randint(len(x_test) )
...
```
Hope this helps. |
56,184,013 | Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If `tensorflow-gpu` is installed and `tensorflow.lite.python.interpreter` is imported, will GPU be used automatically? | 2019/05/17 | [
"https://Stackoverflow.com/questions/56184013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349476/"
] | one solution is to convert tflite to onnx and use onnxruntime-gpu
convert to onnx with <https://github.com/onnx/tensorflow-onnx>:
```
pip install tf2onnx
python3 -m tf2onnx.convert --opset 11 --tflite path/to/model.tflite --output path/to/model.onnx
```
then `pip install onnxruntime-gpu`
and run like:
```
sessio... | You can force the computation to take place on a GPU:
```
import tensorflow as tf
with tf.device('/gpu:0'):
for i in range(10):
t = np.random.randint(len(x_test) )
...
```
Hope this helps. |
56,184,013 | Anyone know if Tensorflow Lite has GPU support for Python? I've seen guides for Android and iOS, but I haven't come across anything about Python. If `tensorflow-gpu` is installed and `tensorflow.lite.python.interpreter` is imported, will GPU be used automatically? | 2019/05/17 | [
"https://Stackoverflow.com/questions/56184013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5349476/"
] | According to [this](https://github.com/tensorflow/tensorflow/issues/31377) thread, it is not. | one solution is to convert tflite to onnx and use onnxruntime-gpu
convert to onnx with <https://github.com/onnx/tensorflow-onnx>:
```
pip install tf2onnx
python3 -m tf2onnx.convert --opset 11 --tflite path/to/model.tflite --output path/to/model.onnx
```
then `pip install onnxruntime-gpu`
and run like:
```
sessio... |
58,126,489 | I follow the tutorial from Traversy Media on Youtube videos. When I put the command
>
> python manage.py migrate
>
>
>
Then I got such an error like this:
```
C:\Users\Acer\Project\djangoproject>python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
Fi... | 2019/09/27 | [
"https://Stackoverflow.com/questions/58126489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11803617/"
] | There are several dedicated packages for this. For example have a look at the `combine`, `subdocs` or `docmute` packages (A list with even more suggestions can be fond at <https://www.ctan.org/recommendations/docmute>).
Here a short example with the `docmute` package
```
\documentclass{book}
\usepackage{lipsum}
\us... | A Latex document cannot have multiple `\documentclass`. One solution would be to split the header/content of your latex document in overleaf:
* Create a `master.tex` with the documentclass and put all your content (text between `\begin{document}` and `\end{document}` in a second `content.tex`. In the master, just `\in... |
43,736,163 | I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.
```
import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']
```
\*\*
```
reviews_new['review']
Trac... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43736163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123815/"
] | I think first is best investigate, what are real columns names, if convert to list better are seen some whitespaces or similar:
```
print (reviews_new.columns.tolist())
```
---
I think there can be 2 problems (obviously):
**1.whitespaces in columns names (maybe in data also)**
Solutions are [`strip`](http://panda... | ```
import pandas as pd
df=pd.read_csv("file.txt", skipinitialspace=True)
df.head()
df['review']
``` |
43,736,163 | I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.
```
import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']
```
\*\*
```
reviews_new['review']
Trac... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43736163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123815/"
] | I think first is best investigate, what are real columns names, if convert to list better are seen some whitespaces or similar:
```
print (reviews_new.columns.tolist())
```
---
I think there can be 2 problems (obviously):
**1.whitespaces in columns names (maybe in data also)**
Solutions are [`strip`](http://panda... | ```
dfObj['Hash Key'] = (dfObj['DEAL_ID'].map(str) +dfObj['COST_CODE'].map(str) +dfObj['TRADE_ID'].map(str)).apply(hash)
#for index, row in dfObj.iterrows():
# dfObj.loc[`enter code here`index,'hash'] = hashlib.md5(str(row[['COST_CODE','TRADE_ID']].values)).hexdigest()
print(dfObj['hash'])
``` |
43,736,163 | I have successfully read a csv file using pandas. When I am trying to print the a particular column from the data frame i am getting keyerror. Hereby i am sharing the code with the error.
```
import pandas as pd
reviews_new = pd.read_csv("D:\\aviva.csv")
reviews_new['review']
```
\*\*
```
reviews_new['review']
Trac... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43736163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5123815/"
] | ```
import pandas as pd
df=pd.read_csv("file.txt", skipinitialspace=True)
df.head()
df['review']
``` | ```
dfObj['Hash Key'] = (dfObj['DEAL_ID'].map(str) +dfObj['COST_CODE'].map(str) +dfObj['TRADE_ID'].map(str)).apply(hash)
#for index, row in dfObj.iterrows():
# dfObj.loc[`enter code here`index,'hash'] = hashlib.md5(str(row[['COST_CODE','TRADE_ID']].values)).hexdigest()
print(dfObj['hash'])
``` |
28,952,282 | I'm using REPL with sublime text 3 (latest version as of today) and I'm coding in python 3.4. As far as I understand the documentation on REPL if do: tools>sublimeREPL>python>python-RUN current file
then I should run the code I have typed in using REPL. However when I do this I get an error pop up saying:
FileNotFo... | 2015/03/09 | [
"https://Stackoverflow.com/questions/28952282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4651552/"
] | I also had this problem. This is most probably due to the default location of python. If you are running portable python,
```
{
...
"default_extend_env": {"PATH": "{PATH}:\\Programming\\Python\\Portable Python 2.7.6.1\\App\\"}
...
}
```
Otherwise,
```
{
"default_extend_env": {"PATH":"C:\\python27\\"},
}
```
wou... | I had the same problem, when I installed REPL for the first time. Now, that could sound crazy, but the way to solve the problem (at least, the trick worked for me!) is to restart once Sublime Text 3.
**Update**: As pointed out by Mark in the comments, apparently you could have to restart Sublime more than once to solv... |
63,650,186 | Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my do... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] | You can change the separator to the empty string (the default is a space).
```
print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')
``` | Replace `,` with `+` because `,` leaves a space by default, for example:
```
print('Material cost of the project: $' + tot_mat)
print('Labor cost of the project: $' + tot_lab)
print('Total cost of the project: $' + project)
```
You can also use `f-strings` as so:
```
print(f'Material cost of the project: ${tot_ma... |
63,650,186 | Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my do... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] | Use below :
```
print('Total cost of the project: $'+str(project))
```
Note: I have converted project into string with str function as it’s float . You can use same for all. | Replace `,` with `+` because `,` leaves a space by default, for example:
```
print('Material cost of the project: $' + tot_mat)
print('Labor cost of the project: $' + tot_lab)
print('Total cost of the project: $' + project)
```
You can also use `f-strings` as so:
```
print(f'Material cost of the project: ${tot_ma... |
63,650,186 | Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my do... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] | You can change the separator to the empty string (the default is a space).
```
print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')
``` | You could try using fstring syntax as well (Assuming you're using Python 3)
```
print(f'Material cost of the project: ${tot_mat}')
``` |
63,650,186 | Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my do... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] | Use below :
```
print('Total cost of the project: $'+str(project))
```
Note: I have converted project into string with str function as it’s float . You can use same for all. | You could try using fstring syntax as well (Assuming you're using Python 3)
```
print(f'Material cost of the project: ${tot_mat}')
``` |
63,650,186 | Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my do... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] | You can change the separator to the empty string (the default is a space).
```
print('Material cost of the project: $', tot_mat, sep='')
print('Labor cost of the project: $', tot_lab, sep='')
print('Total cost of the project: $', project, sep='')
``` | In addition to other answers, also note that your code will crash if someone inputs something that is in any way incorrect (e. g. "3,9" will throw an error if you try to parse it as a float). Consider reading about `try/except`, catching and handling error in context of the `input()` function. |
63,650,186 | Sorry in advance for what I'm sure will be a very simple question to answer, I'm *very* new to python.
I have a project that I'm working on that takes inputs about the size of a room and cost of materials/installation and outputs costs and amount of materials needed.
I've got everything working but I can't make my do... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63650186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14188403/"
] | Use below :
```
print('Total cost of the project: $'+str(project))
```
Note: I have converted project into string with str function as it’s float . You can use same for all. | In addition to other answers, also note that your code will crash if someone inputs something that is in any way incorrect (e. g. "3,9" will throw an error if you try to parse it as a float). Consider reading about `try/except`, catching and handling error in context of the `input()` function. |
25,150,502 | Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because... | 2014/08/06 | [
"https://Stackoverflow.com/questions/25150502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794743/"
] | You can use [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) function, like this
```
for index, (key, value) in enumerate(mydict.items()):
print index, key, value
```
The `enumerate` function gives the current index of the item and the actual item itself. In this case, the second value i... | If you only need the index to do something special on the first iteration, you could also use `.popitem()`
```
key, val = mydict.popitem()
...
for key, val in mydict.items()
...
```
this will remove the first `key, val` pair from `mydict` (but perhaps that's not an issue for you?) |
25,150,502 | Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because... | 2014/08/06 | [
"https://Stackoverflow.com/questions/25150502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794743/"
] | You can use [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) function, like this
```
for index, (key, value) in enumerate(mydict.items()):
print index, key, value
```
The `enumerate` function gives the current index of the item and the actual item itself. In this case, the second value i... | ```
if mydict:
iterdict = mydict.iteritems()
firstkey, firstvalue = next(iterdict)
# do something special with first item
for key, value in iterdict:
# do something with the rest
``` |
25,150,502 | Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because... | 2014/08/06 | [
"https://Stackoverflow.com/questions/25150502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794743/"
] | If you only need the index to do something special on the first iteration, you could also use `.popitem()`
```
key, val = mydict.popitem()
...
for key, val in mydict.items()
...
```
this will remove the first `key, val` pair from `mydict` (but perhaps that's not an issue for you?) | ```
if mydict:
iterdict = mydict.iteritems()
firstkey, firstvalue = next(iterdict)
# do something special with first item
for key, value in iterdict:
# do something with the rest
``` |
47,799,275 | I need to be able to login into a remote server, switch user and then, do whatever it is required.
I played with ansible and found the "become" tool, so I tried it, after all... it allows dzdo.
My playbook became something like this:
```
- name: Create empty file
file: path=touchedFile.txt state=touch
become:... | 2017/12/13 | [
"https://Stackoverflow.com/questions/47799275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803228/"
] | I have finally found a work-around for my problem, and I'm sharing this answer in case someone finds it useful.
Ansible become module is great, but for my company it is not working. As I explained in the question, it is adding a "**-u root**" at the end of the sudo, which makes the whole command to fail.
I was able t... | This playbook works for me in ansible 2.4 for your limited test case, I'm not sure how well it would work against larger / more complex tasks or modules. It basically just works around your site's dzdo/sudo limitations.
```
---
- hosts: 127.0.0.1
become: yes
become_method: dzdo
become_flags: "su - root -c"
ga... |
12,113,498 | I'm trying to take the dot product of two lil\_matrix sparse matrices that are approx. 100,000 x 50,000 and 50,000 x 100,000 respectively.
```
from scipy import sparse
a = sparse.lil_matrix((100000, 50000))
b = sparse.lil_matrix((50000, 100000))
c = a.dot(b)
```
and getting this error:
```
File "/usr/lib64/python... | 2012/08/24 | [
"https://Stackoverflow.com/questions/12113498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1623172/"
] | This is a bad error message, but the "problem" quite simply is that your resulting matrix would be too big (has too many nonzero elements, not its dimension).
Scipy uses `int32` to store `indptr` and `indices` for the sparse formats. This means that your sparsematrix cannot have more then (approximatly) 2^31 nonzero e... | Just to add to @seberg's answer.
There are two issues related to this on github.com/scipy/scipy.
[Issue #1833](https://github.com/scipy/scipy/issues/1833#ref-issue-13651914) (marked closed April 2013) and [Issue #442](https://github.com/scipy/scipy/pull/442) with some pull requests that haven't been merged (Nov 2013 ... |
32,369,147 | I want to get the url of the link of tag. I have attached the class of the element to type selenium.webdriver.remote.webelement.WebElement in python:
```
elem = driver.find_elements_by_class_name("_5cq3")
```
and the html is:
```
<div class="_5cq3" data-ft="{"tn":"E"}">
<a class="_4-eo" hre... | 2015/09/03 | [
"https://Stackoverflow.com/questions/32369147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159284/"
] | Why not do it directly?
```
url = driver.find_element_by_class_name("_4-eo").get_attribute("href")
```
And if you need the div element first you can do it this way:
```
divElement = driver.find_elements_by_class_name("_5cq3")
url = divElement.find_element_by_class_name("_4-eo").get_attribute("href")
```
or anothe... | You can use xpath for same
If you want to take href of "a" tag, 2nd line according to your HTML code then use
```
url = driver.find_element_by_xpath("//div[@class='_5cq3']/a[@class='_4-eo']").get_attribute("href")
```
If you want to take href of "img" tag, 4nd line according to your HTML code then use
```
url = dr... |
32,369,147 | I want to get the url of the link of tag. I have attached the class of the element to type selenium.webdriver.remote.webelement.WebElement in python:
```
elem = driver.find_elements_by_class_name("_5cq3")
```
and the html is:
```
<div class="_5cq3" data-ft="{"tn":"E"}">
<a class="_4-eo" hre... | 2015/09/03 | [
"https://Stackoverflow.com/questions/32369147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5159284/"
] | Why not do it directly?
```
url = driver.find_element_by_class_name("_4-eo").get_attribute("href")
```
And if you need the div element first you can do it this way:
```
divElement = driver.find_elements_by_class_name("_5cq3")
url = divElement.find_element_by_class_name("_4-eo").get_attribute("href")
```
or anothe... | Use:
1)
`xpath` to specify the path to the `href` first.
```
x = '//a[@class="_4-eo"]'
k = driver.find_elements_by_xpath(x).get_attribute("href")
for url in k:
print url
```
2) Use @drkthng's solution(the simplest).
3)You can use:
```
parentElement = driver.find_elements_by_class("_4-eo")
elementList = parent... |
23,034,781 | I am using scrapy 0.20 with python 2.7
According to [scrapy architecture](http://doc.scrapy.org/en/latest/topics/architecture.html), the spider sends requests to the engine. Then, after the whole crawling process, the item goes through the item pipeline.
So, the item pipeline has nothing to do when the spider opens o... | 2014/04/12 | [
"https://Stackoverflow.com/questions/23034781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2038257/"
] | I had similar problem and then figured it out.
It is possible that all of your left-hand side values (V5) are the same. The error is thrown as a saying that no decision can be made as it is too easy.
My source: <http://kleinfelter.com/learning-r-painful-r-learnings> | After removing all 'NA', the problem has gone. Also, the first column has to be index column. |
10,145,201 | We moved our SQL Server 2005 database to a new physical server, and since then it has been terminating any connection that persist for 30 seconds.
We are experiencing this in Oracle SQL developer and when connecting from python using pyodbc
Everything worked perfectly before, and now python returns this error after 30... | 2012/04/13 | [
"https://Stackoverflow.com/questions/10145201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931235/"
] | First of all what you need is profile the sql server to see if any activity is happening. Look for slow running queries, CPU and memory bottlenecks.
Also you can include the timeout in the querystring like this:
"Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI;Connection Timeout=30";
and... | Maybe check your remote query timeout? It should default to 600, but maybe it's set to 30? [Info here](http://msdn.microsoft.com/en-us/library/ms189040%28v=sql.90%29.aspx) |
18,921,141 | I keep getting an error that there's no such module.
The project name is gmblnew, and I have two subfolders- `core` and `gmblnew` - the app I'm working on is core.
My **urls.py** file is
```
from django.conf.urls import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.a... | 2013/09/20 | [
"https://Stackoverflow.com/questions/18921141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293222/"
] | Your problem is here:
```
url(r'^league/', include('core.views.league')),
```
By using `include` you are specifying a module, which does not exist.
[`include` is used to include other url confs](https://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs), and not to target view methods
What y... | `include` takes a path to a url file, not a view. Just write this instead:
```
url(r'^league/', 'core.views.league'),
``` |
8,575,713 | I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from ... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23457/"
] | I'm guessing you are going to mock the function `returnBar`, you'd like to use [`patch` decorator](http://www.voidspace.org.uk/python/mock/patch.html):
```
from mock import patch
from foo import printFoo
@patch('foo.returnBar')
def test_printFoo(mockBar):
mockBar.return_value = 'Foo'
printFoo()
test_printFo... | Just import the `bar` module before the `foo` module and mock it:
```
from mock import Mock
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
from foo import printFoo
printFoo()
```
When you are importing the `returnBar` in `foo.py`, you are binding the value of the module to a variable called `retu... |
8,575,713 | I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from ... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23457/"
] | Just import the `bar` module before the `foo` module and mock it:
```
from mock import Mock
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
from foo import printFoo
printFoo()
```
When you are importing the `returnBar` in `foo.py`, you are binding the value of the module to a variable called `retu... | Another way to deal with those case is to use some dependency injection.
An easy way to do it in python is to use the magical `**kwargs` :
foo.py
```
from dirBar.bar import returnBar
def printFoo(**kwargs):
real_returnBar = kwargs.get("returnBar", returnBar)
print real_returnBar()
```
test.py
```
from ... |
8,575,713 | I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from ... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23457/"
] | I'm guessing you are going to mock the function `returnBar`, you'd like to use [`patch` decorator](http://www.voidspace.org.uk/python/mock/patch.html):
```
from mock import patch
from foo import printFoo
@patch('foo.returnBar')
def test_printFoo(mockBar):
mockBar.return_value = 'Foo'
printFoo()
test_printFo... | Another way to deal with those case is to use some dependency injection.
An easy way to do it in python is to use the magical `**kwargs` :
foo.py
```
from dirBar.bar import returnBar
def printFoo(**kwargs):
real_returnBar = kwargs.get("returnBar", returnBar)
print real_returnBar()
```
test.py
```
from ... |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get insta... | Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
``` |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get insta... | If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb` |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get insta... | ```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04* |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | Like the warning says:
```none
Couldn't find ffplay or avplay - defaulting to ffplay, but may not work
```
You need to have either `ffplay` or `avplay`; however `ffplay` refers to `ffmpeg` which is not installable in Ubuntu in recent versions. Install the `libav-tools` package with `apt-get`:
```
sudo apt-get insta... | I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can a... |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
``` | If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb` |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | ```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04* | Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
``` |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | Seems like you need ffmpeg, but
```
sudo apt-get install ffmpeg
```
does not work anymore. You can get ffmpeg by:
```
sudo add-apt-repository ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
``` | I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can a... |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | ```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04* | If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb` |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can a... | If it won't let you install using `sudo apt-get install libav-tools` You can [download the .deb from here](https://launchpad.net/ubuntu/bionic/amd64/libav-tools/7:3.3.4-2):
`wget http://launchpadlibrarian.net/339874908/libav-tools_3.3.4-2_all.deb`
Then run `sudo apt install ./libav-tools_3.3.4.2_all.deb` |
29,454,002 | I'm new in python and i'm using `pydub` modules to play mp3 track.
Here is my simple code to play mp3:
```
#Let's play some mp3 files using python!
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_mp3("/media/rajendra/0C86E11786E10256/05_I_Like_It_Rough.mp3")
play(song)
```
... | 2015/04/05 | [
"https://Stackoverflow.com/questions/29454002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4750748/"
] | ```
sudo apt-get install ffmpeg
```
*Note: Tested on Ubuntu 18.04* | I've faced the same problem on my Ubuntu Ubuntu 18.04.3 LTS.
The issue is being solved by simply installing ffmpeg using:
```
sudo apt-get install ffmpeg
```
Instead of the popular Git-thread (<https://github.com/lengstrom/fast-style-transfer/issues/129>) suggestion of:
```
brew install ffmpeg
```
But you can a... |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
``` | You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.t... |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.t... | Firstly you can store the indices of `'a'` from the list.
```
oList = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
idx_a = list()
for idx, char in enumerate(oList):
if char == 'a':
idx_a.append(idx)
```
Then for every consecutive indices you can get the sub-list and store it in a l... |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.t... | You can do this with a single iteration and a simple state machine:
```
original_list = list('kabcadeabefjacab')
multiple_lists = []
for c in original_list:
if multiple_lists:
multiple_lists[-1].append(c)
if c == 'a':
multiple_lists.append([c])
if multiple_lists[-1][-1] != 'a':
multiple_li... |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | You can do this in one loop:
```
lst = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
out = [[]]
for i in lst:
if i == 'a':
out[-1].append(i)
out.append([])
out[-1].append(i)
out = out[1:] if out[-1][-1] == 'a' else out[1:-1]
```
Also using `numpy.split`:
```
out = [ary.t... | We can use `str.split()` to split the list once we `str.join()` it to a string, and then use a f-string to add back the stripped "a"s. Note that even if the list starts/ends with an "a", this the split list will have an empty string representing the substring before the split, so our unpacking logic that discards the f... |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
``` | Firstly you can store the indices of `'a'` from the list.
```
oList = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
idx_a = list()
for idx, char in enumerate(oList):
if char == 'a':
idx_a.append(idx)
```
Then for every consecutive indices you can get the sub-list and store it in a l... |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
``` | You can do this with a single iteration and a simple state machine:
```
original_list = list('kabcadeabefjacab')
multiple_lists = []
for c in original_list:
if multiple_lists:
multiple_lists[-1].append(c)
if c == 'a':
multiple_lists.append([c])
if multiple_lists[-1][-1] != 'a':
multiple_li... |
70,375,415 | For example the original list:
`['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']`
We want to split the list into lists started with `'a'` and ended with `'a'`, like the following:
`['a','b','c','a']`
`['a','d','e','a']`
`['a','b','e','f','j','a']`
`['a','c','a']`
The final ouput can also be a li... | 2021/12/16 | [
"https://Stackoverflow.com/questions/70375415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4143312/"
] | One possible solution is using `re` (regex)
```
import re
l = ['k','a','b','c','a','d','e','a','b','e','f','j','a','c','a','b']
r = [list(f"a{_}a") for _ in re.findall("(?<=a)[^a]+(?=a)", "".join(l))]
print(r)
# [['a', 'b', 'c', 'a'], ['a', 'd', 'e', 'a'], ['a', 'b', 'e', 'f', 'j', 'a'], ['a', 'c', 'a']]
``` | We can use `str.split()` to split the list once we `str.join()` it to a string, and then use a f-string to add back the stripped "a"s. Note that even if the list starts/ends with an "a", this the split list will have an empty string representing the substring before the split, so our unpacking logic that discards the f... |
55,697,976 | I have this input `<input type="file" id="file" name="file" accept="image/*" multiple>` this allow the user select several images and I need to pass all of them to my `FormData` so I do this:
```
var formdata = new FormData();
var files = $('#file')[0].files[0];
formdata.append('file',files);
```
But that only take ... | 2019/04/15 | [
"https://Stackoverflow.com/questions/55697976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5727540/"
] | There are many problems:
1. You can't redeclare the same variable if you want to keep its previous values
2. You need to change the index so that it's not saving to the same spot
3. $("#file") - shouldn't be an array, it's an object so i'm surprised it's not throwing an error
Let's say your code is legit. You could d... | This was my solution
```
var formdata = new FormData();
var files=[];
var count = document.getElementById('file').files.length;
for (i = 0; i < cont; i++) {
files[i] = document.getElementById('file').files[i];
formdata.append('file',files[i]);
}
```
Using `JQuery` for length only brings me 1 element and give... |
6,965,431 | I'm attempting to use GAE TaskQueue's REST API to pull tasks from a queue to an external server (a server not on GAE).
* Is there a library that does this for me?
* The API is simple enough, so I just need to figure out authentication. I examined the request sent by `gtaskqueue_sample` from `google-api-python-client` ... | 2011/08/06 | [
"https://Stackoverflow.com/questions/6965431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | These APIS work only for GAE server since the queues can be created only via queue.yaml and infact API does not expose any API for inserting queue and tasks or project. | The pull queues page has a [whole section](http://code.google.com/appengine/docs/python/taskqueue/overview-pull.html#Pulling_Tasks_from_Outside_App_Engine) about client libraries and sample code. |
6,965,431 | I'm attempting to use GAE TaskQueue's REST API to pull tasks from a queue to an external server (a server not on GAE).
* Is there a library that does this for me?
* The API is simple enough, so I just need to figure out authentication. I examined the request sent by `gtaskqueue_sample` from `google-api-python-client` ... | 2011/08/06 | [
"https://Stackoverflow.com/questions/6965431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | This question is old, but it still applies, so I am going to attempt a better answer based on my recent experience.
It is possible to access pull task queues outside of appengine but as the asker stated, there are no good examples, so here is a more in depth guide. In my case I had a custom python script that needed t... | The pull queues page has a [whole section](http://code.google.com/appengine/docs/python/taskqueue/overview-pull.html#Pulling_Tasks_from_Outside_App_Engine) about client libraries and sample code. |
6,965,431 | I'm attempting to use GAE TaskQueue's REST API to pull tasks from a queue to an external server (a server not on GAE).
* Is there a library that does this for me?
* The API is simple enough, so I just need to figure out authentication. I examined the request sent by `gtaskqueue_sample` from `google-api-python-client` ... | 2011/08/06 | [
"https://Stackoverflow.com/questions/6965431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | This question is old, but it still applies, so I am going to attempt a better answer based on my recent experience.
It is possible to access pull task queues outside of appengine but as the asker stated, there are no good examples, so here is a more in depth guide. In my case I had a custom python script that needed t... | These APIS work only for GAE server since the queues can be created only via queue.yaml and infact API does not expose any API for inserting queue and tasks or project. |
18,401,385 | I'm using Eclipse (on the PyDev perspective), and I just installed (using pip) the python 'requests' module.
Eclipse is giving me an error warning on the 'import requests' line, saying that it is an unresolved import, but I've run it it imports just fine. (But the error message won't go away).
Its really bugging me... | 2013/08/23 | [
"https://Stackoverflow.com/questions/18401385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2258464/"
] | Sometimes, PyDev is a little buggy... When it happens, I usually right-click on the folder containing the file in the PyDev Package Explorer, then "PyDev->remove error markers". And then re-run code analysis.
If it still doesn't work, try removing and adding again the directory to your `requests` module to the PyDev P... | You should manually configure properties of you PyDev project.
Right click on your project name, select **PyDev - PYTHONPATH**, then in External Libraries tab press **Add source folder** and choose the root directory of your library. |
71,792,025 | My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't ... | 2022/04/08 | [
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] | It also happen to me. For me, it because `DOMContentLoaded` callback triggered twice.
My fix just make sure the container rendered only once.
```js
let container = null;
document.addEventListener('DOMContentLoaded', function(event) {
if (!container) {
container = document.getElementById('root1') as HTMLElement... | The answer is inside the warning itself.
>
> You are calling ReactDOMClient.createRoot() on a **container** that has
> already been passed to createRoot() **before**.
>
>
>
The root cause of the warning at my end is that the same DOM element is used to create the root more than once.
To overcome the issue it is ... |
71,792,025 | My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't ... | 2022/04/08 | [
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] | You're likely importing something from your entrypoint file, causing the entry point file to somehow run twice. I've had the same issue and solved it by making sure I was not importing anything from my entrypoint file. | The answer is inside the warning itself.
>
> You are calling ReactDOMClient.createRoot() on a **container** that has
> already been passed to createRoot() **before**.
>
>
>
The root cause of the warning at my end is that the same DOM element is used to create the root more than once.
To overcome the issue it is ... |
71,792,025 | My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't ... | 2022/04/08 | [
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] | I don't know if it's a good way, but you might consider to pass created root as properties (`props`) to the target component to get rid of the warning.
For example;
in the **index.js**
```
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// pass created root as... | The answer is inside the warning itself.
>
> You are calling ReactDOMClient.createRoot() on a **container** that has
> already been passed to createRoot() **before**.
>
>
>
The root cause of the warning at my end is that the same DOM element is used to create the root more than once.
To overcome the issue it is ... |
71,792,025 | My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't ... | 2022/04/08 | [
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] | It also happen to me. For me, it because `DOMContentLoaded` callback triggered twice.
My fix just make sure the container rendered only once.
```js
let container = null;
document.addEventListener('DOMContentLoaded', function(event) {
if (!container) {
container = document.getElementById('root1') as HTMLElement... | You're likely importing something from your entrypoint file, causing the entry point file to somehow run twice. I've had the same issue and solved it by making sure I was not importing anything from my entrypoint file. |
71,792,025 | My bots doesn't queue the songs when i use the play command, it just plays them. Im trying to get all my commands to work before using spotify & soundcloud in the bot.So, when i use the play command & I try to queue the songs, I cannot queue them. So, can anyone help me ? I have checked the wavelink doc but I couldn't ... | 2022/04/08 | [
"https://Stackoverflow.com/questions/71792025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18384528/"
] | It also happen to me. For me, it because `DOMContentLoaded` callback triggered twice.
My fix just make sure the container rendered only once.
```js
let container = null;
document.addEventListener('DOMContentLoaded', function(event) {
if (!container) {
container = document.getElementById('root1') as HTMLElement... | I don't know if it's a good way, but you might consider to pass created root as properties (`props`) to the target component to get rid of the warning.
For example;
in the **index.js**
```
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
// pass created root as... |
51,539,051 | I'm actually trying to send pictures(.jpg) saved on a directory of my computer to a FTP server with a python script and ftplib .
The path where are the images is : "D:/directory\_image".
I use python 2.7 and the command .storbinary from ftplib to send .jpg.
Despite my search, I get an error message that I can't resolve... | 2018/07/26 | [
"https://Stackoverflow.com/questions/51539051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10138893/"
] | [`@Transactional` can't work on private method](https://stackoverflow.com/questions/4396284/does-spring-transactional-attribute-work-on-a-private-method) because it's applied using an aspect (using dynamic proxies)
Basically you want the `retrieveAndSaveInformationFromBac()` to be a single unit of work, ie. a transact... | Since you are using `Hibernate` , you can handle this by a property:
```
<property name="hibernate.connection.autocommit">false</property>
```
Then you can commit with the transaction, like
```
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
//do stuff and then
tx.commi... |
40,499,481 | I configured a new debug environment in Visual Studio Code under OS X.
```
{
"name": "Kivy",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"pythonPath": "/Applications/Kivy3.app/Contents/Frameworks/python/3.5.0/bin",
"program": "${file}",
"debugOptions": [
"WaitOnAbno... | 2016/11/09 | [
"https://Stackoverflow.com/questions/40499481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1321025/"
] | @Albert Gao,
The path you have specified above doesn't contain the name of the python file. You need to provide the path to the file, include the file name. I believe you need to change it as follows:
`"pythonPath": "/Applications/Kivy3.app/Contents/Frameworks/python/3.5.0/bin/python",`
If that doesn't work, then ... | If you are getting the spawn error above while using **OpenOCD** for the Raspberry Pi Pico, make sure that your "**cortex-debug.openocdPath**" in "*settings.json*" is set to "*<Path\_to\_openocd\_executable>***/openocd**" for example:
`"cortex-debug.openocdPath": "/home/vbhunt/pico/openocd/src/openocd", "cortex-debug.... |
24,043,499 | Could any please help me convert this to python? I don't how to translate the conditional operators from C++ into python?
```
Math.easeInExpo = function (t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
``` | 2014/06/04 | [
"https://Stackoverflow.com/questions/24043499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461304/"
] | ```
def easeInExpo( t, b, c, d ):
return b if t == 0 else c * pow( 2, 10 * (t/d - 1) ) + b
``` | Use `if` / `else`:
```
return b if t == 0 else c * pow(2, 10 * (t/d - 1)) +b
``` |
24,043,499 | Could any please help me convert this to python? I don't how to translate the conditional operators from C++ into python?
```
Math.easeInExpo = function (t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
``` | 2014/06/04 | [
"https://Stackoverflow.com/questions/24043499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461304/"
] | ```
def easeInExpo( t, b, c, d ):
return b if t == 0 else c * pow( 2, 10 * (t/d - 1) ) + b
``` | ```
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
```
is equivalent to:
```
if (t == 0)
{
return b;
}
else
{
return c * Math.pow(2, 10 * (t/d - 1)) + b;
}
```
Hopefully that's enough to get you started. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.