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 |
|---|---|---|---|---|---|---|
41,850,558 | I have a model called "document-detail-sample" and when you call it with a GET, something like this, **GET** `https://url/document-detail-sample/` then you get every "document-detail-sample".
Inside the model is the id. So, if you want every Id, you could just "iterate" on the list and ask for the id. Easy.
But... th... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41850558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050960/"
] | You could use `@list_route` decorator
```
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
... | Assuming you don't need pagination, just override the `list` method like so
```
class DocumentDetailSampleViewSet(viewsets.ModelViewSet):
queryset = DocumentDetailSample.objects.all()
serializer_class = DocumentDetailSampleSerializer
def list(self, request):
return Response(self.get_queryset().val... | 0 |
14,585,722 | Suppose you have a python function, as so:
```
def foo(spam, eggs, ham):
pass
```
You could call it using the positional arguments only (`foo(1, 2, 3)`), but you could also be explicit and say `foo(spam=1, eggs=2, ham=3)`, or mix the two (`foo(1, 2, ham=3)`).
Is it possible to get the same kind of functionality... | 2013/01/29 | [
"https://Stackoverflow.com/questions/14585722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731881/"
] | You can do something like this:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--foo',dest='foo',default=None)
parser.add_argument('bar',nargs='?',default=argparse.SUPPRESS)
parser.add_argument('--bar',dest='bar',default=None)... | I believe this is what you are looking for [Argparse defaults](http://docs.python.org/dev/library/argparse.html#default) | 1 |
72,950,868 | I would like to add a closing parenthesis to strings that have an open parenthesis but are missing a closing parenthesis.
For instance, I would like to modify "The dog walked (ABC in the park" to be "The dog walked (ABC) in the park".
I found a similar question and solution but it is in Python ([How to add a missing c... | 2022/07/12 | [
"https://Stackoverflow.com/questions/72950868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533566/"
] | Try this
```
stringr::str_replace_all(text, '\\([A-Z]+(?!\\))\\b', '\\0\\)')
```
* output
```
"The dog walked (ABC) in the park"
``` | Not a one liner, but it does the trick and is (hopefully!) intuitive.
```
library(stringr)
add_brackets = function(text) {
brackets = str_extract(text, "\\([:alpha:]+") # finds the open bracket and any following letters
brackets_new = paste0(brackets, ")") # adds in the closing brackets
str_replace(text, ... | 4 |
67,609,973 | I chose to use Python 3.8.1 Azure ML in Azure Machine learning studio, but when i run the command
`!python train.py`, it uses python Anconda 3.6.9, when i downloaded python 3.8 and run the command `!python38 train.py` in the same dir as before, the response was `python3.8: can't open file` .
Any idea?
Also Python 3 in ... | 2021/05/19 | [
"https://Stackoverflow.com/questions/67609973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14915505/"
] | You should try adding a new Python 3.8 Kernel. Here and instructions how to add a new Kernel: <https://learn.microsoft.com/en-us/azure/machine-learning/how-to-access-terminal#add-new-kernels> | Yeah I understand your pain point, and I agree that calling bash commands in a notebook cell should execute in the same conda environment as the one associated with the selected kernel of the notebook. I think this is bug, I'll flag it to the notebook feature team, but I encourage you to open a priority support ticket ... | 7 |
58,483,706 | I am new to python and trying my hands on certain problems. I have a situation where I have 2 dataframe which I want to combine to achieve my desired dataframe.
I have tried .merge and .join, both of which was not able to get my desired outbcome.
let us suppose I have the below scenario:
```
lt = list(['a','b','c','... | 2019/10/21 | [
"https://Stackoverflow.com/questions/58483706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11378087/"
] | If you don't mind the order of the columns changing, this is just a right join. The only caveat is that those are performed on rows rather than columns, so you need to transpose first:
```py
In [44]: df.T.join(df1.T, how='right').T
Out[44]:
a a a b b b c d
0 10 10 10 11 11 11 12 12
1 15 15 ... | Use [`concat()`](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html)
```py
pd.concat([df, df1], axis=0, join='inner', sort=False)
a b c d a b a b
0 10 11 12 12 10 11 10 11
1 15 14 12 10 15 14 15 14
``` | 8 |
14,187,973 | Simmilar question (related with Python2: [Python: check if method is static](https://stackoverflow.com/questions/8727059/python-check-if-method-is-static))
Lets concider following class definition:
```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
```
In Python 3 ... | 2013/01/06 | [
"https://Stackoverflow.com/questions/14187973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | ```
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))
<class 'staticmethod'>
<class 'function'>
``` | I needed this solution and wrote the following based on the answer from @root
```
def is_method_static(cls, method_name):
# http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static
for c in cls.mro():
if method_name in c.__dict__:
return isinstance(c.__dict__[method_nam... | 10 |
46,132,431 | I have written code to generate numbers from 0500000000 to 0500000100:
```
def generator(nums):
count = 0
while count < 100:
gg=print('05',count, sep='')
count += 1
g = generator(10)
```
as I use linux, I thought I may be able to use this command `python pythonfilename.py >> file.txt`
Yet,... | 2017/09/09 | [
"https://Stackoverflow.com/questions/46132431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548783/"
] | Here I've assumed we're laying out two general images, rather than plots. If your images are actually plots you've created, then you can lay them out as a single image for display using `gridExtra::grid.arrange` for grid graphics or `par(mfrow=c(1,2))` for base graphics and thereby avoid the complications of laying out... | Put them in the same code chunk and do not use align. Let them use html.
THis has worked for me.
```
````{r echo=FALSE, fig.height=3.0, fig.width=3.0}
#type your code here
ggplot(anscombe, aes(x=x1 , y=y1)) + geom_point()
+geom_smooth(method="lm") +
ggtitle("Results for x1 and y1 ")
ggplot(anscombe, aes(x=... | 13 |
54,007,542 | input is like:
```
text="""Hi Team from the following Server :
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
</tbody>
</table>
<p> </p>
<p>Please archive the followin... | 2019/01/02 | [
"https://Stackoverflow.com/questions/54007542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9901523/"
] | Use `BeautifulSoup` to parse HTML
**Ex:**
```
from bs4 import BeautifulSoup
text="""<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td>
</tr>
... | You can use `HTMLParser` as demonstrated below:
```
from HTMLParser import HTMLParser
s = \
"""
<html>
<p>Hi Team from the following Server :</p>
<table border="0" cellpadding="0" cellspacing="0" style="width:203pt">
<tbody>
<tr>
<td style="height:15.0pt; width:203pt">ratsuite.sby.ibm.com</td... | 14 |
38,776,104 | I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use
```
$ python myfile.py &> out.txt
```
to do the same task that I want, but I need to do it from the Python script itself.
I looked into the questions [Redirect subprocess stder... | 2016/08/04 | [
"https://Stackoverflow.com/questions/38776104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1461999/"
] | This works
```
sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout
``` | A SyntaxError in a Python file like the above is raised before your program even begins to run:
Python files are compiled just like in any other compiled language - if the parser or compiler can't find sense in your Python file, no executable bytecode is generated, therefore the program does not run.
The correct way t... | 17 |
57,843,695 | I haven't changed my system configuration, But I'm spotting this error for the first time today.
I've reported it here: <https://github.com/jupyter/notebook/issues/4871>
```
> jupyter notebook
[I 10:44:20.102 NotebookApp] JupyterLab extension loaded from /usr/local/anaconda3/lib/python3.7/site-packages/jupyterlab
[I ... | 2019/09/08 | [
"https://Stackoverflow.com/questions/57843695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435129/"
] | I fixed this by updating both jupyter on pip and pip3 (just to be safe) and this fixed the problem
using both
>
> `pip install --upgrade jupyter`
>
>
>
and
>
> `pip3 install --upgrade jupyter --no-cache-dir`
>
>
>
I believe you can do this in the terminal as well as in conda's terminal (since conda envs al... | As per [Where does Jupyter install site-packages on macOS?](https://stackoverflow.com/questions/57843888/where-does-jupyter-install-site-packages-on-macos), I locate where on my system `jupyter` is searching for this missing file:
```
> find / -path '*/static/components' 2>/dev/null
/usr/local/anaconda3/pkgs/notebook... | 18 |
44,175,800 | Simple question: given a string
```
string = "Word1 Word2 Word3 ... WordN"
```
is there a pythonic way to do this?
```
firstWord = string.split(" ")[0]
otherWords = string.split(" ")[1:]
```
Like an unpacking or something?
Thank you | 2017/05/25 | [
"https://Stackoverflow.com/questions/44175800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131783/"
] | Since Python 3 and [PEP 3132](https://www.python.org/dev/peps/pep-3132/), you can use extended unpacking.
This way, you can unpack arbitrary string containing any number of words. The first will be stored into the variable `first`, and the others will belong to the list (possibly empty) `others`.
```
first, *others =... | From [Extended Iterable Unpacking](https://www.python.org/dev/peps/pep-3132/).
Many algorithms require splitting a sequence in a "first, rest" pair, if you're using Python2.x, you need to try this:
```
seq = string.split()
first, rest = seq[0], seq[1:]
```
and it is replaced by the cleaner and probably more efficie... | 19 |
28,717,067 | I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it w... | 2015/02/25 | [
"https://Stackoverflow.com/questions/28717067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4529171/"
] | Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop.
A much better way to do this would be simply run a COUNT query, get the single result with `fetchone(... | In python you should check for `None` not `NULL`. In your code you can just check for object, if it is not None then control should go inside `if` otherwise `else` will be executed
```
for row in rows:
if row:
print('Available')
else:
print('No available copies of the said book in the library')... | 20 |
65,995,857 | I'm quite new to coding and I'm working on a math problem in python.
To solve it, I would like to extract the first 7 numbers from a string of one hundred 50-digit number (take first 7 numbers, skip 43 numbers, and then take the first 7 again). The numbers aren't separated in any way (just one long string).
Then I want... | 2021/02/01 | [
"https://Stackoverflow.com/questions/65995857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15117090/"
] | Python allows you to iterate over a range with custom step sizes. So that should be allow you to do something like:
```py
your_list = []
for idx in range(0, len(string), 50): # Indexes 0, 50, 100, so on
first_seven_digits = string[idx:idx+7] # Say, "1234567"
str_to_int = int(first_seven_digits) # Converts to t... | first of all your number string is 4999 characters long so you'll have to add one. secondly if you want to use numpy you could make a 100 by 50 array by reshaping the original 5000 long array. like this
```
arr = np.array(list(number)).reshape(100, 50)
```
than you can slice the arr in a way that the first 7 element... | 22 |
21,307,128 | Since I have to mock a static method, I am using **Power Mock** to test my application.
My application uses \**Camel 2.1*\*2.
I define routes in *XML* that is read by *camel-spring* context.
There were no issues when `Junit` alone was used for testing.
While using power mock, I get the error listed at the end of the po... | 2014/01/23 | [
"https://Stackoverflow.com/questions/21307128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2345966/"
] | This error message usually means that your specified truststore can not be read. What I would check:
* Is the path correct? (I'm sure you checked this...)
* Has the user who started the JVM enough access privileges to read the
trustore?
* When do you set the system properties? Are they already set when the webservice ... | ```
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
```
>
> * In my case, I have 2 duplicate Java installations (OpenJDK and
> JDK-17).
> * I installed JDK-17 after configuring environment variable for OpenJDK and... | 23 |
49,059,660 | I am looking for a simple way to constantly monitor a log file, and send me an email notification every time thhis log file has changed (new lines have been added to it).
The system runs on a Raspberry Pi 2 (OS Raspbian /Debian Stretch) and the log monitors a GPIO python script running as daemon.
I need something ver... | 2018/03/01 | [
"https://Stackoverflow.com/questions/49059660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9431262/"
] | You asked for simple:
```
#!/bin/bash
cur_line_count="$(wc -l myfile.txt)"
while true
do
new_line_count="$(wc -l myfile.txt)"
if [ "$cur_line_count" != "$new_line_count" ]
then
python ./sendmail.py
fi
cur_line_count="$new_line_count"
sleep 5
done
``` | I've done this a bunch of different ways. If you run a cron job every minute that counts the number of lines (wc -l) compares that to a stored count (e.g. in /tmp/myfilecounter) and sends the emails when the numbers are different.
If you have inotify, there are more direct ways to get "woken up" when the file changes,... | 24 |
56,794,886 | guys! So I recently started learning about python classes and objects.
For instance, I have a following list of strings:
```
alist = ["Four", "Three", "Five", "One", "Two"]
```
Which is comparable to a class of Numbers I have:
```
class Numbers(object):
One=1
Two=2
Three=3
Four=4
Five=5
```
How co... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56794886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10713538/"
] | If you are set on using the class, one way would be to use [`__getattribute__()`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__)
```
print([Numbers().__getattribute__(a) for a in alist])
#[4, 3, 5, 1, 2]
```
But a much better (and more pythonic IMO) way would be to use a `dict`:
```
Num... | **EDIT:** I suppose that the words and numbers are just a trivial example, a dictionary is the right way to do it if that's not the case as written in the comments.
Your assumptions are correct - either create an empty list and populate it using for loop, or use list comprehension with a for loop to create a new list ... | 25 |
36,108,377 | I want to count the number of times a word is being repeated in the review string
I am reading the csv file and storing it in a python dataframe using the below line
```
reviews = pd.read_csv("amazon_baby.csv")
```
The code in the below lines work when I apply it to a single review.
```
print reviews["review"][1]... | 2016/03/19 | [
"https://Stackoverflow.com/questions/36108377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2861976/"
] | You're trying to split the entire review column of the data frame (which is the Series mentioned in the error message). What you want to do is apply a function to each row of the data frame, which you can do by calling [apply](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html) on the dat... | Well, the problem is with:
```
reviews["review"]
```
The above is a Series. In your first snippet, you are doing this:
```
reviews["review"][1].split("disappointed")
```
That is, you are putting an index for the review. You could try looping over all rows of the column and perform your desired action. For example... | 28 |
72,329,252 | Let's say we have following list. This list contains response times of a REST server in a traffic run.
[1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
I need following output
Percentage of the requests served within a certain time (ms)
50% 3
60% 4
70% 5
80% 6
90% 7
100% 9
How can we get it done in python? This is apache bench... | 2022/05/21 | [
"https://Stackoverflow.com/questions/72329252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4137009/"
] | You can try something like this:
```
responseTimes = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
for time in range(3,10):
percentage = len([x for x in responseTimes if x <= time])/(len(responseTimes))
print(f'{percentage*100}%')
```
>
> *"So basically lets say at 50%, we need to find point in list below which 50% of the... | You basically need to compute the cumulative ratio of the sorted response times.
```py
from collections import Counter
values = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
frequency = Counter(values) # {1: 2, 2: 1, 3: 2, ...}
total = 0
n = len(values)
for time in sorted(frequency):
total += frequency[time]
print(time, f'... | 33 |
50,239,640 | In python have three one dimensional arrays of different shapes (like the ones given below)
```
a0 = np.array([5,6,7,8,9])
a1 = np.array([1,2,3,4])
a2 = np.array([11,12])
```
I am assuming that the array `a0` corresponds to an index `i=0`, `a1` corresponds to index `i=1` and `a2` corresponds to `i=2`. With these ass... | 2018/05/08 | [
"https://Stackoverflow.com/questions/50239640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3761166/"
] | You can use `numpy` stack functions to speed up:
```
aa = [a0, a1, a2]
np.hstack(tuple(np.vstack((np.full(ai.shape, i), ai)) for i, ai in enumerate(aa))).T
``` | One way to do this would be a simple list comprehension:
```
result = np.array([[i, arr_v] for i, arr in enumerate([a0, a1, a2])
for arr_v in arr])
>>> result
array([[ 0, 5],
[ 0, 6],
[ 0, 7],
[ 0, 8],
[ 0, 9],
[ 1, 1],
[ 1, 2],
[ 1... | 34 |
45,939,564 | I am accessing a python file via python.
The google sheets looks like the following:
[](https://i.stack.imgur.com/eIW7v.png)
But when I access it via:
```
self.probe=[]
self.scope = ['https://spreadsheets.google.com/feeds']
self.creds = S... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45939564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3554329/"
] | I'm not familiar with gspread, which appears to be a third-party client for the Google Sheets API, but it looks like you should be using [`get_all_values`](https://github.com/burnash/gspread#getting-all-values-from-a-worksheet-as-a-list-of-lists) rather than `get_all_records`. That will give you a list of lists, rather... | Python dictionaries are unordered. There is the [OrderedDict](https://docs.python.org/3.6/library/collections.html#collections.OrderedDict) in collections, but hard to say more about what the best course of action should be without more insight into why you need this dictionary ordered... | 36 |
55,508,830 | In a virtual Env with Python 3.7.2, I am trying to run django's `python manage.py startap myapp` and I get this error:
```
raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.8.2).
... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6154769/"
] | I've just been through this. I had to install a separate newer version of SQLite, from
<https://www.sqlite.org/download.html>
That is in /usr/local/bin. Then I had to recompile Python, telling it to look there:
```
sudo LD_RUN_PATH=/usr/local/lib ./configure --enable-optimizations
sudo LD_RUN_PATH=/usr/local/lib mak... | In addition to the above mentioned answers, just in case if you experience this behaviour on Travis CI, add `dist: xenial` directive to fix it. | 37 |
46,143,091 | I'm pretty new to python so it's a basic question.
I have data that I imported from a csv file. Each row reflects a person and his data. Two attributes are Sex and Pclass. I want to add a new column (predictions) that is fully depended on those two in one line. If both attributes' values are 1 it should assign 1 to th... | 2017/09/10 | [
"https://Stackoverflow.com/questions/46143091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5252187/"
] | You could try adding a composite index
```
create index test on screenshot (DateTaken, id)
``` | Try running this query:
```
SELECT COUNT(*) as total
FROM screenshot
WHERE DateTaken BETWEEN '2000-05-01' AND '2000-06-10';
```
The reference to `ID` in the `SELECT` could be affecting the use of the index. | 45 |
71,568,396 | We are using a beam multi-language pipeline using python and java(ref <https://beam.apache.org/documentation/sdks/python-multi-language-pipelines/>). We are creating a cross-language pipeline using java. We have some external jar files that required a java library path. Code gets compiled properly and is able to create... | 2022/03/22 | [
"https://Stackoverflow.com/questions/71568396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9648514/"
] | A Worksheet Change Event: Monitor Change in Column's Data
---------------------------------------------------------
* I personally would go with JvdV's suggestion in the comments.
* On each manual change of a cell, e.g. in column `A`, it will check the formula
`=SUM(A2:ALastRow)` in cell `A1` and if it is not correct ... | Use a nested function as below:
=SUM(OFFSET(A2,,,COUNTA(A2:A26))) | 47 |
49,005,651 | This question is motivated by my another question: [How to await in cdef?](https://stackoverflow.com/questions/48989065/how-to-await-in-cdef)
There are tons of articles and blog posts on the web about `asyncio`, but they are all very superficial. I couldn't find any information about how `asyncio` is actually implemen... | 2018/02/27 | [
"https://Stackoverflow.com/questions/49005651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691066/"
] | It all boils down to the two main challenges that asyncio is addressing:
* How to perform multiple I/O in a single thread?
* How to implement cooperative multitasking?
The answer to the first point has been around for a long while and is called a [select loop](https://en.wikipedia.org/wiki/Asynchronous_I/O#Select(/po... | If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it allows ... | 48 |
36,590,875 | How to obtain absolute path via relative path for 'other' project files, not those python file in the project, like Java?
```
D:\Workspaces\ABCPythonProject\
|- src
| |-- com/abc
| |-- conf.py
| |-- abcd.py
| |-- defg.py
| |-- installation.rst
|- resources
| |-- a.txt
| |-- b.txt
| |--... | 2016/04/13 | [
"https://Stackoverflow.com/questions/36590875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762932/"
] | For images you'll have to use:
```
<img src="url">
``` | It should be in following way,
```
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['u_id'] . '</td>';
echo '<td>'. $row['u_role'] . '</td>';
echo '<td>'. $row['u_name'] . '</td>';
echo '<td>'. $row['u_passw'] . '</td>';
echo '<td>'. $row['u_init'] . '</td>';
echo '<td>'. $row['c_name... | 58 |
36,215,958 | I want to filter the moment of a day only with hour and minutes.
For example, a function that return true if now is between the 9.15 and 11.20 of the day.
I tried with datetime but with the minutes is littlebit complicated.
```
#!/usr/bin/python
import datetime
n = datetime.datetime.now()
sta = datetime.time(19,18... | 2016/03/25 | [
"https://Stackoverflow.com/questions/36215958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341022/"
] | You can use tuple comparisons to do any subinterval comparisons pretty easily:
```
>>> def f(dt):
... return (9, 15) <= (dt.hour, dt.minute) < (11, 21)
...
>>> d = datetime.datetime.now()
>>> str(d)
'2016-03-25 09:50:51.782718'
>>> f(d)
True
>>> f(d + datetime.timedelta(hours=2)
False
```
This accepts any dateti... | You'll need to use the combine class method:
```
import datetime
def between():
now = datetime.datetime.now()
start = datetime.datetime.combine(now.date(), datetime.time(9, 15))
end = datetime.datetime.combine(now.date(), datetime.time(11, 20))
return start <= now < end
``` | 61 |
5,965,655 | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | 2011/05/11 | [
"https://Stackoverflow.com/questions/5965655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748676/"
] | You want *inter-process communication*. Sockets are the first thing that comes to mind; you'd need to set up a socket to *listen* for a connection (on the same machine) in PHP and set up a socket to *connect* to the listening socket in Python and *send* it its status.
Have a look at [this socket programming overview](... | I think you would have to use a meta refresh and maybe have the python write the status to a file and then have the php read from it.
You could use AJAX as well to make it more dynamic.
Also, probably shouldn't use exec()...that opens up a world of vulnerabilities. | 62 |
31,480,921 | I can't seem to get the interactive tooltips powered by mpld3 to work with the fantastic lmplot-like scatter plots from seaborn.
I'd love any pointer on how to get this to work! Thanks!
Example Code:
```
# I'm running this in an ipython notebook.
%matplotlib inline
import matplotlib.pyplot as plt, mpld3
mpld3.enable... | 2015/07/17 | [
"https://Stackoverflow.com/questions/31480921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1270151/"
] | I don't think that there is an easy way to do this currently. I can get some of the tooltips to show by replacing your `tooltip` constructor with the following:
```
ax = plt.gca()
pts = ax.get_children()[3]
tooltip = mpld3.plugins.PointLabelTooltip(pts, labels=list(data.label))
```
This only works for the points out... | Your code works for me on `ipython` (no notepad) when saving the figure to file with `mpld3.save_html(fig,"./out.html")`. May be an issue with `ipython` `notepad`/`mpld3` compatibility or `mpld3.display` (which causes an error for me, although I think this is related to an old version of matplotlib on my computer).
T... | 68 |
28,180,252 | I am trying to create a quiver plot from a NetCDF file in Python using this code:
```
import matplotlib.pyplot as plt
import numpy as np
import netCDF4 as Dataset
ncfile = netCDF4.Dataset('30JUNE2012_0300UTC.cdf', 'r')
dbZ = ncfile.variables['MAXDBZF']
data = dbZ[0,0]
U = ncfile.variables['UNEW'][:]
V = ncfile.varia... | 2015/01/27 | [
"https://Stackoverflow.com/questions/28180252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4500459/"
] | `ValueError: too many values to unpack` is because the line `379` of your program is trying to assign two variables (`nr`, `nc`) from `U.shape` when there are not enough variables to assign these values to.
Look above on line `377` - that is correctly assigning two values (`1` and `U.shape[0]` to `nr` and `nc` but lin... | Probably more useful to solve future problems rather then author's but still:
The problem was likely that the netcdf file had a time dimension, therefore U and V where 3 dimensional arrays - you should choose the time slice or aggregate the data across the time dimension. | 71 |
36,486,120 | I'm trying to centre and normalise a data set in python with the following code
```
mean = np.mean(train, axis=0)
std = np.std(train, axis=0)
norm_train = (train - mean) / std
```
The problem is that I get a devision by zero error. Two of the values in the data set end up having a zero std. The data set if of shape ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36486120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531296/"
] | Since the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) is calculated by taking the sum of the *squared* deviations from the mean, a zero standard deviation can only be possible when all the values of a variable are the same (all equal to the mean). In this case, those variables have no discrim... | You could just replace the 0 std to 1 for that feature. This would basically mean that the scaled value would be zero for all the data points for that feature. This makes sense as this implies that the feature values do not deviate even a bit form the mean(as the values is constant, the constant is the mean.)
FYI- Thi... | 72 |
3,950,368 | >
> **Possible Duplicate:**
>
> [What do I use for a max-heap implementation in Python?](https://stackoverflow.com/questions/2501457/what-do-i-use-for-a-max-heap-implementation-in-python)
>
>
>
Python has a min heap implemented in the heapq module. However, if one would want a max heap, would one have to build... | 2010/10/16 | [
"https://Stackoverflow.com/questions/3950368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475790/"
] | You could multiply your numbers by -1 and use the min heap. | No need to implement a max heap from scratch. You can easily employ a bit of math to turn your min heap into a max heap!
See [this](http://www.mail-archive.com/python-list@python.org/msg238926.html) and [this](http://code.activestate.com/recipes/502295/) - but really [this SO answer](https://stackoverflow.com/question... | 77 |
55,522,649 | I have installed numpy but when I import it, it doesn't work.
```
from numpy import *
arr=array([1,2,3,4])
print(arr)
```
Result:
```
C:\Users\YUVRAJ\PycharmProjects\mycode2\venv\Scripts\python.exe C:/Users/YUVRAJ/PycharmProjects/mycode2/numpy.py
Traceback (most recent call last):
File "C:/Users/YUVRAJ/PycharmPr... | 2019/04/04 | [
"https://Stackoverflow.com/questions/55522649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11313285/"
] | The problem is you named your script as `numpy.py`, which is a conflict with the module numpy that you need to use. Just rename your script to something else and will be fine. | Instead of using `from numpy import *`
Try using this:
```
import numpy
from numpy import array
```
And then add your code:
```
arr=array([1,2,3,4])
print(arr)
```
---
**EDIT:** Even though this is the accepted answer, this may not work under all circumstances. If this doesn't work, see [adrtam's answer](https:... | 78 |
24,703,432 | I am attempting to catch messages by topic by using the message\_callback\_add() function in [this library](https://pypi.python.org/pypi/paho-mqtt#usage-and-api). Below is my entire module that I am using to deal with my mqtt subscribe and publishing needs. I have been able to test that the publish works, but I can't s... | 2014/07/11 | [
"https://Stackoverflow.com/questions/24703432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851048/"
] | I called `loop_start` in the wrong place.
I moved the call to right after the connect statement and it now works.
Here is the snippet:
```
client_uniq = "pubclient_"+str(mypid)
mqttclient = paho.Client(client_uniq, False) #nocleanstart
mqttclient.connect(broker, port, 60)
mqttclient.loop_start()
mqttclient.subscri... | `loop_start()` will return immediately, so your program will quit before it gets chance to do anything.
You've also called `subscribe()` before `message_callback_add()` which doesn't make sense, although in this specific example it probably doesn't matter. | 79 |
23,190,348 | Has the alsaaudio library been ported to python3? i have this working on python 2.7 but not on python 3.
is there another library for python 3 if the above cannot be used? | 2014/04/21 | [
"https://Stackoverflow.com/questions/23190348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612242/"
] | I have compiled alsaaudio for python3 manually.
You can install it by following the steps given below.
1. Make sure that **gcc, python3-dev, libasound2-dev** packages are installed in your machine (install them using synaptic if you are using Ubuntu).
2. Download and extract the following package
<http://sourceforg... | It's now called pyalsaaudio.
For me pip install pyalsaaudio worked. | 80 |
66,929,254 | Is there a library for interpreting python code within a python program?
Sample usage might look like this..
```
code = """
def hello():
return 'hello'
hello()
"""
output = Interpreter.run(code)
print(output)
```
which then outputs
`hello` | 2021/04/03 | [
"https://Stackoverflow.com/questions/66929254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12594122/"
] | found this example from grepper
```
the_code = '''
a = 1
b = 2
return_me = a + b
'''
loc = {}
exec(the_code, globals(), loc)
return_workaround = loc['return_me']
print(return_workaround)
```
apparently you can pass global and local scope into `exec`. In your use case, you would just use a named variable instead of ... | You can use the `exec` function. You can't get the return value from the code variable. Instead you can print it there itself.
```
code = """
def hello():
print('hello')
hello()
"""
exec(code)
``` | 81 |
65,697,374 | So I am a beginner at python, and I was trying to install packages using pip. But any time I try to install I keep getting the error:
>
> ERROR: Could not install packages due to an EnvironmentError: [WinError 2] The system cannot find the file specified: 'c:\python38\Scripts\sqlformat.exe' -> 'c:\python38\Scripts\sq... | 2021/01/13 | [
"https://Stackoverflow.com/questions/65697374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14996295/"
] | Try running command line as administrator. The issue looks like its about permission. To run as administrator. Type cmd on search bar and right click on icon of command prompt. There you will find an option of run as administrator. Click the option and then try to install package | Looks like a permissions error. You might try starting the installation with admin rights or install the package only for your current user with:
```
pip install --user package
``` | 82 |
59,662,028 | I am trying to retrieve app related information from Google Play store using selenium and BeautifulSoup. When I try to retrieve the information, I got webdriver exception error. I checked the chrome version and chrome driver version (both are compatible). Here is the weblink that is causing the issue, code to retrieve ... | 2020/01/09 | [
"https://Stackoverflow.com/questions/59662028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293224/"
] | I think this is due to the chromedriver encoding problem.
See <https://bugs.chromium.org/p/chromium/issues/detail?id=723592#c9> for additional information about this bug.
Instead of selenium you can get page source using BeautifulSoup as follows.
```
import requests
from bs4 import BeautifulSoup
r = requests.get('ht... | try this
```
driver = webdriver.Chrome('path')
driver.get('https://play.google.com/store/apps/details?id=com.tudasoft.android.BeMakeup&hl=en&showAllReviews=true')
# retrieve data you want, for example
review_user_list = driver.find_elements_by_class_name("X43Kjb")
``` | 84 |
36,781,198 | I'm sending an integer from python using pySerial.
```
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600);
ser.write(b'5');
```
When i compile,the receiver LED on arduino blinks.However I want to cross check if the integer is received by arduino. I cannot use Serial.println() because the port is busy. I... | 2016/04/21 | [
"https://Stackoverflow.com/questions/36781198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6237876/"
] | A simple way to do it using the standard library :
```
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class Example {
private static final int POOL_SIZE = 5;
private st... | I would recommend reading up on specific tutorials, such as the Java Language Tutorial (available as a book - at least, it used to be - as well as on the Java website <https://docs.oracle.com/javase/tutorial/essential/concurrency/>)
However as others have cautioned, getting into threading is a challenge and requires g... | 87 |
34,685,486 | After installing my python project with `setup.py` and executing it in terminal I get the following error:
```
...
from ui.mainwindow import MainWindow
File "/usr/local/lib/python2.7/dist-packages/EpiPy-0.1-py2.7.egg/epipy/ui/mainwindow.py", line 9, in <module>
from model.sir import SIR
ImportError: No module na... | 2016/01/08 | [
"https://Stackoverflow.com/questions/34685486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2609713/"
] | What I would do is to use absolute imports everywhere (from epipy import ...). That's what is recommanded in [PEP 328](https://docs.python.org/2.5/whatsnew/pep-328.html).
Your imports won't work anymore if the project is not installed. You can add the project directory to your PYTHONPATH, install the package, or, what... | I had a similar issue with one of my projects.
I've been able to solve my issue by adding this line at the start of my module (before all imports besides sys & os, which are required for this insert), so that it would include the parent folder and by that it will be able to see the parent folder (turns out it doesn't d... | 88 |
42,968,543 | I have a file displayed as follows. I want to delete the lines start from `>rev_` until the next line with `>`, not delete the `>` line. I want a python code to realize it.
input file:
```
>name1
fgrsagrhshsjtdkj
jfsdljgagdahdrah
gsag
>rev_name1 # delete from here
jfdsfjdlsgrgagrehdsah
fsagasfd ... | 2017/03/23 | [
"https://Stackoverflow.com/questions/42968543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4672728/"
] | I'd recommend at least trying to come up with a solution on your own before asking us on here. Ask yourself questions regarding what different ways I can work towards a solution, will parsing character by character/line by line/regex be sufficient for this problem.
But in this case since determining when to start and... | The code also can be as follows:
```
with open("human.fasta") as inf, open("human_norev.fasta",'w') as outf:
del_start = False
for line in inf:
if line.startswith('>rev_'):
del_start = True
elif line.startswith('>'):
del_start = False
if not del_start:
... | 89 |
49,396,554 | Okay, so I have the following issue. I have a Mac, so the the default Python 2.7 is installed for the OS's use. However, I also have Python 3.6 installed, and I want to install a package using Pip that is only compatible with python version 3. How can I install a package with Python 3 and not 2? | 2018/03/21 | [
"https://Stackoverflow.com/questions/49396554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9525828/"
] | To download use
```
pip3 install package
```
and to run the file
```
python3 file.py
``` | Why do you ask such a thing here?
<https://docs.python.org/3/using/mac.html>
>
> 4.3. Installing Additional Python Packages
> There are several methods to install additional Python packages:
>
>
> Packages can be installed via the standard Python distutils mode (python setup.py install).
> Many packages can also... | 91 |
57,754,497 | So I think tensorflow.keras and the independant keras packages are in conflict and I can't load my model, which I have made with transfer learning.
Import in the CNN ipynb:
```
!pip install tensorflow-gpu==2.0.0b1
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
```
Loading this pretraine... | 2019/09/02 | [
"https://Stackoverflow.com/questions/57754497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10780811/"
] | Yes, there is a conflict between `tf.keras` and `keras` packages, you trained the model using `tf.keras` but then you are loading it with the `keras` package. That is not supported, you should use only one version of this package.
The specific problem is that you are using TensorFlow 2.0, but the standalone `keras` pa... | Try to replace
```
from keras.models import load_model
model =load_model('Leavesnet Model.h5')
```
with
`model = tf.keras.models.load_model(model_path)`
It works for me, and I am using:
tensorflow version: 2.0.0
keras version: 2.3.1
You can check the following:
<https://www.tensorflow.org/api_docs/python/tf/keras... | 93 |
66,196,791 | So take a triangle formatted as a nested list.
e.g.
```
t = [[5],[3, 6],[8, 14, 7],[4, 9, 2, 0],[9, 11, 5, 2, 9],[1, 3, 8, 5, 3, 2]]
```
and define a path to be the sum of elements from each row of the triangle,
moving 1 to the left or right as you go down rows. Or in python
the second index either stays the same o... | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15208320/"
] | We can simplify the expression a bit by including all the rows in the second argument to reduce - there's no reason to pass the last row as third parameter (the starting value) of `reduce`.
Then, it really helps to give your variables meaningful names, which the original code badly fails to do.
So, this becomes:
```... | you can spell out the lambda function so it can print. does this help you understand?
```
t = [[5],[3, 6],[8, 14, 7],[4, 9, 2, 0],[9, 11, 5, 2, 9],[1, 3, 8, 5, 3, 2]]
def g( xs, ys):
ans=[a + max(b, c) for (a, b, c) in zip(ys, xs, xs[1:])]
print(ans)
return ans
def maxPathSum(rows):
return reduce(
... | 96 |
2,291,176 | I need to arrange some kind of encrpytion for generating user specific links. Users will be clicking this link and at some other view, related link with the crypted string will be decrypted and result will be returned.
For this, I need some kind of encryption function that consumes a number(or a string) that is the pr... | 2010/02/18 | [
"https://Stackoverflow.com/questions/2291176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151937/"
] | There are no encryption algorithms, per se, built in to Python. However, you might want to look at the [Python Cryptography Toolkit](http://www.dlitz.net/software/pycrypto/) (PyCrypt). I've only tinkered with it, but it's referenced in Python's documentation on [cryptographic services](http://docs.python.org/library/cr... | Django has features for this now. See <https://docs.djangoproject.com/en/dev/topics/signing/>
Quoting that page:
"Django provides both a low-level API for signing values and a high-level API for setting and reading signed cookies, one of the most common uses of signing in Web applications.
You may also find signin... | 97 |
11,632,154 | In python if I have two dictionaries, specifically Counter objects that look like so
```
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
```
Can I combine these dictionaries so that the results is a dictionary of lists, as follows:
```
c3 =... | 2012/07/24 | [
"https://Stackoverflow.com/questions/11632154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/801348/"
] | ```
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
c3 = {}
for c in (c1, c2):
for k,v in c.iteritems():
c3.setdefault(k, []).append(v)
```
`c3` is now: `{'item1': [4, 6], 'item2': [2, 2], 'item3': ... | Or with a list comprehension:
```
from collections import Counter
c1 = Counter({'item1': 4, 'item2':2, 'item3': 5, 'item4': 3})
c2 = Counter({'item1': 6, 'item2':2, 'item3': 1, 'item5': 9})
merged = {}
for k in set().union(c1, c2):
merged[k] = [d[k] for d in [c1, c2] if k in d]
>>> merged
{'item2': [2, 2], 'item3... | 98 |
51,745,894 | I am new to using python, and am wanting to be able to install packages for python using pip. I am having trouble running pip on my windows computer. When typing in "pip --version" into command prompt I get:
```
ModuleNotFoundError: No module named 'pip._internal'; 'pip' is not a package
```
I have added the scripts... | 2018/08/08 | [
"https://Stackoverflow.com/questions/51745894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6814024/"
] | Force a reinstall of pip:
```
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall
```
For windows you may have to `choco install curl` or set PATH to where python3 is located | In cmd try using
`py -3.6 -m pip install pygmae`
replace 3.6 with your version of python and add -32 fot 32 bit version
```
py -3.6-32 pip install pygame
```
replace pygame with the module you want to install
this works for most people using python on windows also reboot your pc after adding system variable pat... | 101 |
62,713,607 | I deployed an Azure Functions App with Python `3.8`. Later on I tried to use dataclasses and it failed with the exception that the version available does not support dataclasses. I then SSHed to the host of the Function App and by using `python --version` figured out that version `3.6` was actually installed. As datacl... | 2020/07/03 | [
"https://Stackoverflow.com/questions/62713607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7009990/"
] | This is a known issue (see e.g. <https://learn.microsoft.com/en-us/answers/questions/39124/azure-functions-always-using-python-36.html>) and hopefully fixed soon.
As workaround you can run the following command e.g. in the Cloud shell:
`az functionapp config set --name <func app name> --resource-group <rg name> --sub... | For anyone running into this problem downgrading to Python 3.6 is a workaround.
I tried @quervernetzt solution but it didn't work, my pipelines started giving the following error.
```
##[error]Error: Error: Failed to deploy web package to App Service. Conflict (CODE: 409)
``` | 102 |
15,424,895 | I'm new here in the world of coding and I haven't received a very warm welcome. I've been trying to learn python via the online tutorial <http://learnpythonthehardway.org/book/>. I've been able to struggle my way through the book up until exercise 48 & 49. That's where he turns students loose and says "You figure it ou... | 2013/03/15 | [
"https://Stackoverflow.com/questions/15424895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2172498/"
] | Based on the ex48 instructions, you could create a few lists for each kind of word. Here's a sample for the first test case. The returned value is a list of tuples, so you can append to that list for each word given.
```
direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
class Lexic... | Like the most here I am new to the world of coding and I though I attach my solution below as it might help other students.
I already saw a few more efficient approaches that I could implement. However, the code handles every use case of the exercise and since I am wrote it on my own with my beginners mind it does no... | 103 |
12,424,351 | I want to run a shell command from python and receive its output with subprocess.Popen. The problem is, when I close the process, sending Ctrl-C, I don't get any output. What am I doing wrong? Code:
```
>>> import subprocess
>>> sub = subprocess.Popen(["xinput", "test", "8"], stdout=subprocess.PIPE) #receive mouse eve... | 2012/09/14 | [
"https://Stackoverflow.com/questions/12424351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360544/"
] | The issue here is that the `KeyboardInterrupt` is sent during the call to `communicate`. As a result, `communicate` never returns and so it's output is never stored in the variable `output` and you get the `NameError` when you try to use it. One workaround would be the following:
```
import subprocess
sub = subproce... | @pythonm already explained the `NameError`.
Furthermore, you're using the output of `Popen.communicate()` conceptually wrong. It returns a 2-tuple of strings: `(stdout, stderr)`. It does not return two file-like objects. That's why your `sub.communicate()[0].read()` would fail if `communicate()` returned.
Until the ... | 113 |
65,495,956 | I have searched far and wide, and have followed just about everything... I cannot figure out why this keeps happening to my Python package I've created. It's not a simple "install dependency and you're good" as it's my own project I am attempting to create.
Here's my file structure:
```
-jarvis-discord
--jarvis_disco... | 2020/12/29 | [
"https://Stackoverflow.com/questions/65495956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13002900/"
] | If you are using relative file paths, you have to use
`from .cogs import (`
because it jarvis.py can't see jarvis\_discord\_bot from one level below.
The . in front of cogs means that it is one level up. | Figured out what was the issue!
In my run file, I had to set `PYTHONPATH` from `PWD` to the actual folder of the project. Good luck to anyone reading this in the future! | 114 |
50,151,698 | i have two table like this:
```
table1
id(int) | desc(TEXT)
--------------------
0 | "desc1"
1 | "desc2"
table2
id(int) | table1_id(TEXT)
------------------------
0 | "0"
1 | "0;1"
```
i want to select data into table2 and replace table1\_id by the desc field in table1, when i have string wi... | 2018/05/03 | [
"https://Stackoverflow.com/questions/50151698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5494686/"
] | You can convert the CSV value into an array, then join on that:
```
select string_agg(t1.descr, ',') as descr
from table2 t2
join table1 t1 on t1.id = any (string_to_array(t2.table1_id, ';')::int[])
where t2.id = 1
``` | That is really an abominable data design.
Consequently you will have to write a complicated query to get your desired result:
```
SELECT string_agg(table1."desc", ', ')
FROM table2
CROSS JOIN LATERAL regexp_split_to_table(table2.table1_id, ';') x(d)
JOIN table1 ON x.d::integer = table1.id
WHERE table2.id = 1;
... | 115 |
64,791,458 | Here is my docker-compose.yml used to create the database container.
```
version: '3.7'
services:
application:
build:
context: ./app
dockerfile: dockerfile #dockerfile-prod
depends_on:
- database_mongo
- database_neo4j
- etl_pipeline
environment:
- flask_env=dev #flas... | 2020/11/11 | [
"https://Stackoverflow.com/questions/64791458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14620901/"
] | Usually languages implement functionalities as simply as possible.
Class methods are under the hood just simple functions containing object pointer as an argument, where object in fact is just data structure + functions that can operate on this data structure.
Normally compiler knows which function should operate on ... | No, it does not. Functions are class-wide. When you allocate an object in C++ it will contain space for all its attributes plus a VTable with pointers to all its methods/functions, be it from its own class or inherited from parent classes.
When you call a method on that object, you essentially perform a look-up on tha... | 116 |
45,155,336 | I am running Ubuntu Desktop 16.04 on a VM and am trying to run [Volttron](https://github.com/VOLTTRON/volttron) using the standard install instructions, however I keep getting an error after the following steps:
```
sudo apt-get update
sudo apt-get install build-essential python-dev openssl libssl-dev libevent-dev git... | 2017/07/17 | [
"https://Stackoverflow.com/questions/45155336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8322226/"
] | I would recommend passing in the name of the value you would like to update into the handle change function, for example:
```
import React, { Component } from 'react'
import { Dropdown, Grid } from 'semantic-ui-react'
class DropdownExampleRemote extends Component {
componentWillMount() {
this.setState({
o... | Something along these lines can maybe work for you.
```
handleChange = (propName, e) => {
let state = Object.assign({}, state);
state[propName] = e.target.value;
this.setState(state)
}
```
You can pass in the name of the property you want to update and then use bracket notation to update that part of your stat... | 117 |
53,435,428 | After reading all the existing post related to this issue, i still did not manage to fix it.
```
ModuleNotFoundError: No module named 'plotly'
```
I have tried all the following:
```
pip3 install plotly
pip3 install plotly --upgrade
```
as well as uninstalling plotly with:
```
pip3 uninstall plotly
```
And re... | 2018/11/22 | [
"https://Stackoverflow.com/questions/53435428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10438271/"
] | Just run this to uninstall plotly and then build it from source. That should fix the import
```
pip uninstall plotly && python -m pip install plotly
``` | That sounds like a classic dependency issue.
* Check that your pip version is using the same python version (3.6) as what you launch your script with (IE: Use `python3(.6)` to launch your script, not just `python`)
* Your logs aren't showing plotly already installed. In fact, you probably forgot a line when pasting bu... | 118 |
73,646,583 | In short, is there a pythonic way to write `SETTING_A = os.environ['SETTING_A']`?
I want to provide a module `environment.py` from which I can import constants that are read from environment variables.
##### Approach 1:
```
import os
try:
SETTING_A = os.environ['SETTING_A']
SETTING_B = os.environ['SETTING_B... | 2022/09/08 | [
"https://Stackoverflow.com/questions/73646583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10909217/"
] | You should describe the type of PersonDto:
```js
interface PersonDto {
id: string;
name: string;
country: string;
}
class Person {
private id: string;
private name: string;
private country: string;
constructor(personDto: PersonDto) {
this.id = personDto.id;
this.name = personDto.name;
this.... | Try [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) to not have to type every property.
```typescript
interface PersonDto {
id: string;
name: string;
country: string;
}
class Person {
private id: string;
private name: string;
private countr... | 128 |
21,890,220 | tried multiplication of 109221975\*123222821 in python 2.7 prompt in two different ways
```
Python 2.7.3 (default, Sep 26 2013, 20:08:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 109221975*123222821
13458639874691475L
>>> 109221975*123222821.0
1.3458639874691476... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21890220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1955093/"
] | Your `int` is 54 bits long. `float` can hold 53 significant digits, so effectively the last digit is rounded to an even number.
Internally, your float is represented as:
>
> 2225720309975242\*2-1
>
>
>
Your `int` and `float` is stored in binary like the following:
```
101111110100001000111111001000... | Because `int` in python has infinite precision, but `float` does not. (`float` is a double precision floating point number, which has 53 bits of precision.) | 129 |
66,395,018 | I am new to python. at the moment I am coding a game with a friend. we are currently working on a combat system the only problem is we don't know how to update the the enemy's health once damage has been dealt. The code is as following.
```
enemy1_health = 150
broadsword_attack = 20
rusty_knife = 10.5
attacks = ["b... | 2021/02/27 | [
"https://Stackoverflow.com/questions/66395018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15293735/"
] | You need to change the enemy health outside of the print statement with a statement like this:
```
enemy1_health = enemy1_health - 20
```
or like this, which does the same thing:
```
enemy1_health -= 20
```
You also reset enemy1\_health every time the loop loops, remove that.
You don't define player\_health, def... | You need to change the enemy health outside the print statement.
do:
```
if attackchoice == ("rusty knife jab"):
enemy1_health = enemy1_health - 10.5
print(enemy1_health)
```
and you can do the same for the other attacks.
You also have enemy health defined in the while loop. you need to define it outside o... | 131 |
44,659,242 | During development of Pylint, we encountered [interesting problem related to non-dependency that may break `pylint` package](https://github.com/PyCQA/pylint/issues/1318).
Case is following:
* `python-future` had a conflicting alias to `configparser` package. [Quoting official docs](http://python-future.org/whatsnew.h... | 2017/06/20 | [
"https://Stackoverflow.com/questions/44659242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2912340/"
] | ```
kw = {}
try:
import future
except ImportError:
pass
else:
kw['install_requires'] = ['future>=0.16']
setup(
…
**kw
)
``` | One workaround for this issue is to define this requirement only for the `all` target, so only if someone adds `pylint[all]>=1.2.3` as a requirement they will have futures installed/upgraded.
At this moment I don't know another way to "ignore or upgrade" a dependency.
Also, I would avoid adding Python code to `setup.... | 133 |
37,369,079 | I have a lab colorspace
[](https://i.stack.imgur.com/3pXgm.png)
And I want to "bin" the colorspace in a grid of 10x10 squares.
So the first bin might be (-110,-110) to (-100,-100) then the next one might be (-100,-110) to (-90,-100) and so on. The... | 2016/05/21 | [
"https://Stackoverflow.com/questions/37369079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123905/"
] | The answer is to not use SSTATE\_DUPWHITELIST for this at all. Instead, in the libftdi recipe's do\_install (or do\_install\_append, if the recipe itself doesn't define its own do\_install) you should delete the duplicate files from within ${D} and then they won't get staged and the error won't occur. | I managed to solve this problem by adding the SSTATE\_DUPWHITELIST to the bitbake recipe of the package as follows:
SSTATE\_DUPWHITELIST = "${TMPDIR}/PATH/TO/THE/FILES"
I added the absolute path of all of the 6,7 files that had the conflict to the list. I did that because they were basically coming from a same source... | 135 |
70,008,841 | I was able to follow this example1 and let my ec2 instance read from S3.
In order to write to the same bucket I thought changing line 572 from `grant_read()` to `grant_read_write()`
should work.
```py
...
# Userdata executes script from S3
instance.user_data.add_execute_file_command(
... | 2021/11/17 | [
"https://Stackoverflow.com/questions/70008841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172907/"
] | This is the [documentation](https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_s3_assets/Asset.html) for Asset:
>
> An asset represents a local file or directory, which is automatically
> uploaded to S3 and then can be referenced within a CDK application.
>
>
>
The method grant\_read\_write isn't provi... | an asset is just a Zip file that will be uploded to the bootstraped CDK s3 bucket, then referenced by Cloudformation when deploying.
if you have an script you want ot put into an s3 bucket, you dont want to use any form of asset cause that is a zip file. You would be better suited using a boto3 command to upload it on... | 138 |
2,433,703 | I am running Cygwin Python version 2.5.2.
I have a three-line source file, called import.py:
```
#!/usr/bin/python
import xml.etree.ElementTree as ET
print "Success!"
```
When I execute "python import.py", it works:
```
C:\Temp>python import.py
Success!
```
When I run the python interpreter and type the commands... | 2010/03/12 | [
"https://Stackoverflow.com/questions/2433703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5397/"
] | Probably py extension is connected to some other python interpreter than the one in /usr/bin/python | Try:
```
./import.py
```
Most people don't have "." in their path.
just typing python will call the cygwin python.
import.py will likely call whichever python is associated with .py files under windows.
You are using two different python executables. | 139 |
1,550,226 | I have installed a python package with `python setup.py install`.
How do I uninstall it? | 2009/10/11 | [
"https://Stackoverflow.com/questions/1550226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63051/"
] | At `{virtualenv}/lib/python2.7/site-packages/` (if not using virtualenv then `{system_dir}/lib/python2.7/dist-packages/`)
* Remove the egg file (e.g. `distribute-0.6.34-py2.7.egg`)
* If there is any from file `easy-install.pth`, remove the corresponding line (it should be a path to the source directory or of an egg fi... | **Install from local**
`python setup.py install`
**Uninstall from local**
`pip uninstall mypackage` | 144 |
49,093,290 | I'm trying to install Python 3 alongside 2.7 with Homebrew but am receiving an error message I can't find a resolution to.
When attempting `brew update && brew install python3` I get the following error:
```
Error: python 2.7.12_2 is already installed
To upgrade to 3.6.4_3, run `brew upgrade python`
```
I want to l... | 2018/03/04 | [
"https://Stackoverflow.com/questions/49093290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3673055/"
] | You can press F9 inside [7zip](https://7zipguides.com/), you'll get two panes. In the first, you navigate to the archive you want to extract, and in the second you navigate to the folder where you want your files extracted. This will skip the temp folder step... | you can change **root** value in config/filesystems.php
```
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
``` | 154 |
69,476,449 | I was working with two instances of a python class when I realize they where using the same values. I think I have a missunderestanding of what classes are used for.
A much simpler example:
```
class C():
def __init__(self,err = []):
self.err = err
def add(self):
self.err.append(0)
a = C()... | 2021/10/07 | [
"https://Stackoverflow.com/questions/69476449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11934583/"
] | The reason is here:
`def __init__(self,err = []):`
default `err` value is saved inside class `C`. But `err` itself is mutable, so every time you append anything to it, next time it will have stored value and this default `err` value is saved as `a.err` and `b.err`:
```
a = C()
print(a.err) # a.err is err ([])
... | I recommend that you check the Python core language *features* first. Check the official FAQs for Python 3, particularly <https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects> is what you are looking for.
According to the recommendations, you have to change your code like so
``... | 155 |
46,906,854 | I just started to bash and I have been stuck for sometime on a simple if;then statement.
I use bash to run QIIME commands which are written in python. These commands allow me to deal with microbial DNA. From the raw dataset from the sequencing I first have to first check if they match the format that QIIME can deal wi... | 2017/10/24 | [
"https://Stackoverflow.com/questions/46906854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8759792/"
] | **Key idea :** You can add `UITapGestureRecognizer` to `UIImageView`. Setting up a `selector` which will be fired for each tap. In the `selector` you can check for the co-ordinate where the tap was done. If the co-ordinate satisfy your condition for firing up an event, you can execute your task then.
**Adding the gest... | Given a view (ora imageview) you should define a UIBezierPath of your shape.
Add a taprecognizer to this view, and set the same view as the recognizer delegate.
In the delegate method use UIBezierPath.contains(\_:) to know if the tap is inside the path or not and decide to fire the tap event or not.
Let me know if you... | 158 |
42,553,713 | Currently, I have some issue with Xcode and the proccess **IBDesignablesAgentCocoaTouch** freeze Xcode each time I edit Storyboard.
So, I want to kill this proccess with a bash or python script by checking every x seconds if this proccess is running.
I think I can use this script, but how to do with a timer ( each x ... | 2017/03/02 | [
"https://Stackoverflow.com/questions/42553713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4824110/"
] | Just use a while loop,
```
while sleep 20; do
pid=$(ps -fe | grep 'IBDesignablesAgentCocoaTouch' | awk '{print $2}')
if [[ -n $pid ]]; then
kill $pid
else
echo "Does not exist"
fi
done
```
The syntax `while sleep 20; do <code>` is similar to the one showed in comments `while true; do ... | Use this **If the process is named IBDesignablesAgentCocoaTouch**:
```
kill $(pgrep -x IBDesignablesAgentCocoaTouch)
```
If the process exists it will get killed, if not nothing will happen.
`pgrep` will get PID for you.
```
#!/bin/bash
while sleep 20; do
kill $(pgrep IBDesignablesAgentCocoaTouch)
done
```
I... | 159 |
44,036,372 | Could anyone tell me what files I should download and which statements I must execute in the command line to install Matplotlib?
I have Python 2.7.13 on Windows 10 64 bit.
These are the files I unzipped:

All downloaded from: <http://www.lfd.uc... | 2017/05/17 | [
"https://Stackoverflow.com/questions/44036372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5513436/"
] | Instead of iterating over a simple list of strings. You can store the section along with it's target element as an object then iterate.
```
<div id="introDiv"></div>
<div id="aboutDiv"></div>
<div id="linksDiv"></div>
var sections = [
{ section: "intro", target: "introDiv" },
{ section: "about", target: "abou... | Just set the Ajax to run synchronously, so the each loop will wait for your Ajax to finish before incrementing `counter`.
```
var counter = 1;
["intro","about","links"].each( function (index) {
var frag='<div id="id_'+counter+'"></div>\n";
$("#page").append(frag);
$.ajax({
url: "/data/"+index, ... | 161 |
21,123,963 | I am trying to write a primes module in python. One thing I would like to be able to write is
```
>>> primes.primesLessThan(12)
[2, 3, 5, 7, 11]
```
However, I would also like to be able to write
```
>>> primes.primesLessThan.Sundaram(12)
[2, 3, 5, 7, 11]
```
to force it to use the Sieve of Sundaram. My original ... | 2014/01/14 | [
"https://Stackoverflow.com/questions/21123963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3195702/"
] | As a rule of thumb, if you have a class without any instance variables, an empty init method and just a bunch of static methods, then its probably going to be simpler to organize it as a module instead.
```
#sieves module
def Sundaram(n):
return [2,3,5,7]
def Eratosthenes(n):
return [2,3,5,7]
```
And then you c... | Two ways I can think of, to get these kinds of semantics.
* Make primes a class, and then make primesLessThan a property. It would also be a class, which implements `__iter__` etc. to simulate a list, while also having some subfunctions. primesLessThan would be a constructor to that class, with the argument having a d... | 164 |
42,230,269 | Searching for an alternative as OpenCV would not provide timestamps for **live** camera stream *(on Windows)*, which are required in my computer vision algorithm, I found ffmpeg and this excellent article <https://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-python-using-ffmpeg/>
The solution uses ffm... | 2017/02/14 | [
"https://Stackoverflow.com/questions/42230269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468716/"
] | Redirecting stderr works in python.
So instead of this `pipe = sp.Popen(command, stdout = sp.PIPE, stderr = sp.PIPE)`
do this `pipe = sp.Popen(command, stdout = sp.PIPE, stderr = sp.STDOUT)`
We could avoid redirection by adding an asynchronous call to read both the standard streams (stdout and stderr) of ffmpeg.... | You can use [MoviePy](http://zulko.github.io/moviepy/index.html):
```
import moviepy.editor as mpy
vid = mpy.VideoFileClip('e:\\sample.wmv')
for timestamp, raw_img in vid.iter_frames(with_times=True):
# do stuff
``` | 165 |
14,981,069 | How can I use [Brython](https://www.brython.info/) to compile Python to Javascript? I want to do this on my computer, so I can the run Javascript with nodejs, eg.
```
$ python hello.py
Hello world
$ brython hello.py -o hello.js
$ node hello.js
Hello world
```
The examples on the Brython website only explain how do t... | 2013/02/20 | [
"https://Stackoverflow.com/questions/14981069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284795/"
] | It seems they are very browser oriented, there is no command line option out of the box.
You can try to use their code youself from node.js, perhaps it will work easily. It seems the `$py2js(src, module)` function does the actual conversion so maybe you can just run it with the python code string as first parameter.
... | Brython has a console that runs in the browser, but not a compiler. It is meant for you to either import your python scripts into the html file, or write your python code into the html file. See pyjs if you wish a conversion tool before the page loads. | 168 |
41,460,013 | ```
#!/usr/bin/env python2.7
import vobject
abfile='/foo/bar/directory/file.vcf' #ab stands for address book
ablist = []
with open(abfile) as source_file:
for vcard in vobject.readComponents(source_file):
ablist.append(vcard)
print ablist[0]==ablist[1]
```
Th... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41460013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5965670/"
] | @Brian Barcelona, concerning your answer, just to let you know, instead of:
```
ablist = []
with open(abfile) as source_file:
for vcard in vobject.readComponents(source_file):
ablist.append(vcard)
```
You could do:
```
with open(abfile) as source_file:
ablist = list(vobject.readComponents(source_file... | I have found the following will work - the insight is to "serialize()" the vcard:
```
#!/usr/bin/env python2.7
import vobject
abfile='/foo/bar/directory/file.vcf' #ab stands for address book
ablist = []
with open(abfile) as source_file:
for vcard in vobject.readComponents(source_file):
ablist.append(v... | 171 |
32,652,485 | I'm trying to convert string date object to date object in python.
I did this so far
```
old_date = '01 April 1986'
new_date = datetime.strptime(old_date,'%d %M %Y')
print new_date
```
But I get the following error.
>
> ValueError: time data '01 April 1986' does not match format '%d %M %Y'
>
>
>
Any guess... | 2015/09/18 | [
"https://Stackoverflow.com/questions/32652485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2728494/"
] | `%M` parses *minutes*, a numeric value, not a month. Your date specifies the month as `'April'`, so use `%B` to parse a *named* month:
```
>>> from datetime import datetime
>>> old_date = '01 April 1986'
>>> datetime.strptime(old_date,'%d %B %Y')
datetime.datetime(1986, 4, 1, 0, 0)
```
From the [*`strftime()` and `... | You can first guess the type of date format the string is using and then convert to the same system recognised date format.
I wrote a simple date\_tools utilities that you can find here at [<https://github.com/henin/date_tools/]>
### Installation: pip install date-tools
### Usage:
>
> from date\_tools import date\_... | 172 |
64,934,782 | I am trying to read JSON File but it gives error as below
*Data reference:
<https://github.com/ankitgoel1602/data-science/blob/master/json-data/level_1.json>
<https://github.com/ankitgoel1602/data-science/blob/master/json-data/multiple_levels.json>*
Code
```
with open("multiple_levels.json", 'r') as j:
contents = j... | 2020/11/20 | [
"https://Stackoverflow.com/questions/64934782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5866905/"
] | You will want to use something like `map` instead
This is a simply change to your code:
```
formatedCharcters = data.results.map(character => {
``` | I am not sure that I completely understand your question, but here is one way you could achieve the result you are probably looking for. I have kept the forEach loop in case there is a specific reason for keeping it:
```
// Json data example
function getCharacters() {
const data = {
info: {
count: 671,
... | 173 |
10,049,054 | I want it to give 'Number of donuts: many' when the argument is more than 10 and 'Number of donuts: ' when the argument is count<10. But it always gives me 'Number of donuts: many'
```
#!/usr/bin/python2.6 -tt
import sys
def donuts(count):
if count < 10:
x = str(count)
else:
x = 'many'
print 'Number of d... | 2012/04/06 | [
"https://Stackoverflow.com/questions/10049054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1318217/"
] | `count` is a string. Try `count = int(count)` | You should convert count to an int before comparing it to 10:
```
#!/usr/bin/python2.6 -tt
import sys
def donuts(count):
if int(count) < 10:
x = count
else:
x = 'many'
print 'Number of donuts: %s' % x
def main():
donuts(sys.argv[1])
if __name__ == "__main__":
main()
``` | 175 |
28,656,559 | I am trying to build the \_pjsua C extension in windows, using Visual studio 2012.
I downloaded the source code from here - <http://www.pjsip.org/download.htm>.
I have Python27 installed, and have added the **C:\Python27\include** and the **C:\Python27\libs** directories to the project **include** and **library** dir... | 2015/02/22 | [
"https://Stackoverflow.com/questions/28656559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1662033/"
] | No, it not so.
You can use simple hack:
**Copy python27.lib** and rename it **to python24.lib**, then place it to **C:/Python27/libs** folder. Now you can build you extension, then run in cmd **python setup-vc.py install** command. | The right solution for this is:
1. Open python\_pjsua property pages (righ click->Properties);
2. Linker->Input->Additional Dependencies.
3. Change python24.lib to python27.lib (or python24\_d.lib to python27\_d.lib if debugging).
It should work and compile with no problem. | 182 |
33,326,193 | I need help finding a way to calculate the total cost of items when there is a change in the price once items go up to certain number in python 3.5.
For example,
First 6 items cost $8 each and after that, it costs $5 per item.
How can I achieve this without using an `if` statement and loop? | 2015/10/25 | [
"https://Stackoverflow.com/questions/33326193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5426865/"
] | I would agree with the replies to this post concerning MCVE.
As for an answer to the question (to get the grader to accept your answer), remember that when inheriting the (Parent) `class Person` for (child) `class USResident`, (Parent) `class Person` will need to be initialized in (child) `class USResident` with:
`Pe... | Actually it is very simple, just to test you if you can use a constant in the class.
Just like something: `STATUS = ("c", "i", "l")` and then raise the `ValueError` if the condition failed. | 183 |
42,689,852 | I'm trying to using the [Azure Python SDK](https://github.com/Azure/azure-sdk-for-python) to drive some server configuration management, but I'm having difficulty working out how I'm supposed to use the API to upload and configure SSL certificates.
I can successfully interrogate my Azure account to discovering the App... | 2017/03/09 | [
"https://Stackoverflow.com/questions/42689852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218383/"
] | If you follow the [App Service walkthrough for importing certificates from Key Vault](https://learn.microsoft.com/azure/app-service/configure-ssl-certificate#import-a-certificate-from-key-vault), it'll tell you that your app needs read permissions to access certificates from the vault. But to initially import your cert... | According to your description, based on my understanding, I think you want to upload a certificate and use it on Azure App Service.
Per my experience for Azure Python SDK, there seems not to be any Python API for directly uploading a certificate to Azure App Service. However, there is a workaround way for doing it via... | 184 |
63,482,435 | from the below table I want to pull records with ID 1 and ID 3.
```
ID Status assigned
1 low yes
1 High no
2 low no
3 high yes
3 low yes
```
Please let me know in python how can this be done. | 2020/08/19 | [
"https://Stackoverflow.com/questions/63482435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10214628/"
] | You can target attribute lang on the blockquote tag and add direction rule:
```
blockquote[lang="ar"] {
direction: rtl;
}
```
```css
blockquote {
background-color: #f4f7fc;
font-size: 20px;
color: #191514;
line-height: 1.7;
position: relative;
padding: 50px 30px 30px 115px;
font-family: 'Poppins', sa... | add class to blockquote element, and set the class styling direction attribute to rtl | 185 |
73,581,339 | I want to show status every second in a very slow loop in python code, e.g.
```
for i in range(100):
sleep(1000000) # think there is a very slow job
# I want to show status in console every second
# to know if the job stop or not
```
The output image is, e.g.
```
$ python somejob.py
> 2022-09-02 13:04:... | 2022/09/02 | [
"https://Stackoverflow.com/questions/73581339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6766052/"
] | I think what you're looking for is someting like the tqdm library: [github repo](https://github.com/tqdm/tqdm)
for example
```
from tqdm import tqdm
for i in tqdm(range(1000)):
continue # do something complex here
``` | You may us the [rich module](https://pypi.org/project/rich/) to disply a progress bar:
```
import time
from rich.progress import track
for i in track(range(100)):
time.sleep(0.5)
```
Here's a screenshot within the run:
[](https://i.stack.imgur.... | 186 |
64,327,172 | I am running a django app with a postgreSQL database and I am trying to send a very large dictionary (consisting of time-series data) to the database.
My goal is to write my data into the DB as fast as possible. I am using the library requests to send the data via an API-call (built with django REST):
My API-view is ... | 2020/10/13 | [
"https://Stackoverflow.com/questions/64327172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9893391/"
] | You can solve your issues using two techniques.
Data Creation
-------------
Use bulk\_create to insert a large number of records, if SQL error happens due to large query size etc then provide the `batch_size` in `bulk_create`.
```
records = []
for elem, ts in request.data['time_series'] :
records.append(
... | @micromegas when your solution is correct theoretically, however calling create() many times in a loop, I believe that causes the ConnectionError exception.
try to refactor to something like:
```
big_data_holder = []
for elem, ts in request.data['time_series'] :
big_data_holder.append(
TimeSeries(data_js... | 187 |
46,145,221 | what is different between `os.path.getsize(path)` and `os.stat`? which one is best to used in python 3? and when do we use them? and why we have two same solution?
I found [this](https://stackoverflow.com/questions/18962166/python-os-statfile-name-st-size-versus-os-path-getsizefile-name) answer but I couldn't understan... | 2017/09/10 | [
"https://Stackoverflow.com/questions/46145221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4958447/"
] | `stat` is a POSIX system call (available on Linux, Unix and even Windows) which returns a bunch of information (size, type, protection bits...)
Python has to call it at some point to get the size ([and it does](https://stackoverflow.com/questions/18962166/python-os-statfile-name-st-size-versus-os-path-getsizefile-name... | The answer you are linking to shows that the one calls the other:
```
def getsize(filename):
"""Return the size of a file, reported by os.stat()."""
return os.stat(filename).st_size
```
so fundamentally, both functions are using `os.stat`.
Why? probably because they had similar needs in two different packa... | 188 |
68,856,582 | Is there a similar substituite to `.exit()` and `sys.exit()` that stops the program from running **but without terminating python entirely**?
Here's something similar to what I want to achieve:
```
import random
my_num = random.uniform(0, 1)
if my_num > 0.9:
# stop the code here
# some other huge blocks of code... | 2021/08/20 | [
"https://Stackoverflow.com/questions/68856582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14610650/"
] | When you run your script, use the `-i` option. Then call `sys.exit()` where you want to stop.
```
python3 -i myscript.py
```
```py
if my_num > 0.9:
sys.exit()
```
Python won't actually exit when the `-i` used. It will instead place you in the REPL prompt.
---
The next best method, if you can't use the `-i` o... | If you don't want to terminate the code, you can tell python to "sleep":
```
import random
import time
my_num = random.uniform(0, 1)
if my_num > 0.9:
time.sleep(50) #==== 50 seconds. Use any number.
``` | 189 |
15,661,841 | Is there any video tutorial or book from where I can learn python web programming in django platform in Eclipse(pydev).Please Help | 2013/03/27 | [
"https://Stackoverflow.com/questions/15661841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183898/"
] | Try [The Django Book](http://www.djangobook.com/en/2.0/index.html), or start with the [tutorial](https://docs.djangoproject.com/en/1.5/intro/tutorial01/). | <http://pydev.org/manual_adv_django.html> should get you started. If you're new to eclipse, I would find a tutorial on that first as they have a lot of their own lingo. | 190 |
38,219,216 | I'm using `python` to crawl a webpage and save it. And the code works properly. But when I open the web page it just shows the website name i.e., **<http://www.indiabix.com>** and not the actual content.
You can just go the website and save one of it's pages **NOT** the homepage but other pages like **<http://www.indi... | 2016/07/06 | [
"https://Stackoverflow.com/questions/38219216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3620992/"
] | in this version
```
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
```
try it
```
public class MainActivity extends AppCompatActivity {
private LineChart lc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)... | Version 3.0 is initialized like so:
```
LineChart lineChart = new LineChart(context);
lineChart.setMinimumHeight(ToolBox.dpToPixels(context, 300));
lineChart.setMinimumWidth(ToolBox.getScreenWidth());
ArrayList<Entry> yVals = new ArrayList<>();
for(int i = 0; i < frigbot.getEquipment().getTemperatures().size();... | 192 |
71,153,492 | I'm having multiple errors while running this VGG training code (code and errors shown below). I don't know if its because of my dataset or is it something else.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing import image
from tens... | 2022/02/17 | [
"https://Stackoverflow.com/questions/71153492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15336528/"
] | I faced the same error and tried to test everything with no value, but I heard that you have to make the number of **folders** in the **dataset** the SAME as the one in `Dense`.
I don't know if this will solve your specific bug or not but try this with your code:
```
vgg_model.add(tf.keras.layers.Dense(10, activation... | Check the image size. Size of image defined in model.add(.., input\_shape=(100,100,3)) should be same as the **target\_size=(100,100) in train\_gererator.**
And also check if number of neurons in last dense layer are equal to number of output classes or not.
By the way, there isn't any need to install any other module.... | 193 |
20,893,752 | I started trying to make a script to send emails using python, but nothing worked. I eventually got to the point where I just started copying and pasting email scripts and filling in my info. Still nothing worked. So i eventually just got rid of everything except this:
```
#!/usr/bin/python
import smtplib
```
This s... | 2014/01/02 | [
"https://Stackoverflow.com/questions/20893752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2402862/"
] | Change the name of your script from `email.py` to something else. It is interfering with the Python standard library module of the same name, `email`. | Read this: [Syntax: python smtplib not working in script](https://stackoverflow.com/questions/14102113/syntax-python-smtplib-not-working-in-script)
A user says that you have to remove email.py from the folder. | 196 |
28,262,400 | I am changing the original post to memory leak, as what i have observed that cassandra python driver do not release sessions from memory. And during heavy inserts its eat up all the memory (Thus crashes cassandra as not enough room left for GC).
This was raised earlier but i see the issue in latest drivers as well.
<... | 2015/02/01 | [
"https://Stackoverflow.com/questions/28262400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4460263/"
] | Calling `id.Hex()` will return a string representation of the `bson.ObjectId`.
This is also the default behavior if you try to marshal one `bson.ObjectId` to json string. | Things like to work [playground](https://play.golang.org/p/1LG1NlFEK-)
Just define dot `.` for your template
```
{{ .Name }} {{ .Food }}
<a href="/remove/{{ .Id }}">Remove me</a>
``` | 197 |
33,426,483 | I have created my Rails app on OpenShift. It uses Python and a package installed from PIP. How do I upgrade to a newer Python version (currently it is 2.6) ?
Visible cartridges:
```
user@debian:~$ rhc cartridges
jbossas-7 JBoss Application Server 7 web
jboss-dv-6.1.0 (!) JBoss Data V... | 2015/10/29 | [
"https://Stackoverflow.com/questions/33426483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1906809/"
] | If you have installed phpMyAdmin in your linux server (centos/RHEL/debian), and tried to access phpMyAdmin in most cases you will get this 403 forbidden error. I have seen this issue very often if you are installing phpmyadmin using yum or by apt-get. By default phpmyadmin installed path is **/usr/share/phpmyadmin** an... | I was running into the same issue with a new install of Fedora 25, Apache, MariaDB and PHP.
The router is on 192.168.1.1 and the Fedora 25 server is sitting at 192.168.1.100 which is a staic address handed out by the router. The laptop was getting a random ip in the range of 192.168.1.101 to 150.
The change I made to... | 200 |
19,223,676 | I'm using passenger with apache to run my ruby application. I've noticed that passenger crashes from time to time (apache is still working), and I need to manually restart apache to make it work again.
A look at the log makes me think it occurs when apache changes the log file (archives the current an create a new one... | 2013/10/07 | [
"https://Stackoverflow.com/questions/19223676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149237/"
] | Ah, I see that you are on version 4.0.14. Please upgrade to the latest version, which is 4.0.20. Versions prior to 4.0.17 or so didn't properly support /tmp directories with the setgid flag. | In my case, restart apache solve this problem.
```
$ /etc/init.d/httpd stop
$ /etc/init.d/httpd start
``` | 201 |
4,658,008 | I have a rather long setup, then three questions at the end.
On OS X, the System Python framework contains three executables (let me give them short names):
```
> F=/System/Library/Frameworks/Python.framework/Versions/2.6
> A=$F/bin/python2.6
> B=$F/Resources/Python.app/Contents/MacOS/Python
> C=$F/Python
```
$A and... | 2011/01/11 | [
"https://Stackoverflow.com/questions/4658008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215679/"
] | The Apple-supplied Pythons in OS X 10.6 are built and installed using the standard Python *framework* build option, with a few customization tweaks. It is not in Apple's documentation because the specific layout is not an Apple invention; it has evolved over the years by the Python project using other OS X framework la... | The tools to use are ls and file.
ls -l will give what the symbolic link goes to. The size of a symbolic link is the number of chafracters in the path it points to.
file x will give the type of the file
e.g.
```
file /System/Library/Frameworks/Python.framework/Versions/2.6/Python
/System/Library/Frameworks/Pyth... | 202 |
49,577,050 | I am trying to interact with a database stored in back4app using python. After sending my GET request, I get "{'message': 'Not Found', 'error': {}}". My python code is as follows:
```
import json, http.client, urllib.parse
# create a connection to the server
url = "parseapi.back4app.com"
connection = http.client.HTTPS... | 2018/03/30 | [
"https://Stackoverflow.com/questions/49577050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983936/"
] | You CPP file doesn't include the .h file and it doesn't have `extern "C"` declarations of its own. So, the methods are compiled with C++ signatures, so they cannot be found by the JVM, which expects `extern "C"` signatures as per the .h file.
The easy fix is to include the .h file. | Solution!!!! I fixed it by doing some research and through trial and error i figured out that my imports were messing up the DLL
Cpp file:
```
/* Replace "dll.h" with the name of your header */
#include "IGNORE.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
JNIEXPORT jint JNICALL ... | 203 |
65,573,140 | I was making a virtual assistant in python, but I see the following error.
```
ImportError: No system module 'pywintypes' (pywintypes39.dll)
```
I am using Windows 10 and Python 3.9
Here is the code
```
import speech_recognition as sr
import pyttsx3
listner=sr.Recognizer()
engine=pyttsx3.init()
engine.say('Hello ... | 2021/01/05 | [
"https://Stackoverflow.com/questions/65573140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14856292/"
] | Try importing win32api at the top,
```
import win32api
import speech_recognition as sr
import pyttsx3
``` | I did the following when I experienced the same problem:
When we look at these lines in the error,
```
File "C:\Users\visha\AppData\Roaming\Python\Python39\site-packages\win32\lib\pywintypes.py", line 87, in __import_pywin32_system_module__
raise ImportError("No system module '%s' (%s)" % (modname, filename))
Impo... | 204 |
73,678,506 | I want to get and parse the python (python2) version. This way (which works):
```
python2 -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/'
```
For some reason, python2 is showing the version using the -V argument on its error output. Because this is doing nothing:
```
python2 -V | sed 's/.* \([0-9]\).\([0-9]\).*/\1... | 2022/09/11 | [
"https://Stackoverflow.com/questions/73678506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5300329/"
] | Print output only if the line starts with `Python 2`:
```
python2 -V 2>&1 | sed -n 's/^Python 2\.\([0-9]*\).*/2\1/p'
```
or,
```
command -v python2 >/dev/null && python2 -V 2>&1 | sed ...
``` | Include the next line in your script
```
command python2 >/dev/null 2>&1 || {echo "python2 not installed or in PATH"; exit 1; }
```
EDITED: Changed `which` into `command` | 214 |
28,434,920 | I've been following the djangogirl's tutorial here <http://tutorial.djangogirls.org/en/deploy/README.html> on deploying a django app on Heroku. I am a complete newbie at this so a lot of the stuff just seems like black magic to me, and I have a very fuzzy idea of what is going on. However, I seem to have been able to g... | 2015/02/10 | [
"https://Stackoverflow.com/questions/28434920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If a method does not return anything, then that method must have some side-effect such as changing a property of the class. Test that side-effect, e.g. test the value of said property. | In the strictest sense, if you ware testing only the ReadCities method, your mock shouldn't be testing that engine.ReadFile actually did something (you would have another unit test for that). You should isolate this method by mocking the call to engine.ReadFile (which I think you've done, but I'm not completely familia... | 215 |
73,880,813 | I'm a beginner into python language. I want to develop an android app. I've wrote some code and few days ago I wanted to see how my app looks on mobile before continue.
I've tried all methods to convert .py to .apk but failed. I've tried with google colab, I've installed a VM... but nothing worked. If I use google cola... | 2022/09/28 | [
"https://Stackoverflow.com/questions/73880813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20109886/"
] | Create an interface that describes the data you want to store in the context:
```
interface AuthContextType {
currentUser: IUser;
login: (email: string, password: string) => ......,
signup: (email: string, password: string) => ....,
logout: () => void,
recoverPassword: (email: string) => ....,
... | You can either type `createContext` with `YourInterface | null` as in
```js
const AuthContext = createContext<YourInterface|null>(null);
```
or type cast an empty object as in
```js
const AuthContext = createContext({} as YourInterface)
``` | 218 |
60,715,443 | I've create a pretty standard linked list in python with a Node class and LinkedList class. I've also added in methods for LinkedList as follows:
1. add(newNode): Adds an element to the linked list
2. addBefore(valueToFind, newNode): Adds a new node before an element with the value specified.
3. printClean: Prints the... | 2020/03/17 | [
"https://Stackoverflow.com/questions/60715443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1607450/"
] | Each line to list, then `map()`, `join()` with `\n` would be fine
```
this.setState({ body: value.blocks.map(x => x.text).join("\n") });
```
```
import React from "react";
import Body from "./Body";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
body: ""
};
... | * If you want with break line like as it is in editor, add `<p>` tag while concatination.
```
changeBodyHandler = value => {
let data =value.block;
let text = "";
data.map(index => {
text = text +"<p>" +index.text+"</p>";
});
this.setState({
body: text
});
};
```
* And if you want to display the ... | 219 |
67,168,199 | I'm trying to build an executable from a simple python script using pyvisa-py but I'm running into error after I run the executable generated by pyinstaller.
Here what my small python code looks like
```
import pyvisa as visa
import tkinter as tk
root = tk.Tk()
root.title("SCPI test")
canvas1 = tk.Canvas(root, width... | 2021/04/19 | [
"https://Stackoverflow.com/questions/67168199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13849963/"
] | You can always add missing site-package(s) in your list of hidden imports in your `.spec` file. Specifically for missing '`pyvisa_py`' module you can write following `test.spec` file:
```
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['test.py'],
pathex=['/home/user/test/source'],
... | Recently I was searching for similar issue with another library. What I understood is that in such cases,
1. Make sure that the packages are installed via pip.
2. If it still has a problem, try to copy the entire library folder from *"<python\_env\_path>/lib/site-packages/"* to the *"dist"* folder created by pyinstall... | 220 |
69,583,271 | Here is a toy example of my pandas dataframe:
```
country_market language_market
0 United States English
1 United States French
2 Not used Not used
3 Canada OR United States English
4 Germany English
5 United Kingdom French
6 United States German
7 United Kingdom English
8 United King... | 2021/10/15 | [
"https://Stackoverflow.com/questions/69583271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5269252/"
] | There is no such much-upgraded plugin now, which can help you. But for a workaround, we do have [volume\_watcher: ^2.0.1](https://pub.dev/packages/volume_watcher), which gives a callback when the volume is changed.
```
VolumeWatcher.addListener((volume) {
print("Current Volume :" + volume.toString());
})!;... | I needed the same functionality (listen to volume down, don't change volume when listening) and it didn't exist yet in Flutter so I made a plugin for it myself, you can find it here: <https://pub.dev/packages/flutter_android_volume_keydown>
It only works on Android because overriding iOS hardware buttons is not allowe... | 221 |
46,736,529 | How can I compute the time differential between two time zones in Python? That is, I don't want to compare TZ-aware `datetime` objects and get a `timedelta`; I want to compare two `TimeZone` objects and get an `offset_hours`. Nothing in the `datetime` library handles this, and neither does [`pytz`](https://pypi.python.... | 2017/10/13 | [
"https://Stackoverflow.com/questions/46736529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504550/"
] | Here's another solution:
```
from datetime import datetime
from pytz import timezone
from dateutil.relativedelta import relativedelta
utcnow = timezone('utc').localize(datetime.utcnow()) # generic time
here = utcnow.astimezone(timezone('US/Eastern')).replace(tzinfo=None)
there = utcnow.astimezone(timezone('Asia/Ho_Ch... | ```
from datetime import datetime
from zoneinfo import ZoneInfo
dt = datetime.now() # 2020-09-13
tz0, tz1 = "Europe/Berlin", "US/Eastern" # +2 vs. -4 hours rel. to UTC
utcoff0, utcoff1 = dt.astimezone(ZoneInfo(tz0)).utcoffset(), dt.astimezone(ZoneInfo(tz1)).utcoffset()
print(f"hours offset between {tz0} -> {tz1} tim... | 222 |
28,744,759 | I have a question concerning stdin buffer content inspection.
This acclaimed line of code:
```
int c; while((c = getchar()) != '\n' && c != EOF);
```
deals efficiently with discarding stdin-buffer garbage, in case there is a garbage found. In case the buffer is empty, the program execution wouldn't go past it.
Is ... | 2015/02/26 | [
"https://Stackoverflow.com/questions/28744759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3078414/"
] | >
> You can not give a background color into `include` tag.
>
>
>
**Why ?**
Its obvious , if you could able to give the background color to `include` tag then it would be all messed up with your `include` color and another color which might be applied to that `layout` which has already included .
However, you ca... | Try this:
```
<include
android:id="@+id/list_item_section_text"
android:layout_width="fill_parent"
android:layout_height="match_parent"
layout="@android:layout/preference_category"/>
```
in preference category layout:
```
<LinearLayout
android:id="@+id/preference_category"
android:layout_wi... | 232 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.