qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
35,859,927 | For say in terminal I did `cd Desktop` you should know it moves you to that directory, but how do I do that in python but with use Desktop with `raw_input("")` to pick my command? | 2016/03/08 | [
"https://Stackoverflow.com/questions/35859927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your code structure is very unconventional and I suspect you're rather new to scheme/racket. Your procedure can be written in a much more idiomatic way.
The first criticism I'd probably make about your code is that it makes the assumption that the lists you're unzipping will only have 2 elements each.
* What about un... | It is combining the lists correctly, but it's not combining the correct lists.
Extracting the local definitions makes them testable in isolation:
```
(define (front a)
(if (null? a)
'()
(cons (car (car a)) (unzip (cdr a)))))
(define (back b)
(if (null? b)
'()
(cons (car (cdr (car b))) (un... |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | This usually happens when you're opening someone else's project after unzipping it and your current Android Studio Version is older to the version the project was compiled in.
The way to solve it is
1. Go to Help and about to see your android studio version
2. go to File>Project Structure> and set your Android Gradle... | Check the version of Android Studio, or the IDEA Plugin.
For example, Android Studio **4.0** and Android Plugin 10.**4.0** require a 4.0.x version of the Android tools.
Therefore in build.gradle, change e.g. `com.android.tools.build:gradle:4.2.0-beta2"` to `com.android.tools.build:gradle:4.0.2"`.
**Update:**
This d... |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | Check the version of Android Studio, or the IDEA Plugin.
For example, Android Studio **4.0** and Android Plugin 10.**4.0** require a 4.0.x version of the Android tools.
Therefore in build.gradle, change e.g. `com.android.tools.build:gradle:4.2.0-beta2"` to `com.android.tools.build:gradle:4.0.2"`.
**Update:**
This d... | The error message says:
>
> This version of the Android Support plugin for IntelliJ IDEA (or
> Android Studio) cannot open this project, please retry with version
> 4.2 or newer.
>
>
>
And as you can clearly see from the error message, it's happening because Android Studio (**also known as "Android Support Plugin... |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | **Simply update your android studio**
go to Help > check for updates > update and restart. | I have faced the same issue and it will resolve in two ways
1. Change the gradle version in *Project-Level* **build.gradle**
Earlier i have used below one
```
classpath 'com.android.tools.build:gradle:4.1.2'
```
Now changed with
```
classpath 'com.android.tools.build:gradle:4.2.1'
```
2. Update your Android Stu... |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | **kindly change your class path if you are using older version of android studio**
```
classpath 'com.android.tools.build:gradle:7.0.4'
```
**to**
```
classpath "com.android.tools.build:gradle:4.2.1"
```
**or remain the class path to 7.0.4 and update your android studio** | Change gradle version into build.gradel file (inside of app).
```
classpath "com.android.tools.build:gradle:4.0.2"
``` |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | Another way to update your studio is go to **File>Settings>Appearance and Behavior> System Settings> Updates>** Check "**Automatically check for updates**" box. Select your channel (**stable** for stable updates) and click **check now**. Wait once update is complete you can run your project. | in my case i change **project level of build.gradle**
classpath "com.android.tools.build:gradle:4.1.1"
and in **gradle-wrapper.properties**
distributionUrl=https://services.gradle.org/distributions/gradle-6.5-all.zip
you can easily fix this issue by changing this way,you can create a new project and just checked the... |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | In my case, the solution was simple, update Android Studio to the last version
(Bumblebee) | In my case I created the project in android preview version and when I opened the project in stable android studio I got this issue,
I updated the stable android studio to latest version and it asked me to update the project.
After this the problem was fixed. |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | **kindly change your class path if you are using older version of android studio**
```
classpath 'com.android.tools.build:gradle:7.0.4'
```
**to**
```
classpath "com.android.tools.build:gradle:4.2.1"
```
**or remain the class path to 7.0.4 and update your android studio** | I have faced the same issue and it will resolve in two ways
1. Change the gradle version in *Project-Level* **build.gradle**
Earlier i have used below one
```
classpath 'com.android.tools.build:gradle:4.1.2'
```
Now changed with
```
classpath 'com.android.tools.build:gradle:4.2.1'
```
2. Update your Android Stu... |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | If u r here because of Android Jetpack Compose, I have solved that problem by using the Arctic Fox Canary Build u can download it from here: <https://redirector.gvt1.com/edgedl/android/studio/ide-zips/2020.3.1.12/android-studio-2020.3.1.12-mac.zip> | Change gradle version into build.gradel file (inside of app).
```
classpath "com.android.tools.build:gradle:4.0.2"
``` |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | **Simply update your android studio**
go to Help > check for updates > update and restart. | Simply Update Android Studio or downgrade gradle version... |
62,678,802 | I have a client for whom I have created a program that utilizes a variety of data and machine learning packages. The client would like for the program to be easily run without installing any type of python environment. Is this possible?
I am assuming the best bet would be to transform the .py file into a .exe file but... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12512519/"
] | **Simply update your android studio**
go to Help > check for updates > update and restart. | In my case, the solution was simple, update Android Studio to the last version
(Bumblebee) |
55,125,763 | I'm trying to find the size, *in points*, of some text using Pillow in python. As I understand it, font sizes in points correspond to real physical inches on a target display or surface, with 72 points per inch. When I use Pillow's `textsize` method, I can find the size in pixels of some text rendered at a given font s... | 2019/03/12 | [
"https://Stackoverflow.com/questions/55125763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10686733/"
] | **TL;DR**
There is no implicit pixel density, because the Pillow documentation is incorrect. When you create the font, you are specifying the `size` in *pixels* even though the Pillow documentation says it's in points. It's actually doing all of these operations in pixels.
**More detail**
The Pillow documentation fo... | Image don't have an "implicit" pixel density, they just have different number of pixels. The size of anything measured in pixels will depend on the display device's DPI or dots-per-inch.
For example on a 100 DPI device, 12 pixels would appear to be 12/100 or 0.12 inches long. To convert inches to points, multiply the... |
39,980,658 | I am starting to work with the [Django REST framework](http://www.django-rest-framework.org/) for a mini-reddit project I already developed.
The problem is that I am stuck in this situation:
A `Minisub` is like a subreddit. It has, among others, a field named `managers` which is `ManyToMany` with `User`.
An `Ad` is ... | 2016/10/11 | [
"https://Stackoverflow.com/questions/39980658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595458/"
] | You may get it out of the serializer this way:
```
class YourModelSeializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=YourModel
def validate_myfield(self):
instance = getattr(self, 'instance', None)
...
``` | I believe that this is a job for the [permissions](http://www.django-rest-framework.org/api-guide/permissions/#permissions), if you are performing CRUD operations for inserting that into a database then u can have a permission class returns `True` if the user is a manager.
a permissions instance has access to the requ... |
33,722,333 | It is very nice and easy to run Python from the command line. Especially for testing purposes.
The only drawback is that after making a change in the script, I have to restart Python, do all the imports over again, create the objects and enter the parameters.
```
$ python
>>> from foo import bar
>>> from package.fil... | 2015/11/15 | [
"https://Stackoverflow.com/questions/33722333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5039579/"
] | You could consider turning your testing into an actual python script. which can be run like this, and then checking the output
```
$ python my_tests.py
```
However, a much better way would be to write some unit tests which you can run in a similar way. <https://docs.python.org/2/library/unittest.html>. The unittest ... | Use IPython with a [notebook](http://jupyter.org/) instead. Much better for interactive computing. |
33,722,333 | It is very nice and easy to run Python from the command line. Especially for testing purposes.
The only drawback is that after making a change in the script, I have to restart Python, do all the imports over again, create the objects and enter the parameters.
```
$ python
>>> from foo import bar
>>> from package.fil... | 2015/11/15 | [
"https://Stackoverflow.com/questions/33722333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5039579/"
] | Use IPython with a [notebook](http://jupyter.org/) instead. Much better for interactive computing. | Going for IPython as well. You can write a script which will enter an interactive shell at any point in any frame, for example:
```
import IPython
from foo import bar
from package.file import Class
c = Class
c.name = "John"
c.age = 33
c.function()
from datetime import timedelta, datetime
now = datetime.now().year()
ne... |
33,722,333 | It is very nice and easy to run Python from the command line. Especially for testing purposes.
The only drawback is that after making a change in the script, I have to restart Python, do all the imports over again, create the objects and enter the parameters.
```
$ python
>>> from foo import bar
>>> from package.fil... | 2015/11/15 | [
"https://Stackoverflow.com/questions/33722333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5039579/"
] | You could consider turning your testing into an actual python script. which can be run like this, and then checking the output
```
$ python my_tests.py
```
However, a much better way would be to write some unit tests which you can run in a similar way. <https://docs.python.org/2/library/unittest.html>. The unittest ... | Going for IPython as well. You can write a script which will enter an interactive shell at any point in any frame, for example:
```
import IPython
from foo import bar
from package.file import Class
c = Class
c.name = "John"
c.age = 33
c.function()
from datetime import timedelta, datetime
now = datetime.now().year()
ne... |
32,616,406 | I'm writing a python application that allows users to write their own plugins and extend the core functionality I provide -
```
$ tree project_dir/
.
βββ application.py
βββ plugins
βΒ Β βββ __init__.py
βΒ Β βββ example_plugin.py
βΒ Β βββ plugin1.py
βΒ Β βββ plugin2.py
βΒ Β βββ plugin3
βΒ Β βββ sounds
βΒ Β βΒ Β βββ tes... | 2015/09/16 | [
"https://Stackoverflow.com/questions/32616406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2417277/"
] | You can use the `__import__()` builtin to import the plugins, and then include the `register_plugin()` call in either the plugin file `example_plugin.py` or in `__init__.py` if it's a directory.
For example, let's say this is your project structure:
```
./
application.py
plugins_manager.py
plugins/
__init__.py
... | Strictly speaking I'd say there is no way to run code without it being invoked somehow. To do this, the running program can use
```
import importlib
```
so that once you've found the file you can import it with:
```
mod = importlib.import_module(import_name, pkg_name)
```
and if that file provides a known functio... |
50,716,680 | I have a file with contents like this (I don't wish to change the contents of the file in any way):
```
.
.
lines I don't need.
.
.
abc # I know where it starts and the data can be anything, not just abc
efg # I know where it ends.
.
.
lines I don't need.
.
.
```
I know the line numbers (index) from where ... | 2018/06/06 | [
"https://Stackoverflow.com/questions/50716680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6027453/"
] | I **guess** the compiler error that you see is referring to the fact that you are using `listener` into it's own defining context.
Try this for a change:
In UserManager:
```
func allUsers(completion:@escaping ([User])->Void) -> ListenerRegistration? {
return db.collection("users").addSnapshotListener { querySnap... | I think that *getDocument* instead of *addSnapshotListener* is what you are looking for.
Using this method the listener is automatically detached at the end of the request...
It will be something similar to
```
func allUsers(completion:@escaping ([User])->Void) {
db.collection("users").getDocument { querySnapshot, ... |
47,747,516 | I hope i will get help here. I'm writing program who will read and export to txt 'devices live logging events' every two minutes. Everything works fine until i generate exe file. What is more interesting, program works on my enviroment(geckodriver and python libraries installed), but does not work on computers without ... | 2017/12/11 | [
"https://Stackoverflow.com/questions/47747516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9082203/"
] | The problem is that the `deny from all` denies **everything** including the error documents.
But hey, .htaccess files work in cascade, so you can
1. create a subfolder in your web root (assuming your webroot is `/www` - `/www/errordocs`
2. => in there put your ErrorDocuments like 403.html etc.
3. create another `.hta... | yes I can help a Little bit to solve permission issue , I was encountered by same problem , You just need to give permission +777 to your /app
if you have linux machine , go inside your web folder
```
sudo chmod -R +777 /app
```
and do the same to any other folders you write there
and for 403 error I think yo... |
23,006,023 | I'm trying to install pyOpenSSL using pip, python version is 2.7, OS is linux.
After pyOpenSSL installed, when I tried to import the module in python, I got the following error:
```
Python 2.7.5 (default, Jun 27 2013, 03:17:39)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "l... | 2014/04/11 | [
"https://Stackoverflow.com/questions/23006023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/855643/"
] | This is because low version pyopenssl has not defined SSL\_OP\_NO\_TICKETγ
clone the latest pyopenssl from <https://github.com/pyca/pyopenssl.git> and install it, then that'll be fine. no thks. | The fix is described here:
<https://github.com/pyca/pyopenssl/issues/130>
Indeed, you can apply it manually (not really recommended, but easy)
Or download archive from github
The link to the fix: <https://github.com/pyca/pyopenssl/commit/e7a6939a22a4290fff7aafe39dd0db85157d5e05>
And the fix applied to SSL.py
```
-OP... |
32,156,008 | I am using Calendar and recieve list of lists of lists of tuples from it
```
calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1))
```
Output is:
```
[[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1),...
```
I w... | 2015/08/22 | [
"https://Stackoverflow.com/questions/32156008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386321/"
] | Python has a function to flatten one nesting level. It goes by the unfortunate name `itertools.chain.from_iterable()`. If you apply it three times, it will flatten three levels:
```
import itertools
flatten1 = itertools.chain.from_iterable
flattened_data = flatten1(flatten1(flatten1(your_data)))
for a, b in flattened_... | Try this:
```
def flatten(x):
if isinstance(x, list):
return [a for i in x for a in flatten(i)]
else:
return [x]
```
This answer is similar to this: <https://stackoverflow.com/a/2158522/1628832> but checking for the specific `list` type instead of an iterable.
For optimization, memory effic... |
32,156,008 | I am using Calendar and recieve list of lists of lists of tuples from it
```
calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1))
```
Output is:
```
[[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1),...
```
I w... | 2015/08/22 | [
"https://Stackoverflow.com/questions/32156008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386321/"
] | Python has a function to flatten one nesting level. It goes by the unfortunate name `itertools.chain.from_iterable()`. If you apply it three times, it will flatten three levels:
```
import itertools
flatten1 = itertools.chain.from_iterable
flattened_data = flatten1(flatten1(flatten1(your_data)))
for a, b in flattened_... | If you are using Python 2, the following one liner solution will currently work:
```
import compiler, itertools
lpairs = [[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1)]]]]
print [(x,y) for x,y in itertools.izip(*[iter(compile... |
32,156,008 | I am using Calendar and recieve list of lists of lists of tuples from it
```
calendar.Calendar.yeardays2calendar(calendar.Calendar(), year, 1))
```
Output is:
```
[[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1),...
```
I w... | 2015/08/22 | [
"https://Stackoverflow.com/questions/32156008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386321/"
] | Try this:
```
def flatten(x):
if isinstance(x, list):
return [a for i in x for a in flatten(i)]
else:
return [x]
```
This answer is similar to this: <https://stackoverflow.com/a/2158522/1628832> but checking for the specific `list` type instead of an iterable.
For optimization, memory effic... | If you are using Python 2, the following one liner solution will currently work:
```
import compiler, itertools
lpairs = [[[[(0, 0), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6)], [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)], [(12, 0), (13, 1)]]]]
print [(x,y) for x,y in itertools.izip(*[iter(compile... |
56,721,424 | I have two pandas columns, both converted to datetime format, and can't subtract one from the other.
```
df['date_listed'] = pd.to_datetime(df['date_listed'], errors='coerce').dt.floor('d')
df['date_unconditional'] = pd.to_datetime(df['date_unconditional'], errors='coerce').dt.floor('d')
print df['date_listed'][:5]
... | 2019/06/23 | [
"https://Stackoverflow.com/questions/56721424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4718221/"
] | You could use [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) operations and then map to recombine.
```js
data = [
['Jenny', 'id100... | Try this:
```
function addingRows() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet1');
var rg=sh.getRange(2, 1, sh.getLastRow()-1,sh.getLastColumn());
var vA=rg.getValues();
var vB=[];
for(var i=0;i<vA.length;i++) {
vt=vA[i].slice(3);
for(var j=0;j<vt.length;j++) {
vB.pu... |
4,192,744 | If I enter Baltic characters in textctrl and click button **test1** I have an error
```
"InicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
ordinal not in range(128)"
```
Button **test2** works fine.
```
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import wx
class MyFra... | 2010/11/16 | [
"https://Stackoverflow.com/questions/4192744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/509289/"
] | The [documentation](http://www.novell.com/documentation/suse91/suselinux-adminguide/html/ch12s03.html) for SUSE Linux provides a good explanation of why Linux is booted with a RAMDisk:
>
> As soon as the Linux kernel has been
> booted and the root file system (/)
> mounted, programs can be run and
> further kernel... | The reason that most Linux distributions use a ramfs (initramfs) when booting, is because its contents can be included in the kernel file, or provided by the bootloader. They are therefore available immediately at boot, without the kernel having to load them from somewhere.
That allows the kernel to run userspace prog... |
62,026,013 | I have created a python script which do birthday wish to a person automatically when birthdate is arrive. I added this script on window start up but it run every time when i start my pc and do birthday wish to person also. I want to run that script only once a day. What should i do? | 2020/05/26 | [
"https://Stackoverflow.com/questions/62026013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12942284/"
] | Try this at the start of the file:
```
import datetime
actualday = datetime.datetime.today().day # get the actual day
actualmonth = datetime.datetime.today().month # get the actual month
bday = 1 # day of birthday
bmonth = 1 # month of birthday
if actualday == bday and actualmonth == bmonth :
# code
```
... | You can run this program when the system boot [How to start a python file while Windows starts?](https://stackoverflow.com/questions/4438020/how-to-start-a-python-file-while-windows-starts)
And after that, you need check the time of when the system started like:
```
import datetime
dayToday = datetime.datetime.today(... |
50,225,903 | I am trying a POC running a python script in a back-end implemented in PHP. The web server is Apache in a Docker container.
This is the PHP code:
```
$command = escapeshellcmd('/usr/local/test/script.py');
$output = shell_exec($command);
echo $output;
```
When I execute the python script using the ... | 2018/05/08 | [
"https://Stackoverflow.com/questions/50225903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4681701/"
] | To start is is incredibly bad practice to have relative paths in *any* scripting environment. Start by rewriting your code to use a full path such as `/usr/local/test/script.py` and `/tmp/testfile.txt`. My guess is your script is attempting to write to a different spot than you think it is.
When you *know* exactly whe... | I believe the problem is that you are trying to write to an existing file in the `/tmp/` directory. Typically `/tmp/` [will have the sticky permission bit set.](https://unix.stackexchange.com/questions/71622/what-are-correct-permissions-for-tmp-i-unintentionally-set-it-all-public-recu) That means that only the owner of... |
73,523,116 | i was wondering how i can get the product dimensions and weight from an amazon page. this is the page: [https://www.amazon.com/Vic-Firth-American-5B-Drumsticks/dp/B0002F73Z8/ref=psdc\_11966431\_t1\_B0064RNNP2?th=1](https://rads.stackoverflow.com/amzn/click/com/B0002F73Z8)
there is a place where it says
item weight: 3.... | 2022/08/29 | [
"https://Stackoverflow.com/questions/73523116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17215378/"
] | What you need to do is first install selenium in your computer.
Then after setting it up you can go to the page and click on inspect.Then you search what you need to scrap after that copy the XPath .
You can Follow [Selenium with Python](https://selenium-python.readthedocs.io/) Docs or watch any tutorial for more detai... | I would advise you look into requests, Beautiful Soup and Selenium. These are useful libraries/tools for web scraping. Also I believe Amazon specifically blocks a lot of scraping requests so you will need to mimic a regular users browser for it to work. |
73,523,116 | i was wondering how i can get the product dimensions and weight from an amazon page. this is the page: [https://www.amazon.com/Vic-Firth-American-5B-Drumsticks/dp/B0002F73Z8/ref=psdc\_11966431\_t1\_B0064RNNP2?th=1](https://rads.stackoverflow.com/amzn/click/com/B0002F73Z8)
there is a place where it says
item weight: 3.... | 2022/08/29 | [
"https://Stackoverflow.com/questions/73523116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17215378/"
] | This will get what you want done when it comes to scraping a webpage for specific content in the context of your question. From this point you'd want to loop over a list of desired URLs. Hope this helps :)
```
#!/bin/python3
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Macintos... | I would advise you look into requests, Beautiful Soup and Selenium. These are useful libraries/tools for web scraping. Also I believe Amazon specifically blocks a lot of scraping requests so you will need to mimic a regular users browser for it to work. |
35,173,118 | I am using httplib in my python code and have following mentioned.
`import httplib
httplib.HTTPConnection.debuglevel = 2`
I do get all the info I need but httplib library is printing it on console.
I do not know any way by which I can get all those logs in a log file and not on console. | 2016/02/03 | [
"https://Stackoverflow.com/questions/35173118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2606665/"
] | If you take a look at the httplib source (<https://hg.python.org/cpython/file/2.7/Lib/httplib.py>) you'll see the debugging is done via print statements, so you can't use logging configuration to intercept the logs, and because print is a statement, you can't monkeypatch it to do your bidding.
You have a few options:
... | Maybe try this:
```
f = open('output.txt','w')
sys.stdout = f
```
Redirecting stdout to a file. |
40,518,865 | I am trying to figure out how to use a barely documented feature of a poorly documented API. I have distilled the chunk of code that is giving me trouble down to this for simplicity:
```
def build_custom_args(args):
custom_args = {}
for key in args:
custom_args.update(key.get())
print(c... | 2016/11/10 | [
"https://Stackoverflow.com/questions/40518865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197234/"
] | Well... I found this in the github link you have provided
```
class Email(object):
# code...
def get(self):
```
Matter of fact, a lot of those classes have get methods.
Since Python is duck typed, there isn't really a way to determine what object is correct, but you're just building a dictionary, so sho... | AFAIK the only class with a `get` [method that can take zero arguments](https://docs.python.org/3/library/queue.html?highlight=get#queue.Queue.get) is a `Queue`.
Which in your example is probably a `Queue` of `dict`s |
8,159,414 | I'm trying to debug my [DJango Paypal IPN integration](https://stackoverflow.com/questions/8145907/what-might-cause-the-django-ipn-tool-to-fail-when-posting-to-a-django-based-rece) but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 err... | 2011/11/16 | [
"https://Stackoverflow.com/questions/8159414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] | given that you are running a pre-alpha version of django, I would recomment asking this question on the django user list <https://groups.google.com/group/django-users> | have a look at [django-sentry](http://readthedocs.org/docs/sentry/en/latest/index.html)
it logs 500 errors (also supports regular logging), making the dynamic "orange 500 pages" browsable after the fact. this is especially useful when you never get the original error page, e.g. when using ajax or remote apis like your... |
8,159,414 | I'm trying to debug my [DJango Paypal IPN integration](https://stackoverflow.com/questions/8145907/what-might-cause-the-django-ipn-tool-to-fail-when-posting-to-a-django-based-rece) but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 err... | 2011/11/16 | [
"https://Stackoverflow.com/questions/8159414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] | Another thing to try is to launch a simple SMTP server on your machine.
```
python -m smtpd -n -c DebuggingServer localhost:1025
```
Which will output on your console all emails headers and body.
Make sure localhost and the port 1025 correpond to what you have in your settings.py, respectively in EMAIL\_HOST and EMA... | have a look at [django-sentry](http://readthedocs.org/docs/sentry/en/latest/index.html)
it logs 500 errors (also supports regular logging), making the dynamic "orange 500 pages" browsable after the fact. this is especially useful when you never get the original error page, e.g. when using ajax or remote apis like your... |
8,159,414 | I'm trying to debug my [DJango Paypal IPN integration](https://stackoverflow.com/questions/8145907/what-might-cause-the-django-ipn-tool-to-fail-when-posting-to-a-django-based-rece) but I'm struggling. The Django dev server reports a 500 error to the console (but no other details) and the IPN test tool reports a 500 err... | 2011/11/16 | [
"https://Stackoverflow.com/questions/8159414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15369/"
] | Another thing to try is to launch a simple SMTP server on your machine.
```
python -m smtpd -n -c DebuggingServer localhost:1025
```
Which will output on your console all emails headers and body.
Make sure localhost and the port 1025 correpond to what you have in your settings.py, respectively in EMAIL\_HOST and EMA... | given that you are running a pre-alpha version of django, I would recomment asking this question on the django user list <https://groups.google.com/group/django-users> |
48,373,718 | I have a spring boot web application without registration page or allowing users to register. I'm manually creating passwords using another web spring application which ones gives me encoded password on request.
Using the below link to generate the encoded password: <http://www.baeldung.com/spring-security-registration... | 2018/01/22 | [
"https://Stackoverflow.com/questions/48373718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1550594/"
] | I was facing the same problem, but the following worked for me:
```
bcrypt.gensalt(rounds = 10, prefix=b"2a")
```
This seems to be in sync with the bean `BCryptPasswordEncoder` in SpringBoot :) | BCrypt is a module in python which can be installed using `pip install bcrypt`.
The equivalent to BCryptPasswordEncoder() would require importing bcrypt as `import bcrypt` and then executing `bcrypt.hashpw(password, bcrypt.gensalt())` to encrypt a password.
Source: <https://pypi.python.org/pypi/bcrypt/3.1.0> |
34,030,599 | Hoping you can help me figure this one out. I'm slogging through the [Heroku 'Getting Started with Python'](https://devcenter.heroku.com/articles/getting-started-with-python#declare-app-dependencies) page where you install the necessary dependencies to run an app locally. It all works well up until the 2nd to last step... | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5266746/"
] | pg\_config is part of postgresql ( <http://www.postgresql.org/docs/8.1/static/app-pgconfig.html> ).
So you need to install postgresql. | ```
brew install postgresql
```
resolves this issue on macOS |
34,030,599 | Hoping you can help me figure this one out. I'm slogging through the [Heroku 'Getting Started with Python'](https://devcenter.heroku.com/articles/getting-started-with-python#declare-app-dependencies) page where you install the necessary dependencies to run an app locally. It all works well up until the 2nd to last step... | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5266746/"
] | pg\_config is part of postgresql ( <http://www.postgresql.org/docs/8.1/static/app-pgconfig.html> ).
So you need to install postgresql. | I have overcame this issue defining a environment variable HEROKU and putting the following lines at the end of settings.py
```
if config('HEROKU', cast=bool, default=False):
import django_heroku
django_heroku.settings(locals())
```
As Heroku use the buildpack: heroku/python, there is no additional configur... |
34,030,599 | Hoping you can help me figure this one out. I'm slogging through the [Heroku 'Getting Started with Python'](https://devcenter.heroku.com/articles/getting-started-with-python#declare-app-dependencies) page where you install the necessary dependencies to run an app locally. It all works well up until the 2nd to last step... | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5266746/"
] | ```
brew install postgresql
```
resolves this issue on macOS | I have overcame this issue defining a environment variable HEROKU and putting the following lines at the end of settings.py
```
if config('HEROKU', cast=bool, default=False):
import django_heroku
django_heroku.settings(locals())
```
As Heroku use the buildpack: heroku/python, there is no additional configur... |
68,565,656 | I'm using Selenium to automate a report but when I download it the last number changes as if it were a sequence for example: 0001849191, 0001849192 and so on. I can't make it keep following the order because if someone else generates the report it can skip a number and python doesn't understand that it followed the seq... | 2021/07/28 | [
"https://Stackoverflow.com/questions/68565656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16541350/"
] | You can use the glob and os module to get the latest file.First import os, glob modules i.e:
```
import os
import glob
```
Then you define path.My example gives path for any ones Download folder.
```
home = os.path.expanduser('~')
path = os.path.join(home, 'Downloads')
```
"\*" is necessary.
```
path_a = path + ... | First off, `'\'` is an invalid string, because `\` is used for escape sequences. `'\\'` would get you a string with a single backslash in it.
But more than that, it's best not to construct paths this way; you should use [os.path.join](https://docs.python.org/3/library/os.path.html#os.path.join) to create paths out of ... |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple:
* Find the current position within the file using `tell`.
* Perform a `read` (or `writ... | You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation
For example
```
from itertools import tee
import contextlib
from StringIO import StringIO
s = '''\
cat1
cat2
cat3
'''
... |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation
For example
```
from itertools import tee
import contextlib
from StringIO import StringIO
s = '''\
cat1
cat2
cat3
'''
... | Manually doing it is not that hard:
```
f = open('file.txt')
line = f.readline()
print line
>>> cat1
# the calculation is: - (length of string + 1 because of the \n)
# the second parameter is needed to move from the actual position of the buffer
f.seek((len(line)+1)*-1, 1)
line = f.readline()
print line
>>> cat1
```
... |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation
For example
```
from itertools import tee
import contextlib
from StringIO import StringIO
s = '''\
cat1
cat2
cat3
'''
... | The [`more_itertools`](https://github.com/erikrose/more-itertools) library offers a `peekable` class that allows you to `peek()` ahead without advancing an iterable.
```
with open("file.txt", "r") as f:
p = mit.peekable(f.readlines())
p.peek()
# 'cat1\n'
next(p)
# 'cat1\n'
```
We can view the next line before ... |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | You could use wrap the file up with [itertools.tee](http://docs.python.org/2/library/itertools.html#itertools.tee) and get back two iterators, bearing in mind the caveats stated in the documentation
For example
```
from itertools import tee
import contextlib
from StringIO import StringIO
s = '''\
cat1
cat2
cat3
'''
... | Solutions with `tell()`/`seek()` will not work with `stdin` and other iterators. More generic implementation can be as simple as this:
```
class lookahead_iterator(object):
__slots__ = ["_buffer", "_iterator", "_next"]
def __init__(self, iterable):
self._buffer = []
self._iterator = iter(itera... |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple:
* Find the current position within the file using `tell`.
* Perform a `read` (or `writ... | Manually doing it is not that hard:
```
f = open('file.txt')
line = f.readline()
print line
>>> cat1
# the calculation is: - (length of string + 1 because of the \n)
# the second parameter is needed to move from the actual position of the buffer
f.seek((len(line)+1)*-1, 1)
line = f.readline()
print line
>>> cat1
```
... |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple:
* Find the current position within the file using `tell`.
* Perform a `read` (or `writ... | The [`more_itertools`](https://github.com/erikrose/more-itertools) library offers a `peekable` class that allows you to `peek()` ahead without advancing an iterable.
```
with open("file.txt", "r") as f:
p = mit.peekable(f.readlines())
p.peek()
# 'cat1\n'
next(p)
# 'cat1\n'
```
We can view the next line before ... |
16,840,554 | What's a pythonic approach for reading a line from a file but not advancing where you are in the file?
For example, if you have a file of
```
cat1
cat2
cat3
```
and you do `file.readline()` you will get `cat1\n` . The next `file.readline()` will return `cat2\n` .
Is there some functionality like `file.some_functi... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16840554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431282/"
] | As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python `file` objects support `seek` and `tell` methods for jumping around within a file. So, the process is very simple:
* Find the current position within the file using `tell`.
* Perform a `read` (or `writ... | Solutions with `tell()`/`seek()` will not work with `stdin` and other iterators. More generic implementation can be as simple as this:
```
class lookahead_iterator(object):
__slots__ = ["_buffer", "_iterator", "_next"]
def __init__(self, iterable):
self._buffer = []
self._iterator = iter(itera... |
68,877,064 | I'm pretty new in python and I'm having trouble doing this double summation.

I already tried using
```
x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))
```
and using 2 for loops but nothing seens to work | 2021/08/21 | [
"https://Stackoverflow.com/questions/68877064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16722883/"
] | The solution is incredibly easy -
Instead of using just the relevant part of the Alchemy key:
40Oo3XScVabXXXX8sePUEp9tb90gXXXX
I used the whole URL:
<https://eth-rinkeby.alchemyapi.io/v2/40Oo3XScVabXXXX8sePUEp9tb90gXXXX> | I had the same experience but when using hardhat not truffle.My internet connection was ok,try switching from Git bash to terminal(CMD).Use a completely new terminal avoid Gitbash and powershell. |
68,877,064 | I'm pretty new in python and I'm having trouble doing this double summation.

I already tried using
```
x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))
```
and using 2 for loops but nothing seens to work | 2021/08/21 | [
"https://Stackoverflow.com/questions/68877064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16722883/"
] | The solution is incredibly easy -
Instead of using just the relevant part of the Alchemy key:
40Oo3XScVabXXXX8sePUEp9tb90gXXXX
I used the whole URL:
<https://eth-rinkeby.alchemyapi.io/v2/40Oo3XScVabXXXX8sePUEp9tb90gXXXX> | Remove the function wrapper from provider inside the network configuration.
```
ropsten_infura: {
provider: new HDWalletProvider({
mnemonic: {
phrase: mnemonic
},
providerOrUrl: `https://ropsten.infura.io/v3/${project_id}`,
addressIndex
}),
network_id: 3
}
``` |
68,877,064 | I'm pretty new in python and I'm having trouble doing this double summation.

I already tried using
```
x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))
```
and using 2 for loops but nothing seens to work | 2021/08/21 | [
"https://Stackoverflow.com/questions/68877064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16722883/"
] | I also ran into this error when following the same tutorial.
I use Alchemy (not Infura), and the issue was my API\_KEY.
In other tutorials I've followed, the scripts require the full alchemy API Key (ex. "https://eth-rinkeby.alchemyapi.io/v2/<**random-key**>").
So, when I was following this tutorial, that is what I ... | I had the same experience but when using hardhat not truffle.My internet connection was ok,try switching from Git bash to terminal(CMD).Use a completely new terminal avoid Gitbash and powershell. |
68,877,064 | I'm pretty new in python and I'm having trouble doing this double summation.

I already tried using
```
x = sum(sum((math.pow(j, 2) * (k+1)) for k in range(1, M-1)) for j in range(N))
```
and using 2 for loops but nothing seens to work | 2021/08/21 | [
"https://Stackoverflow.com/questions/68877064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16722883/"
] | I also ran into this error when following the same tutorial.
I use Alchemy (not Infura), and the issue was my API\_KEY.
In other tutorials I've followed, the scripts require the full alchemy API Key (ex. "https://eth-rinkeby.alchemyapi.io/v2/<**random-key**>").
So, when I was following this tutorial, that is what I ... | Remove the function wrapper from provider inside the network configuration.
```
ropsten_infura: {
provider: new HDWalletProvider({
mnemonic: {
phrase: mnemonic
},
providerOrUrl: `https://ropsten.infura.io/v3/${project_id}`,
addressIndex
}),
network_id: 3
}
``` |
63,247,247 | I downloaded pyttsx3 in command prompt
I have a big error
this the code:
```
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
```
output error:
>
>
> >
> >
> > >
> > >
> >
> >
> >
>
>
>
'''
= RESTART: C:\Users\RAMS\AppData\Local\Programs\Python\Python38\te... | 2020/08/04 | [
"https://Stackoverflow.com/questions/63247247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14047733/"
] | Looks like the Vercel docs are currently outdated (AWS SDK V2 instead of V3). You can pass the credentials object to the AWS service when you instantiate it. Use an environment variable that is not reserved by adding the name of your app to it for example.
*.env.local*
```
YOUR_APP_AWS_ACCESS_KEY_ID=[your key]
YOUR_A... | If I'm not mistaken, you want to make `AWS_ACCESS_KEY_ID` into a runtime variable as well. Currently, it is a build time variable, which won't be accessible in your node application.
```
// replace this
env: {
//..others
AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID
},
// with this
module.exports = {
... |
63,247,247 | I downloaded pyttsx3 in command prompt
I have a big error
this the code:
```
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
```
output error:
>
>
> >
> >
> > >
> > >
> >
> >
> >
>
>
>
'''
= RESTART: C:\Users\RAMS\AppData\Local\Programs\Python\Python38\te... | 2020/08/04 | [
"https://Stackoverflow.com/questions/63247247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14047733/"
] | Looks like the Vercel docs are currently outdated (AWS SDK V2 instead of V3). You can pass the credentials object to the AWS service when you instantiate it. Use an environment variable that is not reserved by adding the name of your app to it for example.
*.env.local*
```
YOUR_APP_AWS_ACCESS_KEY_ID=[your key]
YOUR_A... | are you possibly hosting this app via vercel?
As per vercel docs, some env variables are reserved by vercel.
<https://vercel.com/docs/concepts/projects/environment-variables#reserved-environment-variables>
AWS\_ACCESS\_KEY\_ID
AWS\_SECRET\_ACCESS\_KEY
Maybe that's the reason why it is not getting those env vars
I ... |
31,264,522 | I've made a simple combobox in python using Tkinter, I want to retrieve the value selected by the user. After searching, I think I can do this by binding an event of selection and call a function that will use something like box.get(), but this is not working. When the program starts the method is automatically called ... | 2015/07/07 | [
"https://Stackoverflow.com/questions/31264522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018299/"
] | I've figured out what's wrong in the code.
First, as James said the brackets should be removed when binding justamethod to the combobox.
Second, regarding the type error, this is because justamethod is an event handler, so it should take two parameters, self and event, like this,
```
def justamethod (self, event)... | ```
from tkinter import ttk
from tkinter import messagebox
from tkinter import Tk
root = Tk()
root.geometry("400x400")
#^ width - heghit window :D
cmb = ttk.Combobox(root, width="10", values=("prova","ciao","come","stai"))
#cmb = Combobox
class TableDropDown(ttk.Combobox):
def __init__(self, parent):
se... |
70,461,032 | How do I get a user keyboard input with python and print the name of that key ?
e.g:
>
> user clicked on "SPACE" and output is "SPACE"
> user clicked on "CTRL" and output is "CTRL".
>
>
>
for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to... | 2021/12/23 | [
"https://Stackoverflow.com/questions/70461032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17408857/"
] | `pygame` provides a function for getting the name of the key pressed:
[`pygame.key.name`](https://www.pygame.org/docs/ref/key.html#pygame.key.name)
And so you can use it to get the name of the key, there is no need to use a dictionary for this:
```py
import pygame
pygame.init()
screen = pygame.display.set_mode((500... | ```
pip install keyboard
import keyboard #use keyboard module
while True:
if keyboard.is_pressed('SPACE'):
print('You pressed SPACE!')
break
elif keyboard.is_pressed("ENTER"):
print("You pressed ENTER.")
break
``` |
70,461,032 | How do I get a user keyboard input with python and print the name of that key ?
e.g:
>
> user clicked on "SPACE" and output is "SPACE"
> user clicked on "CTRL" and output is "CTRL".
>
>
>
for better understanding i'm using pygame libary. and i built setting controller for my game. its worked fine but i'm able to... | 2021/12/23 | [
"https://Stackoverflow.com/questions/70461032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17408857/"
] | `pygame` provides a function for getting the name of the key pressed:
[`pygame.key.name`](https://www.pygame.org/docs/ref/key.html#pygame.key.name)
And so you can use it to get the name of the key, there is no need to use a dictionary for this:
```py
import pygame
pygame.init()
screen = pygame.display.set_mode((500... | Use `keyboard` module
```py
import keyboard
while True:
print(f"You pressed {keyboard.get_hotkey_name()})
``` |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | Following mewahl's comment I've added to my .bashrc (I use bash):
>
> export PROJ\_LIB=/path/to/your/instalation/of/anaconda/**share/proj/**
>
>
>
and now basemap (and others work). | I faced same problem. I installed anaconda and install conda install -c anaconda basemap.
I used Anaconda built in IDE named "Spyder".
Spyder is better than pycharm. only problem with spyder is lack of intellisense.
I solved problem of Proj4 by setting path.
Other problem kernel restarting when loading of .json larg... |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | This seems to be a common issue. There are several bug reports about it
* [basemap/issues/419](https://github.com/matplotlib/basemap/issues/419),
* [https://github.com/matplotlib/basemap/issues/428](https://github.com/conda-forge/basemap-feedstock/issues/30)
* [basemap/issues/428](https://github.com/matplotlib/basema... | I faced same problem. I installed anaconda and install conda install -c anaconda basemap.
I used Anaconda built in IDE named "Spyder".
Spyder is better than pycharm. only problem with spyder is lack of intellisense.
I solved problem of Proj4 by setting path.
Other problem kernel restarting when loading of .json larg... |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | For Windows 10 with Anaconda + Python 3.71 (and I'm sure other Python 3 versions and Windows 7/8), you can tell Basemap where Proj4's "epsg" file is to succeed. I don't have an "environment" or whatever because it's too much work to figure out - so I didn't have an anaconda\share\proj area (as far as I could discern wh... | Following mewahl's comment I've added to my .bashrc (I use bash):
>
> export PROJ\_LIB=/path/to/your/instalation/of/anaconda/**share/proj/**
>
>
>
and now basemap (and others work). |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | This worked for me:
```
import os
os.environ["PROJ_LIB"] = os.path.join(os.environ["CONDA_PREFIX"], "share", "proj")
```
This extends @Yusuf Baktir 's answer by omitting hard-coding the path to the epsg file. This way the code works on any machine that has conda installed (and activated of course). | I was not able to solve this problem but I was able to find an alternate, use CartoPy.
basemap is being maintained for python 2.7 users.
CartoPy is a better alternative |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | This seems to be a common issue. There are several bug reports about it
* [basemap/issues/419](https://github.com/matplotlib/basemap/issues/419),
* [https://github.com/matplotlib/basemap/issues/428](https://github.com/conda-forge/basemap-feedstock/issues/30)
* [basemap/issues/428](https://github.com/matplotlib/basema... | I was not able to solve this problem but I was able to find an alternate, use CartoPy.
basemap is being maintained for python 2.7 users.
CartoPy is a better alternative |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | You have to set the path of Proj lib as in newer version , this path has been replaced.
Write below two lines of code before importing matplot\_toolkits
```
### For Window's Users
import os
os.environ['PROJ_LIB'] = r'C:\Users\XXXXX\Anaconda3\pkgs\proj4-5.2.0-
ha925a31_1\Library\share'
```
To f... | Proj4 easy solution to fix on pycharm is goto setting-> project interpreter -> + -> write proj4 in the search field and install. |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | The answer is from Github and it worked for me.
```
import os
import conda
conda_file_dir = conda.__file__
conda_dir = conda_file_dir.split('lib')[0]
proj_lib = os.path.join(os.path.join(conda_dir, 'share'), 'proj')
os.environ["PROJ_LIB"] = proj_lib
from mpl_toolkits.basemap import Basemap
``` | I faced same problem. I installed anaconda and install conda install -c anaconda basemap.
I used Anaconda built in IDE named "Spyder".
Spyder is better than pycharm. only problem with spyder is lack of intellisense.
I solved problem of Proj4 by setting path.
Other problem kernel restarting when loading of .json larg... |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | Following mewahl's comment I've added to my .bashrc (I use bash):
>
> export PROJ\_LIB=/path/to/your/instalation/of/anaconda/**share/proj/**
>
>
>
and now basemap (and others work). | Proj4 easy solution to fix on pycharm is goto setting-> project interpreter -> + -> write proj4 in the search field and install. |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | You have to set the path of Proj lib as in newer version , this path has been replaced.
Write below two lines of code before importing matplot\_toolkits
```
### For Window's Users
import os
os.environ['PROJ_LIB'] = r'C:\Users\XXXXX\Anaconda3\pkgs\proj4-5.2.0-
ha925a31_1\Library\share'
```
To f... | I was not able to solve this problem but I was able to find an alternate, use CartoPy.
basemap is being maintained for python 2.7 users.
CartoPy is a better alternative |
52,295,117 | I tried to use Basemap package to plot a map by PyCharm, but I got something wrong with
```
from mpl_toolkits.basemap import Basemap`
```
And the Traceback as followed:
```
Traceback (most recent call last):
File "/Users/yupeipei/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in... | 2018/09/12 | [
"https://Stackoverflow.com/questions/52295117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9101918/"
] | This worked for me:
```
import os
os.environ["PROJ_LIB"] = os.path.join(os.environ["CONDA_PREFIX"], "share", "proj")
```
This extends @Yusuf Baktir 's answer by omitting hard-coding the path to the epsg file. This way the code works on any machine that has conda installed (and activated of course). | This seems to be a common issue. There are several bug reports about it
* [basemap/issues/419](https://github.com/matplotlib/basemap/issues/419),
* [https://github.com/matplotlib/basemap/issues/428](https://github.com/conda-forge/basemap-feedstock/issues/30)
* [basemap/issues/428](https://github.com/matplotlib/basema... |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | I got this problem while testing lambda function.
What worked for me was formatting JSON. | For me, the issue was that I had set the wrong default region environment key. |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | I had this error simply because I had a typo in the role ARN. I really wish the error was more explicit and said something along the lines of "this role doesn't exist", but alas. | I was running into this error with terraform and needed to add an assume role policy and apply it to the role that lambda assumes.
```
data "aws_iam_policy_document" "lambda_assume_role_policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = [
... |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | I got this problem while testing lambda function.
What worked for me was formatting JSON. | I am just learning to use the AWS CLI and ran into this issue.
I am using a series of PowerShell scripts to deploy an entire AWS architecture. My **createRole.ps1** script contains:
```
aws iam create-role `
--role-name $roleName `
--assume-role-policy-document file://myRoleTrustPolicy.json
```
The file **myRoleTr... |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | I'm also encountering this error. Have not got a definitive answer (yet) but figured I'd pass along a couple of hints that may help you and/or anyone else hitting this problem.
A) If you build the Role ARN by putting together your account ID and role name, I think the account ID needs to be without any dashes
B) If y... | For me, the issue was that I had an incomplete name for the role. I set
```
--role arn:aws:iam::000000000000:role/MyRoleName
```
when it should have been
```
--role arn:aws:iam::000000000000:role/service-role/MyRoleName
```
*(of course my aws id isn't actually 000000000000)*
I discovered this by running
```
aw... |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | I am just learning to use the AWS CLI and ran into this issue.
I am using a series of PowerShell scripts to deploy an entire AWS architecture. My **createRole.ps1** script contains:
```
aws iam create-role `
--role-name $roleName `
--assume-role-policy-document file://myRoleTrustPolicy.json
```
The file **myRoleTr... | It could be that the Lambda is missing an execution role. Or this role has been deleted.
In console you can see the status at Lambda > Functions > YourFunction > Permissions. Even an IAM empty role with no policies is enough to make it work. |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | For me, the issue was that I had an incomplete name for the role. I set
```
--role arn:aws:iam::000000000000:role/MyRoleName
```
when it should have been
```
--role arn:aws:iam::000000000000:role/service-role/MyRoleName
```
*(of course my aws id isn't actually 000000000000)*
I discovered this by running
```
aw... | I was running into this error with terraform and needed to add an assume role policy and apply it to the role that lambda assumes.
```
data "aws_iam_policy_document" "lambda_assume_role_policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = [
... |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | For me, the issue was that I had an incomplete name for the role. I set
```
--role arn:aws:iam::000000000000:role/MyRoleName
```
when it should have been
```
--role arn:aws:iam::000000000000:role/service-role/MyRoleName
```
*(of course my aws id isn't actually 000000000000)*
I discovered this by running
```
aw... | I got this problem while testing lambda function.
What worked for me was formatting JSON. |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | I am just learning to use the AWS CLI and ran into this issue.
I am using a series of PowerShell scripts to deploy an entire AWS architecture. My **createRole.ps1** script contains:
```
aws iam create-role `
--role-name $roleName `
--assume-role-policy-document file://myRoleTrustPolicy.json
```
The file **myRoleTr... | Most people end up in this error because of giving the wrong Role ARN in CloudFormation while creating the Lambda Function.
Make sure the role is completed first by using "DependsOn" and use the intrinsic function """{ "Fn::GetAtt" : [ "your-role-logical-name", "Arn" ] }""" |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | For me, the issue was that I had set the wrong default region environment key. | Most people end up in this error because of giving the wrong Role ARN in CloudFormation while creating the Lambda Function.
Make sure the role is completed first by using "DependsOn" and use the intrinsic function """{ "Fn::GetAtt" : [ "your-role-logical-name", "Arn" ] }""" |
36,419,442 | I'm getting the error "The role defined for the function cannot be assumed by Lambda" when I'm trying to create a lambda function with create-function command.
>
> aws lambda create-function
>
> --region us-west-2
>
> --function-name HelloPython
>
> --zip-file fileb://hello\_python.zip
>
> --role arn:... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36419442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045354/"
] | Had the same issue although my IAM role did have the right policy and trust relationship.
Lambda creation worked fine when done through CLI the problem was when using lambda module after just creating the IAM role.
I also tried to "pause" for few seconds but it didn't help.
Ended up adding retry and delay until regi... | It could be that the Lambda is missing an execution role. Or this role has been deleted.
In console you can see the status at Lambda > Functions > YourFunction > Permissions. Even an IAM empty role with no policies is enough to make it work. |
65,751,105 | I'm using python prometheus client and have troubles pushing metrics to VictoriaMetrics (VM).
There is a function called `push_to_gateway` and I tried to replace prometheus URL with VM: `http://prometheus:9091 -> http://vm:8428/api/v1/write`. But VM responded with 400 status code. | 2021/01/16 | [
"https://Stackoverflow.com/questions/65751105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6689249/"
] | It possible to use `push_to_gateway` method with VictoriaMetrics, check examples at gist <https://gist.github.com/f41gh7/85b2eb895bb63b93ce46ef73448c62d0> | Also, pls take a look at the client I recently created: <https://github.com/gistart/prometheus-push-client>
>
> supports pushes directly to VictoriaMetrics via UDP and HTTP using InfluxDB line protocol
>
>
>
>
> to StatsD or statsd-exporter in StatsD format via UDP
>
>
>
>
> to pushgateway or prom-aggregati... |
65,751,105 | I'm using python prometheus client and have troubles pushing metrics to VictoriaMetrics (VM).
There is a function called `push_to_gateway` and I tried to replace prometheus URL with VM: `http://prometheus:9091 -> http://vm:8428/api/v1/write`. But VM responded with 400 status code. | 2021/01/16 | [
"https://Stackoverflow.com/questions/65751105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6689249/"
] | I'm using CSV import at `/api/v1/import/csv` as described here: <https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/README.md#how-to-import-csv-data>
Generating CSV directly from pandas dataframe. Something like:
```
df.rename(columns={'timestamp': 'ts_ns'}, inplace=True)
data = df.to_csv(index=Fa... | Also, pls take a look at the client I recently created: <https://github.com/gistart/prometheus-push-client>
>
> supports pushes directly to VictoriaMetrics via UDP and HTTP using InfluxDB line protocol
>
>
>
>
> to StatsD or statsd-exporter in StatsD format via UDP
>
>
>
>
> to pushgateway or prom-aggregati... |
21,202,434 | I have to random choose names from a list in python **using random.randint.**
I have done it so far. but i am unable to figure out how to print them without repetition.
some of the name repeat them after 10 to 15 names.
please help me out. **I am not allowed to use any high functions.** I should do it with simple fun... | 2014/01/18 | [
"https://Stackoverflow.com/questions/21202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209210/"
] | Assuming, that you can only use **randint** and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result
```
copy = names[:]
for i in xrange( user_input-1, 1, -1 ):
swap = random.randint(0, i)
copy[i],copy[swap]... | Generate an array of random numbers of the same length as `names`
```
sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))]
```
and sort your `names` array based on this new array
```
names = [name for sa, name in sorted(zip(sortarr, names))]
```
What it does is assigns some random numbers to t... |
21,202,434 | I have to random choose names from a list in python **using random.randint.**
I have done it so far. but i am unable to figure out how to print them without repetition.
some of the name repeat them after 10 to 15 names.
please help me out. **I am not allowed to use any high functions.** I should do it with simple fun... | 2014/01/18 | [
"https://Stackoverflow.com/questions/21202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209210/"
] | These restrictions are pretty silly. I'm not sure what "high functions" are, but you still need help after I provided [the function in your last question](https://stackoverflow.com/a/21202023/2980246), so perhaps function declarations aren't allowed?
Still, you can do the same thing without a function. You just need t... | Assuming, that you can only use **randint** and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result
```
copy = names[:]
for i in xrange( user_input-1, 1, -1 ):
swap = random.randint(0, i)
copy[i],copy[swap]... |
21,202,434 | I have to random choose names from a list in python **using random.randint.**
I have done it so far. but i am unable to figure out how to print them without repetition.
some of the name repeat them after 10 to 15 names.
please help me out. **I am not allowed to use any high functions.** I should do it with simple fun... | 2014/01/18 | [
"https://Stackoverflow.com/questions/21202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209210/"
] | If you can destructively modify `names`, just `pop` the values instead of copying them. Then they're not there anymore, so you won't be able to repeat.
If you can't destructively modify `names`, just do the same to a copy:
```
tmp = names[:]
result = [tmp.pop(random.randrange(len(tmp))) for _ in range(user_input)]
... | Assuming, that you can only use **randint** and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result
```
copy = names[:]
for i in xrange( user_input-1, 1, -1 ):
swap = random.randint(0, i)
copy[i],copy[swap]... |
21,202,434 | I have to random choose names from a list in python **using random.randint.**
I have done it so far. but i am unable to figure out how to print them without repetition.
some of the name repeat them after 10 to 15 names.
please help me out. **I am not allowed to use any high functions.** I should do it with simple fun... | 2014/01/18 | [
"https://Stackoverflow.com/questions/21202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209210/"
] | These restrictions are pretty silly. I'm not sure what "high functions" are, but you still need help after I provided [the function in your last question](https://stackoverflow.com/a/21202023/2980246), so perhaps function declarations aren't allowed?
Still, you can do the same thing without a function. You just need t... | Generate an array of random numbers of the same length as `names`
```
sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))]
```
and sort your `names` array based on this new array
```
names = [name for sa, name in sorted(zip(sortarr, names))]
```
What it does is assigns some random numbers to t... |
21,202,434 | I have to random choose names from a list in python **using random.randint.**
I have done it so far. but i am unable to figure out how to print them without repetition.
some of the name repeat them after 10 to 15 names.
please help me out. **I am not allowed to use any high functions.** I should do it with simple fun... | 2014/01/18 | [
"https://Stackoverflow.com/questions/21202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209210/"
] | If you can destructively modify `names`, just `pop` the values instead of copying them. Then they're not there anymore, so you won't be able to repeat.
If you can't destructively modify `names`, just do the same to a copy:
```
tmp = names[:]
result = [tmp.pop(random.randrange(len(tmp))) for _ in range(user_input)]
... | Generate an array of random numbers of the same length as `names`
```
sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))]
```
and sort your `names` array based on this new array
```
names = [name for sa, name in sorted(zip(sortarr, names))]
```
What it does is assigns some random numbers to t... |
21,202,434 | I have to random choose names from a list in python **using random.randint.**
I have done it so far. but i am unable to figure out how to print them without repetition.
some of the name repeat them after 10 to 15 names.
please help me out. **I am not allowed to use any high functions.** I should do it with simple fun... | 2014/01/18 | [
"https://Stackoverflow.com/questions/21202434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3209210/"
] | If you can destructively modify `names`, just `pop` the values instead of copying them. Then they're not there anymore, so you won't be able to repeat.
If you can't destructively modify `names`, just do the same to a copy:
```
tmp = names[:]
result = [tmp.pop(random.randrange(len(tmp))) for _ in range(user_input)]
... | These restrictions are pretty silly. I'm not sure what "high functions" are, but you still need help after I provided [the function in your last question](https://stackoverflow.com/a/21202023/2980246), so perhaps function declarations aren't allowed?
Still, you can do the same thing without a function. You just need t... |
18,942,003 | I have this Python skeleton, where main.py is fine and server.py is fine. But the moment chat() is launched i see the GUI, but the moment `gtk.main()` was executed it does not allow any activity under server.py module nor in chat.py itself.
How can i have the chat.py flexible so that it does not interupt other class a... | 2013/09/22 | [
"https://Stackoverflow.com/questions/18942003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Instead of the default `sent_tokenize`, what you'll need is the realignment feature that is already pre-coded pre-trained in the `punkt` sentence tokenizer.
```
>>> import nltk
>>> st2 = nltk.data.load('tokenizers/punkt/english.pickle')
>>> sent = 'A problem. She said: "I don\'t know about it."'
>>> st2.tokenize(sent,... | The default sentence tokenizer is `PunktSentenceTokenizer` that detects a new sentence each time it founds a period except, for example, the period belongs to an acronym like U.S.A.
In nltk documentation there are examples of how to train a new sentence splitter with different corpus. You can find it [here.](http://nl... |
23,386,290 | I want to use the logging module instead of printing for debug information and documentation.
The goal is to print on the console with DEBUG level and log to a file with INFO level.
I read through a lot of documentation, the cookbook and other tutorials on the logging module but couldn't figure out, how I can use it t... | 2014/04/30 | [
"https://Stackoverflow.com/questions/23386290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2889642/"
] | In your main module, you're configuring the logger of name `'__main__'` (or whatever `__name__` equates to in your case) while in module.py you're using a different logger. You either need to configure loggers per module, or you can configure the root logger (by configuring `logging.getLogger()`) in your main module wh... | The generally recommended logging setup is having at most 1 logger per module.
If your project is [properly packaged](https://packaging.python.org/), `__name__` will have the value of `"mypackage.mymodule"`, except in your main file, where it has the value `"__main__"`
If you want more context about the code that is ... |
65,222,770 | i am new to all this and im trying to make a shoot 'em up game. after i try to run the code, i encounter an error `TypeError: 'int' object is not subscriptable` at:
line 269:
`collision = isCollision(enemyX[i],enemyY[i],knifeX,knifeY)`
line 118:
`distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemy... | 2020/12/09 | [
"https://Stackoverflow.com/questions/65222770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11592606/"
] | You call `isCollision()` with `enemyX[i]`, but then in `isCollision`, you try to access `enemyX[i]`. So you're trying to do `enemyX[i][i]`. But since `enemyX[i]` is an integer, trying to get a subscript of it, `[i]`, is invalid so that's why you get that error. | You're already sending the specific number with e.g. `enemyX[i]` when you call `isCollision(enemyX[i], ...)`. Once in that function, you can just use the passed argument (which you also happen to call `enemyX` - it's just a different one from the caller's `enemyX`) by itself, e.g. `math.pow(enemyX -...`. I recommend re... |
65,222,770 | i am new to all this and im trying to make a shoot 'em up game. after i try to run the code, i encounter an error `TypeError: 'int' object is not subscriptable` at:
line 269:
`collision = isCollision(enemyX[i],enemyY[i],knifeX,knifeY)`
line 118:
`distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemy... | 2020/12/09 | [
"https://Stackoverflow.com/questions/65222770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11592606/"
] | You do the subscription when you call the function `isCollision`:
```py
if ( knife_state == "fire" and isCollision( enemyX[i], enemyY[i], knifeX, knifeY ) ):
```
Hence you must remove the subscription in the function:
~~`distance = math.sqrt((math.pow(enemyX[i] - knifeX,2)) + (math.pow(enemyY[i] - knifeY,2)))`~~
`... | You're already sending the specific number with e.g. `enemyX[i]` when you call `isCollision(enemyX[i], ...)`. Once in that function, you can just use the passed argument (which you also happen to call `enemyX` - it's just a different one from the caller's `enemyX`) by itself, e.g. `math.pow(enemyX -...`. I recommend re... |
38,218,609 | I started to learn Scrapy but I stuck up at weird point where I couldn't set default shell to ipython. The operating system of my laptop is Ubuntu 15.10. I also installed ipython and scrapy. They run well without causing any errors.
According to Scrapy's [official tutorial](http://doc.scrapy.org/en/latest/topics/shell... | 2016/07/06 | [
"https://Stackoverflow.com/questions/38218609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5538922/"
] | Another way to configure (or test) the shell used by `scrapy shell` is the [`SCRAPY_PYTHON_SHELL` environment variable](http://doc.scrapy.org/en/latest/topics/shell.html#configuring-the-shell).
So running:
```
paul@paul:~$ SCRAPY_PYTHON_SHELL=ipython scrapy shell
```
would use `ipython` as first choice, whatever se... | If you are inside of the project you can use this:
```
from scrapy.utils.project import get_project_settings
settings = get_project_settings()
settings.get('IMPORT_API_URL')
```
If you are outside of the project, you can use this:
```
from scrapy.settings import Settings
settings = Settings()
settings_module_pa... |
41,780,388 | Please refrain from calling this a duplicate, I am completely new to idea of accessing USB devices via Python.
The other questions and answers were often too high level for me to comprehend.
I have a qr code scanner that is USB plug and play.
I can't find it on the command line for whatever reason and it has me stu... | 2017/01/21 | [
"https://Stackoverflow.com/questions/41780388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4562973/"
] | With this (second) call:
```
name_array = realloc(name_array, sizeof(char *));
```
You are still allocating just one char pointer. So, you can't store two pointers; you need to increase the size:
```
name_array = realloc(name_array, 2 * sizeof *name_array);
```
Now, you'd be fine.
Note that `p = realloc(p, ..);... | The error is better reported by address sanitizer than valgrind. If you compile your code like:
```
gcc test.c -fsanitize=address -g
```
and then run it, it will report heap-buffer-overflow error in line 19 of your code. This is the line where you assign second element of name\_array having allocated memory for only... |
16,223,412 | I have a relatively big project that has many dependencies, and I would like to distribute this project around, but installing these dependencies where a bit of a pain, and takes a very long time (pip install takes quite some time). So I was wondering if it was possible to migrate a whole virtualenv to another machine ... | 2013/04/25 | [
"https://Stackoverflow.com/questions/16223412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515864/"
] | Export virtualenvironment
*from within the virtual environment:*
```
pip freeze > requirements.txt
```
as example, here is for myproject virtual environment:
[](https://i.stack.imgur.com/EJUEk.png)
once in the new machine & environment, cop... | When you create a new virtualenv it is configured for the computer it is running on. I even think that it is configured for that specific directory it is created in. So I think you should always create a fresh virtualenv when you move you code. What might work is copying the lib/Pythonx.x/site-packages in your virtuale... |
16,223,412 | I have a relatively big project that has many dependencies, and I would like to distribute this project around, but installing these dependencies where a bit of a pain, and takes a very long time (pip install takes quite some time). So I was wondering if it was possible to migrate a whole virtualenv to another machine ... | 2013/04/25 | [
"https://Stackoverflow.com/questions/16223412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515864/"
] | Export virtualenvironment
*from within the virtual environment:*
```
pip freeze > requirements.txt
```
as example, here is for myproject virtual environment:
[](https://i.stack.imgur.com/EJUEk.png)
once in the new machine & environment, cop... | The clean way seems to be with `virtualenv --relocatable`.
Alternatively, you can do it manually by editing the `VIRTUAL_ENV` path in `bin/activate` to reflect the changes. If you choose to do so, you must also edit the first line (#) of `bin/pserve` which indicates the interpreter path. |
24,209,181 | I have uploaded my first Django Application called **survey** (Its a work in progress) using `mod_wsgi` with `Apache` on an `Ubuntu` VM but I don't know what the URL of it should be. My VM has been made public through a proxyPass at <http://phaedrus.scss.tcd.ie/bias_experiment>.
When working on my application locally ... | 2014/06/13 | [
"https://Stackoverflow.com/questions/24209181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214163/"
] | The URL should be <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/>
I think there is one tiny error in the Apache configuration, which might be my fault (sorry): you need a trailing slash, so:
```
WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi
```
Also note that y... | Try with this changes:
Apache conf:
```
WSGIApplicationGroup %{GLOBAL}
ServerName phaedrus.scss.tcd.ie
WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi
WSGIDaemonProcess bias_experiment processes=4 threads=25 display-name=%{GROUP}
WSGIProcessGroup bias_experiment
WSGIPassAutho... |
24,209,181 | I have uploaded my first Django Application called **survey** (Its a work in progress) using `mod_wsgi` with `Apache` on an `Ubuntu` VM but I don't know what the URL of it should be. My VM has been made public through a proxyPass at <http://phaedrus.scss.tcd.ie/bias_experiment>.
When working on my application locally ... | 2014/06/13 | [
"https://Stackoverflow.com/questions/24209181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214163/"
] | Is this it in your /static/ folder?
<http://phaedrus.scss.tcd.ie/bias_experiment/static/> | Try with this changes:
Apache conf:
```
WSGIApplicationGroup %{GLOBAL}
ServerName phaedrus.scss.tcd.ie
WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi
WSGIDaemonProcess bias_experiment processes=4 threads=25 display-name=%{GROUP}
WSGIProcessGroup bias_experiment
WSGIPassAutho... |
24,209,181 | I have uploaded my first Django Application called **survey** (Its a work in progress) using `mod_wsgi` with `Apache` on an `Ubuntu` VM but I don't know what the URL of it should be. My VM has been made public through a proxyPass at <http://phaedrus.scss.tcd.ie/bias_experiment>.
When working on my application locally ... | 2014/06/13 | [
"https://Stackoverflow.com/questions/24209181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214163/"
] | The URL should be <http://phaedrus.scss.tcd.ie/bias_experiment/surveythree/>
I think there is one tiny error in the Apache configuration, which might be my fault (sorry): you need a trailing slash, so:
```
WSGIScriptAlias /bias_experiment/ /var/www/bias_experiment/src/bias_experiment/index.wsgi
```
Also note that y... | Is this it in your /static/ folder?
<http://phaedrus.scss.tcd.ie/bias_experiment/static/> |
24,618,832 | I wonder if anyone has an elegant solution to being able to pass a python list, a numpy vector (shape(n,)) or a numpy vector (shape(n,1)) to a function. The idea would be to generalize a function such that any of the three would be valid without adding complexity.
Initial thoughts:
```
1) Use a type checking decorato... | 2014/07/07 | [
"https://Stackoverflow.com/questions/24618832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839375/"
] | You can convert the three types to a "canonical" type, which is a 1dim array, using:
```
arr = np.asarray(arr).ravel()
```
Put in a decorator:
```
import numpy as np
import functools
def takes_1dim_array(func):
@functools.wraps(func)
def f(arr, *a, **kw):
arr = np.asarray(arr).ravel()
retur... | I think the simplest thing to do is to start off your function with [`numpy.atleast_2d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_2d.html). Then, all 3 of your possibilities will be converted to the `x.shape == (n, 1)` case, and you can use that to simplify your function.
For example,
```
def... |
20,714,517 | **Hi,
I ran into an encoding error with Python Django.
In my views.py, I have the following:**
```
from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
# Create your views here.
def hello(request):
name = 'Mike... | 2013/12/21 | [
"https://Stackoverflow.com/questions/20714517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1139783/"
] | Well, here you are:
Put `# -*- coding: utf-8 -*-` at top of file, it define de encoding.
The [docs](http://www.python.org/dev/peps/pep-0263/) says:
>
> Python will default to ASCII as standard encoding if no other
> encoding hints are given.
>
>
>
> ```
> To define a source code encoding, a magic comment must
... | If you read [PEP 263](http://www.python.org/dev/peps/pep-0263/), it clearly says:
>
> To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the fileβ¦
>
>
>
(The original proposal said that it had to be the first line after the #!, if any, but pres... |
49,510,289 | I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information.
I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Pyth... | 2018/03/27 | [
"https://Stackoverflow.com/questions/49510289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9553462/"
] | Yes, all of your answers are correct.
`int` will always take up `sizeof(int)` bytes, 8(int) assuming 32-bit `int` it will take 4 bytes, whereas 8(char) will take up one byte.
The way to think about your last question IMO is that data is stored as *bytes*. *char* and *int* are way of interpreting bytes, so in text fil... | When we consider the memory location for an `int` or for a `char` we think as a whole. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored in an `int` variable. As we need total 32 bits (32/8 = 4) hence we need 4 bytes for an `... |
49,510,289 | I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information.
I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Pyth... | 2018/03/27 | [
"https://Stackoverflow.com/questions/49510289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9553462/"
] | Yes, all of your answers are correct.
`int` will always take up `sizeof(int)` bytes, 8(int) assuming 32-bit `int` it will take 4 bytes, whereas 8(char) will take up one byte.
The way to think about your last question IMO is that data is stored as *bytes*. *char* and *int* are way of interpreting bytes, so in text fil... | >
> if a number is stored as a character it will contain 1 byte per character of the number(not 4 bytes)? for example if I make an int variable of the number 8 and a char variable of '8' the int variable will have consumed more memory?
>
>
>
Yes, since it is guaranteed that (assuming 8-bit bytes):
```
sizeof(cha... |
49,510,289 | I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information.
I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Pyth... | 2018/03/27 | [
"https://Stackoverflow.com/questions/49510289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9553462/"
] | Yes, all of your answers are correct.
`int` will always take up `sizeof(int)` bytes, 8(int) assuming 32-bit `int` it will take 4 bytes, whereas 8(char) will take up one byte.
The way to think about your last question IMO is that data is stored as *bytes*. *char* and *int* are way of interpreting bytes, so in text fil... | When int is defined the memory would be allocated based on compiler option ( it can be 4 to 8 bytes). The number assigned to int is stored as is.
e.g int a = 86;
The number 86 would be stored at memory allocated for a.
When char is defined , there are numbers assigned to each character. When these character needs to ... |
49,510,289 | I have a gigantic excel workbook with a lot of personal data. Each person has a unique numeric identifier, but has multiple rows of information.
I want to filter all the content through that identifier, and then copy the resulting rows to a template excel workbook and save the results. I'm trying to do this with Pyth... | 2018/03/27 | [
"https://Stackoverflow.com/questions/49510289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9553462/"
] | When we consider the memory location for an `int` or for a `char` we think as a whole. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored in an `int` variable. As we need total 32 bits (32/8 = 4) hence we need 4 bytes for an `... | >
> if a number is stored as a character it will contain 1 byte per character of the number(not 4 bytes)? for example if I make an int variable of the number 8 and a char variable of '8' the int variable will have consumed more memory?
>
>
>
Yes, since it is guaranteed that (assuming 8-bit bytes):
```
sizeof(cha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.