qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
13,993,617 | I am currently using Python v2.6 and trying to merge words into a line. My code supposed to read data from a text file, in which I have two rows of data both of which are strings. Then, it takes the second row data every time, which are the words of sentences, those are separated by delimiter strings, such that:
Insid... | 2012/12/21 | [
"https://Stackoverflow.com/questions/13993617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1839494/"
] | ```
def foo(lines):
output = []
for line in lines:
words = line.split()
if len(words) < 2:
word = words[0]
else:
word = words[1]
if word == '</S>+ESTag':
yield ' '.join(output)
output = []
elif word != '<S>+BSTag':
... | I think the problem is that the script isn't being executed (unless you just excluded the [shebang](http://docs.python.org/2/using/unix.html#miscellaneous) in the code you posted)
Try this
```
cat file.txt | python script.py | less
``` | 14,788 |
47,177,112 | I manually create PySpark DataFrame as follows:
```
acdata = sc.parallelize([
[('timestamp', 1506340019), ('pk', 111), ('product_pk', 123), ('country_id', 'FR'), ('channel', 'web')]
])
# Convert to tuple
acdata_converted = acdata.map(lambda x: (x[0][1], x[1][1], x[2][1]))
# Define schema
acschema = StructType([
... | 2017/11/08 | [
"https://Stackoverflow.com/questions/47177112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7316807/"
] | You need to map all 5 fields to match with the schema defined.
```
acdata_converted = acdata.map(lambda x: (x[0][1], x[1][1], x[2][1], x[3][1], x[4][1]))
``` | I'd do it this way:
```
acdata = sc.parallelize([{'timestamp': 1506340019, 'pk': 111, 'product_pk': 123, 'country_id': 'FR', 'channel': 'web'}, {...}])
# Define schema
acschema = StructType([
StructField("timestamp", LongType(), True),
StructField("pk", LongType(), True),
StructField("product_pk", LongTyp... | 14,789 |
70,828,210 | I have `Django` project and want to look the another db (not default db created by `Php Symfony`)
Django can set up two DB in `settins.py`
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
"NAME": config("DB_NAME"),
"USER": config("DB_USER"),
"PASSWORD": config("... | 2022/01/24 | [
"https://Stackoverflow.com/questions/70828210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942868/"
] | You may be looking for the [`managed = false`](https://docs.djangoproject.com/en/4.0/ref/models/options/#django.db.models.Options.managed) meta setting on your models. That will cause Django not to try to manage those models (such as creating migrations for them). It's commonly used when working with externally managed... | I think what you need do is run
```
python manage.py migrate --database extern
``` | 14,790 |
43,433,406 | I am trying to run app not written by me app.
When I write
`python manage.py makemigrations`
I got:
```
Traceback (most recent call last):
File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
return self.cursor.execute(sql,... | 2017/04/16 | [
"https://Stackoverflow.com/questions/43433406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2950593/"
] | I had the same issue while using **Python 3.6.5** and **Django==2.1.7** on **Mac OS 10.15.2**. I fixed it by manually creating the table `django_content_type` with the columns: `id, app_label, model`
On running `python manage.py migrate` and the error appears, there should be a `*.sqlite3` file created on the path spe... | It seems like I was using python 3x
And this app was written using python 2x | 14,793 |
20,492,625 | I've written tests for my python code and want to check how much % is covered with tests, so I decided to use python coverage. But I have a problem launching it. I launch my tests with this bash command:
```
export PYTHONPATH=. && python files/test/tests.py
```
My python program is in "files" directory, and tests ar... | 2013/12/10 | [
"https://Stackoverflow.com/questions/20492625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2876296/"
] | The correct way to do this is to use an appropriate **coverage** plugin for the unit testing framework/runner you are using:
Here are some combinations:
* [pytest](http://pytest.org/latest/) + [pytest-cov](https://pypi.python.org/pypi/pytest-cov)
* [nose](https://pypi.python.org/pypi/nose/1.3.0) + [nose-cov](https://... | ```
coverage run files/test/tests.py
``` | 14,796 |
53,129,263 | Depend on this tutorials [grpc basic](https://grpc.io/docs/tutorials/basic/python.html)
I clone `https://github.com/grpc/grpc` to local,
`cd example/python/helloworld`
start server `python greeter_server.py`
then start client `python greeter_client.py`,
but get error
```
Traceback (most recent call last):
File... | 2018/11/03 | [
"https://Stackoverflow.com/questions/53129263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6449456/"
] | 1. I found I set a global http proxy `export http_proxy=http://127.0.0.1:1087`, I closed this proxy, then It was find.
2. update `greeter_client.py`, change `localhost` to `127.0.0.1`. It's find to me. | Could you try few options and share your feedback:
**Option - 1**
another port(except 50051) in [client](https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_client.py) and [server](https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_server.py#L36)?
**Option-2**
Try wi... | 14,797 |
41,434,350 | I work on a project and I want to download a csv file from a url. I did some research on the site but none of the solutions presented worked for me.
The url offers you directly to download or open the file of the blow I do not know how to say a python to save the file (it would be nice if I could also rename it)
But ... | 2017/01/02 | [
"https://Stackoverflow.com/questions/41434350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6435119/"
] | Try this. Change "folder" to a folder on your machine
```
import os
import requests
url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'
response = requests.get(url)
with open(os.path.join("folder", "file"), 'wb') as f:
f.write(response.content)
``` | You can adapt an example from [the docs](https://docs.python.org/3/howto/urllib2.html)
```
import urllib.request
url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'
with urllib.request.urlopen(url) as testfile, open('dataset.csv', 'w') as f:
f.write(t... | 14,798 |
35,780,768 | I am getting this message when I try to install aws. Anyone have any ideas of what's going on?
```
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip/commands/i... | 2016/03/03 | [
"https://Stackoverflow.com/questions/35780768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5505587/"
] | Pure virtual functions will never cause anything to fail during linking. Instead, pure virtual functions will cause a compilation error if you try to instantiate the object of an abstract type.
Reminder - an abstract type is a type which has (directly or indirectly through inheritance) at least one pure virtual functi... | This may compile or build, if the solution has been previously built. This means that it is using old object code. Try to do a clean build of your solution, then rebuild it. Once your solution is cleaned. Then try to compile the inherited class. Another thing that may be of concern is that you have declared your inheri... | 14,799 |
33,312,175 | I want to use [`re.MULTILINE`](https://docs.python.org/2/library/re.html#re.MULTILINE) but **NOT** [`re.DOTALL`](https://docs.python.org/2/library/re.html#re.DOTALL), so that I can have a regex that includes both an "any character" wildcard and the normal `.` wildcard that doesn't match newlines.
Is there a way to do ... | 2015/10/23 | [
"https://Stackoverflow.com/questions/33312175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | To match a newline, or "any symbol" without `re.S`/`re.DOTALL`, you may use any of the following:
1. `(?s).` - the [inline modifier group](https://www.regular-expressions.info/modifiers.html) with `s` flag on sets a scope where all `.` patterns match any char including line break chars
2. Any of the following work-aro... | Match any character (including new line):
-----------------------------------------
Regular Expression: (Note the use of space ' ' is also there)
```
[\S\n\t\v ]
```
Example:
--------
```
import re
text = 'abc def ###A quick brown fox.\nIt jumps over the lazy dog### ghi jkl'
# We want to extract "A quick brown fo... | 14,801 |
66,880,698 | I have a notebook that runs overnight, and prints out a bunch of stuff, including images and such. I want to cause this output to be saved programatically (perhaps at certain intervals). I also want to save the code that was run. In a Jupyter notebook, you could do:
```
from IPython.display import display, Javascript
... | 2021/03/31 | [
"https://Stackoverflow.com/questions/66880698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11632499/"
] | You can use [ipylab](https://github.com/jtpio/ipylab) to access JupyterLab API from Python. To save the notebook just invoke the `docmanager:save` command:
```py
from ipylab import JupyterFrontEnd
app = JupyterFrontEnd()
app.commands.execute('docmanager:save')
```
You can get the full list of commands with `app.com... | JupyterLab has a bulit-in auto-save function. You can configure the time interval using the Advanced Settings Editor, the Document Manager section (see screenshot below).
[](https://i.stack.imgur.com/01vR4.png)
However, if you *really* want a JavaScript solution ... | 14,802 |
42,103,367 | I am using multiprocessing.Pool.imap to run many independent jobs in parallel using Python 2.7 on Windows 7. With the default settings, my total CPU usage is pegged at 100%, as measured by Windows Task Manager. This makes it impossible to do any other work while my code runs in the background.
I've tried limiting the ... | 2017/02/08 | [
"https://Stackoverflow.com/questions/42103367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4410133/"
] | The solution depends on what you want to do. Here are a few options:
Lower priorities of processes
-----------------------------
You can [`nice`](https://en.wikipedia.org/wiki/Nice_(Unix)) the subprocesses. This way, though they will still eat 100% of the CPU, when you start other applications, the OS gives preferenc... | **On the OS level
---------------**
you can use `nice` to set a priority to a single command. You could also start a python script with nice. (Below from: <http://blog.scoutapp.com/articles/2014/11/04/restricting-process-cpu-usage-using-nice-cpulimit-and-cgroups>)
>
> **nice**
>
>
> The nice command tweaks the pr... | 14,805 |
16,867,347 | From what I have read, there are two ways to debug code in Python:
* With a traditional debugger such as `pdb` or `ipdb`. This supports commands such as `c` for `continue`, `n` for `step-over`, `s` for `step-into` etc.), but you don't have direct access to an IPython shell which can be extremely useful for object insp... | 2013/05/31 | [
"https://Stackoverflow.com/questions/16867347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] | (Update on May 28, 2016) Using RealGUD in Emacs
===============================================
For anyone in Emacs, [this thread](https://github.com/rocky/emacs-dbgr/issues/96) shows how to accomplish everything described in the OP (and more) using
1. a new important debugger in Emacs called **RealGUD** which can op... | Running from inside Emacs' IPython-shell and breakpoint set via pdb.set\_trace() should work.
Checked with python-mode.el, M-x ipython RET etc. | 14,808 |
43,149,637 | I have string in python containing a large text file (over 1MiB).
I need to split it to chunks.
Constrains:
* chunks can be splited only by newline character, and
* len(chunk) must be as big as possbile but smaller than LIMIT (i.e. 100KiB)
Lines longer than LIMIT can be ommited.
Any idea how to implement this nicel... | 2017/03/31 | [
"https://Stackoverflow.com/questions/43149637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/705676/"
] | Following the suggestion of Linuxios you could use rfind to find the last newline within the limit and split at this point. If no newline character is found the chunk is too large and can be dismissed.
```
chunks = []
not_chunked_text = input_text
while not_chunked_text:
if len(not_chunked_text) <= LIMIT:
... | Here is my not-so-pythonic solution:
```
def line_chunks(lines, chunk_limit):
chunks = []
chunk = []
chunk_len = 0
for line in lines:
if len(line) + chunk_len < chunk_limit:
chunk.append(line)
chunk_len += len(line)
else:
chunks.append(chunk)
... | 14,818 |
12,905,300 | I am trying to develop an application that creates an image and fills it with color pixels using bilinear interpolation and then displays it. My code so far is the following:
```
#include <QtCore/QCoreApplication>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
#include <string>
#include <sys/st... | 2012/10/15 | [
"https://Stackoverflow.com/questions/12905300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178770/"
] | The following code is almost the same as William answered, but without using 'for' loop statement.
```
subdirs := A B C
.PHONY: all $(subdirs)
all: $(subdirs)
$(subdirs):
$(MAKE) -C $@
``` | I'm rusty on makefiles and know for sure the following is not the best answer. But it might help for now...
```
TARGETS = A B C
.phoney: all
all:
@for subdir in $(TARGETS); do \
$(MAKE) -C $$subdir all || exit 1; \
done
```
Note that the indents must use a TAB, not spaces | 14,819 |
23,332,259 | I am trying to copy a sheet, `default_sheet`, into a new sheet `new_sheet` in the same workbook.
I did managed to create a new sheet and to copy the values from default sheet. How can I also copy the style of each cell into the new\_sheet cells?
```python
new_sheet = workbook.create_sheet()
new_sheet.title = sheetNam... | 2014/04/28 | [
"https://Stackoverflow.com/questions/23332259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458191/"
] | As of openpyxl 2.5.4, python 3.4: (subtle changes over the older version below)
```python
new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']
from copy import copy
for row in default_sheet.rows:
for cell in row:
new_cell = new_sheet.cell(row=cell.row, column=cell.col_idx,
... | May be this is the convenient way for most.
```
from openpyxl import load_workbook
from openpyxl import Workbook
read_from = load_workbook('path/to/file.xlsx')
read_sheet = read_from.active
write_to = Workbook()
write_sheet = write_to.active
write_sheet['A1'] = read_sheet['A1'].value
wr... | 14,820 |
19,322,350 | I am trying to use f2py to interface my python programs with my Fortran modules.
I am on a Win7 platform.
I use latest Anaconda 64 (1.7) as a Python+NumPy stack.
My Fortran compiler is the latest Intel Fortran compiler 64 (version 14.0.0.103 Build 20130728).
I have been experiencing a number of issues when executin... | 2013/10/11 | [
"https://Stackoverflow.com/questions/19322350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2866568/"
] | I encountered similar problems with my own code some time ago. If I understand the comments correctly you already used the approach that worked for me, so this is just meant as clarification and summary for all those that struggle with f2py and dependencies:
f2py seems to have problems resolving dependecies on externa... | The library path is specified using /LIBPATH not /L | 14,823 |
49,739,245 | I have spent a good amount of time trying to determine what is going wrong exactly, with the code I am using to convert pdf to docx (and doc to docx) using LibreOffice.
I have used both the windows run interface to test-run some of the code I have found to be relevant, and have tried on python as well, neither of whic... | 2018/04/09 | [
"https://Stackoverflow.com/questions/49739245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8492478/"
] | There are a number of problems here. You should first get the `--convert-to` call to work from the command line as @CristiFati commented, and then implement in python.
Here is the code that works on my system. No `//` in the path, and quotes are needed. Also, the folder is `LibreOffice 5` on my system.
```
import sub... | Install pdf2docx package in python
```
source = r'C:\Users\sdDesktop\New Project/Document2.pdf'
destination = r'C:\Users\sd\Desktop\New Project/sample_6.docx'
def Converter_pdf2docx(source,destination):
pdf_file = source
docx_file = destination
cv = Converter(pdf_file)
cv.convert(docx_file, star... | 14,824 |
63,648,764 | I have a program folder for which paths are required:
```
export RBT_ROOT=/path/to/installation/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$RBT_ROOT/lib
export PATH=$PATH:$RBT_ROOT/bin
```
Then the command is run:
```
rbcavity -was -d -r <PRMFILE>
```
rbcavity - is an exe program contained in the program's bin fold... | 2020/08/29 | [
"https://Stackoverflow.com/questions/63648764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12399859/"
] | The issue is that the website filters out requests without a proper `User-Agent`, so just use a random one from MDN:
```py
requests.get("https://apis.digital.gob.cl/fl/feriados/2020", headers={
"User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
})... | It might be due to idle timeout. Overriding default socket options can help
```
import socket
from urllib3.connection import HTTPConnection
HTTPConnection.default_socket_options = (
HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
(socket.SOL_TCP, socket.TCP_K... | 14,825 |
28,999,913 | Is there a 'correct' or preferred manner for sending data over a web socket connection?
In my case, I am sending the information from a C# application to a python (tornado) web server, and I am simply sending a string consisting of several elements separated by commas. In python, I use rudimentary techniques to split ... | 2015/03/12 | [
"https://Stackoverflow.com/questions/28999913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190200/"
] | Writing a *custom* encoding (eg, as "k,v,..") is *different* than 'using binary'.
*It is still text*, just a rigid under-defined one-off hand-rolled format that must be manually replicated. (What happens if a key or value contains a comma? What happens if the data needs to contain nested objects? How can null be inte... | First advice would be to use the same format for both ways, not plain text in one direction and JSON in the other.
I personally think `{'foo':0,'bar':1}` is better than `foo,0,bar,1` because everybody understands JSON but for your custom format they might not without some explanations. The idea is you are inventing a... | 14,826 |
33,006,474 | In the cloud, I have multiple instances, each running a container with a different random name, e.g.:
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5dc97950d924 aws_beanstalk/my-app:latest "/bin/sh -... | 2015/10/08 | [
"https://Stackoverflow.com/questions/33006474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478354/"
] | "the correct container"?
To determine what is the "correct" container, your bash script would still need either the id or the name of that container.
For example, I [have a function in my `.bashrc`](https://github.com/VonC/b2d/blob/f9890cb6e1ee14842b8be2dd66a754550db793a9/.bash_aliases#L54):
```
deb() { docker exec ... | Here's my final solution. It edits the instance's .bashrc if it hasn't been edited yet, prints out docker ps, defines the dock function, and enters the container. A user can then type "exit" if they want to access the raw instances, and "exit" again to quit ssh.
```
commands:
bashrc:
command: if ! grep -Fxq "su... | 14,827 |
32,488,029 | I'm using django-twilio to try and respond to text messages coming from Twilio account. As it recommends using the twilio\_View decorator to imrove upon @csrf\_exempt, I'm using it. Problem is, it doesnt work. No matter what I try, I always get 403.
Things I've done:
1. Twilio test account. Added TWILIO\_ACCOUNT\_SID ... | 2015/09/09 | [
"https://Stackoverflow.com/questions/32488029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1907157/"
] | Twilio team member here.
Are you importing twiml? Try making the first line of your say-hello function:
```
r = twiml.Response()
``` | I don't see anything obviously wrong in what you are doing, so I would suggest removing the `@twilio_view` decorator and logging the X-Twilio-Signature header in your view to see what it is and manually checking to see if it's correct. (Basically, redoing the logic of the `@twilio_view` decorator in your view, just to ... | 14,829 |
60,286,928 | I am learning Python (python3) and am working with a text file containing semi-JSON format. It is not full JSON because the "keys" are not surrounded by quotes. I am looking to programmatically add quotes around all of these key names. My plan was to "open" this file and parse each "line" as an individual string.
**F... | 2020/02/18 | [
"https://Stackoverflow.com/questions/60286928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8729789/"
] | Avoid using regex to handle structured formats. It will almost always mis-handle certain corner cases.
Since your input is valid YAML, you can install [PyYAML](https://pypi.org/project/PyYAML/), load the input as YAML, and dump the data structure as JSON instead:
```
import yaml
import json
s = 'key_name: { another_k... | While the pattern `([{,]\s*)([^"]*?)(\s*:\s*)` isn't going to cover all corner cases, it should work fine for basic JSON content.
Example usage:
```
>>> import re
>>> data = '{ another_key: "somevalue", second_key: "anotherval" }'
>>> repl_fn = lambda x: f'{x.group(1)}"{x.group(2)}"{x.group(3)}'
>>> re.sub(r'([{,]\s*... | 14,830 |
57,701,538 | I have a `Jupyter` notebook and I'd like to convert it into a `Python` script using the `nbconvert` command from *within* the `Jupyter` notebook.
I have included the following line at the end of the notebook:
```
!jupyter nbconvert --to script <filename>.ipynb
```
This creates a `Python` script. However, I'd like t... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57701538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2957960/"
] | One way to get control of what appears in the output is to tag the cells that you don't want in the output and then use the TagRemovePreprocessor to remove the cells.
[](https://i.stack.imgur.com/gvqcA.png)
The code below also uses the exclude\_markd... | Jupyter nbconvert has made this a little bit easier with a new [template structure](https://nbconvert.readthedocs.io/en/latest/customizing.html).
Templates should be placed in the template path. This can be found by running `jupyter --paths`
Each template should be placed in its own directory within the template dire... | 14,831 |
29,578,217 | I made sure to try installing PyQt4 on mac in many different ways, but I always get the error above.
My attempts have in common installing Python 3.4 from the official website installer, then installing Qt4 from [here](https://download.qt.io/archive/qt/4.8/4.8.6/) and finally installing SIP from the package available i... | 2015/04/11 | [
"https://Stackoverflow.com/questions/29578217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2157820/"
] | If you look a little on what Google has to say, there are several references to that problem. I see you are from Brasil so maybe this is your problem:
<https://github.com/thoughtbot/capybara-webkit/issues/291>
(which refers to: <https://github.com/thoughtbot/capybara-webkit/issues/224>
Also:
* <https://github.com/th... | I had the same problem using GCC installed via MacPorts (tested several versions up to gcc5). The solution for me was using g++ supplied with the XCode command line tools. I uninstalled all MacPorts GCC versions. Below version details of the g++ command that worked.
```
$ g++ --version
Configured with: --prefix=/Appl... | 14,833 |
56,387,349 | I'm using Django Rest Framework and want to be able to delete a Content instance via `DELETE` to `/api/content/<int:pk>/`. I *don't* want to implement any method to respond to `GET` requests.
When I include a `.retrieve()` method as follows, the `DELETE` request **works**:
```
class ContentViewSet(GenericViewSet):
... | 2019/05/31 | [
"https://Stackoverflow.com/questions/56387349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4400877/"
] | >
> 1. How can I allow DELETE without implementing a `.retrieve()` method?
>
>
>
Just remove the **`retrieve()`** method from the view class. Which means, the [**`GenericViewSet`**](https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset) doesn't provide any ***HTTP Actions*** unless it's defined ... | My solution for part 1. is to include the mixin but restrict the `http_method_names`:
```
class ContentViewSet(RetrieveModelMixin, GenericViewSet):
http_method_names = ['delete']
...
```
However, I still don't know why I have to include `RetrieveModelMixin` at all. | 14,834 |
64,784,079 | In an attempt to create a JWT in python I have written the following code.
```
#Header
header = str({"alg": "RS256"})
header_binary = header.encode()
header_base64 = base64.urlsafe_b64encode(header_binary)
print(header_base64)
#Claims set (Pay Load)
client_id=""
username=""
URL=""
exp_time=str(round(time.time())+30... | 2020/11/11 | [
"https://Stackoverflow.com/questions/64784079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14233404/"
] | Directly using LTPA in Tomcat is not possible unless you use 3rd party token services. The better way to have SSO experience between WebSphere and Tomcat is to use Windows ADFS as SSO server instead of LDAP. You can setup ADFS as either SAML identity provider and OpenID connect provider, and setup WebSphere and Tomcat ... | The other, simpler approach would be just to use Use Open Liberty instead of Tomcat, which I suggested in other thread. As usually there is no benefit using Tomcat over OpenLibery and LTPA token will work just via configuration in Liberty and can integrate with any older WebSpheres you have in your environment. | 14,836 |
58,843,848 | What I need is simple: a piece of code that will receive a GET request, process some data, and then generate a response. I'm completely new to python web development, so I've decided to use DRF for this purpose because it seemed like the most robust solution, but every example I found online consisted of CRUDs with mod... | 2019/11/13 | [
"https://Stackoverflow.com/questions/58843848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7742448/"
] | Simple way to do thing you want is by using Django REST Framework's `APIView` (or `@api_view` decorator).
Here is an example of it in the docs: <https://www.django-rest-framework.org/api-guide/views/>.
Besides code on that page, you would need to register your view on appropriate route, which can be found here: <htt... | Django and Django REST Framework are pretty heavy products out-of-the-box.
If you want something more lightweight that can handle many incoming requests, you could create a simple Express server using Node.js. This would result in very few lines of code on your end.
Sample Node server:
```
var express = require('exp... | 14,837 |
28,778,843 | I apologize for my noobiness in java, but I am trying to make a very basic app for someone for their birthday and have only really done any programming in python. I have been trying to implement the code found in [android - how to make a button click play a sound file every time it been pressed?](https://stackoverflow.... | 2015/02/28 | [
"https://Stackoverflow.com/questions/28778843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4616988/"
] | You need to just Put your file in res/raw folder and use
```
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
} else{
try {
mp = MediaPlayer.create(this, R.raw.hello);
mp.prepare();
mp.start(... | You can do it in another way. Put the .mp3 files under res/raw folder and use the following code:
```
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.android);
mediaPlayer.start();
```
Refer this [link](http://www.tutorialspoint.com/android/android_mediaplayer.htm) for better example to ... | 14,839 |
51,115,825 | I have numpy array and two python lists of indexes with positions to increase arrays elements by one. Do numpy has some methods to vectorize this operation without use of `for` loops?
My current slow implementation:
```
a = np.zeros([4,5])
xs = [1,1,1,3]
ys = [2,2,3,0]
for x,y in zip(xs,ys): # how to do it in numpy... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `np.add.at` will do just that, just pass both indexes as a single 2D array/list:
```
a = np.zeros([4,5])
xs = [1, 1, 1, 3]
ys = [2, 2, 3, 0]
np.add.at(a, [xs, ys], 1) # in-place
print(a)
array([[0., 0., 0., 0., 0.],
[0., 0., 2., 1., 0.],
[0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0.]])
``` | ```
>>> a = np.zeros([4,5])
>>> xs = [1, 1, 1, 3]
>>> ys = [2, 2, 3, 0]
>>> a[[xs,ys]] += 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 0.],
[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.]])
``` | 14,840 |
74,033,201 | I have a python dictionary which contains multiple key,values which are actually image indexes. For e.g. the dictionary I have looks something as given below
```
{
1: [1, 2, 3],
2: [1, 2, 3],
3: [1, 2, 3],
4: [4, 5],
5: [4, 5],
6: [6]
}
```
this means that 1 is related to 1, 2 & 3. Similarly ... | 2022/10/11 | [
"https://Stackoverflow.com/questions/74033201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7483151/"
] | How about this, use my modification below to remove the first item in the list during each loop. I commented the line which does it.
```
new_dict = dict()
# source is the original dictionary
for k,v in source.items():
ok = True
for k1,v1 in new_dict.items():
if k in v1: ok = False
if ok: new_dict[... | your modified code:
**ver 1:**
```
new_dict = dict()
for k, v in source.items():
if not any(k in v1 for v1 in new_dict.values()):
new_dict[k] = v[1:]
```
**ver 2:**
```
tmp = dict()
for k, v in source.items():
tmp[tuple(v)] = tmp.get(tuple(v), []) + [k]
res = dict()
for k, v in tmp.items():
r... | 14,841 |
37,584,629 | I am trying to connect to a AWS Redshift server via SSL. I am using psycopg2 library in python to establish the connection and used `sslmode='require'` as a parameter in the connect line. Unfortunately i got this error:
```
sslmode value "require" invalid when SSL support is not compiled in
```
I read many other sim... | 2016/06/02 | [
"https://Stackoverflow.com/questions/37584629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5610841/"
] | This worked for me: <https://stackoverflow.com/a/36489939/101266>
>
> had this same error, which turned out to be because I was using the Anaconda version of psycopg2. To fix it, I had adapt VictorF's solution from here and run:
>
>
>
```
conda uninstall psycopg2
sudo ln -s /Users/YOURUSERNAME/anaconda/lib/libssl... | Is your cluster enabled for SSL connections? Your URL itself will have the SSL info. and you can use the same in your code. | 14,843 |
16,946,051 | I have a log file with arbitrary number of lines. All I need is to extract is one line of data from the log file which starts with a string “Total”. I do not want any other lines from the file.
How do I write a simple python program for this?
This is how my input file looks
```
TestName id eno ... | 2013/06/05 | [
"https://Stackoverflow.com/questions/16946051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180817/"
] | ```
theFile = open('thefile.txt','r')
FILE = theFile.readlines()
theFile.close()
printList = []
for line in FILE:
if ('TestName' in line) or ('Totals' in line):
# here you may want to do some splitting/concatenation/formatting to your string
printList.append(line)
for item in printList:
print... | ```
for line in open('filename.txt', 'r'):
if line.startswith('TestName') or line.startswith('Totals'):
fields = line.rsplit(None, 5)
print '\t'.join(fields[:2] + fields[3:4])
``` | 14,844 |
34,254,594 | I am trying to emulate a piano in python using mingus as suggested in [this question](https://stackoverflow.com/questions/6487180/synthesize-musical-notes-with-piano-sounds-in-python/ "this question"). I am running Ubuntu 14.04, and have already created an audio group and added myself to it.
I am using alsa.
I ran the... | 2015/12/13 | [
"https://Stackoverflow.com/questions/34254594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951705/"
] | The data should be passed like this :-
```
$('#event_delete').on('click', function () {
$('#calendar').fullCalendar('removeEvents', calEvent.id);
$.ajax({
data: {id: calEvent.id},
type: "POST",
url: "http://localhost/book/js/delete_events.php" ... | Instead of reloading the entire page you can call $('#calendar').fullCalendar( 'refetchEvents' ). It will get all the events from your database and rerender them. | 14,845 |
63,687,990 | I have a `setup.py` which contains the following:
```
from pip._internal.req import parse_requirements
def load_requirements(fname):
"""Turn requirements.txt into a list"""
reqs = parse_requirements(fname, session="test")
return [str(ir.requirement) for ir in reqs]
setup(
name="Projectname",
[...... | 2020/09/01 | [
"https://Stackoverflow.com/questions/63687990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50065/"
] | You can only use [PEP 508 - *Dependency specification for Python Software Packages*](https://www.python.org/dev/peps/pep-0508/) requirements. `git://github.com/BioGeek/tta_wrapper.git@master#egg=tta_wrapper` is not valid syntax according to that standard.
`setuptools` does accept the [`name@ url` direct reference synt... | In my case there is no any github link in my requirements, but the line
```
-r common.txt
```
in `./requirements/prod.txt` caused the same error.
I've added stupid condition and now it works for me:
```py
def load_requirements(filename) -> list:
requirements = []
try:
with open(filename) as req:
... | 14,846 |
29,192,068 | On Windows 7 machine, Pycharm (community or professional) and Python 3.4 (tried Anaconda 3 as well) were installed newly. There were not problems running Python scripts interactively in main editor. However, when I tried to select *View > Tool Windows > Python Console*, it generates the following error messages and mor... | 2015/03/22 | [
"https://Stackoverflow.com/questions/29192068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018111/"
] | You need to change your working directory. Go to `File->Settings->Build, Execution, Deployment->Console->Python Console` and then change or provide a directory where you have read and write access in the `Working directory` box. | The configuring of pycharm in the presence of various development configurations is a bit of a black art IMHO.
The most effective mechanism I've found for pinning this down is put random strings into the various settings dialogs, Interpreters, consoles, tests , servers and observe the command lines submitted to the int... | 14,847 |
11,782,147 | I am trying to implement the algorithm found [here](http://www.m.cs.osakafu-u.ac.jp/cbdar2007/proceedings/papers/O1-1.pdf) in python with OpenCV.
I am trying to implement the part of the algorithm that remove irrelevant edge boundaries based on the number of interior boundaries that they have.
* If the current edge b... | 2012/08/02 | [
"https://Stackoverflow.com/questions/11782147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1128407/"
] | The main confusion here is probably the fact that the hierarchy returned is a numpy array with more dimensions than necessary. On top of that, it looks like the Python FindContours function returns a tuple that is a LIST of contours, and and NDARRAY of the hierarchy...
You can get a sensible array of hierarchy informa... | **Understanding Contour Hierarchies**
When finding contours in a binary image using [`cv2.findContours()`](https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours), you can use contour hierarchy to select and extract specific contours within the image. Specifically, ... | 14,852 |
37,811,767 | I like to use python interpreter, as it shows the result instantly. But I sometimes make mistakes. Like misspelling or typing 'enter' twice during writing class or function. It's really annoying work to rewrite the code.
Is it possible to add some code to a predefined class or function in the interpreter? | 2016/06/14 | [
"https://Stackoverflow.com/questions/37811767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5894129/"
] | When you want to declare an id in XML you do it as `android:id="@+id/myId"`
R is Java class. When you include the above line for an XML view a `public static final int myId` field gets included into the R class. You can reference this from your own classes.
`findViewById(int)` accepts an integer as a parameter. The R ... | When gradle builds your app, it generates a "
```
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/myEditText" />
```
You would then reference it in your code using the generated R class:
```
EditText myEditText = (EditText) findViewById(R.id.myEditText);
``` | 14,853 |
48,250,092 | How do I upload a excel `.xlsx` file to python flask from angular2?
I upload something but it can't be read when I open the excel file.
html for upload dialog:
```
<mat-form-field>
<input matInput placeholder="Filename" [(ngModel)]="filename">
</mat-form-field>
<button type="button" mat-raised-button (click)="i... | 2018/01/14 | [
"https://Stackoverflow.com/questions/48250092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203556/"
] | ```
temp = (ds_list)(malloc(sizeof(ds_list)));
```
will be
```
temp = malloc(sizeof(*temp)));
```
You want to allocate memory for `struct ds_list_element` not `struct ds_list_element*`. Don't hide pointers behind typedef name. It rarely helps.
Also you should check the return value of `malloc` and the casting is ... | Use `ds_list` as structure not a pointer
```
typedef struct ds_list_element {
char value[MAX];
struct ds_list_element *next;
}ds_list;
```
and allocate memory for the structure not a pointer.
Working program:
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
typedef struct ds_lis... | 14,855 |
2,211,706 | I've always preferred these:
```
not 'x' in 'abc'
not 'x' is 'a'
```
(assuming, of course that everyone knows `in` and `is` out-prioritize `not` -- I probably should use parentheses) over the more (English) grammatical:
```
'x' not in 'abc'
'x' is not 'a'
```
but didn't bother to think why until I realized they d... | 2010/02/06 | [
"https://Stackoverflow.com/questions/2211706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31676/"
] | From the python 2.6.4 docs at: <http://docs.python.org/reference/expressions.html>
>
>
> The operator not in is defined to have
> the inverse true value of in.
>
>
> The operators is and is not test for
> object identity: x is y is true if and
> only if x and y are the same object. x
> is not y yields the inver... | The remainder of your question has been answered above, but I'll address the last question: the Zen of Python bit.
"There should only be one way to do it" isn't mean't in a mathematical sense. If it were, there'd be no `!=` operator, since that's just the inversion of `==`. Similarly, no `and` and `or` --- you can, af... | 14,856 |
12,633,618 | I am new to python. I am working on some other's project but when i tried to run the code it give me the error said above. My all pages are working properly except those in which i had images. Is there any library required for the same??
Any help will be appreciable.
Thanks | 2012/09/28 | [
"https://Stackoverflow.com/questions/12633618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696228/"
] | you need to have `cropresize` package `http://pypi.python.org/pypi/cropresize/` installed on your device.
If it is not there install it from the link
Do `easy_install cropresize` or `pip install cropresize` | Just do [`easy_install cropresize`](http://pypi.python.org/pypi/cropresize/). | 14,864 |
33,168,308 | I have the following directory structure
```
-----root
|___docpd
|__docpd (contains settings.py, wsgi.py , uwsgi.ini)
|__static
```
During my vanilla django setup in dev environment , everything was fine (all static files used to load). But now after setting up uwsgi, i found that none of my static fi... | 2015/10/16 | [
"https://Stackoverflow.com/questions/33168308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270865/"
] | in settings
```
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.normpath(os.path.join(BASE_DIR, "static")),
)
```
in urls.py
```
urlpatterns = [
#urls
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
``` | You could also do it like so:
```
uwsgi --ini uwsgi.ini --http :8000 --static-map /static=/path/to/staticfiles/
```
or just add this to your .ini file:
```
static-map = /static=/path/to/staticfiles
``` | 14,869 |
58,471,984 | Could anyone here tell me how to properly append series of missing values onto a python list?
for example,
```
> ls=[1,2,3]
> ls += []*2
> ls
[1,2,3]
```
but this is not the outcome I want. I want:
```
[1,2,3, , ]
```
where the blanks denotes for the missing values.
(note: also what I DON'T want is:
``... | 2019/10/20 | [
"https://Stackoverflow.com/questions/58471984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12205961/"
] | Where are you set dataSource and Deleagte methods of TableView?
use this code
```
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.register(UITabl... | 2 possible reasons:
1. If the cell is designed as prototype cell you **must not** register the cell.
2. `dataSource` and `delegate` of the table view must be connected to the controller in Interface Builder or set in code. | 14,874 |
59,622,544 | My Data frame is below
I am trying to find the age
```
customer_Id DOB
0 268408 1970-02-01
1 268408 1970-02-01
2 268408 1970-02-01
3 268408 1970-02-01
4 268408 1970-02-01
```
shape is of `207518`
while converting the data i got `ValueError: unconverted data remains: 5`
code is below to convert in ... | 2020/01/07 | [
"https://Stackoverflow.com/questions/59622544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can change your function for working with datetimes, also convert to strings is not necessary:
```
def cal_age(x):
y = dt.date.today()
age = y.year - x.year - ((y.month, x.day) < (y.month, x.day))
return age
df_n_4['DOB'] = pd.to_datetime(df_n_4['DOB'],errors='coerce')
df_n_4['Age'] = df_n_4.DOB.apply... | try this code,
```
df['current_date']=pd.datetime.now()
df['age']=(df.current_date-pd.to_datetime(df.DOB)).dt.days/365
``` | 14,875 |
66,484,870 | So I was developing a python program for my school project that asks a customer for their details such as their Firstname,Lastname,Age etc. So I made a function called customer details.
```
def customerdetails():
Firstname = input("Enter your First name:")
Lastname = input("Enter your last name:")
Ag... | 2021/03/05 | [
"https://Stackoverflow.com/questions/66484870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13290732/"
] | You need to return the information from your `customerdetails` function. Since you have a bunch of different variables, you'll be returning a collection -- a tuple, a list, a dict, etc.
Using a tuple or a list means you need to keep track of the order of all the elements, and using a dict means you need to keep track ... | By default, variables declared within a function are local only to that function.
If you want a function to give back multiple values, you can `return` a tuple of values:
```py
def customerdetails():
Firstname = input("Enter your First name:")
Lastname = input("Enter your last name:")
Age = input("A... | 14,876 |
41,994,645 | Is there a more functional way to create a 2d array in Javascript than what I have here? Perhaps using `.apply`?
```
generatePuzzle(size) {
let puzzle = [];
for (let i = 0; i < size; i++) {
puzzle[i] = [];
for (let j = 0; j < size; j++) {
puzzle[i][j] = Math.floor((Math.random() * 200) + 1);
}
... | 2017/02/02 | [
"https://Stackoverflow.com/questions/41994645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718122/"
] | ```
const repeat = (fn, n) => Array(n).fill(0).map(fn);
const rand = () => Math.floor((Math.random() * 200) + 1);
const puzzle = n => repeat(() => repeat(rand, n), n);
```
And then `puzzle(3)`, eg, will return a 3x3 matrix filled with random numbers. | With lodash just like below:
```
const _ = require('lodash');
function generatePuzzle(size) {
return _.times(size, () => _.times(size, () => (Math.random() * 200) + 1));
}
``` | 14,879 |
64,169,510 | I am using XEN hypervisor. For managing virtual Machine I am using **virt-manager** whenever I want to start to Virtual Machine at last when everything is ready and I click the create Button I get the following error
```
Unable to complete install: 'An error occurred, but the cause is unknown'
Traceback (most recent ... | 2020/10/02 | [
"https://Stackoverflow.com/questions/64169510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12966156/"
] | You can iterate over the result of the dynamic query directly:
```
create or replace function gapandoverlapdetection ( table_name text, entity_ids bigint[])
returns table (entity_id bigint, valid tsrange, causes_overlap boolean, causes_gap boolean)
as $$
declare
var_r record;
begin
for var_r in EXECUTE ... | Firstly, decide whether you want to pass the table's name or oid. If you want to identify the table by name, then the parameter should be of `text` type and not `regclass`.
Secondly, if you want the table name to change between executions then you need to [execute the SQL statement dynamically](https://www.postgresql.... | 14,880 |
60,404,756 | ```
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
```
I am cu... | 2020/02/25 | [
"https://Stackoverflow.com/questions/60404756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12946446/"
] | That for loop is just taking the indices being used for the split and calling those rows of the original data to form the training and test sets. | StratifiedShuffleSplit is better if you are using a K-fold cross-validation, where you divide the training and testing data in different ways and then calculate the mean of a result in K iterations.
`n_splits` must equals the *K* value and in your case *K* is one, which makes no sense for cross-validation. I think you... | 14,881 |
70,310,388 | I have a list of nested dictionaries (python 3.9) that looks something like this:
```
records = [
{'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242}}}},
{'Total:': {'Owner:': {'Available:': {'35 to 64 years': 5699}}}},
{'Total:': {'Owner:': {'Available:': {'65 years and over': 2098}}}},
{'To... | 2021/12/10 | [
"https://Stackoverflow.com/questions/70310388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12413845/"
] | Recursion is an easy way to navigate and operate on arbitrarily nested structures:
```
def combine_into(d: dict, combined: dict) -> None:
for k, v in d.items():
if isinstance(v, dict):
combine_into(v, combined.setdefault(k, {}))
else:
combined[k] = v
combined = {}
for recor... | Quick solution: `res = NDict.from_list_of_dict(records).raw_dict`
Test:
```py
>>> from naapc import NDict
>>> records = [
... {'Total:': {'Owner:': {'Available:': {'15 to 34 years': 1242}}}},
... {'Total:': {'Owner:': {'Available:': {'35 to 64 years': 5699}}}},
... {'Total:': {'Owner:': {'Available:': {'6... | 14,882 |
9,638,826 | I'm using python to simulate some automation models, and with the help of matplotlib I'm producing plots like the one shown below.

I'm currently plotting with the following command:
```
ax.imshow(self.g, cmap=map, interpolation='nearest')
```
whe... | 2012/03/09 | [
"https://Stackoverflow.com/questions/9638826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38055/"
] | You can change the color map you are using via the `cmap` keyword. The color map `'Greys'` provides the effect you want. You can find a list of [available maps on the scipy website](http://scipy-cookbook.readthedocs.io/items/Matplotlib_Show_colormaps.html).
```
import matplotlib.pyplot as plt
import numpy as np
np.r... | There is an alternative method to Yann's answer that gives you finer control. Matplotlib's [imshow](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow) can take a `MxNx3` matrix where each entry is the RGB color value - just set them to white `[1,1,1]` or black `[0,0,0]` accordingly. If you ... | 14,883 |
18,080,556 | I have written a project in python which I am now in the process of moving to google app engine. The problem that occurs is when I run this code on GAE:
```
import requests
from google.appengine.api import urlfetch
def retrievePage(url, id):
response = 'http://online2.citybreak.com/Book/Package/Result.aspx?online... | 2013/08/06 | [
"https://Stackoverflow.com/questions/18080556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2656606/"
] | I think this will do it:
```
var text = "aaa bbb eee ccc <br>ddd eee fff ggg hhh iii jjj kkk";
var search = /eee [^e<>]*ggg/g;
console.log(text.search(search)); // a)
console.log(text.replace(search, "newinsertedstring $&")); // b)
``` | ```
var text = "whatever".Replace("eee fff ggg", "newinsertedstring eee fff ggg");
``` | 14,884 |
12,558,878 | >
> **Possible Duplicate:**
>
> [Python 3.2.3 programming…Almost had it working](https://stackoverflow.com/questions/12558717/python-3-2-3-programming-almost-had-it-working)
>
>
>
```
x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What perc... | 2012/09/24 | [
"https://Stackoverflow.com/questions/12558878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693293/"
] | There is a parentheses missing after `.format(x*(z/100))` that belongs to the preceding `print`.
It should be:
```
print ("Tip: ${}".format(x*(z/100)))
```
**UPDATE:** Not sure if you got it working or not yet, here is the complete code after fixing your unbalanced parentheses...
```
x = float(input("What is/was t... | You missed an end bracket after the third print: `.format(x*(z/100)))`
Here is what appears to be a working version after I fixed the brackets:
```
x = float(input("What is/was the cost of the meal?"))
y = float(input("What is/was the sales tax?"))
z = float(input("What percentage tip would you like to leave?"))
pri... | 14,887 |
13,221,021 | I'm trying to create a basic blogging application in Python using Web.Py. I have started without a direcotry structure, but soon I needed one. So I created this structure:
```
Blog/
├── Application/
│ ├── App.py
│ └── __init__.py
|
├── Engine/
│ ├── Connection/
│ │ ├── __init__.py
│ │ └── MySQLConnection... | 2012/11/04 | [
"https://Stackoverflow.com/questions/13221021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | No, you simply can't. AutoBean requires everything to be *statically typed*: no polymorphism, and no mixed-typed lists of maps.
You might be interested by RequestFactory's built-in support for JSON-RPC though. | Why do your params all need to be passed back in a list? Surely you're not going to do the same thing with a `String`, an `Integer`, and another `Object`! Just send them all back separately.
Further, you're not sending a custom `Object` over the JSON, you're sending the `objid` of that object... so just send the `Inte... | 14,889 |
34,759,366 | I have a python script that uses a while true and continues to run. In the while loop I have several if statements. Some of the if statements have a `time.sleep` in them. After using this for a while I notice that all of the if statements below the first `time.sleep` are waiting.
Is there way to have the if statement... | 2016/01/13 | [
"https://Stackoverflow.com/questions/34759366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5729013/"
] | I have used a Javascript timer in the past to poll the server to test if the session is still active. If I receive a 403 then redirect to the login page.
```
var AutoLogout = {};
AutoLogout.pollInterval = 60000; // Default is 1 minute.
// Force auto logout when session expires
AutoLogout.start = function (heartBea... | I will try to solve your problem
I will suggest to put your logic in action filter
```
public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContex... | 14,890 |
35,475,770 | Every forum I have looked at says that:
```
pip install pillow
```
remedies issues with installing pyautogui, however, I have installed pillow and I am still receiving:
```
python setup.py egg_info failed with error code 1
```
Any suggestions? I also tried installing PIL but that failed as well with the same erro... | 2016/02/18 | [
"https://Stackoverflow.com/questions/35475770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5365094/"
] | Some of the possible solutions.
1. Use an ajax method to get your resource by passing a key.
2. Use Hidden input fields and load values.
3. Use a dedicated jsp page to declare js variables or even a js function to get values according to key.
like this.
>
>
> ```
> <script type="text/javascript">
>
> var mess... | It is normally bad practice to use scriplets `<% %>` inside your `jsp` files.
You can use the `fmt` tag from the jstl core library to fetch information from your resource bundles.
```
<fmt:bundle basename="bundle">
<fmt:message var="variableName" key="bundleKey" />
</fmt:bundle>
<input type="hidden" name="hidden... | 14,891 |
63,378,402 | I am trying to stream Elasticsearch data into Snowflake. I am testing a python script which ultimately will be deployed as a cloud function/docker app on AWS. For historical I am using the `scroll` API to write x amount of objects into a string and the string to a file. I've used Snowflake's `PUT file://file.json.gz @s... | 2020/08/12 | [
"https://Stackoverflow.com/questions/63378402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9972301/"
] | If you create a Snowflake Stage linked to an S3 when you save to your S3, with whatever you decide to use, it will be automatically on your Snowflake Stage, this way, you can just send a COPY INTO command and save a step or two.
In my opinion, it's a simple and handy solution.
if you need the steps, let me know and I... | You can use snowpipe. You need to create smaller files continuously and using snowpipe, keep on uploading them. You can use Amazon Kinesis Firehose to manage the batches.
Refer to documentation at <https://docs.snowflake.com/en/user-guide/data-load-considerations-prepare.html#continuous-data-loads-i-e-snowpipe-and-file... | 14,896 |
17,160,968 | Can inputting and checking be done in the same line in python?
Eg) in C we have
```
if (scanf("%d",&a))
```
The above statement if block works if an integer input is given. But similarly,
```
if a=input():
```
Doesn't work in python. Is there a way to do it? | 2013/06/18 | [
"https://Stackoverflow.com/questions/17160968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2046858/"
] | No, Python can't do assignment as part of the condition of an `if` statement. The only way to do it is on two lines:
```
a=input()
if a:
// Your code here
pass
```
This is by design, as it means that assignment is maintained as an atomic action, independent of comparison. This can help with readability of th... | You can't do it. This was a deliberate design choice for Python because this construct is good for causing hard to find bugs.
see @Jonathan's comment on the question for an example | 14,897 |
57,860,405 | My understanding of Python asserts is that are meant for debugging and that they don't get executed for "optimized" Python code (`python -O`).
For production app engine code, is `-O` used and thus stripping asserts or will asserts get executed? | 2019/09/09 | [
"https://Stackoverflow.com/questions/57860405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136598/"
] | I ran a test on the platforms I use to know for sure. Asserts do get executed for:
* GAE standard first generation
* GAE flexible | As far as i understand from Python asserts, once you set the global assertions to -0 they all become "null-operations" as in, they will get compiled but won't be evaluated or have they're conditional expressions executed.
They get set like that at the Python interpreter level so i don't think that GAE actually affect... | 14,898 |
25,888,828 | I'm trying to make an script which takes all rows starting by 'HELIX', 'SHEET' and 'DBREF' from a .txt, from that rows takes some specifical columns and then saves the results on a new file.
```
#!/usr/bin/python
import sys
if len(sys.argv) != 3:
print("2 Parameters expected: You must introduce your pdb file and ... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25888828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4027271/"
] | cols\_id, cols\_h and cols\_s seems to be lists, not strings.
You can only write a string in your file so you have to convert the list to a string.
```
modified_data.write(' '.join(cols_id))
```
and similar.
`'!'.join(a_list_of_things)` converts the list into a string separating each element with an exclamation mar... | You need to convert the tuple created on RHS in your assignments to string.
```
# Replace this with statement given below
cols_id = dbref[0], dbref[3:5], dbref[8:10]
# Create a string out of the tuple
cols_id = ''.join((dbref[0], dbref[3:5], dbref[8:10]))
``` | 14,899 |
7,234,518 | what is the bes way tho check if two words are ordered in sentence and how many times it occurs in python.
For example: I like to eat maki sushi and the best sushi is in Japan.
words are: [maki, sushi]
Thanks.
The code
```
import re
x="I like to eat maki sushi and the best sushi is in Japan"
x1 = re.split('\W+',... | 2011/08/29 | [
"https://Stackoverflow.com/questions/7234518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461736/"
] | According to the added code, you mean that words are adjacent?
Why not just put them together:
```
print len(re.findall(r'\bmaki sushi\b', sent))
``` | ```
def ordered(string, words):
pos = [string.index(word) for word in words]
return pos == sorted(pos)
s = "I like to eat maki sushi and the best sushi is in Japan"
w = ["maki", "sushi"]
ordered(s, w) #Returns True.
```
Not exactly the most efficient way of doing it but simpler to understand. | 14,902 |
64,348,889 | There's a code I found in internet that says it gives my machines local network IP address:
```
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
```
but the IP it returns is 192.168.94.2 but my IP address in WIFI network is actually 192.168.1.107
How can I only get wifi network local IP addr... | 2020/10/14 | [
"https://Stackoverflow.com/questions/64348889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848316/"
] | You can use this code:
```
import socket
hostname = socket.getfqdn()
print("IP Address:",socket.gethostbyname_ex(hostname)[2][1])
```
or this to get public ip:
```
import requests
import json
print(json.loads(requests.get("https://ip.seeip.org/jsonip?").text)["ip"])
``` | Here's code from the `whatismyip` Python module that can grab it from public websites:
```
import urllib.request
IP_WEBSITES = (
'https://ipinfo.io/ip',
'https://ipecho.net/plain',
'https://api.ipify.org',
'https://ipaddr.site',
'https://icanhazip.com',
... | 14,912 |
5,484,098 | I'm new to Python. I'm writing a simple class but I'm with an error.
My class:
```
import config # Ficheiro de configuracao
import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python
class TwitterC:
def logToDatabase(self, tweet, timestamp):
# Wi... | 2011/03/30 | [
"https://Stackoverflow.com/questions/5484098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488735/"
] | It looks like your call to updateTwitterStatus just needs to lose the square brackets:
```
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=31", "msg": "See some strings..., "})
```
You were passing a list with a single dictionary element. It looks as though the method just requires a dictionary with "url" and "... | The error message tells you everything you need to know. It says "list indices must be integers, not str" and points to the code `short = self.shortUrl(update["url"])`. So obviously the python interpreter thinks `update` is a list, and `"url"` is not a valid index into the list.
Since `update` is passed in as a parame... | 14,913 |
7,606,062 | For example, if a python script will spit out a string giving the path of a newly written file that I'm going to edit immediately after running the script, it would be very nice to have it directly sent to the system clipboard rather than `STDOUT`. | 2011/09/30 | [
"https://Stackoverflow.com/questions/7606062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/560844/"
] | You can use an external program, [`xsel`](http://www.vergenet.net/~conrad/software/xsel/):
```
from subprocess import Popen, PIPE
p = Popen(['xsel','-pi'], stdin=PIPE)
p.communicate(input='Hello, World')
```
With `xsel`, you can set the clipboard you want to work on.
* `-p` works with the `PRIMARY` selection. That... | This is not really a Python question but a shell question. You already can send the output of a Python script (or any command) to the clipboard instead of standard out, by piping the output of the Python script into the `xclip` command.
```
myscript.py | xclip
```
If `xclip` is not already installed on your system (... | 14,914 |
46,062,117 | Following [the plotly directions](https://plot.ly/python/distplot/), I would like to plot something similar to the following code:
```
import plotly.plotly as py
import plotly.figure_factory as ff
import numpy as np
# Add histogram data
x1 = np.random.randn(200) - 2
x2 = np.random.randn(200)
x3 = np.random.randn... | 2017/09/05 | [
"https://Stackoverflow.com/questions/46062117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3604836/"
] | You could try slicing your dataframe and then putting it into in Ploty.
```
fig = ff.create_distplot([df[df.names == a].value for a in df.names.unique()], df.names.unique(), bin_size=[.1, .25, .5, 1])
```
---
[](https://i.stack.imgur.com/IsX83.png)... | The [example](https://plot.ly/python/distplot/) in [`plotly`](https://plot.ly/python/)'s documentation works out of the box for uneven sample sizes too:
```
#!/usr/bin/env python
import plotly
import plotly.figure_factory as ff
plotly.offline.init_notebook_mode()
import numpy as np
# data with different sizes
x1 = ... | 14,920 |
74,513,701 | I am an R User that is trying to learn more about Python.
I found this Python library that I would like to use for address parsing: <https://github.com/zehengl/ez-address-parser>
I was able to try an example over here:
```
from ez_address_parser import AddressParser
ap = AddressParser()
result = ap.parse("290 Brem... | 2022/11/21 | [
"https://Stackoverflow.com/questions/74513701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13203841/"
] | It's not possible to completely remove the authorization prompt but you could make it appear only one time for each user by publishing your script as an Editor add-on.
1. Create a Google Cloud standard project (GCSP) and add the OAuth consent screen.
2. Link the GCSP to the Google Apps Script project.
3. Deploy the sc... | It's just a routine security procedure. If they trust you, then there's no issue in them accepting it, it's just a warning if you don't know the coder | 14,921 |
52,683,832 | ```
Revenue = [400000000,10000000,10000000000,10000000]
s1 = []
for x in Revenue:
message = (','.join(['{:,.0f}'.format(x)]).split())
s1.append(message)
print(s1)
The output I am getting is something like this [['400,000,000'], ['10,000,000'], ['10,000,000,000'], ['10,000,000']] and I want it should be like ... | 2018/10/06 | [
"https://Stackoverflow.com/questions/52683832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10431728/"
] | If your goal is to just add in the commas you will be stuck with the `' '` due to the fact its going to be a `str` but you can eliminate that nesting by using a simpler *list comprehension*
```
Revenue = [400000000,10000000,10000000000,10000000]
l = ['{:,}'.format(i) for i in Revenue]
# ['400,000,000', '10,000,000', ... | I'm not sure why you want the output you've shown, because it is hard to read, but here is how to make it:
```
>>> Revenue = [400000000,10000000,10000000000,10000000]
>>> def revenue_formatted(rev):
... return "[" + ", ".join("{:,d}".format(n) for n in rev) + "]"
...
>>> print(revenue_formatted(Revenue))
[400,000,... | 14,922 |
56,840,250 | I am making an adventure game in python 3.7.3, and I am using F strings for some of my print statements. When running it in the terminal and sublime text, F strings give me an error.
```
import time
from time import sleep
import sys
def printfast(str):
for letter in str:
sys.stdout.write(letter)
s... | 2019/07/01 | [
"https://Stackoverflow.com/questions/56840250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11723707/"
] | You're doing it wrong. `f` isn't a function, it's more of an syntactic identifier. Whereas regular quotes `"` indicate the beginning of a regular string (or the end of any type of string), the token `f"` indicates the beginning of a format string in particular. The same idea goes for raw strings, indicated by `r"`, or ... | In `f("You ...)`, you're calling a function named `f` with the string as input parameter, and you don't have such a function hence the error.
You need to drop the enclosing parentheses `()` to make it a f-string:
```
f"You are the mighty hero {name}. In front of you, there is a grand palace, containing twisting marbl... | 14,923 |
36,985,391 | I am creating a sql query in python of the sort:
```
select lastupdatedatetime from auth_principal_entity where lastupdateddatetime < '02-05-16 03:46:51:527000000 PM'
```
When it is executed, there are escape sequences that are being added which doesn't return me answers.
Although when we print it in stdout, it loo... | 2016/05/02 | [
"https://Stackoverflow.com/questions/36985391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2576170/"
] | The escape sequences won't cause any problem in the cursor.execute(query)
The real issue lies in the date that is being sent as a string is being used to compare and return values from db which are in date-object format.
so something like this should work.
```
query = "SELECT LASTUPDATEDDATETIME FROM AUTH_PRINCIPAL_E... | For me, I wrap my SQL statements in triple quotes so it doesn't run into these issues when I execute:
```
query = """
select lastupdatedatetime from auth_principal_entity where lastupdateddatetime < '02-05-16 03:46:51:527000000 PM'
"""
``` | 14,925 |
46,247,340 | I am currently running tests between XGBoost/lightGBM for their ability to rank items. I am reproducing the benchmarks presented here: <https://github.com/guolinke/boosting_tree_benchmarks>.
I have been able to successfully reproduce the benchmarks mentioned in their work. I want to make sure that I am correctly imple... | 2017/09/15 | [
"https://Stackoverflow.com/questions/46247340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2800840/"
] | Cross-posting my Cross Validated answer to this cross-posted question:
<https://stats.stackexchange.com/questions/303385/how-does-xgboost-lightgbm-evaluate-ndcg-metric-for-ranking/487487#487487>
---
I happened across this myself, and finally dug into the code to figure it out.
The difference is the handling of a mis... | I think the problem is caused by data in the same query that have same labels.
In that case, Both XGBoost and LightGBM will produce ndcg 1 for that query. | 14,926 |
15,854,257 | I am new to python. As part of writing a module to scrape URLs I noticed that what I get using the python requests module could be different from what I get if I load the URL in a browser. This is because the page could contain JS code which is executed and the result is hat I see in the browser.
My questions -
1. h... | 2013/04/06 | [
"https://Stackoverflow.com/questions/15854257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1645536/"
] | The best way to go about this might be, to use [css-gradients](https://developer.mozilla.org/en-US/docs/CSS/gradient) instead of shadows.
I have done a little demo on [jsfiddle](http://jsfiddle.net/Qjgps/1/). I am not sure this is what you are looking for though. Here is the css I used:
```
background: rgb(254,255,25... | I came up with this using [this CSS3 Generator](http://css3generator.com/)
```
-webkit-box-shadow: inset 0px -350px 200px -250px rgba(5, 5, 5, 1);
box-shadow: inset 0px -350px 200px -250px rgba(5, 5, 5, 1);
```
This is a very cross-browser friendly method and if you apply a background color it will achieve ... | 14,927 |
15,671,875 | I seem to have some difficulty getting what I want to work. Basically, I have a series of variables that are assigned strings with some quotes and \ characters. I want to remove the quotes to embed them inside a json doc, since json hates quotes using python dump methods.
I figured it would be easy. Just determine how... | 2013/03/28 | [
"https://Stackoverflow.com/questions/15671875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/933693/"
] | You can't do that. You could make it work using `eval`, but that introduces another level of quoting you have to worry about. Is there some reason you can't use an array?
```
MESSAGE=("this is MESSAGE[0]" "this is MESSAGE[1]")
MESSAGE[2]="I can add more, too!"
for (( i=0; i<${#MESSAGE[@]}; ++i )); do
echo "${MESSAG... | First, a couple of preliminary problems: `MESSAGE23="com."apple".cacng.tokend is present"` will not embed double-quotes in the variable value, use `MESSAGE23="com.\"apple\".cacng.tokend is present"` or `MESSAGE23='com."apple".cacng.tokend is present'` instead. Second, you should almost always put double-quotes around v... | 14,928 |
46,721,993 | I have a shell script that I use to export Env variables. This script calls a python script to get certain values from a web service that I need to store before running my primary python script.
I've tried using a `RUN . /bot/env/setenv.sh`, but this doesn't seem to make the env variables available in the final contai... | 2017/10/13 | [
"https://Stackoverflow.com/questions/46721993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143724/"
] | 1. You are not running the docker container [as a daemon](https://docs.docker.com/engine/reference/run/#detached--d).
>
> docker run -d bot
>
>
>
2. In my experience, print messages don't make it to the logs without input buffering disabled in python.
>
> python -u jbot.py
>
>
> | For your first question, you should check the documentation of `docker run`. Shortly, you are attaching with container so you will never return to your terminal. In order to detach, you need to add option `-d`.
The common used command to launch a container is `docker run -idt <container>`.
For your second question, t... | 14,929 |
52,911,986 | I am working with ros on ubuntu 16.04. Because of this I am working with a virtual environment for python 2.7 and the ros python modules (rospy for example). The "python.pythonPath" is set to the virtual environment and the ros modules are linked through "python.autoComplete.extraPaths".
This leads to the issue where ... | 2018/10/21 | [
"https://Stackoverflow.com/questions/52911986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10534965/"
] | I've never used probuilder, but in other 3d max app you will need to delete the inner polygons that to be able to cap that face. select all the polygons in the "well" and delete, you will now have a hole to fill
[GIF]
[][1](https://i.stack.imgur.com/W... | update
I find a complex but accurate way to do this
unity editor > Tools > Probuilder > editor > open vertex position editor
when i select vertex, position editor
put selected positions to txt file
unity editor > tools > probuilder > editor > open new shape editor > shape selector > custom
build face with position... | 14,930 |
56,443,552 | I will service my django project with uwsgi on Ubuntu Server, but It doesn't run.
I am using python 3.6 but the uwsgi shows me it's 2.7
I changed default python to python3.6 but uwsgi still doesn't work.
This is my command :
```
uwsgi --http :8001 --home /home/ubuntu/repository/env --chdir
/home/ubuntu/repository/... | 2019/06/04 | [
"https://Stackoverflow.com/questions/56443552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11598754/"
] | Unfortunately, uWSGI has to be compiled with python version matching with your virtualenv. That means: if uWSGI was compiled with python 2.7, you cannot use python 3.6 in your virtualenv (and in your Django app).
Fortunately, there are some methods to fix that:
* Installing uWSGI inside your virtualenv and using that... | The log tells there is no module named site
>
> ImportError: No module named site
>
>
>
I assume site is an django app.
did you register this in your INSTALLED\_APPS (settings.py)
Otherwise you may need to register your app. (apps.py in the site app)
Please let me know if I helped you.
Jasper | 14,932 |
20,200,307 | I am using GAE long time but can not find what is maximum length of ListProperty.
I was read [documentation](https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#ListProperty) but not found solution I want to create ListProperty(long) to keep about 30 values of long or more. I want use... | 2013/11/25 | [
"https://Stackoverflow.com/questions/20200307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665926/"
] | I've a list of 20K strings (not indexed though). I don't think there is limitation on the length, but there is limitation on each entity size. Be careful on indexing multi value properties, it could be expensive. | 30 will be fine.
Guido's answer about related question: <https://stackoverflow.com/a/15418435/1279005>
So up to 100 repeated values will be fine.
Repeated properties much easier to understand by using NDB as I think. You should try it.
It's does not matter if you using it with Long or String properties - if the prope... | 14,934 |
58,260,903 | I tried various programs to get the required pattern (Given below). The program which got closest to the required result is given below:
**Input:**
```
for i in range(1,6):
for j in range(i,i*2):
print(j, end=' ')
print( )
```
**Output:**
```
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
```
**Required Outp... | 2019/10/06 | [
"https://Stackoverflow.com/questions/58260903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9957954/"
] | Store the printed value outside of the loop, then increment after its printed
```
v = 1
lines = 4
for i in range(lines):
for j in range(i):
print(v, end=' ')
v += 1
print( )
``` | If you don't want to keep track of the count and solve this mathematically and be able to directly calculate any n-th line, the formula you are looking for is the one for, well, [triangle numbers](https://en.wikipedia.org/wiki/Triangular_number):
```
triangle = lambda n: n * (n + 1) // 2
for line in range(1, 5):
t... | 14,937 |
43,043,437 | I'm trying to create a wordcloud from csv file. The csv file, as an example, has the following structure:
```
a,1
b,2
c,4
j,20
```
It has more rows, more or less 1800. The first column has string values (names) and the second column has their respective frequency (int). Then, the file is read and the key,value row i... | 2017/03/27 | [
"https://Stackoverflow.com/questions/43043437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7658581/"
] | This is because the values in your dictionary are strings but wordcloud expects integer or floats.
After I run your code then inspect your dictionary `d` I get the following.
```
In [12]: d
Out[12]: {'a': '1', 'b': '2', 'c': '4', 'j': '20'}
```
Note the `' '` around the numbers means these are really strings.
A... | ```
# LEARNER CODE START HERE
file_c=""
for index, char in enumerate(file_contents):
if(char.isalpha()==True or char.isspace()):
file_c+=char
file_c=file_c.split()
file_w=[]
for word in file_c:
if word.lower() not in uninteresting_words and word.isalpha()==True:
file_w.append(word)
frequency={}
for ... | 14,938 |
5,719,545 | I am working on web-crawler [using python].
Situation is, for example, I am behind server-1 and I use proxy setting to connect to the Outside world. So in Python, using proxy-handler I can fetch the urls.
Now thing is, I am building a crawler so I cannot use only one IP [otherwise I will be blocked]. To solve this, I ... | 2011/04/19 | [
"https://Stackoverflow.com/questions/5719545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/715600/"
] | **Update** Sounds like you're looking to connect to proxy A and from there initiate HTTP connections via proxies B, C, D which are outside of A. You might look into the [proxychains project](http://proxychains.sourceforge.net/) which says it can "tunnel any protocol via a user-defined chain of TOR, SOCKS 4/5, and HTTP ... | I recommend you take a look at CherryProxy. It lets you send a proxy request to an intermediate server (where CherryProxy is running) and then forward your HTTP request to a proxy on a second level machine (e.g. squid proxy on another server) for processing. Viola! A two-level proxy chain.
<http://www.decalage.info/py... | 14,939 |
66,775,948 | Some python packages wont work in python 3.7 . So wanted to downgrade the default python version in google colab.Is it possible to do? If so how to proceed.Please guide me.. | 2021/03/24 | [
"https://Stackoverflow.com/questions/66775948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15069182/"
] | You could install python 3.6 with `miniconda`:
```
%%bash
MINICONDA_INSTALLER_SCRIPT=Miniconda3-4.5.4-Linux-x86_64.sh
MINICONDA_PREFIX=/usr/local
wget https://repo.continuum.io/miniconda/$MINICONDA_INSTALLER_SCRIPT
chmod +x $MINICONDA_INSTALLER_SCRIPT
./$MINICONDA_INSTALLER_SCRIPT -b -f -p $MINICONDA_PREFIX
```
And... | The following code snippet below will download Python 3.6 without any Colab pre-installed libraries (such as Tensorflow). You can install them later with pip, like `!pip install tensorflow`. Please note that this won't downgrade your default python in colab, rather it would provide a workaround to work with other pytho... | 14,940 |
53,972,642 | I'm a lawyer and python beginner, so I'm both (a) dumb and (b) completely out of my lane.
I'm trying to apply a regex pattern to a text file. The pattern can sometimes stretch across multiple lines. I'm specifically interested in these lines from the text file:
```
Considered and decided by Hemingway, Presiding... | 2018/12/29 | [
"https://Stackoverflow.com/questions/53972642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10823652/"
] | You are passing in **single lines**, because you are iterating over the open file referenced by `case`. The regex is never passed anything other than a single line of text. Your regexes can each match *some* of the lines, but they don't all together match the same single line.
You'd have to read in more than one line.... | Instead of multiple `re.search`, you could use [`re.findall`](https://docs.python.org/3.7/library/re.html#re.findall) with a really short and simple pattern to find all judges at once:
```
import re
text = """Considered and decided by Hemingway, Presiding Judge; Bell,
Judge; and \n
\n
Dickinson, Emily, Judg... | 14,941 |
10,512,026 | I'm new to python and am trying to read "blocks" of data from a file. The file is written something like:
```
# Some comment
# 4 cols of data --x,vx,vy,vz
# nsp, nskip = 2 10
# 0 0.0000000
# 1 4
0.5056E+03 0.8687E-03 -0.1202E-02 0.4652E-02
0.3776E+03 0.8687E-... | 2012/05/09 | [
"https://Stackoverflow.com/questions/10512026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1325437/"
] | A quick basic read:
```
>>> def read_blocks(input_file, i, j):
empty_lines = 0
blocks = []
for line in open(input_file):
# Check for empty/commented lines
if not line or line.startswith('#'):
# If 1st one: new block
if empty_lines == 0:
blocks.append(... | The following code should probably get you started. You will probably need the re module.
You can open the file for reading using:
```
f = open("file_name_here")
```
You can read the file one line at a time by using
```
line = f.readline()
```
To jump to the next line that starts with a "#", you can use:
```
w... | 14,943 |
53,949,017 | I'm trying to develop a lambda that has to work with S3 and dynamoDB.
The thing is that because I am not familiar with the SDK of aws for go I will have lots of tests and tries.
Each time I will change the code is another time I have to compile the project and upload it to aws.
Is there any way to do it locally? pass s... | 2018/12/27 | [
"https://Stackoverflow.com/questions/53949017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8885009/"
] | You can use the lambci docker image(s) to execute your code locally using the same Lambda runtimes that are used on AWS.
<https://github.com/lambci/docker-lambda>
You can also run dynamo DB locally in another container as well
<https://hub.docker.com/r/amazon/dynamodb-local/>
To simulate credentials/roles that woul... | You could use this [aws-lambda-go-test](https://github.com/yogeshlonkar/aws-lambda-go-test) module which can run lambda locally and can be used to test the actual response from lambda
full disclosure I forked and upgraded this module | 14,944 |
59,001,784 | I am building a webscrape that will run over and over that will insert new data or update data based on ID. `if 'id' == 'id':` My goal is to avoid duplicates. MySQL table is ready and built. What is the best Pythonic way to check your python list before inserting/updating it in MySQL DB using SQLAlchemy?
Below are my... | 2019/11/22 | [
"https://Stackoverflow.com/questions/59001784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11396478/"
] | I am using a helper function to create the dynamic sql update queries:
```
def construct_update(table_name, where_vals, update_vals):
query = table_name.update()
for k, v in where_vals.items():
query = query.where(getattr(table_name.c, k) == v)
return query.values(**update_vals)
```
basically you... | You can try using <https://marshmallow.readthedocs.io/en/stable/> library to make validation
Build `Schema` and define fields with types you need. You can also use `@pre_load` and `@post_load` decorators to manipulate your data | 14,945 |
2,105,508 | I'm new to Cython and I'm trying to use Cython to wrap a C/C++ static library. I made a simple example as follow.
**Test.h:**
```
#ifndef TEST_H
#define TEST_H
int add(int a, int b);
int multipy(int a, int b);
#endif
```
**Test.cpp**
```
#include "test.h"
int add(int a, int b)
{
return a+b;
}
int multipy(i... | 2010/01/20 | [
"https://Stackoverflow.com/questions/2105508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150324/"
] | If your C++ code is only used by the wrapper, another option is to let the setup compile your .cpp file, like this:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("test",
["test.pyx", "test.cpp"],
... | I think you can fix this specific problem by specifying the right `library_dirs` (where you actually **put** libtest.a -- apparently it's not getting found), but I think then you'll have another problem -- your entry points are not properly declared as `extern "C"`, so the function's names will have been "mangled" by t... | 14,946 |
74,179,391 | I am responsible for a series of exercises for nonlinear optimization.
I thought it would be cool to start with some examples of optimization problems and solve them with `pyomo` + some black box solvers.
However, as the students learn more about optimization algorithms I wanted them to also implement some simple meth... | 2022/10/24 | [
"https://Stackoverflow.com/questions/74179391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11785620/"
] | You said using jQuery , so no need to loops and addEventListener , all you need is just specifying displayed data inside link using data attribute (like data-text in below snippet )
use the [hover](https://api.jquery.com/hover/) listener then access current hovered by using **`$(this)`** key word , then display the da... | There's a few issues with your code
* you need to use `innerText` or `innerHtml` instead of `value`
* next you need to pass the event into your mouse over and use the current target instead of `boxLi[i]`
* finally, move your ids to the li as that is what the mouse over is on
Also this isn't jQuery
```js
const firstu... | 14,949 |
18,874,387 | Just a little question : it's possible to force a build in Buildbot via a python script or command line (and not via the web interface) ?
Thank you! | 2013/09/18 | [
"https://Stackoverflow.com/questions/18874387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1330954/"
] | If you have a PBSource configured in your master.cfg, you can send a change from the command line:
```
buildbot sendchange --master {MASTERHOST}:{PORT} --auth {USER}:{PASS}
--who {USER} {FILENAMES..}
``` | You can make a python script using the urlib2 or requests library to simulate a POST to the web UI
```
import urllib2
import urllib
import cookielib
import uuid
import unittest
import sys
from StringIO import StringIO
class ForceBuildApi():
MAX_RETRY = 3
def __init__(self, server):
self.server = serv... | 14,951 |
60,913,598 | I am trying to train EfficientNetB1 on Google Colab and constantly running into different issues with correct import statements from Keras or Tensorflow.Keras, currently this is how my imports look like
```
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.preprocessing.image imp... | 2020/03/29 | [
"https://Stackoverflow.com/questions/60913598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9201770/"
] | The problem is the way you import the efficientnet.
You import it from the `Keras` package and not from the `TensorFlow.Keras` package.
Change your efficientnet import to
```
import efficientnet.tfkeras as enet
``` | Not sure, but this error maybe caused by wrong TF version. Google Colab for now comes with TF 1.x by default. Try this to change the TF version and see if this resolves the issue.
```
try:
%tensorflow_version 2.x
except:
print("Failed to load")
``` | 14,952 |
43,109,167 | Below is my data set
```
Date Time
2015-05-13 23:53:00
```
I want to convert date and time into floats as separate columns in a python script.
The output should be like date as `20150513` and time as `235300` | 2017/03/30 | [
"https://Stackoverflow.com/questions/43109167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7521618/"
] | If all you need is to strip the hyphens and colons, [*str.replace()*](https://docs.python.org/2.7/library/stdtypes.html#str.replace) should do the job:
```
>>> s = '2015-05-13 23:53:00'
>>> s.replace('-', '').replace(':', '')
'20150513 235300'
```
For mort sophisticated reformatting, parse the input with [*time.strp... | If you have a datetime you can use [strftime()](http://strftime.org/)
```
your_time.strftime('%Y%m%d.%H%M%S')
```
And if your variables are string, You can use replace()
```
dt = '2015-05-13 23:53:00'
date = dt.split()[0].replace('-','')
time = dt.split()[1].replace(':','')
fl = float(date+ '.' + time)
``` | 14,953 |
31,244,525 | In python, one can attribute some values to some of the keywords that are already predefined in python, unlike other languages. Why?
This is not all, some.
```
> range = 5
> range
> 5
```
But for
```
> def = 5
File "<stdin>", line 1
def = 5
^
SyntaxError: invalid syntax
```
One possible hypothesis ... | 2015/07/06 | [
"https://Stackoverflow.com/questions/31244525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3302133/"
] | While `range` is nothing but a built-in function, `def` is a keyword. (Most IDEs should indicate the difference with appropriate colors.)
Functions - whether built-in or not - can be redefined. And they don't have to remain functions, but can become integers like `range` in your example. But you can never redefine key... | The keyword 'range' is a function, you can create some other vars as well as sum, max...
In the other hand, keyword 'def' expects a defined structure in order to create a function.
```
def <functionName>(args):
``` | 14,956 |
69,023,789 | I'm working on automating changing image colors using python. The image I'm using is below, i'd love to move it from red to another range of colors, say green, keeping the detail and shading if possible. I've been able to convert *some* of the image to a solid color, losing all detail.
[](https://i.stack.imgur.com/sFW5v.jpg)
```
import cv2
impo... | 14,958 |
41,480,055 | Using Python 2.7 and Django 1.10.4, I was trying to deploy my app to pythonanywhere, but I keep getting this error.
[](https://i.stack.imgur.com/1FGB1.png)
**Error Log**
[](https://i... | 2017/01/05 | [
"https://Stackoverflow.com/questions/41480055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7248057/"
] | First of all, check the link give in the error log - <https://help.pythonanywhere.com/pages/DebuggingImportError/>
You could also search for 'from django core wsgi no module named wsgi'. There are many answers already, and I think you should be able to find the answer to your problem there. | Make sure that your project name is "mysite" if not update this line
```
os.environ['DJANGO_SETTINGS_MODULE'] = '<your-project-name>.settings'
```
Project name will be the directory name parent to your app name, see that in your local machine. | 14,960 |
32,814,489 | I've read numerous tutorials and stackex questions/answers, but apparently my questions is too specific and my knowledge too limited to piece together a solution.
**[Edit]** *My confusion was mostly due to the fact that my project required both a shell script and a makefile to run a simple python program. I was not s... | 2015/09/28 | [
"https://Stackoverflow.com/questions/32814489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4876803/"
] | To pass data between two otherwise unconnected View Controllers you'll need to use:
```
presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
```
and transmit your data via viewWillDisappear like this:
```
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animate... | I have found an answer: using global variables.
Here is what I did:
In my first view controller (the view controller that is sending the string), I made a global variable above the class definition, like this:
```
import UIKit
var chosenClass = String()
class EntryViewController: UIViewController, UITableViewD... | 14,961 |
59,302,243 | I'm using this code with python and opencv for displaying about 100 images. But `imshow` function throws an error.
Here is my code:
```py
nn=[]
for j in range (187) :
nn.append(j+63)
images =[]
for i in nn:
path = "02291G0AR\\"
n1=cv2.imread(path +"Bi000{}".format(i))
... | 2019/12/12 | [
"https://Stackoverflow.com/questions/59302243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7415394/"
] | 1. You have to visualize one image at a time, while you are passing `images` which is a list
2. `cv2.imshow()` takes as first argument the name of the window
So you should iterate on your loaded images like:
```py
for image in images:
cv2.imshow('Image', image)
cv2.waitKey(0) # Wait for user interaction
```... | You can use the following snippet to montage more than one image:
```
from imutils import build_montages
im_shape = (129,196)
montage_shape = (7,3)
montages = build_montages(images, im_shape, montage_shape)
```
`im_shape :` A tuple containing the width and height of each image in the montage. Here we indicate that a... | 14,962 |
53,647,426 | How can we fetch details of particular row from mysql database using variable in python?
I want to print the details of particular row using variable from my database and I think I should use something like this:
```
data = cur.execute("SELECT * FROM loginproject.Pro WHERE Username = '%s';"% rob)
```
But this is sh... | 2018/12/06 | [
"https://Stackoverflow.com/questions/53647426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10333908/"
] | Don't put html in laravel controller, you can return the $employees as data and then add html in your ajax success action | ```
public function search(Request $request){
if($request->ajax())
{
$employees = DB::table('employeefms')->where('last_name','LIKE','%'.$request->search.'%')
->orWhere('first_name','LIKE','%'.$request->search.'%')->get();
if(!empty($employees))
{
return js... | 14,963 |
18,289,377 | I'm using Code::Blocks and want to have gdb python-enabled. So I followed the C::B wiki <http://wiki.codeblocks.org/index.php?title=Pretty_Printers> to configure it.
My pp.gdb is the same as that in the wiki except that I replace the path with my path to printers.py.
```
python
import sys
sys.path.insert(0, 'C:/Pro... | 2013/08/17 | [
"https://Stackoverflow.com/questions/18289377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1549348/"
] | Today, I also see this similar issue, after I update my libstdcxx's pretty from an old gcc4.7.x version to the gcc's trunk HEAD version to fix some other problems.
I'm also using Codeblocks, and I have those two lines in my customized gdb script.
```
from libstdcxx.v6.printers import register_libstdcxx_printers
regis... | You probably don't need to have this code. It seems like the libstdc++ prnters are preloaded -- which is normal in many setups... we designed printers to "just work", and the approach of using python code to explicitly load printers was a transitional thing.
One way to check is to run gdb -nx, start your C++ program, ... | 14,964 |
23,480,431 | I want to format a .py file (that generates a random face every time the page is refreshed) using HTML, in the Terminal, that can run in a browser. I have **chmod`ed** it so it should work, but whenever I run in it in a browser, I get an **internal service error**. Can someone help me figure out what it wrong?
```
#!/... | 2014/05/05 | [
"https://Stackoverflow.com/questions/23480431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2888249/"
] | This is neither valid HTML nor valid Python. You can't simply mix in HTML tags into the middle of a Python script like that: you need at the very least to put them inside quotes so that they are a valid string.
```
#!/usr/bin/python
print "Content-Type: text/html\n"
print """
<!DOCTYPE html>
<html>
<pre>
"""
def ...
... | You need a templating engine like jinja to have this <http://jinja.pocoo.org/> | 14,967 |
28,979,898 | I downloaded `Microsoft Visual C++ Compiler for Python 2.7` and it installed in
`C:\Users\user\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat`
However, I am getting the `error: Unable to find vcvarsall.bat` error when attempting to install "MySQL-python".
I added `C:\Users\user\AppDat... | 2015/03/11 | [
"https://Stackoverflow.com/questions/28979898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3412518/"
] | Use the command prompt shortcut provided from installing the MSI.
This will launch the prompt with VCVarsall.bat activated for the targeted environment.
Depending on your installation, you can find this in the Start Menu under All Program -> Microsoft Visual C++ For Python -> then pick the command prompt based on x64... | this worked:
<https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows>
i uninstalled visual studio 2013 and net framework 4 first.
i didnt need visual studio. i only installed it because i was playing with c++.
this worked on a virtual environment:
add `C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin... | 14,968 |
60,063,620 | I am working with code that my client insists cannot be changed. It needs to be called using a python command like subprocess.call() ... The code includes a use of the exit() function. When exiting, the exit() function contains data as a parameter:
```
exit(data)
```
How can I capture the data parameter that the scr... | 2020/02/04 | [
"https://Stackoverflow.com/questions/60063620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7188090/"
] | I found this in 3 Swift files at the end of my code:
```
class UIImage {
private func newBorderMask(_ borderSize: Int, size: CGSize) -> CGImageRef? {
}
}
```
So I saw that the code was redeclaring `class UIImage` after the `extension UIImage`. In each case, I moved the `private func` into the `extension UII... | You need
```
import UIKit
```
at the top of the file | 14,970 |
10,188,165 | I'm using mongodb for my python(2.7) project with django framework..when i give
python manage.py runserver it will work but if i sync the db (python manage.py syncdb) the following error displayed in terminal
```
Creating tables ...
Traceback (most recent call last):
File "manage.py", line 14, in <module>
exec... | 2012/04/17 | [
"https://Stackoverflow.com/questions/10188165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1095290/"
] | You need to use Django-nonrel instead of Django. | I've used mongoengine with django but you need to create a file like mongo\_models.py for example. In that file you define your Mongo documents. You then create forms to match each Mongo document. Each form has a save method which inserts or updates whats stored in Mongo. Django forms are designed to plug into any data... | 14,971 |
56,693,939 | My dict (`cpc_docs`) has a structure like
```py
{
sym1:[app1, app2, app3],
sym2:[app1, app6, app56, app89],
sym3:[app3, app887]
}
```
My dict has 15K keys and they are unique strings. Values for each key are a list of app numbers and they can appear as values for more than one key.
I've looked here [[Python: Best W... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56693939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5170800/"
] | Your `setdefault` code is almost there, you just need an extra loop over the lists of values:
```
res = {}
for k, lst in cpc_docs.items():
for v in lst:
res.setdefault(v, []).append(k)
``` | ### First create a list of key, value tuples
```py
new_list=[]
for k,v in cpc_docs.items():
for i in range(len(v)):
new_list.append((k,v[i]))
```
### Then for each tuple in the list, add the key if it isn't in the dict and append the
```py
doc_cpc = defaultdict(set)
for tup in cpc_doc_list:
doc_cpc... | 14,972 |
6,143,087 | For one of my projects I have a python program built around the python [cmd](http://docs.python.org/library/cmd.html) class. This allowed me to craft a mini language around sql statements that I was sending to a database. Besides making it far easier to connect with python, I could do things that sql can't do. This was... | 2011/05/26 | [
"https://Stackoverflow.com/questions/6143087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/724357/"
] | The limitations of making a "mini language" have become apparent.
Proper languages have a tree-like structure and more complex syntax than `cmd` can handle easily.
Sometimes it's actually easier to use Python directly than it is to invent your own DSL.
Currently, your DSL probably reads a script-like file of command... | After examining the problem set some more, I've come to the conclusion that I can leave the minilanguage alone. It has all the features I need, and I don't have the time to rebuild the project from the ground up. This has been an interesting problem and I'm no longer sure I would build another minilanguage if I encount... | 14,973 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.