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 |
|---|---|---|---|---|---|---|
57,643,746 | I have a pipeline with a set of PTransforms and my method is getting very long.
I'd like to write my DoFns and my composite transforms in a separate package and use them back in my main method. With python it's pretty straightforward, how can I achieve that with Scio? I don't see any example of doing that. :(
```
... | 2019/08/25 | [
"https://Stackoverflow.com/questions/57643746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9726037/"
] | You can try to use the encoding option "Latin-1" standard (also known as ISO 8859-1 or ISO/IEC 8859-1).
```
library(data.table)
type <- fread(file.path("C:/Users/Alonso/Desktop/Tesis_MGII/Avance_mayo/escrito/natural-disasters-by-type.csv", encoding = "Latin-1"))
``` | Use the encoding option inside your read.csv code.
Following code sample is working for me:
```
file <- textConnection("# ---------------------
#
# ---------------------
Año, Número
2001, 3152
2002, 3200
2003, 3500
2004, 3700
2005, 3850
2006, 4200", encoding = c("UTF-8"))
file
# read data from textConnection
desas... | 7,947 |
61,996,944 | I'm completely new to the Python world, so I've been struggling with this issue for a couple days now. I thank you guys in advance.
I have been trying to separate a single Row and column text in three diferente ones. To explain myself better, here's where I am.
So this is my pandas dataframe from a csv:
In[2]:
```
... | 2020/05/25 | [
"https://Stackoverflow.com/questions/61996944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611327/"
] | You can use `assign` with `str.split` like below. But format of text should be fixed.
```
df.assign(number = df.institution.str.split().str[0], \
unit_id = df.institution.str.split().str[-1])
```
Output:
```
institution number unit_id
0 1.1.2. Consejo Nacio... | Just a thought, but what about using named capture groups in a regular expression. For example, use the following after you imported your CSV-file:
```
df.iloc[:,0].str.extract(r'^(?P<number>[\d.]*)\s+(?P<instituion>.*)\s+\((?P<unit_id>[A-Z\d]*)\)$')
```
This would expand your dataframe as such:
```
number ... | 7,949 |
36,002,647 | Given an iterator `i`, I want an iterator that yields each element `n` times, i.e., the equivalent of this function
```
def duplicate(i, n):
for x in i:
for k in range(n):
yield x
```
Is there an one-liner for this?
Related question: [duplicate each member in a list - python](https://stackov... | 2016/03/15 | [
"https://Stackoverflow.com/questions/36002647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2201385/"
] | ```
itertools.chain.from_iterable(itertools.izip(*itertools.tee(source, n)))
```
Example:
```
>>> x = (a**2 for a in xrange(5))
>>> list(itertools.chain.from_iterable(itertools.izip(*itertools.tee(x, 3))))
[0, 0, 0, 1, 1, 1, 4, 4, 4, 9, 9, 9, 16, 16, 16]
```
Another way:
```
itertools.chain.from_iterable(itertool... | Use a generator expression:
```
>>> x = (n for n in range(4))
>>> i = (v for v in x for _ in range(3))
>>> list(i)
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]
``` | 7,951 |
4,081,230 | **Update 2010-11-02 7p:** Shortened description; posted initial bash solution.
---
**Description**
I'd like to create a semantic file structure to better organize my data. I don't want to go a route like recoll, strigi, or beagle; I want no gui and full control. The closest might be oyepa or even closer, [Tagsistant... | 2010/11/02 | [
"https://Stackoverflow.com/questions/4081230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/495152/"
] | >
> A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
>
>
>
Obviously a pr... | >
> A priviledged cleint can invoke the private constructor reflectively with
> the aid of the
> AccessibleObject.setAccessible method,
> If you need to defend this, modify the
> constructor. My question is: How
> exactly can a private constructor is
> invoked? and what is
> AccessibleObject.setAccessible??
>
... | 7,954 |
8,342,891 | I'm very new to Python and have a question. Currently I'm using this to calculate the times between a message goes out and the message comes in. The resulting starting time, time delta, and the Unique ID are then presented in file. As well, I'm using Python 2.7.2
Currently it is subtracting the two times and the resul... | 2011/12/01 | [
"https://Stackoverflow.com/questions/8342891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057243/"
] | If `float(out_ts)` are hours, then `'{0:.3f}'.format(float(out_ts) * 3600.)` will give you the text representation of seconds with three digits after decimal point. | >
> How can I force it to always display the exact number.
>
>
>
This is sometimes not possible, because of floating point inaccuracies
What you *can* do on the other hand is to format your floats as you wish. See [here](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for instructions.
... | 7,963 |
2,036,260 | >
> **Possible Duplicate:**
>
> [Django Unhandled Exception](https://stackoverflow.com/questions/1925898/django-unhandled-exception)
>
>
>
I'm randomly getting 500 server errors and trying to diagnose the problem. The setup is:
Apache + mod\_python + Django
My 500.html page is being served by Django, but I h... | 2010/01/10 | [
"https://Stackoverflow.com/questions/2036260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87719/"
] | Yes, you should have an entry in your apache confs as to where the error log is for the virtual server.
For instance the name of my virtual server is djangoserver, and in my /etc/apache2/sites-enabled/djangoserver file is the line
```
ErrorLog /var/log/apache2/djangoserver-errors.log
```
Although now that I reread y... | Salsa makes several good suggestions. I would add that the Django development server is an excellent environment for tracking these things down. Sometimes I even run it from the production directory (gasp!) with `./manage.py runserver 0.0.0.0:8000` so I *know* I'm running the same code.
Admittedly sometimes something ... | 7,964 |
58,550,284 | After an automatic update of [macOS v10.15](https://en.wikipedia.org/wiki/MacOS_Catalina) (Catalina), I am unable to open Xcode. Xcode prompts me to install additional components but the installation fails because of MobileDevice.pkg (Applications/Xcode.app/Contents/Resources/Packages)
I have found multiple answers on... | 2019/10/24 | [
"https://Stackoverflow.com/questions/58550284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11216994/"
] | I had a similar problem, where I installed Xcode 11.1, and installed the components and everything within the same folder where I had Xcode 10.2.1. Then, I tried to go back to Xcode 10.2.1 and couldn't opened as it was asking me to install components again, and when I tried I was getting this error.
>
> The package “... | You may solve this issue by setting the date of your Mac as October 1st, 2019. But this is just a hack! The real solution (suggested by apple) is this:
All you have to is to upgrade Xcode
-----------------------------------
**But** there is a [known Issues on apple developers site](https://developer.apple.com/documen... | 7,965 |
30,668,557 | I have a problem loading an external dll using Python through Python for .NET. I have tried different methodologis following stackoverflow and similar. I will try to summarize the situation and to describe all the steps that I've done.
I have a dll named for e.g. Test.NET.dll. I checked with dotPeek and I can see, cli... | 2015/06/05 | [
"https://Stackoverflow.com/questions/30668557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3075816/"
] | >
> The return value of this decorator is ignored.
>
>
>
This is irrelevant to your situation. The return value of parameter decorators is ignored because they don't need to be able to replace anything (unlike method and class decorators which can replace the descriptor).
>
> My problem is that when I try to imp... | For my case I used a simple solution **without reflect metadata** API but **using method decoration**.
You can modify it for your purposes:
```
type THandler = (param: any, paramIndex: number, params: any[]) => void;
/**
* @example
* @Params((param1) => someHandlerFn(param1), ...otherParams)
* public async someMe... | 7,975 |
49,369,438 | I'm trying to create a blobstore entry from an image data-uri object, but am getting stuck.
Basically, I'm posting via ajax the data-uri as text, an example of the payload:
```
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPA...
```
I'm trying to receive this payload with the following handler. I'm assuming I need... | 2018/03/19 | [
"https://Stackoverflow.com/questions/49369438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791793/"
] | There are a couple of ways to view your question and the sample code you posted, and it's a little confusing what you need because you are mixing strategies and technologies.
**POST base64 to `_ah/upload/...`**
Your service uses `create_upload_url()` to make a one-time upload URL/session for your client. Your client ... | An image object (<https://cloud.google.com/appengine/docs/standard/python/refdocs/google.appengine.api.images>) isn't a Datastore entity, so it has no key. You need to actually save the image to blobstore[2] or Google Cloud Storage[1] then get a serving url for your image.
[1] <https://cloud.google.com/appengine/docs/... | 7,976 |
59,156,316 | I have a python code like this to interact with an API
```
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import json
from pprint import pprint
key = "[SOME_KEY]" # FROM API PROVIDER
secret = "[SOME_SECRET]" # FROM API PROVIDER
api_client = BackendApplica... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59156316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11719873/"
] | Have you tried to you send a header paramter with this requests?
```py
headers = {"Content-Type": "application/json"}
response = client.post(url, data=json.dumps(body), headers=headers)
``` | This is how I was able to configure the POST request for exchanging the code for a token.
```py
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient
from requests.auth import HTTPBasicAuth
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
authorizati... | 7,977 |
31,932,371 | I have both Python 2.7 and Python 3.4 installed on my MacBook, as both are needed sometimes.
Python 2.7 is shipped by Apple itself.
Python 3.4 is installed by Mac OS X 64-bit/32-bit installer in the link
<https://www.python.org/downloads/release/python-343/>
Here is how I installed Meld on Mac OS X 10.10:
1. Instal... | 2015/08/11 | [
"https://Stackoverflow.com/questions/31932371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778233/"
] | This should solve the problem: `brew link --overwrite python` | I use Linux. I have no clue about Apple and the special things they do. But judging from the error messages given it seems that
1. bash starts *the meld program*
2. *the meld program* refers to *the python program in **someplace***
3. **someplace** is wrong in *the meld program*, causing the bash error message
Now h... | 7,978 |
8,380,733 | I'm trying to run a custom django command as a scheduled task on Heroku. I am able to execute the custom command locally via: `python manage.py send_daily_email`. (note: I do NOT have any problems with the custom management command itself)
However, Heroku is giving me the following exception when trying to "Run" the ... | 2011/12/05 | [
"https://Stackoverflow.com/questions/8380733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/873197/"
] | You are probably using a different interpreter.
Check to make sure shell python is the same as the one you reference in your script /usr/bin/python . It could be that there is a different one in your path, which would explain why it works when you run `python manage.py` but not your shell scrip which you explicitly r... | In addition, this can also be resolved by adding your home directory to your Python path. A quick and unobtrusive way to accomplish that is to add it to the PYTHONPATH environment variable (which is generally /app on the Heroku Cedar stack).
Add it via the heroku config command:
```
$ heroku config:add PYTHONPATH=/ap... | 7,980 |
5,077,765 | I am using Google App Engine's datastore and wants to retrieve an entity whose key value is written as
```
ID/Name
id=1
```
Can anyone suggest me a GQL query to view that entity in datastore admin console and also in my python program? | 2011/02/22 | [
"https://Stackoverflow.com/questions/5077765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/617462/"
] | From your application use the [get\_by\_id()](http://code.google.com/intl/it/appengine/docs/python/datastore/modelclass.html#Model_get_by_id) class method of the Model:
```
entity = YourModel.get_by_id(1)
```
From Datastore viewer you should use the `KEY` function:
```
SELECT * FROM YourModel WHERE __key__ = KEY('Y... | An application can retrieve a model instance for a given Key using the [get()](http://code.google.com/appengine/docs/python/datastore/functions.html#get) function.
```
class member(db.Model):
firstName=db.StringProperty(verbose_name='First Name',required=False)
lastName=db.StringProperty(verbose_name='Last Nam... | 7,981 |
8,062,564 | I try to apply image filters using python's [PIL](http://www.pythonware.com/products/pil/). The code is straight forward:
```
im = Image.open(fnImage)
im = im.filter(ImageFilter.BLUR)
```
This code works as expected on PNGs, JPGs and on 8-bit TIFs. However, when I try to apply this code on 16-bit TIFs, I get the fol... | 2011/11/09 | [
"https://Stackoverflow.com/questions/8062564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17523/"
] | Your TIFF image's mode is most likely a "I;16".
In the current version of ImageFilter, kernels can only be applied to
"L" and "RGB" images (see source of ImageFilter.py)
Try converting first to another mode:
```
im.convert('L')
```
If it fails, try:
```
im.mode = 'I'
im = im.point(lambda i:i*(1./256)).convert('L'... | To move ahead, try using [ImageMagick](http://www.imagemagick.org/script/index.php), look for PythonMagick hooks to the program. On the command prompt, you can use `convert.exe image-16.tiff -blur 2x2 output.tiff`. Didn't manage to install PythonMagick in my windows OS as the source needs compiling. | 7,982 |
13,103,806 | So I have been working on a two player "guess the number" program.
But im just having trouble with one thing.
So here's code:
```
import time
import random
thenumber = random.randint(1, 10)
print "Welcome to Noah's Two Player guess a number game."
print "What is player one's name?"
player1 = raw_input()
print "What i... | 2012/10/27 | [
"https://Stackoverflow.com/questions/13103806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779877/"
] | I guess you need quotes around `yes` : `choice =='yes'` , otherwise python will think that `yes` is a variable. | try `if choice == 'yes':`. You're comparing it with a symbol that isn't defined.
Note there are no 'variables' in Python, only symbols and their values(with their types internally understood by the language interpreter). Think of them as names you give to various objects. They're all symbols. | 7,983 |
73,697,975 | I am working on a Django application where I have used twilio to send sms and whatsapp messages and the sendgrid api for sending the emails. The problem occurs in scheduled messages in all three. For example, if I have schedule an email to be sent at 06:24 PM(scheduled time is 06:24 PM), then I am receiving the email a... | 2022/09/13 | [
"https://Stackoverflow.com/questions/73697975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19663784/"
] | If need replace missing value in `country` column by last value after split `city` by `,` use:
```
df['country'] = df['country'].fillna(df['city'].str.split(',').str[-1])
```
Or if need assign all column in `country` column:
```
df['country'] = df['city'].str.split(',').str[-1]
``` | You can use [`str.extract`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extract.html) with a word regex `\w+` anchored to the end of the string (`$`) to get the last word:
```
# replacing all values
df['country'] = df['city'].str.extract('(\w+)$', expand=False)
# only updating NaNs
df.loc[df['count... | 7,984 |
71,431,272 | I'm having a problem with calling my TextInputs from one class in another. I have a special class inheriting from TextInput, which makes moving with arrows possible, in my MainScreen I want to grab the letters from TextInputs and later on do something with them, however I need to pass them into this class first. I don'... | 2022/03/10 | [
"https://Stackoverflow.com/questions/71431272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15846202/"
] | I finally figured this one out. I ended up using a callback in the onchange attribute that set the value of the current property in the loop.
```
<div class="form-section">
@foreach (var property in DataModel.GetType().GetProperties())
{
var propertyString = $"DataModel.{property.Name.ToString()}";
@if (p... | I think what @nocturns2 said is correct, you could try this code:
```
@if (property.PropertyType == typeof(DateTime))
{
DateTime.TryParse(YourPropertyString, out var parsedValue);
var resutl= (YourType)(object)parsedValue
<InputDate id=@"property.Name" @bind-Value="@resutl">
}
``` | 7,985 |
22,727,782 | I'd previously used Anaconda to handle python, but I'm and start working with virtual environments.
I set up virtualenv and virtualenvwrapper, and have been trying to add modules, specifically scrapy and lxml, for a project I want to try.
Each time I pip install, I hit an error.
For scrapy:
```
File "/home/philip/E... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22727782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3115915/"
] | I had the same problem in Ubuntu 14.04. I've solved it with the instructions of the page linked by @jdigital and the openssl-dev library pointed by @user3115915. Just to help others:
```
sudo apt-get install libxslt1-dev libxslt1.1 libxml2-dev libxml2 libssl-dev
sudo pip install scrapy
``` | In my case, I solve the problem installing all the libraries that Manuel mention plus the extra library: libffi-dev
<https://askubuntu.com/questions/499714/error-installing-scrapy-in-virtualenv-using-pip> | 7,987 |
65,093,883 | I often debug my python code by plotting NumPy arrays in the vscode debugger.
Often I spend more than 3s looking at a plot. When I do vscode prints the extremely
long warning below. It's very annoying because I then have to scroll up a lot
all the time to see previous debugging outputs. Where is this PYDEVD\_WARN\_EVAL... | 2020/12/01 | [
"https://Stackoverflow.com/questions/65093883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8726027/"
] | If found a way to adapt the launch.json which takes care of this problem.
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"env": {"DISPLAY":":1",
... | If you are keen to surpress the warning, you'd go like this:
In this documentation, point 28.6.3, you can do so:
<https://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings>
Here's the code if the link dies in the future.
```
import warnings
def fxn():
warnings.warn("deprecated", Deprecati... | 7,990 |
48,729,915 | I am trying to read a `png` image in python. The `imread` function in `scipy` is being [deprecated](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.imread.html#scipy.ndimage.imread) and they recommend using `imageio` library.
However, I am would rather restrict my usage of external libraries to `sci... | 2018/02/11 | [
"https://Stackoverflow.com/questions/48729915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5495304/"
] | With matplotlib you can use (as shown in the matplotlib [documentation](https://matplotlib.org/2.0.0/users/image_tutorial.html))
```
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('image_name.png')
```
And plot the image if you want
```
imgplot = plt.imshow(img)
``` | From [documentation](https://matplotlib.org/3.1.1/api/image_api.html?highlight=matplotlib%20image#module-matplotlib.image.imread):
>
> Matplotlib can only read PNGs natively. Further image formats are supported via the optional dependency on Pillow.
>
>
>
So in case of `PNG` we may use `plt.imread()`. In other c... | 7,992 |
34,086,675 | I would like to slice an array `a` in Julia in a loop in such a way that it's divided in chunks of `n` samples. The length of the array `nsamples` is *not* a multiple of `n`, so the last stride would be shorter.
My attempt would be using a ternary operator to check if the size of the stride is greater than the length... | 2015/12/04 | [
"https://Stackoverflow.com/questions/34086675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277113/"
] | The `end` keyword is only given this kind of special treatment inside of indexing expressions, where it evaluates to the last index of the dimension being indexed. You could put it inside with e.g.
```
for i in 0:n:nsamples-1
window = a[i+1:min(i+n, end)]
end
```
Or you could just use `length(a)` (or `nsamples`,... | Ugly way:
```
a=rand(7);
nsamples=7;
n=3;
for i in 0:n:nsamples-1
end_ = i+n < nsamples ? i+n : :end
window = @eval a[$i+1:$end_]
println(window)
end
```
Better solution:
```
for i in 0:n:nsamples-1
window = i+n < nsamples ? a[i+1:i+n] : a[i+1:end]
println(window)
end
``` | 8,002 |
43,721,155 | I'm trying to close each image opened via iteration, within each iteration.
I've referred to this thread below, but the correct answer is not producing the results.
[How do I close an image opened in Pillow?](https://stackoverflow.com/questions/31751464/how-do-i-close-an-image-opened-in-pillow)
My code
```
for i ... | 2017/05/01 | [
"https://Stackoverflow.com/questions/43721155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6802252/"
] | Got it working, but I installed a different image viewer on Windows as I couldn't find the .exe of the default viewer.
```
import webbrowser
import subprocess
import os, time
for i in Final_Bioteck[6:11]:
webbrowser.open( '{}.png'.format(i)) # opens the pic
time.sleep(3)
subprocess.run(['task... | In Windows 10, the process is dllhost.exe
using the same script as Moondra, except with "dllhost.exe" instead of "i\_view64.exe"
```
import webbrowser
import subprocess
import os, time
for i in Final_Bioteck[6:11]:
webbrowser.open( '{}.png'.format(i)) # opens the pic
time.sleep(3)
subprocess.run(['taskki... | 8,005 |
32,004,317 | I am working on a python GUI for serial communication with some hardware.I am using USB-RS232 converter for that.I do'nt want user to look for com port of hardware in device manager and then select port no in GUI for communication.How can my python code automatically get the port no. for that particular USB port?I can ... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32004317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5036147/"
] | pyserial can list the ports with their USB VID:PID numbers.
```
from serial.tools import list_ports
list_ports.comports()
```
This function returns a tuple, 3rd item is a string that may contain the USB VID:PID number. You can parse it from there. Or better, you can use the `grep` function also provided by `list_por... | I assume that you are specifically looking for a COM port that is described as being a USB to RS232 in the device manager, rather than wanting to list all available COM ports?
Also, you have not mentioned what OS you are developing on, or the version of Python you are using, but this works for me on a Windows system u... | 8,006 |
14,004,839 | I have Flask, Babel and Flask-Babel installed in the global packages.
When running python and I type this, no error
```
>>> from flaskext.babel import Babel
>>>
```
With a virtual environment, starting python and typing the same command I see
```
>>> from flaskext.babel import Babel
Traceback (most recent call las... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14004839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75517/"
] | I think you're supposed to import Flask extensions like the following from version 0.8 onwards:
```
from flask.ext.babel import Babel
```
I tried the old way (`import flaskext.babel`), and it didn't work for me either. | The old way of importing Flask extension was like:
```
import flaskext.babel
```
[Namespace packages](https://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) were, however, "too painful for everybody involved", so now Flask extensions should be importable like:
```
import flask_ba... | 8,007 |
46,515,990 | Can somebody please help me to create a python program whereby the unsorted list is split up into groups of 2, arranged alphabetically within their groups of two. The program should then create a new list in alphabetical order by taking the next greatest letter from the correct pair. Please don't tell me to do this in ... | 2017/10/01 | [
"https://Stackoverflow.com/questions/46515990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8705227/"
] | In your code, openin tag `<tr>` is not added to first `<td>`. You are appending html twice. You need to form correct html then add it to the table after for loop. Also you don't need ';' commas at the end of condition and standart function definition code blocks.
```js
function myFunction() {
var response = "[\r\n ... | Thought I would offer a different solution.
<https://jsfiddle.net/wfc9p0e8/>
```
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<style>
#table{ display: table; width:100%; }
#table .table-cell { display: inline-table; width:33.33%; }
<... | 8,013 |
38,145,706 | I'm using PyInstaller 3.2 to package a Web.py app. Typically, with Web.py and the built-in WSGI [server](http://webpy.org/cookbook/ssl), you specify the port on the command line, like
```
$ python main.py 8091
```
Would run the Web.py app on port 8091 (default is 8080). I'm bundling the app with PyInstaller via a sp... | 2016/07/01 | [
"https://Stackoverflow.com/questions/38145706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370384/"
] | So very hacky, but what I wound up doing was to just append an argument in `sys.argv` in my web.py app...
```
sys.argv.append('8888')
app.run()
```
I also thought in my `spec` file I could just do:
```
a = Analysis(['main.py 8888'],
```
But that didn't work at all. | `options` argument in EXE is only for the python interpreter ([ref](https://pythonhosted.org/PyInstaller/spec-files.html#giving-run-time-python-options)) | 8,014 |
65,919,766 | I am using python 3.8.3 version.
I installed folium typing `pip install folium` in the command line. After typing `pip show folium` in the command line, the output is as follows:
```
Name: folium
Version: 0.12.1
Summary: Make beautiful maps with Leaflet.js & Python
Home-page: https://github.com/python-visualization/fo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65919766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127138/"
] | Avoiding this kind of errors, always use virtualenv.
Take a look here
<https://docs.python.org/3/library/venv.html> | Try restarting VSCode, sometimes the python extension needs a restart so newly installed modules are indexed.
You can try running the code despite the Error in VSCode. It works if you can confirm that the required module is properly installed. | 8,015 |
62,339,871 | **The question is this:**
We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary day and we add it to the shortest month of the year, February.
In the Gregorian calendar three criteria must be taken into account to identify leap years:
The year can be evenly divided by 4, ... | 2020/06/12 | [
"https://Stackoverflow.com/questions/62339871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13732680/"
] | First of all, you are using bitwise operators **|** and **&** (you can read about it here - <https://www.educative.io/edpresso/what-are-bitwise-operators-in-python>), but you need to use logical operators, such as **or** and **and**.
Also, your code can be simplified:
```
def is_leap(year):
return (year % 4 == 0)... | try this:
```
def leap_year(n):
if (n%100==0 and n%400==0):
return True
elif (n%4==0 and n%100!=0):
return True
else:
return False
``` | 8,020 |
42,742,499 | PEP [3141](https://www.python.org/dev/peps/pep-3141/) defines a numerical hierarchy with `Complex.__add__` but no `Number.__add__`. This seems to be a weird choice, since the other numeric type `Decimal` that (virtually) derives from `Number` also implements an add method.
So why is it this way? If I want to add type ... | 2017/03/12 | [
"https://Stackoverflow.com/questions/42742499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4133053/"
] | Its because you are increamenting two times in the loop.
Remove the last i++ and it works fine. | The form of this for loop is to always increment the counter variable after the final statement or function has executed or returned, respectively. So, any incrementation of 'i' in the loop body, in this case, will add 1 to the value of the for loop counter, corrupting the count. | 8,021 |
59,600,235 | Tell me please, what am I doing wrong?
I try to drag and drop through Selenium, but every time I come across an error "AttributeError: move\_to requires a WebElement"
**Here is my code:**
```
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
chromedriver = '/usr/local/bi... | 2020/01/05 | [
"https://Stackoverflow.com/questions/59600235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9729098/"
] | `find_elements_by_xpath` returns a list of `WebElement`s, `drag_and_drop` (and the other methods) accept a single `WebElement`. Use `find_element_by_xpath`
```
source = driver.find_element_by_xpath('//*[@id="box3"]')
target = driver.find_element_by_xpath('//*[@id="box103"]')
``` | as @guy said:
```
find_elements_by_xpath
```
returns list of `WebElements`. You can use `find_element_by_xpath` method to get single web element. Or select specific element from `WebElements` return by `find_elements_by_xpath`. For example, if you know, you wanted to select 2nd element from return list for target. T... | 8,024 |
19,939,365 | I'm trying to install a module called Scrapy. I installed it using
```
pip install Scrapy
```
I see the 'scrapy' folder in my /usr/local/lib/python2.7/site-packages, but when I try to import it in a Python program, is says there is no module by that name. Any ideas as to why this might be happening?
EDIT: Here is t... | 2013/11/12 | [
"https://Stackoverflow.com/questions/19939365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191726/"
] | Are you using Homebrew or MacPorts or something? As @J.F.Sebastian said, it sounds like you are having issues mixing the default python that comes with OS X, and one that is installed via a package manager... Try `/usr/local/opt/python/bin/python2.7 -m scrapy` and see if that throws an `ImportError`.
If that works, th... | EDIT: You can force pip to install to an alternate location. The details are here: [Install a Python package into a different directory using pip?](https://stackoverflow.com/questions/2915471/install-a-python-package-into-a-different-directory-using-pip). If you do indeed have extra Python folders on your system, maybe... | 8,029 |
64,483,669 | I am trying to make a multi-container docker app using `docker-compose`.
**Here's what I am trying to accomplish:** I have a python3 app, that takes a list of list of numbers as input from API call(`fastAPI` with gunicorn server) and pass the numbers to a function(an ML model actually) that returns a number, which wil... | 2020/10/22 | [
"https://Stackoverflow.com/questions/64483669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11814996/"
] | The problem are your labels.
They have the same ids as your input fields.
Since document.getElementById("date") only finds the first occurrence of the desired id your labels are returned.
To solve this you can change your labels to
```
<label for="date">Date: </label>
```
```html
<html>
<head>
<title>Ex... | On your html file, each `<label>` and `<input>` tags have got the same id so the problem happened.
For example, for the last `input`, the label has id `amount` and the input tag also has id `amount`.
So `document.getElementById("amount")` will return the first tag `<label>` tag so it won't have no values.
To solve t... | 8,038 |
5,253,358 | this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double... | 2011/03/09 | [
"https://Stackoverflow.com/questions/5253358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618111/"
] | Add the line
```
input()
```
to the end of the program, with the correct indentation. The issue is that after the data is printed to the console the program finishes, so the console goes away. `input` tells the program to wait for input, so the console won't be closed when it finishes printing.
I hope you're not us... | Just a bit more on this.
You have a script `myscript.py` in a folder `C:\myscripts`. This is how to set up Windows 7 so that you can type `> myscript` into a CMD window and the script will run.
1) Set your `PATH` variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Se... | 8,039 |
35,600,152 | I am deploying a django project on apache2 using mod\_wsgi, but the problem is that the server dont serve pages and it hangs for 10 minute before giving an error:
```
End of script output before headers
```
This is my **`site-available/000-default.conf`**:
```sh
ServerAdmin webmaster@localhost
DocumentRoot /home/ar... | 2016/02/24 | [
"https://Stackoverflow.com/questions/35600152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4759209/"
] | It seems you have an **'a'** in your *wsgi.py* file between the lines
```
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arTfact_webSite.settings")
a
application = get_wsgi_application()
```
no sure if this is in your actual file as well. | Try use the command:
apachectl configtest
This should help you isolate what is broken in your apache configuration. See this link for more information:
<https://httpd.apache.org/docs/2.4/programs/apachectl.html>
If it reports 'Syntax OK', then you know that it's a configuration **detail** problem rather than a confi... | 8,043 |
33,713,513 | I want to use Drupal for building a Genealogy application. The difficulty, I see, is in allowing users to upload a gedcom file and for it to be parsed and then from that data, various Drupal nodes would be created. Nodes in Drupal are content items. So, I'd have individuals and families as content types and each would ... | 2015/11/14 | [
"https://Stackoverflow.com/questions/33713513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784304/"
] | There are nested calls `Magic(in - 1);`. If number is even it is printed immediately and then `Magic(in - 1);` is called. Only when `n` is zero all functions print not even number in reverse order. The first odd number is printed by the deepest `Magic()` function:
```
Magic(10)
|print 10
|Magic(9)
| |Magic(... | this is caused by the recursion of the function. the function is returning in the order it was called. if you want to print the odd numbers in decreasing order after the even numbers, you need to save them in a variable (array ) that is also passed to the magic function | 8,046 |
597,289 | I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any... | 2009/02/28 | [
"https://Stackoverflow.com/questions/597289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | In python3, `bytes` objects are distinct from `str`, but I don't know any reason why there would be anything wrong with this. | `join` seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of byt... | 8,047 |
22,890,598 | I have a function which calculates the jaccard index for two parse strings. The function is working OK and its code is below:
```
def jack(a,b):
x=a.split()
y=b.split()
k=float(len(list(set(x)&set(y))))/float(len(list(set(x) | set(y))))
return k
```
However, when I want to apply the function for any ... | 2014/04/06 | [
"https://Stackoverflow.com/questions/22890598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2825079/"
] | Since you have one element lists and you are passing the lists as the parameters whereas your function expects strings, I would recommend you to invoke your function like this
```
jack(a[2][0], a[3][0])
```
Also, you dont have to convert the `set` to a `list` to find the length.
```
return float(len(set(x) & set(y)... | That is because your variable `a` is a nested list. You should either flatten `a` or pass the arguments as:
`jack(a[2][0],a[3][0])`
### Or, you could flatten your list as:
`a = [i[0] for i in a]`
then you can easily do:
`jack(a[0],a[1])` | 8,053 |
21,269,702 | I’m using wxPython to write an app that will run under OS X, Windows, and Linux. I’m trying to implement the standard “Close Window” menu item, but I’m not sure how to find out which window is frontmost. WX has a [`GetActiveWindow` function](http://wxpython.org/Phoenix/docs/html/functions.html#GetActiveWindow), but app... | 2014/01/21 | [
"https://Stackoverflow.com/questions/21269702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/371228/"
] | Okay I managed to finally get this program working, I've summarized below. I hope this might help someone also stuck on ex17.
First, I removed the MAX\_DATA and MAX\_ROWS constants and changed the structs like so:
```
struct Address {
int id;
int set;
char *name;
char *email;
};
struct Database {
... | One way is to change your arrays into pointers. Then you could write an alloc\_db function which would use the max\_row and max\_data values to allocate the needed memory.
```
struct Address {
int id;
int set;
char* name;
char* email;
};
struct Database {
struct Address* rows;
unsigned int max... | 8,054 |
9,560,616 | I am using ArcGIS focal statistics tool to add spatial autocorrelation to a random raster to model error in DEMs. The input DEM has a 1.5m pixel size and the semivariogram exhibits a sill around 2000m. I want to make sure to model the extent of the autocorrelation in the input in my model.
Unfortunately, ArcGIS requir... | 2012/03/05 | [
"https://Stackoverflow.com/questions/9560616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839375/"
] | I'm not sure if there is a built-in way, but it should not be hard to roll your own:
```
>>> def kernel_thing(N):
... import numpy as np
... n = N // 2 + 1
... a = np.zeros((N, N), dtype=int)
... for i in xrange(n):
... a[i:N-i, i:N-i] += 1
... return a
...
>>> def kernel_to_string(a):
... return '{} ... | [Hmmph. @wim beat me, but I'd already written the following, so I'll post it anyway.] Short version:
```
import numpy
N = 5
# get grid coords
xx, yy = numpy.mgrid[0:N,0:N]
# get the distance weights
kernel = 1 + N//2 - numpy.maximum(abs(xx-N//2), abs(yy-N//2))
with open('kernel.out','w') as fp:
# header
fp.... | 8,056 |
54,619,732 | I am developing a model for multi-class classification problem ( 4 classes) using Keras with Tensorflow backend. The values of `y_test` have 2D format:
```
0 1 0 0
0 0 1 0
0 0 1 0
```
This is the function that I use to calculate a balanced accuracy:
```
def my_metric(targ, predict):
val_predict = predict
va... | 2019/02/10 | [
"https://Stackoverflow.com/questions/54619732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9585135/"
] | You cannot call a sklearn function on a Keras tensor. You'll need to implement the functionality yourself using Keras' backend functions, or TensorFlow functions if you are using the TF backend.
The `balanced_accuracy_score` is defined [as the average of the recall](https://scikit-learn.org/stable/modules/generated/s... | try :
`pip install --upgrade tensorflow` | 8,057 |
37,463,506 | I am trying to open a word document with python in windows, but I am unfamiliar with windows.
My code is as follows.
```
import docx as dc
doc = dc.Document(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx')
```
Through another post, I learned that I had to put the r in front of my string ... | 2016/05/26 | [
"https://Stackoverflow.com/questions/37463506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4673518/"
] | try this
```
import StringIO
from docx import Document
file = r'H:\myfolder\wordfile.docx'
with open(file) as f:
source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()
```
<http://python-docx.readthedocs.io/en/latest/user/documents.html>
Also, in regards to debugging the f... | If you want to open the document in Microsoft Word try using `os.startfile()`.
In your example it would be:
```
os.startfile(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx')
```
This will open the document in word on your computer. | 8,058 |
32,734,437 | I got an file with text form:
```
a:
b(0.1),
c(0.33),
d:
e(0.21),
f(0.41),
g(0.5),
k(0.8),
h:
y(0.9),
```
And I want get the following form:
```
a: b(0.1), c(0.33)
d: e(0.21), f(0.41), g(0.5), k(0.8)
h: y(0.9)
```
In python language,
I have tried:
```
for line in menu:
for i in line:
if i == ":":
``... | 2015/09/23 | [
"https://Stackoverflow.com/questions/32734437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5316423/"
] | ```
import re
one_line = ''.join(menu).replace('\n', ' ')
print re.sub(', ([a-z]+:)', r'\n\1', one_line)[:-1]
```
You might have to tweak the `one_line` to match your input better. | I am not exactly sure if you want to print the stuff or actually manipulate the file. But in the case of just printing:
```
from __future__ import print_function
from itertools import tee, islice, chain, izip
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None... | 8,059 |
63,811,316 | I am running celery worker(version 4.4) on windows machine, when I run the worker with `-P eventlet` option it throws Attribute error.
Error logs are as follows:-
```
pipenv run celery worker -A src.celery_app -l info -P eventlet --without-mingle --without-heartbeat --without-gossip -Q queue1 -n worker1
Traceback (mos... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63811316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605353/"
] | `os.register_at_fork` is a new function available since `Python 3.7`, it is only available for Unix systems ([Source from Python doc](https://docs.python.org/3.8/library/os.html#os.register_at_fork)) and Eventlet use it to patch `threading` library.
There is an issue opened in Eventlet Github:
<https://github.com/even... | One reason you are facing this is because of the fact that Celery works on a pre-fork model.
So if the underlying OS does not support it, you will have a tough time running celery. As per my knowledge, this model does not exist for the Windows kernel.
You can still use Cygwin if you want to make it work on windows or ... | 8,061 |
18,233,399 | I have a fat32 partition image file dump, for example created with dd. how i can parse this file with python and extract the desired file inside this partition. | 2013/08/14 | [
"https://Stackoverflow.com/questions/18233399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460058/"
] | As far as reading a FAT32 filesystem image in Python goes, the [Wikipedia page](http://en.wikipedia.org/wiki/FAT32) has all the detail you need to write a read-only implementation.
[Construct](http://construct.readthedocs.org/en/latest/) may be of some use. Looks like they have an example for FAT16 (<https://github.co... | Just found out this nice [lib7zip bindings](https://github.com/topia/pylib7zip) that can read RAW FAT images (and [much more](https://7zip.bugaco.com/7zip/MANUAL/general/formats.htm)).
Example usage:
```py
# pip install git+https://github.com/topia/pylib7zip
from lib7zip import Archive, formats
archive = Archive("fd... | 8,066 |
35,569,042 | I apologize if this is a silly question, but I have been trying to teach myself how to use BeautifulSoup so that I can create a few projects.
I was following this link as a tutorial: <https://www.youtube.com/watch?v=5GzVNi0oTxQ>
After following the exact same code as him, this is the error that I get:
```
Traceback... | 2016/02/23 | [
"https://Stackoverflow.com/questions/35569042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790055/"
] | On Debian 9 I had to:
```
$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs
```
I'm not sure why, but this enviroment variable was never set. | This has changed in recent versions of the ssl library. The SSLContext was moved to it's own property. This is the equivalent of Jia's answer in Python 3.8
```
import ssl
ssl.SSLContext.verify_mode = ssl.VerifyMode.CERT_OPTIONAL
``` | 8,067 |
50,640,716 | I am using MACOS 10.12.6
I was trying to uninstall python to reinstall it, and I foolishly typed these commands into my terminals.
```
sudo rm -rf /Users/<myusername>/anaconda2/lib/python2.7
sudo rm -rf /Users/<myusername>/anaconda2/lib/python27.zip
sudo rm -rf /Users/<myusername>/anaconda2/lib/python2.7/plat-darwin... | 2018/06/01 | [
"https://Stackoverflow.com/questions/50640716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9880455/"
] | Since you used Anconda on your mac you should be able to just reinstall python 2.7. If you still have the install package: Anaconda2-5.2.0-MacOSX-x86\_64.pkg, just double click that and follow directions. If you don't have this package, download it from [here](https://www.anaconda.com/download/#macos) and when the pack... | You only deleted Anaconda, not the System Python.
Therefore, you probably only need to edit your PATH variable to remove references to those folders.
Check your `~/.bashrc` | 8,077 |
62,142,223 | I've installed from sources the SimpleITK package on Python3. When I perform the provided registration example :
```
#!/usr/bin/env python
#=========================================================================
#
# Copyright NumFOCUS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ... | 2020/06/01 | [
"https://Stackoverflow.com/questions/62142223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11107590/"
] | The result of running the ImageRegistrationMethod1 example is a transform. SimpleITK supports a number of file formats for transformations, including a text file (.txt), a Matlab file (.mat) and a HDF5Tranform (.hdf5). That does not include a .tif file, which is an image file, not a transform.
You can read more about ... | if you want to write dicom as file output, please try this one.
```
writer.SetFileName(os.path.join('transformed.dcm'))
writer.Execute(cimg)
``` | 8,078 |
73,277,276 | I know how to add a function to a python dict:
```
def burn(theName):
return theName + ' is burning'
kitchen = {'name': 'The Kitchen', 'burn_it': burn}
print(kitchen['burn_it'](kitchen['name']))
### output: "the Kitchen is burning"
```
but is there any way to reference the dictionary's own 'name' value wi... | 2022/08/08 | [
"https://Stackoverflow.com/questions/73277276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1914833/"
] | You can extend `dict` object with your custom class, like this:
```py
class MyDict(dict):
def __init__(self, *args, **kwargs):
self["burn_it"] = self.burn
super().__init__(*args, **kwargs)
def burn(self):
return self["name"] + " is burning"
kitchen = MyDict({'name': 'The Kitchen'})
p... | You cannot know which object reference the function.
A simple example, image the following:
```
def burn(theName):
return theName + ' is burning'
kitchen = {'name': 'The Kitchen', 'burn_it': burn}
garage = {'name': 'The Garage', 'burn_it': burn}
```
`burn` is referenced both in `kitchen` and `garage`, how ... | 8,079 |
56,693,576 | I am trying to access a variable defined inside an if statement in a for loop, outside the for loop. but I am getting the 'Unbounded Local Error'
I have tried assigning `lambdaPriceUsWest2 = None` as suggested here:
[Python Get variable outside the loop](https://stackoverflow.com/questions/25406399/python-get-variable... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56693576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6921304/"
] | the best way is before the for loop try to initialize that variable. For example:
```
lambdaPriceUsWest2 = ""
``` | just defined a var outside loop and update it value
```
local_val =''
for x in range(len(response['PriceList'])):
priceList=json.loads(response['PriceList'][x])
if priceList['product']['sku'] == 'DU9X9ZR8C8DYH3Y9':
lambdaPriceUsWest2= priceListpriceList['product']['sku']['USD']
... | 8,080 |
59,125,889 | ```
npm install expo-cli --global
```
I got this following error:
```
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] postinstall: `test -d .git && cp gitHookPrePush.sh .git/hooks/pre-push || true`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This i... | 2019/12/01 | [
"https://Stackoverflow.com/questions/59125889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5982462/"
] | just try installing `npm install expo-cli --global` this command on git bash. It worked for me. | [I fixed this problem](https://stackoverflow.com/questions/59124830/reactnative-code-elifecycle-error-when-installing-expo-cli/59126514#59126514) :
```
1- Download and install Git SCM
2- Download Visual Studio Community HERE and install a Custom Installation, selecting ONLY the following packages: VISUAL C++, PYTHON T... | 8,082 |
50,751,484 | I trained on TensorFlow model on a GPU cluster, saved the model using
```
saver = tf.train.Saver()
saver.save(sess, config.model_file, global_step=global_step)
```
and now I am trying to restore the model with
```
saver = tf.train.import_meta_graph('model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint(s... | 2018/06/07 | [
"https://Stackoverflow.com/questions/50751484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6263317/"
] | By default, the `Saver` object will write the absolute model checkpoint paths into the `checkpoint` file. So the path returned by `tf.train.latest_checkpoint(save_path)` is the absolute path on your old machine.
Temporary solution:
1. Pass the actual model file path directly to the `restore` method rather than the r... | Open up the checkpoint file with your favorite text editor and simply change the absolute paths found therein to just filenames. | 8,083 |
25,201,504 | I'm trying to minimize function, that returns a vector of values,
and here is an error:
>
> setting an array element with a sequence
>
>
>
Code:
```
P = np.matrix([[0.3, 0.1, 0.2], [0.01, 0.4, 0.2], [0.0001, 0.3, 0.5]])
Ps = np.array([10,14,5])
def objective(x):
x = np.array([x])
res = np.square(Ps... | 2014/08/08 | [
"https://Stackoverflow.com/questions/25201504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2824962/"
] | Your objective function needs to return a scalar value, not a vector. You probably want to return the *sum* of squared errors rather than the vector of squared errors:
```
def objective(x):
res = ((Ps - np.dot(x, P)) ** 2).sum()
return res
``` | Use [`least_squares`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html). This will require to modify the objective a bit to return differences instead of squared differences:
```py
import numpy as np
from scipy.optimize import least_squares
P = np.matrix([[0.3, 0.1, 0.2], [0.01, ... | 8,084 |
31,580,319 | I use ansible module `fetch` to download a large file, said 2GB. Then I got the following error message. Ansible seems to be unable to deal with large file.
```
fatal: [x.x.x.x] => failed to parse:
SUDO-SUCCESS-ucnhswvujwylacnodwyyictqtmrpabxp
Traceback (most recent call last):
File "/home/xxx/.ansible/tmp/ansible-... | 2015/07/23 | [
"https://Stackoverflow.com/questions/31580319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605599/"
] | <https://github.com/ansible/ansible/issues/11702>
This is an Ansible bug which have been solved in newer version. | Looks like the remote server you're trying to fetch from is running out of memory during the base64 encoding process. Perhaps try the synchronize module instead (which will use rsync); fetch isn't really designed to work with large files. | 8,086 |
15,811,082 | I am developing some python packages and I do want to perform proper testing before releasing them to PyPi.
This would require running the unittests across
* different python versions: 2.5, 2.6, 2.7, 3.2
* different operating systems: OS X, Debian, Ubuntu and Windows
Right now I am using pytest
Question: how can I ... | 2013/04/04 | [
"https://Stackoverflow.com/questions/15811082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/99834/"
] | I have used Jenkins, and I would recommend it. It has a plethora of plugins, and is very configurable.
I have used it for running projects over windows/linux/mac/mobile platforms, for sanity, unit, component, and regression tests.
It can support chaining of projects and tests, fingerprinting of items to be monitored ... | You can use [`tox`](http://codespeak.net/tox/index.html) to automate setting up virtual environments and running your tests across Python versions:
```
[tox]
envlist = py25,py26,py27,py32
[testenv]
commands=py.test
```
Tox supports Python versions 2.4 and up, as well as Jython and PyPy.
If you want to look at a rea... | 8,089 |
51,919,720 | I've been unable to use Pyenv to install Python on macOS (10.13.6) and have exhausted advice about common build problems.
pyenv-doctor reports: **OpenSSL development header is not installed.** Reinstallation of OpenSSL, as suggested in various related GitHub issues has not worked, not have various flag settings, eg (... | 2018/08/19 | [
"https://Stackoverflow.com/questions/51919720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7322742/"
] | If this is the same issue as me, it's because there's headers in your path that shouldn't be there. Run `brew doctor` and you would see it complain. To fix it you can do:
```
mkdir /tmp/includes
brew doctor 2>&1 | grep "/usr/local/include" | awk '{$1=$1;print}' | xargs -I _ mv _ /tmp/includes
``` | After applying Kit's answer; I had to do the following to overcome the fact that I also installed `openssl` with homebrew:
```
CFLAGS="-I$(brew --prefix openssl)/include" \
LDFLAGS="-L$(brew --prefix openssl)/lib" \
pyenv doctor
```
That got me working.
Also found this [reference](https://github.com/pyenv/pyenv/wiki... | 8,090 |
46,492,510 | I'm new to python, I'm trying to create a list of lists from a text file. The task seems easy to do but I don't know why it's not working with my code.
I have the following lines in my text file:
```
word1,word2,word3,word4
word2,word3,word1
word4,word5,word6
```
I want to get the following output:
```
[['word1... | 2017/09/29 | [
"https://Stackoverflow.com/questions/46492510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4699562/"
] | You can iterate like this:
```
f = [i.strip('\n').split(',') for i in open('file.txt')]
``` | Your code works fine, if your code creating issues in your system then if you want you can do this in one line with this :
```
with open("file.txt") as f:
print([i.strip().split(',') for i in f])
``` | 8,091 |
61,327,413 | I have a client python and a server python and the commands which work perfectly. Now I want to build the interface which needs a variable(string) from the server file and I encountered a problem.
**my client.py file**
```
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostna... | 2020/04/20 | [
"https://Stackoverflow.com/questions/61327413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12305440/"
] | Here's your exact same code using a file system object instead to do the folder work inside the loop. I didn't test it, but it illustrates what I am talking about in my comment above. You should be able to get it working using this:
```
Sub Unzip()
Dim oApplicationlication As Object
Dim MyFolder As String
Dim MyFile A... | Your code is failing because you are using `Dir` within the loop to check the existence of the folder to extract to. Instead, move that piece of code to outside the loop:
```
Sub Unzip()
Dim oApplication As Object
Dim MyFolder As String
Dim MyFile As String
Dim ExtractTo As Variant
Application.Scre... | 8,092 |
29,859,173 | I am following the example to deploy sample python application to bluemix
[BLUEMIX-PYTHON-FLASK-SAMPLE](https://github.com/IBM-Bluemix/bluemix-python-flask-sample)
Created project successfully
Cloned repository successfully
Configured pipeline successfully
Deploy to BLUEMIX failed.
I checked the error in deployment l... | 2015/04/24 | [
"https://Stackoverflow.com/questions/29859173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2639529/"
] | The memory limit is controlled by the memory value in the manifest.yml file in the root of the project. You don't need to have this manifest.yml file present as Bluemix will define defaults for you. In this case the memory allocation would be 1GB as this is the default which is really to much for a sample app like this... | You probably have exceeded the max app limit on your Bluemix account.
Login to your Bluemix account and check if all the app memory limit is utilized. If you have reached your limit then you might have to remove one or more of the apps which you are not using based on how much memory space is needed.
in the python-fl... | 8,093 |
18,950,409 | I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration.
For example:
```
#!/usr/bin/python
doubleDict = dict()
doubleDict['one'] = dict()
doubleDict['one']['type'] = 'animal'
doubleDict['on... | 2013/09/23 | [
"https://Stackoverflow.com/questions/18950409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174102/"
] | For-loops in `dict`s iterates over the keys and not over the values.
To iterate over the values do:
```
for thing in doubleDict.itervalues():
print thing
print thing['type']
print thing['name']
print thing['species']
```
I used your exact same code, but added the `.itervalues()` at t... | When you iterate through a dictionary, you iterate through it's keys and not its values. To get nested values, you have to do:
```
for thing in doubleDict:
print doubleDict[thing]
print doubleDict[thing]['type']
print doubleDict[thing]['name']
print doubleDict[thing]['species']
``` | 8,095 |
48,000,225 | I have two dataframes as follows:
`leader`:
```none
0 11
1 8
2 5
3 9
4 8
5 6
[6065 rows x 2 columns]
```none
`DatasetLabel`:
```none
0 1 .... 7 8 9 10 11 12
0 A J .... 1 2 5 NaN NaN NaN
1 B K .... 3 4 NaN NaN NaN NaN
[4095 rows x 14 columns]
```
The Information dataset colu... | 2017/12/28 | [
"https://Stackoverflow.com/questions/48000225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3806649/"
] | You can use `apply` to index into `leader` and exchange values with `DatasetLabel`, although it's not very pretty.
One issue is that Pandas won't let us index with `NaN`. Converting to `str` provides a workaround. But that creates a second issue, namely, column `9` is of type `float` (because `NaN` is `float`), so `5... | The [source code](https://github.com/pandas-dev/pandas/blob/v1.5.2/pandas/core/indexing.py#L1828-L1882) shows that this error occurs when you try to broadcast a list-like object (numpy array, list, set, tuple etc.) to multiple columns or rows but didn't specify the index correctly. Of course, list-like objects don't ha... | 8,103 |
7,007,400 | I have a small python application, which uses pyttsx for some text to speech.
How it works:
simply say whatever is there in the clipboard.
The program works as expected inside eclipse. But if run on cmd.exe it only works partly if the text on the clipboard is too large(a few paras). Why ?
when run from cmd, it prin... | 2011/08/10 | [
"https://Stackoverflow.com/questions/7007400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161179/"
] | Checked that the problem is not in the code that reads the text from the clipboard.
You should check if your eclipse setup specifies custom environment variables for the project which do not exist outside Eclipse. Especially:
* PYTHONPATH (and also additional projects on which your program could depend in your setup... | In fact, eclipse itself uses a commandline command to start it's apps.
You should check what command eclipse is giving to start the program. It might be a bit verbose, but you can start from there and test what is necessary and what isn't.
You can find out the commandline eclipse uses by running the program and then ... | 8,104 |
32,678,690 | How to install pip for python3.4 when my pi have python3.2 and python3.4
when I used `sudo install python3-pip`
it's only for python3.2
but I want install pip for python3.4 | 2015/09/20 | [
"https://Stackoverflow.com/questions/32678690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5089211/"
] | Python 3.4 has `pip` included, see [*What's New in Python 3.4*](https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453).
Just execute:
```
python3.4 -m ensurepip
```
to install it if it is missing for you. See the [`ensurepip` module documentation](https://docs.python.org/3/library/ensurepip.html) for further... | You can go to your python 3.4 directory scripts and run it's pip in:
`../python3.4/scripts` | 8,107 |
7,921,973 | i'm writing an installer using py2exe which needs to run in admin to have permission to perform various file operations. i've modified some sample code from the user\_access\_controls directory that comes with py2exe to create the setup file. creating/running the generated exe works fine when i run it on my own compute... | 2011/10/27 | [
"https://Stackoverflow.com/questions/7921973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971550/"
] | Try to set `options={'py2exe': {'bundle_files': 1}},` and `zipfile = None` in setup section. Python will make single .exe file without dependencies. Example:
```
from distutils.core import setup
import py2exe
setup(
console=['watt.py'],
options={'py2exe': {'bundle_files': 1}},
zipfile = None
)
``` | I rewrite your setup script for you. This will work
```
from distutils.core import setup
import py2exe
# The targets to build
# create a target that says nothing about UAC - On Python 2.6+, this
# should be identical to "asInvoker" below. However, for 2.5 and
# earlier it will force the app into compatibility mode ... | 8,109 |
71,853,039 | In short, how do I get this:
[](https://i.stack.imgur.com/JBBws.jpg)
From this:
```py
def fiblike(ls, n):
store = []
for i in range(n):
a = ls.pop(0)
ls.append(sum(ls)+a)
store.appe... | 2022/04/13 | [
"https://Stackoverflow.com/questions/71853039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | * Getting pair token balance of contracts
>
> web3.eth.contract(address=token\_address,abi=abi).functions.balanceOf(contract\_address).call()
>
>
>
* and then get current price of each token / USDT by calling function slot0 in pool tokenA/USDT & tokenB/USDT
>
> slot0 = contract.functions.slot0().call()
>
>
> ... | No offense but you are following a hard way, which needs to use `TickBitmap` to get the next initialized tick (Remember not all ticks are initialized unless necessary.)
Alternatively the easy way to get a pool's TVL is to query Uniswap V3's [subgraph](https://thegraph.com/hosted-service/subgraph/ianlapham/uniswap-v3-s... | 8,110 |
60,325,327 | I wrote an app in python3.7.5 that connects to RabbitMQ:
========================================================
### Using Ubuntu as the docker-machine
I am running rabbitmq with docker:
`docker run --name rabbitmq -p 5671:5671 -p 5672:5672 -p 15672:15672 --hostname rabbitmq rabbitmq:3.6.6-management`
TEST:
----... | 2020/02/20 | [
"https://Stackoverflow.com/questions/60325327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1125913/"
] | According to <https://docs.docker.com/network/host/>,
>
> Note: Given that the container does not have its own IP-address when using host mode networking, port-mapping does not take effect, and the -p, --publish, -P, and --publish-all option are ignored, producing a warning instead:
>
>
>
I am not sure this is y... | RabbitMQ container
```
docker run --name rabbitmq \
-p 5671:5671 -p 5672:5672 -p 15672:15672 \
--hostname rabbitmq \
--network host \ # <-- Add this line, now both container see each other
rabbitmq:3.6.6-management
```
App container
```
docker run \
-P \
--env ENVIRONMEN... | 8,111 |
66,169,625 | I have two CSV files:
**File 1**
```
Id, 1st, 2nd
1, first, row
2, second, row
```
**File 2**
```
Id, 1st, 2nd
1, first, row
2, second, line
3, third, row
```
I am just starting in python and need to write some code, which can do the diff on these files based on primary columns and in this case first column "Id"... | 2021/02/12 | [
"https://Stackoverflow.com/questions/66169625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15196604/"
] | I suggest you load both CSV files as Pandas DataFrames, and then you use and outer `merge` with indicator to know what rows changed in the second file. Then, you use `query` to get only the rows that changed in the second file, and you drop the indicator column ('\_merge').
```py
import pandas as pd
df1 = pd.read_csv... | I'd also use pandas, as Enrico suggested, for anything more complex than your example. But if you want to do it in pure Python, you can convert your rows into sets and compute a set difference:
```py
import csv
from io import StringIO
data1 = """Id, 1st, 2nd
1, first, row
2, second, row"""
data2 = """Id, 1st, 2nd
1, ... | 8,112 |
60,532,107 | Trying to find out the correct number of parallel processes to run with [python multiprocessing](https://docs.python.org/3.6/library/multiprocessing.html).
Scripts below are run on an 8-core, 32 GB (Ubuntu 18.04) machine. (There were only system processes and basic user processes running while the below was tested.)
... | 2020/03/04 | [
"https://Stackoverflow.com/questions/60532107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1333610/"
] | >
> **Q** : *"**Why** is running 5 to 8 in parallel at a time **worse than running 4** at a time?"*
>
>
>
Well, there are several reasons and we will start from a static, easiest observable one :
Since the **silicon design** ( for which they used a few hardware tricks ) **does not scale** beyond the 4.
So **the ... | Most likely cause is that you are running the program on a CPU that uses [simultaneous multithreading (SMT)](https://en.wikipedia.org/wiki/Simultaneous_multithreading), better known as [hyper-threading](https://en.wikipedia.org/wiki/Hyper-threading) on Intel units. To cite after wiki, *for each processor core that is p... | 8,113 |
73,171,968 | I'm trying to make a form where JavaScript makes the authentication of it. After JavaScript says that the user followed the rules correctly, the JavaScript file collects the data typed by the user, so the data is sent to Python (with the help of ajax). From the Python file, I want that it recognizes the data and finall... | 2022/07/29 | [
"https://Stackoverflow.com/questions/73171968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19575161/"
] | A very simple, and performant way of checking if all pixels are the same, would be to use PIL's `getextrema()` which tells you the brightest and darkest pixel in an image. So you would just test if they are the same and that would work if testing they were both zero, or any other number. It will be performant because i... | 1. Convert image to 3D numpy array
[enter link description here](https://ru.stackoverflow.com/questions/1145128/%D0%9A%D0%B0%D0%BA-%D0%BF%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C-jpg-%D0%B2-%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2-numpy)
2. Check if all elements of an array are the same
[ente... | 8,114 |
69,607,510 | ```
import csv
import mysql.connector as mysql
marathons = []
with open ("marathon_results.csv") as file:
data = csv.reader(file)
next(data)
for rij in data:
year = rij[0],
winner = rij[1],
gender = rij[2],
country = rij[3],
time = rij[4],
marathon = rij[5],... | 2021/10/17 | [
"https://Stackoverflow.com/questions/69607510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17025019/"
] | The problem is in these lines:
```py
year = rij[0],
winner = rij[1],
gender = rij[2],
country = rij[3],
time = rij[4],
marathon = rij[5],
```
The trailing commas cause `year`, `winner`, `gender` and so on to be created as 1-tuples. It's the same as writing
```py
... | Your sql comad had a & instead of a %.
I additionally simplified the data loop
```
import csv
import mysql.connector as mysql
marathons = []
with open ("test2.csv") as file:
data = csv.reader(file)
next(data)
marathons = [tuple(row) for row in data]
conn = mysql.connect(
host="localhost",
us... | 8,115 |
46,053,097 | I have created and API using python+flask. When is try to hit the api using postman or chrome it works fine and I am able to get to the api.
On the other hand when I try to use python
```
import requests
requests.get("http://localhost:5050/")
```
I get 407. I guess that the proxy of the our environment is not allo... | 2017/09/05 | [
"https://Stackoverflow.com/questions/46053097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6128923/"
] | According to [requests module documentation](http://docs.python-requests.org/en/master/user/advanced/#proxies) you can either provide proxy details through environment variable **HTTP\_PROXY** (in case use Linux distribution):
```
$ export HTTP_PROXY="http://corporate-proxy:port"
$ python
>>> import requests
>>> reque... | Try
```
import requests
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
requests.get("http://localhost:5050/")
``` | 8,116 |
7,641,592 | I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p... | 2011/10/03 | [
"https://Stackoverflow.com/questions/7641592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/654789/"
] | You can compress the data with [bzip2](http://docs.python.org/library/bz2.html):
```
from __future__ import with_statement # Only for Python 2.5
import bz2,json,contextlib
hugeData = {'key': {'x': 1, 'y':2}}
with contextlib.closing(bz2.BZ2File('data.json.bz2', 'wb')) as f:
json.dump(hugeData, f)
```
Load it like ... | >
> faster, or even possible, to zip this pickle file prior to [writing]
>
>
>
Of course it's possible, but there's no reason to try to make an explicit zipped copy in memory (it might not fit!) before writing it, when you can *automatically cause it to be zipped as it is written, with built-in standard library fu... | 8,117 |
21,068,471 | Running the following python script through web site works fine and (as expected) stops the playback of MPD:
```
#!/usr/bin/env python
import subprocess
subprocess.call(["mpc", "stop"])
print ("Content-type: text/plain;charset=utf-8\n\n")
print("Hello")
```
This script however causes an error (playback starts as ex... | 2014/01/11 | [
"https://Stackoverflow.com/questions/21068471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143211/"
] | 1. You're running your script in some sort of CGI-like environment. I would strongly suggest using a light web framework like Flask or Bottle.
2. `mpc play` is writing to stdout. You need to silence it:
```
import os
with open(os.devnull, 'w') as dev_null:
subprocess.call(["mpc", "stop"], stdout=dev_null)
```
3.... | You need to use `\r\n` line endings. | 8,126 |
2,700,195 | I have some data that I would like to save to a MAT file (version 4 or 5, or any version, for that matter). The catch: I wanted to do this without using matlab libraries, since this code will not necessary run in a machine with matlab. My program uses Java and C++, so any existing library in those languages that achiev... | 2010/04/23 | [
"https://Stackoverflow.com/questions/2700195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227103/"
] | C: [matio](http://sourceforge.net/projects/matio/)
Java: [jmatio](http://sourceforge.net/projects/jmatio/)
(I'm really tempted to, so I will, tell you to learn to google)
But really, it's not that hard to write matfiles using `fwrite` if you don't need to handle some of the more complex stuff (nested structs, cl... | MAT files since version 7 are HDF5 based. I recall that they use some rather funny conventions, but you may be able to reverse engineer what you need. There are certainly HDF5 writing libraries for both Java and C++.
Along these lines, Matlab can read/write several standard formats, including HDF5. It may be easiest t... | 8,127 |
31,073,212 | When running:
mkvirtualenv test
I get following error:
```
File "/usr/lib/python3/dist-packages/virtualenv.py", line 2378, in <module>
main()
File "/usr/lib/python3/dist-packages/virtualenv.py", line 830, in main
symlink=options.symlink)
File "/usr/lib/python3/dist-packages/virtualenv.py", line 999, i... | 2015/06/26 | [
"https://Stackoverflow.com/questions/31073212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3294412/"
] | You are likely getting the error because you cannot create the virtualenv folder in the current working directory.
If you do an `ls -ld .` you'll see the output of the current directory you're running the command from, e.g.:
```
➜ ~ ls -ld .
drwxr-xr-x+ 114 tfisher staff 3876 Jun 26 08:46 .
```
and if you do a... | i have did the same the issue i found is :
>
> `echo $WORKON_HOME`
>
>
>
you will find : ***/home/user/.virtualenvs/extra\_path***
just yoy need to remove this extra\_path added after ***.virtualenvs*** path
from your ***.bashrc*** and then *source* it again try again creating *mkvirtualenv* | 8,128 |
3,934,777 | I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization.
I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s... | 2010/10/14 | [
"https://Stackoverflow.com/questions/3934777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133374/"
] | I don't think there is a language native implementation of memoization.
But you can implement it easily, as a decorator of your method. You have to maintain a Map: the key of your Map is the parameter, the value the result.
Here is a simple implementation, for a one-arg method:
```
Map<Integer, Integer> memoizator =... | You could use the [Function](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html) interface in Google's [guava](http://code.google.com/p/guava-libraries/) library to easily achieve what you're after:
```
import java.util.HashMap;
import java.util.Map;
import com.google.common.... | 8,131 |
71,972,703 | I am trying to to a very simple python request using `requests.get` but am getting the following error using this code:
```
url = 'https://www.tesco.com/'
status = requests.get(url)
```
The error:
```
requests.exceptions.SSLError: HTTPSConnectionPool(host='www.tesco.com', port=443): Max retries exceeded with url: /... | 2022/04/22 | [
"https://Stackoverflow.com/questions/71972703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10574250/"
] | Explanation
===========
The errors is caused by an invalid or expired [SSL Certificate](https://www.gogetssl.com/wiki/ssl-basics/what-is-ssl-tls/)
When making a GET request to a server such as `www.tesco.com` you have 2 options, an [http](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) and an [https](https... | Paraphrasing [similar post](https://stackoverflow.com/questions/41287979/cant-access-certain-sites-requests-get-in-python-3) to your specific question.
Response 403 means forbidden, in other words, the website understands the request but doesn't allow access. It could be a security measure to prevent scraping.
As a w... | 8,140 |
69,751,866 | I am getting this error while Executing simple **Recursion Program** in **Python**.
```
RecursionError Traceback (most recent call last)
<ipython-input-19-e831d27779c8> in <module>
4 num = 7
5
----> 6 factorial(num)
<ipython-input-19-e831d27779c8> in factorial(n)
1 de... | 2021/10/28 | [
"https://Stackoverflow.com/questions/69751866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15926850/"
] | A recursive function has a simple rule to follow.
1. Create an exit condition
2. Call yourself (the function) somewhere.
Your factorial function only calls itself. And it will not stop in any condition (goes on to negative).
Then you hit maximum recursion depth.
You should stop when you hit a certain point. In your... | You have to return another value at some point.
Example below:
```
def factorial(n):
if n == 1:
return 1
return (n * factorial(n-1))
```
Else, your recursive loop will not stop and go to - infinity. | 8,141 |
24,023,512 | I know this is probably not a good style, but I was wondering if it is possible to construct a class when a static method is called
```
class myClass():
def __init__(self):
self.variable = "this worked"
@staticmethod
def test_class(var=myClass().variable):
print self.variable
if "__name__... | 2014/06/03 | [
"https://Stackoverflow.com/questions/24023512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3692553/"
] | Perhaps the easiest is to turn it into a `classmethod` instead:
```
class myClass(object):
def __init__(self):
self.variable = "this worked"
@classmethod
def test_class(cls):
var = cls().variable
print var
if __name__ == "__main__":
myClass.test_class()
```
See [What is the... | Yes, the default value for a function argument has to be definable at the point that the function appears, and a class isn't actually finished defining until the end of the "class block." The easiest way to do what you're trying to do is:
```
@staticmethod
def test_class(var=None):
if var is None: var = myClass().... | 8,142 |
59,867,504 | I am very new to the Python language and have a small program. It had been working but something change and now I can't get it to run. It's having a problem with finding 'pyodbc'. I installed the 'pyodbc' package so I don't understand why there error. I am using Python 3.7.6. Thank you for your help!
**pip install pyo... | 2020/01/22 | [
"https://Stackoverflow.com/questions/59867504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216326/"
] | If I'm understanding your question correctly and you're looking for how frequent two of the same categories are 1 in the same row (e.g. pairwise like @M-- asked), here's how I've done it in the past. I'm sure there's a more graceful way of going about it though :D
```
library(dplyr)
library(tidyr)
test.df <- structur... | You can use arules which is geared from this kind of analysis. You can read more about some of its uses [here](https://cran.r-project.org/web/packages/arules/vignettes/arules.pdf)
So this is your data:
```
df = structure(list(Type_SunflowerSeeds = c(1L, 1L, 1L, 0L, 0L), Type_SafflowerSeeds = c(0L,
0L, 0L, 0L, 0L), T... | 8,143 |
55,483,057 | I have the following task in one of my ansible playbook:
```
- name: Generate vault token
uri:
url: "{{vault_address}}/v1/auth/github/login"
method: POST
body: "{ \"token\": \"{{ token }}\" }"
validate_certs: no
body_format: json
register: vault_token
- nam... | 2019/04/02 | [
"https://Stackoverflow.com/questions/55483057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5996587/"
] | Add `-vvvv` to your command line to debug.
As you specified `body_format: json`, you can simplify your `body` part:
```
- name: Generate vault token
uri:
url: "{{vault_address}}/v1/auth/github/login"
method: POST
body:
token: mytoken
validate_certs: no
body_format: json
``` | I was able to get past this issue with ansible version `2.7.9` I was on `2.0.0.2` | 8,144 |
11,639,577 | I installed oauth2 by just downloading tar.gz package and doing `python setup.py install`. However I'm getting this error
```
bash-3.2$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license... | 2012/07/24 | [
"https://Stackoverflow.com/questions/11639577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730403/"
] | I don't have an answer, but I have some general suggestions:
Run `python setup.py install` with the same python that you intend to use it from (in your case one is capitalised, the other is not).
I always `export` my bashrc variables to ensure they are global, but I am not sure that is your issue here.
When running ... | it looks like you have two different versions of python installed, and one of them you launched using Python as opposed to python.
Since your second example workd, it looks like you've installed oauth2 using Python. | 8,145 |
34,579,327 | I am receiving this error in Python 3.5.1.
>
> json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
>
>
>
Here is my code:
```
import json
import urllib.request
connection = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_220996.json')
js = connection.read()
print(js)
info... | 2016/01/03 | [
"https://Stackoverflow.com/questions/34579327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4679487/"
] | If you look at the output you receive from `print()` and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by `b`):
```none
b'{\n "note":"This file .....
```
If you fetch the URL using a tool such as `curl -v`, you will see that the content type is
```none
... | in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use *try json.loads(str) except* to check your input | 8,146 |
25,937,443 | In Python, I have three lists containing x and y coordinates. Each list contains 128 points. How can I find the the closest three points in an efficient way?
This is my working python code but it isn't efficient enough:
```
def findclosest(c1, c2, c3):
mina = 999999999
for i in c1:
for j in... | 2014/09/19 | [
"https://Stackoverflow.com/questions/25937443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4058928/"
] | As written, this is problematic, you are trying to write to a vector for which you did not yet allocate memory.
Option 1 - Resize your vectors ahead of time
```
vector< vector<int> > matrix;
cout << "Filling matrix with test numbers.";
matrix.resize(4); // resize top level vector
for (int i = 0; i < 4; i++)
{
ma... | You have not allocated any space for your 2d vector. So in your current code, you are trying to access some memory that does not belong to your program's memory space. This will result in Segmentation Fault.
try:
```
vector<vector<int> > matrix(4, vector<int>(4));
```
If you want to give all elements the same val... | 8,147 |
14,510,286 | I'm currently writing an application which allows the user to extend it via a 'plugin' type architecture. They can write additional python classes based on a BaseClass object I provide, and these are loaded against various application signals. The exact number and names of the classes loaded as plugins is unknown befor... | 2013/01/24 | [
"https://Stackoverflow.com/questions/14510286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233608/"
] | The [metaclass approach](http://martyalchin.com/2008/jan/10/simple-plugin-framework/) is useful for this issue in Python < 3.6 (see @quasoft's answer for Python 3.6+). It is very simple and acts automatically on any imported module. In addition, complex logic can be applied to plugin registration with very little effor... | The approach from will-hart was the most useful one to me!
For i needed more control I wrapped the Plugin Base class in a function like:
```
def get_plugin_base(name='Plugin',
cls=object,
metaclass=PluginMount):
def iter_func(self):
for mod in self._models:
... | 8,150 |
1,933,217 | I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings.
I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in [Ruby](http://github.com/whymirror/mouseh... | 2009/12/19 | [
"https://Stackoverflow.com/questions/1933217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143725/"
] | Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting.
In Apache... | If you looking for a Perl solution then take a look at [`HTTP::Proxy`](http://search.cpan.org/dist/HTTP-Proxy/)
Not sure of any mod\_perl solutions though. [CPAN](http://search.cpan.org) does bring up [`Apache::Proxy`](http://search.cpan.org/dist/Apache-Proxy/) and Googling brings up [MyProxy](http://sourceforge.net/p... | 8,152 |
29,397,839 | I am SSHed into a remote machine and I do not have rights to download python packages but I want to use 3rd party applications for my project. I found `cx_freeze` but I'm not sure if that is what I need.
What I want to achieve is to be able to run different parts of my project (will mains everywhere) with command line... | 2015/04/01 | [
"https://Stackoverflow.com/questions/29397839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815710/"
] | When you pass an primitive array such as `char[]` to `Arrays.asList`, that method can't return a `List<char>`, because primitive types aren't allowed as type arguments. But it can and does produce a `List<char[]>`. Your random `char` is never equal to the single `char[]` inside the `List`, so any duplicate `char` is al... | Add you Alphabet in a ArrayList and remove the element selected at each turn of your while. Then update your rand.nextInt like:
```
rand.nextInt(AlphabetList.size());
```
And your ALPHABET like:
```
List<char> AlphabetList = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p'... | 8,157 |
70,702,139 | I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap.
What is the best way to build a snap with multiple python modules?
I have a simple script which imports the SDK and then prints some inform... | 2022/01/13 | [
"https://Stackoverflow.com/questions/70702139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17927115/"
] | Looks like your problem is that you are trying to run python main.py from within the Python interpreter, which is why you're seeing that traceback.
Make sure you're out of the interpreter:
```
exit()
```
Then run the **python main.py** command from bash or command prompt or whatever. | Invoke python scripts like this:
```
PS C:\Users\sween\Desktop> python ./a.py
```
Not like this:
```
PS C:\Users\sween\Desktop> python
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> ./a.py
... | 8,159 |
28,780,489 | When am trying to run the chron job in django using below command
```
python manage.py runcrons
```
its showing one error like below
```
$ python manage.py runcrons
No handlers could be found for logger "django_cron"
```
Does any one have any idea about this error? Any help is appreciated. | 2015/02/28 | [
"https://Stackoverflow.com/questions/28780489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582293/"
] | It is kind of given in the error you get. You are missing a handler for the "django\_cron" logger. See for example <https://stackoverflow.com/a/7048543/1197616>. Also have a look at the docs for Django, <https://docs.djangoproject.com/en/dev/topics/logging/>. | Actually the *django-cron* library does not require a 'django\_cron' logger. I resolved the same problem by running the migrations of django\_cron:
```
python manage.py migrate #migrate database
``` | 8,168 |
62,978,500 | I have made a python program that uses Pygame. For some reason, I can't close the window when pressing the red cross. I tried using Command+Q but it doesn't work as well. I have to quit idle (my python interpreter) to close the window. Is there any other way to make the window close by pressing the red 'x' at the top r... | 2020/07/19 | [
"https://Stackoverflow.com/questions/62978500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12987382/"
] | A pygame window can be closed properly if you use a different python interpreter. Try using pycharm, you can close pygame windows using pycharm. | Try this:
```
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,800))
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
``` | 8,169 |
20,905,702 | I'm currently working with Freeswitch and its [event socket library](http://wiki.freeswitch.org/wiki/Event_Socket_Library) (through the [mod event socket](http://wiki.freeswitch.org/wiki/Mod_event_socket)). For instance:
```
from ESL import ESLconnection
cmd = 'uuid_kill %s' % active_call # active_call comes from a ... | 2014/01/03 | [
"https://Stackoverflow.com/questions/20905702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030960/"
] | Short answer: `cmd` likely contains a Unicode string, which cannot be trivially converted to a `const char *`. The error message likely comes from a wrapper framework that automates writing Python bindings for C libraries, such as SWIG or ctypes. The framework knows what to do with a byte string, but punts on Unicode s... | I had similar problem, and I solved it by doing this:
`cmd = 'uuid_kill %s'.encode('utf-8')` | 8,172 |
28,431,765 | So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed...
I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this:
```
Open ... | 2015/02/10 | [
"https://Stackoverflow.com/questions/28431765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1381537/"
] | * OS: Win 10,
* Python 3.8.1
+ selenium==3.141.0
```
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path=r'TO\Your\Path\geckodriver.exe')
driver.get('https://www.google.com/')
# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.... | I tried for a very long time to duplicate tabs in Chrome running using action\_keys and send\_keys on body. The only thing that worked for me was an answer [here](https://stackoverflow.com/a/41633373/10488716). This is what my duplicate tabs def ended up looking like, probably not the best but it works fine for me.
``... | 8,173 |
27,767,937 | Ive been trying to figure this out all night with no luck. Im assuming that this will be a simple question for the more experienced programmer.
Im working on a canonical request that I can sign.
something like this:
```
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonica... | 2015/01/04 | [
"https://Stackoverflow.com/questions/27767937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4400330/"
] | So you want to not have "actual" newlines, but the escape character for newlines in your string? Just add a second slash to `'\n'` to escape it as well, `'\\n'`. Or prepend your strings with r to make them "raw"; in them the backslash is interpreted literally; `r'\n'` (commonly used for regular expressions).
```
canon... | As an alternative and more elegant way you can put your strings in a list and join them with escape the `\n` with add `\` to leading :
```
>>> l=['method', 'canonical_uri', 'canonical_querystring', 'canonical_headers']
>>> print '\\n'.join(l)
method\ncanonical_uri\ncanonical_querystring\ncanonical_headers
```
>
> ... | 8,183 |
14,206,760 | I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk.
In my `.ebextensions/python.config` file, I have set the following:
```
option_settings:
- namespace: aws:elasticbeanstalk:application:environment
option_name: ProductionBucket
value: s3-bucket-name
... | 2013/01/08 | [
"https://Stackoverflow.com/questions/14206760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165988/"
] | I was having the same problem.
Believe it or not, you have to commit the `.ebextensions` directory and all `*.config` files to version control before you deploy in order for them to show up as environment variables on the server.
In order to keep sensitive information out of version control, you can use a config file... | I know this is an old question but for those who still have the same question like I did here is the solution from AWS documentation: <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html>
>
> To configure environment properties in the Elastic Beanstalk console
>
>
> 1. Open... | 8,184 |
48,937,024 | I am going to write down this pseudocode in python:
```
if (i < .1):
doX()
elif (i < .3):
doY()
elif (i < .5):
doZ()
.
.
else:
doW()
```
The range of numbers may be 20, and each float number which shapes the constraints is read from a list. For the above example (shorter version), it is the list:
```
... | 2018/02/22 | [
"https://Stackoverflow.com/questions/48937024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8899386/"
] | ```
from bisect import *
a=[0.1, 0.3, 0.5, 1]
b=["a","b","c","d"]
print b[bisect_left(a,0.2)]
``` | Here's an answer that you should not use:
```
doX = lambda x: x + 1
doY = lambda x: x + 10
doZ = lambda x: x + 100
ranges = [0.1, 0.3, 0.5, 1]
functions = [doX, doY, doZ]
answer = lambda x: [func(x) for (low, high), func in zip(zip(ranges[:-1],ranges[1:]), function) if low <= x < high][0]
```
The point is, that g... | 8,194 |
63,815,087 | I'm porting some Python 2 legacy code and I have this class:
```
class myfile(file):
"Wrapper for file object whose read member returns a string buffer"
def __init__ (self, *args):
return file.__init__ (self, *args)
def read(self, size=-1):
return create_string_buffer(file.read(self, size)... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63815087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6271889/"
] | If another way is fine , you can try the below, it is a little dirty though (you can try optimizing it)
```
cols = ['name','color','amount']
u = df[df.columns.difference(cols)].join(df[cols].agg(dict,1).rename('d'))
v = (u.groupby(['cat1','cat2','cat3'])['d'].agg(list).reset_index("cat3"))
v = v.groupby(v.index).appl... | We can `groupby` on `cat1`, `cat2` and `cat3` and recursively build the dictionary based on the grouped categories:
```
def set_val(d, k, v):
if len(k) == 1:
d[k[0]] = v
else:
d[k[0]] = set_val(d.get(k[0], {}), k[1:], v)
return d
dct = {}
for k, g in df.groupby(['cat1', 'cat2', 'cat3']):
... | 8,197 |
21,962,250 | I have a string that hold a binary number as a string
```
string = '0b100111'
```
I want to have that value not be a string type but a value (pseudo-code)
```
bin(string) = 0b100111
```
Any pythoners know an easy way to do this?
It is all part of this code for a Codecademy: (After answer implemented)
```
def fl... | 2014/02/22 | [
"https://Stackoverflow.com/questions/21962250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2918785/"
] | What about calling `int` function with base `2`?
```
>>>s = '0b100111'
>>>b = int(s, 2)
>>>print b
39
``` | you can make it binary by putting a b before the quotes:
```
>>> s = b'hello'
>>> s.decode()
'hello'
``` | 8,200 |
9,787,741 | What is the equivalent of the following in python?
```
for (i=0; i<n; i++)
for (j=i+1; j<n; j++)
//do stuff with A[i], A[j]
```
Or in some sense, the following. It should also remove the element from A at the completion of each round of the loop.
```
for a in A:
for a' in A/{a}: #i.e. rest of the el... | 2012/03/20 | [
"https://Stackoverflow.com/questions/9787741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/408412/"
] | Since your two questions are different, here is solution for your second problem:
```
for i in xrange(len(A)):
for j in xrange(len(A)):
if i != j:
do_stuff(A[i], A[j])
```
or **using** `itertools` (I think using the included **batteries** is very pythonic!):
```
import itertools
for a, b in... | In the first for-loop, **enumerate()** walks through the array and makes the index,value of each element available to the second for-loop. In the second loop, **range()** makes j = i+1 --> len(a) available. At this point you'd have exactly what you need which is `i` & `j` to do your operation.
```
>>> a = [1,2,3,4]
>... | 8,202 |
9,403,415 | I'm using the great [quantities](http://pypi.python.org/pypi/quantities) package for Python. I would like to know how I can get at just the numerical value of the quantity, without the unit.
I.e., if I have
```
E = 5.3*quantities.joule
```
I would like to get at just the 5.3. I know I can simply divide by the "und... | 2012/02/22 | [
"https://Stackoverflow.com/questions/9403415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633318/"
] | `E.item()` seems to be what you want, if you want a Python float. `E.magnitude`, offered by tzaman, is a 0-dimensional NumPy array with the value, if you'd prefer that.
The documentation for `quantities` doesn't seem to have a very good API reference. | I believe `E.magnitude` gets you what you want. | 8,212 |
7,758,913 | How can I implement graph colouring in python using adjacency matrix? Is it possible? I implemented it using list. But it has some problems. I want to implement it using matrix. Can anybody give me the answer or suggestions to this? | 2011/10/13 | [
"https://Stackoverflow.com/questions/7758913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992874/"
] | Is it possible? Yes, of course. But are your problems with making Graphs, or coding algorithms that deal with them?
Separating the algorithm from the data type might make it easier for you. Here are a couple suggestions:
* create (or use) an abstract data type Graph
* code the coloring algorithm against the Graph int... | Implementing using adjacency is somewhat easier than using lists, as lists take a longer time and space. igraph has a quick method neighbors which can be used. However, with adjacency matrix alone, we can come up with our own graph coloring version which may not result in using minimum chromatic number. A quick strateg... | 8,214 |
34,567,484 | I have a list that has several days in it. Each day have several timestamps. What I want to do is to make a new list that only takes the start time and the end time in the list for each date.
I also want to delete the Character between the date and the time on each one, the char is always the same type of letter.
the t... | 2016/01/02 | [
"https://Stackoverflow.com/questions/34567484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738256/"
] | First of all, you should convert all your strings into proper dates, Python can work with. That way, you have a lot more control on it, also to change the formatting later. So let’s parse your dates using [`datetime.strptime`](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) in `list2`:
```
... | Because your data is ordered you just need to pull the first and last value from each group, you can use re.sub to remove the single letter replacing it with a space then split each date string just comparing the dates:
```
from re import sub
def grp(l):
it = iter(l)
prev = start = next(it).replace("A"," ")
... | 8,215 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.