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 |
|---|---|---|---|---|---|---|
56,305,416 | Hi I am following this tutorial
<https://stackabuse.com/association-rule-mining-via-apriori-algorithm-in-python/>
and am getting the following error when I run the below code.
I am honestly not sure what to try as I am following the tutorial verbatim.
I don't see what the issue is.
```
#import numpy as np
#import... | 2019/05/25 | [
"https://Stackoverflow.com/questions/56305416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11554788/"
] | Your code is very similar to this one I found on medium:
<https://medium.com/@deepak.r.poojari/apriori-algorithm-in-python-recommendation-engine-5ba89bd1a6da>
I guess you wanted to do `print(len(association_results))` instead of association\_rules, as is done in the linked article? | it's a generator, and it only point's to the first block of your code list, if u want to find length , then iterate over it first and then use length ie `print(len(list(association_rules)))` | 971 |
14,669,990 | How can I write this complete code in python in just one line or may be I must say something which uses least space or least no of characters?
```
t=int(input())
while t>0:
n=int(input())
s=sum(1/(2.0*i+1) for i in range(n))
print "%.15f"%s
t-=1
``` | 2013/02/03 | [
"https://Stackoverflow.com/questions/14669990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1440140/"
] | You're welcome
```
for t in range(int(input()), 0, -1): print '%.15f' % sum(1/(2.0*i+1) for i in range(int(input())))
```
**EDIT** (explanation):
Firstly, instead of a while loop you can use a [for loop](http://docs.python.org/2/reference/compound_stmts.html#for) in a [range](http://docs.python.org/2/library/functi... | `exec"print sum((-1.)**i/(i-~i)for i in range(input()));"*input()`
I know I am too late for answering this question.but above code gives same result.
It will get even more shorter. I am also finding ways to shorten it. #CodeGolf #Python2.4 | 972 |
58,599,829 | I have a python script called "server.py" and inside it I have a function `def calcFunction(arg1): ... return output` How can I call the function calcFunction with arguments and use the return value in autohotkey? This is what I want to do in autohotkey:
```
ToSend = someString ; a string
output = Run server.py, calc... | 2019/10/28 | [
"https://Stackoverflow.com/questions/58599829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11340003/"
] | You can define a custom GHCi command using `:def` in this way:
```
> :def foo (\_ -> return "print 100\nprint 200\n:t length")
> :foo
100
200
length :: Foldable t => t a -> Int
```
In the returned string, `:`-commands can be included as well, like `:t` above. | One way I've found is creating a separate file:
```
myfunction 0 100
myfunction 0 200
myfunction 0 300
:r
```
and then using:
`:script path/to/file` | 974 |
58,736,009 | I am trying to run the puckel airflow docker container using the LocalExecutor.yml file found here:
<https://github.com/puckel/docker-airflow>
I am not able to get airflow to send me emails on failure or retry.
I've tried the following:
1. Editing the config file with the smtp host name
```
[smtp]
# If you want ai... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7470072/"
] | You can groupby and transform for idxmax, eg:
```
dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax')
``` | Given your example, you can use reset\_index() together with groupby and then merge it into the original dataframe:
```
import pandas as pd
data = [['AAA','2019-01-01', 10], ['AAA','2019-01-02', 21],
['AAA','2019-02-01', 30], ['AAA','2019-02-02', 45],
['BBB','2019-01-01', 50], ['BBB','2019-01-02', 60]... | 976 |
44,424,308 | C++ part
I have a class `a` with a **public** variable 2d int array `b` that I want to print out in python.(The way I want to access it is `a.b`)
I have been able to wrap the most part of the code and I can call most of the functions in class a in python now.
So how can I read b in python? How to read it into an nump... | 2017/06/07 | [
"https://Stackoverflow.com/questions/44424308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7967265/"
] | There's some relevant information in the Fetch specification.
As per <https://fetch.spec.whatwg.org/#forbidden-response-header-name>:
>
> A forbidden response-header name is a header name that is a
> byte-case-insensitive match for one of:
>
>
> * `Set-Cookie`
> * `Set-Cookie2`
>
>
>
And then as per item 6 in... | You may try following:
```
async function handleRequest(request) {
let response = await fetch(request.url, request);
// Copy the response so that we can modify headers.
response = new Response(response.body, response)
response.headers.set("Set-Cookie", "test=1234");
return response;
}
``` | 981 |
38,722,340 | Let's consider the code below
code:
```
#!/usr/bin/env python
class Foo():
def __init__(self, b):
self.a = 0.0
self.b = b
def count_a(self):
self.a += 0.1
foo = Foo(1)
for i in range(0, 15):
foo.count_a()
print "a =", foo.a, "b =", foo.b, '"a == b" ->', foo.a == foo.b
```
O... | 2016/08/02 | [
"https://Stackoverflow.com/questions/38722340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/829496/"
] | This has nothing to do with Object Orientation - it has to do with the way computers represent floating point numbers internally, and rounding errors.
<http://floating-point-gui.de/basic/>
The Python specificity here is the default string representation of floating point numbers, which will round them at less decimal ... | Aside from the, correct, explanation by jsbueno, remember that Python often allows casting of "basic types" to themselves.
i.e. str("a") == "a"
So, if you need a workaround in addition to the reason, just convert your int/float mix to all floats and test those.
```
a = 2.0
b = 2
print "a == b", float(a) == float(... | 982 |
58,721,480 | I have a python/flask/html project I'm currently working on. I'm using bootstrap 4 for a grid system with multiple rows and columns. When I try to run my project, it cuts off a few pixels on the left side of the screen. I've looked all over my code and I'm still not sure as to why this is. [Here](https://jsfiddle.net/m... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58721480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11757353/"
] | As far as Bootstrap layout is concerned, you always need to put your row and col elements within a div with the class of **container** or **container-fluid**.
If you want full width column then use **container-fluid**. **container** has a max width pixel value, whereas .**container-fluid** is max-width 100%. .**contain... | wrap your row class div inside of a container or container-fluid class div
```html
<div class='container'>
<div class='row'>
<!--your grid-->
</div>
</div>
``` | 983 |
5,159,351 | urllib fetches data from urls right? is there a python library that can do the reverse of that and send data to urls instead (for example, to a site you are managing)? and if so, is that library compatible with apache?
thanks. | 2011/03/01 | [
"https://Stackoverflow.com/questions/5159351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/582485/"
] | What does sending data to a URL mean? The usual way to do that is just via an HTTP POST, and `urllib` (and `urllib2`) handle that just fine. | urllib can send data associated with a request by using GET or POST.
`urllib2.urlopen(url, data)` where data is a dict of key-values representing the data you're sending. See [this link on usage](http://www.java2s.com/Code/Python/Network/SubmitPOSTData.htm).
Then process that data on the server-side.
If you want to ... | 986 |
63,894,354 | i'm very much a newbie to python. I've read a csv file correctly, and if i do a print(row[0]) in a for loop it prints the first column. But now within the loop, i'd like to do a conditional. Obviously using row[0] in it doesn't work. what's the correct syntax?
here's my code
```
video_choice = input("What movie would ... | 2020/09/15 | [
"https://Stackoverflow.com/questions/63894354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8628471/"
] | you could do
```
if video_choice in row[0]:
...
``` | nvm, I have the if as "If". I'm def a newb | 987 |
28,176,866 | I have a list in python like this:
```
myList = [1,14,2,5,3,7,8,12]
```
How can I easily find the first unused value? (in this case '4') | 2015/01/27 | [
"https://Stackoverflow.com/questions/28176866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506998/"
] | Don't know how efficient, but why not use an xrange as a mask and use set minus?
```
>>> myList = [1,14,2,5,3,7,8,12]
>>> min(set(xrange(1, len(myList) + 1)) - set(myList))
4
```
You're only creating a set as big as `myList`, so it can't be that bad :)
This won't work for "full" lists:
```
>>> myList = range(1, 5)... | I just solved this in a probably non pythonic way
```
def solution(A):
# Const-ish to improve readability
MIN = 1
if not A: return MIN
# Save re-computing MAX
MAX = max(A)
# Loop over all entries with minimum of 1 starting at 1
for num in range(1, MAX):
# going for greatest missing ... | 988 |
8,616,617 | I installed a local [SMTP server](http://www.hmailserver.com/) and used [`logging.handlers.SMTPHandler`](http://docs.python.org/library/logging.handlers.html#smtphandler) to log an exception using this code:
```
import logging
import logging.handlers
import time
gm = logging.handlers.SMTPHandler(("localhost", 25), 'in... | 2011/12/23 | [
"https://Stackoverflow.com/questions/8616617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348545/"
] | The simplest form of asynchronous smtp handler for me is just to override `emit` method and use the original method in a new thread. GIL is not a problem in this case because there is an I/O call to SMTP server which releases GIL. The code is as follows
```
class ThreadedSMTPHandler(SMTPHandler):
def emit(self, re... | Here's the implementation I'm using, which I based on Jonathan Livni code.
```
import logging.handlers
import smtplib
from threading import Thread
# File with my configuration
import credentials as cr
host = cr.set_logSMTP["host"]
port = cr.set_logSMTP["port"]
user = cr.set_logSMTP["user"]
pwd = cr.set_logSMTP["pwd"... | 998 |
10,647,045 | When I try to use `ftp.delete()` from ftplib, it raises `error_perm`, resp:
```
>>> from ftplib import FTP
>>> ftp = FTP("192.168.0.22")
>>> ftp.login("user", "password")
'230 Login successful.'
>>> ftp.cwd("/Public/test/hello/will_i_be_deleted/")
'250 Directory successfully changed.'
>>> ftp.delete("/Public/test/hell... | 2012/05/18 | [
"https://Stackoverflow.com/questions/10647045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1402511/"
] | You need to use the `rmd` command, i.e
`ftp.rmd("/Public/test/hello/will_i_be_deleted/")`
`rmd` is for removing directories, `delete`is for removing files. | The only method that works for me is that I can rename with the ftp.rename() command:
e.g.
```
ftp.mkd("/Public/Trash/")
ftp.rename("/Public/test/hello/will_i_be_deleted","/Public/Trash/will_i_be_deleted")
```
and then to manually delete the contents of Trash from time to time.
I do not know if this is an exclusiv... | 1,008 |
56,581,237 | How efficient is python (cpython I guess) when allocating resources for a newly created instance of a class? I have a situation where I will need to instantiate a node class millions of times to make a tree structure. Each of the node objects *should* be lightweight, just containing a few numbers and references to pare... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56581237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1394763/"
] | Superficially it's quite simple: Methods, class variables, and the class docstring are stored in the class (function docstrings are stored in the function). Instance variables are stored in the instance. The instance also references the class so you can look up the methods. Typically all of them are stored in dictionar... | *[edit] It is not easy to get an accurate measurement of memory usage by a python process; **I don't think my answer completely answers the question**, but it is one approach that may be useful in some cases.*
*Most approaches use proxy methods (create n objects and estimate the impact on the system memory), and exter... | 1,010 |
13,876,441 | Hej,
I'm using the latest version (1.2.0) of matplotlib distributed with macports. I run into an AssertionError (I guess stemming from internal test) running this code
```
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
X,Y = np.meshgrid(np.arange(0, 2*np.pi, .2), np.arange(0, 2*np.pi, .2))... | 2012/12/14 | [
"https://Stackoverflow.com/questions/13876441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/932593/"
] | You can save as eps or svg and convert to pdf. I found that the best way to produce small pdf files is to save as eps in matplotlib and then use epstopdf.
svg also works fine, you can use Inkscape to convert to pdf. A side-effect of svg is that the text is converted to paths (no embedded fonts), which might be desirab... | The matplotlib (v 1.2.1) distributed with Ubuntu 13.04 (raring) also has this bug. I don't know if it's still a problem in newer versions.
Another workaround (seems to work for me) is to completely delete the `draw_path_collection` function in `.../matplotlib/backends/backend_pdf.py`. | 1,013 |
892,196 | buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !! | 2009/05/21 | [
"https://Stackoverflow.com/questions/892196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105167/"
] | If you want the Python standard library to do the work for you (recommended!), use [smtplib](http://docs.python.org/library/smtplib.html). To see whether sending the mail worked, just open your inbox ;)
If you want to implement the protocol yourself (is this homework?), then read up on the [SMTP protocol](http://www.i... | Depends what you mean by "received". It's possible to verify "delivery" of a message to a server but there is no 100% reliable guarantee it actually ended up in a mailbox. smtplib will throw an exception on certain conditions (like the remote end reporting user not found) but just as often the remote end will accept th... | 1,014 |
7,230,621 | I'm trying to find a method to iterate over an a pack variadic template argument list.
Now as with all iterations, you need some sort of method of knowing how many arguments are in the packed list, and more importantly how to individually get data from a packed argument list.
The general idea is to iterate over the li... | 2011/08/29 | [
"https://Stackoverflow.com/questions/7230621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658162/"
] | There is no specific feature for it right now but there are some workarounds you can use.
Using initialization list
=========================
One workaround uses the fact, that subexpressions of [initialization lists](http://en.cppreference.com/w/cpp/language/list_initialization) are evaluated in order. `int a[] = {g... | You can use multiple variadic templates, this is a bit messy, but it works and is easy to understand.
You simply have a function with the variadic template like so:
```
template <typename ...ArgsType >
void function(ArgsType... Args){
helperFunction(Args...);
}
```
And a helper function like so:
```
void helpe... | 1,017 |
13,736,191 | I'm stuck on this [exercise](http://www.codecademy.com/courses/python-beginner-en-qzsCL/0?curriculum_id=4f89dab3d788890003000096#!/exercises/3). Its asking me to print out from the list that has dictionaries in it but I don't even know how to. I can't find how to do something like this on google... | 2012/12/06 | [
"https://Stackoverflow.com/questions/13736191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1260452/"
] | This is a more efficient answer that I found:
```
for persons in students:
for grades in persons:
print persons[grades]
``` | Next time you should specify more carefully what your question is.
Below is the loop that the exercise is asking for.
```
for s in students:
print s['name']
print s['homework']
print s['quizzes']
print s['tests']
``` | 1,027 |
29,384,129 | Basically I have a matrix in python 'example' (although much larger). I need to product the array 'example\_what\_I\_want' with some python code. I guess a for loop is in order- but how can I do this?
```
example=
[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]
example_what_I_want =
... | 2015/04/01 | [
"https://Stackoverflow.com/questions/29384129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285950/"
] | I'm assuming `example` is actually:
```
example = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
```
In which case you could do:
```
swapped_example = [sublst if idx%2 else sublst[::-1] for
idx,sublst in enumerate(exam... | Or, you can use iter.
```
a = [[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]]
b = []
rev_a = iter(a[::-1])
while rev_a:
try:
b.append(rev_a.next()[::-1])
b.append(rev_a.next())
except StopIteration:
break
print b
```
Modified (Did not know that ea... | 1,028 |
61,882,136 | working on a coding program that I think I have licked and I'm getting the correct values for. However the test conditions are looking for the values formatted in a different way. And I'm failing at figuring out how to format the return in my function correctly.
I get the values correctly when looking for the answer:
... | 2020/05/19 | [
"https://Stackoverflow.com/questions/61882136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13571383/"
] | The `try-except` indention creates the problem:
```
def myAlarm():
try:
myTime = list(map(int, input("Enter time in hr min sec\n") .split()))
if len(mytime) == 3:
total_secounds = myTime[0]*60*60+myTime[1]*60+myTime[2]
time.sleep(total_secounds)
frequency = 2500 ... | There were three mistakes in your code
1. Indentation of try-except block
2. Spelling of except
3. at one place you have used myTime and at another mytime.
```
import time
import winsound
print("Made by Ethan")
def myAlarm():
try:
myTime = list(map(int, input("Enter time in hr min sec\n") .split()))
... | 1,029 |
39,026,950 | I'm trying to set up a django app that connects to a remote MySQL db. I currently have Django==1.10 and MySQL-python==1.2.5 installed in my venv. In settings.py I have added the following to the DATABASES variable:
```
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_name',
'USER': 'db_user',... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3861295/"
] | The error you're seeing has nothing to do with your database settings (assuming your real code has the actual database name, username, and password) or connection. You are not importing the RequestSite from the correct spot.
Change (wherever you have this set) from:
```
from django.contrib.sites.models import Request... | This is documentation you should look at this for connecting to databases and how django does it, from what you gave us, as long as your parameters are correct you should be connecting to the database but a good confirmation of this would be the inspectdb tool.
<https://docs.djangoproject.com/en/1.10/ref/databases/>
... | 1,034 |
50,322,384 | I am new to machine learning and the sklearn package. when trying to import sklearn, I am getting an error saying it cannot find a DLL. I installed sklearn through pip, have un-installed everything including python and re-installed it all and still am having the same issue. only one version of python is installed on th... | 2018/05/14 | [
"https://Stackoverflow.com/questions/50322384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9785849/"
] | Check the version of python that you are using. Is it 64 bit or 32 bit? The only time I have seen that error is when there was a mismatch between the package type and the Python version.
If there is nothing wrong there you can try the following:
```
import imp
imp.find_module("sklearn")
```
This will tell you exact... | Although it is difficult to guess the issue you are experiencing based on what is provided, try the following:
```
from sklearn.model_selection import cross_validate
from sklearn.neighbors import KNeighborsClassifier
``` | 1,035 |
54,717,221 | I'm trying to write a Python operator in an airflow DAG and pass certain parameters to the Python callable.
My code looks like below.
```
def my_sleeping_function(threshold):
print(threshold)
fmfdependency = PythonOperator(
task_id='poke_check',
python_callable=my_sleeping_function,
provide_context=True... | 2019/02/15 | [
"https://Stackoverflow.com/questions/54717221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4017926/"
] | Add \*\*kwargs to your operator parameters list after your threshold param | This is how you can pass arguments for a Python operator in Airflow.
```
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from time import sleep
from datetime import datetime
def my_func(*op_args):
print(op_args)
... | 1,038 |
55,052,883 | I may may need help phrasing this question better. I'm writing an async api interface, via python3.7, & with a class (called `Worker()`). `Worker` has a few blocking methods I want to run using `loop.run_in_executor()`.
I'd like to build a decorator I can just add above all of the non-`async` methods in `Worker`, but... | 2019/03/07 | [
"https://Stackoverflow.com/questions/55052883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6293857/"
] | Not\_a\_Golfer answered my question in the comments.
Changing the inner `wraps()` function from a coroutine into a generator solved the problem:
```py
def run_method_in_executor(func, *, loop=None):
def wraps(*args):
_loop = loop if loop is not None else asyncio.get_event_loop()
yield _loop.run_i... | Here is a complete example for Python 3.6+ which does not use interfaces deprecated by 3.8. Returning the value of `loop.run_in_executor` effectively converts the wrapped function to an *awaitable* which executes in a thread, so you can `await` its completion.
```py
#!/usr/bin/env python3
import asyncio
import functo... | 1,039 |
40,535,066 | I'm trying to override a python class (first time doing this), and I can't seem to override this method. When I run this, my recv method doesn't run. It runs the superclasses's method instead. What am I doing wrong here? (This is python 2.7 by the way.)
```
import socket
class PersistentSocket(socket.socket):
def... | 2016/11/10 | [
"https://Stackoverflow.com/questions/40535066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2100448/"
] | The socket type (officially `socket.SocketType`, though `socket.socket` happens to be the same object) makes the strange choice of implementing `recv` and a few other methods as instance attributes, rather than as normal methods in the class dict. In `socket.SocketType.__init__`, it sets a `self.recv` instance attribut... | Picking on the explanation from @user2357112, one thing that seems to have helped is to do a `delattr(self, 'recv')` on the class constructor (inheriting from `socket.SocketType`) and then define you own `recv` method; for example:
```
class PersistentSocket(socket.SocketType):
def __init__(self):
"""As us... | 1,042 |
37,598,337 | I want to apply a fee to an amount according with this scale:
```
AMOUNT FEE
------- ---
0 24.04 €
6010.12 0.00450
30050.61 0.00150
60101.21 0.00100
150253.03 0.00050
601012.11 0.00030
```
From 0 to 6010.13€ is a fix fee of 24.04€
My code:
```
def fee(amount):
scale = [[0, 24.0... | 2016/06/02 | [
"https://Stackoverflow.com/questions/37598337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3160820/"
] | I think a better way would be to use a while loop to check if `amount` is lesser then `scale[i+1][0]` so that you may just use `scale[i][1]`. And also give an else to handle anything greater than `scale[len(scale)][0]`. | You aren't handling that one case. You should just add another `if` statement outside the loop (similar to the `if ammount <= scale[1][0]` you used, because values in both of these ranges are not handled by the loop):
```
if ammount >= scale[len(scale) - 1][0]:
fee = scale[len(scale) - 1][1]
```
Btw, there's a l... | 1,043 |
60,011,277 | New to coding and running through the exercises in Python Crash Course version 2. One of the exercises involves creating a file called "remember\_me.py" and as far as I can tell, I'm entering the code as it exists in the book almost verbatim, but getting an error:
```
"""Exercise for Python Crash Course."""
import jso... | 2020/01/31 | [
"https://Stackoverflow.com/questions/60011277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12821839/"
] | ```
import json
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")
e... | ```
def get_stored_number():
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
**except json.decoder.JSONDecodeError:
return None**
else:
return username
number()
```
Solve this problem adding except for blank file ... | 1,046 |
5,238,785 | In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax
obj.send(funcname)
Is there something similar in python.
The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement. | 2011/03/08 | [
"https://Stackoverflow.com/questions/5238785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650556/"
] | ```
getattr(obj, "name")(args)
```
| hmmm... getattr(obj, funcname)(\*args, \*\*kwargs) ?
```
>>> s = "Abc"
>>> s.upper()
'ABC'
>>> getattr(s, "upper")()
'ABC'
>>> getattr(s, "lower")()
'abc'
``` | 1,047 |
47,608,612 | Whilst I was learning pygame, I stumbled across a line of code that I did not understand:
```
if y == 0 or y == height-1: var1 *= -1
```
I understand what if statements are in python and the usage of logic gates, what I don't understand is the small piece of statement after the if statement:
"var1 \*= 1"
Can someon... | 2017/12/02 | [
"https://Stackoverflow.com/questions/47608612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8687842/"
] | Actually there is no rule that you cannot write something after a colon in Python. In fact, you could write multiple statements after an if condition as well, like: `if True: print("foo"); print("bar")`.
However for stylistic reasons generally it is recommended to write it in a new line after the colon. Exceptions mig... | ```
var *= -1
```
is equivalent to
```
var = var * (-1)
```
So it means that the sign of var will change .
---
```
if condition: statement
```
is equivalent to
```
if condition:
statement
``` | 1,052 |
59,338,922 | I'm looking for a convention stating how different types of methods (i.e. `@staticmethod` or `@classmethod`) inside the Python class definition should be arranged. [PEP-8](https://www.python.org/dev/peps/pep-0008) does not provide any information about such topic.
For example, Java programming language has some [code... | 2019/12/14 | [
"https://Stackoverflow.com/questions/59338922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7217645/"
] | The lack of answers so far just triggered me to simply write down the way I do it:
```
class thing(object):
info = 'someinfo'
# this can be useful to provide information about the class,
# either as text or otherwise, in case you have multiple similar
# but different classes.
# It's also useful if... | I think the way to declare `@staticmethod` and `@classmethod` on python is by adding that method statement (`@staticmethod` or `@classmethod`) directly above of your function.
The usage of `@classmethod` is like instance function, it requires some argument like `class` or `cls` (u can change the parameter name so it... | 1,057 |
51,928,090 | I am trying to separate the pixel values of an image in python which are in a numpy array of 'object' data-type in a single quote like this:
```
['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 .... 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 ... | 2018/08/20 | [
"https://Stackoverflow.com/questions/51928090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9804344/"
] | You can use `str.split`
**Ex:**
```
l = ['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90']
print( list(map(int, l[0].split())) )
```
**Output:**
```
[238, 236, 237, 238, 240, 240,... | I believe using [`np.ndarray.item()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html) is idiomatic to retrieve a single item from a numpy array.
```
import numpy as np
your_numpy_array = np.asarray(['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 143 136 13... | 1,058 |
37,335,027 | The following python code has a bug:
```
class Location(object):
def is_nighttime():
return ...
if location.is_nighttime:
close_shades()
```
The bug is that the programmer forgot to call `is_nighttime` (or forgot to use a `@property` decorator on the method), so the method is cast by `bool` evaluat... | 2016/05/19 | [
"https://Stackoverflow.com/questions/37335027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1205529/"
] | In theory, you could wrap the function in a function-like object with a `__call__` that delegates to the function and a `__bool__` that raises a TypeError. It'd be really unwieldy and would probably cause more bad interactions than it'd catch - for example, these objects won't work as methods unless you add more specia... | Short answer: `if is_nighttime():`, with parenthesis to call it.
Longer answer:
`is_nighttime` points to a function, which is a non-None type. `if` looks for a condition which is a boolean, and casts the symbol `is_nighttime` to boolean. As it is not zero and not None, it is True. | 1,059 |
15,663,899 | It turns out building the following string in python...
```
# global variables
cr = '\x0d' # segment terminator
lf = '\x0a' # data element separator
rs = '\x1e' # record separator
sp = '\x20' # white space
a = 'hello'
b = 'world'
output = a + rs + b
```
...is not the same as it may be in C#.
How do I accomplish t... | 2013/03/27 | [
"https://Stackoverflow.com/questions/15663899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/687137/"
] | It is known as [type cast](http://en.wikipedia.org/wiki/Type_conversion) or type conversion. It is used when you want to cast one of type of data to another type of data. | ```
(some_type) *apointer
```
This mean that you cast the `apointer` content to the `some_type` type | 1,061 |
60,212,670 | I have a form on an HTML page with an `input type="text"` that I'm replacing with a `textarea`. Now the form no longer works. When I try to submit it, I get an error "UnboundLocalError: local variable 'updated\_details' referenced before assignment" referring to my python code (I didn't change the python at all).
**Ol... | 2020/02/13 | [
"https://Stackoverflow.com/questions/60212670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12555158/"
] | Since you want to test `if(getStatisticsLinks) { ... }` and narrow the type to `LinkInterface` when test passes, this is actually very easy. Your function never returns `true`, only `false`, so the return type can be `LinkInterface | false` instead of `LinkInterface | boolean`.
That said, I would suggest returning `un... | You will need to write your own typeguard to "narrow down" the type, such that the TypeScript compiler knows that `getStatisticsLinks` is of type `LinkInterface` when it is being used in `this.service.get(getStatisticsLinks.href).subscribe(.....);`.
This is one way you can write the type guard:
```
function isLinkInt... | 1,064 |
69,188,407 | I try to use a loop to do some operations on the Pandas numeric and category columns.
```
df = sns.load_dataset('diamonds')
print(df.dtypes,'\n')
carat float64
cut category
color category
clarity category
depth float64
table float64
price int64
x float64
y ... | 2021/09/15 | [
"https://Stackoverflow.com/questions/69188407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15670527/"
] | Solution
========
Try using `pd.api.types.is_categorical_dtype`:
```
for i in df.columns:
if pd.api.types.is_categorical_dtype(df[i]):
print(i)
```
Or check the `dtype` name:
```
for i in df.columns:
if df[i].dtype.name == 'category':
print(i)
```
Output:
```
cut
color
clarity
```
Expl... | If you have only one possibility in your list, go with @U12-Forward's solution.
Yet, if you want to match several types, you can just convert your type to check to its string representation:
```
for i in df.columns:
if str(df[i].dtypes) in ['category', 'othertype']:
print(i)
```
Output:
```
cut
color
c... | 1,065 |
48,477,200 | I'm having a problem trying to extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that.
Instead, I get this error message, but I'm not able to solve it:
```
Traceback (most recent call last):
File "python", line 45, ... | 2018/01/27 | [
"https://Stackoverflow.com/questions/48477200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9147054/"
] | Modifying a list while going through it is a bad idea.
```
for i in range (0,10) :
if queue1.items[i]!=s2 :
queue1.extract()
elif queue1.items[i]==s2 :
queue1.extract()
print ("Remaining numbers:\n",queue1.items)
```
This code modifies your queue - items, it shortens the items-li... | You can try replacing the last part of your code i.e.
```
for i in range (0,10) :
if queue1.items[i]!=s2 :
queue1.extract()
elif queue1.items[i]==s2 :
queue1.extract()
print ("Remaining numbers:\n",queue1.items)
break
if queue1.empty()==True :
print ("Queue is empty now", cola1.items)
```
... | 1,066 |
50,151,490 | I've been trying to send free sms using way2sms. I found this link where it seemed to work on python 3: <https://github.com/shubhamc183/way2sms>
I've saved this file as way2sms.py:
```
import requests
from bs4 import BeautifulSoup
class sms:
def __init__(self,username,password):
'''
Takes username and pass... | 2018/05/03 | [
"https://Stackoverflow.com/questions/50151490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5250206/"
] | To send `sms` using `way2sms` account, you may use below code snippet.
Before that you would be required to create an API `Key` from [here](https://smsapi.engineeringtgr.com/)
```
import requests
url = "https://smsapi.engineeringtgr.com/send/"
params = dict(
Mobile='login username',
Password='login password',... | First of all make sure you have all the dependencies like requests and bs4, if not trying downloading them using pip3 since this code work on Python3 **not** python2.
I have update the [repository](https://github.com/shubhamc183/way2sms).
>
> The mobilenumber should also be in String format
>
>
>
So, instead of ... | 1,070 |
38,885,431 | I'm really stuck on this one, but I am a python (and Raspberry Pi) newbie. All I want is to output the `print` output from my python script. The problem is (I believe) that a function in my python script takes half a second to execute and PHP misses the output.
This is my php script:
```
<?php
error_reporting(E_ALL);... | 2016/08/11 | [
"https://Stackoverflow.com/questions/38885431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066625/"
] | Following code example may help you understand what you need to do:
1. Create an array of index paths
2. Add the 20 data objects which you received from the server in your data source.
3. Now since your data source and array of index paths are on the same page, begin table view updates and insert the rows.
That's it.... | When you call `insertRowsAtIndexPaths`, the number of row present in your data source must be equal to the previous count plus the number of rows being inserted. But you appear to be inserting one `NSIndexPath` in the table, but your `names` array presumably has 20 more items. So, make sure that the number of `NSIndexP... | 1,072 |
67,039,337 | Here's my [small CSV file](https://github.com/gusbemacbe/aparecida-covid-19-tracker/blob/main/data/aparecida-small-sample.csv), which is totally encoded in UTF-8, and the date is totally correct.
I repaired the erros from:
* [Is there a function to get the difference between two values on a pandas dataframe timeserie... | 2021/04/10 | [
"https://Stackoverflow.com/questions/67039337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8041366/"
] | Based on your posted code I made some changes:
1. I have put in a print statement for the DataFrame after read.
This should show the datatypes for each column in the DataFrame. For the date - field it should be "datetime64[ns]".
2. Afterwards you don't have to parse it again as a date.
3. Some code changes for the "ca... | @Gustavo Reis according to your question in the answered segment:
```py
city['daily_cases'] = city['totalCases']
city['daily_deaths'] = city['totalDeaths']
city['daily_recovered'] = city['totalRecovered']
tempCityDailyCases = city[['date','daily_cases']]
tempCityDailyCases["title"] = "Daily Cases"
tempCityDailyDeaths... | 1,073 |
42,015,768 | How would I modify this program so that my list doesn't keep spitting out the extra text per line? The program should only output the single line that the user wants to display rather than the quotes that were added to the list before. The program will read a textfile indicated by the user, then it will display the sel... | 2017/02/03 | [
"https://Stackoverflow.com/questions/42015768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7151347/"
] | As far as disk storage and ram memory are concerned, `'\n` is just another character. As far as tcl/tk and Python's `tkinter` wrapper are concerned, newlines are very important. Since tk's Text widget is intended to display text to humans, and since vertical scrolling is much more useful for this than horizontal scroll... | You shouldn't have to worry about a limit. As for a new line, you can use an `if` with `\n` or a `for` loop depending on what you're going for. | 1,074 |
49,658,679 | I have a nested json and i want to find a record whose value is equal to a given number. I'm using pymongo in python wih equal operator but getting some errors:
```
from pymongo import MongoClient
import datetime
import json
import pprint
def connectDatabase(service):
try:
if service=="mongodb":
... | 2018/04/04 | [
"https://Stackoverflow.com/questions/49658679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7422128/"
] | In Python you have to use Python syntax, not JS syntax like in the Mongo shell. That means that dictionary keys need quotes:
```
print(cstore.posts1.find( {"CSPAccountNo": { "$eq": "414693" } } )
```
(Note, in your code you never actually insert the `new_posts` into the collection, so your find call might not actual... | It should be
```
print (xxx.posts1.find( {"tags.CSPAccountNo": { $eq: "414693" } } )
``` | 1,076 |
60,928,238 | I'm using selenium in python and I'm looking to select the option Male from the below:
```
<div class="formelementcontent">
<select aria-disabled="false" class="Width150" id="ctl00_Gender" name="ctl00$Gender" onchange="javascript: return doSearch();" style="display: none;">
<option selected="selec... | 2020/03/30 | [
"https://Stackoverflow.com/questions/60928238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11483107/"
] | As per the HTML you have shared the `<select>` tag is having the value of *style* attribute set as **`display: none;`**. So using [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491) it would be tough interacting with this [WebElement](https://stackoverflow.c... | Try below solutions:
**Solution 1:**
```
select = Select(driver.find_element_by_id('ctl00_Gender'))
select.select_by_value('MALE')
```
**Note** add below imports to your solution :
```
from selenium.webdriver.support.ui import Select
```
**Solution 2:**
```
driver.find_element_by_xpath("//select[@id='ctl00_Ge... | 1,077 |
52,672,810 | I have a Node.js API using Express.js with body parser which receives a BSON binary file from a python client.
Python client code:
```
data = bson.BSON.encode({
"some_meta_data": 12,
"binary_data": binary_data
})
headers = {'content-type': 'application/octet-stream'}
response = requests.put(endpoint_url, hea... | 2018/10/05 | [
"https://Stackoverflow.com/questions/52672810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531894/"
] | You'll want to use <https://www.npmjs.com/package/raw-body> to grab the raw contents of the body.
And then pass the [`Buffer`](https://nodejs.org/api/buffer.html) object to `bson.deserialize(..)`. Quick dirty example below:
```
const getRawBody = require("raw-body");
app.use(async (req, res, next) => {
if (req.... | You could as well use the [body-parser](https://github.com/expressjs/body-parser) package:
```
const bodyParser = require('body-parser')
app.use(bodyParser.raw({type: 'application/octet-stream', limit : '100kb'}))
app.use((req, res, next) => {
if (Buffer.isBuffer(req.body)) {
req.body = JSON.parse(req.bo... | 1,078 |
73,428,442 | I need to get the absolute path of a file in python, i already tried `os.path.abspath(filename)` in my code like this:
```py
def encrypt(filename):
with open(filename, 'rb') as toencrypt:
content = toencrypt.read()
content = Fernet(key).encrypt(content)
with open(filename, "wb") as toencrypt:
t... | 2022/08/20 | [
"https://Stackoverflow.com/questions/73428442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19400931/"
] | If you want to control something over time in Pygame you have two options:
1. Use [`pygame.time.get_ticks()`](https://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks) to measure time and and implement logic that controls the object depending on the time.
2. Use the timer event. Use [`pygame.time.set_timer()`](... | You could try making spawn\_ship async, then use a thread so it doesn't affect the main loop
```py
import threading
def main():
threading.Timer(5.0, spawn_ship).start()
async def spawn_ship():
# ...
``` | 1,079 |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correc... | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match.
Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framew... | What middleware do you think you need? You may very well not need to include any WSGI ‘middleware’-like components at all. You can perfectly well put together a loose ‘pseudo-framework’ of standalone libraries without needing to ‘wrap’ the application in middleware at all.
(Personally I use a separate form-reading lib... | 1,080 |
32,295,943 | I am trying to sort a list in python with integers and a float using
"a.sort([1])" (I am sorting it from the second element of the list) but it keeps on saying "TypeError: must use keyword argument for key function". What should I do? Also my list looks like this:
["bob","2","6","8","5.3333333333333"] | 2015/08/30 | [
"https://Stackoverflow.com/questions/32295943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4464968/"
] | [Paul's answer](https://stackoverflow.com/a/32296030/21945) does a nice job of explaining how to use `sort` correctly.
I want to point out, however, that sorting strings of numbers is not the same as sorting numeric values (ints and floats etc.). Sorting by strings will use character collating sequence to determine th... | try to do "a.sort()". it will sort your list.
sort cant get 1 as argument.
read more here:
<http://www.tutorialspoint.com/python/list_sort.htm>
if you trying to sort every element except the first one try to do:
```
a[1:] = sorted(a[1:])
``` | 1,090 |
66,831,049 | I am trying to document the Reports, Visuals and measures used in a PBIX file. I have a PBIX file(containing some visuals and pointing to Tabular Model in Live Mode), I then exported it as a PBIT, renamed to zip. Now in this zip file we have a folder called Report, within that we have a file called Layout. The layout f... | 2021/03/27 | [
"https://Stackoverflow.com/questions/66831049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6668031/"
] | Not sure if you have come across an answer for your question yet, but I have been looking into something similar.
Here is what I have had to do in order to get the file to parse correctly.
Big items here to not is the encoding and all the whitespace replacements.
data will then contain the parsed object.
```
with op... | This script may help: <https://github.com/grenzi/powerbi-model-utilization>
a portion of the script is:
```
def get_layout_from_pbix(pbixpath):
"""
get_layout_from_pbix loads a pbix file, grabs the layout from it, and returns json
:parameter pbixpath: file to read
:return: json goodness
"""
ar... | 1,091 |
48,097,949 | Hi am running the following model with statsmodel and it works fine.
```
from statsmodels.formula.api import ols
from statsmodels.iolib.summary2 import summary_col #for summary stats of large tables
time_FE_str = ' + C(hour_of_day) + C(day_of_week) + C(week_of_year)'
weather_2_str = ' + C(weather_index) + rain + ext... | 2018/01/04 | [
"https://Stackoverflow.com/questions/48097949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7969556/"
] | The methods t\_test, wald\_test and f\_test are for hypothesis test on the parameters directly and not for a entire categorical or composite effect.
Results.summary() shows the parameter names that patsy created for the categorical variables. Those can be used to create contrast or restrictions for the categorical eff... | Leave out the `C()`!
I tried making an analysis of these data.
```
Area Clover_yield Yarrow_stems
A 19.0 220
A 76.7 20
A 11.4 510
A 25.1 40
A 32.2 120
A 19.5 300
A 89.9 60
A 38.8 10
A 45.3 70
A 39.7 290
B 16.5 460
B 1.8 320
B 82.4 0
B 54.2 80
B ... | 1,092 |
8,919,080 | This is what my problem is: I need to make a random string 50 characters long, made up of `1`s and `0`s.
I know how to solve this problem, and even have a one-liner for it. I have also looked for various solutions to this problem on SO, only to get back what I already know([1](https://stackoverflow.com/questions/22574... | 2012/01/18 | [
"https://Stackoverflow.com/questions/8919080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198633/"
] | For Python2.7 or better:
```
In [83]: import random
In [84]: '{:050b}'.format(random.randrange(1<<50))
Out[84]: '10011110110110000011111000011100101111101001001011'
```
(In Python2.6, use `'{0:050b}'` instead of `'{:050b}'`.)
---
**Explanation**:
The `string.format` method can convert integers into their binary ... | ```
# Choose a number in [0, 1L << 50), and format it as binary.
# The [2:] lops off the prefix "0b"
bit_str = bin(random.randint(0, (1L << 50) - 1))[2:]
# We then need to pad to 50 bits.
fifty_random_bits = '%s%s' % ('0' * (50 - len(bit_str)), bit_str)
``` | 1,093 |
47,355,844 | I'm trying to run a python script in a Docker container, and i don't know why, python can't find any of the python's module. I thaught it has something to do with the PYTHONPATH env variable, so i tried to add it in the Dockerfile like this : `ENV PYTHONPATH $PYTHONPATH`
But it didn't work.
this is what my Dockerfile... | 2017/11/17 | [
"https://Stackoverflow.com/questions/47355844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8538327/"
] | Inside the container, when I `pip install bugsnag`, I get the following:
```
root@af08af24a458:/app# pip install bugsnag
Requirement already satisfied: bugsnag in /usr/local/lib/python2.7/dist-packages
Requirement already satisfied: webob in /usr/local/lib/python2.7/dist-packages (from bugsnag)
Requirement already sat... | since you're using py3, try using pip3 to install bugsnag instead of pip | 1,098 |
33,617,221 | I am trying to speed up some heavy simulations by using python's multiprocessing module on a machine with 24 cores that runs Suse Linux. From reading through the documentation, I understand that this only makes sense if the individual calculations take much longer than the overhead for creating the pool etc.
What con... | 2015/11/09 | [
"https://Stackoverflow.com/questions/33617221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5543796/"
] | Cores are shared resource like anything else on computer.
OS will usually balance load. Meaning it will spread threads on as many cores as possible.`*` Guiding metric will be core load.
So if there are less thread counts then core count some cores will sit idle. (Thread architecture prevent splitting onto multiple co... | This is the best answer I could come up with after looking through different questions and documentations:
It is pretty widely known that `multiprocessing` in general adds some sort of overhead when it comes to run time performance. This is/can be a result of a lot of different factors such as allocating RAM space, in... | 1,099 |
65,157,911 | I"m struggling on how to count the letter, number, and special character in a string. I'm a beginner and exploring python. Thank you in advance guys!
```
string=input("Enter string: Abc123--- ")
count1=0
count2=0
count3=0
count4=0
for i in string:
if(i.isletter()):
count1=count1+1
count2=c... | 2020/12/05 | [
"https://Stackoverflow.com/questions/65157911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055559/"
] | * You should import your classes directly:
```
from Item import Item # Assuming the file name is Item.py
from Inventory import Inventory # Assuming the file name is Inventory.py
```
and then you can do:
```
item1 = Item(0,"Hat", 14, 10.00)
```
* Then you use `Item` inside the `Inventory` class, but you... | This error statement TypeError: 'module' object is not callable is raised as you are being confused about the Class name and Module name. The problem is in the import line . You are importing a module, not a class. This happend because the module name and class name have the same name.
If you have a class MyClass in a ... | 1,101 |
2,693,820 | How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page.
I'm using python 2.7 but can use 3.x if required. | 2010/04/22 | [
"https://Stackoverflow.com/questions/2693820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14420/"
] | Often in a PDF, the image is simply stored as-is. For example, a PDF with a jpg inserted will have a range of bytes somewhere in the middle that when extracted is a valid jpg file. You can use this to very simply extract byte ranges from the PDF. I wrote about this some time ago, with sample code: [Extracting JPGs from... | I added all of those together in PyPDFTK [here](https://github.com/ronanpaixao/PyPDFTK/blob/master/pdf_images.py).
My own contribution is handling of `/Indexed` files as such:
```
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
... | 1,102 |
94,334 | What is the best python framework to create distributed applications? For example to build a P2P app. | 2008/09/18 | [
"https://Stackoverflow.com/questions/94334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You could checkout [pyprocessing](http://pyprocessing.berlios.de/) which will be included in the standard library as of 2.6. It allows you to run tasks on multiple processes using an API similar to threading. | You could download the source of BitTorrent for starters and see how they did it.
<http://download.bittorrent.com/dl/> | 1,112 |
51,817,237 | I am working on a Flask project and I am using marshmallow to validate user input.
Below is a code snippet:
```
def create_user():
in_data = request.get_json()
data, errors = Userschema.load(in_data)
if errors:
return (errors), 400
fname = data.get('fname')
lname = data.get('lname')
ema... | 2018/08/13 | [
"https://Stackoverflow.com/questions/51817237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10217900/"
] | I recommend you check your dependency versions.
Per the [Marshmallow API reference](http://marshmallow.readthedocs.io/en/latest/api_reference.html#schema), schema.load returns:
>
> Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if ... | according to the documentation in its most recent version (3.17.1) the way of handling with validation errors is as follows:
```
from marshmallow import ValidationError
try:
result = UserSchema().load({"name": "John", "email": "foo"})
except ValidationError as err:
print(err.messages) # => {"email": ['"foo" ... | 1,120 |
48,072,131 | I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide accordingly.
I am new to python programming. I have this simple code to generate Fibonacci series.
```
1: def fibo(n):
2: a = 0
3: b = 1
4: for x in range(n):
5: print (a, ... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48072131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1755089/"
] | ```
a = b
b = a + b
```
is actually:
```
a = b
b = b + b
```
what you want is:
```
a = b
b = old_value_of_a + b
```
When you do
`a, b = b, a + b`
it really is doing:
```
tmp_a = b
tmp_b = a + b
a = tmp_a
b = tmp_b
```
which is what you want | In line 7, you've already assigned the value in `b` to `a`, so in line 8, new value for `b` is actually double the old b's value.
While in line 6, the values on the right side of `=` will be using the old values, that's why you could get Fibo series. | 1,121 |
43,566,044 | Python does a lot with magic methods and most of these are part of some protocol. I am familiar with the "iterator protocol" and the "number protocol" but recently stumbled over the term ["sequence protocol"](https://docs.python.org/c-api/sequence.html#sequence-protocol). But even after some research I'm not exactly su... | 2017/04/23 | [
"https://Stackoverflow.com/questions/43566044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5393381/"
] | It's not really consistent.
Here's [`PySequence_Check`](https://github.com/python/cpython/blob/3.6/Objects/abstract.c#L1460):
```
int
PySequence_Check(PyObject *s)
{
if (PyDict_Check(s))
return 0;
return s != NULL && s->ob_type->tp_as_sequence &&
s->ob_type->tp_as_sequence->sq_item != NULL;
}
... | For a type to be in accordance with the sequence protocol, these 4 conditions must be met:
* Retrieve elements by index
`item = seq[index]`
* Find items by value
`index = seq.index(item)`
* Count items
`num = seq.count(item)`
* Produce a reversed sequence
`r = reversed(seq)` | 1,129 |
26,199,376 | I am trying to use level db in my python project. I zeroed in on python binding PlyVel <http://plyvel.readthedocs.org/en/latest/installation.html>, which seems to be better maintained and documented python binding.
However installation fails for plyvel
>
> plyvel/\_plyvel.cpp:359:10: fatal error: 'leveldb/db.h' fil... | 2014/10/05 | [
"https://Stackoverflow.com/questions/26199376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089768/"
] | In OS X, it seems like `/usr/local/include`, where the leveldb headers (db.h) live, is not visible to gcc.
You need to install the Apple command line tools:
```
xcode-select --install
```
plyvel will compile after that.
[Link to GH issue](https://github.com/wbolster/plyvel/issues/34). Seems to be an OS X problem. | I'm not familiar with leveldb but most direct binary installations require you to run `./configure` then `make` then `make install` before the binary is actually installed. You should try that.
Also, according to this github page you should be able to install it with `gem`: <https://github.com/DAddYE/leveldb> | 1,130 |
47,944,927 | I am trying to make a GET request to a shopify store, packershoes as follow:
```
endpoint = "http://www.packershoes.com"
print session.get(endpoint, headers=headers)
```
When I run a get request to the site I get the following error:
```
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 467, in ge... | 2017/12/22 | [
"https://Stackoverflow.com/questions/47944927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8528309/"
] | This looks like more of an SSL problem than a Python problem. You haven't shown us your code, so I'm making some guesses here, but it looks as if the site to which you are connecting is presenting an SSL certificate that doesn't match the hostname you're using. The resolution here is typically:
* See if there is an al... | Requests verifies SSL certificates for HTTPS requests, just like a web browser. By default, SSL verification is enabled, and Requests will throw a `SSLError` if it's unable to verify the certificate, you have set verify to False:
```
session.get("http://www.packershoes.com", headers=headers, verify=False)
``` | 1,139 |
22,042,673 | I've setup a code in python to search for tweets using the oauth2 and urllib2 libraries only. (I'm not using any particular twitter library)
I'm able to search for tweets based on keywords. However, I'm getting zero number of tweets when I search for this particular keyword - "Jurgen%20Mayer-Hermann". (this is challen... | 2014/02/26 | [
"https://Stackoverflow.com/questions/22042673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2935885/"
] | Change `$(document).load(` to [`$(document).ready(`](http://learn.jquery.com/using-jquery-core/document-ready/)
```
$(document).ready(function() {
var vague = $('.zero').Vague({
intensity: 3,
forceSVGUrl: false
});
vague.blur();
});
```
or use
```
$(window).load(function(){
```
or... | Try to use:
```
$(window).load(function() {
```
or:
```
$(document).ready(function() {
```
instead of:
```
$(document).load(function() {
``` | 1,140 |
56,112,849 | I have a Div containing 4 images of the same size, placed in a row. I want them to occupy all the space avaible in the div by staying in the same row, with the first image in the far left and the fourth image in the far right, they also have to be equally spaced. I can accomplish this by modifying the padding of each i... | 2019/05/13 | [
"https://Stackoverflow.com/questions/56112849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11426745/"
] | You can use flexbox. Read more about it here: <https://css-tricks.com/snippets/css/a-guide-to-flexbox/>
```css
#my-container {
display: flex;
justify-content: space-between;
}
```
```html
<div id="my-container">
<img src="https://placekitten.com/50/50" />
<img src="https://placekitten.com/50/50" />
<i... | if bootstrap is available and you can change the html then you can wrap each image in a div and use bootstrap's grid system ([here is a demo](https://codepen.io/carnnia/pen/ZNprZa)).
```css
#container{
width: 100%;
border: 1px solid red;
}
.row{
text-align: center;
}
```
```html
<div class="container" i... | 1,143 |
8,051,506 | am I going about this in the correct way? Ive never done anything like this before, so im not 100% sure on what I am doing. The code so far gets html and css files and that works fine, but images wont load, and will I have to create a new "if" for every different file type? or am I doing this a silly way...here is what... | 2011/11/08 | [
"https://Stackoverflow.com/questions/8051506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/787367/"
] | You are on the right track with it, though your ifs are very redundant. I suggest you refactor the code to check for type using a loop and a dict:
```
mime = {"html":"text/html", "css":"text/css", "png":"image/png"}
if RequestedFileType in mime.keys():
self.send_response(200)
self.send_header('Content-type', m... | As to a panoply of `if` statements, the usual approach is to have a file that handles the mapping between extensions and mime types (look here: [List of ALL MimeTypes on the Planet, mapped to File Extensions?](https://stackoverflow.com/questions/1735659/list-of-all-mimetypes-on-the-planet-mapped-to-file-extensions)). R... | 1,144 |
74,061,083 | My python GUI has been working fine from VSCode for months now, but today (with no changes in the code that I can find) it has been throwing me an error in the form of:
Exception has occurred: ModuleNotFoundError
No module named '\_tkinter'
This error occurs for any import that is not commented out. The GUI works as ... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74061083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20234707/"
] | Press Ctrl+Shift+P and type "select interpreter", press Enter and select the python interpreter path that you want to use by default in current project.
If currently selected one does not have some libraries installed, you may see error from Pylance. | The cause of this problem may be that there are multiple python versions on your machine, and the interpreter environment you are currently using is not the same environment where you installed the third-party library.
**Solution:**
1. Use the following code to get the current interpreter path
```
import sys
print(s... | 1,145 |
35,127,452 | Could someone please help me create a field in my model that generates a unique 8 character alphanumeric string (i.e. A#######) ID every time a user makes a form submission?
My **models.py** form is currently as follows:
```
from django.db import models
from django.contrib.auth.models import User
class Transfer(... | 2016/02/01 | [
"https://Stackoverflow.com/questions/35127452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2798841/"
] | Something like this:
```
''.join(random.choice(string.ascii_uppercase) for _ in range(8))
``` | In order for the ID to be truly unique you have to keep track of previously generated unique IDs, This can be simply done with a simple sqlite DB.
In order to generate a simple unique id use the following line:
```
import random
import string
u_id = ''.join(random.choice(string.ascii_letters + string.digits) for _ in... | 1,146 |
13,529,852 | I have a python GUI and i want to run a shell command which you cannot do using windows cmd
i have installed cygwin and i was wondering how i would go about running cygwin instead of the windows cmd. I am wanting to use subprocess and get the results of the .sh file
but my code
```
subprocess.check_output("./listChai... | 2012/11/23 | [
"https://Stackoverflow.com/questions/13529852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1810400/"
] | Execute a cygwin shell (e.g. `bash`) and have it run your script, instead of running your script directly:
```
subprocess.check_output("C:/cygwin/bin/bash.exe ./listChains.sh < 2p31protein.pdb")
```
Alternatively, associate the `.sh` filetype extension to open with `bash.exe`. | Using python sub-process to run a cygwin executable requires that the ./bin directory with `cygwin1.dll` be on the Windows path. `cygwin1.dll` exposes cygwin executables to Windows, allowing them to run in Windows command line and be called by Python sub-process. | 1,149 |
74,581,136 | I would like to do the same in python pandas as shown on the picture.
[pandas image](https://i.stack.imgur.com/ZsHLT.png)
This is sum function where the first cell is fixed and the formula calculates "**continuous sum**".
I tried to create pandas data frame however I did not manage to do this exactly. | 2022/11/26 | [
"https://Stackoverflow.com/questions/74581136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20557036/"
] | The phrasing, and the unqualified template, aren't super-helpful in figuring out the difference, but: `transform()` does "re-boxing" into an optional, but `and_then()` does not, expecting the function to returned a boxed value on its own. So,
* `transform()` is for when you want to use a function like `T2 foo(T1 x)`.
... | `and_then` is monadic `bind` aka `flatmap` aka `>>=` and `transform` is functorial `map`.
One can express `map` in terms of `bind` generically, but not the other way around, because a functor is not necessarily a monad. Of course the particular monad of `std::optional` can be opened at any time, so both functions are ... | 1,150 |
60,155,460 | I was planning to automate the manual steps to run the ssh commands using python. I developed the code that automatically executes the below command and log me in VM. The SSH command works fine whenever i run the code in spyder and conda prompt. The command works whenever I open the cmd and try the command directly whe... | 2020/02/10 | [
"https://Stackoverflow.com/questions/60155460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12873907/"
] | Just resolved the issue here.
I updated to the last version of all libs
```
"@react-navigation/bottom-tabs": "^5.0.1",
"@react-navigation/core": "^5.1.0",
"@react-navigation/material-top-tabs": "^5.0.1",
"@react-navigation/native": "^5.0.1",
"@react-navigation/stack": "^5.0.1",
```
and then i deleted my package-loc... | Make sure you have installed latest versions of `@react-navigation/native` and `@react-navigation/bottom-tabs`:
```js
npm install @react-navigation/native @react-navigation/bottom-tabs
```
Then clear the cache:
```sh
npm react-native start --reset-cache
```
Or if using Expo:
```js
expo start -c
``` | 1,153 |
54,337,433 | I have a list of tuples and need to delete tuples if its 1st item is matching with 1st item of other tuples in the list. 3rd item may or may not be the same, so I cannot use set (I have seen this question - [Grab unique tuples in python list, irrespective of order](https://stackoverflow.com/questions/35975441/grab-uniq... | 2019/01/23 | [
"https://Stackoverflow.com/questions/54337433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2565385/"
] | The usual way is keying a dict off whatever you want to dedupe by, for example:
```
>>> a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')]
>>> print(*{tup[:2]: tup for tup in a}.values())
(0, 13, 'order1') (14, 27, 'order2.1') (28, 41, 'order3')
```
This is *O(... | You can get the first element of each group in a grouped, sorted list:
```
from itertools import groupby
from operator import itemgetter
a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')]
result = [list(g)[0] for k, g in groupby(sorted(a), key=itemgetter(0))]
pri... | 1,154 |
54,028,502 | I have this kind of list of dictionary in python
```
[
{
"compania": "Fiat",
"modelo": "2014",
"precio": "1000"
},
{
"compania": "Renault",
"modelo": "2014",
"precio": "2000"
},
{
"compania": "Volkwagen",
"modelo": "2014",
"precio": "3000"
},
{
"compani... | 2019/01/03 | [
"https://Stackoverflow.com/questions/54028502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10864244/"
] | We can use dict comprehension
```
{a.get('compania'): {k: v for k, v in a.items() if k != 'compania'} for a in c}
{'Fiat': {'modelo': '2014', 'precio': '1000'},
'Renault': {'modelo': '2014', 'precio': '2000'},
'Volkwagen': {'modelo': '2014', 'precio': '3000'},
'Chevrolet': {'modelo': '2014', 'precio': '1000'},
'P... | ```
result = {}
for d in l:
# Store the value of the key 'compania' before popping it from the small dictionary d
compania = d['compania']
d.pop('compania')
# Construct new dictionary with key of the compania and value of the small dictionary without the compania key/value pair
result[compania] = d
... | 1,157 |
55,655,666 | Hello i m new at django. I installed all moduoles from anaconda. Then created a web application with
```
django-admin startproject
```
My project crated successfully. No problem
Then i tried to run that project at localhost to see is everything okay or not. And i run that code in command line
```
python manage.py ... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55655666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4511476/"
] | I had this problem. I solved it by running it in the Anaconda shell.
1. Open **Anaconda Shell/terminal** by pressing your Windows key and searching Anaconda
2. Go to the directory you have your django project in
3. `python manage.py runserver` | It sounds like you need to install SQLite:
<https://www.sqlite.org/download.html>
Or you could change the database settings in your settings file to use some other database. | 1,167 |
55,779,936 | I used pip to install keras and tensorflow, yet when I import subpackages from keras, my shell fails a check for PyBfloat16\_Type.tp\_base.
I tried uninstalling and reinstalling tensorflow, but I don't know for certain what is causing this error.
```
from keras.models import Sequential
from keras.layers import Dense
... | 2019/04/21 | [
"https://Stackoverflow.com/questions/55779936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11262404/"
] | You may try to downgrade python to 3.6 (I know some people have troubles with tensorflow and keras using python 3.7). One simple way is to download anaconda, create a new environment with python 3.6, then install tensorflow and keras.
`conda create -n myenv python=3.6`
`conda activate myenv`
`pip3 install tensorflow... | You have a few options to try:
First, try to uninstall and re-install the TensorFlow and see whether the problem is resolved or not (replace `tensorflow` with `tensorflow-gpu` in the following commands if you have installed the GPU version):
```
pip uninstall tensorflow
pip install --no-cache-dir tensorflow
```
I... | 1,172 |
28,023,697 | I want to setup cronjobs on various servers at the same time for Data Mining. I was also already following the steps in [Ansible and crontabs](https://stackoverflow.com/questions/21787755/ansible-and-crontabs) but so far nothing worked.
Whatever i do, i get the Error Message:
```
ERROR: cron is not a legal parameter ... | 2015/01/19 | [
"https://Stackoverflow.com/questions/28023697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4469762/"
] | I've got (something very much like) this in a ./roles/cron/tasks/main.yml file:
```
- name: Creates weekly backup cronjob
cron: minute="20" hour="5" weekday="sun"
name="Backup mysql tables (weekly schedule)"
cron_file="mysqlbackup-WeeklyBackups"
user="root"
job="/usr/local/bin/mysqlba... | If you're setting it up to run on the Crontab of the user:
```
- name: Install Batchjobs on crontab
cron:
name: "Manage Disk Space"
minute: "30"
hour: "02"
weekday: "0-6"
job: "home/export/manageDiskSpace.sh > home/export/manageDiskSpace.sh.log 2>&1"
#user: "admin"
disabled: "no"
become... | 1,173 |
61,262,487 | Having an issue with Django Allauth. When I log out of one user, and log back in with another, I get this issue, both locally and in production.
I'm using the latest version of Allauth, Django 3.0.5, and Python 3.7.4.
It seems like this is an Allauth issue, but I haven't seen it reported online anywhere else. So just... | 2020/04/17 | [
"https://Stackoverflow.com/questions/61262487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636064/"
] | You need to have the segue from LiveController, not from Navigation Controller | This could be a few things so try these fixes:
1. Clean and build your project. Then, run again.
2. Quit Xcode, open up project and run.
3. In the `Attribute Inspector`, remove `openWelcomePage` and leave it blank.
Hope that either of these suggestions help. | 1,176 |
8,651,095 | How do you control how the order in which PyYaml outputs key/value pairs when serializing a Python dictionary?
I'm using Yaml as a simple serialization format in a Python script. My Yaml serialized objects represent a sort of "document", so for maximum user-friendliness, I'd like my object's "name" field to appear fir... | 2011/12/28 | [
"https://Stackoverflow.com/questions/8651095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247542/"
] | Took me a few hours of digging through PyYAML docs and tickets, but I eventually discovered [this comment](https://web.archive.org/web/20170308231702/http://pyyaml.org/ticket/29) that lays out some proof-of-concept code for serializing an OrderedDict as a normal YAML map (but maintaining the order).
e.g. applied to my... | The last time I checked, Python's dictionaries weren't ordered. If you really want them to be, I strongly recommend using a list of key/value pairs.
```
[
('key', 'value'),
('key2', 'value2')
]
```
Alternatively, define a list with the keys and put them in the right order.
```
keys = ['key1', 'name', 'price... | 1,177 |
52,528,911 | In the [docs](https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-gremlin-differences.html) under **Updating a Vertex Property**, it is mentioned that one can *"update a property value without adding an additional value to the set of values"*
by doing
`g.V('exampleid01').property(single, 'age', 25)`
... | 2018/09/27 | [
"https://Stackoverflow.com/questions/52528911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4007615/"
] | You need to be sure to import `single` which is seen [here in the code](https://github.com/apache/tinkerpop/blob/d1a3fa147d1f009ae57274827c9b59426dfc6e58/gremlin-python/src/main/jython/gremlin_python/process/traversal.py#L127) and can be imported with:
```
from gremlin_python.process.traversal import Cardinality
```
... | ```
from gremlin_python.process.traversal import Cardinality
g.V().hasLabel('placeholder-vertex').property(Cardinality.single,'maker','unknown').next()
```
This should also work. | 1,182 |
15,713,427 | I want to remove rows from several data frames so that they are all length n. When I tried to use a -for- loop, the changes would not persist through the rest of the script.
```
n = 50
groups = [df1, df2, df3]
for dataset in groups:
dataset = dataset[:n]
```
Redefining names individually (e.g., df1 = df1[:n] ),... | 2013/03/30 | [
"https://Stackoverflow.com/questions/15713427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560238/"
] | This is a slight python mis-understanding, rather than to do with pandas specific one. :)
You're re-assigning the variable used in the iteration and not changing it in the list:
```
In [1]: L = [1, 2, 3]
In [2]: for i in L:
i = i + 1
In [3]: L
Out[3]: [1, 2, 3]
```
You want to actually change the list... | Your code creates (and discards) a new variable `dataset` in the for-loop.
Try this:
```
n = 50
groups = [df1, df2, df3]
for dataset in groups:
dataset[:] = dataset[:n]
``` | 1,185 |
52,465,856 | ```
def frame_processing(frame):
out_frame = np.zeros((frame.shape[0],frame.shape[1],4),dtype = np.uint8)
b,g,r = cv2.split(frame)
alpha = np.zeros_like(b , dtype=np.uint8)
print(out_frame.shape)
print(b.shape);print(g.shape);print(r.shape);print(alpha.shape)
for i in range(frame.shape[0]):
for j in range(frame.sha... | 2018/09/23 | [
"https://Stackoverflow.com/questions/52465856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9811461/"
] | Use `cv2.inRange` to find the mask, then merge them with `np.dstack`:
```
#!/use/bin/python3
# 2018/09/24 11:51:31 (CST)
import cv2
import numpy as np
#frame = ...
mask = cv2.inRange(frame, (225,225,225), (255,255,255))
#dst = np.dstack((frame, 255-mask))
dst = np.dstack((frame, mask))
cv2.imwrite("dst.png", dst)
... | Its a simple typo. You are changing the variable "b" in the for loop and it conflicts with variable of blue channel. Change `b = (225,225,225)` to `threshold = (225, 255, 255)` and `zip(a,b)` to `zip(a, threshold)` should fix the problem.
By the way, you can use this to create your alpha channel:
```
alpha = np.ze... | 1,188 |
60,823,720 | I have a really long ordered dict that looks similar to this:
```
OrderedDict([('JIRAUSER16100', {'name': 'john.smith', 'fullname': 'John Smith', 'email': 'John.Smith@domain.test', 'active': True}), ('JIRAUSER16300', {'name': 'susan.jones', 'fullname': 'Susan Jones', 'email': 'Susan.Jones@domain.test', 'active': True}... | 2020/03/24 | [
"https://Stackoverflow.com/questions/60823720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11483315/"
] | Two ways you could potentially improve on this. You say your `OrderedDict` is really long, so I'd recommend the first option, since quickly become faster than the second as the size of your data grows.
1) **use [Pandas](https://pandas.pydata.org/)**:
```
In [1]: from collections import OrderedDict
In [2]: import pan... | If you are looking for a specific match you will have to iterate through your structure until you find it so you don't have to go through the entire dictionary.
Something like:
```
In [19]: d = OrderedDict([('JIRAUSER16100', {'name': 'john.smith', 'fullname': 'John Smith', 'email': 'John.Smith@domain.test',
...:... | 1,189 |
58,983,828 | I am using docplex in google collab with python
For the following LP, the some of the decision variables are predetermined, and the LP needs to be solved for that. It's a sequencing problem and the sequence is a set of given values. The other decision variables will be optimized based on this.
```
#Define the decisi... | 2019/11/21 | [
"https://Stackoverflow.com/questions/58983828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3916398/"
] | `join()` doesn't do anything to the child thread -- all it does is block until the child thread has exited. It only has an effect on the calling thread (i.e. by blocking its progress). The child thread can keep running for as long as it wants (although typically you'd prefer it to exit quickly, so that the thread calli... | >
> And to my surprise, joining these alive threads does not remove them from list of threads that top is giving. Is this expected behaviour?
>
>
>
That suggests the thread(s) are still running. Calling `join()` on a thread doesn't have any impact on that running thread; simply the calling thread
waits for the cal... | 1,190 |
54,440,762 | I'm busy configuring a TensorFlow Serving client that asks a TensorFlow Serving server to produce predictions on a given input image, for a given model.
If the model being requested has not yet been served, it is downloaded from a remote URL to a folder where the server's models are located. (The client does this). At... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54440762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/141789/"
] | So it took me ages of trawling through pull requests to finally find a code example for this. For the next person who has the same question as me, here is an example of how to do this. (You'll need the `tensorflow_serving package` for this; `pip install tensorflow-serving-api`).
Based on this pull request (which at th... | **Add a model** to TF Serving server and to the existing config file `conf_filepath`: Use arguments `name`, `base_path`, `model_platform` for the new model. Keeps the original models intact.
Notice a small difference from @Karl 's answer - using `MergeFrom` instead of `CopyFrom`
>
> pip install tensorflow-serving-ap... | 1,191 |
10,496,815 | I have written a job server that runs 1 or more jobs concurrently (or simultaneously depending on the number of CPUs on the system). A lot of the jobs created connect to a SQL Server database, perform a query, fetch the results and write the results to a CSV file. For these types of jobs I use `pyodbc` and Microsoft SQ... | 2012/05/08 | [
"https://Stackoverflow.com/questions/10496815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328695/"
] | I had a very similar problem and in my case the solution was to upgrade the ODBC driver on the machine I was trying to make the connection from. I'm afraid I don't know much about why that fixed the problem. I suspect something was changed or upgraded on the database server I was trying to connect to.
This answer migh... | I also encounter this problem recently. My config includes unixODBC-2.3.0 plus MS ODBC Driver 1.0 for Linux. After some experiments, we speculate that the problem may arise due to database upgrade (to SQLServer 2008 SP1 in our case), thus triggering some bugs in the MS ODBC driver. The problem also occurs in this threa... | 1,197 |
57,465,747 | I do the following operations:
1. Convert string datetime in pandas dataframe to python datetime via `apply(strptime)`
2. Convert `datetime` to posix timestamp via `.timestamp()` method
3. If I revert posix back to `datetime` with `.fromtimestamp()` I obtain different datetime
It differs by 3 hours which is my timezo... | 2019/08/12 | [
"https://Stackoverflow.com/questions/57465747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5331908/"
] | First, I suggest using the `np.timedelta64` dtype when working with `pandas`. In this case it makes the reciprocity simple.
```
pd.to_datetime('2018-03-03 14:30:00').value
#1520087400000000000
pd.to_datetime(pd.to_datetime('2018-03-03 14:30:00').value)
#Timestamp('2018-03-03 14:30:00')
```
The issue with the other ... | An answer with the [`to_datetime`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html) function:
```py
df = pd.DataFrame(['2018-03-03 14:30:00'], columns=['c'])
df['c'] = pd.to_datetime(df['c'].values, dayfirst=False).tz_localize('Your/Timezone')
```
When working with date, you should... | 1,199 |
17,219,675 | I am trying to use bash functions inside my python script to allow me to locate a specific directory and then grep a given file inside the directory. The catch is that I only have part of the directory name, so I need to use the bash function find to get the rest of the directory name (names are unique and will only ev... | 2013/06/20 | [
"https://Stackoverflow.com/questions/17219675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506070/"
] | The right way is checking the `Value` property of the item selected on the list control.
You could use `SelectedValue` property, try something like this:
```
if(radioButtonList.SelectedValue == "Option 2")
{
Messagebox.Show("Warning: Selecting this option may release deadly neurotoxins")
}
```
You also can check... | Try this one.I hope it helps.
```
if(radioButtonList.SelectedValue == "Option 2")
{
string script = "alert('Warning: Selecting this option may release deadly neurotoxins');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
}
``` | 1,200 |
39,175,648 | I am using `datetime` in some Python udfs that I use in my `pig` script. So far so good. I use pig 12.0 on Cloudera 5.5
However, I also need to use the `pytz` or `dateutil` packages as well and they dont seem to be part of a vanilla python install.
Can I use them in my `Pig` udfs in some ways? If so, how? I think `d... | 2016/08/26 | [
"https://Stackoverflow.com/questions/39175648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1609428/"
] | Well, as you probably know all Python UDF functions are not executed by Python interpreter, but Jython that is distributed with Pig. By default in 0.12.0 it should be [Jython 2.5.3](https://stackoverflow.com/questions/17711451/python-udf-version-with-jython-pig). Unfortunately `six` package supports Python starting fro... | From the answer to [a different but related question](https://stackoverflow.com/questions/7831649/how-do-i-make-hadoop-find-imported-python-modules-when-using-python-udfs-in-pig), it seems that you should be able to use resources as long as they are available on each of the nodes.
I think you can then add the path as ... | 1,202 |
21,998,545 | I have code like:
```
While 1:
A = input()
print A
```
How long can I expect this to run? How many times?
Is there a way I can just throw away whatever I have in A once I have printed it?
How does python deal with it? Will the program crash after a while?
Thank you. | 2014/02/24 | [
"https://Stackoverflow.com/questions/21998545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When you reassign `A` to a new value, there is nothing left referring to the old value. [Garbage collection](https://stackoverflow.com/questions/4484167/details-how-python-garbage-collection-works) comes into play here, and the old object is automatically returned back to free memory.
Thus you should never run out of ... | You change the value of A so memory wouldn't be an issue as python garbage collects the old value and returns the memory... so forever | 1,203 |
41,934,574 | I am new to C# programming, I migrated from python. I want to append two or more array (exact number is not known , depends on db entry) into a single array
like the list.append method in python does. Here the code example of what I want to do
```
int[] a = {1,2,3};
int[] b = {4,5,6};
int[] c = {7,8,9};
int[] d;
```... | 2017/01/30 | [
"https://Stackoverflow.com/questions/41934574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7268744/"
] | Well, if you want a simple **1D** array, try `SelectMany`:
```
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = { 7, 8, 9 };
// d == {1, 2, 3, 4, 5, 6, 7, 8, 9}
int[] d = new[] { a, b, c } // initial jagged array
.SelectMany(item => item) // flattened
.ToArray(); // materialized... | It seems from your code that `d` is not a single-dimensional array, but it seems to be a jagged array (and array of arrays). If so, you can write this:
```
int[][] d = new int[][] { a, b, c };
```
If you instead want to concatenate all arrays to a new `d`, you can use:
```
int[] d = a.Concat(b).Concat(c).ToArray();... | 1,206 |
11,477,643 | So I'm contemplating what language to use in the development of an app that uses OpenCV. As a part of my decision, I'm interested in knowing how easy/difficult it is to include the opencv library in the final app. I'd really like to write this in python because the opencv bindings are great, python's easy, etc.
But I ... | 2012/07/13 | [
"https://Stackoverflow.com/questions/11477643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132467/"
] | I've effectively packaged, deployed, and shipped a Python app using OpenCV with cxFreeze.
<http://cx-freeze.sourceforge.net/>
Yes, cxFreeze auto picked up the python extensions to OpenCV. I had to manually copy the OpenCV DLLs (Windows), but that was a minor issue that can be solved by a post-processing step in cxFr... | You can have a look at
<http://www.pyinstaller.org/>
It's great and it packages the necessary dll for opencv.
For opencv to work it py2exe also package numpy. Make sure you add a dependency for it in case you are using py2exe. | 1,209 |
13,053,429 | I'm new to python. I am trying to create a script that gives me a different response when the same data is inputted more than once. The code goes like this :
```
def loop() :
Repeat = 0
response = raw_input("enter something : ")
if response == "hi"
Repeat += 1
print "hello"
loop()
... | 2012/10/24 | [
"https://Stackoverflow.com/questions/13053429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1636006/"
] | I would use a `dict` to store words/count. You can then inquire if the word is in the dictionary and update count ...
```
words = {}
while True:
word = raw_input("Say something:")
if word in words:
words[word] += 1
print "you already said ",words[word]
continue
else:
words[word]... | Your statement above is recursively calling itself. The new instance of loop does not have access to the calling value of Repeat and instead has its own local copy of Repeat. Also, you have if `Repeat > 2`. As written this means that it won't get your other print statement until they input "hello" three times to get th... | 1,210 |
34,543,513 | I'm looking for maximum absolute value out of chunked list.
For example, the list is:
```
[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
```
I want to find the maximum with lookahead = 4. For this case, it will return me:
```
[5, 7, 9, 8]
```
How can I do simply in Python?
```
for d in data[::4]:
if coun... | 2015/12/31 | [
"https://Stackoverflow.com/questions/34543513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517403/"
] | Using standard Python:
```
[max(abs(x) for x in arr[i:i+4]) for i in range(0, len(arr), 4)]
```
This works also if the array cannot be evenly divided. | Map the `list` to `abs()`, then [chunk the `list`](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) and send it to `max()`:
```
array = [1,2,4,5,4,5,6,7,2,6,-9,6,4,2,7,8]
array = [abs(item) for item in array]
# use linked question's answer to chunk
# array = [[1,2,... | 1,212 |
57,673,070 | I am logging into gmail via python and deleting emails. However when I do a search for two emails I get no results to delete.
```
mail.select('Inbox')
result,data = mail.uid('search',None '(FROM target.com)')
```
The above works and will find and delete any email that had target.com in the from address. However wh... | 2019/08/27 | [
"https://Stackoverflow.com/questions/57673070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11951910/"
] | First of all I can confirm this behaviour for JavaFX 13 ea build 13. This was probably a very simplistic attempt to fix an old bug which the OP has already mentioned (image turning pink) which I reported a long time ago. The problem is that JPEGS cannot store alpha information and in the past the output was just garble... | Additionally to the answer of mipa and in the case that you do not have SwingFXUtils available, you could clone the BufferedImage into another BufferedImage without alpha channel:
```
BufferedImage withoutAlpha = new BufferedImage(
(int) originalWithAlpha.getWidth(),
(int) originalWithAlpha.getHeight(),
B... | 1,217 |
52,753,613 | I have a dataframe say `df`. `df` has a column `'Ages'`
`>>> df['Age']`
[](https://i.stack.imgur.com/pcs2l.png)
I want to group this ages and create a new column something like this
```
If age >= 0 & age < 2 then AgeGroup = Infant
If age >= 2 & age < 4 then AgeGroup =... | 2018/10/11 | [
"https://Stackoverflow.com/questions/52753613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005417/"
] | Use [`pandas.cut`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html) with parameter `right=False` for not includes the rightmost edge of bins:
```
X_train_data = pd.DataFrame({'Age':[0,2,4,13,35,-1,54]})
bins= [0,2,4,13,20,110]
labels = ['Infant','Toddler','Kid','Teen','Adult']
X_train_data['AgeG... | Just use:
```
X_train_data.loc[(X_train_data.Age < 13), 'AgeGroup'] = 'Kid'
``` | 1,218 |
65,513,452 | I am trying to display results in a table format (with borders) in a cgi script written in python.
How to display table boarders within python code.
```
check_list = elements.getvalue('check_list[]')
mydata=db.get_data(check_list)
print("_____________________________________")
print("<table><th>",check_list[0],"</t... | 2020/12/30 | [
"https://Stackoverflow.com/questions/65513452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12888614/"
] | Digging through issues on vercel's github I found this alternative that doesn't use next-i18next or any other nextjs magic:
<https://github.com/Xairoo/nextjs-i18n-static-page-starter>
It's just basic i18n using i18next that bundles all locale together with JS, so there are obvious tradeoffs but at least it works with... | You can't use `export` with next.js i18n implementation.
>
> Note that Internationalized Routing does not integrate with next export as next export does not leverage the Next.js routing layer. Hybrid Next.js applications that do not use next export are fully supported.
>
>
>
[Next.js docs](https://nextjs.org/docs... | 1,219 |
73,679,017 | I'm very new to python, so as one of the first projects I decided to a simple log-in menu, however, it gives me a mistake shown at the bottom.
The link to the tutorial I used:
>
> <https://www.youtube.com/watch?v=dR_cDapPWyY&ab_channel=techWithId>
>
>
>
This is the code to the log-in menu:
```
def welcome():
... | 2022/09/11 | [
"https://Stackoverflow.com/questions/73679017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19810120/"
] | You can find the center of each region like this:
```py
markers = cv2.watershed(img, markers)
labels = np.unique(markers)
for label in labels:
y, x = np.nonzero(markers == label)
cx = int(np.mean(x))
cy = int(np.mean(y))
```
The result:
[, no pixel at all will remain. You have two options
* use a pixel from the "ultimate eroded";
* use some location near the region and a leader line (but avoiding... | 1,224 |
54,768,539 | While I iterate within a for loop I continually receive the same warning, which I want to suppress. The warning reads:
`C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not ... | 2019/02/19 | [
"https://Stackoverflow.com/questions/54768539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973400/"
] | Try this at the beginning of the script to ignore specific warnings:
```
import warnings
warnings.filterwarnings("ignore", message="Numerical issues were encountered ")
``` | The python contextlib has a contextmamager for this: [suppress](https://docs.python.org/3/library/contextlib.html#contextlib.suppress)
```
from contextlib import suppress
with suppress(UserWarning):
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val... | 1,225 |
60,094,997 | Given a triangular matrix `m` in python how best to extract from it the value at row `i` column `j`?
```
m = [1,np.nan,np.nan,2,3,np.nan,4,5,6]
m = pd.DataFrame(np.array(x).reshape((3,3)))
```
Which looks like:
```
0 1 2
0 1.0 NaN NaN
1 2.0 3.0 NaN
2 4.0 5.0 6.0
```
I can get lower elements easily `... | 2020/02/06 | [
"https://Stackoverflow.com/questions/60094997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6948859/"
] | Use `pandas.DataFrame.fillna` with transpose:
```
m = m.fillna(m.T)
print(m)
```
Output:
```
0 1 2
0 1.0 2.0 4.0
1 2.0 3.0 5.0
2 4.0 5.0 6.0
m.loc[0,2] == m.loc[2,0] == 4
# True
```
---
In case there are column names (like `A`,`B`,`C`):
```
m.where(m.notna(), m.T.values)
```
Output:
```
... | The easiest way I have found to solve this is to make the matrix symmetrical, I learnt how from [this](https://stackoverflow.com/a/2573982/6948859) answer.
There are a couple of steps:
1. Convert nan to 0
```
m0 = np.nan_to_num(m)
```
2. Add the transpose of the matrix to itself
```
m = m0 + m0.T
```
3. Subtrac... | 1,230 |
48,924,491 | Working in python 3.
So I have a dictionary like this;
`{"stripes": [1,0,5,3], "legs": [4,4,2,3], "colour": ['red', 'grey', 'blue', 'green']}`
I know all the lists in the dictionary have the same length, but the may not contain the same type of element. Some of them may even be lists of lists.
I want to return a dic... | 2018/02/22 | [
"https://Stackoverflow.com/questions/48924491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7690011/"
] | The answer to your question would be in this particular case to NOT use LINQ. My advice is to avoid abusing LINQ methods like `.ToList(), .ToArray()` etc, since it has a huge impact on performance. You iterate through the collection and creating a new collection. Very often simple `foreach` much more readable and under... | Linq is usually used to query and transform some data.
In case you can change how `persons` are created, this will be the best approach:
```
Person[] persons = nums.Select(n => new Person { Age = n }).ToArray();
```
If you already have the list of persons, go with the `foreach` loop. LinQ should be only used for qu... | 1,231 |
14,631,708 | I need to set up a private PyPI repository. I've realized there are a lot of them to choose from, and after surfing around, I chose [djangopypi2](http://djangopypi2.readthedocs.org/) since I found their installation instructions the clearest and the project is active.
I have never used Django before, so the question m... | 2013/01/31 | [
"https://Stackoverflow.com/questions/14631708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1919913/"
] | You could declare, *and implement*, a pure virtual destructor:
```
class ShapeF
{
public:
virtual ~ShapeF() = 0;
...
};
ShapeF::~ShapeF() {}
```
It's a tiny step from what you already have, and will prevent `ShapeF` from being instantiated directly. The derived classes won't need to change. | Try using a protected constructor | 1,234 |
74,242,407 | I have a code that looks like:
```
#!/usr/bin/env python
'''Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
'''
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
parser = argparse.ArgumentParser()
# parser.add_argument('--dos', help='Plot the dos', required=... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005559/"
] | Use `window` property `localStorage` to save the `theme` value across browser sessions.
Try the following code:
```
const theme = localStorage.getItem('theme')
if (!theme) localStorage.setItem('theme', 'light') // set the theme; by default 'light'
document.body.classList.add(theme)
``` | here is a way you could do it: Cookies.
```
function toggleDarkMode() {
let darkTheme= document.body;
darkTheme.classList.toggle("darkMode");
document.cookie = "theme=dark";
}
```
```
function toggleLightMode() {
let lightTheme= document.body;
lightTheme.classList.toggle("lightMode");
documen... | 1,237 |
38,571,667 | I'm trying to use Python to download an Excel file to my local drive from Box.
Using the boxsdk I was able to authenticate via OAuth2 and successfully get the file id on Box.
However when I use the `client.file(file_id).content()` function, it just returns a string, and if I use `client.file(file_id).get()` then it j... | 2016/07/25 | [
"https://Stackoverflow.com/questions/38571667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6635737/"
] | It is correct that the documentation and source for `download_to` can be found [here](http://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html?highlight=download_to#boxsdk.object.file.File.download_to) and [here](http://box-python-sdk.readthedocs.io/en/latest/_modules/boxsdk/object/file.html#File.download_to).... | You could use python [csv library](https://docs.python.org/2/library/csv.html), along with dialect='excel' flag. It works really nice for exporting data to Microsoft Excel.
The main idea is to use csv.writer inside a loop for writing each line. Try this and if you can't, post the code here. | 1,238 |
53,077,341 | I am trying to find the proper python syntax to create a flag with a value of `yes` if `columnx` contains any of the following numbers: **`1, 2, 3, 4, 5`**.
```
def create_flag(df):
if df['columnx'] in (1,2,3,4,5):
return df['flag']=='yes'
```
I get the following error.
>
> TypeError: invalid type com... | 2018/10/31 | [
"https://Stackoverflow.com/questions/53077341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6365890/"
] | Use `np.where` with pandas `isin` as:
```
df['flag'] = np.where(df['columnx'].isin([1,2,3,4,5]),'yes','no')
``` | You have lot of problems in your code! i assume you want to try something like this
```
def create_flag(df):
if df['columnx'] in [1,2,3,4,5]:
df['flag']='yes'
x = {"columnx":2,'flag':None}
create_flag(x)
print(x["flag"])
``` | 1,240 |
25,299,625 | I have implemented a REST Api (<http://www.django-rest-framework.org/>) as follows:
```
@csrf_exempt
@api_view(['PUT'])
def updateinfo(request, id, format=None):
try:
user = User.objects.get(id=id)
except User.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
if request.m... | 2014/08/14 | [
"https://Stackoverflow.com/questions/25299625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3324751/"
] | You are missing the django-rest framework parser decorator, in your case, you need use `@parser_classes((FormParser,))` to populate request.DATA dict. [Read more here](http://www.django-rest-framework.org/api-guide/parsers)
try with that:
```
from rest_framework.parsers import FormParser
@parser_classes((FormParser,... | Try doing everything using JSON.
1. Add JSONParser, like [levi](https://stackoverflow.com/users/1539655/levi) explained
2. Add custom headers to your request, like in [this example](http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers)
So for you, maybe something like:
```
>>> payload = {'id':id... | 1,241 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.