qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
26,902,359 | I have example list like this:
```
example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
```
Now, I check if it has empty string like this:
```
has_empty = False;
for list1 in example_list:
for val1 in list1:
if val1 == '':
has_empty = True
print(has_empty)
```
This works OK as it prints True, but looking for more pythonik method? | 2014/11/13 | [
"https://Stackoverflow.com/questions/26902359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654650/"
] | Just convert the whole list to string and check for the presence of empty strings, i.e. `''` or `""` in it.
```
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
>>> any(empty in str(example_list) for empty in ("''", '""'))
True
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], [ 'gg', '\'']]
>>> any(empty in str(example_list) for empty in ("''", '""'))
False
```
Note that this won't work with lists which have empty string as part of the string itself - example `'hello "" world'`
Another approach could be to flatten the dict and check for presence of empty strings in it
```
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['gg', 'hello "" world']]
>>> '' in [item for sublist in example_list for item in sublist]
False
>>> example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg', 'hello "" world']]
>>> '' in [item for sublist in example_list for item in sublist]
True
``` | using `map` and `lambda`:
```
>>> def check_empty(l):
... k=map(lambda x: '' in x and True,l)
... for x in k:
... if x==True:
... return True
... return False
...
>>> check_empty(example_list)
False
>>> example_list
[['aaa'], ['fff', 'gg'], ['ff'], ['gg', 'hello "" world']]
>>> example_list = [['aaa'], ['fff', 'gg',''], ['ff'], ['gg', 'hello "" world']]
>>> check_empty(example_list)
True
``` |
26,902,359 | I have example list like this:
```
example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
```
Now, I check if it has empty string like this:
```
has_empty = False;
for list1 in example_list:
for val1 in list1:
if val1 == '':
has_empty = True
print(has_empty)
```
This works OK as it prints True, but looking for more pythonik method? | 2014/11/13 | [
"https://Stackoverflow.com/questions/26902359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654650/"
] | using `map` and `lambda`:
```
>>> def check_empty(l):
... k=map(lambda x: '' in x and True,l)
... for x in k:
... if x==True:
... return True
... return False
...
>>> check_empty(example_list)
False
>>> example_list
[['aaa'], ['fff', 'gg'], ['ff'], ['gg', 'hello "" world']]
>>> example_list = [['aaa'], ['fff', 'gg',''], ['ff'], ['gg', 'hello "" world']]
>>> check_empty(example_list)
True
``` | ```
example_list = [['aaa'], ['fff', 'gg'], ['ff'], ['', 'gg']]
has_empty = False
for list in example_list:
if '' in list:
has_empty = True
print(has_empty)
``` |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | You cannot have two primary keys in a table. Instead, you must use a compound primary key.
This can be done by adding a `PrimaryKeyConstraint` in your model as below (remember to add a comma before closing the bracket in `__table_args__`:
```
from db import PrimaryKeyConstraint
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
__table_args__ = (
PrimaryKeyConstraint('application_essay_id', 'theme_essay_id'),
)
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"))
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"))
state = db.Column(db.String, default="pending")
``` | You get this error because you have trailing commas after your `Column()` definitions, which cause `application_essay_id` and `theme_essay_id` to each be parsed as a one-element tuple containing a `Column` instead of just a `Column`. This stops SQLAlchemy from "seeing" that the columns are present, and consequently causes your model not to contain any primary key column.
If you simply replace
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
```
with
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True)
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True)
```
then your error will be fixed.
Aside: since SQLAlchemy (and Alembic and Flask-SQLAlchemy) contain some syntaxes for declaring models/tables that involve passing a comma-separated sequence of `Column`s as arguments (e.g. to `op.create_table()` or the `Table()` constructor) and others that involve declaring a class with `Column`s as class properties, it's *really easy* to run into this error by cutting and pasting `Column` declarations from the first syntax to the second and forgetting to remove some of the commas. I suspect that this easy-to-make mistake is the reason this question has such a huge number of views - over 16000 at the time that I post this answer. |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | You cannot have two primary keys in a table. Instead, you must use a compound primary key.
This can be done by adding a `PrimaryKeyConstraint` in your model as below (remember to add a comma before closing the bracket in `__table_args__`:
```
from db import PrimaryKeyConstraint
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
__table_args__ = (
PrimaryKeyConstraint('application_essay_id', 'theme_essay_id'),
)
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"))
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"))
state = db.Column(db.String, default="pending")
``` | I got this error because of a syntax mistake. I.v misspell 'primary\_key' in my declaration |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | You cannot have two primary keys in a table. Instead, you must use a compound primary key.
This can be done by adding a `PrimaryKeyConstraint` in your model as below (remember to add a comma before closing the bracket in `__table_args__`:
```
from db import PrimaryKeyConstraint
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
__table_args__ = (
PrimaryKeyConstraint('application_essay_id', 'theme_essay_id'),
)
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"))
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"))
state = db.Column(db.String, default="pending")
``` | In relational database tables, it must require the candidate key. You can refer this article <https://en.wikipedia.org/wiki/Candidate_key>.
You just need to add primary key or composite primary key. For composite primary key, you can use below line in Flask APP. No need to import any thing. All will be take care by **db** variable in Flask.
In your example,
```
db.PrimaryKeyConstraint(application_essay_id , application_essay_id )
``` |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | You cannot have two primary keys in a table. Instead, you must use a compound primary key.
This can be done by adding a `PrimaryKeyConstraint` in your model as below (remember to add a comma before closing the bracket in `__table_args__`:
```
from db import PrimaryKeyConstraint
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
__table_args__ = (
PrimaryKeyConstraint('application_essay_id', 'theme_essay_id'),
)
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"))
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"))
state = db.Column(db.String, default="pending")
``` | Though good answers have been given above, One trivial mistake that one could make is to create a table without any primary key. Though it may seem unnecessary, a primary key needs to be created for every table. Else the error above gets thrown. |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | You get this error because you have trailing commas after your `Column()` definitions, which cause `application_essay_id` and `theme_essay_id` to each be parsed as a one-element tuple containing a `Column` instead of just a `Column`. This stops SQLAlchemy from "seeing" that the columns are present, and consequently causes your model not to contain any primary key column.
If you simply replace
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
```
with
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True)
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True)
```
then your error will be fixed.
Aside: since SQLAlchemy (and Alembic and Flask-SQLAlchemy) contain some syntaxes for declaring models/tables that involve passing a comma-separated sequence of `Column`s as arguments (e.g. to `op.create_table()` or the `Table()` constructor) and others that involve declaring a class with `Column`s as class properties, it's *really easy* to run into this error by cutting and pasting `Column` declarations from the first syntax to the second and forgetting to remove some of the commas. I suspect that this easy-to-make mistake is the reason this question has such a huge number of views - over 16000 at the time that I post this answer. | I got this error because of a syntax mistake. I.v misspell 'primary\_key' in my declaration |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | You get this error because you have trailing commas after your `Column()` definitions, which cause `application_essay_id` and `theme_essay_id` to each be parsed as a one-element tuple containing a `Column` instead of just a `Column`. This stops SQLAlchemy from "seeing" that the columns are present, and consequently causes your model not to contain any primary key column.
If you simply replace
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
```
with
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True)
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True)
```
then your error will be fixed.
Aside: since SQLAlchemy (and Alembic and Flask-SQLAlchemy) contain some syntaxes for declaring models/tables that involve passing a comma-separated sequence of `Column`s as arguments (e.g. to `op.create_table()` or the `Table()` constructor) and others that involve declaring a class with `Column`s as class properties, it's *really easy* to run into this error by cutting and pasting `Column` declarations from the first syntax to the second and forgetting to remove some of the commas. I suspect that this easy-to-make mistake is the reason this question has such a huge number of views - over 16000 at the time that I post this answer. | In relational database tables, it must require the candidate key. You can refer this article <https://en.wikipedia.org/wiki/Candidate_key>.
You just need to add primary key or composite primary key. For composite primary key, you can use below line in Flask APP. No need to import any thing. All will be take care by **db** variable in Flask.
In your example,
```
db.PrimaryKeyConstraint(application_essay_id , application_essay_id )
``` |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | You get this error because you have trailing commas after your `Column()` definitions, which cause `application_essay_id` and `theme_essay_id` to each be parsed as a one-element tuple containing a `Column` instead of just a `Column`. This stops SQLAlchemy from "seeing" that the columns are present, and consequently causes your model not to contain any primary key column.
If you simply replace
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
```
with
```
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True)
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True)
```
then your error will be fixed.
Aside: since SQLAlchemy (and Alembic and Flask-SQLAlchemy) contain some syntaxes for declaring models/tables that involve passing a comma-separated sequence of `Column`s as arguments (e.g. to `op.create_table()` or the `Table()` constructor) and others that involve declaring a class with `Column`s as class properties, it's *really easy* to run into this error by cutting and pasting `Column` declarations from the first syntax to the second and forgetting to remove some of the commas. I suspect that this easy-to-make mistake is the reason this question has such a huge number of views - over 16000 at the time that I post this answer. | Though good answers have been given above, One trivial mistake that one could make is to create a table without any primary key. Though it may seem unnecessary, a primary key needs to be created for every table. Else the error above gets thrown. |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | Though good answers have been given above, One trivial mistake that one could make is to create a table without any primary key. Though it may seem unnecessary, a primary key needs to be created for every table. Else the error above gets thrown. | I got this error because of a syntax mistake. I.v misspell 'primary\_key' in my declaration |
24,872,541 | When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong?
```
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
```
**My model:**
```
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
``` | 2014/07/21 | [
"https://Stackoverflow.com/questions/24872541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/465623/"
] | Though good answers have been given above, One trivial mistake that one could make is to create a table without any primary key. Though it may seem unnecessary, a primary key needs to be created for every table. Else the error above gets thrown. | In relational database tables, it must require the candidate key. You can refer this article <https://en.wikipedia.org/wiki/Candidate_key>.
You just need to add primary key or composite primary key. For composite primary key, you can use below line in Flask APP. No need to import any thing. All will be take care by **db** variable in Flask.
In your example,
```
db.PrimaryKeyConstraint(application_essay_id , application_essay_id )
``` |
5,022,725 | I have a python class `foo` that contains:
* data (ints, floats)
* lists (of ints, of floats, and of other objects)
* dictionaries (of ints, of floats, of other objects)
Assuming that there are no back-references (cycles), is there an easy way to measure the total memory usage of a `foo` object ?
Essentially, I am looking for a ***recursive version*** of `sys.getsizeof`
A few of the tools I came across included: heapy, objgraph and gc, but I don't think any of them are up to the task (I may be corrected on this) | 2011/02/16 | [
"https://Stackoverflow.com/questions/5022725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496011/"
] | Try [Pympler](http://pypi.python.org/pypi/Pympler/), which describes itself as *"A development tool to measure, monitor and analyze the memory behavior of Python objects."*
Something along the lines of
```
>>> import pympler
>>> print pympler.asizeof.asizeof(your_object)
```
has been helpful to me in the past.
See [examples](https://pympler.readthedocs.io/en/latest/intro.html#usage-examples) from the official documentation and [other questions](https://stackoverflow.com/search?q=pympler) on stack overflow. | I'm not sure if you're trying to get the size of the type, or the actual complex object, but looking at getsizeof, the documentation points to this recipe for a robust recursive version:
<http://code.activestate.com/recipes/577504/>
so I'd assume there's no 'stock' python call that will do it, otherwise the docs would mention it. |
14,415,353 | I have a clean virtual machine with XP SP3 32-bit and ActivePython 2.7.2 32-bit community edition, current dir is "C:\test". I have placed `sitecustomize.py` with "print( 'dir1' )" code indie "C:\test\dir1" and `sitecustomize.py` with "print( 'dir2' )" code indie "C:\test\dir2".
If i set `PYTHONPATH` to `dir1` or `dir2`, corresponding `sitecustomize.py` is executed:
```
C:\test> set PYTHONPATH=C:\test\dir1\
C:\text> python
dir1
>>>exit()
C:\test> set PYTHONPATH=C:\test\dir2\
C:\text> python
dir2
```
But if i add both dirs to pythonpath, only `sitecustomize.py` of **first** dir is executed:
```
C:\test> set PYTHONPATH=C:\test\dir1\;C:\test\dir2\
C:\text> python
dir1
>>>exit()
C:\test> set PYTHONPATH=C:\test\dir2\;C:\test\dir1\
C:\text> python
dir2
```
So is it possible to have multiple dirs in `PYTHONPATH` and multiple `sitecustomize.py` or i'm limited to one? Documentation states that i can have many dirs in `PYTHONPATH`, but it don't say anything about `sitecustomize.py` | 2013/01/19 | [
"https://Stackoverflow.com/questions/14415353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69882/"
] | Yes, you can list multiple directories in `PYTHONPATH`.
`sitecustomize` is a module that automatically gets imported when the interpreter starts up. Consequently, if there are several `sitecustomize.py` on your `PYTHONPATH`, only the first one will be loaded.
The process is described in the [documentation](http://docs.python.org/2/library/site.html):
>
> After these path manipulations, an attempt is made to import a module named `sitecustomize`, which can perform arbitrary site-specific customizations. It is typically created by a system administrator in the site-packages directory. If this import fails with an `ImportError` exception, it is silently ignored.
>
>
> | I sometimes do sys.path.append() to add paths |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | The `open` function operates relative to the current process working directory, not the module it is called from. If the path must be module-relative, do this:
```
import os.path
f = open(os.path.dirname(__file__) + '/../data.yml')
``` | Having encountered this question and not being satisfied with the answer, I ran across a different solution. It took the following to get what I wanted.
1. Determine the current directory using `os.path.dirname`:
`current_directory = os.path.dirname(__file__)`
2. Determine the parent directory using `os.path.split`:
`parent_directory = os.path.split(current_directory)[0] # Repeat as needed`
3. Join parent\_directory with any sub-directories:
`file_path = os.path.join(parent_directory, 'path', 'to', 'file')`
4. Open the file:
`open(file_path)`
Combined together:
```
open(os.path.join(os.path.split(os.path.dirname(__file__))[0], 'path', 'to', 'file')
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | The `open` function operates relative to the current process working directory, not the module it is called from. If the path must be module-relative, do this:
```
import os.path
f = open(os.path.dirname(__file__) + '/../data.yml')
``` | *alternative solution*
You can also use the `sys` module to get the current working directory.
Thus, another alternative to do the same thing would be:
```
import sys
f = open(sys.path[0] + '/../data.yml')
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | The `open` function operates relative to the current process working directory, not the module it is called from. If the path must be module-relative, do this:
```
import os.path
f = open(os.path.dirname(__file__) + '/../data.yml')
``` | I wrote a little function called get\_parent\_directory() which might help getting the path of the parent directory:
```
import sys
def get_parent_directory():
list = sys.path[0].split('/')[:-1]
return_str = ''
for element in list:
return_str += element + '/'
return return_str.rstrip('/')
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | The `open` function operates relative to the current process working directory, not the module it is called from. If the path must be module-relative, do this:
```
import os.path
f = open(os.path.dirname(__file__) + '/../data.yml')
``` | @ThatsAmorais answer in a function
```
import os
def getParent(path: str, levels=1) -> str:
"""
@param path: starts without /
@return: Parent path at the specified levels above.
"""
current_directory = os.path.dirname(__file__)
parent_directory = current_directory
for i in range(0, levels):
parent_directory = os.path.split(parent_directory)[0]
file_path = os.path.join(parent_directory, path)
return file_path
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | Having encountered this question and not being satisfied with the answer, I ran across a different solution. It took the following to get what I wanted.
1. Determine the current directory using `os.path.dirname`:
`current_directory = os.path.dirname(__file__)`
2. Determine the parent directory using `os.path.split`:
`parent_directory = os.path.split(current_directory)[0] # Repeat as needed`
3. Join parent\_directory with any sub-directories:
`file_path = os.path.join(parent_directory, 'path', 'to', 'file')`
4. Open the file:
`open(file_path)`
Combined together:
```
open(os.path.join(os.path.split(os.path.dirname(__file__))[0], 'path', 'to', 'file')
``` | *alternative solution*
You can also use the `sys` module to get the current working directory.
Thus, another alternative to do the same thing would be:
```
import sys
f = open(sys.path[0] + '/../data.yml')
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | Having encountered this question and not being satisfied with the answer, I ran across a different solution. It took the following to get what I wanted.
1. Determine the current directory using `os.path.dirname`:
`current_directory = os.path.dirname(__file__)`
2. Determine the parent directory using `os.path.split`:
`parent_directory = os.path.split(current_directory)[0] # Repeat as needed`
3. Join parent\_directory with any sub-directories:
`file_path = os.path.join(parent_directory, 'path', 'to', 'file')`
4. Open the file:
`open(file_path)`
Combined together:
```
open(os.path.join(os.path.split(os.path.dirname(__file__))[0], 'path', 'to', 'file')
``` | I wrote a little function called get\_parent\_directory() which might help getting the path of the parent directory:
```
import sys
def get_parent_directory():
list = sys.path[0].split('/')[:-1]
return_str = ''
for element in list:
return_str += element + '/'
return return_str.rstrip('/')
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | Having encountered this question and not being satisfied with the answer, I ran across a different solution. It took the following to get what I wanted.
1. Determine the current directory using `os.path.dirname`:
`current_directory = os.path.dirname(__file__)`
2. Determine the parent directory using `os.path.split`:
`parent_directory = os.path.split(current_directory)[0] # Repeat as needed`
3. Join parent\_directory with any sub-directories:
`file_path = os.path.join(parent_directory, 'path', 'to', 'file')`
4. Open the file:
`open(file_path)`
Combined together:
```
open(os.path.join(os.path.split(os.path.dirname(__file__))[0], 'path', 'to', 'file')
``` | @ThatsAmorais answer in a function
```
import os
def getParent(path: str, levels=1) -> str:
"""
@param path: starts without /
@return: Parent path at the specified levels above.
"""
current_directory = os.path.dirname(__file__)
parent_directory = current_directory
for i in range(0, levels):
parent_directory = os.path.split(parent_directory)[0]
file_path = os.path.join(parent_directory, path)
return file_path
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | *alternative solution*
You can also use the `sys` module to get the current working directory.
Thus, another alternative to do the same thing would be:
```
import sys
f = open(sys.path[0] + '/../data.yml')
``` | I wrote a little function called get\_parent\_directory() which might help getting the path of the parent directory:
```
import sys
def get_parent_directory():
list = sys.path[0].split('/')[:-1]
return_str = ''
for element in list:
return_str += element + '/'
return return_str.rstrip('/')
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | *alternative solution*
You can also use the `sys` module to get the current working directory.
Thus, another alternative to do the same thing would be:
```
import sys
f = open(sys.path[0] + '/../data.yml')
``` | @ThatsAmorais answer in a function
```
import os
def getParent(path: str, levels=1) -> str:
"""
@param path: starts without /
@return: Parent path at the specified levels above.
"""
current_directory = os.path.dirname(__file__)
parent_directory = current_directory
for i in range(0, levels):
parent_directory = os.path.split(parent_directory)[0]
file_path = os.path.join(parent_directory, path)
return file_path
``` |
2,753,254 | How to open a file in the parent directory in python in AppEngine?
I have a python file module/mod.py with the following code
```
f = open('../data.yml')
z = yaml.load(f)
f.close()
```
data.yml is in the parent dir of module. The error I get is
```
IOError: [Errno 13] file not accessible: '../data.yml'
```
I am using AppEngine SDK 1.3.3.
Is there a work around for this? | 2010/05/02 | [
"https://Stackoverflow.com/questions/2753254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177526/"
] | I wrote a little function called get\_parent\_directory() which might help getting the path of the parent directory:
```
import sys
def get_parent_directory():
list = sys.path[0].split('/')[:-1]
return_str = ''
for element in list:
return_str += element + '/'
return return_str.rstrip('/')
``` | @ThatsAmorais answer in a function
```
import os
def getParent(path: str, levels=1) -> str:
"""
@param path: starts without /
@return: Parent path at the specified levels above.
"""
current_directory = os.path.dirname(__file__)
parent_directory = current_directory
for i in range(0, levels):
parent_directory = os.path.split(parent_directory)[0]
file_path = os.path.join(parent_directory, path)
return file_path
``` |
44,599,379 | I have a python script that should print all the ID's of people in my JSON files stored in elasticsearch. But I only get ten results(truncated), as I know that by default only 10 results are shown.
```
from elasticsearch import Elasticsearch
import sys
es = Elasticsearch()
res = es.search(index="my_docs", body={"query": {"match_all": {}}})
print("%d documents found" % res['hits']['total'])
for doc in res['hits']['hits']:
print (" Doc ID: %s" % (doc['_id']))
```
It says 5000 Documents found but returns 10 ID's only.
What is the way to get all documents' Doc ID's printed from my collection in Elasticsearch? | 2017/06/16 | [
"https://Stackoverflow.com/questions/44599379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8088493/"
] | You need to tell ES to return more than ten results (which is the default):
```
body={"query": {"match_all": {}}, 'results': 1000}
```
For very large amounts of results you need to get all results in a paging manner; ES provides means to do this. | 1. Use Scroll api if Number of documents exceeds 10000.
2. Use Search api with limit to get specified count. |
30,234,792 | I've got a data structure like these:
```
[{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}, ...]
```
a list of dictionaries. My task is to find duplicate entries regarding the remote value. If i found entries with the same remote value than i want to delete all except the one with the newest timestamp value.
In this example i had to find and delete the secound dictionary because the third one has the same remote, but a newer timestamp value.
Iam not that familiar with python. I've googled alot and found just solutions for lists like this:
[How can I count the occurrences of a list item in Python?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python)
My problem is, that iam not smart enough to apply this on my problem. Furthermore the solution should be somewhat efficient, because it has to run permanently in a backround job with rather low computing power.
Thank you for help! | 2015/05/14 | [
"https://Stackoverflow.com/questions/30234792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394244/"
] | Input:
```
entries = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
```
Removal:
```
newest = {}
for entry in entries:
current = newest.get(entry['remote'])
if current is None or entry['timestamp'] > current['timestamp']:
newest[entry['remote']] = entry
entries[:] = newest.values()
```
Output:
```
from pprint import pprint
pprint(entries)
Prints:
[{'quantity': 1.0, 'remote': '2', 'timestamp': 3},
{'quantity': 1.0, 'remote': '1', 'timestamp': 1}]
``` | If you have this:
```
data = [{"remote":1, "quantity":1.0, "timestamp":1},
{"remote":2, "quantity":1.0, "timestamp":2},
{"remote":2, "quantity":1.0, "timestamp":3}]
```
You can filter the entries like that:
```
filtered_data = []
for d1 in sorted(data, key=lambda e: e["timestamp"], reverse=True):
for d2 in filtered_data:
if d1["remote"] == d2["remote"]:
break
else:
filtered_data.append(d1)
``` |
30,234,792 | I've got a data structure like these:
```
[{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}, ...]
```
a list of dictionaries. My task is to find duplicate entries regarding the remote value. If i found entries with the same remote value than i want to delete all except the one with the newest timestamp value.
In this example i had to find and delete the secound dictionary because the third one has the same remote, but a newer timestamp value.
Iam not that familiar with python. I've googled alot and found just solutions for lists like this:
[How can I count the occurrences of a list item in Python?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python)
My problem is, that iam not smart enough to apply this on my problem. Furthermore the solution should be somewhat efficient, because it has to run permanently in a backround job with rather low computing power.
Thank you for help! | 2015/05/14 | [
"https://Stackoverflow.com/questions/30234792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394244/"
] | If you have this:
```
data = [{"remote":1, "quantity":1.0, "timestamp":1},
{"remote":2, "quantity":1.0, "timestamp":2},
{"remote":2, "quantity":1.0, "timestamp":3}]
```
You can filter the entries like that:
```
filtered_data = []
for d1 in sorted(data, key=lambda e: e["timestamp"], reverse=True):
for d2 in filtered_data:
if d1["remote"] == d2["remote"]:
break
else:
filtered_data.append(d1)
``` | ```
In [55]: from itertools import groupby
In [56]: from operator import itemgetter
In [58]: a
Out[58]:
[{'quantity': 1.0, 'remote': '1', 'timestamp': 1},
{'quantity': 1.0, 'remote': '2', 'timestamp': 2},
{'quantity': 1.0, 'remote': '2', 'timestamp': 3}]
```
Sorted a based on timestamp and since you need the lastest(maximum),reversed is true
```
In [58]: s_a=sorted(a,key=lambda x: x['timestamp'],reverse = True)
In [59]: groups=[]
In [60]:for k,g in groupby(s_a,key=lambda x:x['remote']):
groups.append(list(g))
In [69]: [elem[0] for elem in groups]
Out[69]:
[{'quantity': 1.0, 'remote': '2', 'timestamp': 3},
{'quantity': 1.0, 'remote': '1', 'timestamp': 1}]
``` |
30,234,792 | I've got a data structure like these:
```
[{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}, ...]
```
a list of dictionaries. My task is to find duplicate entries regarding the remote value. If i found entries with the same remote value than i want to delete all except the one with the newest timestamp value.
In this example i had to find and delete the secound dictionary because the third one has the same remote, but a newer timestamp value.
Iam not that familiar with python. I've googled alot and found just solutions for lists like this:
[How can I count the occurrences of a list item in Python?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python)
My problem is, that iam not smart enough to apply this on my problem. Furthermore the solution should be somewhat efficient, because it has to run permanently in a backround job with rather low computing power.
Thank you for help! | 2015/05/14 | [
"https://Stackoverflow.com/questions/30234792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394244/"
] | Input:
```
entries = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
```
Removal:
```
newest = {}
for entry in entries:
current = newest.get(entry['remote'])
if current is None or entry['timestamp'] > current['timestamp']:
newest[entry['remote']] = entry
entries[:] = newest.values()
```
Output:
```
from pprint import pprint
pprint(entries)
Prints:
[{'quantity': 1.0, 'remote': '2', 'timestamp': 3},
{'quantity': 1.0, 'remote': '1', 'timestamp': 1}]
``` | If your dicts are in sorted order based on the `'remote'` key , you can group them by the `'remote'` key and get the last entry which will be the latest timestamp.
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
from itertools import groupby
from operator import itemgetter
l[:] = (list(v)[-1] for _, v in groupby(l,key=(itemgetter("remote"))))
print(l)
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0},
{'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
```
`l[:]` changes the original list, `(list(v)[-1] for k,v in groupby(l,key=(itemgetter("remote"))))` is a generator expression which means we don't need to store all the content in memory at once which if memory is also an issue will help.
This will also work for unsorted data once the dupes are always together and the latest dupe comes last:
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
l[:] = (list(v)[-1] for k,v in groupby(l, key=(itemgetter("remote"))))
print(l)
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0}, {'timestamp': 1, 'remote': '4', 'quantity': 1.0}, {'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
```
Or if the dupes are not sorted get the max based on timestamp:
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2}]
l[:] = (max(v,key=itemgetter("timestamp")) for _, v in groupby(l, key=(itemgetter("remote")))
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0}, {'timestamp': 1, 'remote': '4', 'quantity': 1.0}, {'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
```
If you were going to sort you should do an inplace reverse sort by the remote key, them call next on the grouping `v` to get the latest:
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2}]
l.sort(key=itemgetter("remote"),reverse=True)
l[:] = (next(v) for _, v in groupby(l, key=(itemgetter("remote"))))
print(l)
```
Sorting will change the order of the dicts though so that may not be suitable for your problem, if your `dicts` are in order like your input then you don't need to worry about sorting anyway. |
30,234,792 | I've got a data structure like these:
```
[{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}, ...]
```
a list of dictionaries. My task is to find duplicate entries regarding the remote value. If i found entries with the same remote value than i want to delete all except the one with the newest timestamp value.
In this example i had to find and delete the secound dictionary because the third one has the same remote, but a newer timestamp value.
Iam not that familiar with python. I've googled alot and found just solutions for lists like this:
[How can I count the occurrences of a list item in Python?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python)
My problem is, that iam not smart enough to apply this on my problem. Furthermore the solution should be somewhat efficient, because it has to run permanently in a backround job with rather low computing power.
Thank you for help! | 2015/05/14 | [
"https://Stackoverflow.com/questions/30234792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394244/"
] | Input:
```
entries = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
```
Removal:
```
newest = {}
for entry in entries:
current = newest.get(entry['remote'])
if current is None or entry['timestamp'] > current['timestamp']:
newest[entry['remote']] = entry
entries[:] = newest.values()
```
Output:
```
from pprint import pprint
pprint(entries)
Prints:
[{'quantity': 1.0, 'remote': '2', 'timestamp': 3},
{'quantity': 1.0, 'remote': '1', 'timestamp': 1}]
``` | ```
In [55]: from itertools import groupby
In [56]: from operator import itemgetter
In [58]: a
Out[58]:
[{'quantity': 1.0, 'remote': '1', 'timestamp': 1},
{'quantity': 1.0, 'remote': '2', 'timestamp': 2},
{'quantity': 1.0, 'remote': '2', 'timestamp': 3}]
```
Sorted a based on timestamp and since you need the lastest(maximum),reversed is true
```
In [58]: s_a=sorted(a,key=lambda x: x['timestamp'],reverse = True)
In [59]: groups=[]
In [60]:for k,g in groupby(s_a,key=lambda x:x['remote']):
groups.append(list(g))
In [69]: [elem[0] for elem in groups]
Out[69]:
[{'quantity': 1.0, 'remote': '2', 'timestamp': 3},
{'quantity': 1.0, 'remote': '1', 'timestamp': 1}]
``` |
30,234,792 | I've got a data structure like these:
```
[{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}, ...]
```
a list of dictionaries. My task is to find duplicate entries regarding the remote value. If i found entries with the same remote value than i want to delete all except the one with the newest timestamp value.
In this example i had to find and delete the secound dictionary because the third one has the same remote, but a newer timestamp value.
Iam not that familiar with python. I've googled alot and found just solutions for lists like this:
[How can I count the occurrences of a list item in Python?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python)
My problem is, that iam not smart enough to apply this on my problem. Furthermore the solution should be somewhat efficient, because it has to run permanently in a backround job with rather low computing power.
Thank you for help! | 2015/05/14 | [
"https://Stackoverflow.com/questions/30234792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394244/"
] | If your dicts are in sorted order based on the `'remote'` key , you can group them by the `'remote'` key and get the last entry which will be the latest timestamp.
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
from itertools import groupby
from operator import itemgetter
l[:] = (list(v)[-1] for _, v in groupby(l,key=(itemgetter("remote"))))
print(l)
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0},
{'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
```
`l[:]` changes the original list, `(list(v)[-1] for k,v in groupby(l,key=(itemgetter("remote"))))` is a generator expression which means we don't need to store all the content in memory at once which if memory is also an issue will help.
This will also work for unsorted data once the dupes are always together and the latest dupe comes last:
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3}]
l[:] = (list(v)[-1] for k,v in groupby(l, key=(itemgetter("remote"))))
print(l)
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0}, {'timestamp': 1, 'remote': '4', 'quantity': 1.0}, {'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
```
Or if the dupes are not sorted get the max based on timestamp:
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2}]
l[:] = (max(v,key=itemgetter("timestamp")) for _, v in groupby(l, key=(itemgetter("remote")))
[{'timestamp': 1, 'remote': '1', 'quantity': 1.0}, {'timestamp': 1, 'remote': '4', 'quantity': 1.0}, {'timestamp': 3, 'remote': '2', 'quantity': 1.0}]
```
If you were going to sort you should do an inplace reverse sort by the remote key, them call next on the grouping `v` to get the latest:
```
l = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
{'remote': '4', 'quantity': 1.0, 'timestamp': 1},
{'remote': '2', 'quantity': 1.0, 'timestamp': 3},
{'remote': '2', 'quantity': 1.0, 'timestamp': 2}]
l.sort(key=itemgetter("remote"),reverse=True)
l[:] = (next(v) for _, v in groupby(l, key=(itemgetter("remote"))))
print(l)
```
Sorting will change the order of the dicts though so that may not be suitable for your problem, if your `dicts` are in order like your input then you don't need to worry about sorting anyway. | ```
In [55]: from itertools import groupby
In [56]: from operator import itemgetter
In [58]: a
Out[58]:
[{'quantity': 1.0, 'remote': '1', 'timestamp': 1},
{'quantity': 1.0, 'remote': '2', 'timestamp': 2},
{'quantity': 1.0, 'remote': '2', 'timestamp': 3}]
```
Sorted a based on timestamp and since you need the lastest(maximum),reversed is true
```
In [58]: s_a=sorted(a,key=lambda x: x['timestamp'],reverse = True)
In [59]: groups=[]
In [60]:for k,g in groupby(s_a,key=lambda x:x['remote']):
groups.append(list(g))
In [69]: [elem[0] for elem in groups]
Out[69]:
[{'quantity': 1.0, 'remote': '2', 'timestamp': 3},
{'quantity': 1.0, 'remote': '1', 'timestamp': 1}]
``` |
53,203,678 | In python, I have numpy arrays `a0`, `a1`, and `a2`, each of which refer to different contents. I want to shift the relations between the reference names and the referred objects, so that `a2` will now point to the content pointed by `a1` before, and `a1` will now point to the content pointed by `a0` before. Then, I want to let `a0` to point to a new content.
To be more specific, I want to do something like this:
```
import numpy as np
a2=np.array([1,2,3,4])
a1=np.array([10,20,30,40])
a0=np.array([8,8,8,8])
a2=a1
a1=a0
# I want to assign new values to a0[0], a0[1], .., without affecting a1.
```
Can I do it without copying values (e.g. by `np.copy`) and without memory reallocation (e.g. by `del` and `np.empty`)? | 2018/11/08 | [
"https://Stackoverflow.com/questions/53203678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/883431/"
] | Use tuple unpacking to exchanging values kindaof like the `a,b=b,a`
```
In [183]: a2=np.array([1,2,3,4])
...: a1=np.array([10,20,30,40])
...: a0=np.array([8,8,8,8])
...:
...:
In [184]:
In [185]: a2,a1=np.copy(a1),np.copy(a0)
In [186]: a0
Out[186]: array([8, 8, 8, 8])
In [187]: a1
Out[187]: array([8, 8, 8, 8])
In [188]: a2
Out[188]: array([10, 20, 30, 40])
```
You are free to point `a0` where ever you want and i dont think you can create get away with changing `a0` and not affecting `a1` without `np.copy` or something else like `copy.deepcopy` | What are you asking is not possible without making a copy of `a0`, otherwise `a0` and `a1` will be pointing to the same object and changing `a0` will change `a1`. So you should do this:
```
a2 = np.array([1,2,3,4])
a1 = np.array([10,20,30,40])
a0 = np.array([8,8,8,8])
a2 = a1
a1 = a0.copy()
# let's change a0
a0[0] = 9
# check
a0
Out[31]: array([9, 8, 8, 8])
a1
Out[32]: array([8, 8, 8, 8])
a2
Out[33]: array([10, 20, 30, 40])
``` |
10,545,828 | I am going to develop a Tetris in practice. But I have no idea how to start it, especially the graphic part - how to draw the frame and blocks? how to move them on screen?
Could you please you refer me to some useful libs or tools?
Programming language is c. (if this is done, I am planing to do it again with c++ and python. :) Both Windows or Unix-like is ok. It's better if it is portable.
I know openGL, and DirectX is heavy-weight lib. dose it efficiently fit to a small game like Tetris? Any light-weight? which is better?
I would appreciate if you could refer me to some materials or links for this.
Thanks. | 2012/05/11 | [
"https://Stackoverflow.com/questions/10545828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/881873/"
] | Use this in your receiver
```
<receiver android:name=".UpdateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
```
Your UpdateRecieiver
```
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
if (isConnected)
Log.i("NET", "connecte" +isConnected);
else Log.i("NET", "not connecte" +isConnected);
}
}
``` | try out this function
>
>
>
```
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
```
and in the manifest
```
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```
enjoy.. |
60,267,444 | I have been trying to make an interactive periodic table using Tkinter & python3. However, on running the code, I don't get any output except a blank tkinter window. Can anyone point in the code attached below about why don't the buttons get rendered? Code is borrowed from (<https://gist.github.com/slabach/11197977>)
```
import tkinter as tk
# Creates and Initiates class 'App'
class App(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.winfo_toplevel().title("Periodic Table of the Elements")
self.topLabel = tk.Label(self, text="Click the element you would like information about.", font=20)
self.topLabel.grid(row=0, column=0, columnspan=18)
# Names of tk.Buttons in column 1
column1 = [
('H', 'Hydrogen', 'Atomic # = 1\nAtomic Weight =1.01\nState = Gas\nCategory = Alkali Metals'),
('Li', 'Lithium', 'Atomic # = 3\nAtomic Weight = 6.94\nState = Solid\nCategory = Alkali Metals'),
('Na', 'Sodium', 'Atomic # = 11\nAtomic Weight = 22.99\nState = Solid\nCategory = Alkali Metals'),
('K', 'Potassium', 'Atomic # = 19\nAtomic Weight = 39.10\nState = Solid\nCategory = Alkali Metals'),
('Rb', 'Rubidium', 'Atomic # = 37\nAtomic Weight = 85.47\nState = Solid\nCategory = Alkali Metals'),
('Cs', 'Cesium', 'Atomic # = 55\nAtomic Weight = 132.91\nState = Solid\nCategory = Alkali Metals'),
('Fr', 'Francium', 'Atomic # = 87\nAtomic Weight = 223.00\nState = Solid\nCategory = Alkali Metals')]
# create all tk.Buttons with a loop
r = 1
c = 0
for b in column1:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="grey",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column2 = [
('Be', 'Beryllium', 'Atomic # = 4\nAtomic Weight = 9.01\nState = Solid\nCategory = Alkaline Earth Metals'),
('Mg', 'Magnesium', 'Atomic # = 12\nAtomic Weight = 24.31\nState = Solid\nCategory = Alkaline Earth Metal'),
('Ca', 'Calcium', 'Atomic # = 20\nAtomic Weight = 40.08\nState = Solid\nCategory = Alkaline Earth Metals'),
('Sr', 'Strontium', 'Atomic # = 38\nAtomic Weight = 87.62\nState = Solid\nCategory = Alkaline Earth Metal'),
('Ba', 'Barium', 'Atomic # = 56\nAtomic Weight = 137.33\nState = Solid\nCategory = Alkaline Earth Metals'),
('Ra', 'Radium', 'Atomic # = 88\nAtomic Weight = 226.03\nState = Solid\nCategory = Alkaline Earth Metals')]
r = 2
c = 1
for b in column2:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light green",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column3 = [
('Sc', 'Scandium', 'Atomic # = 21\nAtomic Weight = 44.96\nState = Solid\nCategory = Trans Metals'),
('Y', 'Yttrium', 'Atomic # = 39\nAtomic Weight = 88.91\nState = Solid\nCategory = Trans Metals'),
('La >|', 'Lanthanum', 'Atomic # = 57\nAtomic Weight = 138.91\nState = Solid\nCategory = Trans Metals'),
('Ac >|', 'Actinium', 'Atomic # = 89\nAtomic Weight = 227.03\nState = Solid\nCategory = Trans Metals')]
r = 4
c = 2
for b in column3:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column4 = [
('Ti', 'Titanium', 'Atomic # = 22\nAtomic Weight = 47.90\nState = Solid\nCategory = Trans Metals'),
('Zr', 'Zirconium', 'Atomic # = 40\nAtomic Weight = 91.22\nState = Solid\nCategory = Trans Metals'),
('Hf', 'Hanium', 'Atomic # = 72\nAtomic Weight = 178.49\nState = Solid\nCategory = Trans Metals'),
('Rf', 'Rutherfordium', 'Atomic # = 104\nAtomic Weight = 261.00\nState = Synthetic\nCategory = Tran Metal')]
r = 4
c = 3
for b in column4:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 10:
r = 1
c += 1
column5 = [
('V', 'Vanadium', 'Atomic # = 23\nAtomic Weight = 50.94\nState = Solid\nCategory = Trans Metals'),
('Nb', 'Niobium', 'Atomic # = 41\nAtomic Weight = 92.91\nState = Solid\nCategory = Trans Metals'),
('Ta', 'Tantalum', 'Atomic # = 73\nAtomic Weight = 180.95\nState = Solid\nCategory = Trans Metals'),
('Ha', 'Hahnium', 'Atomic # = 105\nAtomic Weight = 262.00\nState = Synthetic\nCategory = Trans Metals')]
r = 4
c = 4
for b in column5:
tk.Button(self,
text=b[0],
width=5, height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 10:
r = 1
c += 1
column6 = [
('Cr', 'Chromium', 'Atomic # = 24\nAtomic Weight = 51.99\nState = Solid\nCategory = Trans Metals'),
('Mo', 'Molybdenum', 'Atomic # = 42\nAtomic Weight = 95.94\nState = Solid\nCategory = Trans Metals'),
('W', 'Tungsten', 'Atomic # = 74\nAtomic Weight = 183.85\nState = Solid\nCategory = Trans Metals'),
('Sg', 'Seaborgium', 'Atomic # = 106\nAtomic Weight = 266.00\nState = Synthetic\nCategory = Trans Metals')]
r = 4
c = 5
for b in column6:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column7 = [
('Mn', 'Manganese', 'Atomic # = 25\nAtomic Weight = 178.49\nState = Solid\nCategory = Trans Metals'),
('Tc', 'Technetium', 'Atomic # = 43\nAtomic Weight = 178.49\nState = Synthetic\nCategory = Trans Metals'),
('Re', 'Rhenium', 'Atomic # = 75\nAtomic Weight = 178.49\nState = Solid\nCategory = Trans Metals'),
('Bh', 'Bohrium', 'Atomic # = 107\nAtomic Weight = 262.00\nState = Synthetic\nCategory = Trans Metals')]
r = 4
c = 6
for b in column7:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column8 = [
('Fe', 'Iron', 'Atomic # = 26\nAtomic Weight = 55.85\nState = Solid\nCategory = Trans Metals'),
('Ru', 'Ruthenium', 'Atomic # = 44\nAtomic Weight = 101.07\nState = Solid\nCategory = Trans Metals'),
('Os', 'Osmium', 'Atomic # = 76\nAtomic Weight = 190.20\nState = Solid\nCategory = Trans Metals'),
('Hs', 'Hassium', 'Atomic # = 108\nAtomic Weight = 265.00\nState = Synthetic\nCategory = Trans Metals')]
r = 4
c = 7
for b in column8:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column9 = [
('Co', 'Cobalt', 'Atomic # = 27\nAtomic Weight = 58.93\nState = Solid\nCategory = Trans Metals'),
('Rh', 'Rhodium', 'Atomic # = 45\nAtomic Weight = 102.91\nState = Solid\nCategory = Trans Metals'),
('Ir', 'Iridium', 'Atomic # = 77\nAtomic Weight = 192.22\nState = Solid\nCategory = Trans Metals'),
('Mt', 'Meitnerium', 'Atomic # = 109\nAtomic Weight = 266.00\nState = Synthetic\nCategory = Trans Metals')]
r = 4
c = 8
for b in column9:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column10 = [
('Ni', 'Nickle', 'Atomic # = 28\nAtomic Weight = 58.70\nState = Solid\nCategory = Trans Metals'),
('Pd', 'Palladium', 'Atomic # = 46\nAtomic Weight = 106.40\nState = Solid\nCategory = Trans Metals'),
('Pt', 'Platinum', 'Atomic # = 78\nAtomic Weight = 195.09\nState = Solid\nCategory = Trans Metals')]
r = 4
c = 9
for b in column10:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column11 = [
('Cu', 'Copper', 'Atomic # = 29\nAtomic Weight = 63.55\nState = Solid\nCategory = Trans Metals'),
('Ag', 'Silver', 'Atomic # = 47\nAtomic Weight = 107.97\nState = Solid\nCategory = Trans Metals'),
('Au', 'Gold', 'Atomic # = 79\nAtomic Weight = 196.97\nState = Solid\nCategory = Trans Metals')]
r = 4
c = 10
for b in column11:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column12 = [
('Zn', 'Zinc', 'Atomic # = 30\nAtomic Weight = 65.37\nState = Solid\nCategory = Trans Metals'),
('Cd', 'Cadmium', 'Atomic # = 48\nAtomic Weight = 112.41\nState = Solid\nCategory = Trans Metals'),
('Hg', 'Mercury', 'Atomic # = 80\nAtomic Weight = 200.59\nState = Liquid\nCategory = Trans Metals')]
r = 4
c = 11
for b in column12:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column13_1 = [
('B', 'Boron', 'Atomic # = 5\nAtomic Weight = 10.81\nState = Solid\nCategory = Nonmetals')]
r = 2
c = 12
for b in column13_1:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Blue",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column13_2 = [
('Al', 'Aluminum', 'Atomic # = 13\nAtomic Weight = 26.98\nState = Solid\nCategory = Other Metals'),
('Ga', 'Gallium', 'Atomic # = 31\nAtomic Weight = 69.72\nState = Solid\nCategory = Other Metals'),
('In', 'Indium', 'Atomic # = 49\nAtomic Weight = 69.72\nState = Solid\nCategory = Other Metals'),
('Ti', 'Thallium', 'Atomic # = 81\nAtomic Weight = 204.37\nState = Solid\nCategory = Other Metals')]
r = 3
c = 12
for b in column13_2:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Pink",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column14_1 = [
('C', 'Carbon', 'Atomic # = 6\nAtomic Weight = 12.01\nState = Solid\nCategory = Nonmetals'),
('Si', 'Silicon', 'Atomic # = 14\nAtomic Weight = 28.09\nState = Solid\nCategory = Nonmetals')]
r = 2
c = 13
for b in column14_1:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Blue",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column14_2 = [
('Ge', 'Germanium', 'Atomic # = 32\nAtomic Weight = 72.59\nState = Solid\nCategory = Other Metals'),
('Sn', 'Tin', 'Atomic # = 50\nAtomic Weight = 118.69\nState = Solid\nCategory = Other Metals'),
('Pb', 'Lead', 'Atomic # = 82\nAtomic Weight = 207.20\nState = Solid\nCategory = Other Metals')]
r = 4
c = 13
for b in column14_2:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Pink",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column15_1 = [
('N', 'Nitrogen', 'Atomic # = 7\nAtomic Weight = 14.01\nState = Gas\nCategory = Nonmetals'),
('P', 'Phosphorus', 'Atomic # = 15\nAtomic Weight = 30.97\nState = Solid\nCategory = Nonmetals'),
('As', 'Arsenic', 'Atomic # = 33\nAtomic Weight = 74.92\nState = Solid\nCategory = Nonmetals')]
r = 2
c = 14
for b in column15_1:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Blue",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column15_2 = [
('Sb', 'Antimony', 'Atomic # = 51\nAtomic Weight = 121.75\nState = Solid\nCategory = Other Metals'),
('Bi', 'Bismuth', 'Atomic # = 83\nAtomic Weight = 208.98\nState = Solid\nCategory = Other Metals')]
r = 5
c = 14
for b in column15_2:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Pink",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column16_1 = [
('O', 'Oxygen', 'Atomic # = 8\nAtomic Weight = 15.99\nState = Gas\nCategory = Nonmetals'),
('S', 'Sulfur', 'Atomic # = 16\nAtomic Weight = 32.06\nState = Solid\nCategory = Nonmetals'),
('Se', 'Selenium', 'Atomic # = 34\nAtomic Weight = 78.96\nState = Solid\nCategory = Nonmetals'),
('Te', 'Tellurium', 'Atomic # = 52\nAtomic Weight = 127.60\nState = Solid\nCategory = Nonmetals')]
r = 2
c = 15
for b in column16_1:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Blue",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column16_2 = [
('Po', 'Polonium', 'Atomic # = 84\nAtomic Weight = 209.00\nState = Solid\nCategory = Other Metals')]
r = 6
c = 15
for b in column16_2:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Pink",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column17 = [
('F', 'Fluorine', 'Atomic # = 9\nAtomic Weight = 18.99\nState = Gas\nCategory = Nonmetals'),
('Cl', 'Chlorine', 'Atomic # = 17\nAtomic Weight = 35.45\nState = Gas\nCategory = Nonmetals'),
('Br', 'Bromine', 'Atomic # = 35\nAtomic Weight = 79.90\nState = Liquid\nCategory = Nonmetals'),
('I', 'Iodine', 'Atomic # = 53\nAtomic Weight = 126.90\nState = Solid\nCategory = Nonmetals'),
('At', 'Astatine', 'Atomic # = 85\nAtomic Weight = 210.00\nState = Solid\nCategory = Nonmetals')]
r = 2
c = 16
for b in column17:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="Light Blue",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
column18 = [
('He', 'Helium', 'Atomic # = 2\nAtomic Weight = 4.00\nState = Gas\nCategory = Nobel Gases'),
('Ne', 'Neon', 'Atomic # = 10\nAtomic Weight = 20.18\nState = Gas\nCategory = Nobel Gases'),
('Ar', 'Argon', 'Atomic # = 18\nAtomic Weight = 39.95\nState = Gas\nCategory = Nobel Gases'),
('Kr', 'Krypton', 'Atomic # = 36\nAtomic Weight = 83.80\nState = Gas\nCategory = Nobel Gases'),
('Xe', 'Xenon', 'Atomic # = 54\nAtomic Weight = 131.30\nState = Gas\nCategory = Nobel Gases'),
('Rn', 'Radon', 'Atomic # = 86\nAtomic Weight = 222.00\nState = Gas\nCategory = Nobel Gases')]
r = 1
c = 17
for b in column18:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="indian red",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
self.fillerLine = tk.Label(self, text="")
self.fillerLine.grid(row=10, column=0)
lanthanide = [
('>| Ce', 'Cerium', 'Atomic # = 58\nAtomic Weight = 140.12\nState = Solid\nCategory = Trans Metals'),
('Pr', 'Praseodymium', 'Atomic # = 59\nAtomic Weight = 140.91\nState = Solid\nCategory = Trans Metals'),
('Nd', 'Neodymium', 'Atomic # = 60\nAtomic Weight = 144.24\nState = Solid\nCategory = Trans Metals'),
('Pm', 'Promethium', 'Atomic # = 61\nAtomic Weight = 145.00\nState = Synthetic\nCategory = Trans Metals'),
('Sm', 'Samarium', 'Atomic # = 62\nAtomic Weight = 150.40\nState = Solid\nCategory = Trans Metals'),
('Eu', 'Europium', 'Atomic # = 63\nAtomic Weight = 151.96\nState = Solid\nCategory = Trans Metals'),
('Gd', 'Gadolinium', 'Atomic # = 64\nAtomic Weight = 157.25\nState = Solid\nCategory = Trans Metals'),
('Tb', 'Terbium', 'Atomic # = 65\nAtomic Weight = 158.93\nState = Solid\nCategory = Trans Metals'),
('Dy', 'Dyprosium', 'Atomic # = 66\nAtomic Weight = 162.50\nState = Solid\nCategory = Trans Metals'),
('Ho', 'Holmium', 'Atomic # = 67\nAtomic Weight = 164.93\nState = Solid\nCategory = Trans Metals'),
('Er', 'Erbium', 'Atomic # = 68\nAtomic Weight = 167.26\nState = Solid\nCategory = Trans Metals'),
('Tm', 'Thulium', 'Atomic # = 69\nAtomic Weight = 168.93\nState = Solid\nCategory = Trans Metals'),
('Yb', 'Ytterbium', 'Atomic # = 70\nAtomic Weight = 173.04\nState = Solid\nCategory = Trans Metals'),
('Lu', 'Lutetium', 'Atomic # = 71\nAtomic Weight = 174.97\nState = Solid\nCategory = Trans Metals')]
r = 11
c = 3
for b in lanthanide:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
c += 1
if c > 18:
c = 1
r += 1
actinide = [
('>| Th', 'Thorium', 'Atomic # = 90\nAtomic Weight = 232.04\nState = Solid\nCategory = Trans Metals'),
('Pa', 'Protactinium', 'Atomic # = 91\nAtomic Weight = 231.04\nState = Solid\nCategory = Trans Metals'),
('U', 'Uranium', 'Atomic # = 92\nAtomic Weight = 238.03\nState = Solid\nCategory = Trans Metals'),
('Np', 'Neptunium', 'Atomic # = 93\nAtomic Weight = 237.05\nState = Synthetic\nCategory = Trans Metals'),
('Pu', 'Plutonium', 'Atomic # = 94\nAtomic Weight = 244.00\nState = Synthetic\nCategory = Trans Metals'),
('Am', 'Americium', 'Atomic # = 95\nAtomic Weight = 243.00\nState = Synthetic\nCategory = Trans Metals'),
('Cm', 'Curium', 'Atomic # = 96\nAtomic Weight = 247\nState = Synthetic\nCategory = Trans Metals'),
('Bk', 'Berkelium', 'Atomic # = 97\nAtomic Weight = 247\nState = Synthetic\nCategory = Trans Metals'),
('Cf', 'Californium', 'Atomic # = 98\nAtomic Weight = 247\nState = Synthetic\nCategory = Trans Metals'),
('Es', 'Einsteinium', 'Atomic # = 99\nAtomic Weight = 252.00\nState = Synthetic\nCategory = Trans Metals'),
('Fm', 'Fermium', 'Atomic # = 100\nAtomic Weight = 257.00\nState = Synthetic\nCategory = Trans Metals'),
('Md', 'Mendelevium', 'Atomic # = 101\nAtomic Weight = 260.00\nState = Synthetic\nCategory = Trans Metals'),
('No', 'Nobelium', 'Atomic # = 102\nAtomic Weight = 259\nState = Synthetic\nCategory = Trans Metals'),
('Lr', 'Lawrencium', 'Atomic # = 103\nAtomic Weight = 262\nState = Synthetic\nCategory = Trans Metals')]
r = 12
c = 3
for b in actinide:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="light goldenrod",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
c += 1
if c > 18:
c = 1
r += 1
reset = [
('Reset', 'Click the element you would like information about.', '')]
r = 12
c = 0
for b in reset:
tk.Button(self,
text=b[0],
width=5,
height=2,
bg="black",
fg="white",
command=lambda text=b: self.name(text[1]) & self.info(text[2])).grid(row=r, column=c)
r += 1
if r > 7:
r = 1
c += 1
self.infoLine = tk.Label(self, text="", justify='left')
self.infoLine.grid(row=1, column=3, columnspan=10, rowspan=4)
self.mainloop()
# Replaces Label at the top with the name of whichever element tk.Button was pressed
def name(self, text):
self.topLabel.config(text=text)
# Displays information on the element of whichever element tk.Button was pressed
def info(self, text):
self.infoLine.config(text=text)
# Creates an instance of 'app' class
def main():
root = tk.Tk()
a = App(root)
a.mainloop()
# runs main function
if __name__ == "__main__":
main()
``` | 2020/02/17 | [
"https://Stackoverflow.com/questions/60267444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12914106/"
] | In Postgres, you can use [the `?` operator](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE) to check if a jsonb array contains a given value:
```
AND myTable.PhoneNumberJson ? OtherTable.PhoneNumber
```
Please note that this requires `PhoneNumberJson` to be of `jsonb` datatype. If it's a `json`, then you can cast first:
```
AND myTable.PhoneNumberJson::jsonb ? OtherTable.PhoneNumber
``` | I am here posting the my expected answer if anybody is searching for how to convert and check not in object for varchar to double precision.
```
and not (myTable.Phone_Number = any
(array(select
regexp_split_to_table(replace(replace(other_Table.PhoneNumberJson,'[',''),']',''),',')::
double precision)));
``` |
51,678,204 | I have the following **PySpark Input Dataframe:**
```python
+-------+------------+
| index | valuelist |
+-------+------------+
| 1.0 | [10,20,30] |
| 2.0 | [11,21,31] |
| 0.0 | [14,12,15] |
+-------+------------+
```
Where:
* Index: type Double
* Valuelist: type **Vector**. (it's **NOT Array**)
From the above Input Dataframe, I want to get the following **Output Dataframe** in **PySpark**
```python
+-------+-------+
| index | value |
+-------+-------+
| 1.0 | 20 |
| 2.0 | 31 |
| 0.0 | 14 |
+-------+-------+
```
**Logic:**
```python
for each row:
value = valuelist[index]
``` | 2018/08/03 | [
"https://Stackoverflow.com/questions/51678204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6825384/"
] | ### Spark version 1.5 and higher
You can use `pyspark.sql.functions.expr` to [pass a column value as an input to a function](https://stackoverflow.com/questions/51140470/using-a-column-value-as-a-parameter-to-a-spark-dataframe-function):
```python
df.select("index", f.expr("valuelist[CAST(index AS integer)]").alias("value")).show()
#+-----+-----+
#|index|value|
#+-----+-----+
#| 1.0| 20|
#| 2.0| 31|
#| 0.0| 14|
#+-----+-----+
```
### Spark version 2.1 and higher
If you have `spark` version 2.1 or higher, here's an alternative using `pyspark.sql.functions.posexplode`:
```python
import pyspark.sql.functions as f
df.select("index", f.posexplode("valuelist").alias("pos", "value"))\
.where(f.col("index").cast("int") == f.col("pos"))\
.select("index", "value")\
.show()
#+-----+-----+
#|index|value|
#+-----+-----+
#| 1.0| 20|
#| 2.0| 31|
#| 0.0| 14|
#+-----+-----+
``` | You can create a new column and pass these two columns as an input.
```python
from pyspark.sql import functions as F
columns = ['index', 'valuelist']
vals = [
(0, [1,2]),
(1, [1,2])
]
df = sqlContext.createDataFrame(vals, columns)
df = df.withColumn(
"value", udf(lambda index_and_list: index_and_list[0][index_and_list[1]], IntegerType())(
F.struct(F.col("valuelist"), F.col("index")))
)
```
Got the following output:
```python
> +-----+---------+-----+
|index|valuelist|value|
+-----+---------+-----+
| 0| [1, 2]| 1|
| 1| [1, 2]| 2|
+-----+---------+-----+
``` |
31,240,305 | I would like to protect the python calculator I have created from crashing when a user inputs a string instead of an integer.
I have tried doing so with an else statement printing "Invalid Input" (or something else I cant remember) when ever a user inputs a string instead of numbers.
I would also like to know if there is a way to let a user do another operation instead of having to restart the application.
If any importing is required (if you can) please list if it is compatible with cx\_Freeze.
**Source code:**
```
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
``` | 2015/07/06 | [
"https://Stackoverflow.com/questions/31240305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080845/"
] | you can use something like this for input
```
while True:
try:
num1 = int(input("Enter first number: "))
except ValueError:
continue
else:
break
``` | This code snippet should help :-
```
def is_string(test_data):
if type(test_data) is str:
return True
else:
return False
``` |
31,240,305 | I would like to protect the python calculator I have created from crashing when a user inputs a string instead of an integer.
I have tried doing so with an else statement printing "Invalid Input" (or something else I cant remember) when ever a user inputs a string instead of numbers.
I would also like to know if there is a way to let a user do another operation instead of having to restart the application.
If any importing is required (if you can) please list if it is compatible with cx\_Freeze.
**Source code:**
```
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
``` | 2015/07/06 | [
"https://Stackoverflow.com/questions/31240305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080845/"
] | you can use something like this for input
```
while True:
try:
num1 = int(input("Enter first number: "))
except ValueError:
continue
else:
break
``` | Take a look at the changes I have made to your code as follows:
```
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
def input_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That was not a number")
# Keep going around the loop until the user chooses 5 to quit
while True:
print
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Quit")
choice = input("Enter choice(1/2/3/4/5):")
# Do they want to quit?
if choice == 5:
break
num1 = input_number("Enter first number: ")
num2 = input_number("Enter second number: ")
if choice == 1:
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 2:
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 3:
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 4:
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("%s - Invalid input" % choice)
```
In order to ask for more input, you needed to wrap your prompts in a loop. You would then need to add an option to the user to allow them to quit.
Also, you can move the prompting for numbers to a function. This would keep asking for number if the user typed in a character. |
31,240,305 | I would like to protect the python calculator I have created from crashing when a user inputs a string instead of an integer.
I have tried doing so with an else statement printing "Invalid Input" (or something else I cant remember) when ever a user inputs a string instead of numbers.
I would also like to know if there is a way to let a user do another operation instead of having to restart the application.
If any importing is required (if you can) please list if it is compatible with cx\_Freeze.
**Source code:**
```
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
``` | 2015/07/06 | [
"https://Stackoverflow.com/questions/31240305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080845/"
] | Take a look at the changes I have made to your code as follows:
```
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
def input_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That was not a number")
# Keep going around the loop until the user chooses 5 to quit
while True:
print
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Quit")
choice = input("Enter choice(1/2/3/4/5):")
# Do they want to quit?
if choice == 5:
break
num1 = input_number("Enter first number: ")
num2 = input_number("Enter second number: ")
if choice == 1:
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 2:
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 3:
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 4:
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("%s - Invalid input" % choice)
```
In order to ask for more input, you needed to wrap your prompts in a loop. You would then need to add an option to the user to allow them to quit.
Also, you can move the prompting for numbers to a function. This would keep asking for number if the user typed in a character. | This code snippet should help :-
```
def is_string(test_data):
if type(test_data) is str:
return True
else:
return False
``` |
56,159,051 | I am using Eclipse on Linux to develop C applications, and the build system I have makes use of `make` and `python`. I have a custom virtualenv installed and managed by `pyenv`, and it works fine from the command line if I pre-select the virtualenv with, say `pyenv shell myvenv`.
However I want Eclipse to make use of this virtualenv when building (via "existing makefile") from within Eclipse. Currently it runs my Makefile but uses the system python in `/usr/bin/python`, which is missing all of the packages needed by the build system.
It isn't clear to me how to configure Eclipse to use a custom Python interpreter such as the one in my virtualenv. I have heard talk of setting `PYTHONPATH` however this seems to be for finding site-packages rather than the interpreter itself. My virtualenv is based on python 3.7 and my system python is 2.7, so setting this alone probably isn't going to work.
I am not using PyDev (this is a C project, not a Python project) so there's no explicit support for Python in Eclipse. I'd prefer not to install PyDev if I can help it.
I've noticed that pyenv adds its `plugins`, `shims` and `bin` directories to PATH when activated. I could explicitly add these to PATH in Eclipse, so that Eclipse uses pyenv to find an interpreter. However I'd prefer to point directly at a specific virtualenv rather than use the pyenv machinery to find the current virtualenv. | 2019/05/15 | [
"https://Stackoverflow.com/questions/56159051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143397/"
] | I had the same trouble and after some digging, there are two solutions; project-wide and workspace-wide. I prefer the project-wide as it will be saved in the git repository and the next person doesn't have to pull their hair.
For the project-wide add `/Users/${USER}/.pyenv/shims:` to the start of the "Project properties > C/C++ Build > Environment > PATH".
I couldn't figure out the other method fully (mostly because I'm happy with the other one) but it should be with possible to modify "Eclipse preferences > C/C++ > Build > Environment". You should change the radio button and add PATH variable. | For me, following steps worked ( mac os 10.12, eclipse photon version, with pydev plugin)
1. Project -> properties
2. Pydev-Interpreter/Grammar
3. Click here to configure an interpreter not listed (under interpret combobox)
4. open interpreter preference page
5. Browse for python/pypy exe -> my virtualenvdirectory/bin/python
6. Then the chosen python interpreter path should show ( for me still, it was not pointing to my virtual env, but I typed my path explicitly here and it worked)
In the bottom libraries section, you should be able to see the site-packages from your virtual env
Extra tip - In my mac os the virtual env was starting with .pyenv, since it's a hidden directory, I was not able to select this directory and I did not know how to view the hidden directory in eclipse file explorer. Therefore I created an softlink ( without any . in the name) to the hidden directory (.pyenv) and then I was able to select the softlink |
56,159,051 | I am using Eclipse on Linux to develop C applications, and the build system I have makes use of `make` and `python`. I have a custom virtualenv installed and managed by `pyenv`, and it works fine from the command line if I pre-select the virtualenv with, say `pyenv shell myvenv`.
However I want Eclipse to make use of this virtualenv when building (via "existing makefile") from within Eclipse. Currently it runs my Makefile but uses the system python in `/usr/bin/python`, which is missing all of the packages needed by the build system.
It isn't clear to me how to configure Eclipse to use a custom Python interpreter such as the one in my virtualenv. I have heard talk of setting `PYTHONPATH` however this seems to be for finding site-packages rather than the interpreter itself. My virtualenv is based on python 3.7 and my system python is 2.7, so setting this alone probably isn't going to work.
I am not using PyDev (this is a C project, not a Python project) so there's no explicit support for Python in Eclipse. I'd prefer not to install PyDev if I can help it.
I've noticed that pyenv adds its `plugins`, `shims` and `bin` directories to PATH when activated. I could explicitly add these to PATH in Eclipse, so that Eclipse uses pyenv to find an interpreter. However I'd prefer to point directly at a specific virtualenv rather than use the pyenv machinery to find the current virtualenv. | 2019/05/15 | [
"https://Stackoverflow.com/questions/56159051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/143397/"
] | I had the same trouble and after some digging, there are two solutions; project-wide and workspace-wide. I prefer the project-wide as it will be saved in the git repository and the next person doesn't have to pull their hair.
For the project-wide add `/Users/${USER}/.pyenv/shims:` to the start of the "Project properties > C/C++ Build > Environment > PATH".
I couldn't figure out the other method fully (mostly because I'm happy with the other one) but it should be with possible to modify "Eclipse preferences > C/C++ > Build > Environment". You should change the radio button and add PATH variable. | Typing CMD+SHIFT+. will show you dotfiles & directories that begin with dot in any Mac finder dialog box... |
19,580,944 | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3], [2,3,4]])
set([])
```
Am I losing my mind here? Why isn't set.intersection() operating as I'd expect it to?
How can I do the intersection of many sets as I did with union (assuming the `[[1,2,3], [2,3,4]]` had a whole bunch more lists)? What would the "pythonic" way be? | 2013/10/25 | [
"https://Stackoverflow.com/questions/19580944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406230/"
] | When you do `set()` you are creating an empty set. When you do `set().intersection(...)` you are intersecting this empty set with other stuff. The intersection of an empty set with any other collection of sets is empty.
If you actually have a list of *sets*, you can get their intersection similar to how you did it.
```
>>> x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
>>> set.intersection(*x)
set([3])
```
You can't do this directly with the way you're doing it, though, because you don't actually have any sets at all in your example with `intersection(*...)`. You just have a list of *lists*. You should first convert the elements in your list to sets. So if you have
```
x = [[1,2,3], [2,3,4]]
```
you should do
```
x = [set(a) for a in x]
``` | [removed incorrect answer]
As @Anto Vinish suggested you should first convert the lists to sets and then use set.intersection
For example:
```
>>> sets = [set([1, 2, 3]), set([2, 3, 4]), set([3, 4, 5])]
>>> set.intersection(*sets)
set([3])
``` |
19,580,944 | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3], [2,3,4]])
set([])
```
Am I losing my mind here? Why isn't set.intersection() operating as I'd expect it to?
How can I do the intersection of many sets as I did with union (assuming the `[[1,2,3], [2,3,4]]` had a whole bunch more lists)? What would the "pythonic" way be? | 2013/10/25 | [
"https://Stackoverflow.com/questions/19580944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406230/"
] | When you do `set()` you are creating an empty set. When you do `set().intersection(...)` you are intersecting this empty set with other stuff. The intersection of an empty set with any other collection of sets is empty.
If you actually have a list of *sets*, you can get their intersection similar to how you did it.
```
>>> x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
>>> set.intersection(*x)
set([3])
```
You can't do this directly with the way you're doing it, though, because you don't actually have any sets at all in your example with `intersection(*...)`. You just have a list of *lists*. You should first convert the elements in your list to sets. So if you have
```
x = [[1,2,3], [2,3,4]]
```
you should do
```
x = [set(a) for a in x]
``` | convert the list to set first
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4])])
set([2, 3])
```
For multiple lists you can just use,
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4]), set([5,3,4])])
set([3])
``` |
19,580,944 | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3], [2,3,4]])
set([])
```
Am I losing my mind here? Why isn't set.intersection() operating as I'd expect it to?
How can I do the intersection of many sets as I did with union (assuming the `[[1,2,3], [2,3,4]]` had a whole bunch more lists)? What would the "pythonic" way be? | 2013/10/25 | [
"https://Stackoverflow.com/questions/19580944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406230/"
] | When you do `set()` you are creating an empty set. When you do `set().intersection(...)` you are intersecting this empty set with other stuff. The intersection of an empty set with any other collection of sets is empty.
If you actually have a list of *sets*, you can get their intersection similar to how you did it.
```
>>> x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
>>> set.intersection(*x)
set([3])
```
You can't do this directly with the way you're doing it, though, because you don't actually have any sets at all in your example with `intersection(*...)`. You just have a list of *lists*. You should first convert the elements in your list to sets. So if you have
```
x = [[1,2,3], [2,3,4]]
```
you should do
```
x = [set(a) for a in x]
``` | ```
set().intersection(*[[1,2,3], [2,3,4]])
```
is of course empty because you start with the empty set and intersect it with all the others
You can try calling the method on the `class`
```
set.intersection(*[[1,2,3], [2,3,4]])
```
but that won't work because the first argument passed needs to be a set
```
set.intersection({1, 2, 3}, *[[2,3,4], ...])
```
This looks awkward, better if you could use a list of sets in the first place. Especially if they are coming from a generator which makes it difficult to pull off the first item cleanly
```
set.intersection(*[{1,2,3}, {2,3,4}])
```
Otherwise you can just *make* them all into sets
```
set.intersection(*(set(x) for x in [[1,2,3], [2,3,4]]))
``` |
19,580,944 | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3], [2,3,4]])
set([])
```
Am I losing my mind here? Why isn't set.intersection() operating as I'd expect it to?
How can I do the intersection of many sets as I did with union (assuming the `[[1,2,3], [2,3,4]]` had a whole bunch more lists)? What would the "pythonic" way be? | 2013/10/25 | [
"https://Stackoverflow.com/questions/19580944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406230/"
] | convert the list to set first
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4])])
set([2, 3])
```
For multiple lists you can just use,
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4]), set([5,3,4])])
set([3])
``` | [removed incorrect answer]
As @Anto Vinish suggested you should first convert the lists to sets and then use set.intersection
For example:
```
>>> sets = [set([1, 2, 3]), set([2, 3, 4]), set([3, 4, 5])]
>>> set.intersection(*sets)
set([3])
``` |
19,580,944 | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3], [2,3,4]])
set([])
```
Am I losing my mind here? Why isn't set.intersection() operating as I'd expect it to?
How can I do the intersection of many sets as I did with union (assuming the `[[1,2,3], [2,3,4]]` had a whole bunch more lists)? What would the "pythonic" way be? | 2013/10/25 | [
"https://Stackoverflow.com/questions/19580944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406230/"
] | ```
set().intersection(*[[1,2,3], [2,3,4]])
```
is of course empty because you start with the empty set and intersect it with all the others
You can try calling the method on the `class`
```
set.intersection(*[[1,2,3], [2,3,4]])
```
but that won't work because the first argument passed needs to be a set
```
set.intersection({1, 2, 3}, *[[2,3,4], ...])
```
This looks awkward, better if you could use a list of sets in the first place. Especially if they are coming from a generator which makes it difficult to pull off the first item cleanly
```
set.intersection(*[{1,2,3}, {2,3,4}])
```
Otherwise you can just *make* them all into sets
```
set.intersection(*(set(x) for x in [[1,2,3], [2,3,4]]))
``` | [removed incorrect answer]
As @Anto Vinish suggested you should first convert the lists to sets and then use set.intersection
For example:
```
>>> sets = [set([1, 2, 3]), set([2, 3, 4]), set([3, 4, 5])]
>>> set.intersection(*sets)
set([3])
``` |
19,580,944 | I'm doing some set operations in Python, and I noticed something odd..
```
>> set([1,2,3]) | set([2,3,4])
set([1, 2, 3, 4])
>> set().union(*[[1,2,3], [2,3,4]])
set([1, 2, 3, 4])
```
That's good, expected behaviour - but with intersection:
```
>> set([1,2,3]) & set([2,3,4])
set([2, 3])
>> set().intersection(*[[1,2,3], [2,3,4]])
set([])
```
Am I losing my mind here? Why isn't set.intersection() operating as I'd expect it to?
How can I do the intersection of many sets as I did with union (assuming the `[[1,2,3], [2,3,4]]` had a whole bunch more lists)? What would the "pythonic" way be? | 2013/10/25 | [
"https://Stackoverflow.com/questions/19580944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1406230/"
] | ```
set().intersection(*[[1,2,3], [2,3,4]])
```
is of course empty because you start with the empty set and intersect it with all the others
You can try calling the method on the `class`
```
set.intersection(*[[1,2,3], [2,3,4]])
```
but that won't work because the first argument passed needs to be a set
```
set.intersection({1, 2, 3}, *[[2,3,4], ...])
```
This looks awkward, better if you could use a list of sets in the first place. Especially if they are coming from a generator which makes it difficult to pull off the first item cleanly
```
set.intersection(*[{1,2,3}, {2,3,4}])
```
Otherwise you can just *make* them all into sets
```
set.intersection(*(set(x) for x in [[1,2,3], [2,3,4]]))
``` | convert the list to set first
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4])])
set([2, 3])
```
For multiple lists you can just use,
```
>>> set.intersection(*[set([1,2,3]), set([2,3,4]), set([5,3,4])])
set([3])
``` |
50,624,440 | How can I pause a running test and wait for user input?
I have an unconventional test (python 3, pytest) where I want to "pause" to ask the user (me) for a id code before continuing on with the test.
I'm aware this is not standard, and would like to know how to solve the problem.
Example Test:
```
def test_oauth_flow(self):
url_jwt = auth(id=client_id, scope=scope)
id_code = webbrowser.open_new(url_jwt)
# pause wait for user input.
# use code to complete flow etc....
auth = auth(code)
assert auth is 1
``` | 2018/05/31 | [
"https://Stackoverflow.com/questions/50624440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5246980/"
] | You would be better storing them as BAK files.
SQL Server actually has an option for an instance to back-up with compression. Setting the compression on, will reduce your need to Zip the backups, and the Microsoft SQL server can restore directly from its own compressed backups.
see: <https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/configure-backup-compression-sql-server?view=sql-server-2017> for how to set up compression.
see : <https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/backup-compression-sql-server?view=sql-server-2017> for more details on the compression. | Why are you using zip files when SQL Server has been able to compress backups for many years now?
If you aren't using third party backup software then back up as .bak and .trn files, compress the backup as part of the backup job and leave the files as is without zipping them.
I'm sure that if you take a compressed .bak file and try to zip it, then it won't compress very much. In some cases the zip file may even be larger than the original .bak file. |
4,835,141 | I'm using the Python-Freebase module's [mqlread()](http://www.google.com/codesearch/p?hl=en#DXpVckidmh4/trunk/freebase/api/session.py&q=mqlread%28%29%20package%3ahttp://freebase-python%5C.googlecode%5C.com&l=607). Using the following query:
```
query = [{
"cursor": True,
"id": None,
"type": "/games/game",
"mid": None,
}]
```
That returns 100 entries, but the result does not include "cursor". If you run the query manually you get something like:
```
{ "code": "/api/status/ok", "cursor": "eNqFj8FqwzAQRD-mF4sisrtaaaWlhP6H8MHYNTUEW8hpKP36KjgU2kvnMoeZ4THjR923qhKS07wpAvR5VZbYBIL9sE76FDGAs-yCA_FISprL_nWUt5tC383L59ukh9llH_TvpL7Y7rYUdZ4CN9iRITB6vTwnAhriCAwAgXGO8Etkz48dicnvy3ptTGO6OwgsBwIfwJNeHpDWowgh_URO63-M0Z7vM0neGZNL3RrihBKFU_uZS2l3sT-9cpIBaRrnOE8JhaAhQL4B9ZFRmg==", "result": [
{
"id": "/en/cities_and_knights_of_catan",
"mid": "/m/02hq3",
"type": "/games/game"
},
....
```
Which contains the "cursor". But the result from:
```
freebase.mqlread(query, extended=True)
```
Will return:
```
[{u'type': u'/games/game', u'id': u'/en/cities_and_knights_of_catan'}, ...
```
Which strips out "code" and "cursor". How can I get the "cursor"? | 2011/01/29 | [
"https://Stackoverflow.com/questions/4835141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535822/"
] | I found that the Freebase-Python module actually includes a method that takes care of cursoring for you. Just call mqlreaditer(query, extended=true), and that will return a Python generator that you can iterate through. Behind the scenes the Freebase module will query and keep track of the cursor, return results on demand until a "false" cursor is reached.
Very simple! | Support for MQL envelope parameters was dropped, presumably accidentally, in the 1.0.8 release of the Freebase Python library.
If not don't need MQL extensions, you can just drop the parameter `extended=True` parameter and use `mqlreaditer(query)`.
If you need MQL extensions (or other envelope parameters), you'll have to fall back to 1.0.6 until someone fixes the problem and does a new release.
```
sudo easy_install freebase==1.0.6
``` |
67,368,459 | I am pretty newbie to python, still learning. Here i faced a problem i can't figure out how to solve yet.
```
import random
materials = ["wood", "stone", "iron"]
wood = {
"name": "wood",
"weight": 50,
"quality": 1
}
stone = {
"name": "stone",
"weight": 80,
"quality": 2
}
iron = {
"name": "iron",
"weight": 110,
"quality": 3
}
r = random.choice(materials)
```
Basically what i wanted to do is to print a specific dictionary depends from the r - random pick.
Any tips on how to do that correctly? | 2021/05/03 | [
"https://Stackoverflow.com/questions/67368459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15822648/"
] | You should use object type instead of string, from
```
materials = ["wood", "stone", "iron"]
```
to
```
materials = [wood, stone, iron]
```
And you should also call this after assign those object. | I'd say just use a list of dictionaries. The random pick will be the dictionary in that case:
```
import random
materials = [{
"name": "wood",
"weight": 50,
"quality": 1
}, {
"name": "stone",
"weight": 80,
"quality": 2
}, {
"name": "iron",
"weight": 110,
"quality": 3
}]
r = random.choice(materials)
print(r)
``` |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | Just add `System.setProperty('java.awt.headless', 'false')` before `import groovy.swing.SwingBuilder` and kill gradle deamon with `./gradlew --stop`
it give you something liket that :
```
apply plugin: 'com.android.application'
System.setProperty('java.awt.headless', 'false')
import groovy.swing.SwingBuilder
``` | To solve this problem you have to add these 3 line exactly in this order (other orders don't work)
```
apply plugin: 'com.android.application'
import groovy.swing.SwingBuilder
System.setProperty('java.awt.headless', 'false')
``` |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | Just add `System.setProperty('java.awt.headless', 'false')` before `import groovy.swing.SwingBuilder` and kill gradle deamon with `./gradlew --stop`
it give you something liket that :
```
apply plugin: 'com.android.application'
System.setProperty('java.awt.headless', 'false')
import groovy.swing.SwingBuilder
``` | For me it finally worked when I added `System.setProperty('java.awt.headless', 'false')` twice:
* immediately after import
* after `System.console() == null` check
But then it happens be ok with only after `System.console() == null` check.
Don't forget to `./gradlew --stop` as mentioned before. |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | Just add `System.setProperty('java.awt.headless', 'false')` before `import groovy.swing.SwingBuilder` and kill gradle deamon with `./gradlew --stop`
it give you something liket that :
```
apply plugin: 'com.android.application'
System.setProperty('java.awt.headless', 'false')
import groovy.swing.SwingBuilder
``` | ```
def doPromptForPassword(msg) {
if (System.console() == null) {
System.setProperty('java.awt.headless', 'false') // worked for me
def ret = null
new SwingBuilder().edt {
dialog(modal: true, title: 'Enter password', alwaysOnTop: t
``` |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | Just add `System.setProperty('java.awt.headless', 'false')` before `import groovy.swing.SwingBuilder` and kill gradle deamon with `./gradlew --stop`
it give you something liket that :
```
apply plugin: 'com.android.application'
System.setProperty('java.awt.headless', 'false')
import groovy.swing.SwingBuilder
``` | I faced this error while building a release version of my Ionic-**Cordova** app.
All I did was assigning **"storePassword"** in my **build.json** File in my project root directory
**build.json**
```
{
"android": {
"debug": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
},
"release": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
}
}
}
``` |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | To solve this problem you have to add these 3 line exactly in this order (other orders don't work)
```
apply plugin: 'com.android.application'
import groovy.swing.SwingBuilder
System.setProperty('java.awt.headless', 'false')
``` | For me it finally worked when I added `System.setProperty('java.awt.headless', 'false')` twice:
* immediately after import
* after `System.console() == null` check
But then it happens be ok with only after `System.console() == null` check.
Don't forget to `./gradlew --stop` as mentioned before. |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | To solve this problem you have to add these 3 line exactly in this order (other orders don't work)
```
apply plugin: 'com.android.application'
import groovy.swing.SwingBuilder
System.setProperty('java.awt.headless', 'false')
``` | I faced this error while building a release version of my Ionic-**Cordova** app.
All I did was assigning **"storePassword"** in my **build.json** File in my project root directory
**build.json**
```
{
"android": {
"debug": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
},
"release": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
}
}
}
``` |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | ```
def doPromptForPassword(msg) {
if (System.console() == null) {
System.setProperty('java.awt.headless', 'false') // worked for me
def ret = null
new SwingBuilder().edt {
dialog(modal: true, title: 'Enter password', alwaysOnTop: t
``` | For me it finally worked when I added `System.setProperty('java.awt.headless', 'false')` twice:
* immediately after import
* after `System.console() == null` check
But then it happens be ok with only after `System.console() == null` check.
Don't forget to `./gradlew --stop` as mentioned before. |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | For me it finally worked when I added `System.setProperty('java.awt.headless', 'false')` twice:
* immediately after import
* after `System.console() == null` check
But then it happens be ok with only after `System.console() == null` check.
Don't forget to `./gradlew --stop` as mentioned before. | I faced this error while building a release version of my Ionic-**Cordova** app.
All I did was assigning **"storePassword"** in my **build.json** File in my project root directory
**build.json**
```
{
"android": {
"debug": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
},
"release": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
}
}
}
``` |
45,909,266 | I am working on an application that plays mp3 files using Python 3.5.2 running in IDLE with pygame 1.9.3.The problem is that some mp3 files play correctly and others do not play at all.
Test code used to evaluate the problem:
```
import pygame
from pygame import mixer
from pygame.locals import *
pygame.init()
mixer.init()
mixer.music.load('good.mp3')
mixer.music.play()
u = input('Good file')
mixer.music.load('bad.mp3')
mixer.music.play()
u = input('Bad file')
```
The file labeled 'good' plays correctly, while the one labled 'bad' does not. Both files are in the same directory; both files play with a music player; and both files work with python 3.4 and pygame on a Windows 7 machine. | 2017/08/27 | [
"https://Stackoverflow.com/questions/45909266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823241/"
] | ```
def doPromptForPassword(msg) {
if (System.console() == null) {
System.setProperty('java.awt.headless', 'false') // worked for me
def ret = null
new SwingBuilder().edt {
dialog(modal: true, title: 'Enter password', alwaysOnTop: t
``` | I faced this error while building a release version of my Ionic-**Cordova** app.
All I did was assigning **"storePassword"** in my **build.json** File in my project root directory
**build.json**
```
{
"android": {
"debug": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
},
"release": {
"keystore": "./my-release-key.keystore",
"storePassword": "password",
"alias": "name",
"password" : "password",
"keystoreType": "",
"packageType": "apk"
}
}
}
``` |
39,767,898 | i have added one list like below:
```
>>> l = [1,2,3,4]
>>> len(l)
4
```
so when i accessed
`l[3:1]` python has return blank list like `[]`
`l[3:1]=4` it returns error like
```
>>> l[3:1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
```
but when i used `l[3:1] = 'a'`. it successfully run and gives new list as below:
```
>>> l[3:1] = 'a'
>>> l
[1, 2, 3, 'a', 4]
>>>
```
now i have length of 5. now i want to add new element at 5th index so i write
```
>>> l[5] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>>
```
my questions are follow:
1. why ptyhon returns blank list when accessing like l[3:1]?
2. why it gives error when using `l[3:1] = 4` but works fine using `l[3:1]='a'`?
3. Why it is giving error instead of adding new value at 5th index? | 2016/09/29 | [
"https://Stackoverflow.com/questions/39767898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3779104/"
] | as `l[3:1]` is a `Sequence` hence you can assign only a `Sequence` to it thus,
the reason `l[3:1]` works because 'a' itself is a sequence but `4` is a normal integer. | First question - You are trying to slice the list from two different ways.
Given `l = [1, 2, 3, 4]`
`l[3:]` slices the list from element with index 3 and onwards, leaving you with `[4]`
`l[:1]` slices the list from element with index 1 and backwards, leaving you with `[1]`.
Now if you slice it both ways, you will have an empty list, there's nothing in that range.
Second question - this one is kind of odd. In theory string behaves like a list with each character being an item in that list, so that's why you can only enter 'a' and 4 being an integer throws an error. I don't exactly know why, but `[3:1]` inserts the new list (characters of the string) after 3rd element. If you leave out the `[:1]`, it will replace the list from 3rd element instead, leaving you with `[1, 2, 3, 'a']`
Third question - You can only access indexes of a list that already exist. 5th index doesn't exist for you yet. You have to create it. That's either by append, insert etc. Then you can modify it with `l[5]` |
39,767,898 | i have added one list like below:
```
>>> l = [1,2,3,4]
>>> len(l)
4
```
so when i accessed
`l[3:1]` python has return blank list like `[]`
`l[3:1]=4` it returns error like
```
>>> l[3:1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
```
but when i used `l[3:1] = 'a'`. it successfully run and gives new list as below:
```
>>> l[3:1] = 'a'
>>> l
[1, 2, 3, 'a', 4]
>>>
```
now i have length of 5. now i want to add new element at 5th index so i write
```
>>> l[5] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>>
```
my questions are follow:
1. why ptyhon returns blank list when accessing like l[3:1]?
2. why it gives error when using `l[3:1] = 4` but works fine using `l[3:1]='a'`?
3. Why it is giving error instead of adding new value at 5th index? | 2016/09/29 | [
"https://Stackoverflow.com/questions/39767898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3779104/"
] | >
> 1. why python returns blank list when accessing like l[3:1]?
>
>
>
`list[i:j] means you want sliced list with value from 'i'th index to upto 'j'th index` (not including jth index). For example:
```
>>> my_list = [1, 2, 3, 4, 5]
>>> my_list[2:3]
[3]
```
In your case `i > j`, hence list is empty.
>
> 2. why it gives error when using l[3:1] = 4 but works fine using l[3:1]='a'?
>
>
>
`l[3:1]` is the sliced list. You can a assigned it only with list. since, python `str` are considered as the list of chars. That is why you are able to assigned it.
>
> 3. Why it is giving error instead of adding new value at 5th index?
>
>
>
Even though the length of your list is `5` but since the index of the list starts with 0, you can access element of list only till `len(list) - 1`. In case you want to add item at the end of list, you need to do `.append()` on the list. Below is the example to show this:
```
>>> my_list = [1, 2, 7, 9, 8, 4, 5]
>>> len(my_list)
7 # <-- Length as 7
>>> my_list[6]
5 # <-- value of index at length(list) - 1, which is the last value of list
>>> my_list[7] # <-- index as length of list, resulted in 'IndexError'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> my_list.append(9) # <-- Adds an item at the of list
>>> len(my_list) # length incremented by 1
8
``` | as `l[3:1]` is a `Sequence` hence you can assign only a `Sequence` to it thus,
the reason `l[3:1]` works because 'a' itself is a sequence but `4` is a normal integer. |
39,767,898 | i have added one list like below:
```
>>> l = [1,2,3,4]
>>> len(l)
4
```
so when i accessed
`l[3:1]` python has return blank list like `[]`
`l[3:1]=4` it returns error like
```
>>> l[3:1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
```
but when i used `l[3:1] = 'a'`. it successfully run and gives new list as below:
```
>>> l[3:1] = 'a'
>>> l
[1, 2, 3, 'a', 4]
>>>
```
now i have length of 5. now i want to add new element at 5th index so i write
```
>>> l[5] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>>
```
my questions are follow:
1. why ptyhon returns blank list when accessing like l[3:1]?
2. why it gives error when using `l[3:1] = 4` but works fine using `l[3:1]='a'`?
3. Why it is giving error instead of adding new value at 5th index? | 2016/09/29 | [
"https://Stackoverflow.com/questions/39767898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3779104/"
] | >
> 1. why python returns blank list when accessing like l[3:1]?
>
>
>
`list[i:j] means you want sliced list with value from 'i'th index to upto 'j'th index` (not including jth index). For example:
```
>>> my_list = [1, 2, 3, 4, 5]
>>> my_list[2:3]
[3]
```
In your case `i > j`, hence list is empty.
>
> 2. why it gives error when using l[3:1] = 4 but works fine using l[3:1]='a'?
>
>
>
`l[3:1]` is the sliced list. You can a assigned it only with list. since, python `str` are considered as the list of chars. That is why you are able to assigned it.
>
> 3. Why it is giving error instead of adding new value at 5th index?
>
>
>
Even though the length of your list is `5` but since the index of the list starts with 0, you can access element of list only till `len(list) - 1`. In case you want to add item at the end of list, you need to do `.append()` on the list. Below is the example to show this:
```
>>> my_list = [1, 2, 7, 9, 8, 4, 5]
>>> len(my_list)
7 # <-- Length as 7
>>> my_list[6]
5 # <-- value of index at length(list) - 1, which is the last value of list
>>> my_list[7] # <-- index as length of list, resulted in 'IndexError'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> my_list.append(9) # <-- Adds an item at the of list
>>> len(my_list) # length incremented by 1
8
``` | First question - You are trying to slice the list from two different ways.
Given `l = [1, 2, 3, 4]`
`l[3:]` slices the list from element with index 3 and onwards, leaving you with `[4]`
`l[:1]` slices the list from element with index 1 and backwards, leaving you with `[1]`.
Now if you slice it both ways, you will have an empty list, there's nothing in that range.
Second question - this one is kind of odd. In theory string behaves like a list with each character being an item in that list, so that's why you can only enter 'a' and 4 being an integer throws an error. I don't exactly know why, but `[3:1]` inserts the new list (characters of the string) after 3rd element. If you leave out the `[:1]`, it will replace the list from 3rd element instead, leaving you with `[1, 2, 3, 'a']`
Third question - You can only access indexes of a list that already exist. 5th index doesn't exist for you yet. You have to create it. That's either by append, insert etc. Then you can modify it with `l[5]` |
39,767,898 | i have added one list like below:
```
>>> l = [1,2,3,4]
>>> len(l)
4
```
so when i accessed
`l[3:1]` python has return blank list like `[]`
`l[3:1]=4` it returns error like
```
>>> l[3:1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
```
but when i used `l[3:1] = 'a'`. it successfully run and gives new list as below:
```
>>> l[3:1] = 'a'
>>> l
[1, 2, 3, 'a', 4]
>>>
```
now i have length of 5. now i want to add new element at 5th index so i write
```
>>> l[5] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>>
```
my questions are follow:
1. why ptyhon returns blank list when accessing like l[3:1]?
2. why it gives error when using `l[3:1] = 4` but works fine using `l[3:1]='a'`?
3. Why it is giving error instead of adding new value at 5th index? | 2016/09/29 | [
"https://Stackoverflow.com/questions/39767898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3779104/"
] | 1. Why does python return a blank list when accessing like l[3:1]?
Slicing works as follows:
```
l[start:end] # start to end-1
l[start:] # start to rest of list
l[:end] # beginning of list to end-1
l[:] # copy complete list
```
As you are passing `l[3:1]` i.e start from 3rd index and end at 1-1 i.e 0th index, that means `start index > end index`, so empty list will be displayed. Either you can pass `l[1:3]` or any negative indexes (ex: `l[-3:-1]`).
2. Why does it throw an error when using l[3:1] = 4 but works fine using l[3:1]='a'?
In slicing retrieval, you will get a list (sequence)
In same way, in case of slicing assignment, you can pass sequence. Here string is sequence of characters and so working for string and not for integer
In case of integer, you can try:
```
l[3:1] = [4]
```
3. Why does it throw an error instead of adding new value at 5th index?
list contain only 4 elements. `l = [1,2,3,4]`
Here, you can not access or assign more than index 3 (index starts from 0).
In your scenario, you can append data. | First question - You are trying to slice the list from two different ways.
Given `l = [1, 2, 3, 4]`
`l[3:]` slices the list from element with index 3 and onwards, leaving you with `[4]`
`l[:1]` slices the list from element with index 1 and backwards, leaving you with `[1]`.
Now if you slice it both ways, you will have an empty list, there's nothing in that range.
Second question - this one is kind of odd. In theory string behaves like a list with each character being an item in that list, so that's why you can only enter 'a' and 4 being an integer throws an error. I don't exactly know why, but `[3:1]` inserts the new list (characters of the string) after 3rd element. If you leave out the `[:1]`, it will replace the list from 3rd element instead, leaving you with `[1, 2, 3, 'a']`
Third question - You can only access indexes of a list that already exist. 5th index doesn't exist for you yet. You have to create it. That's either by append, insert etc. Then you can modify it with `l[5]` |
39,767,898 | i have added one list like below:
```
>>> l = [1,2,3,4]
>>> len(l)
4
```
so when i accessed
`l[3:1]` python has return blank list like `[]`
`l[3:1]=4` it returns error like
```
>>> l[3:1] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
```
but when i used `l[3:1] = 'a'`. it successfully run and gives new list as below:
```
>>> l[3:1] = 'a'
>>> l
[1, 2, 3, 'a', 4]
>>>
```
now i have length of 5. now i want to add new element at 5th index so i write
```
>>> l[5] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>>
```
my questions are follow:
1. why ptyhon returns blank list when accessing like l[3:1]?
2. why it gives error when using `l[3:1] = 4` but works fine using `l[3:1]='a'`?
3. Why it is giving error instead of adding new value at 5th index? | 2016/09/29 | [
"https://Stackoverflow.com/questions/39767898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3779104/"
] | >
> 1. why python returns blank list when accessing like l[3:1]?
>
>
>
`list[i:j] means you want sliced list with value from 'i'th index to upto 'j'th index` (not including jth index). For example:
```
>>> my_list = [1, 2, 3, 4, 5]
>>> my_list[2:3]
[3]
```
In your case `i > j`, hence list is empty.
>
> 2. why it gives error when using l[3:1] = 4 but works fine using l[3:1]='a'?
>
>
>
`l[3:1]` is the sliced list. You can a assigned it only with list. since, python `str` are considered as the list of chars. That is why you are able to assigned it.
>
> 3. Why it is giving error instead of adding new value at 5th index?
>
>
>
Even though the length of your list is `5` but since the index of the list starts with 0, you can access element of list only till `len(list) - 1`. In case you want to add item at the end of list, you need to do `.append()` on the list. Below is the example to show this:
```
>>> my_list = [1, 2, 7, 9, 8, 4, 5]
>>> len(my_list)
7 # <-- Length as 7
>>> my_list[6]
5 # <-- value of index at length(list) - 1, which is the last value of list
>>> my_list[7] # <-- index as length of list, resulted in 'IndexError'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> my_list.append(9) # <-- Adds an item at the of list
>>> len(my_list) # length incremented by 1
8
``` | 1. Why does python return a blank list when accessing like l[3:1]?
Slicing works as follows:
```
l[start:end] # start to end-1
l[start:] # start to rest of list
l[:end] # beginning of list to end-1
l[:] # copy complete list
```
As you are passing `l[3:1]` i.e start from 3rd index and end at 1-1 i.e 0th index, that means `start index > end index`, so empty list will be displayed. Either you can pass `l[1:3]` or any negative indexes (ex: `l[-3:-1]`).
2. Why does it throw an error when using l[3:1] = 4 but works fine using l[3:1]='a'?
In slicing retrieval, you will get a list (sequence)
In same way, in case of slicing assignment, you can pass sequence. Here string is sequence of characters and so working for string and not for integer
In case of integer, you can try:
```
l[3:1] = [4]
```
3. Why does it throw an error instead of adding new value at 5th index?
list contain only 4 elements. `l = [1,2,3,4]`
Here, you can not access or assign more than index 3 (index starts from 0).
In your scenario, you can append data. |
22,278,352 | I'm following some online python tutorials and i ran across this syntax error code twice now and can't figure out what's wrong.
Here's my code:
```
import urllib
import re
htmlfile = urllib.urlopen("http://finance.yahoo.com/q?s=AAPL")
htmltext = htmlfile.read()
regex = '<span id="yfs_l84_aapl">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern, html)
print price
```
I am using Enthought Python Distribution package (python version 2.7.3)
Here's the syntax error when i run the above script.
```
Traceback (most recent call last):
File "E:\python\scripts\stocks.py", line 4, in <module>
htmlfile = urllib.urlopen("http://finance.yahoo.com/q?s=AAPL")
File "e:\python27\lib\urllib.py", line 86, in urlopen
return opener.open(url)
File "e:\python27\lib\urllib.py", line 207, in open
return getattr(self, name)(url)
File "e:\python27\lib\urllib.py", line 291, in open_http
import httplib
File "e:\python27\lib\httplib.py", line 79, in <module>
import mimetools
File "e:\python27\lib\mimetools.py", line 6, in <module>
import tempfile
File "e:\python27\lib\tempfile.py", line 34, in <module>
from random import Random as _Random
File "E:\python\scripts\random.py", line 1
def random
^
SyntaxError: invalid syntax
```
I tried searching around to understand what's going on but no avail. What's python trying to tell me with all these traceback lines and why do I get a syntax error? | 2014/03/09 | [
"https://Stackoverflow.com/questions/22278352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2241963/"
] | If you look at the stack trace, towards the bottom, you can see that the syntax error is in a file called `E:\python\scripts\random.py`. This script is one you've added to the system, and it appears to contain a syntax error. Because it's named `random` and is located in the `Scripts` directory, it is "overriding" the built-in `random` library.
Remove or rename that file and you should be good to go. | The import of `module` is controlled by `sys.path`. To a first approximation when your program executes `import module` the interpreter visits the directories on `sys.path` in turn. It looks for a `module.pyc` file and a `module.py` file in each directory, moving on to the next if it finds neither. When it finds one or both, if the `.py` is newer than the `.pyc` (in other words, if the source has been modified since the file was last compiled, or if the compiled file does not exist) then the interpreter compiles the `.py` file and attempts to write to it. There are no guarantees your process will be able to write in that particular directory.
Having identified the correct file the interpreter creates a new namespace, executes the code of the module with that namespace as local, then binds the name of the module with the namespace just created. So if you have bound a name in `module` it should (modulo any `__all__` assignment in the module's code) be available within your importing module as `module.name`.
I suspect this question has taught you why it's not a good idea to duplicate the names of system libraries in your own code - a lesson we all have to learn! |
55,975,708 | In python objects, overriding the methods `__repr__` and `__str__` of an object allows one to provide "unambiguous" and "human-readable" representations of the object, respectively. How does one achieve similar behavior in Racket?
I came across the `printable<%>` interface [here](https://docs.racket-lang.org/reference/objectprinting.html), which seems like it should be usable for this purpose, but I haven't been able to get it to work quite as I expect it to. Building on the standard "fish" example from the docs:
```
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print "Print called!"))
(define/public (custom-write port)
(print "Write called!"))
(define/public (custom-display port)
(print "Display called!"))))
```
This is the output I get:
```
> (define f (new fish% [size 10]))
> f
"Display called!""Display called!""Print called!"
> (print f)
"Write called!""Print called!"
> (display f)
"Display called!""Display called!"
> (write f)
"Write called!""Write called!"
>
```
So the question is threefold:
1. Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
2. What should the methods custom-print, custom-write, and custom-display evaluate to? Should they simply return a string, or should they actually entail the side effect of printing, writing, or displaying, as the case may be? E.g. should the custom-write method invoke the `write` function internally?
3. Is this the right construct to use for this purpose at all? If not, is there one / what is it? | 2019/05/03 | [
"https://Stackoverflow.com/questions/55975708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/323874/"
] | IIUC
```
df.apply(lambda x : x.name+'_'+x.astype(str))
Out[1323]:
Col1 Col2
0 Col1_12 Col2_34
1 Col1_12 Col2_34
``` | Use `DataFrame.columns` to access each column and concatenate as string to each value:
```
for col in df.columns:
df[col] = col + '_' + df[col].astype(str)
```
---
```
print(df)
Col1 Col2
0 Col1_12 Col2_34
1 Col1_12 Col2_34
``` |
55,975,708 | In python objects, overriding the methods `__repr__` and `__str__` of an object allows one to provide "unambiguous" and "human-readable" representations of the object, respectively. How does one achieve similar behavior in Racket?
I came across the `printable<%>` interface [here](https://docs.racket-lang.org/reference/objectprinting.html), which seems like it should be usable for this purpose, but I haven't been able to get it to work quite as I expect it to. Building on the standard "fish" example from the docs:
```
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print "Print called!"))
(define/public (custom-write port)
(print "Write called!"))
(define/public (custom-display port)
(print "Display called!"))))
```
This is the output I get:
```
> (define f (new fish% [size 10]))
> f
"Display called!""Display called!""Print called!"
> (print f)
"Write called!""Print called!"
> (display f)
"Display called!""Display called!"
> (write f)
"Write called!""Write called!"
>
```
So the question is threefold:
1. Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
2. What should the methods custom-print, custom-write, and custom-display evaluate to? Should they simply return a string, or should they actually entail the side effect of printing, writing, or displaying, as the case may be? E.g. should the custom-write method invoke the `write` function internally?
3. Is this the right construct to use for this purpose at all? If not, is there one / what is it? | 2019/05/03 | [
"https://Stackoverflow.com/questions/55975708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/323874/"
] | IIUC
```
df.apply(lambda x : x.name+'_'+x.astype(str))
Out[1323]:
Col1 Col2
0 Col1_12 Col2_34
1 Col1_12 Col2_34
``` | Convert each row in your dataframe as string and concat the column name:
```
df = pd.DataFrame({
"col1": [12 , 34],
'col2': [7,9]},)
for c in df:
df[c] = c + '_' + df[c].astype(str)
df
```
Result:
```
col1 col2
0 col1_12 col2_7
1 col1_34 col2_9
``` |
55,975,708 | In python objects, overriding the methods `__repr__` and `__str__` of an object allows one to provide "unambiguous" and "human-readable" representations of the object, respectively. How does one achieve similar behavior in Racket?
I came across the `printable<%>` interface [here](https://docs.racket-lang.org/reference/objectprinting.html), which seems like it should be usable for this purpose, but I haven't been able to get it to work quite as I expect it to. Building on the standard "fish" example from the docs:
```
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print "Print called!"))
(define/public (custom-write port)
(print "Write called!"))
(define/public (custom-display port)
(print "Display called!"))))
```
This is the output I get:
```
> (define f (new fish% [size 10]))
> f
"Display called!""Display called!""Print called!"
> (print f)
"Write called!""Print called!"
> (display f)
"Display called!""Display called!"
> (write f)
"Write called!""Write called!"
>
```
So the question is threefold:
1. Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
2. What should the methods custom-print, custom-write, and custom-display evaluate to? Should they simply return a string, or should they actually entail the side effect of printing, writing, or displaying, as the case may be? E.g. should the custom-write method invoke the `write` function internally?
3. Is this the right construct to use for this purpose at all? If not, is there one / what is it? | 2019/05/03 | [
"https://Stackoverflow.com/questions/55975708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/323874/"
] | IIUC
```
df.apply(lambda x : x.name+'_'+x.astype(str))
Out[1323]:
Col1 Col2
0 Col1_12 Col2_34
1 Col1_12 Col2_34
``` | ```
df = pd.DataFrame({'colA': [12,34], 'colB': [56,78]})
df = df.columns.values + '_' + df.astype(str)
print(df)
```
Output:
```
colA colB
0 colA_12 colB_56
1 colA_34 colB_78
``` |
54,437,030 | I want to containerise a pipeline of code that was predominantly developed in Python but has a dependency on a model that was trained in R. There are some additional dependencies on the requirements and packages needed for both codebases. How can I create a Docker image that allows me to build a container that will run this Python and R code together?
For context, I have an R code that runs a model (random forest) but it needs to be part of a data pipeline that was built in Python. The Python pipeline performs some functionality first and generates input for the model, then executes the R code with that input, before taking the output to the next stage of the Python pipeline.
So I've created a template for this process by writing a simple test Python function to call an R code ("test\_call\_r.py" which imports the subprocess package) and need to put this in a Docker container with the necessary requirements and packages for both Python and R.
I have been able to build the Docker container for the Python pipeline itself, but cannot successfully install R and the associated packages alongside the Python requirements. I want to rewrite the Dockerfile to create an image to do this.
From the Dockerhub documentation I can create an image for the Python pipeline using, e.g.,
```
FROM python:3
WORKDIR /app
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app
CMD [ "python", "./test_call_r.py" ]
```
And similarly from Dockerhub I can use a base R image (or Rocker) to create a Docker container that can run a randomForest model, e.g.,
```
FROM r-base
WORKDIR /app
COPY myscripts /app/
RUN Rscript -e "install.packages('randomForest')"
CMD ["Rscript", "myscript.R"]
```
But what I need is to create an image that can install the requirements and packages for both Python and R, and execute the codebase to run R from a subprocess in Python. How can I do this? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54437030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6033545/"
] | The Dockerfile I built for Python and R to run together with their dependencies in this manner is:
```
FROM ubuntu:latest
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends build-essential r-base r-cran-randomforest python3.6 python3-pip python3-setuptools python3-dev
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip3 install -r requirements.txt
RUN Rscript -e "install.packages('data.table')"
COPY . /app
```
The commands to build the image, run the container (naming it SnakeR here), and execute the code are:
```
docker build -t my_image .
docker run -it --name SnakeR my_image
docker exec SnakeR /bin/sh -c "python3 test_call_r.py"
```
I treated it like a Ubuntu OS and built the image as follows:
* suppress the prompts for choosing your location during the R install;
* update the apt-get;
* set installation criteria of:
* + y = yes to user prompts for proceeding (e.g. memory allocation);
* + install only the recommended, not suggested, dependencies;
* include some essential installation packages for Ubuntu;
* r-base for the R software;
* r-cran-randomforest to force the package to be available (unlike the separate install of data.table which didn’t work for randomForest for some reason);
* python3.6 version of python;
* python3-pip to allow pip be used to install the requirements;
* python3-setuptools to somehow help execute the pip installs (?!);
* python3-dev to execute the JayDeBeApi installation as part of the requirements (that it otherwise confuses is for Python2 not 3);
* specify the active “working directory” to be the /app location;
* copy the requirements file that holds the python dependencies (built from the virtual environment of the Python codebase, e.g., with pip freeze);
* install the Python packages from the requirements file (pip3 for Python3);
* install the R packages (e.g. just data.table here);
* copy the directory contents to the specified working directory /app.
This is replicated from my blog post at <https://datascienceunicorn.tumblr.com/post/182297983466/building-a-docker-to-run-python-r> | I made an image for my personal projects, you could use this if you want: <https://github.com/dipayan90/docker-python-r> |
54,437,030 | I want to containerise a pipeline of code that was predominantly developed in Python but has a dependency on a model that was trained in R. There are some additional dependencies on the requirements and packages needed for both codebases. How can I create a Docker image that allows me to build a container that will run this Python and R code together?
For context, I have an R code that runs a model (random forest) but it needs to be part of a data pipeline that was built in Python. The Python pipeline performs some functionality first and generates input for the model, then executes the R code with that input, before taking the output to the next stage of the Python pipeline.
So I've created a template for this process by writing a simple test Python function to call an R code ("test\_call\_r.py" which imports the subprocess package) and need to put this in a Docker container with the necessary requirements and packages for both Python and R.
I have been able to build the Docker container for the Python pipeline itself, but cannot successfully install R and the associated packages alongside the Python requirements. I want to rewrite the Dockerfile to create an image to do this.
From the Dockerhub documentation I can create an image for the Python pipeline using, e.g.,
```
FROM python:3
WORKDIR /app
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app
CMD [ "python", "./test_call_r.py" ]
```
And similarly from Dockerhub I can use a base R image (or Rocker) to create a Docker container that can run a randomForest model, e.g.,
```
FROM r-base
WORKDIR /app
COPY myscripts /app/
RUN Rscript -e "install.packages('randomForest')"
CMD ["Rscript", "myscript.R"]
```
But what I need is to create an image that can install the requirements and packages for both Python and R, and execute the codebase to run R from a subprocess in Python. How can I do this? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54437030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6033545/"
] | The Dockerfile I built for Python and R to run together with their dependencies in this manner is:
```
FROM ubuntu:latest
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends build-essential r-base r-cran-randomforest python3.6 python3-pip python3-setuptools python3-dev
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip3 install -r requirements.txt
RUN Rscript -e "install.packages('data.table')"
COPY . /app
```
The commands to build the image, run the container (naming it SnakeR here), and execute the code are:
```
docker build -t my_image .
docker run -it --name SnakeR my_image
docker exec SnakeR /bin/sh -c "python3 test_call_r.py"
```
I treated it like a Ubuntu OS and built the image as follows:
* suppress the prompts for choosing your location during the R install;
* update the apt-get;
* set installation criteria of:
* + y = yes to user prompts for proceeding (e.g. memory allocation);
* + install only the recommended, not suggested, dependencies;
* include some essential installation packages for Ubuntu;
* r-base for the R software;
* r-cran-randomforest to force the package to be available (unlike the separate install of data.table which didn’t work for randomForest for some reason);
* python3.6 version of python;
* python3-pip to allow pip be used to install the requirements;
* python3-setuptools to somehow help execute the pip installs (?!);
* python3-dev to execute the JayDeBeApi installation as part of the requirements (that it otherwise confuses is for Python2 not 3);
* specify the active “working directory” to be the /app location;
* copy the requirements file that holds the python dependencies (built from the virtual environment of the Python codebase, e.g., with pip freeze);
* install the Python packages from the requirements file (pip3 for Python3);
* install the R packages (e.g. just data.table here);
* copy the directory contents to the specified working directory /app.
This is replicated from my blog post at <https://datascienceunicorn.tumblr.com/post/182297983466/building-a-docker-to-run-python-r> | Being specific on both Python and R versions will save you future headaches. This approach, for instance, will always install R v4.0 and Python v3.8
```
FROM r-base:4.0.3
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev python3.8 python3-pip python3-setuptools python3-dev
RUN pip3 install --upgrade pip
ENV PYTHONPATH "${PYTHONPATH}:/app"
WORKDIR /app
ADD requirements.txt .
ADD requirements.r .
# installing python libraries
RUN pip3 install -r requirements.txt
# installing r libraries
RUN Rscript requirements.r
```
And your requirements.r file should look like
```
install.packages('data.table')
install.packages('jsonlite')
...
``` |
54,437,030 | I want to containerise a pipeline of code that was predominantly developed in Python but has a dependency on a model that was trained in R. There are some additional dependencies on the requirements and packages needed for both codebases. How can I create a Docker image that allows me to build a container that will run this Python and R code together?
For context, I have an R code that runs a model (random forest) but it needs to be part of a data pipeline that was built in Python. The Python pipeline performs some functionality first and generates input for the model, then executes the R code with that input, before taking the output to the next stage of the Python pipeline.
So I've created a template for this process by writing a simple test Python function to call an R code ("test\_call\_r.py" which imports the subprocess package) and need to put this in a Docker container with the necessary requirements and packages for both Python and R.
I have been able to build the Docker container for the Python pipeline itself, but cannot successfully install R and the associated packages alongside the Python requirements. I want to rewrite the Dockerfile to create an image to do this.
From the Dockerhub documentation I can create an image for the Python pipeline using, e.g.,
```
FROM python:3
WORKDIR /app
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app
CMD [ "python", "./test_call_r.py" ]
```
And similarly from Dockerhub I can use a base R image (or Rocker) to create a Docker container that can run a randomForest model, e.g.,
```
FROM r-base
WORKDIR /app
COPY myscripts /app/
RUN Rscript -e "install.packages('randomForest')"
CMD ["Rscript", "myscript.R"]
```
But what I need is to create an image that can install the requirements and packages for both Python and R, and execute the codebase to run R from a subprocess in Python. How can I do this? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54437030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6033545/"
] | Being specific on both Python and R versions will save you future headaches. This approach, for instance, will always install R v4.0 and Python v3.8
```
FROM r-base:4.0.3
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev python3.8 python3-pip python3-setuptools python3-dev
RUN pip3 install --upgrade pip
ENV PYTHONPATH "${PYTHONPATH}:/app"
WORKDIR /app
ADD requirements.txt .
ADD requirements.r .
# installing python libraries
RUN pip3 install -r requirements.txt
# installing r libraries
RUN Rscript requirements.r
```
And your requirements.r file should look like
```
install.packages('data.table')
install.packages('jsonlite')
...
``` | I made an image for my personal projects, you could use this if you want: <https://github.com/dipayan90/docker-python-r> |
50,468,180 | Does a function exist in Julia to create a dense layer ?
An equivalent to the function [tf.layers.dense](https://www.tensorflow.org/api_docs/python/tf/layers/dense) in Python ?
```
tf.layers.dense(
inputs,
units,
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
reuse=None
)
``` | 2018/05/22 | [
"https://Stackoverflow.com/questions/50468180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9529736/"
] | No,
The [Layers module](https://www.tensorflow.org/api_guides/python/contrib.layers) in python tensorflow, is a **contrib** module.
That means (amongst other things),
it will not normally be available in TensorFlow binding for any language other than Python (because it doesn't correspond to an operation in `libtensorflow.so`.)
However, Dense layers are trivially implementable from first principles in tensorflow.
A simple dense layer is:
```
using TensorFlow
@tf begin
X=placeholder(Float32; shape=[-1, 10])
W = get_variable((10, 100), Float32)
b = get_variable(100, Float32)
Y = nn.relu(X*W + b)
end
```
So from there you could build your own Dense function
To get you started, something like
```
using TensorFlow: get_shape
function dense(inputs::Tensor, units::Int, activation=identity, name=randstring())
in_dims = get_shape(inputs, 2)
W = get_variable("W_$name", (in_dims, units), Float32)
b = get_variable("b_$name", units, Float32)
activation(inputs*W + b)
end
```
That could readily be extended to do whatever you needed. | Look at `Dense` in [Flux.jl](https://github.com/FluxML/Flux.jl#features). See the README and docs for details, but it acts very similarly.
Flux.jl is not TensorFlow, but is a newer pure julia neural network library. |
58,422,124 | This is to practice nested dictionary, or, array of dictionaries, list of dictionary etc.
The data structure can be best described as array of struct/class in C/C++, and each struct has multiple members. The challenge to me:
1). There is string "**Sample Name**" as separator at the beginning of each record followed by multi-members;
2). 6 members of the record in each row separate by colon ":";
3). how to read multiple lines (instead of multiple fields of the same line, which is easier to parse) into the member of the record;
4). The **record** separator may not be preceded with a blank line.
I put sample input and the expected output for testing.
Example: **input.txt**
```
Sample Name: CanNAM1_192
SNPs : 5392
MNPs : 0
Insertions : 248
Deletions : 359
Phased Genotypes : 8.8% (2349/26565)
MNP Het/Hom ratio : - (0/0)
Sample Name: CanNAM2_195
SNPs : 5107
MNPs : 0
Insertions : 224
Deletions : 351
Phased Genotypes : 8.9% (2375/26560)
MNP Het/Hom ratio : - (0/0)
Sample Name: CanNAM3_196
SNPs : 4926
MNPs : 0
Insertions : 202
Deletions : 332
Phased Genotypes : 8.0% (2138/26582)
MNP Het/Hom ratio : - (0/0)
```
In awk there is RECORD separator RS and FIELD separator FS that can be set at beginning, but no such function in python to my knowledge.
**Output.tab:**
```
CanNAM1_192 5392 0 248 359 8.8% -
CanNAM2_195 5107 0 224 351 8.9% -
CanNAM3_196 4926 0 202 332 8.0% -
```
Tried search some example code for my case like this [one](https://stackoverflow.com/questions/46985556/read-text-file-lines-and-create-a-dictionary-using-python), [this one](https://stackoverflow.com/questions/1657299/how-do-i-read-two-lines-from-a-file-at-a-time-using-python)
```
import sys
filename=sys.argv[1]
Dictn = {}
with open(filename, 'r') as fh:
for line in fh:
while True:
if line.startswith('Sample Name'):
nameLine = line.strip()
ID = nameLine.split(':')
else:
line2 = next(fh).strip()
line2 = line2.split(':')
print (line2[0], line2[1]) # For debugging to see the parsing result
line3 = next(fh).strip().split(':')
line4 = next(fh).strip().split(':')
line5 = next(fh).strip().split(':')
line6 = next(fh).strip().split(':')
line7 = next(fh).strip().split(':')
Dictn.update({
ID[1]: {
line2[0]: line2[1],
line3[0]: line3[1],
line4[0]: line4[1],
line5[0]: line5[1],
line6[0]: line6[1],
line7[0]: line7[1],
}
})
break
print(Dictn)
Dictn.get('CanNAM1_192')
# {CanNAM1_192:{ {'SNPs' : '5392'}, {'MNPs' : '0'}, {'Insertions' : '248'}, {'Deletions' : '359'}, {'Phased Genotypes' : '8.8%'}, {'MNP Het/Hom ratio' : '-'} }}
```
I am stuck with the parsing each record by reading 7 lines at a time, then push/update the record into the dictionary. Not good at Python, and I really appreciate any help! | 2019/10/16 | [
"https://Stackoverflow.com/questions/58422124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5650705/"
] | ```
data = {}
with open("data.txt",'r') as fh:
for line in fh.readlines(): #read in multiple lines
if len(line.strip())==0:
continue
if line.startswith('Sample Name'):
nameLine = line.strip()
name = nameLine.split(": ")[1]
data[name] = {}
else:
splitLine = line.split(":")
variableName = splitLine[0].strip()
value = splitLine[1].strip()
data[name][variableName] = value
print(data)
```
1. Make sure that the line you're reading in is not empty. If you strip all the empty space from an empty line, you'll get a string with length zero. We just check for this.
2. If the line starts with `Sample Name`, we know that the id will come after a colon and a space. We can split by these characters. The id will be the second part of the split line, and so we just get the item at index one.
3. Keep track of the current id, in a variable (I call it `name`). Create an empty nested dictionary entry for that id.
4. If the line is not an ID line, then it must be a data line associated with the last entered ID.
5. We get the line, split it by `:`. The name of the variable will be on the left, the first item, and the value will be on the right, so the second item. Make sure we strip all the extra spaces on either side.
6. Add the variable and value pair to the dictionary entry for the ID. | Spent more time on the question and got a solution, which seems **NOT** "pythonic" as my code handling the first "record" (8 lines of data including the blank line at the bottom) are redundant of the rest.
```
import itertools
data = {}
with open("vcfstats.txt", 'r') as f:
for line in f:
if line.strip(): #Non blank line
if line.startswith('Sample Name'):
nameLine = line.strip()
name = nameLine.split(": ")[1].strip()
data[name] = {}
else:
splitLine = line.split(": ")
variableName = splitLine[0].strip()
values = splitLine[1].strip().split(" ")
data[name][variableName] = values[0] #Only take the first item as value
else:
continue
for line in itertools.islice(f, 8):
lines = (line.rstrip() for line in f) # including blank lines
lines = list(line for line in lines if line) # skip blank lines
for line in lines:
if line.startswith('Sample Name'):
nameLine = line.strip()
name = nameLine.split(": ")[1].strip()
data[name] = {}
else:
splitLine = line.split(": ")
variableName = splitLine[0].strip()
values = splitLine[1].strip().split(" ")
data[name][variableName] = values[0] #Only take the first item as value
```
What did I miss? Thanks a lot! |
14,735,366 | I'm writing a shell script that do some work after checking the version of python on the system.
and I do a=`python -V` and a echo of $a:
```
[root@machine folder]# a=`python -V`
Python 2.3.4
[root@machine folder]# echo $a
```
and `echo $a` just output nothing
at the same time I do:
```
[root@machine folder]# if grep "2.3.4" `python -V` ; then echo "bad" ; fi
Python 2.3.4
```
after I hit enter it just output the version of the python but nothing else.
Why it behaves like this? Is there other ways for me to do the same task? | 2013/02/06 | [
"https://Stackoverflow.com/questions/14735366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/990106/"
] | `python -V` appears to output on `stderr`. If you run
```
a=`python -V`
```
the output appears on the console (i.e. it's not being picked up by the subshell assignment). However, if you redirect `stderr` to stdout, then
```
a=`python -V 2>&1`
```
works | Is it worth actually asking Python via `sys` ?
```
python -c "import sys; print sys.version_info[0:3]"
(2, 7, 3)
```
As that way one can check version values other than just checking for a version.
```
pyver=$(python -c "import sys; print sys.version_info[0:3]")
required="(2, 7, 1)"
echo pyver=$pyver
if [[ "$pyver" > "$required" ]] ; then
echo safe to proceed
else
echo require Python version ">" $required got $pyver
fi
required="(3, 0, 0)"
if [[ "$pyver" > "$required" ]] ; then
echo safe to proceed
else
echo require Python version ">" $required got $pyver
fi
#-- use integer values --
echo Integer version
# Trouble being the output looks odd but allows use of -gt
pyver=$(python -c "import sys; print '%03d%03d%03d' % sys.version_info[0:3]")
required="002007001"
echo pyver=$pyver
if [[ $pyver -gt $required ]] ; then
echo safe to proceed
else
echo require Python version $required got $pyver
fi
required="003000000"
if [[ $pyver -gt $required ]] ; then
echo safe to proceed
else
echo require Python version $required got $pyver
fi
```
Output on my system with Python version 2.7.3
```
pyver=(2, 7, 3)
safe to proceed
require Python version > (3, 0, 0) got (2, 7, 3)
Integer version
pyver=002007003
safe to proceed
require Python version 003000000 got 002007003
``` |
39,501,785 | the following does not work using python 2.7.9, but also does not throw any error or exception. is there a bug, or can multiprocessing not be used in a class?
```
from multiprocessing import Pool
def testNonClass(arg):
print "running %s" % arg
return arg
def nonClassCallback(result):
print "Got result %s" % result
class Foo:
def __init__(self):
po = Pool()
for i in xrange(1, 3):
po.apply_async(self.det, (i,), callback=self.cb)
po.close()
po.join()
print "done with class"
po = Pool()
for i in xrange(1, 3):
po.apply_async(testNonClass, (i,), callback=nonClassCallback)
po.close()
po.join()
def cb(self, r):
print "callback with %s" % r
def det(self, M):
print "method"
return M+2
if __name__ == "__main__":
Foo()
```
running prints this:
```
done with class
running 1
running 2
Got result 1
Got result 2
```
EDIT: THis seems related, but it uses `.map`, while I specifically am needing to use `apply_async` which seems to matter in terms of how multiprocessing works with class instances (e.g. I dont have a picklnig error, like many other questions related to this) - [Python how to do multiprocessing inside of a class?](https://stackoverflow.com/questions/29009790/python-how-to-do-multiprocessing-inside-of-a-class) | 2016/09/15 | [
"https://Stackoverflow.com/questions/39501785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119592/"
] | Processes don't share state or memory by default, each process is an independent program. You need to either 1) use threading 2) use [specific types capable of sharing state](https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes) or 3) design your program to avoid shared state and rely on return values instead.
Update
You have two issues in your code, and one is masking the other.
1) You don't do anything with the result of the `apply_async`, I see that you're using callbacks, but you still need to catch the results and handle them. Because you're not doing this, you're not seeing the error caused by the second problem.
2) Methods of an object cannot be passed to other processes... I was really annoyed when I first discovered this, but there is an easy workaround. Try this:
```
from multiprocessing import Pool
def _remote_det(foo, m):
return foo.det(m)
class Foo:
def __init__(self):
pass
po = Pool()
results = []
for i in xrange(1, 3):
r = po.apply_async(_remote_det, (self, i,), callback=self.cb)
results.append(r)
po.close()
for r in results:
r.wait()
if not r.successful():
# Raises an error when not successful
r.get()
po.join()
print "done with class"
def cb(self, r):
print "callback with %s" % r
def det(self, M):
print "method"
return M+2
if __name__ == "__main__":
Foo()
``` | I'm pretty sure it can be used in a class, but you need to protect the call to `Foo` inside of a clause like:
`if name == "__main__":`
so that it only gets called in the main thread. You may also have to alter the `__init__` function of the class so that it accepts a pool as an argument instead of creating a pool.
I just tried this
```
from multiprocessing import Pool
#global counter
#counter = 0
class Foo:
def __init__(self, po):
for i in xrange(1, 300):
po.apply_async(self.det, (i,), callback=self.cb)
po.close()
po.join()
print( "foo" )
#print counter
def cb(self, r):
#global counter
#print counter, r
counter += 1
def det(self, M):
return M+2
if __name__ == "__main__":
po = Pool()
Foo(po)
```
and I think I know what the problem is now. Python isn't multi-threaded; global interpreter lock prevents that. Python is using multiple processes, instead, so the sub-processes in the Pool don't have access to the standard output of the main process.
The subprocesses also are unable to modify the variable `counter` because it exists in a different process (I tried running with the `counter` lines commented out and uncommented). Now, I do recall seeing cases where global state variables get altered by processes in the pool, so I don't know all of the minutiae. I do know that it is, in general, a bad idea to have global state variables like that, if for no other reason than they can lead to race conditions and/or wasted time with locks and waiting for access to the global variable. |
72,720,129 | I am building a model for a multiclass classification problem. So I want to evaluate the model performance using the Recall and Precision.
I have 4 classes in the dataset and it is provided in `one hot` representation.
I was reading the [Precision](https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Precision) and [Recall](https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Recall) `tf.keras` documentation, and have some questions:
1. When it calculating the Precision and Recall for the multi-class classification, how can we take the average of all of the labels, meaning the global precision & Recall? is it calculated with `macro` or `micro` since it is not specified in the documentation as in the [Sikit learn](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html).
2. If I want to calculate the precision & Recall for each label separately, can I use the argument `class_id` for each label to do `one_vs_rest` or `binary` classification. Like what I have done in the code below?
3. can I use the argument `top_k` with the value `top_k=2` would be helpful here or it is not suitable for my classification of 4 classes only?
4. While I am measuring the performance of each class, What could be the difference, when I set the `top_k=1` and not setting `top_k`overall?
```
model.compile(
optimizer='sgd',
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=[tf.keras.metrics.CategoricalAccuracy(),
##class 0
tf.keras.metrics.Precision(class_id=0,top_k=2),
tf.keras.metrics.Recall(class_id=0,top_k=2),
##class 1
tf.keras.metrics.Precision(class_id=1,top_k=2),
tf.keras.metrics.Recall(class_id=1,top_k=2),
##class 2
tf.keras.metrics.Precision(class_id=2,top_k=2),
tf.keras.metrics.Recall(class_id=2,top_k=2),
##class 3
tf.keras.metrics.Precision(class_id=3,top_k=2),
tf.keras.metrics.Recall(class_id=3,top_k=2),
])
```
Any clarification of this function will be appreciated.
Thanks in advance | 2022/06/22 | [
"https://Stackoverflow.com/questions/72720129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17534198/"
] | **3. can I use the argument top\_k with the value top\_k=2 would be helpful here or it is not suitable for my classification of 4 classes only?**
According to the description, it will only calculate top\_k(with the function of \_filter\_top\_k) predictions, and turn other predictions to `False` if you use this argument
The example from official document link:<https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Precision>
You may also want to read the original code:
<https://github.com/keras-team/keras/blob/07e13740fd181fc3ddec7d9a594d8a08666645f6/keras/utils/metrics_utils.py#L487>
***With top\_k=2, it will calculate precision over y\_true[:2] and y\_pred[:2]***
```
m = tf.keras.metrics.Precision(top_k=2)
m.update_state([0, 0, 1, 1], [1, 1, 1, 1])
m.result().numpy()
0.0
```
As we can see the note posted in the example here, it will only calculate y\_true[:2] and y\_pred[:2], which means the precision will calculate only top 2 predictions (also turn the rest of y\_pred to 0).
If you want to use 4 classes classification, the argument of `class_id` maybe enough.
**4.While I am measuring the performance of each class, What could be the difference when I set the top\_k=1 and not setting top\_koverall?**
The function will calculate the precision across all the predictions your model make if you don't set `top_k` value. If you want to measure the perfromance.
Top k may works for other model, not for classification model | **1. Is it macro or micro ?**
To be precise, all the metrics are reset at the beginning of every epoch and at the beginning of every validation if there is. So I guess, we can call it macro.
**2. Class specific precision and recall ?**
You can take a look at `tf.compat.v1.metrics.precision_at_k` and `tf.compat.v1.metrics.recall_at_k`. It seems that it computes the respectivly the precision at the recall for a specific **class k**.
<https://www.tensorflow.org/api_docs/python/tf/compat/v1/metrics/precision_at_k>
<https://www.tensorflow.org/api_docs/python/tf/compat/v1/metrics/recall_at_k> |
62,509,441 | I am using python google app engine
could you tell me, how i can run python3 google app engine with ndb on local system?
Help me
<https://cloud.google.com/appengine/docs/standard/python3> | 2020/06/22 | [
"https://Stackoverflow.com/questions/62509441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879888/"
] | App Engine is a Serverless service provided by Google Cloud Platform where you can deploy your applications and configure Cloud resources like instances' CPU, memory, scaling method, etc. This will provide you the architecture to run your app.
This service is not meant to be used on local environments. Instead, it is a great option to host an application that (ideally) has been tested on local environments.
Let's say: You *don't* run a Django application with Datastore dependencies using App Engine locally, You run a Django application with Datastore (and other) dependencies locally *and then* deploy it to App Engine once it is ready.
Most GCP services have their Client libraries so we can interact with them via code, even on local environments. The `ndb` you asked belongs to the Google Cloud Datastore and can be installed in Python environments with:
```
pip install google-cloud-ndb
```
After installing it, you will be ready to interact with Datastore locally. Please find details about setting up credentials and code snippets in the [Datastore Python Client Library](https://googleapis.dev/python/python-ndb/latest/index.html) reference.
Hope this is helpful! :) | You can simply create emulator instance of the datastore on your local:
```
gcloud beta emulators datastore start --project test --host-port "0.0.0.0:8002" --no-store-on-disk --consistency=1
```
And then use it in the code in main app file:
```
from google.cloud import ndb
def get_ndb_client(namespace):
if config.ENVIRONMENT != ENVIRONMENTS.LOCAL:
# production
db = ndb.Client(namespace=namespace)
else:
# localhost
import mock
credentials = mock.Mock(spec=google.auth.credentials.Credentials)
db = ndb.Client(project="test", credentials=credentials, namespace=namespace)
return db
ndb_client = get_ndb_client("ns1")
``` |
62,509,441 | I am using python google app engine
could you tell me, how i can run python3 google app engine with ndb on local system?
Help me
<https://cloud.google.com/appengine/docs/standard/python3> | 2020/06/22 | [
"https://Stackoverflow.com/questions/62509441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879888/"
] | Please try this
Go to service account [https://cloud.google.com/docs/authentication/getting-started](http://service%20account)
create json file
and add install this pip
```
$ pip install google-cloud-ndb
```
now open linux terminal
```
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/credentials.json"
```
if window then open command prompt
```
set GOOGLE_APPLICATION_CREDENTIALS=C:\path\to\credentials.json
```
run this code in python3 in your terminal/command prompt
```
from google.cloud import ndb
client = ndb.Client()
with client.context():
contact1 = Contact(name="John Smith",
phone="555 617 8993",
email="john.smith@gmail.com")
contact1.put()
```
see this result in your datastore.. Google console | You can simply create emulator instance of the datastore on your local:
```
gcloud beta emulators datastore start --project test --host-port "0.0.0.0:8002" --no-store-on-disk --consistency=1
```
And then use it in the code in main app file:
```
from google.cloud import ndb
def get_ndb_client(namespace):
if config.ENVIRONMENT != ENVIRONMENTS.LOCAL:
# production
db = ndb.Client(namespace=namespace)
else:
# localhost
import mock
credentials = mock.Mock(spec=google.auth.credentials.Credentials)
db = ndb.Client(project="test", credentials=credentials, namespace=namespace)
return db
ndb_client = get_ndb_client("ns1")
``` |
68,856,714 | I am performing an integrity test on my Airflow DAGs using pytest, this is my current folder structure:
```
|-- dags
| |-- 01_lasic_retraining_overview.py
| |-- 02_lasic_retraining_sagemaker_autopilot.py
| |-- 03_lasic_retraining_h20_automl.py
| |-- __init__.py
| `-- common
| |-- __init__.py
| `-- helper.py
|-- docker-compose.yaml
|-- newrelic.ini
|-- plugins
|-- requirements.txt
|-- sample.env
|-- setup.sh
|-- test.sh
`-- tests
|-- common
| `-- test_helper.py
`-- dags
|-- test_02_lasic_retraining_sagemaker_autopilot.py
|-- test_03_lasic_retraining_h20_automl.py
`-- test_dag_integrity.py
```
In all my dags except `01_lasic_retraining_overview.py`(not testing), I import helper functions from `dags/common/helper.py` to them which is what is failing the test:
```
import airflow
from airflow import DAG
from airflow.exceptions import AirflowFailException
from airflow.operators.python import PythonOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
> from common.helper import _create_connection, _etl_lasic
E ModuleNotFoundError: No module named 'common'
dags/03_lasic_retraining_h20_automl.py:6: ModuleNotFoundError
=================================== short test summary info ===================================
FAILED tests/dags/test_dag_integrity.py::test_dag_integrity[/Users/yravindranath/algo_lasic2_ct_pipeline/tests/dags/../../dags/02_lasic_retraining_sagemaker_autopilot.py]
FAILED tests/dags/test_dag_integrity.py::test_dag_integrity[/Users/yravindranath/algo_lasic2_ct_pipeline/tests/dags/../../dags/03_lasic_retraining_h20_automl.py]
```
Now this code runs with no issue in my docker container. Things that I have tried and did not work:
1. adding `__init__py` to the `tests` folder.
2. running `python -m pytest tests/`
3. removing the `__init__.py` files in the dir `dags`
4. setting `PYTHONPATH=. pytest`
#### Code for integrity test is at `/tests/dags/test_dag_integrity.py`
```
import re
import glob
import importlib.util
import os
import pytest
from airflow.models import DAG
# go to the root dir and browse for any files that match the pattern
# this will find all the dag files
DAG_PATH = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"dags/**/0*.py",
)
# holds a list of all the dag files
DAG_FILES = glob.glob(
DAG_PATH,
recursive=True,
)
# filter the files to exclude the 01 dag run as that is just a plan of the
# pipeline
DAG_FILES = [file for file in DAG_FILES if not re.search("/01", file)]
@pytest.mark.parametrize("dag_file", DAG_FILES)
def test_dag_integrity(dag_file):
# Load file
module_name, _ = os.path.splitext(dag_file)
module_path = os.path.join(DAG_PATH, dag_file)
mod_spec = importlib.util.spec_from_file_location(
module_name,
module_path,
)
module = importlib.util.module_from_spec(
mod_spec, # type: ignore
)
mod_spec.loader.exec_module(module) # type: ignore
# all objects of class DAG found in file
dag_objects = [
var
for var in vars(module).values()
if isinstance(
var,
DAG,
)
]
# check if DAG objects were found in the file
assert dag_objects
# check if there are no cycles in the dags
for dag in dag_objects:
dag.test_cycle() # type: ignore
``` | 2021/08/20 | [
"https://Stackoverflow.com/questions/68856714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337635/"
] | You need to check what your `PYTHONPATH` is. You likely do not have `dags` in your `PYTHONPATH`. Likely your `PYTHONPATH` points to the root of your file structure, so the right way of importing the "common" folder of it is
```
import dags.common
```
Similarly as your common test code is
```
import tests.common
```
Python (even python 3) does not have a very good mechanism to import stuff relatively to the currently loaded file. Even if there are "relative" imports (with "." in front) - they are confusing and work differently than you think they are. Avoid using them. Simply make sure your.
Also avoid setting PYTHONPATH to ".". It makes your import work differently depending on which is your current directory. Best way is to set it once and export.
```
export PYTHONPATH="$(pwd)"
```
The above will set the `PYTHONPATH` to the directory you are currently in and it will set it to absolute path. | I am also running the application in a Docker container where the answer provided by @Jarek Potiuk didn't work when actually running the DAG, so instead I am using a super hack way by just including the import parts that work in docker and the ones that work locally.
```
try:
# Works locally with tests
from common.helper import _create_connection, _etl_lasic
except ImportError:
# Works in docker container
from dags.common.helper import _create_connection, _etl_lasic
``` |
68,856,714 | I am performing an integrity test on my Airflow DAGs using pytest, this is my current folder structure:
```
|-- dags
| |-- 01_lasic_retraining_overview.py
| |-- 02_lasic_retraining_sagemaker_autopilot.py
| |-- 03_lasic_retraining_h20_automl.py
| |-- __init__.py
| `-- common
| |-- __init__.py
| `-- helper.py
|-- docker-compose.yaml
|-- newrelic.ini
|-- plugins
|-- requirements.txt
|-- sample.env
|-- setup.sh
|-- test.sh
`-- tests
|-- common
| `-- test_helper.py
`-- dags
|-- test_02_lasic_retraining_sagemaker_autopilot.py
|-- test_03_lasic_retraining_h20_automl.py
`-- test_dag_integrity.py
```
In all my dags except `01_lasic_retraining_overview.py`(not testing), I import helper functions from `dags/common/helper.py` to them which is what is failing the test:
```
import airflow
from airflow import DAG
from airflow.exceptions import AirflowFailException
from airflow.operators.python import PythonOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
> from common.helper import _create_connection, _etl_lasic
E ModuleNotFoundError: No module named 'common'
dags/03_lasic_retraining_h20_automl.py:6: ModuleNotFoundError
=================================== short test summary info ===================================
FAILED tests/dags/test_dag_integrity.py::test_dag_integrity[/Users/yravindranath/algo_lasic2_ct_pipeline/tests/dags/../../dags/02_lasic_retraining_sagemaker_autopilot.py]
FAILED tests/dags/test_dag_integrity.py::test_dag_integrity[/Users/yravindranath/algo_lasic2_ct_pipeline/tests/dags/../../dags/03_lasic_retraining_h20_automl.py]
```
Now this code runs with no issue in my docker container. Things that I have tried and did not work:
1. adding `__init__py` to the `tests` folder.
2. running `python -m pytest tests/`
3. removing the `__init__.py` files in the dir `dags`
4. setting `PYTHONPATH=. pytest`
#### Code for integrity test is at `/tests/dags/test_dag_integrity.py`
```
import re
import glob
import importlib.util
import os
import pytest
from airflow.models import DAG
# go to the root dir and browse for any files that match the pattern
# this will find all the dag files
DAG_PATH = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"dags/**/0*.py",
)
# holds a list of all the dag files
DAG_FILES = glob.glob(
DAG_PATH,
recursive=True,
)
# filter the files to exclude the 01 dag run as that is just a plan of the
# pipeline
DAG_FILES = [file for file in DAG_FILES if not re.search("/01", file)]
@pytest.mark.parametrize("dag_file", DAG_FILES)
def test_dag_integrity(dag_file):
# Load file
module_name, _ = os.path.splitext(dag_file)
module_path = os.path.join(DAG_PATH, dag_file)
mod_spec = importlib.util.spec_from_file_location(
module_name,
module_path,
)
module = importlib.util.module_from_spec(
mod_spec, # type: ignore
)
mod_spec.loader.exec_module(module) # type: ignore
# all objects of class DAG found in file
dag_objects = [
var
for var in vars(module).values()
if isinstance(
var,
DAG,
)
]
# check if DAG objects were found in the file
assert dag_objects
# check if there are no cycles in the dags
for dag in dag_objects:
dag.test_cycle() # type: ignore
``` | 2021/08/20 | [
"https://Stackoverflow.com/questions/68856714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337635/"
] | You need to check what your `PYTHONPATH` is. You likely do not have `dags` in your `PYTHONPATH`. Likely your `PYTHONPATH` points to the root of your file structure, so the right way of importing the "common" folder of it is
```
import dags.common
```
Similarly as your common test code is
```
import tests.common
```
Python (even python 3) does not have a very good mechanism to import stuff relatively to the currently loaded file. Even if there are "relative" imports (with "." in front) - they are confusing and work differently than you think they are. Avoid using them. Simply make sure your.
Also avoid setting PYTHONPATH to ".". It makes your import work differently depending on which is your current directory. Best way is to set it once and export.
```
export PYTHONPATH="$(pwd)"
```
The above will set the `PYTHONPATH` to the directory you are currently in and it will set it to absolute path. | Throwing a crazy idea here, try adding `__init__.py` both to `*/dag` or `*/common` and to `*/tests`. |
68,856,714 | I am performing an integrity test on my Airflow DAGs using pytest, this is my current folder structure:
```
|-- dags
| |-- 01_lasic_retraining_overview.py
| |-- 02_lasic_retraining_sagemaker_autopilot.py
| |-- 03_lasic_retraining_h20_automl.py
| |-- __init__.py
| `-- common
| |-- __init__.py
| `-- helper.py
|-- docker-compose.yaml
|-- newrelic.ini
|-- plugins
|-- requirements.txt
|-- sample.env
|-- setup.sh
|-- test.sh
`-- tests
|-- common
| `-- test_helper.py
`-- dags
|-- test_02_lasic_retraining_sagemaker_autopilot.py
|-- test_03_lasic_retraining_h20_automl.py
`-- test_dag_integrity.py
```
In all my dags except `01_lasic_retraining_overview.py`(not testing), I import helper functions from `dags/common/helper.py` to them which is what is failing the test:
```
import airflow
from airflow import DAG
from airflow.exceptions import AirflowFailException
from airflow.operators.python import PythonOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
> from common.helper import _create_connection, _etl_lasic
E ModuleNotFoundError: No module named 'common'
dags/03_lasic_retraining_h20_automl.py:6: ModuleNotFoundError
=================================== short test summary info ===================================
FAILED tests/dags/test_dag_integrity.py::test_dag_integrity[/Users/yravindranath/algo_lasic2_ct_pipeline/tests/dags/../../dags/02_lasic_retraining_sagemaker_autopilot.py]
FAILED tests/dags/test_dag_integrity.py::test_dag_integrity[/Users/yravindranath/algo_lasic2_ct_pipeline/tests/dags/../../dags/03_lasic_retraining_h20_automl.py]
```
Now this code runs with no issue in my docker container. Things that I have tried and did not work:
1. adding `__init__py` to the `tests` folder.
2. running `python -m pytest tests/`
3. removing the `__init__.py` files in the dir `dags`
4. setting `PYTHONPATH=. pytest`
#### Code for integrity test is at `/tests/dags/test_dag_integrity.py`
```
import re
import glob
import importlib.util
import os
import pytest
from airflow.models import DAG
# go to the root dir and browse for any files that match the pattern
# this will find all the dag files
DAG_PATH = os.path.join(
os.path.dirname(__file__),
"..",
"..",
"dags/**/0*.py",
)
# holds a list of all the dag files
DAG_FILES = glob.glob(
DAG_PATH,
recursive=True,
)
# filter the files to exclude the 01 dag run as that is just a plan of the
# pipeline
DAG_FILES = [file for file in DAG_FILES if not re.search("/01", file)]
@pytest.mark.parametrize("dag_file", DAG_FILES)
def test_dag_integrity(dag_file):
# Load file
module_name, _ = os.path.splitext(dag_file)
module_path = os.path.join(DAG_PATH, dag_file)
mod_spec = importlib.util.spec_from_file_location(
module_name,
module_path,
)
module = importlib.util.module_from_spec(
mod_spec, # type: ignore
)
mod_spec.loader.exec_module(module) # type: ignore
# all objects of class DAG found in file
dag_objects = [
var
for var in vars(module).values()
if isinstance(
var,
DAG,
)
]
# check if DAG objects were found in the file
assert dag_objects
# check if there are no cycles in the dags
for dag in dag_objects:
dag.test_cycle() # type: ignore
``` | 2021/08/20 | [
"https://Stackoverflow.com/questions/68856714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337635/"
] | You need to check what your `PYTHONPATH` is. You likely do not have `dags` in your `PYTHONPATH`. Likely your `PYTHONPATH` points to the root of your file structure, so the right way of importing the "common" folder of it is
```
import dags.common
```
Similarly as your common test code is
```
import tests.common
```
Python (even python 3) does not have a very good mechanism to import stuff relatively to the currently loaded file. Even if there are "relative" imports (with "." in front) - they are confusing and work differently than you think they are. Avoid using them. Simply make sure your.
Also avoid setting PYTHONPATH to ".". It makes your import work differently depending on which is your current directory. Best way is to set it once and export.
```
export PYTHONPATH="$(pwd)"
```
The above will set the `PYTHONPATH` to the directory you are currently in and it will set it to absolute path. | * Make `tests/conftest.py` file
* Create this fixture inside conftest.py
##### Make sure, your path name to the module `common` is correct
```
import pytest
import sys
@pytest.fixture(scope='session)
def append_path():
sys.path.insert(0 , 'absolute_path_to_common_module' )
yield
```
* Now use this fixture as :
>
>
> ```
> @pytest.mark.usefixtures("append_path")
> @pytest.mark.parametrize("dag_file", DAG_FILES)
> def test_dag_integrity(dag_file):
> .....
>
> ```
>
>
What we are doing ?
* Making sure, the module is visible by python.
Note : You could rename your custom-module `common` to something less common and more unique. No pun intended. To avoid any conflicts. |
55,497,007 | *Just on a starting note, Please excuse the lack of c++ conventions and logic shown in this code. I'm still trying to get around formatting syntax for c++..*
With this small part of a larger application building project, I am trying to create a 'data validation' type subroutine with integers and strings being the main test cases, the input coming from the intended user.
The problem is that each character of the variable input is being iterated over, even if the 'if statements' are outside of the 'for loop' (or in some other cases while loops).
An example of the error being:
```
Enter a value:f1o2o3
Your value is a string
Your value is a integer
Your value is a string
Your value is a integer
Your value is a string
Your value is a integer
```
The extra lines after the first `Your value is a string` and
`Your value is a integer` are unwanted.
I know that I could just instead return the boolean variable `letexists` or `intexsits`, with them both being iterated without a problem.
However this 'character iterating' problem has been a nuisance in other parts too and I cannot seem to find a definite, understandable fix anywhere.
I am used to using python so this 'iterating over every character while passing parameters' is quite new to me.
I have tried looking into what it could be for multiple days now. Both: searching online and asking others (in person showing them code that has problems) about the 'iteration over each character' problem, however, none seem to know why this happens.
I have solved this problem in the past by breaking a `while(true)` loop after the intended data value has been received, however I understand this is really bad practice and therefore want to figure out how I can improve data validation.
```
#include <iostream> // for std::cin, std::cout
#include <string> // for string datatype
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
using namespace std;
// If the 'cout's are changed to returning functions I will change this to a function itself (using int datacheck(...){...})
void datacheck(string &i) {
const char nums[] = { '0','1','2','3','4','5','6','7','8','9','\0' };
const char alph[] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','\0' };
for (char& c : i) {
bool intexists = find(begin(nums), end(nums), c) != end(nums);
bool letexists = find(begin(alph), end(alph), c) != end(alph);
if (letexists || (letexists && intexists))
cout << "Your value is a string" << endl;
// This will be changed for a return value
else if (!letexists && intexists)
cout << "Your value is a integer" << endl;
// This will be changed for a return value
else
cout << "Your value has an erogenous input (Special characters or non-letter/ number related stuff.";
}
}
int main(void) {
string checkedvalue;
cout << "Enter a value: ";
cin >> checkedvalue;
cin.clear();
cin.ignore(512, '\n');
datacheck(checkedvalue);
return 0;
}
```
I have realised that it may be because each character is being sent through individually into the subroutine, however, if this is the case I am still unsure how to fix this.
Just to end off...
Overall, an explained solution for why the iterating happens and how it can be fixed will be greatly appreciated. If possible for general cases, however, just this case will be extremely helpful nonetheless.
Thank you. | 2019/04/03 | [
"https://Stackoverflow.com/questions/55497007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8519590/"
] | You can use for...of statement instead of for...in .
So your code should look like that:
```
for(var campoObrigatorio of formulario.controls){
if(campoObrigatorio.status == "INVALID"){
console.log(campoObrigatorio);
return
}
}
```
>
> The for...of statement creates a loop iterating over iterable objects,
> including: built-in String, Array, Array-like objects (e.g., arguments
> or NodeList), TypedArray, Map, Set, and user-defined iterables. It
> invokes a custom iteration hook with statements to be executed for the
> **value of each distinct property of the object**.
>
>
>
More about for..of [Here](https://developer.mozilla.org/he/docs/Web/JavaScript/Reference/Statements/for...of). | You in fact **have** the property name in your loop out of the box, it actually corresponds to `var campoObrigatorio`, so this should do what you want:
```
for(var campoObrigatorio in formulario.controls){
if (formulario.get(campoObrigatorio).status === "INVALID") { // I like to use get
console.log(campoObrigatorio) // here is the name of the form control!
return;
}
}
``` |
63,159,559 | Can some one please help me with this error. I am using Ubuntu 20.04 and jupyter notebook. (I have directly installed project jupyter from ubuntu app store. I don't have anaconda installed with it or spyder.)
I have tried following but nothing worked at
```
!pip install opencv-python
sudo apt-get install python3-opencv
apt update && apt install -y libsm6 libxext6 libxrender-dev
```
Strange thing is if write the same code in other python file and run it through terminal it's working. But I am unable to run the same code in Jupyter Notebook
```
ImportError Traceback (most recent call last)
<ipython-input-1-c8ec22b3e787> in <module>
----> 1 import cv2
/home/adarsh/snap/jupyter/common/lib/python3.7/site-packages/cv2/__init__.py in <module>
3 import sys
4
----> 5 from .cv2 import *
6 from .data import *
7
ImportError: libSM.so.6: cannot open shared object file: No such file or directory
``` | 2020/07/29 | [
"https://Stackoverflow.com/questions/63159559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13408916/"
] | Use
```
^\w+:(?:(?!.*[.!?])(.*))?
```
See [proof](https://regex101.com/r/hILSmM/1).
**EXPLANATION**
```
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
.* any character except \n (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
[.!?] any character of: '.', '!', '?'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.* any character except \n (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
)? end of grouping
``` | Does this do what you want?
```
(?:^\w+:)((?:(?![!?.]).)*)$
```
What makes you feel that this is clunky?
```
(?: ... ) non-capturing group
^ start with
\w+: a series of one or more word characters followed by a :
( ... )$ capturing group that continues to the end
(?: ... )* non-capturing group, repeated zero or more times, with
(?! ... ) negative look-ahead: no following character can be
[!?.] either ?, ! or .
. followed by any character
``` |
63,159,559 | Can some one please help me with this error. I am using Ubuntu 20.04 and jupyter notebook. (I have directly installed project jupyter from ubuntu app store. I don't have anaconda installed with it or spyder.)
I have tried following but nothing worked at
```
!pip install opencv-python
sudo apt-get install python3-opencv
apt update && apt install -y libsm6 libxext6 libxrender-dev
```
Strange thing is if write the same code in other python file and run it through terminal it's working. But I am unable to run the same code in Jupyter Notebook
```
ImportError Traceback (most recent call last)
<ipython-input-1-c8ec22b3e787> in <module>
----> 1 import cv2
/home/adarsh/snap/jupyter/common/lib/python3.7/site-packages/cv2/__init__.py in <module>
3 import sys
4
----> 5 from .cv2 import *
6 from .data import *
7
ImportError: libSM.so.6: cannot open shared object file: No such file or directory
``` | 2020/07/29 | [
"https://Stackoverflow.com/questions/63159559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13408916/"
] | Use
```
^\w+:(?:(?!.*[.!?])(.*))?
```
See [proof](https://regex101.com/r/hILSmM/1).
**EXPLANATION**
```
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
.* any character except \n (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
[.!?] any character of: '.', '!', '?'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.* any character except \n (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
)? end of grouping
``` | For the first pattern, you could first check that there is no `!` `?` or `.` present using a negative lookahead. Then capture in the first group 1+ word chars and `:` and the rest of the line in group 2.
```
^(?![^!?.\n\r]*[!?.])(\w+:)(.*)$
```
* `^` Start of string
* `(?!` Negative lookahead, assert what is on the right is not
+ `[^!?.\n\r]*[!?.]` Match 0+ times any char except the listed using [contrast](https://www.rexegg.com/regex-style.html#contrast), then match either `!` `?` `.`
* `)` Close lookahead
* `(\w+:)` Capture group 1, match 1+ word chars and a colon
* `(.*)` Capture group 2, match any char except a newline 0+ times
* `$` End of string
[Regex demo](https://regex101.com/r/wOnHIs/1)
For the second part, if you want a match only for `Choose:`, you could use the negative lookahead only without a capturing group.
```
^(?![^!?.\n\r]*[!?.])\w+:
```
[Regex demo](https://regex101.com/r/04NKe7/1) |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | You need to use `OrderedDict` :
```
>>> from collections import OrderedDict
>>> a=OrderedDict()
>>> s=sorted(d.items())
>>> for i,j in s:
... a.update({i:j})
...
>>> a
OrderedDict([((0, 0), 0.01), ((0, 1), 0.01), ((0, 2), 0.01), ((0, 3), 0.01), ((0, 4), 0.01), ((0, 5), 0.01), ((0, 6), 0.01), ((0, 7), 0.01), ((0, 8), 0.01), ((0, 9), 0.01), ((1, 0), 0.01), ((1, 1), 0.01), ((1, 2), 0.01), ((1, 3), 0.01), ((1, 4), 0.01), ((1, 5), 0.01), ((1, 6), 0.01), ((1, 7), 0.01), ((1, 8), 0.01), ((1, 9), 0.01), ((2, 0), 0.01), ((2, 1), 0.01), ((2, 2), 0.01), ((2, 3), 0.01), ((2, 4), 0.01), ((2, 5), 0.01), ((2, 6), 0.01), ((2, 7), 0.01), ((2, 8), 0.01), ((2, 9), 0.01), ((3, 0), 0.01), ((3, 1), 0.01), ((3, 2), 0.01), ((3, 3), 0.01), ((3, 4), 0.01), ((3, 5), 0.01), ((3, 6), 0.01), ((3, 7), 0.01), ((3, 8), 0.01), ((3, 9), 0.01), ((4, 0), 0.01), ((4, 1), 0.01), ((4, 2), 0.01), ((4, 3), 0.01), ((4, 4), 0.01), ((4, 5), 0.01), ((4, 6), 0.01), ((4, 7), 0.01), ((4, 8), 0.01), ((4, 9), 0.01), ((5, 0), 0.01), ((5, 1), 0.01), ((5, 2), 0.01), ((5, 3), 0.01), ((5, 4), 0.01), ((5, 5), 0.01), ((5, 6), 0.01), ((5, 7), 0.01), ((5, 8), 0.01), ((5, 9), 0.01), ((6, 0), 0.01), ((6, 1), 0.01), ((6, 2), 0.01), ((6, 3), 0.01), ((6, 4), 0.01), ((6, 5), 0.01), ((6, 6), 0.01), ((6, 7), 0.01), ((6, 8), 0.01), ((6, 9), 0.01), ((7, 0), 0.01), ((7, 1), 0.01), ((7, 2), 0.01), ((7, 3), 0.01), ((7, 4), 0.01), ((7, 5), 0.01), ((7, 6), 0.01), ((7, 7), 0.01), ((7, 8), 0.01), ((7, 9), 0.01), ((8, 0), 0.01), ((8, 1), 0.01), ((8, 2), 0.01), ((8, 3), 0.01), ((8, 4), 0.01), ((8, 5), 0.01), ((8, 6), 0.01), ((8, 7), 0.01), ((8, 8), 0.01), ((8, 9), 0.01), ((9, 0), 0.01), ((9, 1), 0.01), ((9, 2), 0.01), ((9, 3), 0.01), ((9, 4), 0.01), ((9, 5), 0.01), ((9, 6), 0.01), ((9, 7), 0.01), ((9, 8), 0.01), ((9, 9), 0.01)])
``` | I would use a OrderdDict [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) (You can see more here: [enter link description here](https://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key) Does that solve your problem, else a for-loop like you are talking about is the only other option who spring to my mind.. :-) |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | I see most everybody's recommending `OrderedDict`, but I think that's likely overkill for a mere `print` -- personally, I'd rather replace the `print p_w` with, e.g
```
for x in range(xwhale):
for y in range(ywhale):
print '(%s,%s): %s' % (x, y, p_[x,y]),
print
```
(add braces and commas to the prints if for some weird reason you want them; switch x and y if that's a more natural way to show your grid; etc, etc -- this is just the general idea!). | I would use a OrderdDict [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) (You can see more here: [enter link description here](https://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key) Does that solve your problem, else a for-loop like you are talking about is the only other option who spring to my mind.. :-) |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | ```
data = {(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
for coords in sorted(data): # sorts the keys, data order unchanged
print '{0}: {1}'.format(coords, data[coords])
``` | I would use a OrderdDict [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) (You can see more here: [enter link description here](https://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key) Does that solve your problem, else a for-loop like you are talking about is the only other option who spring to my mind.. :-) |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | You need to use `OrderedDict` :
```
>>> from collections import OrderedDict
>>> a=OrderedDict()
>>> s=sorted(d.items())
>>> for i,j in s:
... a.update({i:j})
...
>>> a
OrderedDict([((0, 0), 0.01), ((0, 1), 0.01), ((0, 2), 0.01), ((0, 3), 0.01), ((0, 4), 0.01), ((0, 5), 0.01), ((0, 6), 0.01), ((0, 7), 0.01), ((0, 8), 0.01), ((0, 9), 0.01), ((1, 0), 0.01), ((1, 1), 0.01), ((1, 2), 0.01), ((1, 3), 0.01), ((1, 4), 0.01), ((1, 5), 0.01), ((1, 6), 0.01), ((1, 7), 0.01), ((1, 8), 0.01), ((1, 9), 0.01), ((2, 0), 0.01), ((2, 1), 0.01), ((2, 2), 0.01), ((2, 3), 0.01), ((2, 4), 0.01), ((2, 5), 0.01), ((2, 6), 0.01), ((2, 7), 0.01), ((2, 8), 0.01), ((2, 9), 0.01), ((3, 0), 0.01), ((3, 1), 0.01), ((3, 2), 0.01), ((3, 3), 0.01), ((3, 4), 0.01), ((3, 5), 0.01), ((3, 6), 0.01), ((3, 7), 0.01), ((3, 8), 0.01), ((3, 9), 0.01), ((4, 0), 0.01), ((4, 1), 0.01), ((4, 2), 0.01), ((4, 3), 0.01), ((4, 4), 0.01), ((4, 5), 0.01), ((4, 6), 0.01), ((4, 7), 0.01), ((4, 8), 0.01), ((4, 9), 0.01), ((5, 0), 0.01), ((5, 1), 0.01), ((5, 2), 0.01), ((5, 3), 0.01), ((5, 4), 0.01), ((5, 5), 0.01), ((5, 6), 0.01), ((5, 7), 0.01), ((5, 8), 0.01), ((5, 9), 0.01), ((6, 0), 0.01), ((6, 1), 0.01), ((6, 2), 0.01), ((6, 3), 0.01), ((6, 4), 0.01), ((6, 5), 0.01), ((6, 6), 0.01), ((6, 7), 0.01), ((6, 8), 0.01), ((6, 9), 0.01), ((7, 0), 0.01), ((7, 1), 0.01), ((7, 2), 0.01), ((7, 3), 0.01), ((7, 4), 0.01), ((7, 5), 0.01), ((7, 6), 0.01), ((7, 7), 0.01), ((7, 8), 0.01), ((7, 9), 0.01), ((8, 0), 0.01), ((8, 1), 0.01), ((8, 2), 0.01), ((8, 3), 0.01), ((8, 4), 0.01), ((8, 5), 0.01), ((8, 6), 0.01), ((8, 7), 0.01), ((8, 8), 0.01), ((8, 9), 0.01), ((9, 0), 0.01), ((9, 1), 0.01), ((9, 2), 0.01), ((9, 3), 0.01), ((9, 4), 0.01), ((9, 5), 0.01), ((9, 6), 0.01), ((9, 7), 0.01), ((9, 8), 0.01), ((9, 9), 0.01)])
``` | Sort the existing dict by key and use `OrderedDict` to maintain order.
```
from collections import OrderedDict
xwhale = ywhale = 10
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
print p_w
op_w = OrderedDict(sorted(p_w.items(), key=lambda t: t[0]))
print '\n\n'
print op_w
``` |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | I see most everybody's recommending `OrderedDict`, but I think that's likely overkill for a mere `print` -- personally, I'd rather replace the `print p_w` with, e.g
```
for x in range(xwhale):
for y in range(ywhale):
print '(%s,%s): %s' % (x, y, p_[x,y]),
print
```
(add braces and commas to the prints if for some weird reason you want them; switch x and y if that's a more natural way to show your grid; etc, etc -- this is just the general idea!). | You need to use `OrderedDict` :
```
>>> from collections import OrderedDict
>>> a=OrderedDict()
>>> s=sorted(d.items())
>>> for i,j in s:
... a.update({i:j})
...
>>> a
OrderedDict([((0, 0), 0.01), ((0, 1), 0.01), ((0, 2), 0.01), ((0, 3), 0.01), ((0, 4), 0.01), ((0, 5), 0.01), ((0, 6), 0.01), ((0, 7), 0.01), ((0, 8), 0.01), ((0, 9), 0.01), ((1, 0), 0.01), ((1, 1), 0.01), ((1, 2), 0.01), ((1, 3), 0.01), ((1, 4), 0.01), ((1, 5), 0.01), ((1, 6), 0.01), ((1, 7), 0.01), ((1, 8), 0.01), ((1, 9), 0.01), ((2, 0), 0.01), ((2, 1), 0.01), ((2, 2), 0.01), ((2, 3), 0.01), ((2, 4), 0.01), ((2, 5), 0.01), ((2, 6), 0.01), ((2, 7), 0.01), ((2, 8), 0.01), ((2, 9), 0.01), ((3, 0), 0.01), ((3, 1), 0.01), ((3, 2), 0.01), ((3, 3), 0.01), ((3, 4), 0.01), ((3, 5), 0.01), ((3, 6), 0.01), ((3, 7), 0.01), ((3, 8), 0.01), ((3, 9), 0.01), ((4, 0), 0.01), ((4, 1), 0.01), ((4, 2), 0.01), ((4, 3), 0.01), ((4, 4), 0.01), ((4, 5), 0.01), ((4, 6), 0.01), ((4, 7), 0.01), ((4, 8), 0.01), ((4, 9), 0.01), ((5, 0), 0.01), ((5, 1), 0.01), ((5, 2), 0.01), ((5, 3), 0.01), ((5, 4), 0.01), ((5, 5), 0.01), ((5, 6), 0.01), ((5, 7), 0.01), ((5, 8), 0.01), ((5, 9), 0.01), ((6, 0), 0.01), ((6, 1), 0.01), ((6, 2), 0.01), ((6, 3), 0.01), ((6, 4), 0.01), ((6, 5), 0.01), ((6, 6), 0.01), ((6, 7), 0.01), ((6, 8), 0.01), ((6, 9), 0.01), ((7, 0), 0.01), ((7, 1), 0.01), ((7, 2), 0.01), ((7, 3), 0.01), ((7, 4), 0.01), ((7, 5), 0.01), ((7, 6), 0.01), ((7, 7), 0.01), ((7, 8), 0.01), ((7, 9), 0.01), ((8, 0), 0.01), ((8, 1), 0.01), ((8, 2), 0.01), ((8, 3), 0.01), ((8, 4), 0.01), ((8, 5), 0.01), ((8, 6), 0.01), ((8, 7), 0.01), ((8, 8), 0.01), ((8, 9), 0.01), ((9, 0), 0.01), ((9, 1), 0.01), ((9, 2), 0.01), ((9, 3), 0.01), ((9, 4), 0.01), ((9, 5), 0.01), ((9, 6), 0.01), ((9, 7), 0.01), ((9, 8), 0.01), ((9, 9), 0.01)])
``` |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | I see most everybody's recommending `OrderedDict`, but I think that's likely overkill for a mere `print` -- personally, I'd rather replace the `print p_w` with, e.g
```
for x in range(xwhale):
for y in range(ywhale):
print '(%s,%s): %s' % (x, y, p_[x,y]),
print
```
(add braces and commas to the prints if for some weird reason you want them; switch x and y if that's a more natural way to show your grid; etc, etc -- this is just the general idea!). | Sort the existing dict by key and use `OrderedDict` to maintain order.
```
from collections import OrderedDict
xwhale = ywhale = 10
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
print p_w
op_w = OrderedDict(sorted(p_w.items(), key=lambda t: t[0]))
print '\n\n'
print op_w
``` |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | ```
data = {(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
for coords in sorted(data): # sorts the keys, data order unchanged
print '{0}: {1}'.format(coords, data[coords])
``` | Sort the existing dict by key and use `OrderedDict` to maintain order.
```
from collections import OrderedDict
xwhale = ywhale = 10
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
print p_w
op_w = OrderedDict(sorted(p_w.items(), key=lambda t: t[0]))
print '\n\n'
print op_w
``` |
27,594,375 | i have a 10x10 grid. this grid is in a dictionary called p\_w. when i print out p\_w i get this:
```
{(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
```
i am trying to get it so that its print out in order of coordinates. for example
```
{(0,0):0.01, (0.1):0.01, (0,2):0.01... etc
```
how do i order the tuples in the dictionary i curreny have:
```
p_w = {}
for x in range(xwhale):
for y in range(ywhale):
p_w[x,y] = 0.01
self.p_w = p_w
print p_w
```
PS. im still quite new to python | 2014/12/21 | [
"https://Stackoverflow.com/questions/27594375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837282/"
] | I see most everybody's recommending `OrderedDict`, but I think that's likely overkill for a mere `print` -- personally, I'd rather replace the `print p_w` with, e.g
```
for x in range(xwhale):
for y in range(ywhale):
print '(%s,%s): %s' % (x, y, p_[x,y]),
print
```
(add braces and commas to the prints if for some weird reason you want them; switch x and y if that's a more natural way to show your grid; etc, etc -- this is just the general idea!). | ```
data = {(7, 3): 0.01, (6, 9): 0.01, (0, 7): 0.01, (1, 6): 0.01, (3, 7): 0.01, (2, 5): 0.01, (8, 5): 0.01, (5, 8): 0.01, (4, 0): 0.01, (9, 0): 0.01,
(6, 7): 0.01, (5, 5): 0.01, (7, 6): 0.01, (0, 4): 0.01, (1, 1): 0.01, (3, 2): 0.01, (2, 6): 0.01, (8, 2): 0.01, (4, 5): 0.01, (9, 3): 0.01,
(6, 0): 0.01, (7, 5): 0.01, (0, 1): 0.01, (3, 1): 0.01, (9, 9): 0.01, (7, 8): 0.01, (2, 1): 0.01, (8, 9): 0.01, (9, 4): 0.01, (5, 1): 0.01,
(7, 2): 0.01, (1, 5): 0.01, (3, 6): 0.01, (2, 2): 0.01, (8, 6): 0.01, (4, 1): 0.01, (9, 7): 0.01, (6, 4): 0.01, (5, 4): 0.01, (7, 1): 0.01,
(0, 5): 0.01, (1, 0): 0.01, (0, 8): 0.01, (3, 5): 0.01, (2, 7): 0.01, (8, 3): 0.01, (4, 6): 0.01, (9, 2): 0.01, (6, 1): 0.01, (5, 7): 0.01,
(7, 4): 0.01, (0, 2): 0.01, (1, 3): 0.01, (4, 8): 0.01, (3, 0): 0.01, (2, 8): 0.01, (9, 8): 0.01, (8, 0): 0.01, (6, 2): 0.01, (5, 0): 0.01,
(1, 4): 0.01, (3, 9): 0.01, (2, 3): 0.01, (1, 9): 0.01, (8, 7): 0.01, (4, 2): 0.01, (9, 6): 0.01, (6, 5): 0.01, (5, 3): 0.01, (7, 0): 0.01,
(6, 8): 0.01, (0, 6): 0.01, (1, 7): 0.01, (0, 9): 0.01, (3, 4): 0.01, (2, 4): 0.01, (8, 4): 0.01, (5, 9): 0.01, (4, 7): 0.01, (9, 1): 0.01,
(6, 6): 0.01, (5, 6): 0.01, (7, 7): 0.01, (0, 3): 0.01, (1, 2): 0.01, (4, 9): 0.01, (3, 3): 0.01, (2, 9): 0.01, (8, 1): 0.01, (4, 4): 0.01,
(6, 3): 0.01, (0, 0): 0.01, (7, 9): 0.01, (3, 8): 0.01, (2, 0): 0.01, (1, 8): 0.01, (8, 8): 0.01, (4, 3): 0.01, (9, 5): 0.01, (5, 2): 0.01}
for coords in sorted(data): # sorts the keys, data order unchanged
print '{0}: {1}'.format(coords, data[coords])
``` |
56,537,035 | I am trying to create x,y,z coordinates to generate an elevation dataset.
I was able to create x,y,z arrays with meshgrid- where z is a constant value.
(This is a follow on from my previous question and I am new to python)
I also want to create sloping terrain, where z is dependent on x.
I was able to create an array with the correct z values. However when trying to combine the three arrays (x,y,z) into coordinates using the zip tool, I got this error:
```
TypeError Traceback (most recent call last)
<ipython-input-81-6454cf2caa60> in <module>
3 for a, b, c in zip(x_mesh, y_mesh, z_int):
4 for a1, b1, c1 in zip(a, b, c):
----> 5 for a2, b2, c2 in zip(a1, b1, c1):
6 coords.append((a2, b2, c2,))
TypeError: zip argument #1 must support iteration
```
The code below is for a small area as a test for creating a slope over a much larger area.
I thought it may have been initially because my z array was in float and not int, so I converted it, but it made no difference.
My code with z as a constant incorporated z into meshgrid and the coords[] code worked well in that instance.
```
sp=(10)
x=np.arange(313000, 333000, sp)
y=np.arange(6220000,6227000, sp)
z=15
x_mesh, y_mesh, z_mesh=np.meshgrid(x,y,z)
coords = []
for a, b, c in zip(x_mesh, y_mesh, z_mesh):
for a1, b1, c1 in zip(a, b, c):
for a2, b2, c2 in zip(a1, b1, c1):
coords.append((a2, b2, c2,))
```
However when I tried to make z dependent on x and not include it in the meshgrid process, the 'coords=[]' part returned the error:
TypeError: zip argument #1 must support iteration
```
import numpy as np
sp=10
svx=313000
evx=313040
x=np.arange(svx,evx,sp)
y=np.arange(6220000,6220040,sp)
x_mesh, y_mesh =np.meshgrid(x,y)
evz=-30
totalnosteps=((evx-svx)/sp)-1
nosteps=((x_mesh-svx)/sp)
dedep=(evz/totalnosteps)
z=nosteps*dedep
z_int=z.astype(int)
coords = []
for a, b, c in zip(x_mesh, y_mesh, z_int):
for a1, b1, c1 in zip(a, b, c):
for a2, b2, c2 in zip(a1, b1, c1):
coords.append((a2, b2, c2,))
```
I'm after an end result with (x,y,z) | 2019/06/11 | [
"https://Stackoverflow.com/questions/56537035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612535/"
] | Here is what you would need to change on the current code:
```
Option Explicit
Sub MergeExcelFiles()
Dim fso As New FileSystemObject
Dim f As Folder, sf As Folder
Dim ofile As File
Dim MyPath As String, MyFile As String, File As Workbook
Dim fnameList, fnameCurFile As Variant
Dim countFiles As Long, countSheets As Long
Dim wksCurSheet As Worksheet
Dim wbkCurBook As Workbook, wbkSrcBook As Workbook
Dim RootFolderName As String
RootFolderName = Application.FileDialog(msoFileDialogFolderPicker).AllowMultiSelect = False
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.ButtonName = "Select Root Folder"
If .Show <> -1 Then Exit Sub ' if OK is pressed
RootFolderName = .SelectedItems(1)
End With
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
End With
countFiles = 0
countSheets = 0
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(RootFolderName)
For Each sf In f.SubFolders
Set wbkCurBook = Workbooks.Add 'this comes here so we add a new workbook in every folder
For Each ofile In sf.Files
If fso.GetExtensionName(ofile.Path) Like "xls*" Then
countFiles = countFiles + 1
fnameCurFile = ofile.Path
Debug.Print fnameCurFile
Set wbkSrcBook = Workbooks.Open(Filename:=fnameCurFile)
For Each wksCurSheet In wbkSrcBook.Sheets
countSheets = countSheets + 1
wksCurSheet.Copy after:=wbkCurBook.Sheets(wbkCurBook.Sheets.Count)
Next
wbkSrcBook.Close SaveChanges:=False
Kill wbkSrcBook.FullName 'this will delete the workbook that was being copied
End If
Next
wbkCurBook.SaveAs sf.Name & "\" & "here the name of the workbook" 'this will save the file on the current folder.
Set wbkCurBook = Nothing 'reset the varaible
Next
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
MsgBox "Processed " & countFiles & " files" & vbCrLf & "Merged " & countSheets & " worksheets", Title:="Merge Excel files"
End Sub
``` | May try something like (modify it to your requirement). Some declarations are not used (left out due to quick copy paste) may be deleted.
```
Option Explicit
Sub MergeExcelFiles()
Dim fso As New FileSystemObject
Dim f As Folder, sf As Folder
Dim ofile As File
Dim MyPath As String, MyFile As String, File As Workbook
Dim fnameList, fnameCurFile As Variant
Dim countFiles As Long, countSheets As Long
Dim wksCurSheet As Worksheet
Dim wbkCurBook As Workbook, wbkSrcBook As Workbook
Dim RootFolderName As String
RootFolderName = Application.FileDialog(msoFileDialogFolderPicker).AllowMultiSelect = False
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.ButtonName = "Select Root Folder"
If .Show <> -1 Then Exit Sub ' if OK is pressed
RootFolderName = .SelectedItems(1)
End With
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
End With
countFiles = 0
countSheets = 0
Set wbkCurBook = ActiveWorkbook
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(RootFolderName)
For Each sf In f.SubFolders
For Each ofile In sf.Files
If fso.GetExtensionName(ofile.Path) Like "xls*" Then
countFiles = countFiles + 1
fnameCurFile = ofile.Path
Debug.Print fnameCurFile
Set wbkSrcBook = Workbooks.Open(Filename:=fnameCurFile)
For Each wksCurSheet In wbkSrcBook.Sheets
countSheets = countSheets + 1
wksCurSheet.Copy after:=wbkCurBook.Sheets(wbkCurBook.Sheets.Count)
Next
wbkSrcBook.Close SaveChanges:=False
End If
Next
Next
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
MsgBox "Processed " & countFiles & " files" & vbCrLf & "Merged " & countSheets & " worksheets", Title:="Merge Excel files"
End Sub
``` |
47,965,021 | I keep getting this error
`OpenCV Error: Assertion failed (_img.rows * _img.cols == vecSize) in get, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/apps/traincascade/imagestorage.cpp, line 157
terminate called after throwing an instance of 'cv::Exception'
what(): /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/apps/traincascade/imagestorage.cpp:157: error: (-215) _img.rows * _img.cols == vecSize in function get
Aborted (core dumped)`
when running `opencv_traincascade`. I run with these arguments: `opencv_traincascade -data data -vec positives.vec -bg bg.txt -numPos 1600 -numNeg 800 -numStages 10 -w 20 -h 20`.
---
My project build is as follows: `workspace
|__bg.txt
|__data/ # where I plan to put cascade
|__info/
|__ # all samples
|__info.lst
|__jersey5050.jpg
|__neg/
|__ # neg images
|__opencv/
|__positives.vec`
---
before I ran `opencv_createsamples -img jersey5050.jpg -bg bg.txt -info info/info.lst -maxxangle 0.5 - maxyangle 0.5 -maxzangle 0.5 -num 1800`
---
Not quite sure why I'm getting this error. The images are all converted to greyscale as well. The neg's are sized at 100x100 and `jersey5050.jpg` is sized at 50x50. I saw someone had a the same error on the OpenCV forums and someone suggested deleting the backup .xml files that are created b OpenCV in case the training is "interrupted". I deleted those and nothing. Please help! I'm using python 3 on mac. I'm also running these commands on an ubuntu server from digitalocean with 2GB of ram but I don't think that's part of the problem.
**EDIT**
Forgot to mention, after the `opencv_createsamples` command, i then ran `opencv_createsamples -info info/info.lst -num 1800 -w 20 -h20 -vec positives.vec` | 2017/12/25 | [
"https://Stackoverflow.com/questions/47965021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8485058/"
] | I solved it haha. Even though I specified in the command the width and height to be 20x20, it changed it to 20x24. So the `opencv_traincascade` command was throwing an error. Once I changed the width and height arguments in the `opencv_traincascade` command it worked. | This error is observed when the parameters passed is not matching with the vec file generated, as rightly put by the terminal in this line
>
> Assertion failed (\_img.rows \* \_img.cols == vecSize)
>
>
>
opencv\_createsamples displays the parameters passed to it for training. Please verify of the parameters used for creating samples are the same that you passed. I have attached the terminal log for reference.
```
mayank@mayank-Aspire-A515-51G:~/programs/opencv/CSS/homework/HAAR_classifier/dataset$ opencv_createsamples -info pos.txt -num 235 -w 40 -h 40 -vec positives_test.vec
Info file name: pos.txt
Img file name: (NULL)
Vec file name: positives_test.vec
BG file name: (NULL)
Num: 235
BG color: 0
BG threshold: 80
Invert: FALSE
Max intensity deviation: 40
Max x angle: 1.1
Max y angle: 1.1
Max z angle: 0.5
Show samples: FALSE
Width: 40 <--- confirm
Height: 40 <--- confirm
Max Scale: -1
RNG Seed: 12345
Create training samples from images collection...
Done. Created 235 samples
``` |
62,420,282 | I am trying to write a simple bot that just logs into my Instagram for me and I have run into an issue installing Selenium for Chrome.
I have run pip install Selenuim from the command line and it appears in the Python directory. I have then downloaded the chromedriver file from online and added it to my path. I then made a new script in my documents and wrote the following python:
```
from selenuim import webdriver
driver = webdriver.Chrome()
driver.get("http://www.python.org")
driver.close()
```
When I ran the program it gives the following error.
Traceback (most recent call last):
File "C:\Users\user\Documents\Bot\Bot.py", line 2, in
from selenuim import webdriver
ModuleNotFoundError: No module named 'selenuim'
How to I get an installed module to import properly in python.
Thank you for helping.
EDIT: PLEASE DO NOT ANSWER THIS QUESTION I CANNOT SPELL | 2020/06/17 | [
"https://Stackoverflow.com/questions/62420282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13759278/"
] | You imported `selenuim`, It has a spelling mistake.
`selenium` | You imported selenuim, It has a spelling mistake.
selenium
go your scripts path and install it in cmd.
C:\Users\vignesh.rajendran\AppData\Local\Programs\Python\Python35-32\Scripts> pip install selenium
Check chrome.exe is present in the below path after installing selenium
C:\Users\vignesh.rajendran\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\webbot\drivers |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | The answer is on the same page in footnote (2):
>
> The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons.
>
>
>
The "historical reasons" are described in <https://bugs.python.org/issue2568>. | Probably to account for [leap seconds](http://en.wikipedia.org/wiki/Leap_second). |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | The answer is on the same page in footnote (2):
>
> The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons.
>
>
>
The "historical reasons" are described in <https://bugs.python.org/issue2568>. | When you have to add leap second it will be helpful to calculate that. You can search on net for leap second. Due to that second range in python is `0-61`. |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | The answer is on the same page in footnote (2):
>
> The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons.
>
>
>
The "historical reasons" are described in <https://bugs.python.org/issue2568>. | Leap seconds.
It has been the case that there have been 62 seconds in a minute in the past.
It adjusts for the world spinning slower.
Part of this is down to tides. The energy for the tides comes from the rotation of the earth and moon. The result is that the world slows down.
If global warming takes place the oceans get hotter and expand. That is like a skater throwing their arms out, and the spin slows down. That hasn't taken place. The measurement of ocean levels doesn't agree with the rotation measurements. It's likely to be down to problems with the earth's surface moving, which is far larger than the sea level rise. |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | The answer is on the same page in footnote (2):
>
> The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons.
>
>
>
The "historical reasons" are described in <https://bugs.python.org/issue2568>. | There is no such thing as a double leap second. There cannot be 62 seconds in a minute. 59, yes. 60, yes. 61, yes. 62, no.
<http://www.monkey.org/openbsd/archive2/tech/199905/msg00031.html> |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | Probably to account for [leap seconds](http://en.wikipedia.org/wiki/Leap_second). | When you have to add leap second it will be helpful to calculate that. You can search on net for leap second. Due to that second range in python is `0-61`. |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | Probably to account for [leap seconds](http://en.wikipedia.org/wiki/Leap_second). | Leap seconds.
It has been the case that there have been 62 seconds in a minute in the past.
It adjusts for the world spinning slower.
Part of this is down to tides. The energy for the tides comes from the rotation of the earth and moon. The result is that the world slows down.
If global warming takes place the oceans get hotter and expand. That is like a skater throwing their arms out, and the spin slows down. That hasn't taken place. The measurement of ocean levels doesn't agree with the rotation measurements. It's likely to be down to problems with the earth's surface moving, which is far larger than the sea level rise. |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | When you have to add leap second it will be helpful to calculate that. You can search on net for leap second. Due to that second range in python is `0-61`. | Leap seconds.
It has been the case that there have been 62 seconds in a minute in the past.
It adjusts for the world spinning slower.
Part of this is down to tides. The energy for the tides comes from the rotation of the earth and moon. The result is that the world slows down.
If global warming takes place the oceans get hotter and expand. That is like a skater throwing their arms out, and the spin slows down. That hasn't taken place. The measurement of ocean levels doesn't agree with the rotation measurements. It's likely to be down to problems with the earth's surface moving, which is far larger than the sea level rise. |
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | There is no such thing as a double leap second. There cannot be 62 seconds in a minute. 59, yes. 60, yes. 61, yes. 62, no.
<http://www.monkey.org/openbsd/archive2/tech/199905/msg00031.html> | When you have to add leap second it will be helpful to calculate that. You can search on net for leap second. Due to that second range in python is `0-61`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.