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 |
|---|---|---|---|---|---|
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | If you add comma at the end it should work for you.
```
>>> def test():
... print 1,
... print 2,
...
>>> test()
1 2
``` | Use this code for your print
`print(x,end="")` |
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | Just add a `,` at the end of the item(s) you're printing.
```
print(x,)
# 3 4
```
Or in Python 2:
```
print x,
# 3 4
``` | ```
my_list = ['keyboard', 'mouse', 'led', 'monitor', 'headphones', 'dvd']
for i in xrange(0, len(my_list), 4):
print '\t'.join(my_list[i:i+4])
``` |
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | Just add a `,` at the end of the item(s) you're printing.
```
print(x,)
# 3 4
```
Or in Python 2:
```
print x,
# 3 4
``` | ```
a=int(input("RangeFinal "))
print("Prime Numbers in the range")
for n in range(2, a):
p=0
for x in range(2, n):
if n % x == 0:
break
else:
if(p==0):
print(n,end=' ')
p=1
```
Answer
```
RangeFinal 19
Prime Numbers in the range
3 5 7 9 11... |
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | Use this code for your print
`print(x,end="")` | Python 3:
```
l = [3.14, 'string', ('tuple', 'of', 'items')]
print(', '.join(map(repr, l)))
```
Output:
>
>
> ```
> 3.14, 'string', ('tuple', 'of', 'items')
>
> ```
>
> |
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | ```
my_list = ['keyboard', 'mouse', 'led', 'monitor', 'headphones', 'dvd']
for i in xrange(0, len(my_list), 4):
print '\t'.join(my_list[i:i+4])
``` | Python 3:
```
l = [3.14, 'string', ('tuple', 'of', 'items')]
print(', '.join(map(repr, l)))
```
Output:
>
>
> ```
> 3.14, 'string', ('tuple', 'of', 'items')
>
> ```
>
> |
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | If you add comma at the end it should work for you.
```
>>> def test():
... print 1,
... print 2,
...
>>> test()
1 2
``` | ```
my_list = ['keyboard', 'mouse', 'led', 'monitor', 'headphones', 'dvd']
for i in xrange(0, len(my_list), 4):
print '\t'.join(my_list[i:i+4])
``` |
8,437,964 | I was wondering if we can print like row-wise in python.
Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise
```
print x
# currently gives
# 3
# 4
#.. and so on
```
and i am looking something like
... | 2011/12/08 | [
"https://Stackoverflow.com/questions/8437964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | In Python2:
```
data = [3, 4]
for x in data:
print x, # notice the comma at the end of the line
```
or in Python3:
```
for x in data:
print(x, end=' ')
```
prints
```
3 4
``` | You don't need to use a for loop to do that!
--------------------------------------------
```py
mylist = list('abcdefg')
print(*mylist, sep=' ')
# Output:
# a b c d e f g
```
Here I'm using the unpack operator for iterators: `*`. At the background the print function is beeing called like this: `print('a', 'b', 'c'... |
7,843,497 | I am trying to run an awk script using python, so I can process some data.
Is there any way to get an awk script to run in a python class without using the system class to invoke it as shell process? The framework where I run these python scripts does not allow the use of a subprocess call, so I am stuck either figuri... | 2011/10/20 | [
"https://Stackoverflow.com/questions/7843497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006198/"
] | If you can't use the *subprocess* module, the best bet is to recode your AWK script in Python. To that end, the *fileinput* module is a great transition tool with and AWK-like feel. | [Python's re module](http://docs.python.org/library/re.html) can help, or, if you can't be bothered with regular expressions and just need to do some quick field seperation, you can use [the built in str `.split()`](http://docs.python.org/library/stdtypes.html#str.split) and [`.find()`](http://docs.python.org/library/... |
7,843,497 | I am trying to run an awk script using python, so I can process some data.
Is there any way to get an awk script to run in a python class without using the system class to invoke it as shell process? The framework where I run these python scripts does not allow the use of a subprocess call, so I am stuck either figuri... | 2011/10/20 | [
"https://Stackoverflow.com/questions/7843497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006198/"
] | If you can't use the *subprocess* module, the best bet is to recode your AWK script in Python. To that end, the *fileinput* module is a great transition tool with and AWK-like feel. | I have barely started learning AWK, so I can't offer any advice on that front. However, for some python code that does what you need:
```
class ProteinIterator():
def __init__(self, file):
self.file = open(file, 'r')
self.first_line = self.file.readline()
def __iter__(self):
return self... |
40,617,324 | So I have an assignment, and For a specific section, we are supposed to import a .py file into our program."You will need to import histogram.py into your program."
Does that simply mean to create a new python file and just copy and past whatever is in the histogram.py into the file?
This part of my assignment is to c... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40617324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7045663/"
] | With a small tweak in your Plan model, it is indeed possible to do what you want.
First of all, you'll need to change your Plan `days` field, which is probably an `IntegerField`, to [DurationField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#durationfield).
Now the catch is that we have to use [Expressi... | For me you must first grab the plan object.
```
plan = Plan.objects.filter(...)
```
and then reference the days
```
Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=plan.days))
``` |
40,617,324 | So I have an assignment, and For a specific section, we are supposed to import a .py file into our program."You will need to import histogram.py into your program."
Does that simply mean to create a new python file and just copy and past whatever is in the histogram.py into the file?
This part of my assignment is to c... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40617324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7045663/"
] | Assuming Postgres database:
```
table_post = Post._meta.db_table
table_plan = Plan._meta.db_table
old_posts = Post.objects.select_related('plan')\
.extra(where=["%s.created_at <= NOW() - INTERVAL '1 day' * %s.days"
% (table_post, table_plan)])
``` | For me you must first grab the plan object.
```
plan = Plan.objects.filter(...)
```
and then reference the days
```
Post.objects.filter(createdAt__lte=datetime.now() - timedelta(days=plan.days))
``` |
40,617,324 | So I have an assignment, and For a specific section, we are supposed to import a .py file into our program."You will need to import histogram.py into your program."
Does that simply mean to create a new python file and just copy and past whatever is in the histogram.py into the file?
This part of my assignment is to c... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40617324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7045663/"
] | With a small tweak in your Plan model, it is indeed possible to do what you want.
First of all, you'll need to change your Plan `days` field, which is probably an `IntegerField`, to [DurationField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#durationfield).
Now the catch is that we have to use [Expressi... | Assuming Postgres database:
```
table_post = Post._meta.db_table
table_plan = Plan._meta.db_table
old_posts = Post.objects.select_related('plan')\
.extra(where=["%s.created_at <= NOW() - INTERVAL '1 day' * %s.days"
% (table_post, table_plan)])
``` |
2,262,482 | I have made my own php MVC framework and have also written its documentation. It is about 80% complete. Now basically I am looking for a way so that other developers should be able to analyze my code and possibly join hands for its further development and improvement and also they should be able to browse through the d... | 2010/02/14 | [
"https://Stackoverflow.com/questions/2262482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139459/"
] | [**Github**](http://github.com/) comes to mind. It's free for Open Source projects, and supports a lot of "social coding" functions.
If you prefer Subversion Version Control, take a look at [**Google Code**](http://code.google.com/).
**HTML Hosting**
Github can even [**host static HTML pages**](http://github.com/blo... | [GitHub,](http://github.com) [SourceForge](http://sourceforge.com) and [Google Code](http://code.google.com) are all great places to make your project public and get others involved.
But these sites will only host your code, documentation, maybe provide you a forum, a mailing list and a bug tracker. They usually does... |
2,262,482 | I have made my own php MVC framework and have also written its documentation. It is about 80% complete. Now basically I am looking for a way so that other developers should be able to analyze my code and possibly join hands for its further development and improvement and also they should be able to browse through the d... | 2010/02/14 | [
"https://Stackoverflow.com/questions/2262482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139459/"
] | [**Github**](http://github.com/) comes to mind. It's free for Open Source projects, and supports a lot of "social coding" functions.
If you prefer Subversion Version Control, take a look at [**Google Code**](http://code.google.com/).
**HTML Hosting**
Github can even [**host static HTML pages**](http://github.com/blo... | ```
#include<stdio.h>
int main()
{ int selection;
printf("this is a program to build a calculator program \n");
printf("for addition press 1 \n");
printf("for multiplication press 2 \n");
printf("for subtraction enter 3 \n");
printf("for division enter 4 \n"); /* this is cool */
scanf("%d",&selection);
switch(sele... |
2,262,482 | I have made my own php MVC framework and have also written its documentation. It is about 80% complete. Now basically I am looking for a way so that other developers should be able to analyze my code and possibly join hands for its further development and improvement and also they should be able to browse through the d... | 2010/02/14 | [
"https://Stackoverflow.com/questions/2262482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139459/"
] | [GitHub,](http://github.com) [SourceForge](http://sourceforge.com) and [Google Code](http://code.google.com) are all great places to make your project public and get others involved.
But these sites will only host your code, documentation, maybe provide you a forum, a mailing list and a bug tracker. They usually does... | ```
#include<stdio.h>
int main()
{ int selection;
printf("this is a program to build a calculator program \n");
printf("for addition press 1 \n");
printf("for multiplication press 2 \n");
printf("for subtraction enter 3 \n");
printf("for division enter 4 \n"); /* this is cool */
scanf("%d",&selection);
switch(sele... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | They're both within an order of magnitude of each other, when you run them with identical cycle counts rather than having the Python counts being larger by an order of magnitude:
### PHP: <https://ideone.com/3ebkai> 2.7089s
```
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x;... | The loop itself appears to be twice as slow in CPython 3:
<https://ideone.com/bI6jzD>
```php
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x; ++$i)
{
//1.40s Reassign and use $a.
//$a += 1;
//1.15s Use and increment $a.
//$a++;
//0.8... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | They're both within an order of magnitude of each other, when you run them with identical cycle counts rather than having the Python counts being larger by an order of magnitude:
### PHP: <https://ideone.com/3ebkai> 2.7089s
```
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x;... | You guys are not being fair. The two pieces of code are NOT doing the same thing.
While PHP only increments two variables ($a and $i), Python is generating a range before it loops.
So, to have a fair comparison your Python code should be:
```
import time
def test2(x):
r = range(x) #please generate this first
... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | They're both within an order of magnitude of each other, when you run them with identical cycle counts rather than having the Python counts being larger by an order of magnitude:
### PHP: <https://ideone.com/3ebkai> 2.7089s
```
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x;... | As others have pointed out, your arguments are an order of magnitude off for the Python code. But I just want to add that callables in loop conditions should be avoided as much as possible whenever writing any kind of code as Rafael Beckel pointed out in his answer. On every iteration the callable is executed, which re... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | They're both within an order of magnitude of each other, when you run them with identical cycle counts rather than having the Python counts being larger by an order of magnitude:
### PHP: <https://ideone.com/3ebkai> 2.7089s
```
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x;... | PHP code using `range` is faster than without. My version:
```php
<?php
declare(strict_types=1);
function test(int $x): int
{
$range = range(1, $x);
$a = 0;
$t1 = microtime(true);
foreach($range as $i)
{
$a++;
}
$t2 = microtime(true);
echo 'Time for ' . $x . ' was ' . ($t2 - ... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | You guys are not being fair. The two pieces of code are NOT doing the same thing.
While PHP only increments two variables ($a and $i), Python is generating a range before it loops.
So, to have a fair comparison your Python code should be:
```
import time
def test2(x):
r = range(x) #please generate this first
... | The loop itself appears to be twice as slow in CPython 3:
<https://ideone.com/bI6jzD>
```php
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x; ++$i)
{
//1.40s Reassign and use $a.
//$a += 1;
//1.15s Use and increment $a.
//$a++;
//0.8... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | The loop itself appears to be twice as slow in CPython 3:
<https://ideone.com/bI6jzD>
```php
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x; ++$i)
{
//1.40s Reassign and use $a.
//$a += 1;
//1.15s Use and increment $a.
//$a++;
//0.8... | As others have pointed out, your arguments are an order of magnitude off for the Python code. But I just want to add that callables in loop conditions should be avoided as much as possible whenever writing any kind of code as Rafael Beckel pointed out in his answer. On every iteration the callable is executed, which re... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | The loop itself appears to be twice as slow in CPython 3:
<https://ideone.com/bI6jzD>
```php
<?php
function test($x)
{
$t1 = microtime(true);
$a = 0;
for($i = 0; $i < $x; ++$i)
{
//1.40s Reassign and use $a.
//$a += 1;
//1.15s Use and increment $a.
//$a++;
//0.8... | PHP code using `range` is faster than without. My version:
```php
<?php
declare(strict_types=1);
function test(int $x): int
{
$range = range(1, $x);
$a = 0;
$t1 = microtime(true);
foreach($range as $i)
{
$a++;
}
$t2 = microtime(true);
echo 'Time for ' . $x . ' was ' . ($t2 - ... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | You guys are not being fair. The two pieces of code are NOT doing the same thing.
While PHP only increments two variables ($a and $i), Python is generating a range before it loops.
So, to have a fair comparison your Python code should be:
```
import time
def test2(x):
r = range(x) #please generate this first
... | As others have pointed out, your arguments are an order of magnitude off for the Python code. But I just want to add that callables in loop conditions should be avoided as much as possible whenever writing any kind of code as Rafael Beckel pointed out in his answer. On every iteration the callable is executed, which re... |
48,031,283 | As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B.
Python's execution time was *horrible* in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Pytho... | 2017/12/30 | [
"https://Stackoverflow.com/questions/48031283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1502289/"
] | You guys are not being fair. The two pieces of code are NOT doing the same thing.
While PHP only increments two variables ($a and $i), Python is generating a range before it loops.
So, to have a fair comparison your Python code should be:
```
import time
def test2(x):
r = range(x) #please generate this first
... | PHP code using `range` is faster than without. My version:
```php
<?php
declare(strict_types=1);
function test(int $x): int
{
$range = range(1, $x);
$a = 0;
$t1 = microtime(true);
foreach($range as $i)
{
$a++;
}
$t2 = microtime(true);
echo 'Time for ' . $x . ' was ' . ($t2 - ... |
19,943,977 | I am a somewhat Python/programing newbie, and I am attempting to use a python class for the first time.
In this code I am trying to create a script to backup some files. I have 6 files in total that I want to back up regularly with this script so I thought that I would try and use the python Class to save me writing ... | 2013/11/13 | [
"https://Stackoverflow.com/questions/19943977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2680443/"
] | If you just want your files backed up, may I suggest using `shutil.copy()`?
As for your program:
If you want to substitute in a string to build a filename, you can do it. But your code doesn't do it.
You have this:
```
with open('%s.txt', 'r') as f, open('{}.txt', 'w') as f2 % (self.file_name, self.back_up_file):
... | Try simplicity :)
Your line 7 is not going to parse. Split it using intermediate variables:
```
source_fname = "%s.txt" % self.file_name
target_fname = "%s.txt" % self.back_up_file
with open(source_fname) as source, open(target_fname) as target:
# do your thing
```
Also, try hard avoiding inconsistent and overly ... |
12,548,572 | I'm trying to make a simple derived class based on `str`, with the addition of an instance variable, `flag`. For reasons I do not understand, I get an error if I try to pass the flag to the constructor:
```
>>> class Strvalue(str):
def __init__(self, content, flag=None):
str.__init__(self, cont... | 2012/09/22 | [
"https://Stackoverflow.com/questions/12548572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699305/"
] | You need to use `__new__` instead of `__init__` when subclassing `str`, see [basic customization](http://docs.python.org/reference/datamodel.html#basic-customization).
```
>>> class Strvalue(str):
... def __new__(cls, content, flag=None):
... inst = str.__new__(cls, content)
... inst.flag = flag
..... | You need to override `__new__` instead of (or as well as) `__init__`. |
9,052,588 | I am new to python and new to programming. I have question how can I use variables from method1 in method too.
Example
```
class abc(self):
def method1 (self,v1):
v1 = a+b
return v1 # want to use this value in method 2
def method2(self)
v2 * v1 = v3
```
Than... | 2012/01/29 | [
"https://Stackoverflow.com/questions/9052588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172372/"
] | let `method2` "know" it is waiting for an argument:
```
def method2(self,v1): #note v1 was added here
v2 * v1 = v3 #what does that suppse to do? [look my "third note"]
```
also note: you also need to pass `v2` to `method2()`
third note: what exactly are you trying to do in `v2 * v1 = v3` ? maybe you meant `v3 = ... | To use a value throughout a class, you need to bind that value to an attribute of its instance.
For example:
```
class Abc(object): # put object here, not self
def method1(self):
self.v1 = 3 + 7 # now v1 is an attribute
def method2(self)
return 4 * self.v1
a = Abc()
a.method1()
a.v1 ... |
9,052,588 | I am new to python and new to programming. I have question how can I use variables from method1 in method too.
Example
```
class abc(self):
def method1 (self,v1):
v1 = a+b
return v1 # want to use this value in method 2
def method2(self)
v2 * v1 = v3
```
Than... | 2012/01/29 | [
"https://Stackoverflow.com/questions/9052588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172372/"
] | let `method2` "know" it is waiting for an argument:
```
def method2(self,v1): #note v1 was added here
v2 * v1 = v3 #what does that suppse to do? [look my "third note"]
```
also note: you also need to pass `v2` to `method2()`
third note: what exactly are you trying to do in `v2 * v1 = v3` ? maybe you meant `v3 = ... | one more way is to use global variable.
```
def a():
global v
v = 10;
def b():
print v
if __name__=='__main__':
a()
b()
``` |
9,052,588 | I am new to python and new to programming. I have question how can I use variables from method1 in method too.
Example
```
class abc(self):
def method1 (self,v1):
v1 = a+b
return v1 # want to use this value in method 2
def method2(self)
v2 * v1 = v3
```
Than... | 2012/01/29 | [
"https://Stackoverflow.com/questions/9052588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172372/"
] | Make `v1` an instance variable by using `self`, i.e. `self.v1 = a+b` and `v2 * self.v1 = v3`. But that second command should look like this: `v3 = v2 * self.v1`. And there is still a problem in `v2` not being defined.
Note that with this approach, `method1` must be called before `method2`, otherwise `self.v1` will no... | To use a value throughout a class, you need to bind that value to an attribute of its instance.
For example:
```
class Abc(object): # put object here, not self
def method1(self):
self.v1 = 3 + 7 # now v1 is an attribute
def method2(self)
return 4 * self.v1
a = Abc()
a.method1()
a.v1 ... |
9,052,588 | I am new to python and new to programming. I have question how can I use variables from method1 in method too.
Example
```
class abc(self):
def method1 (self,v1):
v1 = a+b
return v1 # want to use this value in method 2
def method2(self)
v2 * v1 = v3
```
Than... | 2012/01/29 | [
"https://Stackoverflow.com/questions/9052588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1172372/"
] | Make `v1` an instance variable by using `self`, i.e. `self.v1 = a+b` and `v2 * self.v1 = v3`. But that second command should look like this: `v3 = v2 * self.v1`. And there is still a problem in `v2` not being defined.
Note that with this approach, `method1` must be called before `method2`, otherwise `self.v1` will no... | one more way is to use global variable.
```
def a():
global v
v = 10;
def b():
print v
if __name__=='__main__':
a()
b()
``` |
63,894,460 | An example is something like [Desmos](https://www.desmos.com/calculator) (but as a desktop application). The function is given by the user as text, so it cannot be written at compile-time. Furthermore, the function may be reused thousands of times before it changes. However, a true example would be something where the ... | 2020/09/15 | [
"https://Stackoverflow.com/questions/63894460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10868964/"
] | The paper [“A Killer Adversary for Quicksort”](https://www.cs.dartmouth.edu/%7Edoug/mdmspe.pdf) gives an algorithm that, for any quicksort implementation that satisfies certain “reasonable” requirements and runs deterministically, produces arbitrarily long input sequences that cause the algorithm to run in quadratic ti... | the worst case of quick sort is when each time the pivot is chosen it's the max or min number/value in the array.
in this case it will run at O(n^2) for the regular version of Quick sort.
However, there's a version of Quick sort that uses the partition algorithm in order to choose better pivots. In this version of Quic... |
29,124,435 | So I'm having this issue where I'm trying to convert something such as
```
[0]['question']: "what is 2+2",
[0]['answers'][0]: "21",
[0]['answers'][1]: "312",
[0]['answers'][2]: "4"
```
into an actual formated json object like so
```
[
{
'question': 'what is 2+2',
'answers': ["21", "312", "4"]
}
]
```
... | 2015/03/18 | [
"https://Stackoverflow.com/questions/29124435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3254198/"
] | Something like this. You need to handle input errors.
A function to take a data structure and add stuff to it based on input
```
function add(old, input) {
var index = input[0];
var section = input[1];
if (old[index] == undefined) {
old[index] = {}
};
if (section == "question") {
old[index]['questio... | I think you should format the json as follow:
```
{
"questions": [
{
"question": "What is 2+2",
"possible_answers": [
{
"value": 1,
"correct": false
},
{
"value": 4,
... |
55,994,238 | I have a code to scrape hotels reviews in python (from yelp).
The code scrape the first page of reviews perfectly, but, I am struggling to scrape the next pages.
The While loop don't work, data scraped in each loop is the same (data of the first page)
```
import requests
from lxml import html
from bs4 import Beauti... | 2019/05/05 | [
"https://Stackoverflow.com/questions/55994238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5539782/"
] | The following is one of the ways you can get your job done. I've slightly modified your existing logic of traversing next pages. Give it a shot.
```
import requests
from lxml.html import fromstring
url = 'https://www.yelp.com/biz/fairmont-san-francisco-san-francisco?sort_by=rating_desc'
while True:
res = request... | You just need to be smart about looking at the URL. Most websites follow a scheme with their page progression. In this case, it seems like it changes to the following format for the next pages:
```
https://www.yelp.com/biz/fairmont-san-francisco-san-francisco?start=20&sort_by=rating_desc
```
Where the start=20 is wh... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | There are a couple of reasons WHY you can get a NaN-result, often it is because of too high a learning rate but plenty other reasons are possible like for example corrupt data in your input-queue or a log of 0 calculation.
Anyhow, debugging with a print as you describe cannot be done by a simple print (as this would r... | I used to find it's much tougher to pinpoint where the nans and infs may occur than to fix the bug. As a complementary to @scai's answer, I'd like to add some points here:
The debug module, you can imported by:
```
from tensorflow.python import debug as tf_debug
```
is much better than any print or assert.
You ... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | For TensorFlow 2, inject some `x=tf.debugging.check_numerics(x,'x is nan')` into your code. They will throw an `InvalidArgument` error if `x`has any values that are not a number (NaN) or infinity (Inf).
Oh and for the next person finding this when hunting a TF2 NaN issue, my case turned out to be an exploding gradient... | I was able to fix my NaN issues by getting rid of all of my dropout layers in the network model. I suspected that maybe for some reason a unit (neuron?) in the network lost too many input connections (so it had zero after the dropout), so then when information was fed through, it had a value of NaN. I don't see how tha... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | For TensorFlow 2, inject some `x=tf.debugging.check_numerics(x,'x is nan')` into your code. They will throw an `InvalidArgument` error if `x`has any values that are not a number (NaN) or infinity (Inf).
Oh and for the next person finding this when hunting a TF2 NaN issue, my case turned out to be an exploding gradient... | NANs occurring in the forward process are one thing and those occurring in the backward process are another.
Step 0: data
============
Make sure that there are no extreme inputs such as NAN inputs or negative labels in the prepared dataset using NumPy tools, for instance: `assert not np.any(np.isnan(x))`.
Step 1: th... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | There are a couple of reasons WHY you can get a NaN-result, often it is because of too high a learning rate but plenty other reasons are possible like for example corrupt data in your input-queue or a log of 0 calculation.
Anyhow, debugging with a print as you describe cannot be done by a simple print (as this would r... | For TensorFlow 2, inject some `x=tf.debugging.check_numerics(x,'x is nan')` into your code. They will throw an `InvalidArgument` error if `x`has any values that are not a number (NaN) or infinity (Inf).
Oh and for the next person finding this when hunting a TF2 NaN issue, my case turned out to be an exploding gradient... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | It look like you can call it after you complete making the graph.
`check = tf.add_check_numerics_ops()`
I think this will add the check for all floating point operations. Then in the sessions run function you can add the check operation.
`sess.run([check, ...])` | I was able to fix my NaN issues by getting rid of all of my dropout layers in the network model. I suspected that maybe for some reason a unit (neuron?) in the network lost too many input connections (so it had zero after the dropout), so then when information was fed through, it had a value of NaN. I don't see how tha... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | NANs occurring in the forward process are one thing and those occurring in the backward process are another.
Step 0: data
============
Make sure that there are no extreme inputs such as NAN inputs or negative labels in the prepared dataset using NumPy tools, for instance: `assert not np.any(np.isnan(x))`.
Step 1: th... | I was able to fix my NaN issues by getting rid of all of my dropout layers in the network model. I suspected that maybe for some reason a unit (neuron?) in the network lost too many input connections (so it had zero after the dropout), so then when information was fed through, it had a value of NaN. I don't see how tha... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | NANs occurring in the forward process are one thing and those occurring in the backward process are another.
Step 0: data
============
Make sure that there are no extreme inputs such as NAN inputs or negative labels in the prepared dataset using NumPy tools, for instance: `assert not np.any(np.isnan(x))`.
Step 1: th... | Current implementation of `tfdbg.has_inf_or_nan` seems do not break immediately on hitting any tensor containing `NaN`. When it does stop, the huge list of tensors displayed are *not* sorted in order of its execution.
A possible hack to find the first appearance of `Nan`s is to dump all tensors to a temporary directory... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | First of all, you need to check you input data properly. In most cases this is the reason. But not always, of course.
I usually use Tensorboard to see whats happening while training. So you can see the values on each step with
```
Z = tf.pow(Z, 2.0)
summary_z = tf.scalar_summary('z', Z)
#etc..
summary_merge = t... | I was able to fix my NaN issues by getting rid of all of my dropout layers in the network model. I suspected that maybe for some reason a unit (neuron?) in the network lost too many input connections (so it had zero after the dropout), so then when information was fed through, it had a value of NaN. I don't see how tha... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | As of version 0.12, TensorFlow is shipped with a builtin debugger called `tfdbg`. It optimizes the workflow of debugging this type of bad-numerical-value issues (like `inf` and `nan`). The documentation is at:
<https://www.tensorflow.org/programmers_guide/debugger> | Current implementation of `tfdbg.has_inf_or_nan` seems do not break immediately on hitting any tensor containing `NaN`. When it does stop, the huge list of tensors displayed are *not* sorted in order of its execution.
A possible hack to find the first appearance of `Nan`s is to dump all tensors to a temporary directory... |
38,810,424 | I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that bec... | 2016/08/07 | [
"https://Stackoverflow.com/questions/38810424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1601580/"
] | I used to find it's much tougher to pinpoint where the nans and infs may occur than to fix the bug. As a complementary to @scai's answer, I'd like to add some points here:
The debug module, you can imported by:
```
from tensorflow.python import debug as tf_debug
```
is much better than any print or assert.
You ... | For TensorFlow 2, inject some `x=tf.debugging.check_numerics(x,'x is nan')` into your code. They will throw an `InvalidArgument` error if `x`has any values that are not a number (NaN) or infinity (Inf).
Oh and for the next person finding this when hunting a TF2 NaN issue, my case turned out to be an exploding gradient... |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Need to pass driver
```
TouchAction action = new TouchAction(driver);
action.longPress(webElement).release().perform();
``` | Here is the update for `Java Client: 5.0.4`
```
WebElement recBtn = driver.findElement(MobileBy.id("img_button"));
new TouchAction((MobileDriver) driver).press(recBtn).waitAction(Duration.ofMillis(10000)).release().perform();
``` |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Here is the update for `Java Client: 5.0.4`
```
WebElement recBtn = driver.findElement(MobileBy.id("img_button"));
new TouchAction((MobileDriver) driver).press(recBtn).waitAction(Duration.ofMillis(10000)).release().perform();
``` | This works:
```
TouchActions action = new TouchActions(driver);
action.longPress(element);
action.perform();
``` |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | It should be like this. The duration is calculated in milliseconds, so it need to multiply by 1000 as 1 second.
```
TouchAction action = new TouchAction(driver);
action.longPress(webElement,duration*1000).release().perform();
``` | Once you have identified the pageElement you want to longPress on.
```
//pageElement
editPreferenceButton = driver.whatever
//code for waiting for display of element
waitForDisplayed(editPreferenceButton, 10)
//this line is not required, keeping it here for easy readability
MobileElement longpress = editPreferen... |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Here is the update for `Java Client: 5.0.4`
```
WebElement recBtn = driver.findElement(MobileBy.id("img_button"));
new TouchAction((MobileDriver) driver).press(recBtn).waitAction(Duration.ofMillis(10000)).release().perform();
``` | Once you have identified the pageElement you want to longPress on.
```
//pageElement
editPreferenceButton = driver.whatever
//code for waiting for display of element
waitForDisplayed(editPreferenceButton, 10)
//this line is not required, keeping it here for easy readability
MobileElement longpress = editPreferen... |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Yes, you can use TouchAction class to longPress any element. Try this:
```
TouchAction action = new TouchAction();
action.longPress(webElement).release().perform();
``` | It should be like this. The duration is calculated in milliseconds, so it need to multiply by 1000 as 1 second.
```
TouchAction action = new TouchAction(driver);
action.longPress(webElement,duration*1000).release().perform();
``` |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Need to pass driver
```
TouchAction action = new TouchAction(driver);
action.longPress(webElement).release().perform();
``` | In latest Java client versions below will work.
```
AndroidTouchAction touch = new AndroidTouchAction (driver);
touch.longPress(LongPressOptions.longPressOptions()
.withElement (ElementOption.element (element)))
.perform ();
System.out.println("LongPressed Tapped");
``` |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Need to pass driver
```
TouchAction action = new TouchAction(driver);
action.longPress(webElement).release().perform();
``` | Following worked:
```
MobileElement longpress = driver.findElement({element find strategy})
LongPressOptions longPressOptions = new LongPressOptions();
longPressOptions.withDuration(Duration.ofSeconds(3)).withElement(ElementOption.element(longpress));
TouchAction action = new TouchAction(driver);
a... |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | It should be like this. The duration is calculated in milliseconds, so it need to multiply by 1000 as 1 second.
```
TouchAction action = new TouchAction(driver);
action.longPress(webElement,duration*1000).release().perform();
``` | Following worked:
```
MobileElement longpress = driver.findElement({element find strategy})
LongPressOptions longPressOptions = new LongPressOptions();
longPressOptions.withDuration(Duration.ofSeconds(3)).withElement(ElementOption.element(longpress));
TouchAction action = new TouchAction(driver);
a... |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | In latest Java client versions below will work.
```
AndroidTouchAction touch = new AndroidTouchAction (driver);
touch.longPress(LongPressOptions.longPressOptions()
.withElement (ElementOption.element (element)))
.perform ();
System.out.println("LongPressed Tapped");
``` | Once you have identified the pageElement you want to longPress on.
```
//pageElement
editPreferenceButton = driver.whatever
//code for waiting for display of element
waitForDisplayed(editPreferenceButton, 10)
//this line is not required, keeping it here for easy readability
MobileElement longpress = editPreferen... |
29,298,096 | Is there any code to tap and hold on Appium? i use python , is there any command to support it ?
For double click i used click on element twice, for tap and hold i am not getting any solution | 2015/03/27 | [
"https://Stackoverflow.com/questions/29298096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4310652/"
] | Yes, you can use TouchAction class to longPress any element. Try this:
```
TouchAction action = new TouchAction();
action.longPress(webElement).release().perform();
``` | Once you have identified the pageElement you want to longPress on.
```
//pageElement
editPreferenceButton = driver.whatever
//code for waiting for display of element
waitForDisplayed(editPreferenceButton, 10)
//this line is not required, keeping it here for easy readability
MobileElement longpress = editPreferen... |
31,321,906 | I have a string like this in Java:
`"\xd0\xb5\xd0\xbd\xd0\xb4\xd0\xbf\xd0\xbe\xd0\xb9\xd0\xbd\xd1\x82"`
How can I convert it to a human readable equivalent?
Note:
actually it is `GWT` and this string is coming from python as part of a JSON data.
The `JSONParser` transforms it to something that is totally irrelevant, ... | 2015/07/09 | [
"https://Stackoverflow.com/questions/31321906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2961166/"
] | It seems indeed that there's no endpoint voor search exists, but I think you use a simple alternative:
Use an empty "fields" array. And count the results of your query. If == 0: false. If > 0: true
```
GET /giata_index/giata_type/_search
{
"fields": [],
"query": {
"bool": {
"must": [
... | It should be possible with the [latest 2.x version](https://github.com/elastic/elasticsearch-php/blob/master/src/Elasticsearch/Endpoints/SearchExists.php).
Code sample could be something like this:
```
$clientBuilder = Elasticsearch\ClientBuilder::create();
// Additional client options, hosts, etc.
$client = $clientBu... |
37,293,366 | I am trying to list the instances on tag values of different tag keys
For eg> one tag key - Environment, other tag key - Role.
My code is given below :
```
import argparse
import boto3
AWS_ACCESS_KEY_ID = '<Access Key>'
AWS_SECRET_ACCESS_KEY = '<Secret Key>'
def get_ec2_instances(Env,Role):
ec2 = boto3.client("... | 2016/05/18 | [
"https://Stackoverflow.com/questions/37293366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349605/"
] | This looks familiar, did I modify this for somebody somewhere ;-) . Actually the code I wrote is in rush and not tested properly (And I don't bother to amend the % string formating and replace it with str.format() ) . In fact,using Filters parameter is not properly documented in AWS.
Please refer to Russell Ballestri... | Fix the Env and Role, as I am not sure mine or mootmoot's answer will work because the Array for Values [expects](http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances) strings.
```
reservervations = ec2.describe_instances(
Filters=[
{'Name': 'tag:environmen... |
37,293,366 | I am trying to list the instances on tag values of different tag keys
For eg> one tag key - Environment, other tag key - Role.
My code is given below :
```
import argparse
import boto3
AWS_ACCESS_KEY_ID = '<Access Key>'
AWS_SECRET_ACCESS_KEY = '<Secret Key>'
def get_ec2_instances(Env,Role):
ec2 = boto3.client("... | 2016/05/18 | [
"https://Stackoverflow.com/questions/37293366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349605/"
] | This looks familiar, did I modify this for somebody somewhere ;-) . Actually the code I wrote is in rush and not tested properly (And I don't bother to amend the % string formating and replace it with str.format() ) . In fact,using Filters parameter is not properly documented in AWS.
Please refer to Russell Ballestri... | In my own python script I use the following:
```
import boto3
ec2client = boto3.client('ec2','us-east-1')
response = ec2client.describe_instances(Filters=[{'Name' : 'instance-state-name','Values' : ['running']}])
``` |
37,293,366 | I am trying to list the instances on tag values of different tag keys
For eg> one tag key - Environment, other tag key - Role.
My code is given below :
```
import argparse
import boto3
AWS_ACCESS_KEY_ID = '<Access Key>'
AWS_SECRET_ACCESS_KEY = '<Secret Key>'
def get_ec2_instances(Env,Role):
ec2 = boto3.client("... | 2016/05/18 | [
"https://Stackoverflow.com/questions/37293366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349605/"
] | This looks familiar, did I modify this for somebody somewhere ;-) . Actually the code I wrote is in rush and not tested properly (And I don't bother to amend the % string formating and replace it with str.format() ) . In fact,using Filters parameter is not properly documented in AWS.
Please refer to Russell Ballestri... | Although not actually the answer to your question but **DO NOT**, **NEVER**, put your AWS credentials hard coded in your scripts. With your AWS credentials, **anyone** can use your account. There are bots scouring github and other git repositories looking for hard coded AWS credentials.
Also, when rotating credential... |
37,293,366 | I am trying to list the instances on tag values of different tag keys
For eg> one tag key - Environment, other tag key - Role.
My code is given below :
```
import argparse
import boto3
AWS_ACCESS_KEY_ID = '<Access Key>'
AWS_SECRET_ACCESS_KEY = '<Secret Key>'
def get_ec2_instances(Env,Role):
ec2 = boto3.client("... | 2016/05/18 | [
"https://Stackoverflow.com/questions/37293366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349605/"
] | In my own python script I use the following:
```
import boto3
ec2client = boto3.client('ec2','us-east-1')
response = ec2client.describe_instances(Filters=[{'Name' : 'instance-state-name','Values' : ['running']}])
``` | Fix the Env and Role, as I am not sure mine or mootmoot's answer will work because the Array for Values [expects](http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances) strings.
```
reservervations = ec2.describe_instances(
Filters=[
{'Name': 'tag:environmen... |
37,293,366 | I am trying to list the instances on tag values of different tag keys
For eg> one tag key - Environment, other tag key - Role.
My code is given below :
```
import argparse
import boto3
AWS_ACCESS_KEY_ID = '<Access Key>'
AWS_SECRET_ACCESS_KEY = '<Secret Key>'
def get_ec2_instances(Env,Role):
ec2 = boto3.client("... | 2016/05/18 | [
"https://Stackoverflow.com/questions/37293366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6349605/"
] | Although not actually the answer to your question but **DO NOT**, **NEVER**, put your AWS credentials hard coded in your scripts. With your AWS credentials, **anyone** can use your account. There are bots scouring github and other git repositories looking for hard coded AWS credentials.
Also, when rotating credential... | Fix the Env and Role, as I am not sure mine or mootmoot's answer will work because the Array for Values [expects](http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_instances) strings.
```
reservervations = ec2.describe_instances(
Filters=[
{'Name': 'tag:environmen... |
51,710,083 | * I am writing unit tests for a Python library using **pytest**
* I need to **specify a directory** for test files to avoid automatic test file discovery, because there is a large sub-directory structure, including many files in the library containing "\_test" or "test\_" in the name but are not intended for pytest
* S... | 2018/08/06 | [
"https://Stackoverflow.com/questions/51710083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8477566/"
] | `parse_args()` without argument reads the `sys.argv[1:]` list. That will include the 'tests' string.
`pytests` also uses that `sys.argv[1:]` with its own parser.
One way to make your parser testable is provide an optional `argv`:
```
def parse_args(argv=None):
parser = argparse.ArgumentParser(description="descri... | To add to hpaulj's answer, you can also use a library like [unittest.mock](https://docs.python.org/3/library/unittest.mock.html) to temporarily mask the value of `sys.argv`. That way your parse args command will run using the "mocked" argv but the *actual* `sys.argv` remains unchanged.
When your tests call `parse_args... |
51,710,083 | * I am writing unit tests for a Python library using **pytest**
* I need to **specify a directory** for test files to avoid automatic test file discovery, because there is a large sub-directory structure, including many files in the library containing "\_test" or "test\_" in the name but are not intended for pytest
* S... | 2018/08/06 | [
"https://Stackoverflow.com/questions/51710083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8477566/"
] | `parse_args()` without argument reads the `sys.argv[1:]` list. That will include the 'tests' string.
`pytests` also uses that `sys.argv[1:]` with its own parser.
One way to make your parser testable is provide an optional `argv`:
```
def parse_args(argv=None):
parser = argparse.ArgumentParser(description="descri... | I ran into a similar problem with test discovery in VS Code. The run adapter in VS Code passes in parameters that my program does not understand. My solution was to make the parser accepts unknown arguments.
Change:
```
return parser.parse_args()
```
To:
```
args, _ = parser.parse_known_args()
return args
``` |
51,710,083 | * I am writing unit tests for a Python library using **pytest**
* I need to **specify a directory** for test files to avoid automatic test file discovery, because there is a large sub-directory structure, including many files in the library containing "\_test" or "test\_" in the name but are not intended for pytest
* S... | 2018/08/06 | [
"https://Stackoverflow.com/questions/51710083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8477566/"
] | To add to hpaulj's answer, you can also use a library like [unittest.mock](https://docs.python.org/3/library/unittest.mock.html) to temporarily mask the value of `sys.argv`. That way your parse args command will run using the "mocked" argv but the *actual* `sys.argv` remains unchanged.
When your tests call `parse_args... | I ran into a similar problem with test discovery in VS Code. The run adapter in VS Code passes in parameters that my program does not understand. My solution was to make the parser accepts unknown arguments.
Change:
```
return parser.parse_args()
```
To:
```
args, _ = parser.parse_known_args()
return args
``` |
59,704,959 | I'm trying to count the number of dots in an email address using Python + Pandas.
The first record is "[email protected]". It should count 2 dots. Instead, it returns 26, the length of the string.
```
import pandas as pd
url = "http://profalibania.com.br/python/EmailsDoctors.xlsx"
docs = pd.read_excel(url)
... | 2020/01/12 | [
"https://Stackoverflow.com/questions/59704959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5518389/"
] | [`pandas.Series.str.count`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html) takes a regex expression as input. To match a literal period (`.`), you must escape it:
```
docs["Email"].str.count('\.')
```
Just specifying `.` will use the regex meaning of the period (matching any... | The [**`.str.count(..)`** method [pandas-doc]](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html) works with a [*regular expression* [wiki]](https://en.wikipedia.org/wiki/Regular_expression). This is specified in the documentation:
>
> This function is used to count the number of... |
59,704,959 | I'm trying to count the number of dots in an email address using Python + Pandas.
The first record is "[email protected]". It should count 2 dots. Instead, it returns 26, the length of the string.
```
import pandas as pd
url = "http://profalibania.com.br/python/EmailsDoctors.xlsx"
docs = pd.read_excel(url)
... | 2020/01/12 | [
"https://Stackoverflow.com/questions/59704959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5518389/"
] | [`pandas.Series.str.count`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html) takes a regex expression as input. To match a literal period (`.`), you must escape it:
```
docs["Email"].str.count('\.')
```
Just specifying `.` will use the regex meaning of the period (matching any... | A variant here would be to compare the length of the original email column with the length of that column with all dots removed:
```
docs["Email"].str.len() - docs["Email"].str.replace("[.]", "").len()
``` |
57,718,512 | I'm trying to try using this model to train on rock, paper, scissor pictures. However, it was trained on 1800 pictures and only has an accuracy of 30-40%. I was then trying to use TensorBoard to see whats going on, but the error in the title appears.
```
from keras.models import Sequential
from keras.layers import De... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57718512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7858253/"
] | The problem is here:
```
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras.callbacks import TensorBoard
```
Do not mix `keras` and `tf.keras` imports, these are **not compatible with each other**, and produc... | I changed `from tensorflow.python.keras.callbacks import TensorBoard`
to `from keras.callbacks import TensorBoard` and it worked for me. |
57,718,512 | I'm trying to try using this model to train on rock, paper, scissor pictures. However, it was trained on 1800 pictures and only has an accuracy of 30-40%. I was then trying to use TensorBoard to see whats going on, but the error in the title appears.
```
from keras.models import Sequential
from keras.layers import De... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57718512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7858253/"
] | The problem is here:
```
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras.callbacks import TensorBoard
```
Do not mix `keras` and `tf.keras` imports, these are **not compatible with each other**, and produc... | for me, this did the job:
```
from tensorflow.keras import datasets, layers, models
from tensorflow import keras
``` |
57,718,512 | I'm trying to try using this model to train on rock, paper, scissor pictures. However, it was trained on 1800 pictures and only has an accuracy of 30-40%. I was then trying to use TensorBoard to see whats going on, but the error in the title appears.
```
from keras.models import Sequential
from keras.layers import De... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57718512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7858253/"
] | The problem is here:
```
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras.callbacks import TensorBoard
```
Do not mix `keras` and `tf.keras` imports, these are **not compatible with each other**, and produc... | It seems that you are mixing imports from `keras` and `tensorflow.keras` (last one is preferred).
<https://www.pyimagesearch.com/2019/10/21/keras-vs-tf-keras-whats-the-difference-in-tensorflow-2-0/>
>
> And most importantly, going forward all deep learning practitioners
> should switch their code to TensorFlow 2.0... |
57,718,512 | I'm trying to try using this model to train on rock, paper, scissor pictures. However, it was trained on 1800 pictures and only has an accuracy of 30-40%. I was then trying to use TensorBoard to see whats going on, but the error in the title appears.
```
from keras.models import Sequential
from keras.layers import De... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57718512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7858253/"
] | I changed `from tensorflow.python.keras.callbacks import TensorBoard`
to `from keras.callbacks import TensorBoard` and it worked for me. | for me, this did the job:
```
from tensorflow.keras import datasets, layers, models
from tensorflow import keras
``` |
57,718,512 | I'm trying to try using this model to train on rock, paper, scissor pictures. However, it was trained on 1800 pictures and only has an accuracy of 30-40%. I was then trying to use TensorBoard to see whats going on, but the error in the title appears.
```
from keras.models import Sequential
from keras.layers import De... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57718512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7858253/"
] | I changed `from tensorflow.python.keras.callbacks import TensorBoard`
to `from keras.callbacks import TensorBoard` and it worked for me. | It seems that you are mixing imports from `keras` and `tensorflow.keras` (last one is preferred).
<https://www.pyimagesearch.com/2019/10/21/keras-vs-tf-keras-whats-the-difference-in-tensorflow-2-0/>
>
> And most importantly, going forward all deep learning practitioners
> should switch their code to TensorFlow 2.0... |
51,664,292 | I'm getting the error below when I'm parsing the xml from the URL in the code. I won't post the XML because it's huge. The link is in the code below.
ERROR:
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipyt... | 2018/08/03 | [
"https://Stackoverflow.com/questions/51664292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1706665/"
] | Instead of checking if `child.find('EmentaMateria').text` is not `None`, you should make sure that `child.find('EmentaMateria')` is not `None` first.
Also, you should store the returning value of `child.find('EmentaMateria')` to avoid calling it twice.
Lastly, you should assign `ementa` a default value if `child.find... | If you are using the code to parse an xml file, open the xml file with a text editor and inspect the tags. In my case there were some rogue tags at the end. Once i removed those, the code worked as expected. |
12,164,692 | So I am new in this field and am not sure how to do this!!But basically here is what i did.
I sshed to somehost.
```
ssh hostname
username: foo
password: bar
```
In one of the directories, there is a huge csv file.. abc.csv
Now, i dont want to copy that file to my local.. but read it from there.
When I asked the ... | 2012/08/28 | [
"https://Stackoverflow.com/questions/12164692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | So, here are your options:
**1.** Declare your **base class** as `abstract` and some methods as well
This approach has two good points: you will be free to implement common methods at the base class (that is, not all of them need to be `abstract`) while any abstract method will **must be** overridden at derived class... | You need to specify an abstract method in Parent:
```
public abstract class Parent
{
public void DoSomething()
{
// Do something here...
}
public abstract void ForceChildToDoSomething();
}
```
This forces the child to implement it:
```
public class Child : Parent
{
public override void ... |
12,164,692 | So I am new in this field and am not sure how to do this!!But basically here is what i did.
I sshed to somehost.
```
ssh hostname
username: foo
password: bar
```
In one of the directories, there is a huge csv file.. abc.csv
Now, i dont want to copy that file to my local.. but read it from there.
When I asked the ... | 2012/08/28 | [
"https://Stackoverflow.com/questions/12164692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | So, here are your options:
**1.** Declare your **base class** as `abstract` and some methods as well
This approach has two good points: you will be free to implement common methods at the base class (that is, not all of them need to be `abstract`) while any abstract method will **must be** overridden at derived class... | Yes, abstract:
```
public abstract Parent
{
protected abstract bool CancelCanExecute(object param);
//more stuff
}
```
It could also be `public`, but not `private`.
Now you can't have a derived class that doesn't either implement `CancelCanExecute` or is itself `abstract` so forcing further derived classes to i... |
12,164,692 | So I am new in this field and am not sure how to do this!!But basically here is what i did.
I sshed to somehost.
```
ssh hostname
username: foo
password: bar
```
In one of the directories, there is a huge csv file.. abc.csv
Now, i dont want to copy that file to my local.. but read it from there.
When I asked the ... | 2012/08/28 | [
"https://Stackoverflow.com/questions/12164692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | So, here are your options:
**1.** Declare your **base class** as `abstract` and some methods as well
This approach has two good points: you will be free to implement common methods at the base class (that is, not all of them need to be `abstract`) while any abstract method will **must be** overridden at derived class... | You should define an interface and then your code should accept only objects that implement that interface. While it is very tempting to use `abstract` and to create a common base class, this approach is (almost) wrong by definition (almost).
In C# and other languages that does not allow multiple-inheritance, creating... |
12,164,692 | So I am new in this field and am not sure how to do this!!But basically here is what i did.
I sshed to somehost.
```
ssh hostname
username: foo
password: bar
```
In one of the directories, there is a huge csv file.. abc.csv
Now, i dont want to copy that file to my local.. but read it from there.
When I asked the ... | 2012/08/28 | [
"https://Stackoverflow.com/questions/12164692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | You need to specify an abstract method in Parent:
```
public abstract class Parent
{
public void DoSomething()
{
// Do something here...
}
public abstract void ForceChildToDoSomething();
}
```
This forces the child to implement it:
```
public class Child : Parent
{
public override void ... | Yes, abstract:
```
public abstract Parent
{
protected abstract bool CancelCanExecute(object param);
//more stuff
}
```
It could also be `public`, but not `private`.
Now you can't have a derived class that doesn't either implement `CancelCanExecute` or is itself `abstract` so forcing further derived classes to i... |
12,164,692 | So I am new in this field and am not sure how to do this!!But basically here is what i did.
I sshed to somehost.
```
ssh hostname
username: foo
password: bar
```
In one of the directories, there is a huge csv file.. abc.csv
Now, i dont want to copy that file to my local.. but read it from there.
When I asked the ... | 2012/08/28 | [
"https://Stackoverflow.com/questions/12164692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | You need to specify an abstract method in Parent:
```
public abstract class Parent
{
public void DoSomething()
{
// Do something here...
}
public abstract void ForceChildToDoSomething();
}
```
This forces the child to implement it:
```
public class Child : Parent
{
public override void ... | You should define an interface and then your code should accept only objects that implement that interface. While it is very tempting to use `abstract` and to create a common base class, this approach is (almost) wrong by definition (almost).
In C# and other languages that does not allow multiple-inheritance, creating... |
28,454,359 | I need to process a large text file containing information on scientific publications, exported from the ScienceDirect search page. I want to store the data in an array of arrays, so that each paper is an array, and all papers are stored in a larger array.
The good part is that each line corresponds to the value I wan... | 2015/02/11 | [
"https://Stackoverflow.com/questions/28454359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4554385/"
] | Since you want to skip blank lines, the easiest thing to do is to check if a line is blank.
```
x = []
with open('my_file.txt', 'r') as f:
temp_list = []
for line in f:
if line.strip(): #line is not blank
temp_list.append(line)
else: #line is blank, i.e., it contains only newlines ... | If first lines are mandatory, you can try to parse them and for each article create structure like this `{'author': 'Name', 'digital_object_identifier': 'Value'}` and so on.
Than you can try to parse most common keywords and append them as fields. So your article woild be like this:
`{'author': 'Name', 'digital_object... |
44,851,342 | How to convert a python dictionary `d = {1:10, 2:20, 3:30, 4:30}` to `{10: [1], 20: [2], 30: [3, 4]}`?
I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter. | 2017/06/30 | [
"https://Stackoverflow.com/questions/44851342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238359/"
] | ```
d = {1:10, 2:20, 3:30, 4:30}
inv = {}
for key, val in d.iteritems():
inv[val] = inv.get(val, []) + [key]
```
Try this! | ```
o = {}
for k,v in d.iteritems():
if v in o:
o[v].append(k)
else:
o[v] = [k]
```
`o = {10: [1], 20: [2], 30: [3, 4]}` |
44,851,342 | How to convert a python dictionary `d = {1:10, 2:20, 3:30, 4:30}` to `{10: [1], 20: [2], 30: [3, 4]}`?
I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter. | 2017/06/30 | [
"https://Stackoverflow.com/questions/44851342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238359/"
] | This use case is easily handled by [*dict.setdefault()*](https://docs.python.org/3/library/stdtypes.html#dict.setdefault)
```
>>> d = {1:10, 2:20, 3:30, 4:30}
>>> e = {}
>>> for x, y in d.items():
e.setdefault(y, []).append(x)
>>> e
{10: [1], 20: [2], 30: [3, 4]}
```
An alternative is to use [collections.de... | ```
o = {}
for k,v in d.iteritems():
if v in o:
o[v].append(k)
else:
o[v] = [k]
```
`o = {10: [1], 20: [2], 30: [3, 4]}` |
44,851,342 | How to convert a python dictionary `d = {1:10, 2:20, 3:30, 4:30}` to `{10: [1], 20: [2], 30: [3, 4]}`?
I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter. | 2017/06/30 | [
"https://Stackoverflow.com/questions/44851342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238359/"
] | Reversing keys and values in a python dict is a bit tricky. You should have in mind that a python dict must have a `unique` keys.
So, if you know that when reversing keys and values of your current dict will have a unique keys, you can use a simple `dict comprehension` like this example:
```
{v:k for k,v in my_dict.... | ```
o = {}
for k,v in d.iteritems():
if v in o:
o[v].append(k)
else:
o[v] = [k]
```
`o = {10: [1], 20: [2], 30: [3, 4]}` |
44,851,342 | How to convert a python dictionary `d = {1:10, 2:20, 3:30, 4:30}` to `{10: [1], 20: [2], 30: [3, 4]}`?
I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter. | 2017/06/30 | [
"https://Stackoverflow.com/questions/44851342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238359/"
] | This use case is easily handled by [*dict.setdefault()*](https://docs.python.org/3/library/stdtypes.html#dict.setdefault)
```
>>> d = {1:10, 2:20, 3:30, 4:30}
>>> e = {}
>>> for x, y in d.items():
e.setdefault(y, []).append(x)
>>> e
{10: [1], 20: [2], 30: [3, 4]}
```
An alternative is to use [collections.de... | ```
d = {1:10, 2:20, 3:30, 4:30}
inv = {}
for key, val in d.iteritems():
inv[val] = inv.get(val, []) + [key]
```
Try this! |
44,851,342 | How to convert a python dictionary `d = {1:10, 2:20, 3:30, 4:30}` to `{10: [1], 20: [2], 30: [3, 4]}`?
I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter. | 2017/06/30 | [
"https://Stackoverflow.com/questions/44851342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8238359/"
] | Reversing keys and values in a python dict is a bit tricky. You should have in mind that a python dict must have a `unique` keys.
So, if you know that when reversing keys and values of your current dict will have a unique keys, you can use a simple `dict comprehension` like this example:
```
{v:k for k,v in my_dict.... | ```
d = {1:10, 2:20, 3:30, 4:30}
inv = {}
for key, val in d.iteritems():
inv[val] = inv.get(val, []) + [key]
```
Try this! |
29,385,340 | I'm trying to find all the divisors ("i" in my case) of a given number ("a" in my case) with no remainder (a % i == 0). I'm running a loop that goes trough all the vales of i starting from 1 up to the value of a. The problem is that only first 2 products of a % i == 0 are taken into account. The rest is left out. Why i... | 2015/04/01 | [
"https://Stackoverflow.com/questions/29385340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4262683/"
] | The behavior of the script is correct. See for yourself:

I think it's your logic, and what you are trying to achieve is:
```
a = 999
i = 1
d = []
while (i < a):
if(a % i == 0):
d.append(i)
i += 1
print (d)
```
Outputs:
```
[1, ... | To complement Anton's answer, a more Pythonic way to loop would be:
```
a, d = 999, []
for i in range(1, a):
if a%i == 0:
d.append(i)
```
You can also take advantage of the fact that object have a [Boolean value](https://docs.python.org/3.4/reference/datamodel.html#object.__bool__):
```
if not a%i:
```... |
41,690,010 | [](https://i.stack.imgur.com/FnX1O.png)In python selenium, how to create xpath for below code which needs only id and class:
```
<button type="button" id="ext-gen756" class=" x-btn-text">Save</button>
```
And I also need to select Global ID from bel... | 2017/01/17 | [
"https://Stackoverflow.com/questions/41690010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5907308/"
] | If you want to club `id` and `class` together in your `xpath` try like this-
```
driver.find_element_by_xpath('//button[@id="ext-gen756"][@class=" x-btn-text"]');
```
You can also try the same using `AND` -
```
driver.find_element_by_xpath('//button[@id="ext-gen756" and @class=" x-btn-text"]');
```
**EDITED**
Yo... | Just answering my own question after a long time had a look on this. The Question was posted when I was new in xpath topics.
```
<button type="button" id="ext-gen756" class=" x-btn-text">Save</button>
```
in terms of id and class:
```
driver.find_element_by_xpath("//button[@id='ext-gen756'][@class=' x-btn-text']")
... |
5,048,217 | i have some data stored in a .txt file in this format:
```
----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces 3292532113435532419963
```
don't ask...
i have many lines of this, and i need a way to add more digits to ... | 2011/02/19 | [
"https://Stackoverflow.com/questions/5048217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623985/"
] | As a general principle, there's no shortcut to "inserting" new data in the middle of a text file. You will need to make a copy of the entire original file in a new file, modifying your desired line(s) of text on the way.
For example:
```
with open("input.txt") as infile:
with open("output.txt", "w") as outfile:
... | Copy the file, line by line, to another file. When you get to the line that needs extra chars then add them before writing. |
5,048,217 | i have some data stored in a .txt file in this format:
```
----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces 3292532113435532419963
```
don't ask...
i have many lines of this, and i need a way to add more digits to ... | 2011/02/19 | [
"https://Stackoverflow.com/questions/5048217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623985/"
] | As a general principle, there's no shortcut to "inserting" new data in the middle of a text file. You will need to make a copy of the entire original file in a new file, modifying your desired line(s) of text on the way.
For example:
```
with open("input.txt") as infile:
with open("output.txt", "w") as outfile:
... | Check out the [fileinput](http://docs.python.org/py3k/library/fileinput.html#module-fileinput) module, it can do sort of "inplace" edits with files. though I believe temporary files are still involved in the internal process.
```
import fileinput
for line in fileinput.input('input.txt', inplace=1, backup='.orig'):
... |
5,048,217 | i have some data stored in a .txt file in this format:
```
----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces 3292532113435532419963
```
don't ask...
i have many lines of this, and i need a way to add more digits to ... | 2011/02/19 | [
"https://Stackoverflow.com/questions/5048217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623985/"
] | As a general principle, there's no shortcut to "inserting" new data in the middle of a text file. You will need to make a copy of the entire original file in a new file, modifying your desired line(s) of text on the way.
For example:
```
with open("input.txt") as infile:
with open("output.txt", "w") as outfile:
... | ```
target_chain = '1020414646canBeFollowedBySpaces 3292532113435532419963'
to_add = '01846372998'
with open('zaza.txt','rb+') as f:
ch = f.read()
x = ch.find(target_chain)
f.seek(x + len(target_chain),0)
f.write(to_add)
f.write(ch[x + len(target_chain):])
```
In this method it's absolutely ob... |
5,048,217 | i have some data stored in a .txt file in this format:
```
----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces 3292532113435532419963
```
don't ask...
i have many lines of this, and i need a way to add more digits to ... | 2011/02/19 | [
"https://Stackoverflow.com/questions/5048217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623985/"
] | Check out the [fileinput](http://docs.python.org/py3k/library/fileinput.html#module-fileinput) module, it can do sort of "inplace" edits with files. though I believe temporary files are still involved in the internal process.
```
import fileinput
for line in fileinput.input('input.txt', inplace=1, backup='.orig'):
... | Copy the file, line by line, to another file. When you get to the line that needs extra chars then add them before writing. |
5,048,217 | i have some data stored in a .txt file in this format:
```
----------|||||||||||||||||||||||||-----------|||||||||||
1029450386abcdefghijklmnopqrstuvwxy0293847719184756301943
1020414646canBeFollowedBySpaces 3292532113435532419963
```
don't ask...
i have many lines of this, and i need a way to add more digits to ... | 2011/02/19 | [
"https://Stackoverflow.com/questions/5048217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623985/"
] | ```
target_chain = '1020414646canBeFollowedBySpaces 3292532113435532419963'
to_add = '01846372998'
with open('zaza.txt','rb+') as f:
ch = f.read()
x = ch.find(target_chain)
f.seek(x + len(target_chain),0)
f.write(to_add)
f.write(ch[x + len(target_chain):])
```
In this method it's absolutely ob... | Copy the file, line by line, to another file. When you get to the line that needs extra chars then add them before writing. |
2,541,954 | I basically want to be able to:
* Write a few functions in python (with the minimum amount of extra meta data)
* Turn these functions into a web service (with the minimum of effort / boiler plate)
* Automatically generate some javascript functions / objects for rpc (this should prevent me from doing as many stupid thi... | 2010/03/29 | [
"https://Stackoverflow.com/questions/2541954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47741/"
] | Yes there is, there is [Pyjamas](http://pyjs.org/). Some people bill this as the "[GWT](http://code.google.com/webtoolkit/) for Python" | It looks like using a javascript XML RPC client (there is jquery plugin for this) together with an XML RPC server is a good way to go.
The jquery plugin will introspect your rpc service and will populate method names make it impossible to mis type the name of a method call without getting early warning. It will not ho... |
36,510,431 | I am very new to python and programming in general and I want to print out the string "forward" whenever i press "w" on the keyboard. It is a test which I will transform into a remote control for a motorized vehicle.
```
while True:
if raw_input("") == "w":
print "forward"
```
Why does it just print out ... | 2016/04/08 | [
"https://Stackoverflow.com/questions/36510431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909346/"
] | In Python 2.x the raw\_input function will display all characters pressed, and return upon receiving a newline. If you want different behaviour you'll have to use a different function. Here's a portable version of getch for Python, it will return every key press:
```
# Copied from: stackoverflow.com/questions/510357/p... | `raw_input` reads an entire line of input. The line you're inputting is made visible to you, and you can do things like type some text:
```
aiplanes
```
go left a few characters to fix your typo:
```
airplanes
```
go back to the end and delete a character because you didn't mean to make it plural:
```
airplane
... |
74,134,047 | I need some help recursively searching a python dict that contains nested lists.
I have a structure like the below example. The value of key "c" is a list of one or more dicts. The structure can be nested multiple times (as you can see in the second item), but the pattern is the same. In all likelihood, the nested dep... | 2022/10/20 | [
"https://Stackoverflow.com/questions/74134047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20287604/"
] | (Just posting this here from Matt Wards comment as I cannot mark the comment as the answer.)
As the comment suggests, Visual Studio for Mac seems to only use launchSettings.json for Asp.Net projects. I was working with a Console App.
Visual Studio for PC uses launchSettings.json for console applications too but not t... | Well, you can try to change the properties of the file and how VS Studio treats it during build.
1. Right-click on `launchSettings.json` and choose `Properties`
2. Set the below properties as follows:
```
Build action -> Content
Copy to directory -> Copy if newer
```
See if this helps. |
74,134,047 | I need some help recursively searching a python dict that contains nested lists.
I have a structure like the below example. The value of key "c" is a list of one or more dicts. The structure can be nested multiple times (as you can see in the second item), but the pattern is the same. In all likelihood, the nested dep... | 2022/10/20 | [
"https://Stackoverflow.com/questions/74134047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20287604/"
] | (Just posting this here from Matt Wards comment as I cannot mark the comment as the answer.)
As the comment suggests, Visual Studio for Mac seems to only use launchSettings.json for Asp.Net projects. I was working with a Console App.
Visual Studio for PC uses launchSettings.json for console applications too but not t... | Change the top line of your project file to the following:
`<Project Sdk="Microsoft.NET.Sdk.Web">`
(It was probably missing the `.Web` namespace) |
44,756,447 | I've got a lot of commands running in impala shell, in the middle of them I now have a need to run a python script. The script itself is fine when run from outside the impala shell.
When I run from within the impala shell using ! or "shell" (documentation found [here](https://www.cloudera.com/documentation/enterprise/... | 2017/06/26 | [
"https://Stackoverflow.com/questions/44756447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5065581/"
] | This is caused by a known bug [IMPALA-4664](https://issues.apache.org/jira/browse/IMPALA-4664).
A workaround is to leave a space after "!". Can you try this (note the space):
! /home/DOMAIN\_USERS/somemorefolders/python/script.py | Thanks to [@BoboDarph](https://stackoverflow.com/users/8085234/bobodarph "bobodarph") for help in getting there.
I was able to use `!~/somemorefolders/python/script.py` as I could get there from my home directory.
I still think it's a bit shortsighted of impala to force things into lower case but there you go. |
43,021,399 | Just creating a python program that creates a function named letterX, that ... well makes an X. The two lines must be 90 degrees from each other. The pointer ends at the initial position.
I solved this pretty easily, just wondering if you can put this into a loop or just simplify it. I don't know how since i have to c... | 2017/03/25 | [
"https://Stackoverflow.com/questions/43021399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7767472/"
] | Like francescalus commented, it looks like problem is related to integer arithmetic in Fortran.
You may modify the first `if` statement in Matlab implementation as follows:
```
if fix(k/2) ~= j/2
```
---
In your second part, there is a typo error in the Matlab code.
You wrote `x2` instead of `x1`.
Correct co... | I made a small fortran program based on your posts. Then put it through my f2matlab fortran source to matlab source converter (matlab file exchange). Here is the fortran:
```
program kt_f
implicit none
integer j,n,k,f1,f2
real x1,x2,h,sum1,sum2
n=100
k=50
do j=1,n-1
k=j
if(k/2/=j/2.) then
if(j==1) x1=x1+h
if(j... |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | No. Types defined in C cannot be monkeypatched. | No, because I'm pretty sure all the built-in types are written in optimized C and thus can't be modified with Python. When I try it, I just get:
```
TypeError: can't set attributes of built-in/extension type 'list'
``` |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | Nope, you gotta subclass!
```
>>> import string
>>> class MyString(str):
... def disemvowel(self):
... return MyString(string.translate(self, None, "aeiou"))
...
>>> s = MyString("this is only a test")
>>> s.disemvowel()
'ths s nly tst'
```
---
Or more specific to your example
```
>>> class MyList(li... | No, because I'm pretty sure all the built-in types are written in optimized C and thus can't be modified with Python. When I try it, I just get:
```
TypeError: can't set attributes of built-in/extension type 'list'
``` |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | It can be done in pure Python with this incredibly clever module:
<https://pypi.python.org/pypi/forbiddenfruit>
For example:
```
import functools
import ctypes
import __builtin__
import operator
class PyObject(ctypes.Structure):
pass
Py_ssize_t = hasattr(ctypes.pythonapi, 'Py_InitModule4_64') and ctypes.c_int6... | No, because I'm pretty sure all the built-in types are written in optimized C and thus can't be modified with Python. When I try it, I just get:
```
TypeError: can't set attributes of built-in/extension type 'list'
``` |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | No. Types defined in C cannot be monkeypatched. | The best you can do appears to be deriving a class from the built-in type. For example:
```
class mylist(list):
def myfunc(self, x):
self.append(x)
test = mylist([1,2,3,4])
test.myfunc(99)
```
(You could even name it "list" so as to get the same constructor, if you wanted.) However, you cannot directly ... |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | It can be done in pure Python with this incredibly clever module:
<https://pypi.python.org/pypi/forbiddenfruit>
For example:
```
import functools
import ctypes
import __builtin__
import operator
class PyObject(ctypes.Structure):
pass
Py_ssize_t = hasattr(ctypes.pythonapi, 'Py_InitModule4_64') and ctypes.c_int6... | No. Types defined in C cannot be monkeypatched. |
6,738,987 | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding ... | 2011/07/18 | [
"https://Stackoverflow.com/questions/6738987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614953/"
] | Nope, you gotta subclass!
```
>>> import string
>>> class MyString(str):
... def disemvowel(self):
... return MyString(string.translate(self, None, "aeiou"))
...
>>> s = MyString("this is only a test")
>>> s.disemvowel()
'ths s nly tst'
```
---
Or more specific to your example
```
>>> class MyList(li... | The best you can do appears to be deriving a class from the built-in type. For example:
```
class mylist(list):
def myfunc(self, x):
self.append(x)
test = mylist([1,2,3,4])
test.myfunc(99)
```
(You could even name it "list" so as to get the same constructor, if you wanted.) However, you cannot directly ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.