qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
1,183,420 | I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either python, Ruby on Rails or PHP, which would you go with and why? The service basically just takes a request and talks to a MySql database.
Note: Was planning on using the SOAP protocol.. though I am open to suggestions since I have a clean slate with these languages. | 2009/07/26 | [
"https://Stackoverflow.com/questions/1183420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/77393/"
] | **The short answer is, I'd go with PHP.**
I have some experience in all two of your three choices: PHP, Ruby with Ruby on Rails. If I had no experience however and I was looking to set out and create a web service that largely just interacts with a database and I wanted it done this weekend, I'd choose PHP. If I had no experience with any of the above languages and I wanted to project done in a couple of weeks, I'd choose rails. I personally have much less experience with with Python and Django so I can't really comment.
*Ruby with Ruby on Rails:* I've been working with Ruby and ruby on rails for several years now. I previously had experience in Java (which is roughly analogous to your experience in .Net). I found the transition to rails to be a little bit bumpy. I wanted to jump right in and start understanding how rails works and how to build a web application but with no understanding of ruby this was difficult. There are a lot of example out there that will help you build an application quickly but often times the quickness comes at the expense of understanding. To build solid rails web application you need a good understanding of ruby and of the rails frameworks. Rails is fantastic, but for building something you understand and getting it up and running quickly it may not be your best choice. Also, rails hosting has come a long way (you can tell because we're starting to see many hosts offer it) but there are still some bumps.
*PHP*: PHP is fantastic for getting something up and running quickly. You can upload files and immediately see if your result if working. If you keep your database setup clean (and it sounds like you will, because you work with databases all day) the PHP shouldn't be too bad. I would look into an Object Relational Mapper to help keep your PHP even cleaner, I've heard good thinks about [Doctorine](http://www.doctrine-project.org/).
*Python*: I would imagine that you'd probably use Django with Python. Because of this you're probably going to come up against the same stumbling blocks that you would with ruby + ruby on rails.
If you'd like to start to learn Ruby on Rails, I'd recommend checking out [this thread](https://stackoverflow.com/questions/55574/learning-ruby-on-rails) on stackoverflow.
Finally, if you'd like to work with a PHP framework, there's a great thread on that [here on stackoverflow](https://stackoverflow.com/questions/58424/a-lightweight-application-framework-for-php). | The first programming I ever did was with PHP, and it's definitely very easy to get going with PHP on Dreamhost (I use Dreamhost for my PHP-based blog as well as Ruby on Rails project hosting). Ruby on Rails is pretty easy to get going on Dreamhost as well, now that they've started using [Passenger](http://www.modrails.com/). I learned Ruby and Ruby on Rails several years after I became comfortable in PHP and I prefer it to PHP because it feels much cleaner and I love the Model View Controller pattern for separation of code and content. I tried to learn Django after that but found myself frustrated because the meaning of "view" was different in Django than in Rails/MVC, so I didn't get very far.
If you are doing quick-and-dirty, you might go with PHP. You could look into various frameworks for PHP, such as CakePHP or Symfony, for cleaner, more organized development. If you're willing to spend more time learning (first for the language Ruby, then for the framework Ruby on Rails), you could go with Ruby on Rails. I really enjoy Rails development, but there was a learning curve since I learned both Ruby and Rails at the same time. There's a lot of [information](http://rails.dreamhosters.com/) out there about deploying Rails apps on Dreamhost. |
49,496,096 | I'm learning python and I'm not sure why the output of the below code is only "False" and not many "false" if I created a loop and the list of dict have 5 elements.
I was expect an ouput like
"False"
"False"
"False"
"False"
```
"False"
movies = [{
"name": "Usual Suspects"
}, {
"name": "Hitman",
}, {
"name": "Dark Knight",
},{
"name": "The Choice",
}, {
"name": "Colonia",}
]
def peliMayor(p):
index= -1
for n in movies:
index= index + 1
if (movies[index]['name'] == p):
return print("True")
else:
return print("False")
peli = "Thriller"
peliMayor(peli)
``` | 2018/03/26 | [
"https://Stackoverflow.com/questions/49496096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5544653/"
] | Try using the Remote VSCode plugin as explained here: [Using Remote VSCode](https://spin.atomicobject.com/2017/12/18/remote-vscode-file-editing/)
This discussion is exactly about your problem: [VSCode 13643 issue Github](https://github.com/Microsoft/vscode/issues/13643)
EDIT: I have recently found a new VSCode plugin on Github: [vs-deploy](https://github.com/mkloubert/vs-deploy). It was designed to deploy files and folders remotely very quickly. It seems to be working and I haven't found any bugs so far. It works with FTP, SFTP (SSH) and many other protocols. | The [SSH.NET nuget Package](https://www.nuget.org/packages/SSH.NET) can be used quite nicly to copy files and folders.
Here is an example:
```
var host = "YourServerIpAddress";
var port = 22;
var user = "root"; // TODO: fix
var yourPathToAPrivateKeyFile = @"C:\Users\Bob\mykey"; // Use certificate for login
var authMethod = new PrivateKeyAuthenticationMethod(user, new PrivateKeyFile(yourPathToAPrivateKeyFile));
var connectionInfo = new ConnectionInfo(host, port, user, authMethod);
using (var client = new SftpClient(connectionInfo))
{
client.Connect();
if (client.IsConnected)
{
//TODO: Copy folders recursivly etc.
DirectoryInfo source = new DirectoryInfo(@"C:\your\probject\publish\path");
foreach (var file in source.GetFiles())
{
client.UploadFile(File.OpenRead(file.FullName), $"/home/yourUploadPath/{file.Name}", true);
}
}
}
```
When you create a upload console application using the code above your should be able to automatically trigger an upload by using postbuild events by adding a section to your Project.
```
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="path to execute your script or application" />
</Target>
```
If you prefer to do the same but more manual you can perform a
```
dotnet build --configuration Release
```
followed by a
```
dotnet publish ~/projects/app1/app1.csproj
```
and then use the code above to perform an upload. |
49,496,096 | I'm learning python and I'm not sure why the output of the below code is only "False" and not many "false" if I created a loop and the list of dict have 5 elements.
I was expect an ouput like
"False"
"False"
"False"
"False"
```
"False"
movies = [{
"name": "Usual Suspects"
}, {
"name": "Hitman",
}, {
"name": "Dark Knight",
},{
"name": "The Choice",
}, {
"name": "Colonia",}
]
def peliMayor(p):
index= -1
for n in movies:
index= index + 1
if (movies[index]['name'] == p):
return print("True")
else:
return print("False")
peli = "Thriller"
peliMayor(peli)
``` | 2018/03/26 | [
"https://Stackoverflow.com/questions/49496096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5544653/"
] | Try using the Remote VSCode plugin as explained here: [Using Remote VSCode](https://spin.atomicobject.com/2017/12/18/remote-vscode-file-editing/)
This discussion is exactly about your problem: [VSCode 13643 issue Github](https://github.com/Microsoft/vscode/issues/13643)
EDIT: I have recently found a new VSCode plugin on Github: [vs-deploy](https://github.com/mkloubert/vs-deploy). It was designed to deploy files and folders remotely very quickly. It seems to be working and I haven't found any bugs so far. It works with FTP, SFTP (SSH) and many other protocols. | Search for the extension SSHExtension developed by Vitaly Kondratiev
Install the extension.
And edit the serverlist json with the server details.
ex:
"sshextension.serverList": [
{
"name": "Kuberntes 212",
"host": "10.64.234.54",
"port": 22,
"username": "root",
"password": "byebye"
}
]
save the file
Then log in using ctrl+shift+p and choose sshextension open ssh extension category. It shall create a session for you.
More Easily if u need the entire directory structure into ur local workspace.
Use extension ftp-simple in vscode. It works as a wonder, trust me.
Install ftp-simple in vscode
ctrl+shift+p
select ftp-simple:config.
Configure your settings
[
{
"name": "Kubernetes 212",
"host": "10.75.64.2",
"port": 22,
"type": "sftp",
"username": "root",
"password": "byebye",
"path": "/home/vinod/",
"autosave": true,
"confirm": true
}]
save the file.
Now ctrl+shift+p
and select ftp-simple:remote directory to workspace.
Viola Your work is done, Life is simple |
637,399 | I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.
This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.
I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <http://www.secdev.org/projects/scapy/index.html> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause. | 2009/03/12 | [
"https://Stackoverflow.com/questions/637399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] | Just make sure Avahi / Bonjour's running, then type *hostname*.local (or also try *hostname*.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts. | You could also use **arp-scan** (a Debian package of the name exists, not sure about other distributions) to scan your whole network. Have a script parse its output and you'll be all set. |
637,399 | I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.
This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.
I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <http://www.secdev.org/projects/scapy/index.html> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause. | 2009/03/12 | [
"https://Stackoverflow.com/questions/637399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] | Cleanest solution would be to have a DHCP server that exchanges its assignments with a local DNS server. So regardless which IP address your workstation is being assigned to, it is accessible under the same hostname.
This concept is used in every full-blown windows network as well as in any other well configured network. | Just make sure Avahi / Bonjour's running, then type *hostname*.local (or also try *hostname*.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts. |
637,399 | I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.
This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.
I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <http://www.secdev.org/projects/scapy/index.html> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause. | 2009/03/12 | [
"https://Stackoverflow.com/questions/637399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] | Sorry, it looks like an attempt to create a problem where no problem exists, and subsequently solve it using a bit crazy methods. :)
You can configure your dhcp server (router) to always issue a fixed ip for your workstation. If you don't have dhcp server, then why do you use dhcp for configuring the interface? Change the configuration (`/etc/network/interfaces` in Ubuntu and Debian) to assign static ip address to the interface. | You could also use **arp-scan** (a Debian package of the name exists, not sure about other distributions) to scan your whole network. Have a script parse its output and you'll be all set. |
637,399 | I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.
This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.
I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <http://www.secdev.org/projects/scapy/index.html> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause. | 2009/03/12 | [
"https://Stackoverflow.com/questions/637399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] | Cleanest solution would be to have a DHCP server that exchanges its assignments with a local DNS server. So regardless which IP address your workstation is being assigned to, it is accessible under the same hostname.
This concept is used in every full-blown windows network as well as in any other well configured network. | You could also use **arp-scan** (a Debian package of the name exists, not sure about other distributions) to scan your whole network. Have a script parse its output and you'll be all set. |
637,399 | I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.
So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.
This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.
I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <http://www.secdev.org/projects/scapy/index.html> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause. | 2009/03/12 | [
"https://Stackoverflow.com/questions/637399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9908/"
] | Cleanest solution would be to have a DHCP server that exchanges its assignments with a local DNS server. So regardless which IP address your workstation is being assigned to, it is accessible under the same hostname.
This concept is used in every full-blown windows network as well as in any other well configured network. | Sorry, it looks like an attempt to create a problem where no problem exists, and subsequently solve it using a bit crazy methods. :)
You can configure your dhcp server (router) to always issue a fixed ip for your workstation. If you don't have dhcp server, then why do you use dhcp for configuring the interface? Change the configuration (`/etc/network/interfaces` in Ubuntu and Debian) to assign static ip address to the interface. |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | You have two separate questions with two separate pythonic ways of answering those questions.
1- Your first concern was that you don't want to keep adding new lines the more arguments you start supporting when formatting a string. The way to work around that is using a `defaultdict` so you're able to return an empty string when you don't provide a specific keyword argument and `str.format_map` that accepts a dict as a way to input keyword arguments to format. This way, you only have to update your string and what keyword arguments you want to print:
```
from collections import defaultdict
def call_me_by_name(**kwargs):
default_kwargs = defaultdict(str, kwargs)
print("Your name is {first_name} {second_name} {third_name}".format_map(default_kwargs))
```
2- If, on the other hand and answering your second question, you want to provide different behavior depending on the keyword arguments, like changing the way a string looks or providing different file lookup functionalities, without using if statements, you have to add different functions/methods and call them from this common function/method. Here are two ways of doing that:
OOP:
```
class FileLookup:
def parse(self, **kwargs):
return getattr(self, next(iter(kwargs)))(**kwargs)
def line_number(self, line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(self, byte_position):
print('parsing with a byte position: {}'.format(byte_position))
fl = FileLookup()
fl.parse(byte_position=10)
fl.parse(line_number=10)
```
Module:
```
def line_number(line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(byte_position):
print('parsing with a byte position: {}'.format(byte_position))
def parse(**kwargs):
return globals()[next(iter(kwargs))](**kwargs)
parse(byte_position=29)
parse(line_number=29)
``` | You can simplify it by:
```
middle_name = kwargs.get('middle_name', '')
``` |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | Seem to me your better off not using kwargs and not even a function, you can simply do something like this:
```
print("Your name is", " ".join([first_name, middle_name, last_name]))
```
Or if you do want a function:
```
def call_me_by_name(*args):
print("Your name is", " ".join(args))
``` | I think that your call\_me\_by\_name is no good example for \*\*kwargs. But if you want to avoid omitting some exotic, unconsidered name fields, call\_me\_by\_name could look like:
```
def call_me_by_name(first_name, last_name, middle_name='', **kwargs):
s = "Your name is {} {} {}".format(first_name,middle_name,last_name)
if kwargs:
s += " (" + ", ".join(["{}: {}".format(k,v) for k,v in kwargs.items()]) + ")"
print(s)
```
Test:
```
name = {'first_name': 'Henry', 'last_name': 'Ford', 'ordinal': 'II', 'nickname': 'Hank the Deuce'}
call_me_by_name(**name)
>>> Your name is Henry Ford (ordinal: II, nickname: Hank the Deuce)
``` |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | You have two separate questions with two separate pythonic ways of answering those questions.
1- Your first concern was that you don't want to keep adding new lines the more arguments you start supporting when formatting a string. The way to work around that is using a `defaultdict` so you're able to return an empty string when you don't provide a specific keyword argument and `str.format_map` that accepts a dict as a way to input keyword arguments to format. This way, you only have to update your string and what keyword arguments you want to print:
```
from collections import defaultdict
def call_me_by_name(**kwargs):
default_kwargs = defaultdict(str, kwargs)
print("Your name is {first_name} {second_name} {third_name}".format_map(default_kwargs))
```
2- If, on the other hand and answering your second question, you want to provide different behavior depending on the keyword arguments, like changing the way a string looks or providing different file lookup functionalities, without using if statements, you have to add different functions/methods and call them from this common function/method. Here are two ways of doing that:
OOP:
```
class FileLookup:
def parse(self, **kwargs):
return getattr(self, next(iter(kwargs)))(**kwargs)
def line_number(self, line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(self, byte_position):
print('parsing with a byte position: {}'.format(byte_position))
fl = FileLookup()
fl.parse(byte_position=10)
fl.parse(line_number=10)
```
Module:
```
def line_number(line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(byte_position):
print('parsing with a byte position: {}'.format(byte_position))
def parse(**kwargs):
return globals()[next(iter(kwargs))](**kwargs)
parse(byte_position=29)
parse(line_number=29)
``` | Seem to me your better off not using kwargs and not even a function, you can simply do something like this:
```
print("Your name is", " ".join([first_name, middle_name, last_name]))
```
Or if you do want a function:
```
def call_me_by_name(*args):
print("Your name is", " ".join(args))
``` |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | You have two separate questions with two separate pythonic ways of answering those questions.
1- Your first concern was that you don't want to keep adding new lines the more arguments you start supporting when formatting a string. The way to work around that is using a `defaultdict` so you're able to return an empty string when you don't provide a specific keyword argument and `str.format_map` that accepts a dict as a way to input keyword arguments to format. This way, you only have to update your string and what keyword arguments you want to print:
```
from collections import defaultdict
def call_me_by_name(**kwargs):
default_kwargs = defaultdict(str, kwargs)
print("Your name is {first_name} {second_name} {third_name}".format_map(default_kwargs))
```
2- If, on the other hand and answering your second question, you want to provide different behavior depending on the keyword arguments, like changing the way a string looks or providing different file lookup functionalities, without using if statements, you have to add different functions/methods and call them from this common function/method. Here are two ways of doing that:
OOP:
```
class FileLookup:
def parse(self, **kwargs):
return getattr(self, next(iter(kwargs)))(**kwargs)
def line_number(self, line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(self, byte_position):
print('parsing with a byte position: {}'.format(byte_position))
fl = FileLookup()
fl.parse(byte_position=10)
fl.parse(line_number=10)
```
Module:
```
def line_number(line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(byte_position):
print('parsing with a byte position: {}'.format(byte_position))
def parse(**kwargs):
return globals()[next(iter(kwargs))](**kwargs)
parse(byte_position=29)
parse(line_number=29)
``` | I think that your call\_me\_by\_name is no good example for \*\*kwargs. But if you want to avoid omitting some exotic, unconsidered name fields, call\_me\_by\_name could look like:
```
def call_me_by_name(first_name, last_name, middle_name='', **kwargs):
s = "Your name is {} {} {}".format(first_name,middle_name,last_name)
if kwargs:
s += " (" + ", ".join(["{}: {}".format(k,v) for k,v in kwargs.items()]) + ")"
print(s)
```
Test:
```
name = {'first_name': 'Henry', 'last_name': 'Ford', 'ordinal': 'II', 'nickname': 'Hank the Deuce'}
call_me_by_name(**name)
>>> Your name is Henry Ford (ordinal: II, nickname: Hank the Deuce)
``` |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | If your function care so specifically about keyword arguments, this is probably not the right tool. In this case, you can get the same effect with default arguments:
```
def call_me_by_name(first_name, middle_name="", last_name=""):
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
It's better for when you want a sort of "grab-bag" of options. E.g.
```
def configure(**kwargs):
if 'color' in kwargs:
set_color(kwargs['color'])
```
etc. | I think that your call\_me\_by\_name is no good example for \*\*kwargs. But if you want to avoid omitting some exotic, unconsidered name fields, call\_me\_by\_name could look like:
```
def call_me_by_name(first_name, last_name, middle_name='', **kwargs):
s = "Your name is {} {} {}".format(first_name,middle_name,last_name)
if kwargs:
s += " (" + ", ".join(["{}: {}".format(k,v) for k,v in kwargs.items()]) + ")"
print(s)
```
Test:
```
name = {'first_name': 'Henry', 'last_name': 'Ford', 'ordinal': 'II', 'nickname': 'Hank the Deuce'}
call_me_by_name(**name)
>>> Your name is Henry Ford (ordinal: II, nickname: Hank the Deuce)
``` |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | If your function care so specifically about keyword arguments, this is probably not the right tool. In this case, you can get the same effect with default arguments:
```
def call_me_by_name(first_name, middle_name="", last_name=""):
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
It's better for when you want a sort of "grab-bag" of options. E.g.
```
def configure(**kwargs):
if 'color' in kwargs:
set_color(kwargs['color'])
```
etc. | I will post it as a answer then :
You can instantly unpack the **kwargs** values to the format function like this :
```
"Your name is {} {} {}".format(first_name , *kwargs)
```
But as a User **@PM 2Ring** mentioned You must be aware that doesn't guarantee that the names will be in the correct order. |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | You have two separate questions with two separate pythonic ways of answering those questions.
1- Your first concern was that you don't want to keep adding new lines the more arguments you start supporting when formatting a string. The way to work around that is using a `defaultdict` so you're able to return an empty string when you don't provide a specific keyword argument and `str.format_map` that accepts a dict as a way to input keyword arguments to format. This way, you only have to update your string and what keyword arguments you want to print:
```
from collections import defaultdict
def call_me_by_name(**kwargs):
default_kwargs = defaultdict(str, kwargs)
print("Your name is {first_name} {second_name} {third_name}".format_map(default_kwargs))
```
2- If, on the other hand and answering your second question, you want to provide different behavior depending on the keyword arguments, like changing the way a string looks or providing different file lookup functionalities, without using if statements, you have to add different functions/methods and call them from this common function/method. Here are two ways of doing that:
OOP:
```
class FileLookup:
def parse(self, **kwargs):
return getattr(self, next(iter(kwargs)))(**kwargs)
def line_number(self, line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(self, byte_position):
print('parsing with a byte position: {}'.format(byte_position))
fl = FileLookup()
fl.parse(byte_position=10)
fl.parse(line_number=10)
```
Module:
```
def line_number(line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(byte_position):
print('parsing with a byte position: {}'.format(byte_position))
def parse(**kwargs):
return globals()[next(iter(kwargs))](**kwargs)
parse(byte_position=29)
parse(line_number=29)
``` | I will post it as a answer then :
You can instantly unpack the **kwargs** values to the format function like this :
```
"Your name is {} {} {}".format(first_name , *kwargs)
```
But as a User **@PM 2Ring** mentioned You must be aware that doesn't guarantee that the names will be in the correct order. |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | Seem to me your better off not using kwargs and not even a function, you can simply do something like this:
```
print("Your name is", " ".join([first_name, middle_name, last_name]))
```
Or if you do want a function:
```
def call_me_by_name(*args):
print("Your name is", " ".join(args))
``` | I will post it as a answer then :
You can instantly unpack the **kwargs** values to the format function like this :
```
"Your name is {} {} {}".format(first_name , *kwargs)
```
But as a User **@PM 2Ring** mentioned You must be aware that doesn't guarantee that the names will be in the correct order. |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | You can simplify it by:
```
middle_name = kwargs.get('middle_name', '')
``` | I will post it as a answer then :
You can instantly unpack the **kwargs** values to the format function like this :
```
"Your name is {} {} {}".format(first_name , *kwargs)
```
But as a User **@PM 2Ring** mentioned You must be aware that doesn't guarantee that the names will be in the correct order. |
52,331,595 | I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question.
As an example, I've taken a simple method to print my name.
```
def call_me_by_name(first_name):
print("Your name is {}".format(first_name))
```
Later on, I realized that optionally, I would also like to be able to print the middle name and last name. I made the following changes to accommodate that using \*\*kwargs fearing that in the future, I might be made to add more fields for the name itself (such as a 3rd, 4th, 5th name etc.)
I decided to use \*\*kwargs
```
def call_me_by_name(first_name,**kwargs):
middle_name = kwargs['middle_name'] if kwargs.get('middle_name') else ""
last_name = kwargs['last_name'] if kwargs.get('last_name') else ""
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
My only concern here is that as I continue to implement support for more names, I end up writing one line of code for every single keyword argument that may or may not come my way. I'd like to find a solution that is as pythonic as possible. Is there a better way to achieve this ?
**EDIT 1**
I want to use keyword arguments since this is just an example program. The actual use case is to parse through a file. The keyword arguments as of now would support parsing a file from
1) A particular byte in the file.
2) A particular line number in the file.
Only one of these two conditions can be set at any given point in time (since it's not possible to read from a particular byte offset in the file and from a line number at the same time.) but there could be more such conditions in the future such as parse a file from the first occurrence of a character etc. There could be 10-20 different such conditions my method should support BUT only one of those conditions would ever be set at any time by the caller. I don't want to have 20-30 different IF conditions unless there's no other option. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52331595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4020238/"
] | You have two separate questions with two separate pythonic ways of answering those questions.
1- Your first concern was that you don't want to keep adding new lines the more arguments you start supporting when formatting a string. The way to work around that is using a `defaultdict` so you're able to return an empty string when you don't provide a specific keyword argument and `str.format_map` that accepts a dict as a way to input keyword arguments to format. This way, you only have to update your string and what keyword arguments you want to print:
```
from collections import defaultdict
def call_me_by_name(**kwargs):
default_kwargs = defaultdict(str, kwargs)
print("Your name is {first_name} {second_name} {third_name}".format_map(default_kwargs))
```
2- If, on the other hand and answering your second question, you want to provide different behavior depending on the keyword arguments, like changing the way a string looks or providing different file lookup functionalities, without using if statements, you have to add different functions/methods and call them from this common function/method. Here are two ways of doing that:
OOP:
```
class FileLookup:
def parse(self, **kwargs):
return getattr(self, next(iter(kwargs)))(**kwargs)
def line_number(self, line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(self, byte_position):
print('parsing with a byte position: {}'.format(byte_position))
fl = FileLookup()
fl.parse(byte_position=10)
fl.parse(line_number=10)
```
Module:
```
def line_number(line_number):
print('parsing with a line number: {}'.format(line_number))
def byte_position(byte_position):
print('parsing with a byte position: {}'.format(byte_position))
def parse(**kwargs):
return globals()[next(iter(kwargs))](**kwargs)
parse(byte_position=29)
parse(line_number=29)
``` | If your function care so specifically about keyword arguments, this is probably not the right tool. In this case, you can get the same effect with default arguments:
```
def call_me_by_name(first_name, middle_name="", last_name=""):
print("Your name is {} {} {}".format(first_name,middle_name,last_name))
```
It's better for when you want a sort of "grab-bag" of options. E.g.
```
def configure(**kwargs):
if 'color' in kwargs:
set_color(kwargs['color'])
```
etc. |
12,830,838 | Hello I have what I hope is an easy problem to solve. I am attempting to read a csv file and write a portion into a list. I need to determine the index and the value in each row and then summarize.
so the row will have 32 values...each value is a classification (class 0, class 1, etc.) with a number associated with it. I need a pythonic solution to make this work.
```
import os,sys,csv
csvfile=sys.argv[1]
f=open(csvfile,'rt')
reader=csv.reader(f)
classes=[]
for row in reader:
classes.append(row[60:92])
f.close()
classes = [' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']
```
how would i extract the index values from each list to get a sum for each?
for example: 0=(' ', ' ') 1=('1234', '76541') 2= ('645', ' ') 3= ('9897', '8888')
then find the sum of each
```
class 0 = 0
class 1 = 77775
class 2 = 645
class3 = 18785
```
Any assistance would be greatly appreciated | 2012/10/11 | [
"https://Stackoverflow.com/questions/12830838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736554/"
] | I find your use case a bit difficult to understand, but does this list comprehension give you some new ideas about how to solve your problem?
```
>>> classes = [' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']
>>> [sum(int(n) for n in x if n != ' ') for x in zip(*classes)]
[0, 77775, 645, 18785]
``` | ```
>>> classes = [[' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']]
>>> my_int = lambda s: int(s) if s.isdigit() else 0
>>> class_groups = dict(zip(range(32), zip(*classes)))
>>> class_groups[1]
('1234', '76541')
>>> class_sums = {}
>>> for class_ in class_groups:
... group_sum = sum(map(my_int, class_groups[class_]))
... class_sums[class_] = group_sum
...
>>> class_sums[1]
77775
>>> class_sums[3]
18785
>>>
``` |
12,830,838 | Hello I have what I hope is an easy problem to solve. I am attempting to read a csv file and write a portion into a list. I need to determine the index and the value in each row and then summarize.
so the row will have 32 values...each value is a classification (class 0, class 1, etc.) with a number associated with it. I need a pythonic solution to make this work.
```
import os,sys,csv
csvfile=sys.argv[1]
f=open(csvfile,'rt')
reader=csv.reader(f)
classes=[]
for row in reader:
classes.append(row[60:92])
f.close()
classes = [' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']
```
how would i extract the index values from each list to get a sum for each?
for example: 0=(' ', ' ') 1=('1234', '76541') 2= ('645', ' ') 3= ('9897', '8888')
then find the sum of each
```
class 0 = 0
class 1 = 77775
class 2 = 645
class3 = 18785
```
Any assistance would be greatly appreciated | 2012/10/11 | [
"https://Stackoverflow.com/questions/12830838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736554/"
] | I find your use case a bit difficult to understand, but does this list comprehension give you some new ideas about how to solve your problem?
```
>>> classes = [' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']
>>> [sum(int(n) for n in x if n != ' ') for x in zip(*classes)]
[0, 77775, 645, 18785]
``` | You could sum as you go through the CSV file rows. (e.g. put the for class\_ loop inside your rows loop) .. :
```
>>> classes
[[' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']]
>>> sums = {}
>>> for row in classes:
... for class_, num in enumerate(row):
... try:
... num = int(num)
... except ValueError:
... num = 0
... sums[class_] = sums.get(class_, 0) + num
...
>>> sums
{0: 0, 1: 77775, 2: 645, 3: 18785}
``` |
3,484,976 | I'm trying to write a Python client for a a WSDL service. I'm using the [Suds](https://fedorahosted.org/suds/wiki/Documentation) library to handle the SOAP messages.
When I try to call the service, I get a Suds exception: `<rval />` not mapped to message part. If I set the `retxml` Suds option I get XML which looks OK to me.
Is the problem with the client code? Am I missing some flag which will allow Suds to correctly parse the XML? Alternatively, the problem could be with the server. Is the XML not structured correctly?
My code is a follows (method names changed):
```
c = Client(url)
p = c.factory.create('MyParam')
p.value = 100
c.service.run(p)
```
This results in a Suds exception:
```
File "/home/.../test.py", line 38, in test
res = self.client.service.run(p)
File "/usr/local/lib/python2.6/dist-packages/suds-0.3.9-py2.6.egg/suds/client.py", line 539, in __call__
return client.invoke(args, kwargs)
File "/usr/local/lib/python2.6/dist-packages/suds-0.3.9-py2.6.egg/suds/client.py", line 598, in invoke
result = self.send(msg)
File "/usr/local/lib/python2.6/dist-packages/suds-0.3.9-py2.6.egg/suds/client.py", line 627, in send
result = self.succeeded(binding, reply.message)
File "/usr/local/lib/python2.6/dist-packages/suds-0.3.9-py2.6.egg/suds/client.py", line 659, in succeeded
r, p = binding.get_reply(self.method, reply)
File "/usr/local/lib/python2.6/dist-packages/suds-0.3.9-py2.6.egg/suds/bindings/binding.py", line 151, in get_reply
result = self.replycomposite(rtypes, nodes)
File "/usr/local/lib/python2.6/dist-packages/suds-0.3.9- py2.6.egg/suds/bindings/binding.py", line 204, in replycomposite
raise Exception('<%s/> not mapped to message part' % tag)
Exception: <rval/> not mapped to message part
```
The returned XML (modified to remove customer identifiers)
```
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getResponse xmlns:ns2="http://api.xxx.xxx.com/api/">
<rval xmlns="http://xxx.xxx.xxx.com/api/">
<ns2:totalNumEntries>
2
</ns2:totalNumEntries>
<ns2:entries>
<ns2:id>
1
</ns2:id>
</ns2:entries>
<ns2:entries>
<ns2:id>
2
</ns2:id>
</ns2:entries>
</rval>
</ns2:getResponse>
</S:Body>
</S:Envelope>
``` | 2010/08/14 | [
"https://Stackoverflow.com/questions/3484976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4697/"
] | Possible dup of [What does suds mean by "<faultcode/> not mapped to message part"?](https://stackoverflow.com/questions/2963094/what-does-suds-mean-by-faultcode-not-mapped-to-message-part/18948575#18948575)
Here is my answer from that question:
I had a similar issue where the call was successful, and Suds crashed on parsing the response from the client. The workaround I used was to use the [Suds option to return raw XML](http://jortel.fedorapeople.org/suds/doc/suds.options.Options-class.html) and then use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) to parse the response.
Example:
```
client = Client(url)
client.set_options(retxml=True)
soapresp_raw_xml = client.service.submit_func(data)
soup = BeautifulStoneSoup(soapresp_raw_xml)
value_i_want = soup.find('ns:NewSRId')
``` | This exception actually means that the answer from SOAP-service contains tag `<rval>`, which doesn't exist in the WSDL-scheme of the service.
Keep in mind that the Suds library caches the WSDL-scheme, that is why the problem may occur if the WSDL-scheme was changed recently. Then the answers match the new scheme, but are verified by the suds-client with the old one. In this case `rm /tmp/suds/*` will help you. |
35,122,185 | I have a Profiles app that has a model called profile, i use that model to extend the django built in user model without subclassing it.
**models.py**
```
class BaseProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner',primary_key=True)
supervisor = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='supervisor', null=True, blank=True)
@python_2_unicode_compatible
class Profile(BaseProfile):
def __str__(self):
return "{}'s profile". format(self.user)
```
**admin.py**
```
class UserProfileInline(admin.StackedInline):
model = Profile
class NewUserAdmin(NamedUserAdmin):
inlines = [UserProfileInline ]
admin.site.unregister(User)
admin.site.register(User, NewUserAdmin)
```
admin
**the error is**
```
<class 'profiles.admin.UserProfileInline'>: (admin.E202) 'profiles.Profile' has more than one ForeignKey to 'authtools.User'.
```
obviously i want to select a user to be a supervisor to another user. I think the relationship in the model is OK, the one that's complaining is admins.py file. Any idea ? | 2016/02/01 | [
"https://Stackoverflow.com/questions/35122185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031794/"
] | You need to use multiple inline admin.
When you have a model with multiple ForeignKeys to the same parent model, you'll need specify the `fk_name` attribute in your inline admin:
```
class UserProfileInline(admin.StackedInline):
model = Profile
fk_name = "user"
class SupervisorProfileInline(admin.StackedInline):
model = Profile
fk_name = "supervisor"
class NewUserAdmin(NamedUserAdmin):
inlines = [UserProfileInline, SupervisorProfileInline]
```
Django has some documentation on dealing with this: <https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#working-with-a-model-with-two-or-more-foreign-keys-to-the-same-parent-model> | Here is an example that I have just tested to be working
```
class Task(models.Model):
owner = models.ForeignKey(User, related_name='task_owner')
assignee = models.ForeignKey(User, related_name='task_assigned_to')
```
In admin.py
```
class TaskInLine(admin.TabularInLine):
model = User
@admin.register(Task)
class MyModelAdmin(admin.ModelAdmin):
list_display = ['owner', 'assignee']
inlines = [TaskInLine]
``` |
15,351,081 | For example let's say I have a file called myscript.py
This file contains the following code.
```
foo(var):
return var
```
How would I call the function foo with argument var on command line.
I know that I can go to the directory myscript.py is placed in and type.
```
>>> python myscript.py
```
Which will run myscript.py. The only problem is myscript.py doesn't automatically call foo when it is run.
I have tried using
```
if __name__ == "__main__":
foo( )
```
Which does not work for me. For some reason when I do that nothing happens. I get no error message and nothing is called. | 2013/03/12 | [
"https://Stackoverflow.com/questions/15351081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2158898/"
] | You don't get any output because you don't generate any. Try calling [`print`](http://docs.python.org/3/library/functions.html#print):
```
def foo(var):
print(var)
if __name__ == '__main__':
foo('Hello, world')
``` | You have to use the `sys` module to pass arguments from the command line.
You can do this:
```
import sys
def foo(var):
return var
if __name__ == '__main__':
# arguments check
if len(sys.argv) != 2:
print "USAGE: %s <value>" % sys.argv[0]
sys.exit(1)
# get the agument so as to use it to the function call
arg = sys.argv[1]
# call the function using this argument
val = foo(arg)
# print the returned value
print val
```
Then you can run your python script by this command:
`python myscript.py 3`
giving as argument e.g. the number 3 |
22,214,463 | The title is self explanatory. What is going on here? How can I get this not to happen? Do I really have to change all of my units (it's a physics problem) just so that I can get a big enough answer that python doesn't round 1-x to 1?
code:
```
import numpy as np
import math
vel=np.array([5e-30,5e-30,5e-30])
c=9.7156e-12
def mag(V):
return math.sqrt(V[0]**2+V[1]**2+V[2]**2)
gam=(1-(mag(vel)/c)**2)**(-1/2)
print(mag(vel))
print(mag(vel)**2)
print(mag(vel)**2/(c**2))
print(1-mag(vel)**2/(c**2))
print(gam)
```
output:
```
>>> (executing lines 1 to 17 of "<tmp 1>")
8.660254037844386e-30
7.499999999999998e-59
7.945514251743055e-37
1.0
1.0
>>>
``` | 2014/03/06 | [
"https://Stackoverflow.com/questions/22214463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347826/"
] | In python [decimal](http://docs.python.org/library/decimal.html#module-decimal) may work and maybe [mpmath](https://code.google.com/p/mpmath/).
as is discussed in this SO [article](https://stackoverflow.com/questions/11522933/python-floating-point-arbitrary-precision-available)
If you are willing to use Java (instead of python), you might be able to use BigDecimal, or [apfloat](http://www.apfloat.org/) or [JScience](http://jscience.org/).
8.66e-30 only uses 3 sigs, but to illustrate 1 minus that would require more than 30. Any more than 16 significant figures you will need to represent digits using something else, like very long strings. But it's difficult to do math with long strings. You could also perform binary computations on very long arrays of byte values. The byte values could be made to represent a very large integer value modified by a scale factor of your choice. So if you can support and integer larger than 1E60, then you can alternately scale the value so that you can represent 1E-60 with a maximum value of 1. You can probably do that with about 200 bits or 25 bytes, and with 400 bits, you should be able to precisely represent the entire range of 1E60 to 1E-60. There may already be utilities that can perform calculations of this type out there used by people that work in math or security as they may want to represent PI to a thousand places for instance, which you can't do with a double.
The other useful trick is to use scale factors. That is, in your original coordinate space you cannot do the subtraction because the digits will not be able to represent the values. But, if you make the assumption that if you are making small adjustments you do not simultaneously care about large adjustments, then you can perform a transform on the data. So for instance you subtract 1 from your numbers. Then you could represent 1-1E-60 as -1E-60. You could do as many operations very precisely in your transform space, but knowing full well that if you attempt to convert them back from your transform space they will be lost as irrelevant. This sort of tactic is useful when zooming in on a map. Making adjustments on the scale of micrometers in units of latitude and longitude for your single precision floating point DirectX calculations won't work. But you could temporarily change your scale while you are zoomed in so that the operations will work normally.
So complicated numbers can then be represented by a big number plus a second number that represents the small scale adjustment. So for instance, if you have 16 digits in a double, you can use the first number to represent the large portion of the value, like from 1 to 1E16, and the second double to represent the additional small portion. Except that using 16 digits might be flirting with errors from the double's ability to represent the big value accurately so you might use only 15 or 14 or so just to be safe.
```
1234567890.1234567890
```
becomes
```
1.234567890E9 + 1.23456789E-1.
```
and basically the bigger your precision the more terms your complex number gets. But while this sort of thing works pretty well when each term is more or less mathematically independent, in cases where you have to do lots of rigorous calculations that operate across the scales, doing the book-keeping between these values would likely be more of a pain than it would be worth. | I think you won't get the result you are expecting because you are dealing with computer math limits. The thing about this kind of calculations is that nobody can avoid this error, unless you make/find some models that has infinite (theoretically) decimals and you can operate with them. If that is too much for the problem you are trying to solve, maybe you just have to be careful and try to do whatever you need but trying to handle these errors in calculations.
There are a lot of bibliography out there with many different approaches to handle the errors in calculations that helps not to avoid but to minimize these errors.
Hope my answer helps and don't disappoint you.. |
73,007,506 | Hi I want to clean up my code where I am converting a list of items to integers whenever possible in the python programming language.
```
example_list = ["4", "string1", "9", "string2", "10", "string3"]
```
So my goal (which is probably very simple) is to convert all items in the list from integers to integers and keep the actual strings as strings. The desired output of the program should be:
```
example_list = [4, "string1", 9, "string2", 10, "string3"]
```
I am looking for a nice clean method as I am sure that it is possible. I am curious about what nice methods there are. | 2022/07/16 | [
"https://Stackoverflow.com/questions/73007506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13840524/"
] | Perhaps add this somewhere:
```
<style>
div {
max-width: 306px !important;
}
</style>
``` | u can try and use max width set to 306px for that part |
61,412,481 | I am trying to access Google Sheet (read only mode) from Python (runs in GKE).
I am able to get application default creds, but getting scopes issue (as I am missing `https://www.googleapis.com/auth/spreadsheets.readonly` scope). See code below:
```
from googleapiclient.discovery import build
from oauth2client import client
creds=client.GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
sheet.values().get(spreadsheetId='XXXXXXXXXX', range='Sheet1!A:C').execute()
```
The output is:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/googleapiclient/http.py", line 840, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/XXXXXX/values/Sheet1%21A%3AC?alt=json returned "Request had insufficient authentication scopes.">
```
I tried to read any documentation available, but al of the relevant scope related is using external service account JSON file.
Is there a way to use Application Default and add the required scope? | 2020/04/24 | [
"https://Stackoverflow.com/questions/61412481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/408628/"
] | You need to separate tick values and tick labels.
```
ax.set_xticks([]) # values
ax.set_xticklabels([]) # labels
``` | Just change it to:
```
self.ax.set_xticks([])
self.ax.set_yticks([])
```
The error says that the second parameter cannot be given positionally, meaning that you need to explicitly give the parameter name minor=False for the second parameter or remove the second parameter in your case. |
17,713,692 | I am trying to simplify an expression using z3py but am unable to find any documentation on what different tactics do. The best resource I have found is a [stack overflow question](https://stackoverflow.com/questions/16167088/z3-tactics-are-not-available-via-online-interface) that lists all the tactics by name.
Is someone able to link me to detailed documentation on the tactics available?
The on line python tutorials are not sufficient.
Or can someone recommend a better way to accomplish this.
An example of the problems is an expression such as:
`x < 5, x < 4, x < 3, x = 1` I would like this to simplify down to `x = 1`.
Using the tactic `unit-subsume-simplify` appears works for this example.
But when I try a more complicated example such as `x > 1, x < 5, x != 3, x != 4` I get `x > 1, x < 5, x ≠ 3, x ≠ 4` as the result. When I would like `x = 2`.
What is the best approach to achieve this type of simplification using z3py?
[My current solution](http://rise4fun.com/Z3Py/QLRG).
Thanks Matt | 2013/07/18 | [
"https://Stackoverflow.com/questions/17713692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016669/"
] | What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
```
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
``` | I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
\*\*Note have used Python 2.7 so some minor modification might be required for Python 3+
```
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
```
Calling get\_config method using class instance in a separate python file:
```
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
``` |
17,713,692 | I am trying to simplify an expression using z3py but am unable to find any documentation on what different tactics do. The best resource I have found is a [stack overflow question](https://stackoverflow.com/questions/16167088/z3-tactics-are-not-available-via-online-interface) that lists all the tactics by name.
Is someone able to link me to detailed documentation on the tactics available?
The on line python tutorials are not sufficient.
Or can someone recommend a better way to accomplish this.
An example of the problems is an expression such as:
`x < 5, x < 4, x < 3, x = 1` I would like this to simplify down to `x = 1`.
Using the tactic `unit-subsume-simplify` appears works for this example.
But when I try a more complicated example such as `x > 1, x < 5, x != 3, x != 4` I get `x > 1, x < 5, x ≠ 3, x ≠ 4` as the result. When I would like `x = 2`.
What is the best approach to achieve this type of simplification using z3py?
[My current solution](http://rise4fun.com/Z3Py/QLRG).
Thanks Matt | 2013/07/18 | [
"https://Stackoverflow.com/questions/17713692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016669/"
] | What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
```
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
``` | ```
def prepare_table_row(row):
lst = [i.text for i in row if i != u'\n']
return dict(rank = int(lst[0]),
grade = str(lst[1]),
channel=str(lst[2])),
videos = float(lst[3].replace(",", " ")),
subscribers = float(lst[4].replace(",", "")),
views = float(lst[5].replace(",", "")))
``` |
17,713,692 | I am trying to simplify an expression using z3py but am unable to find any documentation on what different tactics do. The best resource I have found is a [stack overflow question](https://stackoverflow.com/questions/16167088/z3-tactics-are-not-available-via-online-interface) that lists all the tactics by name.
Is someone able to link me to detailed documentation on the tactics available?
The on line python tutorials are not sufficient.
Or can someone recommend a better way to accomplish this.
An example of the problems is an expression such as:
`x < 5, x < 4, x < 3, x = 1` I would like this to simplify down to `x = 1`.
Using the tactic `unit-subsume-simplify` appears works for this example.
But when I try a more complicated example such as `x > 1, x < 5, x != 3, x != 4` I get `x > 1, x < 5, x ≠ 3, x ≠ 4` as the result. When I would like `x = 2`.
What is the best approach to achieve this type of simplification using z3py?
[My current solution](http://rise4fun.com/Z3Py/QLRG).
Thanks Matt | 2013/07/18 | [
"https://Stackoverflow.com/questions/17713692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016669/"
] | What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
```
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
``` | ```
def query(id):
for line in file:
table = line.split(";")
if id == int(table[0]):
yield table
id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
print("ID: " + id_)
print("Name: " + name)
print("City: " + city)
file.close()
```
Using yield.. |
17,713,692 | I am trying to simplify an expression using z3py but am unable to find any documentation on what different tactics do. The best resource I have found is a [stack overflow question](https://stackoverflow.com/questions/16167088/z3-tactics-are-not-available-via-online-interface) that lists all the tactics by name.
Is someone able to link me to detailed documentation on the tactics available?
The on line python tutorials are not sufficient.
Or can someone recommend a better way to accomplish this.
An example of the problems is an expression such as:
`x < 5, x < 4, x < 3, x = 1` I would like this to simplify down to `x = 1`.
Using the tactic `unit-subsume-simplify` appears works for this example.
But when I try a more complicated example such as `x > 1, x < 5, x != 3, x != 4` I get `x > 1, x < 5, x ≠ 3, x ≠ 4` as the result. When I would like `x = 2`.
What is the best approach to achieve this type of simplification using z3py?
[My current solution](http://rise4fun.com/Z3Py/QLRG).
Thanks Matt | 2013/07/18 | [
"https://Stackoverflow.com/questions/17713692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016669/"
] | ```
def prepare_table_row(row):
lst = [i.text for i in row if i != u'\n']
return dict(rank = int(lst[0]),
grade = str(lst[1]),
channel=str(lst[2])),
videos = float(lst[3].replace(",", " ")),
subscribers = float(lst[4].replace(",", "")),
views = float(lst[5].replace(",", "")))
``` | I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
\*\*Note have used Python 2.7 so some minor modification might be required for Python 3+
```
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
```
Calling get\_config method using class instance in a separate python file:
```
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
``` |
17,713,692 | I am trying to simplify an expression using z3py but am unable to find any documentation on what different tactics do. The best resource I have found is a [stack overflow question](https://stackoverflow.com/questions/16167088/z3-tactics-are-not-available-via-online-interface) that lists all the tactics by name.
Is someone able to link me to detailed documentation on the tactics available?
The on line python tutorials are not sufficient.
Or can someone recommend a better way to accomplish this.
An example of the problems is an expression such as:
`x < 5, x < 4, x < 3, x = 1` I would like this to simplify down to `x = 1`.
Using the tactic `unit-subsume-simplify` appears works for this example.
But when I try a more complicated example such as `x > 1, x < 5, x != 3, x != 4` I get `x > 1, x < 5, x ≠ 3, x ≠ 4` as the result. When I would like `x = 2`.
What is the best approach to achieve this type of simplification using z3py?
[My current solution](http://rise4fun.com/Z3Py/QLRG).
Thanks Matt | 2013/07/18 | [
"https://Stackoverflow.com/questions/17713692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016669/"
] | ```
def query(id):
for line in file:
table = line.split(";")
if id == int(table[0]):
yield table
id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
print("ID: " + id_)
print("Name: " + name)
print("City: " + city)
file.close()
```
Using yield.. | I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
\*\*Note have used Python 2.7 so some minor modification might be required for Python 3+
```
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
```
Calling get\_config method using class instance in a separate python file:
```
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
``` |
17,713,692 | I am trying to simplify an expression using z3py but am unable to find any documentation on what different tactics do. The best resource I have found is a [stack overflow question](https://stackoverflow.com/questions/16167088/z3-tactics-are-not-available-via-online-interface) that lists all the tactics by name.
Is someone able to link me to detailed documentation on the tactics available?
The on line python tutorials are not sufficient.
Or can someone recommend a better way to accomplish this.
An example of the problems is an expression such as:
`x < 5, x < 4, x < 3, x = 1` I would like this to simplify down to `x = 1`.
Using the tactic `unit-subsume-simplify` appears works for this example.
But when I try a more complicated example such as `x > 1, x < 5, x != 3, x != 4` I get `x > 1, x < 5, x ≠ 3, x ≠ 4` as the result. When I would like `x = 2`.
What is the best approach to achieve this type of simplification using z3py?
[My current solution](http://rise4fun.com/Z3Py/QLRG).
Thanks Matt | 2013/07/18 | [
"https://Stackoverflow.com/questions/17713692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016669/"
] | ```
def query(id):
for line in file:
table = line.split(";")
if id == int(table[0]):
yield table
id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
print("ID: " + id_)
print("Name: " + name)
print("City: " + city)
file.close()
```
Using yield.. | ```
def prepare_table_row(row):
lst = [i.text for i in row if i != u'\n']
return dict(rank = int(lst[0]),
grade = str(lst[1]),
channel=str(lst[2])),
videos = float(lst[3].replace(",", " ")),
subscribers = float(lst[4].replace(",", "")),
views = float(lst[5].replace(",", "")))
``` |
73,381,445 | I need to have bash shell commands run through python in order to be universal with pc and mac/linux. `./bin/production` doesn't work in powershell and putting 'bash' in front would give an error that it doesn't recognize 'docker' command
./bin/production contents:
```
#!/bin/bash
docker run --rm -it \
--volume ${PWD}/prime:/app \
$(docker build -q docker/prime) \
npm run build
```
This is the python script:
```
import subprocess
from python_on_whales import docker
cmd = docker.run('docker run --rm -it --volume ${PWD}/prime:/app $(docker build -q docker/prime) npm run build')
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, err = p.communicate()
print(out)
```
This is the error I get when running the python script:
python\_on\_whales.exceptions.NoSuchImage: The docker command executed was `C:\Program Files\Docker\Docker\resources\bin\docker.EXE image inspect docker run --rm -it --volume ${PWD}/prime:/app $(docker build -q docker/prime) npm run build`.
It returned with code 1
The content of stdout is '[]
'
The content of stderr is 'Error response from daemon: no such image: docker run --rm -it --volume ${PWD}/prime:/app $(docker build -q docker/prime) npm run build: invalid reference format: repository name must be lowercase
'
Running the command, `docker run --rm -it--volume ${PWD}/prime:/app $(docker build -q docker/prime) npm run build` in one long line in powershell works but we want a universal standard command for both pc and mac/linux | 2022/08/16 | [
"https://Stackoverflow.com/questions/73381445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19779700/"
] | ### Modification points:
* In your showing script, it seems that `payload` is not used.
* When `getValue()` is used in a loop, the process cost becomes high. [Ref](https://gist.github.com/tanaikech/d102c9600ba12a162c667287d2f20fe4)
When these points are reflected in a sample script for achieving your goal, it becomes as follows.
### Sample script:
When your showing script is modified, how about the following modification?
```js
function testRun() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var LastRow = ss.getLastRow();
var LastCol = ss.getLastColumn();
var [header, ...values] = ss.getRange(1, 1, LastRow, LastCol).getValues();
var arr = [];
for (var i = 0; i < LastRow - 1; i++) {
var temp = {};
for (var j = 0; j < LastCol; j++) {
temp[header[j]] = values[i][j];
}
arr.push(temp);
}
console.log(JSON.stringify(arr))
}
```
* When this script is run, `arr` is `[{"FirstName":"Kim","LastName":"hana","Phone":"010-1234-5648","Email":"abc@gmail.com"}]`.
* As another apporach, I thought that you might be able to also use the following sample script.
```
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var [header, ...values] = ss.getRange(1, 1, ss.getLastRow(), ss.getLastColumn()).getValues();
var arr = values.map(r => header.reduce((o, h, j) => (o[h] = r[j], o), {}));
console.log(JSON.stringify(arr))
``` | Your code creates separate objects in each iteration. Create an empty object for every Person, then add the properties you need.
This should look something like this:
```js
for(var i=2; i<=LastRow; i++){
var payload = {}
for(var j=1; j<=LastCol; j++){
payload[arr[j-1]] = ss.getRange(i,j).getValue()};
}
}
``` |
6,499,839 | >
> **Possible Duplicate:**
>
> [Flatten (an irregular) list of lists in Python](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python)
>
>
>
I have the following list --
```
[1,[2,3],4,[5,[6,7]]]
```
And I need to make it flat --
```
[1,2,3,4,5,6,7]
```
To do this, I am currently using a `for` loop with `isinstance`, with the number of loops being `#nests - 1`.
What woud be the simplest way to make the nested list flat? Thank you.
A similar question which deals with making a flat list out of nested lists (only) can be found here: [Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python). | 2011/06/27 | [
"https://Stackoverflow.com/questions/6499839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651174/"
] | Hauled from [webhelpers.misc.flatten](http://sluggo.scrapping.cc/python/WebHelpers/modules/misc.html?highlight=flatten#webhelpers.misc.flatten)
```
def flatten(iterable):
"""Recursively iterate lists and tuples.
"""
for elm in iterable:
if isinstance(elm, (list, tuple)):
for relm in flatten(elm):
yield relm
else:
yield elm
```
**EDIT:** The iterable test here is quite naive and can be improved by checking for the presence of `__iter__` or an instance of the `collections.Iterable` abstract base class.
**EDIT 2:** @ChristopheD is absolutely correct, this is a dupe so head over to the linked question. | Try this:
```
def flat(mlist):
result = []
for i in mlist:
if type(i) is list:
result.extend(flat(i))
else:
result.append(i)
return result
``` |
72,081,872 | Hi I trying to make RBM Model code using pytorch module but got a issue in visible layer to hidden layer. Here is the problem part code.
```py
h_bias = (self.h_bias.clone()).expand(10)
v = v.clone().expand(10)
p_h = F.sigmoid(
F.linear(v, self.W, bias=h_bias)
)
sample_h = self.sample_from_p(p_h)
return p_h, sample_h
```
and each parameters size is here.
```
h_bias v self.W
torch.Size([10]) torch.Size([10]) torch.Size([1, 10])
1 1 2
```
```
Traceback (most recent call last):
File "/Users/bahk_insung/Documents/Github/ecg-dbn/model.py", line 68, in <module>
v, v1 = rbm(sample_data)
File "/Users/bahk_insung/miniforge3/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1102, in _call_impl
return forward_call(*input, **kwargs)
File "/Users/bahk_insung/Documents/Github/ecg-dbn/RBM.py", line 54, in forward
pre_h1, h1 = self.v_to_h(v)
File "/Users/bahk_insung/Documents/Github/ecg-dbn/RBM.py", line 36, in v_to_h
F.linear(v, self.W, bias=h_bias)
File "/Users/bahk_insung/miniforge3/lib/python3.9/site-packages/torch/nn/functional.py", line 1849, in linear
return torch._C._nn.linear(input, weight, bias)
RuntimeError: output with shape [1] doesn't match the broadcast shape [10]
```
I think dimension and size are not matched thats reason why happened. But I can't get any solutions. Please help me guys. Thank you. | 2022/05/02 | [
"https://Stackoverflow.com/questions/72081872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9713429/"
] | If you look at the pytorch functional.linear documentation it shows the weight parameter can be either 1D or 2D: "Weight: (out\_features, in\_features) or (in\_features)". Since your weight is 2D ([1, 10]) it indicates that you are trying to create an output of size "1" with an input size of "10". The linear transform does not know how to change your inputs of size 10 into an output of size 1. If your weight will always be [1, N] then you can use squeeze to change it to 1D like so:
```
F.linear(v, self.W.squeeze(), bias=h_bias)
```
This would create an output of size 10. | I solved with torch.repeat() function. As mandias said...
>
> you are trying to create an output of size "1" with an input size of "10". The linear transform does not know how to change your inputs of size 10 into an output of size 1.
>
>
>
That was a my problem. So I changed weight input like this.
```py
w = self.W.clone().repeat(10, 1)
```
Originally, self.W size is [1, 10]. After used repeat function then changed as [10, 10]. Input is 10 size, and Output is 10.
Tbh not sure this code is right thing but I HAVE TO run this code quickly... anyway thank you guys. |
49,259,985 | I am reading data from a python dictionary and trying to add more book elements in the below tree. Below is just an examplke, i need to copy an element with it's child(s) but replace the content, in this case i need to copy the book element but replace title and author.
```
<store>
<bookstore>
<book>
<title lang="en">IT book</title>
<author>Some IT Guy</author>
</book>
</bookstore>
</store>
```
I use this code:
```
root = et.parse('Template.xml').getroot()
bookstore = root.find('bookstore')
book = root.find('bookstore').find('book')
```
Then i run the loop through a dictionary and trying to add new book elements under the bookstore:
```
for bk in bks:
book.find('title').text = bk
bookstore.append(book)
```
The result is that book elements are added to the bookstore, however they all contain title from the last iteration of the loop. I know i am doing something wrong here, but i can't understand what. I tried:
```
book[0].append(book) and book[-1].append(book)
```
But it did not help. | 2018/03/13 | [
"https://Stackoverflow.com/questions/49259985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4977702/"
] | You changing the same object.
You need to actual copy the object with copy.deepcopy
Example:
```
import xml.etree.ElementTree as et
import copy
root = et.parse('Template.xml').getroot()
bookstore = root.find('bookstore')
book = root.find('bookstore').find('book')
bks = ["book_title_1", "book_title_2", "book_title_3"]
for bk in bks:
new_book = copy.deepcopy(book)
new_book.find('title').text = bk
bookstore.append(new_book)
print et.tostring(root)
``` | I'm guessing instead of `books.append(book)` you mean `bookstore.append(book)`.
Basically here you have a structure:
```
- store
- bookstore
- book
- book infos
```
with `book = root.find('bookstore').find('book')` you are actually getting a reference to the (only) one you already have, and in the loop you keep updating its title and re-appending it to the store (so basically you are only overwriting the title). What you must do is to create every time a new [`Element`](https://docs.python.org/2/library/xml.etree.elementtree.html#element-objects) (or clone it as [Chertkov Pavel](https://stackoverflow.com/a/49261244/1029516) suggested, but you must remember to overwrite *all* the fields, or you may end up inheriting the wrong author) and append it to the bookstore:
```
for bk in bks:
new_book = et.Element('book')
# create and append title
new_title = et.Element('title', attib={'lang':'eng'})
new_title.text = bk
new_book.append(new_title)
# add also author and any other info
# ...
# append to the bookstore
bookstore.append(new_book)
print et.tostring(root)
``` |
2,741,986 | I'm developing a small python like language using flex, byacc (for lexical and parsing) and C++, but i have a few questions regarding scope control.
just as python it uses white spaces (or tabs) for indentation, not only that but i want to implement index breaking like for instance if you type "break 2" inside a while loop that's inside another while loop it would not only break from the last one but from the first loop as well (hence the number 2 after break) and so on.
example:
```
while 1
while 1
break 2
'hello world'!! #will never reach this. "!!" outputs with a newline
end
'hello world again'!! #also will never reach this. again "!!" used for cout
end
#after break 2 it would jump right here
```
but since I don't have an "anti" tab character to check when a scope ends (like C for example i would just use the '}' char) i was wondering if this method would the the best:
I would define a global variable, like "int tabIndex" on my yacc file that i would access in my lex file using extern. then every time i find a tab character on my lex file i would increment that variable by 1. when parsing on my yacc file if i find a "break" keyword i would decrement by the amount typed after it from the tabIndex variable, and when i reach and EOF after compiling and i get a tabIndex != 0 i would output compilation error.
now the problem is, whats the best way to see if the indentation got reduced, should i read \b (backspace) chars from lex and then reduce the tabIndex variable (when the user doesn't use break)?
another method to achieve this?
also just another small question, i want every executable to have its starting point on the function called start() should i hardcode this onto my yacc file?
sorry for the long question any help is greatly appreciated. also if someone can provide an yacc file for python would be nice as a guideline (tried looking on Google and had no luck).
thanks in advance. | 2010/04/30 | [
"https://Stackoverflow.com/questions/2741986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/208153/"
] | I am currently implementing a programming language rather similar to this (including the multilevel break oddly enough). My solution was to have the tokenizer emit indent and dedent tokens based on indentation. Eg:
```
while 1: # colons help :)
print('foo')
break 1
```
becomes:
```
["while", "1", ":",
indent,
"print", "(", "'foo'", ")",
"break", "1",
dedent]
```
It makes the tokenizer's handling of '\n' somewhat complicated though. Also, i wrote the tokenizer and parser from scratch, so i'm not sure whether this is feasable in lex and yacc.
### Edit:
Semi-working pseudocode example:
```
level = 0
levels = []
for c = getc():
if c=='\n':
emit('\n')
n = 0
while (c=getc())==' ':
n += 1
if n > level:
emit(indent)
push(levels,n)
while n < level:
emit(dedent)
level = pop(levels)
if level < n:
error tokenize
# fall through
emit(c) #lazy example
``` | Very interesting exercise. Can't you use the `end` keyword to check when the scope ends?
On a different note, I have never seen a language that allows you to break out of several nested loops at once. There may be a good reason for that... |
53,882,241 | I've seen a few similar questions on SO regarding detecting changes to a dictionary and calling a function when the dictionary changes, such as:
* [How to trigger function on value change?](https://stackoverflow.com/questions/6190468/how-to-trigger-function-on-value-change)
* [python detect if any element in a dictionary changes](https://stackoverflow.com/questions/26189090/python-detect-if-any-element-in-a-dictionary-changes)
These examples use variations of the Observer pattern or overloading `__setitem__`, but all these examples don't detect changes on nested dictionary values.
For example, if I have:
```
my_dict = {'a': {'b': 1}}
my_dict['a']['b'] = 2
```
The assignment of `2` to the element `['a']['b']` will not be detected.
I'm wondering if there is an elegant way of detecting changes not only to the base elements of a dictionary but all the child elements of a nested dictionary as well. | 2018/12/21 | [
"https://Stackoverflow.com/questions/53882241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/512965/"
] | Building on the answer given in [here](https://stackoverflow.com/questions/26189090/python-detect-if-any-element-in-a-dictionary-changes), just do the following:
```
class MyDict(dict):
def __setitem__(self, item, value):
print("You are changing the value of {} to {}!!".format(item, value))
super(MyDict, self).__setitem__(item, value)
```
and then:
```
my_dict = MyDict({'a': MyDict({'b': 1})})
my_dict['a']['b'] = 2
```
>
> You are changing the value of b to 2!!
>
>
>
```
my_dict['a'] = 5
```
>
> You are changing the value of a to 5!!
>
>
>
If you want to avoid manual calls to MyDict at each nesting level, one way of doing it, is to fully overload the *dict* class. For example:
```
class MyDict(dict):
def __init__(self,initialDict):
for k,v in initialDict.items():
if isinstance(v,dict):
initialDict[k] = MyDict(v)
super().__init__(initialDict)
def __setitem__(self, item, value):
if isinstance(value,dict):
_value = MyDict(value)
else:
_value = value
print("You are changing the value of {} to {}!!".format(item, _value))
super().__setitem__(item, _value)
```
You can then do the following:
```
# Simple initialization using a normal dict synthax
my_dict = MyDict({'a': {'b': 1}})
# update example
my_dict['c'] = {'d':{'e':4}}
```
>
> You are changing the value of c to {'d': {'e': 4}}!!
>
>
>
```
my_dict['a']['b'] = 2
my_dict['c']['d']['e'] = 6
```
>
> You are changing the value of b to 2!!
>
>
> You are changing the value of e to 6!!
>
>
> | Complete solution borrowing from the [this](https://stackoverflow.com/questions/26189090/python-detect-if-any-element-in-a-dictionary-changes) link(the second one given by OP)
```
class MyDict(dict):
def __setitem__(self, item, value):
print("You are changing the value of {key} to {value}!!".format(key=item, value=value))
super(MyDict, self).__setitem__(item, convert_to_MyDict_nested(value))
def convert_to_MyDict_nested(d):
if not(isinstance(d, dict)):
return d
for k, v in d.items():
if isinstance(v, dict):
d[k] = convert_to_MyDict_nested(v)
return MyDict(d)
```
So that if
```
d = {'a': {'b': 1}}
```
then,
```
d = convert_to_MyDict_nested(d)
d['a']['b'] = 2 # prints You are changing the value of b to 2!!
d['a']= 5 # prints You are changing the value of a to 5!!
```
Also, edited according to comment by OP. So,
```
d["c"] = {"e" : 7} # prints You are changing the value of c to {'e': 7}!!
d["c"]["e"] = 9 # prints You are changing the value of e to 9!!
``` |
53,882,241 | I've seen a few similar questions on SO regarding detecting changes to a dictionary and calling a function when the dictionary changes, such as:
* [How to trigger function on value change?](https://stackoverflow.com/questions/6190468/how-to-trigger-function-on-value-change)
* [python detect if any element in a dictionary changes](https://stackoverflow.com/questions/26189090/python-detect-if-any-element-in-a-dictionary-changes)
These examples use variations of the Observer pattern or overloading `__setitem__`, but all these examples don't detect changes on nested dictionary values.
For example, if I have:
```
my_dict = {'a': {'b': 1}}
my_dict['a']['b'] = 2
```
The assignment of `2` to the element `['a']['b']` will not be detected.
I'm wondering if there is an elegant way of detecting changes not only to the base elements of a dictionary but all the child elements of a nested dictionary as well. | 2018/12/21 | [
"https://Stackoverflow.com/questions/53882241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/512965/"
] | Building on the answer given in [here](https://stackoverflow.com/questions/26189090/python-detect-if-any-element-in-a-dictionary-changes), just do the following:
```
class MyDict(dict):
def __setitem__(self, item, value):
print("You are changing the value of {} to {}!!".format(item, value))
super(MyDict, self).__setitem__(item, value)
```
and then:
```
my_dict = MyDict({'a': MyDict({'b': 1})})
my_dict['a']['b'] = 2
```
>
> You are changing the value of b to 2!!
>
>
>
```
my_dict['a'] = 5
```
>
> You are changing the value of a to 5!!
>
>
>
If you want to avoid manual calls to MyDict at each nesting level, one way of doing it, is to fully overload the *dict* class. For example:
```
class MyDict(dict):
def __init__(self,initialDict):
for k,v in initialDict.items():
if isinstance(v,dict):
initialDict[k] = MyDict(v)
super().__init__(initialDict)
def __setitem__(self, item, value):
if isinstance(value,dict):
_value = MyDict(value)
else:
_value = value
print("You are changing the value of {} to {}!!".format(item, _value))
super().__setitem__(item, _value)
```
You can then do the following:
```
# Simple initialization using a normal dict synthax
my_dict = MyDict({'a': {'b': 1}})
# update example
my_dict['c'] = {'d':{'e':4}}
```
>
> You are changing the value of c to {'d': {'e': 4}}!!
>
>
>
```
my_dict['a']['b'] = 2
my_dict['c']['d']['e'] = 6
```
>
> You are changing the value of b to 2!!
>
>
> You are changing the value of e to 6!!
>
>
> | You can write an adapter class that automatically wraps values in itself, like this (untested, but I think it illustrates the point):
```
class DictChangeListenerAdapter:
def __init__(self, original, listener):
self._original = original
self._listener = listener
def __getitem__(self, key):
value = self._original.__getitem__(key)
if isinstance(value, dict):
return DictChangeListenerAdapter(self._original[key], self._listener)
else:
return value
def __setitem__(self, key, value):
self._original.__setitem__(key, value)
self._listener(self, key, value)
```
Note that this is going to cause access to the wrapped items to be much more expensive, use with care. |
8,662,887 | I've read that subprocess should be used but all the examples i've seen on it shows that it runs only command-line commands. I want my program to run a python command along with another command. The command i want to run is to send an email to a user while a user plays a game i created. i have to have the python commands run at the same time because without doing so nothing else in the game can happen before the email is finished sending so it lags the game. Please help and any input is appreciated. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8662887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1082837/"
] | It sounds like you are looking for threading, which is a relatively deep topic, but this should help you get started: <http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/> | Threading is talked about in another answer, but you can get basically what you want by using subprocess's Popen command: <http://docs.python.org/library/subprocess.html#subprocess.Popen>
What you'll basically want is this (assuming proc is initialized somewhere in the game loop):
```
#...game code here...
args = [command_name_as_string, arg_1_to_command, arg_2_to_command, etc.]
proc = subprocess.Popen(args)
```
Then, you'll go back to your game loop. At some point in the game loop, you can put in something like this:
```
if proc:
proc.poll()
if proc.returncode:
#...do whatever you want with the process output here, which can
# be accessed with proc.stdin, proc.stderr, and so on...
proc = None
``` |
23,434,748 | I hate Recursive right now. Any way does any one know how to find square root using recursive solution on python. Or at least break it down to simple problems. All examples I found are linear only using one argument in the function. My function needs square Root(Number, low Guess, high Guess, Accuracy) I think the accuracy is supposed to be the base case but I just can't figure out the recursive part.
This is what I have tried:
```
L = 1
H = 3
def s(n,L,H):
if (((L + H)/2)**2) <= 0.05:
print(((L + H)/2))
else:
if (((L + H)/2)**2) > 2:
L = (L + H)/2
return s(n,L,H)
else:
H = (L + H)/2
return s(n,J,H)
``` | 2014/05/02 | [
"https://Stackoverflow.com/questions/23434748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597291/"
] | Remove the timeout setting:
```
rm config/initializers/timeout.rb
```
Heroku times-out all requests at 30 seconds but the process will continue running in the background.
If you want to avoid that, re-add the line above but [put rack-timeout in your Gemfile](https://github.com/heroku/rack-timeout). | I would suggest trying the following:
```
heroku labs:enable user-env-compile
```
If this fails, you could always precompile your production assets, add them to your codebase and push them to heroku yourself.
```
RAILS_ENV=production rake assets:precompile
git add .
git commit -m 'serving up my precompiled assets'
git push origin master
git push origin heroku
``` |
23,434,748 | I hate Recursive right now. Any way does any one know how to find square root using recursive solution on python. Or at least break it down to simple problems. All examples I found are linear only using one argument in the function. My function needs square Root(Number, low Guess, high Guess, Accuracy) I think the accuracy is supposed to be the base case but I just can't figure out the recursive part.
This is what I have tried:
```
L = 1
H = 3
def s(n,L,H):
if (((L + H)/2)**2) <= 0.05:
print(((L + H)/2))
else:
if (((L + H)/2)**2) > 2:
L = (L + H)/2
return s(n,L,H)
else:
H = (L + H)/2
return s(n,J,H)
``` | 2014/05/02 | [
"https://Stackoverflow.com/questions/23434748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3597291/"
] | It looks like your problem is actually related to `Rack::Timeout` and not asset compilation.
```
uninitialized constant Rack::Timeout
/tmp/build_d3989303-c1d8-4020-9b98-eb9e1834f0d0/config/initializers/timeout.rb:1:in `<top (required)>'
```
Have you included the rack-timeout gem in your gemfile? And ran `bundle install` after that?
```
gem "rack-timeout"
``` | I would suggest trying the following:
```
heroku labs:enable user-env-compile
```
If this fails, you could always precompile your production assets, add them to your codebase and push them to heroku yourself.
```
RAILS_ENV=production rake assets:precompile
git add .
git commit -m 'serving up my precompiled assets'
git push origin master
git push origin heroku
``` |
28,551,263 | ```
import pygame
import time
pygame.mixer.init()
pygame.mixer.music.load('/home/bahara.mp3')
time.sleep(2)
pygame.mixer.music.play()
```
While compiling this code from terminal, no error is thrown, but I am unable to hear any music. But when executed line by line, the code is working fine.
Can you suggest a way to debug this? I am using Ubuntu 14.04 and python 2.7.6 | 2015/02/16 | [
"https://Stackoverflow.com/questions/28551263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4573517/"
] | Pygame requires an active display which you have not initialized. I suggest you try installing and using `mpg123` command line tool.
Install:
```
$ sudo apt-get install mpg123
```
Program:
```
import os, time
os.system('mpg123 /home/bahara.mp3')
``` | I'm going to post my earlier comment as an answer because I think it's worth trying if you want to retain pygame's ability to control the music player.
I suspect you're getting no sound because pygame is exiting as your script ends, whereas when you run line by line in a python terminal session pygame remains active. One way you could test this is by adding a loop after you start playing the file e.g. by checking the [get\_busy](http://www.pygame.org/docs/ref/music.html#pygame.mixer.music.get_busy) status:
```
import pygame
import time
pygame.mixer.init()
pygame.mixer.music.load('/home/bahara.mp3')
time.sleep(2)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
print "Song is playing"
time.sleep(1)
print "Song has finished"
```
Assuming this works, you'll still be able to use pygame's controls to play, pause etc.
Also, please note, as Malik and I have both pointed out, MP3 support is quite limited in pygame so you may want to try converting your files to ogg. |
40,739,504 | My project consists of a python script(.py file) which has following dependencies :
1) numpy
2) scipy
3) sklearn
4) opencv (cv2)
5) dlib
6) torch
and many more ...
That is , the python script imports all of the above.
In order to run this script I need to manually install all of the dependencies by running 'pip install' or 'sudo apt-get install' commands on bash.
For dependencies like dlib , opencv and torch I need to curl the respective repositories build them using cmake and then install .(Here again i need to apt-get install cmake).
As a result I run a lot of commands just get the setup ready to run one python .py script.
Is there anyway I can build all these dependencies , package them , and just install everything using one command ?
PS :- I am a beginner in python . So please forgive if my question seems silly .
Thanks !!
Manasi | 2016/11/22 | [
"https://Stackoverflow.com/questions/40739504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6864242/"
] | I know that this Response may be a bit late. However, even if you can't benefit from this information now, perhaps someone else who may be looking for a similar answer will stumble onto this posting one day.
You can use [py2exe](https://pypi.org/project/py2exe/) or [pyinstaller](https://pypi.org/project/PyInstaller/) Modules, along w/ the [conda](https://pypi.org/project/conda/) Package Manager to Package and Compile an Executable. You will also need to install [pywin32](https://github.com/mhammond/pywin32/releases), if you're working on the Windows Platform.
If your project includes Non-Python Dependencies, you may also want to take a look at [NSIS](http://nsis.sourceforge.net/Download) (Nullsoft Scriptable Install System). If you plan on running Python Scripts during the Unpacking/Installation process, the NSIS Website also has [NsPython Plugins](http://nsis.sourceforge.net/NsPython_plug-in) available, for that purpose.
I hope this helps to get you started! | In case of only python dependencies, use [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/).
In case of others, write a shell script which has all the installation commands. |
15,161,843 | i noticed some seemingly strange behaviour when trying to import a python module named rmod2 in different ways. if i start python from the directory where the *rmod2.py* file is located, it works fine. however, if i move the file to another folder where other modules are locate, it doesn't work as expected anymore.
the module/package folder is */usr/lib/pymodules/python2.7* and it is also contained in the *sys.path*. so i've created the folder */usr/lib/pymodules/python2.7/rmod2* and put an empty *\_\_init\_\_.py* and the *rmod2.py* in there. if i don't have the *\_\_init\_\_.py* i get:
```
>>> import rmod2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named rmod2
```
with the *\_\_init\_\_.py* file, the import seems to work, but the package is empty:
```
>>> import rmod2
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'rmod2']
>>> dir(rmod2)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> rmod2.__path__
['/usr/lib/pymodules/python2.7/rmod2']
>>> rmod2.__file__
'/usr/lib/pymodules/python2.7/rmod2/__init__.py'
```
can someone tell me what's going on, and how to fix it to actually load the module contents when importing? | 2013/03/01 | [
"https://Stackoverflow.com/questions/15161843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2124120/"
] | APK will be generated under \bin\ folder once you run your app for the first time.
Connect your Android device to dev machine via USB cable (assuming you got Android SDK etc installed), right click on Android project and do Run as->Android app.
The app will be installed and started on Android device. APK will be generated in \bin folder.
In general, you don't need the device, same thing can be done with emulator. | You can also do an export on the android application project. This is what you would do if you are looking at doing some key signing. This is the way you would want to export it if you are uploading to Google play or an enterprise app store.
Keep in mind, Worklight doesn't build your .ipa, .apk, or etc. It builds you compile ready resources. It will build you the folder structure and the project layers needed to build in the corresponding Native Environment (for apple, you would export to xcode, build it, and run). |
44,204,937 | I am trying to change the behavior of python's `int` class, but I'm not sure if it can be done using pure python. Here is what I tried so far:
```
import builtins
class int_new(builtins.int):
def __eq__(self, other):
return True
int = int_new
print(5 == 6) # the result is False, but I'm anticipating True
``` | 2017/05/26 | [
"https://Stackoverflow.com/questions/44204937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7416363/"
] | You should replace last line with:
```
print(int(5) == int(6))
```
to force/ask Python to use your new class for integer numbers. | A year later I finally learned what I was wondering. When I was learning Python, I was not exposed to the idea of what a primitive type is. After learning C++ I realized that I was actually wondering if it is possible to replace primitive type with other custom types. The answer is obviously no. |
38,909,362 | I'm working with International Phonetic Alphabet (IPA) symbols in my Python program, a rather strange set of characters whose UTF-8 codes can range anywhere from 1 to 3 bytes long. [This thread](https://stackoverflow.com/questions/7291120/python-and-unicode-code-point-extraction) from several years ago basically asked the reverse question and it seems that `ord(character)` can retrieve a decimal number that I could convert to hex and thereafter to a code point, but the input for `ord()` seems to be limited to one byte. If I try `ord()` on any non-ASCII character, like `ɨ` for example, it outputs:
```
TypeError: ord() expected a character, but a string of length 2 found
```
With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a `unicode` type?) I don't mean by just manually looking it up on a Unicode table, either. | 2016/08/12 | [
"https://Stackoverflow.com/questions/38909362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6707199/"
] | >
> With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a unicode type?) I don't mean by just manually looking it up on a Unicode table, either.
>
>
>
You can only find the unicode code point of a unicode object. To convert your byte string to a unicode object, decode it using `mystr.decode(encoding)`, where `encoding` is the encoding of your string. (You know the encoding of your string, right? It's probably UTF-8. :-) Then you can use `ord` according to the instructions you already found.
```
>>> ord(b"ɨ".decode('utf-8'))
616
```
As an aside, from your question it sounds like you're working with the strings in their UTF-8 encoded bytes form. That's probably going to be a pain. You should decode the strings to unicode objects as soon as you get them, and only encode them if you need to output them somewhere. | ```
>>> u'ɨ'
u'\u0268'
>>> u'i'
u'i'
>>> 'ɨ'.decode('utf-8')
u'\u0268'
``` |
38,909,362 | I'm working with International Phonetic Alphabet (IPA) symbols in my Python program, a rather strange set of characters whose UTF-8 codes can range anywhere from 1 to 3 bytes long. [This thread](https://stackoverflow.com/questions/7291120/python-and-unicode-code-point-extraction) from several years ago basically asked the reverse question and it seems that `ord(character)` can retrieve a decimal number that I could convert to hex and thereafter to a code point, but the input for `ord()` seems to be limited to one byte. If I try `ord()` on any non-ASCII character, like `ɨ` for example, it outputs:
```
TypeError: ord() expected a character, but a string of length 2 found
```
With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a `unicode` type?) I don't mean by just manually looking it up on a Unicode table, either. | 2016/08/12 | [
"https://Stackoverflow.com/questions/38909362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6707199/"
] | This is actually a bug in Python 2, depending on how it was built, for unicode characters outside the BMP (>= 0xFFFF); see: <https://bugs.python.org/issue8670#msg105656>
For example this works:
```
>>> ord('\uffff')
65535
>>> len('\uffff')
1
```
But this does not:
```
>>> ord(u'\U00010000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
```
And even more surprisingly:
```
>>> len(u'\U00010000')
2
```
This is because there used to be "narrow" builds of Python versus "wide" builds. In "narrow" builds, unicode strings are represented internally with UCS2 (and thus use less memory, but have to use two UCS2 characters ("surrogate pairs") to represent characters above U+FFFF), whereas in "wide" builds UCS4 is used internally for unicode strings and you won't have this problem.
In newer versions of Python 3 (I think since 3.2 or 3.3 but I can't remember) this is no longer a problem and the situation is much better. The easiest way to check is with `sys.maxunicode` which will be `0xffff` on narrow builds.
[This answer](https://stackoverflow.com/a/7291240/982257) demonstrates how to extract the ordinal from surrogate pairs in narrow builds. | ```
>>> u'ɨ'
u'\u0268'
>>> u'i'
u'i'
>>> 'ɨ'.decode('utf-8')
u'\u0268'
``` |
38,909,362 | I'm working with International Phonetic Alphabet (IPA) symbols in my Python program, a rather strange set of characters whose UTF-8 codes can range anywhere from 1 to 3 bytes long. [This thread](https://stackoverflow.com/questions/7291120/python-and-unicode-code-point-extraction) from several years ago basically asked the reverse question and it seems that `ord(character)` can retrieve a decimal number that I could convert to hex and thereafter to a code point, but the input for `ord()` seems to be limited to one byte. If I try `ord()` on any non-ASCII character, like `ɨ` for example, it outputs:
```
TypeError: ord() expected a character, but a string of length 2 found
```
With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a `unicode` type?) I don't mean by just manually looking it up on a Unicode table, either. | 2016/08/12 | [
"https://Stackoverflow.com/questions/38909362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6707199/"
] | >
> With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a unicode type?) I don't mean by just manually looking it up on a Unicode table, either.
>
>
>
You can only find the unicode code point of a unicode object. To convert your byte string to a unicode object, decode it using `mystr.decode(encoding)`, where `encoding` is the encoding of your string. (You know the encoding of your string, right? It's probably UTF-8. :-) Then you can use `ord` according to the instructions you already found.
```
>>> ord(b"ɨ".decode('utf-8'))
616
```
As an aside, from your question it sounds like you're working with the strings in their UTF-8 encoded bytes form. That's probably going to be a pain. You should decode the strings to unicode objects as soon as you get them, and only encode them if you need to output them somewhere. | This is actually a bug in Python 2, depending on how it was built, for unicode characters outside the BMP (>= 0xFFFF); see: <https://bugs.python.org/issue8670#msg105656>
For example this works:
```
>>> ord('\uffff')
65535
>>> len('\uffff')
1
```
But this does not:
```
>>> ord(u'\U00010000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
```
And even more surprisingly:
```
>>> len(u'\U00010000')
2
```
This is because there used to be "narrow" builds of Python versus "wide" builds. In "narrow" builds, unicode strings are represented internally with UCS2 (and thus use less memory, but have to use two UCS2 characters ("surrogate pairs") to represent characters above U+FFFF), whereas in "wide" builds UCS4 is used internally for unicode strings and you won't have this problem.
In newer versions of Python 3 (I think since 3.2 or 3.3 but I can't remember) this is no longer a problem and the situation is much better. The easiest way to check is with `sys.maxunicode` which will be `0xffff` on narrow builds.
[This answer](https://stackoverflow.com/a/7291240/982257) demonstrates how to extract the ordinal from surrogate pairs in narrow builds. |
61,902,162 | I am working with Python version 2.7 and boto3 , but cannot import boto3 library .
My Python path is
```
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
```
When I look under
```
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
```
I see boto3 installed . But I keep getting this error
```
import boto3
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/boto3/__init__.py", line 16, in <module>
from boto3.session import Session
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/boto3/session.py", line 14, in <module>
import copy
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py", line 60, in <module>
from org.python.core import PyStringMap
File "/Users/user/git_repos/aws-boto3/org.py", line 7, in <module>
client = boto3.client('organizations')
AttributeError: 'module' object has no attribute 'client'
```
Python version: 2.7
boto3 Version: 1.13.13
botocore Version: 1.16.13
What am I missing?
Here is the code
```
import boto3
print('hello')
```
Note that from a python commandline I can import boto3 this fails when I run `python hello.py` | 2020/05/19 | [
"https://Stackoverflow.com/questions/61902162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3987161/"
] | You may be more familiar and comfortable with the `map` function from its common use in `Iterator`s but using `map` to work with `Result`s and `Option`s is also considered idiomatic in Rust. If you'd like to make your code more concise you can use [`map_or`](https://doc.rust-lang.org/std/result/enum.Result.html#method.map_or) like so:
```rust
let is_dir = entry.file_type().map_or(false, |t| t.is_dir());
``` | Alternatively, if you find the `map` unclear, you could use an `if` or `match` to be more explicit (and verbose):
```
let is_dir = if let Ok(file_type) = entry.file_type() {
file_type.is_dir()
} else {
false
};
```
or
```
let is_dir = match entry.file_type() {
Ok(file_type) => file_type.is_dir(),
_ => false,
};
```
Not necessarily better or worse, but an option available to you :) |
72,289,828 | I have source of truth stored in yaml file sot-inventory.yaml
```
- Hostname: NY-SW1
IP mgmt address: 10.1.1.1
OS: IOS
Operational status: Install
Role of work: Switch
Site: New_York
- Hostname: MI-SW1
IP mgmt address: 11.1.1.1
OS: NX-OS
Operational status: Install
Role of work: Switch
Site: Maiami
- Hostname: PA-SW1
IP mgmt address: 12.1.1.1
OS: Arista
Operational status: Install
Role of work: Witch
Site: Paris
```
I would like to get yaml ansible hosts inventory from file above with python script like this:
hosts.yaml
```
---
new_york:
hosts:
ny-sw1:
ansible_host: 10.1.1.1
os: ios
'role of work': switch
maiami:
hosts:
mi-sw1:
ansible_host: 11.1.1.1
os: nxos
'role of work': switch
paris:
hosts:
pa-sw1:
ansible_host: 12.1.1.1
os: arista
'role of work': switch
```
Could someone give an advice - which python structure or sample of scrypt may help to automate this staff? | 2022/05/18 | [
"https://Stackoverflow.com/questions/72289828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19145073/"
] | The **X.509 Client Certificate** option which is part of the docker plugin, has recently changed its name as it used to be named **Docker Certificate Directory** (the behavior itself has not changed), therefore is it is tricky to find it in the `withCredentials` [Documentation](https://www.jenkins.io/doc/pipeline/steps/credentials-binding/).
The option you are looking for is called `dockerCert` (named after the old option) and it includes two parameter inputs `variable` and `credentialsId`:
>
> *dockerCert*
>
> **variable**
> Name of an environment variable to be set during the build.
>
> Its value will be the absolute path of the directory where the {ca,cert,key}.pem files will be created.
> You probably want to call this variable DOCKER\_CERT\_PATH, which will be understood by the docker client binary.
>
> *Type: String*
>
> **credentialsId**
> Credentials of an appropriate type to be set to the variable.
>
> *Type: String*
>
>
>
Pipeline usage example:
```groovy
withCredentials([dockerCert(credentialsId: 'myClientCert', variable: 'DOCKER_CERT_PATH')]) {
// code that uses the certificate files
}
``` | On my Jenkins, it's
```
withCredentials([certificate(aliasVariable: 'ALIAS_VAR',
credentialsId: 'myClientCert',
keystoreVariable: 'KEYSTORE_VAR',
passwordVariable: 'PASSWORD_VAR')]) {
...
}
```
Hint: If you add `/pipeline-syntax/` to your Jenkins URL, it will take you to a snippet generator that will generate some snippets for you based on your input. That's what I used to generate the above snippet. |
57,218,302 | I have a an excel sheet with one column, the header is Name and the row below it says Jerry. All i want to do is append to this using python with the header: Age then a row below that saying e.g. 14.
How do i do this?
```
with open('simpleexcel.csv', 'r') as f_input: # Declared variable f_input to open and read the input file
input_reader = csv.reader(f_input) # this will iterate ober lines from input file
with open('Outputfile.csv', "w", newline='') as f_output: # opens a file for qwriting in this case outputfile
line_writer = csv.writer(f_output) #If csvfile is a file object, it should be opened with newline=''
for line in input_reader: #prints every row
line_writer.writerow(line+['14'])
```
instead i get 14 and 14 i do not know how i get another header
What i have to start with is
```
Name
Jerry
```
what i would like is:
```
Name Age
Jerry 14
```
Instead i get:
```
Name 14
Jerry 14
```
how can i ammend my above code? | 2019/07/26 | [
"https://Stackoverflow.com/questions/57218302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6714667/"
] | Use `next(input_reader)` to get the header and then append the new column name and write it back to csv.
**Ex:**
```
with open('simpleexcel.csv', 'r') as f_input: # Declared variable f_input to open and read the input file
input_reader = csv.reader(f_input) # this will iterate ober lines from input file
with open('Outputfile.csv', "w", newline='') as f_output: # opens a file for qwriting in this case outputfile
line_writer = csv.writer(f_output) #If csvfile is a file object, it should be opened with newline=''
line_writer.writerow(next(input_reader) + ["Age"])) #Write Header
for line in input_reader: #prints every row
line_writer.writerow(line+['14'])
``` | I don't know what you are trying to accomplish here but for your sample case this can be used.
```
import csv
with open('simpleexcel.csv', 'r') as f_input:
input_reader = list(csv.reader(f_input))
input_reader[0].append('Age')
for row in input_reader[1:]:
row.append(14)
with open('Outputfile.csv', "w", newline='') as f_output:
csv.writer(f_output).writerows(input_reader)
```
**Input:**
```
Name
Jerry
```
**Output:**
```
Name,Age
Jerry,14
``` |
66,948,944 | I managed to find python code that defines a LinkedList class and all the defacto methods in it but quite can't figure out what each line of code does...Can someone comment on it explaining what each line does so i can grasp a better understanding of LinkedLists in python?
```
class Node:#what is the significance of a node
def __init__(self, data, next):#why these parameters
self.data = data
self.next = next
class LinkedList:
def __init__(self):#what is a head
self.head = None
def add_at_front(self, data):
self.head = Node(data, self.head)
def add_at_end(self, data):
if not self.head:#what is it checking
self.head = Node(data, None)
return#what is it returning
curr = self.head
while curr.next:
curr = curr.next
curr.next = Node(data, None)
def get_last_node(self):
n = self.head
while(n.next != None):
n = n.next
return n.data
def is_empty(self):#i understand this method
return self.head == None
def print_list(self):#i also undertsnad this one
n = self.head
while n != None:#what is this loop doing
print(n.data, end = " => ")
n = n.next
print()
s = LinkedList()
s.add_at_front(5)
s.add_at_end(8)
s.add_at_front(9)
s.print_list()
print(s.get_last_node())
``` | 2021/04/05 | [
"https://Stackoverflow.com/questions/66948944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Usually people use macros to append `__LINE__` to the declaration to allow for multiple declarations in one scope block.
Prior to C++20 this was impossible without macros. C++20 and later, with a little work, can use [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location).
Jason Turner has a video on it in his C++ weekly video series [here](https://www.youtube.com/watch?v=TAS85xmNDEc) | I was initially not sure to grasp the advantage of that macro, apart hiding the timer instance name (and cause possible conflicts).
But I think that the intent could be to have the possibility to do this:
```
#ifdef _DEBUG
#define SCOPED_TIMER(slot) ScopedTimer __scopedTimer( slot );
#else
#define SCOPED_TIMER(slot) ;
#endif
```
That would indeed save some keystrokes; otherwise, if the timing takes place also in release builds, I would simply use directly the macro definition; either way, I would get rid of the initial underscores in the object name (that are conventionally reserved for compiler implementers):
```
ScopedTimer scoped_timer( some_magic_slot_number );
``` |
7,456,630 | I have a python REST API server running on my laptop. I am trying to write a rest client in Android (using Eclipse ADT etc) to contact it using Apache's client (org.apache.http.client) libraries.
The code is really simple, and basically does the following -
```
HttpGet httpget = new HttpGet(new URI("http://10.0.2.2:8000/user?username=tim"));
HttpResponse response = httpclient.execute(httpget);
```
However at execute, it exceptions out with a time out exception. I cannot hit the URL even from the browser in the emulator.
Details of the exception
```
org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.2.2:8000 timed out
```
However, I tried using the cREST client on Chrome on my laptop, and I am able to query the REST server fine. | 2011/09/17 | [
"https://Stackoverflow.com/questions/7456630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856919/"
] | I was gonna post this code sample:
```
Process rsyncProc = Runtime.exec ("rsync");
OutputStreanm rsyncStdIn = rsyncProv.getOutputStream ();
rsyncStdIn.write ("password".getBytes ());
```
But [Vineet Reynolds](https://stackoverflow.com/users/3916/vineet-reynolds) was ahead of me.
As Vineet Reynolds pointed out using such approach will require an additional piece of code to detect when rsync requires a password. So using an external password file seems to be an easier way.
P.S.: There may be a problem related to the encoding, it can by solved by converting the string to a byte array using appropriate encoding as described [here](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#getBytes(java.lang.String)).
P.P.S.: It seems that I can't yet comment an answer, so I had to post a new one. | You can write to the output stream of the `Process`, to pass in any inputs. However, this will require you to have knowledge of `rsync`'s behavior, for you must write the password to the outputstream only when the password prompt is detected (by reading the input stream of the `Process`).
You may however, create a non-world readable password file, and pass the location of this password file using the `--password-file` option when you launch the `rsync` process from Java. |
7,456,630 | I have a python REST API server running on my laptop. I am trying to write a rest client in Android (using Eclipse ADT etc) to contact it using Apache's client (org.apache.http.client) libraries.
The code is really simple, and basically does the following -
```
HttpGet httpget = new HttpGet(new URI("http://10.0.2.2:8000/user?username=tim"));
HttpResponse response = httpclient.execute(httpget);
```
However at execute, it exceptions out with a time out exception. I cannot hit the URL even from the browser in the emulator.
Details of the exception
```
org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.2.2:8000 timed out
```
However, I tried using the cREST client on Chrome on my laptop, and I am able to query the REST server fine. | 2011/09/17 | [
"https://Stackoverflow.com/questions/7456630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856919/"
] | You can write to the output stream of the `Process`, to pass in any inputs. However, this will require you to have knowledge of `rsync`'s behavior, for you must write the password to the outputstream only when the password prompt is detected (by reading the input stream of the `Process`).
You may however, create a non-world readable password file, and pass the location of this password file using the `--password-file` option when you launch the `rsync` process from Java. | Need not wait till the password is requested to write it to the stream. Make use of a BufferedWriter instead.
```
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream())
);
writer.write(passwd, 0, passwd.length());
writer.newLine();
writer.close();
```
This must work. |
7,456,630 | I have a python REST API server running on my laptop. I am trying to write a rest client in Android (using Eclipse ADT etc) to contact it using Apache's client (org.apache.http.client) libraries.
The code is really simple, and basically does the following -
```
HttpGet httpget = new HttpGet(new URI("http://10.0.2.2:8000/user?username=tim"));
HttpResponse response = httpclient.execute(httpget);
```
However at execute, it exceptions out with a time out exception. I cannot hit the URL even from the browser in the emulator.
Details of the exception
```
org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.2.2:8000 timed out
```
However, I tried using the cREST client on Chrome on my laptop, and I am able to query the REST server fine. | 2011/09/17 | [
"https://Stackoverflow.com/questions/7456630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856919/"
] | I was gonna post this code sample:
```
Process rsyncProc = Runtime.exec ("rsync");
OutputStreanm rsyncStdIn = rsyncProv.getOutputStream ();
rsyncStdIn.write ("password".getBytes ());
```
But [Vineet Reynolds](https://stackoverflow.com/users/3916/vineet-reynolds) was ahead of me.
As Vineet Reynolds pointed out using such approach will require an additional piece of code to detect when rsync requires a password. So using an external password file seems to be an easier way.
P.S.: There may be a problem related to the encoding, it can by solved by converting the string to a byte array using appropriate encoding as described [here](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#getBytes(java.lang.String)).
P.P.S.: It seems that I can't yet comment an answer, so I had to post a new one. | Took me some time, but here it goes:
```
Process ssh = Runtime.getRuntime ().exec (new String[] {"rsync", ... /*other arguments*/});
Reader stdOut = new InputStreamReader (ssh.getInputStream (), "US-ASCII");
OutputStream stdIn = ssh.getOutputStream ();
char[] passRequest = new char[128];//Choose it big enough for rsync password request and all that goes before it
int len = 0;
while (true)
{
len += stdOut.read (passRequest, len, passRequest.length - len);
if (new String (passRequest, 0, len).contains ("password:")) break;
}
System.out.println ("Password requested");
stdIn.write ("your_password\n".getBytes ("US-ASCII"));
stdIn.flush ();
```
P.S.: I don't really know how rsync works, so you may need to change it a bit - just run rsync manually from a terminal an see how exactly it requests a password. |
7,456,630 | I have a python REST API server running on my laptop. I am trying to write a rest client in Android (using Eclipse ADT etc) to contact it using Apache's client (org.apache.http.client) libraries.
The code is really simple, and basically does the following -
```
HttpGet httpget = new HttpGet(new URI("http://10.0.2.2:8000/user?username=tim"));
HttpResponse response = httpclient.execute(httpget);
```
However at execute, it exceptions out with a time out exception. I cannot hit the URL even from the browser in the emulator.
Details of the exception
```
org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.2.2:8000 timed out
```
However, I tried using the cREST client on Chrome on my laptop, and I am able to query the REST server fine. | 2011/09/17 | [
"https://Stackoverflow.com/questions/7456630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856919/"
] | I was gonna post this code sample:
```
Process rsyncProc = Runtime.exec ("rsync");
OutputStreanm rsyncStdIn = rsyncProv.getOutputStream ();
rsyncStdIn.write ("password".getBytes ());
```
But [Vineet Reynolds](https://stackoverflow.com/users/3916/vineet-reynolds) was ahead of me.
As Vineet Reynolds pointed out using such approach will require an additional piece of code to detect when rsync requires a password. So using an external password file seems to be an easier way.
P.S.: There may be a problem related to the encoding, it can by solved by converting the string to a byte array using appropriate encoding as described [here](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#getBytes(java.lang.String)).
P.P.S.: It seems that I can't yet comment an answer, so I had to post a new one. | Need not wait till the password is requested to write it to the stream. Make use of a BufferedWriter instead.
```
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream())
);
writer.write(passwd, 0, passwd.length());
writer.newLine();
writer.close();
```
This must work. |
7,456,630 | I have a python REST API server running on my laptop. I am trying to write a rest client in Android (using Eclipse ADT etc) to contact it using Apache's client (org.apache.http.client) libraries.
The code is really simple, and basically does the following -
```
HttpGet httpget = new HttpGet(new URI("http://10.0.2.2:8000/user?username=tim"));
HttpResponse response = httpclient.execute(httpget);
```
However at execute, it exceptions out with a time out exception. I cannot hit the URL even from the browser in the emulator.
Details of the exception
```
org.apache.http.conn.ConnectTimeoutException: Connect to /10.0.2.2:8000 timed out
```
However, I tried using the cREST client on Chrome on my laptop, and I am able to query the REST server fine. | 2011/09/17 | [
"https://Stackoverflow.com/questions/7456630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856919/"
] | Took me some time, but here it goes:
```
Process ssh = Runtime.getRuntime ().exec (new String[] {"rsync", ... /*other arguments*/});
Reader stdOut = new InputStreamReader (ssh.getInputStream (), "US-ASCII");
OutputStream stdIn = ssh.getOutputStream ();
char[] passRequest = new char[128];//Choose it big enough for rsync password request and all that goes before it
int len = 0;
while (true)
{
len += stdOut.read (passRequest, len, passRequest.length - len);
if (new String (passRequest, 0, len).contains ("password:")) break;
}
System.out.println ("Password requested");
stdIn.write ("your_password\n".getBytes ("US-ASCII"));
stdIn.flush ();
```
P.S.: I don't really know how rsync works, so you may need to change it a bit - just run rsync manually from a terminal an see how exactly it requests a password. | Need not wait till the password is requested to write it to the stream. Make use of a BufferedWriter instead.
```
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream())
);
writer.write(passwd, 0, passwd.length());
writer.newLine();
writer.close();
```
This must work. |
10,971,649 | >
> **Possible Duplicate:**
>
> [How to read specific characters from lines in a text file using python?](https://stackoverflow.com/questions/10968973/how-to-read-specific-characters-from-lines-in-a-text-file-using-python)
>
>
>
I have a .txt file with lines looking like this
>
> Water 16:-30.4674 1:-30.4759 17:-30.5373 7:-30.6892 8:-31.128
> 13:-31.393 2:-31.4036 9:-32.0214 5:-32.4387 12:-32.6972 14:-32.8345
> 4:-33.1583 3:-34.1308 15:-34.9566 11:-38.799 10:-51.471 6:-211.086
>
>
> Water 13:-33.3397 9:-33.511 12:-33.6573 17:-33.7629 5:-33.9539
> 3:-34.1326 7:-34.3554 15:-34.7484 8:-35.0615 2:-35.4279 11:-37.0607
> 16:-37.2666 1:-38.4928 14:-41.2152 4:-43.3593 10:-80.4689 6:-208.802
>
>
> Yawn 13:-36.4616 9:-37.1025 15:-37.2519 17:-38.8885 8:-39.1585
> 14:-39.8553 2:-40.2131 12:-41.2615 1:-41.6317 7:-41.8205 3:-41.9883
> 11:-43.8492 16:-46.8158 5:-49.8107 4:-52.5595 10:-70.4841 6:-220.906
>
>
>
What i need to do is store the numbers that are before '`:`' in an array.
what is the iterative way or the easyest way to do it?
```
f=open('path','r')
lines=f.readlines()
for line in lines:
...
```
and from here on i do not know the spliting and storing procedure... please help. | 2012/06/10 | [
"https://Stackoverflow.com/questions/10971649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447337/"
] | If the format is always the same you could do this for each line:
```
items = line.split()[1:]
items = [item.split(':')[0] for item in items]
```
And then if you want them as integers:
```
items = map(int, items)
```
As for storing them, create a list before iterating over each line `rows = []` and then you can add the items like this:
```
rows.append(items)
```
So all together it would look something like this:
```
f = open('path','r')
lines = f.readlines()
rows = []
for line in lines:
items = line.split()[1:]
items = [item.split(':')[0] for item in items]
items = map(int, items)
rows.append(items)
f.close()
print rows
``` | Use split method and append it to your array:
```
myArray=line.split(':-')
``` |
10,971,649 | >
> **Possible Duplicate:**
>
> [How to read specific characters from lines in a text file using python?](https://stackoverflow.com/questions/10968973/how-to-read-specific-characters-from-lines-in-a-text-file-using-python)
>
>
>
I have a .txt file with lines looking like this
>
> Water 16:-30.4674 1:-30.4759 17:-30.5373 7:-30.6892 8:-31.128
> 13:-31.393 2:-31.4036 9:-32.0214 5:-32.4387 12:-32.6972 14:-32.8345
> 4:-33.1583 3:-34.1308 15:-34.9566 11:-38.799 10:-51.471 6:-211.086
>
>
> Water 13:-33.3397 9:-33.511 12:-33.6573 17:-33.7629 5:-33.9539
> 3:-34.1326 7:-34.3554 15:-34.7484 8:-35.0615 2:-35.4279 11:-37.0607
> 16:-37.2666 1:-38.4928 14:-41.2152 4:-43.3593 10:-80.4689 6:-208.802
>
>
> Yawn 13:-36.4616 9:-37.1025 15:-37.2519 17:-38.8885 8:-39.1585
> 14:-39.8553 2:-40.2131 12:-41.2615 1:-41.6317 7:-41.8205 3:-41.9883
> 11:-43.8492 16:-46.8158 5:-49.8107 4:-52.5595 10:-70.4841 6:-220.906
>
>
>
What i need to do is store the numbers that are before '`:`' in an array.
what is the iterative way or the easyest way to do it?
```
f=open('path','r')
lines=f.readlines()
for line in lines:
...
```
and from here on i do not know the spliting and storing procedure... please help. | 2012/06/10 | [
"https://Stackoverflow.com/questions/10971649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447337/"
] | This is a job for regular expressions:
```
import re
with open(myFilePath, "r") as f:
text = f.read()
numbers = re.findall(r"(-?\d+):\S+", text)
```
The above is assuming that all of the numbers before the colons are integers. | Use split method and append it to your array:
```
myArray=line.split(':-')
``` |
10,971,649 | >
> **Possible Duplicate:**
>
> [How to read specific characters from lines in a text file using python?](https://stackoverflow.com/questions/10968973/how-to-read-specific-characters-from-lines-in-a-text-file-using-python)
>
>
>
I have a .txt file with lines looking like this
>
> Water 16:-30.4674 1:-30.4759 17:-30.5373 7:-30.6892 8:-31.128
> 13:-31.393 2:-31.4036 9:-32.0214 5:-32.4387 12:-32.6972 14:-32.8345
> 4:-33.1583 3:-34.1308 15:-34.9566 11:-38.799 10:-51.471 6:-211.086
>
>
> Water 13:-33.3397 9:-33.511 12:-33.6573 17:-33.7629 5:-33.9539
> 3:-34.1326 7:-34.3554 15:-34.7484 8:-35.0615 2:-35.4279 11:-37.0607
> 16:-37.2666 1:-38.4928 14:-41.2152 4:-43.3593 10:-80.4689 6:-208.802
>
>
> Yawn 13:-36.4616 9:-37.1025 15:-37.2519 17:-38.8885 8:-39.1585
> 14:-39.8553 2:-40.2131 12:-41.2615 1:-41.6317 7:-41.8205 3:-41.9883
> 11:-43.8492 16:-46.8158 5:-49.8107 4:-52.5595 10:-70.4841 6:-220.906
>
>
>
What i need to do is store the numbers that are before '`:`' in an array.
what is the iterative way or the easyest way to do it?
```
f=open('path','r')
lines=f.readlines()
for line in lines:
...
```
and from here on i do not know the spliting and storing procedure... please help. | 2012/06/10 | [
"https://Stackoverflow.com/questions/10971649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447337/"
] | If the format is always the same you could do this for each line:
```
items = line.split()[1:]
items = [item.split(':')[0] for item in items]
```
And then if you want them as integers:
```
items = map(int, items)
```
As for storing them, create a list before iterating over each line `rows = []` and then you can add the items like this:
```
rows.append(items)
```
So all together it would look something like this:
```
f = open('path','r')
lines = f.readlines()
rows = []
for line in lines:
items = line.split()[1:]
items = [item.split(':')[0] for item in items]
items = map(int, items)
rows.append(items)
f.close()
print rows
``` | This is a job for regular expressions:
```
import re
with open(myFilePath, "r") as f:
text = f.read()
numbers = re.findall(r"(-?\d+):\S+", text)
```
The above is assuming that all of the numbers before the colons are integers. |
14,574,595 | What I'm trying to do is make a gaussian function graph. then pick random numbers anywhere in a space say y=[0,1] (because its normalized) & x=[0,200]. Then, I want it to ignore all values above the curve and only keep the values underneath it.
```
import numpy
import random
import math
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from math import sqrt
from numpy import zeros
from numpy import numarray
variance = input("Input variance of the star:")
mean = input("Input mean of the star:")
x=numpy.linspace(0,200,1000)
sigma = sqrt(variance)
z = max(mlab.normpdf(x,mean,sigma))
foo = (mlab.normpdf(x,mean,sigma))/z
plt.plot(x,foo)
zing = random.random()
random = random.uniform(0,200)
import random
def method2(size):
ret = set()
while len(ret) < size:
ret.add((random.random(), random.uniform(0,200)))
return ret
size = input("Input number of simulations:")
foos = set(foo)
xx = set(x)
method = method2(size)
def undercurve(xx,foos,method):
Upper = numpy.where(foos<(method))
Lower = numpy.where(foos[Upper]>(method[Upper]))
return (xx[Upper])[Lower],(foos[Upper])[Lower]
```
When I try to print undercurve, I get an error:
```
TypeError: 'set' object has no attribute '__getitem__'
```
and I have no idea how to fix it.
As you can all see, I'm quite new at python and programming in general, but any help is appreciated and if there are any questions I'll do my best to answer them. | 2013/01/29 | [
"https://Stackoverflow.com/questions/14574595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1884319/"
] | The immediate cause of the error you're seeing is presumably this line (which should be identified by the full traceback -- it's generally quite helpful to post that):
```
Lower = numpy.where(foos[Upper]>(method[Upper]))
```
because the confusingly-named variable `method` is actually a `set`, as returned by your function `method2`. Actually, on second thought, `foos` is also a `set`, so it's probably failing on that first. Sets don't support indexing with something like `the_set[index]`; that's what the complaint about `__getitem__` means.
I'm not entirely sure what all the parts of your code are intended to do; variable names like "foos" don't really help like that. So here's how I might do what you're trying to do:
```
# generate sample points
num_pts = 500
sample_xs = np.random.uniform(0, 200, size=num_pts)
sample_ys = np.random.uniform(0, 1, size=num_pts)
# define distribution
mean = 50
sigma = 10
# figure out "normalized" pdf vals at sample points
max_pdf = mlab.normpdf(mean, mean, sigma)
sample_pdf_vals = mlab.normpdf(sample_xs, mean, sigma) / max_pdf
# which ones are under the curve?
under_curve = sample_ys < sample_pdf_vals
# get pdf vals to plot
x = np.linspace(0, 200, 1000)
pdf_vals = mlab.normpdf(x, mean, sigma) / max_pdf
# plot the samples and the curve
colors = np.array(['cyan' if b else 'red' for b in under_curve])
scatter(sample_xs, sample_ys, c=colors)
plot(x, pdf_vals)
```

Of course, you should also realize that if you only want the points under the curve, this is equivalent to (but much less efficient than) just sampling from the normal distribution and then randomly selecting a `y` for each sample uniformly from 0 to the pdf value there:
```
sample_xs = np.random.normal(mean, sigma, size=num_pts)
max_pdf = mlab.normpdf(mean, mean, sigma)
sample_pdf_vals = mlab.normpdf(sample_xs, mean, sigma) / max_pdf
sample_ys = np.array([np.random.uniform(0, pdf_val) for pdf_val in sample_pdf_vals])
``` | It's hard to read your code.. Anyway, you can't access a set using `[]`, that is, `foos[Upper]`, `method[Upper]`, etc are all illegal. I don't see why you convert `foo`, `x` into set. In addition, for a point produced by `method2`, say (x0, y0), it is very likely that x0 is not present in `x`.
I'm not familiar with numpy, but this is what I'll do for the purpose you specified:
```
def undercurve(size):
result = []
for i in xrange(size):
x = random()
y = random()
if y < scipy.stats.norm(0, 200).pdf(x): # here's the 'undercurve'
result.append((x, y))
return results
``` |
64,155,517 | I am trying to create a CSS grid, but it gets scattered when using width.
I want 3 posts on a row. I believe the problem might be with my border box. Only the desktop view is affected, mobile view looks perfectly normal.
I am using `width: 33.333%` to achieve the grid.
What is wrong with the CSS code?
```css
/*-----------------------------------------------------------------------*/
/* 1. Common Style */
/*-----------------------------------------------------------------------*/
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font: 400 14px / 1.8 "Whitney SSm A", "Whitney SSm B", "Helvetica Neue", "Helvetica", "Arial", sans-serif;
background: #FFFFFF;
color: #000;
padding-bottom: 10%;
}
@media screen and (min-width: 801px) and (max-width: 2000px) {
a {
color: #FFFFFF;
text-decoration: none;
}
.list-item-header {
letter-spacing: 0.15em;
text-transform: uppercase;
font-size: 11px;
font-weight: 400;
margin: 0 0 4px;
color: #555A72;
}
.list-item {
box-sizing: border-box;
padding-top: 50px;
padding-bottom: 50px;
text-align: left;
vertical-align: top;
position: relative;
z-index: 1;
width: 33.333%;
}
.list-item-body {
font-size: 14px;
font-weight: 300;
margin: 10px 0 0;
color: rgba(85, 90, 114, 0.9);
overflow: hidden;
margin-top: 10px;
margin-bottom: 20px;
}
.list-item-link {
font-weight: 300;
font-size: 13px;
display: inline-block;
position: relative;
margin-top: 5px;
color: blue;
}
.greed {
display: block;
padding: 60px;
}
li {
list-style: none;
width: 33.33%;
float: left;
padding: 30px;
}
.cont {
margin-left: auto;
margin-right: auto;
padding: auto;
}
.contt {
box-sizing: border-box;
max-width: 1064px;
}
l::after {
content: "";
position: absolute;
top: 0;
left: 35px;
right: 0;
border-top: solid 1px rgba(35, 31, 32, 0.25);
}
}
@media screen and (min-width: 400px) and (max-width: 800px) {
a {
color: #FFFFFF;
text-decoration: none;
}
.list-item-header {
letter-spacing: 0.15em;
text-transform: uppercase;
font-size: 11px;
font-weight: 400;
margin: 0 0 4px;
color: #555A72;
}
.list-item {
box-sizing: border-box;
padding-top: 50px;
padding-bottom: 50px;
text-align: left;
vertical-align: top;
position: relative;
z-index: 1;
width: 33.333%;
}
.list-item-body {
font-size: 14px;
font-weight: 300;
margin: 10px 0 0;
color: rgba(85, 90, 114, 0.9);
overflow: hidden;
margin-top: 10px;
margin-bottom: 20px;
}
.list-item-link {
font-weight: 300;
font-size: 13px;
display: inline-block;
position: relative;
margin-top: 5px;
color: blue;
}
.greed {
display: block;
padding: 60px;
}
li {
list-style: none;
float: left;
padding: 10px;
}
.cont {
margin-left: auto;
margin-right: auto;
padding: auto;
}
.contt {
box-sizing: border-box;
max-width: 1064px;
}
l::after {
content: "";
position: absolute;
top: 0;
left: 35px;
right: 0;
border-top: solid 1px rgba(35, 31, 32, 0.25);
}
}
```
```html
<!doctype html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="img/favicon.png" type="image/png">
<title>Blog posts</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="static/css/blog.css">
</head>
<body>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/django-database-relationship">
<h3 class="list-item-header">Django database relationship</h3>
<p class="list-item-body">
ForeignKey is only one-to-one if you specify ForeignKey(Dude, unique=True), so with the above code you will get a Dude with multiple PhoneNumbers. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/database-models-for-tables-reservation-and-customer">
<h3 class="list-item-header">Database Models for tables, reservation and customer</h3>
<p class="list-item-body">
Class Customer(models.Model): email = models.EmailField() # And whatever other custom fields here; maybe make a ForeignKey link to User? <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/python-package-basics">
<h3 class="list-item-header">Python package basics</h3>
<p class="list-item-body">
https://dzone.com/articles/executable-package-pip-install <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/flask-sitemap">
<h3 class="list-item-header">Flask sitemap</h3>
<p class="list-item-body">
Sitemap route @app . route ( '/sitemap.xml' , methods =[ 'GET' ]) def sitemap (): try : """Generate sitemap.xml. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/git-commands">
<h3 class="list-item-header">Git commands</h3>
<p class="list-item-body">
The following are git commands thm <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/creating-a-cicd-pipeline-with-jenkins-and-also-eks-clusters-through-aws-cloudformation-and-deploys-a">
<h3 class="list-item-header">Creating a CI/CD Pipeline with Jenkins and also EKS Clusters through AWS CloudFormation and deploys a Nginx image</h3>
<p class="list-item-body">
GitHub repo notes. Creating a CI/CD Pipeline with Jenkins and also EKS Clusters through AWS CloudFormation and deploys a Nginx image. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/navigation-menu-css-from-codepen">
<h3 class="list-item-header">Navigation menu CSS from codepen</h3>
<p class="list-item-body">
Navigation menu https://codepen.io/kirstenhumphreys/pen/vgaKmG Nav Bar https://codepen.io/MilanMilosev/pen/GJbGJq <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/creating-virtual-environments-for-python">
<h3 class="list-item-header">Creating virtual environments for python</h3>
<p class="list-item-body">
Steps in creating a virtual environment for a python project <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/push-empty-git-to-check-ci">
<h3 class="list-item-header">Push empty git to check ci</h3>
<p class="list-item-body">
Sometimes, you need to push a commit to Git purely to check if some CI thing is working. The allow-empty flag lets you push a <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/webscraping-with-python-for-data-collection">
<h3 class="list-item-header">Webscraping with Python for data collection</h3>
<p class="list-item-body">
What is webscraping <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
</body>
</html>
```
[](https://i.stack.imgur.com/Zna8r.png) | 2020/10/01 | [
"https://Stackoverflow.com/questions/64155517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6499765/"
] | You are better off using `flex-box` or `grid` for this. There are a few things with your code that needed to be changed:
1. You have `float` and `width` set on your inner `li` item. That doesn't work when it's a child element, so, the `li` was floating in relation to its parent `ul`.
2. You can move the padding on the `ul.greed` to the `.cont` element instead.
3. I wrapped all your code in a `wrapper` element that has `display: flex` so the `.cont` elements become flex children.
4. I adjusted the media query to make it a bit more readable.
5. You could simplify your HTML a ton as well, but I left it since it may be auto-generated.
```css
/*-----------------------------------------------------------------------*/
/* 1. Common Style */
/*-----------------------------------------------------------------------*/
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font: 400 14px / 1.8 "Whitney SSm A", "Whitney SSm B", "Helvetica Neue", "Helvetica", "Arial", sans-serif;
background: #FFFFFF;
color: #000;
padding-bottom: 10%;
}
.wrapper {
display: flex;
flex-wrap: wrap;
}
.cont {
flex: 0 0 100%;
padding: 20px;
}
a {
color: #FFFFFF;
text-decoration: none;
}
.list-item-header {
letter-spacing: 0.15em;
text-transform: uppercase;
font-size: 11px;
font-weight: 400;
margin: 0 0 4px;
color: #555A72;
}
.list-item-body {
font-size: 14px;
font-weight: 300;
margin: 10px 0 0;
color: rgba(85, 90, 114, 0.9);
overflow: hidden;
margin-top: 10px;
margin-bottom: 20px;
}
.list-item-link {
font-weight: 300;
font-size: 13px;
display: inline-block;
position: relative;
margin-top: 5px;
color: blue;
}
.greed {
display: block;
}
li {
padding: 30px;
list-style: none;
position: relative;
}
li::after {
content: "";
position: absolute;
top: 0;
left: 35px;
right: 0;
border-top: solid 1px rgba(35, 31, 32, 0.25);
}
@media (min-width: 801px) {
.cont {
flex: 0 0 33.33333%;
}
}
```
```html
<!doctype html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="img/favicon.png" type="image/png">
<title>Blog posts</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="static/css/blog.css">
</head>
<body>
<div class="wrapper">
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/django-database-relationship">
<h3 class="list-item-header">Django database relationship</h3>
<p class="list-item-body">
ForeignKey is only one-to-one if you specify ForeignKey(Dude, unique=True), so with the above code you will get a Dude with multiple PhoneNumbers. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/database-models-for-tables-reservation-and-customer">
<h3 class="list-item-header">Database Models for tables, reservation and customer</h3>
<p class="list-item-body">
Class Customer(models.Model): email = models.EmailField() # And whatever other custom fields here; maybe make a ForeignKey link to User? <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/python-package-basics">
<h3 class="list-item-header">Python package basics</h3>
<p class="list-item-body">
https://dzone.com/articles/executable-package-pip-install <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/flask-sitemap">
<h3 class="list-item-header">Flask sitemap</h3>
<p class="list-item-body">
Sitemap route @app . route ( '/sitemap.xml' , methods =[ 'GET' ]) def sitemap (): try : """Generate sitemap.xml. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/git-commands">
<h3 class="list-item-header">Git commands</h3>
<p class="list-item-body">
The following are git commands thm <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/creating-a-cicd-pipeline-with-jenkins-and-also-eks-clusters-through-aws-cloudformation-and-deploys-a">
<h3 class="list-item-header">Creating a CI/CD Pipeline with Jenkins and also EKS Clusters through AWS CloudFormation and deploys a Nginx image</h3>
<p class="list-item-body">
GitHub repo notes. Creating a CI/CD Pipeline with Jenkins and also EKS Clusters through AWS CloudFormation and deploys a Nginx image. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/navigation-menu-css-from-codepen">
<h3 class="list-item-header">Navigation menu CSS from codepen</h3>
<p class="list-item-body">
Navigation menu https://codepen.io/kirstenhumphreys/pen/vgaKmG Nav Bar https://codepen.io/MilanMilosev/pen/GJbGJq <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/creating-virtual-environments-for-python">
<h3 class="list-item-header">Creating virtual environments for python</h3>
<p class="list-item-body">
Steps in creating a virtual environment for a python project <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/push-empty-git-to-check-ci">
<h3 class="list-item-header">Push empty git to check ci</h3>
<p class="list-item-body">
Sometimes, you need to push a commit to Git purely to check if some CI thing is working. The allow-empty flag lets you push a <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
<div class="cont contt">
<ul class="greed">
<li>
<a href="/blog/webscraping-with-python-for-data-collection">
<h3 class="list-item-header">Webscraping with Python for data collection</h3>
<p class="list-item-body">
What is webscraping <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</li>
</ul>
</div>
</div>
</body>
</html>
```
Simplified HTML
---------------
```css
/*-----------------------------------------------------------------------*/
/* 1. Common Style */
/*-----------------------------------------------------------------------*/
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font: 400 14px / 1.8 "Whitney SSm A", "Whitney SSm B", "Helvetica Neue", "Helvetica", "Arial", sans-serif;
background: #FFFFFF;
color: #000;
padding-bottom: 10%;
}
.wrapper {
display: flex;
flex-wrap: wrap;
}
.cont {
flex: 0 0 100%;
padding: 20px;
position: relative;
}
a {
color: #FFFFFF;
text-decoration: none;
}
.list-item-header {
letter-spacing: 0.15em;
text-transform: uppercase;
font-size: 11px;
font-weight: 400;
margin: 0 0 4px;
color: #555A72;
}
.list-item-body {
font-size: 14px;
font-weight: 300;
margin: 10px 0 0;
color: rgba(85, 90, 114, 0.9);
overflow: hidden;
margin-top: 10px;
margin-bottom: 20px;
}
.list-item-link {
font-weight: 300;
font-size: 13px;
display: inline-block;
position: relative;
margin-top: 5px;
color: blue;
}
.cont::after {
content: "";
position: absolute;
top: 0;
left: 35px;
right: 0;
border-top: solid 1px rgba(35, 31, 32, 0.25);
}
@media (min-width: 801px) {
.cont {
flex: 0 0 33.33333%;
}
}
```
```html
<!doctype html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="img/favicon.png" type="image/png">
<title>Blog posts</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="static/css/blog.css">
</head>
<body>
<div class="wrapper">
<div class="cont contt">
<a href="/blog/django-database-relationship">
<h3 class="list-item-header">Django database relationship</h3>
<p class="list-item-body">
ForeignKey is only one-to-one if you specify ForeignKey(Dude, unique=True), so with the above code you will get a Dude with multiple PhoneNumbers. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</div>
<div class="cont contt">
<a href="/blog/django-database-relationship">
<h3 class="list-item-header">Django database relationship</h3>
<p class="list-item-body">
ForeignKey is only one-to-one if you specify ForeignKey(Dude, unique=True), so with the above code you will get a Dude with multiple PhoneNumbers. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</div>
<div class="cont contt">
<a href="/blog/django-database-relationship">
<h3 class="list-item-header">Django database relationship</h3>
<p class="list-item-body">
ForeignKey is only one-to-one if you specify ForeignKey(Dude, unique=True), so with the above code you will get a Dude with multiple PhoneNumbers. <span class="list-item-link">
Read the post.
</span>
</p>
</a>
</div>
</div>
</body>
</html>
``` | I don't get why using that HTML strucure, it looks unnecessarily complicated!
Your problem is that the divs(.cont.contt) have a height and interacts with each other misaliging everything else, I don't think is a correct approach.
A partial solution might be to forse a height to 0 but is not clean at all.
I'd suggest to revist the strucure, maybe without using lists where not necessary or going directly with the [CSS Grid Layout](https://developer.mozilla.org/en-US/docs/Web/CSS/grid).
If I missed something let me know!
Have a nice day |
18,519,217 | When creating a string out of many substrings what is more pythonic - + or %?
```
big_string = string1 + string2 + ... + stringN
big_string = ''
for i in range(n):
big_string+=str(i)
```
or
```
big_string = "%s%s...%s" % (string1, string2, ... , stringN)
big_string = ''
for i in range(n):
big_string = "%s%s" % (big_string, str(i))
``` | 2013/08/29 | [
"https://Stackoverflow.com/questions/18519217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1445070/"
] | ```
big_string = ''.join([string1, string2, ..., stringN])
``` | `big_string = reduce(lambda x, y: x + y, [string1, string2, ..., stringN], "")` |
37,002,134 | I have just started to use Tensorflow and I have done "hello world" with my test.py file. Moving on to next step, I started to do tutorial(<https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html>).
This is what I have done
>
> $ git clone <https://github.com/tensorflow/tensorflow>
>
>
>
and run the file of "fully\_connected\_feed.py "
>
> python tensorflow/examples/tutorials/mnist/fully\_connected\_feed.py
>
>
>
I got the error like
>
> Traceback (most recent call last):
>
>
> File "tensorflow/examples/tutorials/mnist/fully\_connected\_feed.py",
>
>
> line 27, in
>
>
> from tensorflow.examples.tutorials.mnist import input\_data
>
>
> ImportError: No module named examples.tutorials.mnist
>
>
>
so I changed code from
>
> from tensorflow.examples.tutorials.mnist import input\_data
>
>
> from tensorflow.examples.tutorials.mnist import mnist
>
>
>
to
>
> import input\_data
>
>
> import mnist
>
>
>
but I got error again.
>
> Traceback (most recent call last):
>
>
> File "tensorflow/examples/tutorials/mnist/fully\_connected\_feed.py", line 27, in
>
>
> import input\_data
> File
>
>
> "/Users/naggi/Documents/ML/tensorflow/tensorflow/examples/tutorials/mnist/input\_data.py", line 29, in
>
>
> from tensorflow.contrib.learn.python.learn.datasets.mnist import read\_data\_sets
>
>
> ImportError: No module named contrib.learn.python.learn.datasets.mnist
>
>
>
Could someone help me?
Thanks | 2016/05/03 | [
"https://Stackoverflow.com/questions/37002134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6285272/"
] | You were pretty close with the `drop` function, but I suggest you take a look at its documentation. It drops the given number of elements from the beginning of the list.
What you actually want is `take` the first one and `takeRight` the last one:
```
mp.mapValues(list => list.take(1) ++ list.takeRight(1))
```
This is pretty ugly, however. If you are certain that your values are always a 3-element list, I suggest pattern matching just as I showed with tuples:
```
mp.mapValues {
case List(first, _, third) => List(first, third)
}
``` | It looks like your map has lists of tuples, not lists of strings. Something like this should work:
```
m.mapValues { case List((a,b,c)) => (a,c) }
```
or
```
m.mapValues { case List((a,b,c)) => List((a,c)) }
```
or
```
m.mapValues { case List((a,b,c)) => List(a,c) }
```
... depending on what type of output you want to end up with. |
10,713,966 | I am trying to migrate over to Python from Matlab and can't figure out how to get interactive(?) plotting working within the Spyder IDE. My test code is shown below. With the .ion() nothing happens, I get a quick flash of a figure being drawn then the window instantly closes and spits out my Hello. Without the .ion() the figure is drawn correctly but the script hangs and doesn't spit out Hello until I manually close the figure window. I would like the script to run like a matlab script would and plot the various figures I ask it to while chugging along any computations and putting the output on the terminal(?) window.
I tried typing out the lines one at a time in ipython and it seemed to work but I would much rather work in a script sheet format where I can go back and forth between lines tweaking code.
I'm working in windows 7 if that helps. I installed python(x,y) and am launching spyder from there (spyder version 2.1.9). I have seen some similar-ish questions asked but I wasn't able to solve this problem. It seemed to me that someone said ipythons latest version is not compatible with spyder but then I saw another post that said interactive plotting should be supported regardless. Thanks for the help! If anyone has alternative environments I could use to mimick matlab behaviour that would work too, I'm really new to Python.
```
import matplotlib.pylab as plt
plt.ion()
plt.plot([1,2,3])
plt.show()
plt.ylabel('This is an axis')
print ("Hello")
``` | 2012/05/23 | [
"https://Stackoverflow.com/questions/10713966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411736/"
] | The run configuration should be set to *Execute in current Python or IPython interpreter* which by default allows for interactive plotting. If the interpreter is set to *Execute in a new dedicated Python interpreter* then *Interact with the Python interpreter after execution* must be selected. | in my case, these were the default settings in spyder however it still didn't show the plot until I typed: **%matplotlib inline**
Not sure if this is helpful but thought of sharing here. |
25,858,331 | Is there a meaningful difference between
```
if self.pk is not None:
```
and
```
if self.pk:
```
when checking a model field in python django?
Other languages have all kinds of differing 'correct' ways to check for a variable being null, empty, nonexistant, whatever.
a) I don't know how python handles the check
b) I don't know if this is important and / or meaningful in the context of django model fields | 2014/09/15 | [
"https://Stackoverflow.com/questions/25858331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3539965/"
] | The first check is checking that the primary key is not [`None`](https://docs.python.org/3/library/constants.html#None). The second is checking that the primary key is [truthy](https://docs.python.org/3/library/stdtypes.html#truth-value-testing). So yes, there is a difference. | `Pk` is a [property](https://github.com/django/django/blob/1.7/django/db/models/base.py#L515) that usually resolves to `id`. There is no magic other than that.
So the only difference between the two statements is how Python treats them. The first one explicitely tests if `pk` is None, whereas the second one will pass for any ["falsy" value](https://docs.python.org/release/2.5.2/lib/truth.html) of `pk`.
Note that `pk` shouldn't usually evaluate to `False` unless the model instance is not saved to the database, so in practice the two statements should be pretty much equivalent. |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | The problem here is that `range(1, 11)` returns a list and `for...in` iterates over the list elements hence changing `i` to something else doesn't work as expected. Using a `while` loop should solve your problem. | Just some food for thought.
The for loop loops over an iterable. Create your own iterable that you can move forward yourself.
```
iterator = iter(range(11))
for i in iterator:
print 'for i = ', i
try:
print 'next()', iterator.next()
except StopIteration:
continue
>>> foo()
for i = 0
next() 1
for i = 2
next() 3
for i = 4
next() 5
for i = 6
next() 7
for i = 8
next() 9
for i = 10
next()
>>>
```
xrange() is an iterating version of range()
iterable = xrange(11) would behave as an iterator.
itertools provides nice functions like dropwhile <http://docs.python.org/library/itertools.html#itertools.dropwhile>
This can proceed your iterator for you.
```
from itertools import dropwhile
iterator = iter(range(11))
for i in iterator:
if i == 3:
i = dropwhile(lambda x: x<8, iterator).next()
print 'i = ', i
>>> foo()
i = 0
i = 1
i = 2
i = 8
i = 9
i = 10
>>>
```
dropwhile could be called outside your loop to create the iterator over your iteratator.
Then you can simply call next() on it. Since the for loop and the dropwhile are both calling next() on the same iterator you have some control over it.
You could also implement your own iterator that uses send() to allow you to manipulate the iterator.
<http://onlamp.com/pub/a/python/2006/10/26/python-25.html?page=2> |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | One possibility is that you want to skip items. Everything to do with looping over an index is ugly but here's a way to do that with a while loop.
```
i = 1
while i < 11:
if predicate(i):
i = 4
i += 1
```
---
It's better to loop over items of the list that you want to work with directly and just skip the items that you don't want to deal with.
```
for item in some_list_of_items:
if not predicate(item):
continue
do_something_with_item(item)
```
Or use a generator expression to filter the items
```
for item in (item for item in some_list_of_items if predicate(item)):
do_something_with_item(item)
```
--- | For this case, you may want to use *while loop* instead of *for loop* in Python.
For example:
```
i = 0
while i < 10:
if ...:
i = 4
``` |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | Python does not permit you to modify your looping variable inline. If you wish to do this you should do the following
```
i = 0
while i < 10:
if i == 3:
i = 7
print(i)
i += 1
```
This should have the effect you desire.
You can also do the following:
```
for i in range(10):
if 2 < i < 7:
continue
print(i)
```
Both have the same effect. | For this case, you may want to use *while loop* instead of *for loop* in Python.
For example:
```
i = 0
while i < 10:
if ...:
i = 4
``` |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | Python does not permit you to modify your looping variable inline. If you wish to do this you should do the following
```
i = 0
while i < 10:
if i == 3:
i = 7
print(i)
i += 1
```
This should have the effect you desire.
You can also do the following:
```
for i in range(10):
if 2 < i < 7:
continue
print(i)
```
Both have the same effect. | Mind you that is just a bad idea. Changing iteration variable inside a for loop? In my eyes thats equivalent to a goto statement.
Why don't you just ask what you want to accomplish?
* Do you want to filter collection? Use continue statement.
* Or do you want to repeat some things more times? Create a repeat loop inside.
* Do you want iteration in different order? Well prepare the order beforehand.
The while loop solutions that others posted are correct translations, but that is not a very good idea either. |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | Python does not permit you to modify your looping variable inline. If you wish to do this you should do the following
```
i = 0
while i < 10:
if i == 3:
i = 7
print(i)
i += 1
```
This should have the effect you desire.
You can also do the following:
```
for i in range(10):
if 2 < i < 7:
continue
print(i)
```
Both have the same effect. | Just some food for thought.
The for loop loops over an iterable. Create your own iterable that you can move forward yourself.
```
iterator = iter(range(11))
for i in iterator:
print 'for i = ', i
try:
print 'next()', iterator.next()
except StopIteration:
continue
>>> foo()
for i = 0
next() 1
for i = 2
next() 3
for i = 4
next() 5
for i = 6
next() 7
for i = 8
next() 9
for i = 10
next()
>>>
```
xrange() is an iterating version of range()
iterable = xrange(11) would behave as an iterator.
itertools provides nice functions like dropwhile <http://docs.python.org/library/itertools.html#itertools.dropwhile>
This can proceed your iterator for you.
```
from itertools import dropwhile
iterator = iter(range(11))
for i in iterator:
if i == 3:
i = dropwhile(lambda x: x<8, iterator).next()
print 'i = ', i
>>> foo()
i = 0
i = 1
i = 2
i = 8
i = 9
i = 10
>>>
```
dropwhile could be called outside your loop to create the iterator over your iteratator.
Then you can simply call next() on it. Since the for loop and the dropwhile are both calling next() on the same iterator you have some control over it.
You could also implement your own iterator that uses send() to allow you to manipulate the iterator.
<http://onlamp.com/pub/a/python/2006/10/26/python-25.html?page=2> |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | The problem here is that `range(1, 11)` returns a list and `for...in` iterates over the list elements hence changing `i` to something else doesn't work as expected. Using a `while` loop should solve your problem. | Mind you that is just a bad idea. Changing iteration variable inside a for loop? In my eyes thats equivalent to a goto statement.
Why don't you just ask what you want to accomplish?
* Do you want to filter collection? Use continue statement.
* Or do you want to repeat some things more times? Create a repeat loop inside.
* Do you want iteration in different order? Well prepare the order beforehand.
The while loop solutions that others posted are correct translations, but that is not a very good idea either. |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | The problem here is that `range(1, 11)` returns a list and `for...in` iterates over the list elements hence changing `i` to something else doesn't work as expected. Using a `while` loop should solve your problem. | For this case, you may want to use *while loop* instead of *for loop* in Python.
For example:
```
i = 0
while i < 10:
if ...:
i = 4
``` |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | Mind you that is just a bad idea. Changing iteration variable inside a for loop? In my eyes thats equivalent to a goto statement.
Why don't you just ask what you want to accomplish?
* Do you want to filter collection? Use continue statement.
* Or do you want to repeat some things more times? Create a repeat loop inside.
* Do you want iteration in different order? Well prepare the order beforehand.
The while loop solutions that others posted are correct translations, but that is not a very good idea either. | For this case, you may want to use *while loop* instead of *for loop* in Python.
For example:
```
i = 0
while i < 10:
if ...:
i = 4
``` |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | One possibility is that you want to skip items. Everything to do with looping over an index is ugly but here's a way to do that with a while loop.
```
i = 1
while i < 11:
if predicate(i):
i = 4
i += 1
```
---
It's better to loop over items of the list that you want to work with directly and just skip the items that you don't want to deal with.
```
for item in some_list_of_items:
if not predicate(item):
continue
do_something_with_item(item)
```
Or use a generator expression to filter the items
```
for item in (item for item in some_list_of_items if predicate(item)):
do_something_with_item(item)
```
--- | Just some food for thought.
The for loop loops over an iterable. Create your own iterable that you can move forward yourself.
```
iterator = iter(range(11))
for i in iterator:
print 'for i = ', i
try:
print 'next()', iterator.next()
except StopIteration:
continue
>>> foo()
for i = 0
next() 1
for i = 2
next() 3
for i = 4
next() 5
for i = 6
next() 7
for i = 8
next() 9
for i = 10
next()
>>>
```
xrange() is an iterating version of range()
iterable = xrange(11) would behave as an iterator.
itertools provides nice functions like dropwhile <http://docs.python.org/library/itertools.html#itertools.dropwhile>
This can proceed your iterator for you.
```
from itertools import dropwhile
iterator = iter(range(11))
for i in iterator:
if i == 3:
i = dropwhile(lambda x: x<8, iterator).next()
print 'i = ', i
>>> foo()
i = 0
i = 1
i = 2
i = 8
i = 9
i = 10
>>>
```
dropwhile could be called outside your loop to create the iterator over your iteratator.
Then you can simply call next() on it. Since the for loop and the dropwhile are both calling next() on the same iterator you have some control over it.
You could also implement your own iterator that uses send() to allow you to manipulate the iterator.
<http://onlamp.com/pub/a/python/2006/10/26/python-25.html?page=2> |
4,290,399 | In other languages
```
for(i=0; i<10; i++){
if(...){
i = 4;
}
}
```
the loop will go up,
but in python,it doesn't work
```
for i in range(1, 11):
if ...:
i = 4
```
So can I go up in a loop with 'for'? | 2010/11/27 | [
"https://Stackoverflow.com/questions/4290399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522057/"
] | Mind you that is just a bad idea. Changing iteration variable inside a for loop? In my eyes thats equivalent to a goto statement.
Why don't you just ask what you want to accomplish?
* Do you want to filter collection? Use continue statement.
* Or do you want to repeat some things more times? Create a repeat loop inside.
* Do you want iteration in different order? Well prepare the order beforehand.
The while loop solutions that others posted are correct translations, but that is not a very good idea either. | Just some food for thought.
The for loop loops over an iterable. Create your own iterable that you can move forward yourself.
```
iterator = iter(range(11))
for i in iterator:
print 'for i = ', i
try:
print 'next()', iterator.next()
except StopIteration:
continue
>>> foo()
for i = 0
next() 1
for i = 2
next() 3
for i = 4
next() 5
for i = 6
next() 7
for i = 8
next() 9
for i = 10
next()
>>>
```
xrange() is an iterating version of range()
iterable = xrange(11) would behave as an iterator.
itertools provides nice functions like dropwhile <http://docs.python.org/library/itertools.html#itertools.dropwhile>
This can proceed your iterator for you.
```
from itertools import dropwhile
iterator = iter(range(11))
for i in iterator:
if i == 3:
i = dropwhile(lambda x: x<8, iterator).next()
print 'i = ', i
>>> foo()
i = 0
i = 1
i = 2
i = 8
i = 9
i = 10
>>>
```
dropwhile could be called outside your loop to create the iterator over your iteratator.
Then you can simply call next() on it. Since the for loop and the dropwhile are both calling next() on the same iterator you have some control over it.
You could also implement your own iterator that uses send() to allow you to manipulate the iterator.
<http://onlamp.com/pub/a/python/2006/10/26/python-25.html?page=2> |
53,158,284 | While trying to input my API key python is giving me a line too long code
```
E501: line too long
```
What I have is
```
notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-1aa111a0a111)
```
For obvious reasons I have changed the API key to have only a's 1's and 0's but how can I break up this line of code so I no longer get this error? | 2018/11/05 | [
"https://Stackoverflow.com/questions/53158284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5348714/"
] | E501 is a linter error, not a Python interpreter error. Your code, in theory, should work just fine. If you want to prevent this error, simply break the value up (assuming it's a string ... you don't make that clear):
```
my_key = ('aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-'
'11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-'
'1aa111a0a111')
notifications_client = NotificationsAPIClient(my_key)
``` | Use \ to break your line. Like;
notifications\_client = NotificationsAPIClient(aaaaaaa\_aaaaaaaa-11aa1a1a-\
aa11-111a-aaaa-11111aaa1a1a-\
aa11a1a1-0aa1-11a1-1111-1aa111a0a111) |
53,158,284 | While trying to input my API key python is giving me a line too long code
```
E501: line too long
```
What I have is
```
notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-1aa111a0a111)
```
For obvious reasons I have changed the API key to have only a's 1's and 0's but how can I break up this line of code so I no longer get this error? | 2018/11/05 | [
"https://Stackoverflow.com/questions/53158284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5348714/"
] | E501 is a linter error, not a Python interpreter error. Your code, in theory, should work just fine. If you want to prevent this error, simply break the value up (assuming it's a string ... you don't make that clear):
```
my_key = ('aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-'
'11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-'
'1aa111a0a111')
notifications_client = NotificationsAPIClient(my_key)
``` | Option which doesn't involved breaking the string literal:
```
notifications_client = NotificationsAPIClient(
"kkkkkkkkkkkkkeeeeeeeeeeeeeeeeeeeeeeeeeeyyyyyyyyyyyyyyyyyyyyy"
)
```
So long as your key is <73 (minus scope indentation) characters long. If not, you'll have to split it. |
53,158,284 | While trying to input my API key python is giving me a line too long code
```
E501: line too long
```
What I have is
```
notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-1aa111a0a111)
```
For obvious reasons I have changed the API key to have only a's 1's and 0's but how can I break up this line of code so I no longer get this error? | 2018/11/05 | [
"https://Stackoverflow.com/questions/53158284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5348714/"
] | E501 is a linter error, not a Python interpreter error. Your code, in theory, should work just fine. If you want to prevent this error, simply break the value up (assuming it's a string ... you don't make that clear):
```
my_key = ('aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-'
'11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-'
'1aa111a0a111')
notifications_client = NotificationsAPIClient(my_key)
``` | E501 is not a python error, rather than a PEP8 error. Meaning your line is longer than 80 chars (in your case it's 137 chars long).
Your editor or runtime are verifying that your code is correct by PEP8 rules and that's why you are getting this "error". Your Python code has actually no errors at all.
If you want your code to be PEP8 compliant I suggest:
1. Extract the API key to a local variable.
2. If it's still too long you can break up the string into multiple lines
Here is an example:
```
API_KEY = 'aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a' \
'-aaaa-11111aaa1a1a-aa11a1a1-0aa1-' \
'11a1-1111-1aa111a0a111'
notifications_client = NotificationsAPIClient(API_KEY)
``` |
53,158,284 | While trying to input my API key python is giving me a line too long code
```
E501: line too long
```
What I have is
```
notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-1aa111a0a111)
```
For obvious reasons I have changed the API key to have only a's 1's and 0's but how can I break up this line of code so I no longer get this error? | 2018/11/05 | [
"https://Stackoverflow.com/questions/53158284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5348714/"
] | E501 is not a python error, rather than a PEP8 error. Meaning your line is longer than 80 chars (in your case it's 137 chars long).
Your editor or runtime are verifying that your code is correct by PEP8 rules and that's why you are getting this "error". Your Python code has actually no errors at all.
If you want your code to be PEP8 compliant I suggest:
1. Extract the API key to a local variable.
2. If it's still too long you can break up the string into multiple lines
Here is an example:
```
API_KEY = 'aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a' \
'-aaaa-11111aaa1a1a-aa11a1a1-0aa1-' \
'11a1-1111-1aa111a0a111'
notifications_client = NotificationsAPIClient(API_KEY)
``` | Use \ to break your line. Like;
notifications\_client = NotificationsAPIClient(aaaaaaa\_aaaaaaaa-11aa1a1a-\
aa11-111a-aaaa-11111aaa1a1a-\
aa11a1a1-0aa1-11a1-1111-1aa111a0a111) |
53,158,284 | While trying to input my API key python is giving me a line too long code
```
E501: line too long
```
What I have is
```
notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-1aa111a0a111)
```
For obvious reasons I have changed the API key to have only a's 1's and 0's but how can I break up this line of code so I no longer get this error? | 2018/11/05 | [
"https://Stackoverflow.com/questions/53158284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5348714/"
] | E501 is not a python error, rather than a PEP8 error. Meaning your line is longer than 80 chars (in your case it's 137 chars long).
Your editor or runtime are verifying that your code is correct by PEP8 rules and that's why you are getting this "error". Your Python code has actually no errors at all.
If you want your code to be PEP8 compliant I suggest:
1. Extract the API key to a local variable.
2. If it's still too long you can break up the string into multiple lines
Here is an example:
```
API_KEY = 'aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a' \
'-aaaa-11111aaa1a1a-aa11a1a1-0aa1-' \
'11a1-1111-1aa111a0a111'
notifications_client = NotificationsAPIClient(API_KEY)
``` | Option which doesn't involved breaking the string literal:
```
notifications_client = NotificationsAPIClient(
"kkkkkkkkkkkkkeeeeeeeeeeeeeeeeeeeeeeeeeeyyyyyyyyyyyyyyyyyyyyy"
)
```
So long as your key is <73 (minus scope indentation) characters long. If not, you'll have to split it. |
43,519,906 | I wrote a program that does the job, however it is not very pythonic, not pythonic and definitly not beautiful.
The program must concatenate two numpy arrays in the following manner:
As an example list0 and list1 are the input
```
list0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list1 = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
```
The output should look like the following:
```
[0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11]
```
So basically put in the number of `list0` at every even point of the output, and put in the number of `list1` at every uneven point.
I am fairly new to python so I wrote it in a C-Style:
```
import numpy as np
list0 = np.arange(10)
list1 = np.arange(2,12)
new = []
cnt0 = 0
cnt1 = 0
for i in range(0,2*len(list0)):
if i % 2 == 0:
new.append(list0[cnt0])
cnt0 = cnt0 +1;
else:
new.append(list1[cnt1])
cnt1 = cnt1 +1;
```
Now I want to know if there is a more fancy, pythonic, faster way to achieve the same goal? | 2017/04/20 | [
"https://Stackoverflow.com/questions/43519906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6786718/"
] | Being NumPy tagged, here's one with it -
```
np.vstack((list0, list1)).ravel('F').tolist()
```
[`ravel()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html) here flattens in `fortran` order with the `F` specifier.
A shorter version with [`np.c_`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html) that basically stacks the elements in columns -
```
np.c_[list0,list1].ravel().tolist()
```
`ravel()` here flattens in the default `C` order, so skipped here.
If the final output is to be kept as an array, skip the `.tolist()` from the approaches. | Nice one liner with itertools
```
from itertools import chain
chain(*zip(list0, list1))
[0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11]
``` |
43,519,906 | I wrote a program that does the job, however it is not very pythonic, not pythonic and definitly not beautiful.
The program must concatenate two numpy arrays in the following manner:
As an example list0 and list1 are the input
```
list0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list1 = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
```
The output should look like the following:
```
[0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11]
```
So basically put in the number of `list0` at every even point of the output, and put in the number of `list1` at every uneven point.
I am fairly new to python so I wrote it in a C-Style:
```
import numpy as np
list0 = np.arange(10)
list1 = np.arange(2,12)
new = []
cnt0 = 0
cnt1 = 0
for i in range(0,2*len(list0)):
if i % 2 == 0:
new.append(list0[cnt0])
cnt0 = cnt0 +1;
else:
new.append(list1[cnt1])
cnt1 = cnt1 +1;
```
Now I want to know if there is a more fancy, pythonic, faster way to achieve the same goal? | 2017/04/20 | [
"https://Stackoverflow.com/questions/43519906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6786718/"
] | Being NumPy tagged, here's one with it -
```
np.vstack((list0, list1)).ravel('F').tolist()
```
[`ravel()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html) here flattens in `fortran` order with the `F` specifier.
A shorter version with [`np.c_`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.c_.html) that basically stacks the elements in columns -
```
np.c_[list0,list1].ravel().tolist()
```
`ravel()` here flattens in the default `C` order, so skipped here.
If the final output is to be kept as an array, skip the `.tolist()` from the approaches. | You can use `zip`
```
>>> output = [ data for elem in zip(list0,list1) for data in elem ]
[0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11]
``` |
11,400,590 | I have a python dictionary consisting of JSON results. The dictionary contains a nested dictionary, which contains a nested list which contains a nested dictionary. Still with me? Here's an example:
```
{'hits':{'results':[{'key1':'value1',
'key2':'value2',
'key3':{'sub_key':'sub_value'}},
{'key1':'value3',
'key2':'value4',
'key3':{'sub_key':'sub_value2'}}
]}}
```
What I want to get from the dictionary is the `sub_vale` of each `sub_key` and store it in a different list. No matter what I try I keep getting errors.
This was my last attempt at it:
```
inner_list=mydict['hits']['results']#This is the list of the inner_dicts
index = 0
for x in inner_list:
new_dict[index] = x[u'sub_key']
index = index + 1
print new_dict
```
It printed the first few results then started to return everything in the original dictionary. I can't get my head around it. If I replace the `new_dict[index]` line with a `print` statement it prints to the screen perfectly. Really need some input on this!
```
for x in inner_list:
print x[u'sub_key']
``` | 2012/07/09 | [
"https://Stackoverflow.com/questions/11400590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046501/"
] | The most appropriate way is to override the `clean` method of your model:
```
from django.template import defaultfilters
class Article(models.Model):
...
def clean(self):
if self.slug.strip() == '':
self.slug = defaultfilters.slugify(self.title)
super(Article, self).clean()
```
This method will be called before the model is saved, and before any uniqueness checks are done, so if there's an issue, it will still be caught.
You can read about model's clean method [here](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean) | I would build it into the input form and use a ModelAdmin or ModelForm.
Admin Form:
```
from django.contrib import admin
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title', )}
```
ModelForm:
```
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
def clean_slug(self):
if !self.cleaned_data['slug'] :
self.cleaned_data['slug'] = slugify(self.title)
return True
```
again in that clean\_slug you may want to check to see if its unique first... and modify the slug to be unique if not. |
11,400,590 | I have a python dictionary consisting of JSON results. The dictionary contains a nested dictionary, which contains a nested list which contains a nested dictionary. Still with me? Here's an example:
```
{'hits':{'results':[{'key1':'value1',
'key2':'value2',
'key3':{'sub_key':'sub_value'}},
{'key1':'value3',
'key2':'value4',
'key3':{'sub_key':'sub_value2'}}
]}}
```
What I want to get from the dictionary is the `sub_vale` of each `sub_key` and store it in a different list. No matter what I try I keep getting errors.
This was my last attempt at it:
```
inner_list=mydict['hits']['results']#This is the list of the inner_dicts
index = 0
for x in inner_list:
new_dict[index] = x[u'sub_key']
index = index + 1
print new_dict
```
It printed the first few results then started to return everything in the original dictionary. I can't get my head around it. If I replace the `new_dict[index]` line with a `print` statement it prints to the screen perfectly. Really need some input on this!
```
for x in inner_list:
print x[u'sub_key']
``` | 2012/07/09 | [
"https://Stackoverflow.com/questions/11400590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046501/"
] | I would build it into the input form and use a ModelAdmin or ModelForm.
Admin Form:
```
from django.contrib import admin
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title', )}
```
ModelForm:
```
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
def clean_slug(self):
if !self.cleaned_data['slug'] :
self.cleaned_data['slug'] = slugify(self.title)
return True
```
again in that clean\_slug you may want to check to see if its unique first... and modify the slug to be unique if not. | You can also use signals. Use the post save signal that comes with django.
<https://docs.djangoproject.com/en/dev/topics/signals/> |
11,400,590 | I have a python dictionary consisting of JSON results. The dictionary contains a nested dictionary, which contains a nested list which contains a nested dictionary. Still with me? Here's an example:
```
{'hits':{'results':[{'key1':'value1',
'key2':'value2',
'key3':{'sub_key':'sub_value'}},
{'key1':'value3',
'key2':'value4',
'key3':{'sub_key':'sub_value2'}}
]}}
```
What I want to get from the dictionary is the `sub_vale` of each `sub_key` and store it in a different list. No matter what I try I keep getting errors.
This was my last attempt at it:
```
inner_list=mydict['hits']['results']#This is the list of the inner_dicts
index = 0
for x in inner_list:
new_dict[index] = x[u'sub_key']
index = index + 1
print new_dict
```
It printed the first few results then started to return everything in the original dictionary. I can't get my head around it. If I replace the `new_dict[index]` line with a `print` statement it prints to the screen perfectly. Really need some input on this!
```
for x in inner_list:
print x[u'sub_key']
``` | 2012/07/09 | [
"https://Stackoverflow.com/questions/11400590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046501/"
] | The most appropriate way is to override the `clean` method of your model:
```
from django.template import defaultfilters
class Article(models.Model):
...
def clean(self):
if self.slug.strip() == '':
self.slug = defaultfilters.slugify(self.title)
super(Article, self).clean()
```
This method will be called before the model is saved, and before any uniqueness checks are done, so if there's an issue, it will still be caught.
You can read about model's clean method [here](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.clean) | You can also use signals. Use the post save signal that comes with django.
<https://docs.djangoproject.com/en/dev/topics/signals/> |
11,928,277 | I cant seem to install Rpy2 for python. Initially I ran across the problem where it displayed the following error.
```
Tried to guess R's HOME but no R command in the PATH.
```
But then I followed instructions in the following thread: [trouble installing rpy2 on win7 (R 2.12, Python 2.5)](https://stackoverflow.com/questions/4924917/trouble-installing-rpy2-on-win7-r-2-12-python-2-5)
where by I placed and copied all the files in R\R-2.12.1\bin\i386 to the R\R-2.12.1\bin and then set my environment path to point to R\R-2.12.1. Now trying to install it from source again..
```
python setup.py run
```
I get the same error. If I set the path variable to R\R-2.12.1\bin\ then I get the following error as showed by the person who gave the second answer
```
ValueError: Invalid substring in string
```
That thread went out of ideas so I thought a year from now if there are new ways to work around this.
EDIT = once
Thanks in advance | 2012/08/13 | [
"https://Stackoverflow.com/questions/11928277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610626/"
] | Me too, I had many difficulties getting rpy2 up and running, even after following the crucial link in the answer from lgauthier. But, the final help came from one of the replies on that mailing list.
Summarized, these were the 4 steps needed to get rpy2 up and running on my Windows7 computer:
1. Install rpy2 from this link: <https://bitbucket.org/breisfeld/rpy2_w32_fix/issue/1/binary-installer-for-win32>
2. Add C:\Program Files\R\R-2.12.1\bin\i386 (the path to R.dll) to the environment variable PATH
3. Add an environment variable R\_HOME with C:\Program Files\R\R-2.12.1
4. Add an environment variable R\_USER with your Windows username
In case you don't know how to add/change environment variables, look e.g. here: <http://www.computerhope.com/issues/ch000549.htm> | Check the [rpy-mailing list](http://www.mail-archive.com/rpy-list@lists.sourceforge.net/msg03340.html) on July 18th. There is slight progress on the Windows front for rpy2, and people are reporting some success running it. |
11,928,277 | I cant seem to install Rpy2 for python. Initially I ran across the problem where it displayed the following error.
```
Tried to guess R's HOME but no R command in the PATH.
```
But then I followed instructions in the following thread: [trouble installing rpy2 on win7 (R 2.12, Python 2.5)](https://stackoverflow.com/questions/4924917/trouble-installing-rpy2-on-win7-r-2-12-python-2-5)
where by I placed and copied all the files in R\R-2.12.1\bin\i386 to the R\R-2.12.1\bin and then set my environment path to point to R\R-2.12.1. Now trying to install it from source again..
```
python setup.py run
```
I get the same error. If I set the path variable to R\R-2.12.1\bin\ then I get the following error as showed by the person who gave the second answer
```
ValueError: Invalid substring in string
```
That thread went out of ideas so I thought a year from now if there are new ways to work around this.
EDIT = once
Thanks in advance | 2012/08/13 | [
"https://Stackoverflow.com/questions/11928277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610626/"
] | Check the [rpy-mailing list](http://www.mail-archive.com/rpy-list@lists.sourceforge.net/msg03340.html) on July 18th. There is slight progress on the Windows front for rpy2, and people are reporting some success running it. | I tried four steps above and it works fine. Kudos on Kadee.
For question with regards to user1234440, I just use easy\_install rpy2 and it works just fine.
<http://rpy.sourceforge.net/rpy2/doc-2.2/html/overview.html#download>
Make sure you have set\_up tools installed. If you do not know how to do that,check the link below.
<https://pypi.python.org/pypi/setuptools#windows>
You can just run ez\_setup.py and let it decide for you.
Then you just follow steps 2 through 4 contributed by Kadee. |
11,928,277 | I cant seem to install Rpy2 for python. Initially I ran across the problem where it displayed the following error.
```
Tried to guess R's HOME but no R command in the PATH.
```
But then I followed instructions in the following thread: [trouble installing rpy2 on win7 (R 2.12, Python 2.5)](https://stackoverflow.com/questions/4924917/trouble-installing-rpy2-on-win7-r-2-12-python-2-5)
where by I placed and copied all the files in R\R-2.12.1\bin\i386 to the R\R-2.12.1\bin and then set my environment path to point to R\R-2.12.1. Now trying to install it from source again..
```
python setup.py run
```
I get the same error. If I set the path variable to R\R-2.12.1\bin\ then I get the following error as showed by the person who gave the second answer
```
ValueError: Invalid substring in string
```
That thread went out of ideas so I thought a year from now if there are new ways to work around this.
EDIT = once
Thanks in advance | 2012/08/13 | [
"https://Stackoverflow.com/questions/11928277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1610626/"
] | Me too, I had many difficulties getting rpy2 up and running, even after following the crucial link in the answer from lgauthier. But, the final help came from one of the replies on that mailing list.
Summarized, these were the 4 steps needed to get rpy2 up and running on my Windows7 computer:
1. Install rpy2 from this link: <https://bitbucket.org/breisfeld/rpy2_w32_fix/issue/1/binary-installer-for-win32>
2. Add C:\Program Files\R\R-2.12.1\bin\i386 (the path to R.dll) to the environment variable PATH
3. Add an environment variable R\_HOME with C:\Program Files\R\R-2.12.1
4. Add an environment variable R\_USER with your Windows username
In case you don't know how to add/change environment variables, look e.g. here: <http://www.computerhope.com/issues/ch000549.htm> | I tried four steps above and it works fine. Kudos on Kadee.
For question with regards to user1234440, I just use easy\_install rpy2 and it works just fine.
<http://rpy.sourceforge.net/rpy2/doc-2.2/html/overview.html#download>
Make sure you have set\_up tools installed. If you do not know how to do that,check the link below.
<https://pypi.python.org/pypi/setuptools#windows>
You can just run ez\_setup.py and let it decide for you.
Then you just follow steps 2 through 4 contributed by Kadee. |
62,686,320 | How do I stop from printing an extra input line? I'm new with python/coding
```
class1 = "Math"
class2 = "English"
class3 = "PE"
class4 = "Science"
class5 = "Art"
def get_input(className):
classInput = raw_input("Enter the score you received for " + className + ": ")
while int(classInput) >= 101 or int(classInput) <= -1:
print "Needs to be in the range 0 to 100"
classInput = raw_input("Enter the score you received for " + className + ": ")
return int(classInput)
def get_letter_grade(grade):
if grade >= 93:
return"A"
elif grade >= 90:
return"A-"
elif grade >= 87:
return"B+"
elif grade >= 83:
return"B"
elif grade >= 80:
return"B-"
elif grade >= 77:
return"C+"
elif grade >= 73:
return"C"
elif grade >= 70:
return"C-"
elif grade >= 67:
return"D+"
elif grade >= 63:
return"D"
elif grade >= 60:
return"D-"
else:
return"F"
print "Your " + class1 + " score is " + str(get_input(class1)) + ", you got a " +
get_letter_grade(get_input(class1))
```
Prints out:
```none
Enter the score you received for Math: 85
Enter the score you received for Math: 85
Your Math score is 85, you got a B
``` | 2020/07/01 | [
"https://Stackoverflow.com/questions/62686320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13850019/"
] | Inside your print, you call `get_input()` method twice:
```
print "Your " + class1 + " score is " + str(get_input(class1)) + ", you got a " +
get_letter_grade(get_input(class1))
```
What you need to do is store your score by calling `get_input()` method once and use the stored value in print method:
```
score = get_input(class1)
print("Your " + class1 + " score is " + str(score) + ", you got a " +
get_letter_grade(score))
``` | I would separate out your calls to `get_input` from your print statement, not just here, but generally.
```
score = str(get_input(class1))
print "Your " + class1 + " score is " + score + ", you got a " +
get_letter_grade(score)
```
As a rule of thumb, any user input should almost always be immediately stored in a variable to be manipulated and/or used later. |
48,326,721 | I'm trying to mock **elasticsearch.Elasticsearch.indices.exists** function in my Python test case, but I'm getting the following import error. However, mock just **elasticsearch.Elasticsearch** was working fine.
```
@ddt
class TestElasticSearchConnector(unittest.TestCase):
@patch('elasticsearch.Elasticsearch.indices.exists')
@patch('connectors.elastic_search_connector.ElasticSearchConnector._get_local_conn')
def test_check_index(self, mock_es, _get_local_conn):
mock_es = Mock()
mock_es._index_exists = False
mock_es.indices.exists.return_value = True
mock_es.create.return_value = {'result': 'created'}
```
Getting the mock import error here
======================================================================
ERROR: test\_check\_index (tests.base.TestESConnector)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1197, in \_dot\_lookup
return getattr(thing, comp)
AttributeError: type object 'Elasticsearch' has no attribute 'indices'
```
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1297, in patched
arg = patching.__enter__()
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1353, in __enter__
self.target = self.getter()
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1523, in <lambda>
getter = lambda: _importer(target)
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1210, in _importer
thing = _dot_lookup(thing, comp, import_path)
File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1199, in _dot_lookup
__import__(import_path)
ModuleNotFoundError: No module named 'elasticsearch.Elasticsearch'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
```
Test import
```
>> user$ python
Python 3.6.1 (default, May 10 2017, 09:46:05)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from elasticsearch import Elasticsearch
>>>
>>>
``` | 2018/01/18 | [
"https://Stackoverflow.com/questions/48326721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1187968/"
] | This is legitimately an error. When specifying an attribute/method to mock, it must exist on the object (in this case a class). Perhaps you were expecting this attribute to exist, but it only present on the instantiated object.
```
In [1]: from elasticsearch import Elasticsearch
In [2]: Elasticsearch.indices
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-313eaaedb2f6> in <module>()
----> 1 Elasticsearch.indices
```
Indeed, it exists on an instantiated object:
```
In [3]: Elasticsearch().indices
Out[3]: <elasticsearch.client.indices.IndicesClient at 0x102db0a90>
``` | The Elasticserch library generates the `indices` attribute when you instantiante an `Elasticsearch()` object. And it does so using a class of the library called `IndicesClient`, and it is that class who has the `exists` method. Therefore, if you mock the response of that method of the `IndicesClient` class, you test should work.
Also, the input params of the function should be in reverse order with respoect of the decorators. If you put the `indices.exists` patch first, that should go second in the input to the function.
```
from elasticsearch.client import IndicesClient
@mock.patch.object(IndicesClient, 'exists')
@mock.patch('connectors.elastic_search_connector.ElasticSearchConnector._get_local_conn')
def test_check_index(self, mock_get_local_conn, mock_exists):
mock_exists.return_value = True
...
``` |
13,617,019 | I have a code with heavy symbolic calculations (many multiple symbolic integrals). Also I have access to both an 8-core cpu computer (with 18 GB RAM) and a small 32 cpu cluster. I prefer to remain on my professor's 8-core pc rather than to go to another professor's lab using his cluster in a more limited time, however, I'm not sure it will work on the SMP system, so I am looking for a *parallel tool* in **Python** that can be used on both **SMP** and **Clusters** and of course prefer the codes on one system to be **easily and with least effort** modifiable for use on the other system.
So far, I have found Parallel Python (PP) promising for my need, but I have recently told that MPI also does the same (pyMPI or MPI4py). I couldn't approve this as seemingly very little is discussed about this on the web, only [here](http://wiki.python.org/moin/ParallelProcessing) it is stated that MPI (both pyMPI or MPI4py) is usable for **clusters** only, if I am right about that "only"!
Is "Parallel Python" my only choice, or I can also happily use MPI based solutions? Which one is more promising for my needs?
**PS**. It seems none of them have very comprehensive documentations so if you know some links to other than their official websites that can help a newbie in parallel computation I will be so grateful if you would also mention them in your answer :)
---
**Edit**.
My code has two loops one inside the other, the **outer loop** cannot be parallelized as it is an iteration method (*a recursive solution*) each step depending on the values calculated within its previous step. The outer loop contains the *inner loop* alongside *3 extra equations* whose calculations depend on the whole results of the inner loop. However, the **inner loop** (which contains 9 out of 12 equations computable at each step) can be safely parallelized, all 3\*3 equations are independent w.r.t each other, only depending on the previous step. All my equations are so computationally heavy as each contains many multiple symbolic integrals. Seemingly I can parallelize both the **inner loop's 9 equations** and the **integration calculations in each of these 9 equation** separately, and also parallelize all the **integrations in other 3 equations alongside the inner loop**. You can find my code [**here**](http://ask.sagemath.org/question/1661/how-to-speed-up-a-code-containing-several-symbolic) if it can help you better understand my need, it is written inside *SageMath*. | 2012/11/29 | [
"https://Stackoverflow.com/questions/13617019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1631618/"
] | I would look in to `multiprocessing` [(doc)](http://docs.python.org/2/library/multiprocessing.html) which provides a bunch of nice tools for spawning and working with sub-processes.
To quote the documentation:
>
> multiprocessing is a package that supports spawning processes using an
> API similar to the threading module. The multiprocessing package
> offers both local and remote concurrency, effectively side-stepping
> the Global Interpreter Lock by using subprocesses instead of threads.
>
>
>
From the comments I think the `Pool` and it's `map` would serve your purposes [(doc)](http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool).
```
def work_done_in_inner_loop(arg):
# put your work code here
pass
p = Pool(9)
for o in outer_loop:
# what ever else you do
list_of_args = [...] # what your inner loop currently loops over
res = p.map(work_done_in_inner_loop,list_of_args])
# rest of code
``` | I recently ran into a similar problem. However, the following solution is only valid if (1) you wish to run the python script individually on a group of files, AND (2) each invocation of the script is independent of the others.
If the above applies to you, the simplest solution is to write a wrapper in bash along the lines of:
```
for a_file in $list_of_files
do
python python_script.py a_file &
done
```
The '&' will run the preceding command as a sub-process. The advantage is that bash will not wait for the python script to finish before continuing with the for loop.
You may want to place a cap on the number of processes running simultaneously, since this code will use all available resources. |
13,617,019 | I have a code with heavy symbolic calculations (many multiple symbolic integrals). Also I have access to both an 8-core cpu computer (with 18 GB RAM) and a small 32 cpu cluster. I prefer to remain on my professor's 8-core pc rather than to go to another professor's lab using his cluster in a more limited time, however, I'm not sure it will work on the SMP system, so I am looking for a *parallel tool* in **Python** that can be used on both **SMP** and **Clusters** and of course prefer the codes on one system to be **easily and with least effort** modifiable for use on the other system.
So far, I have found Parallel Python (PP) promising for my need, but I have recently told that MPI also does the same (pyMPI or MPI4py). I couldn't approve this as seemingly very little is discussed about this on the web, only [here](http://wiki.python.org/moin/ParallelProcessing) it is stated that MPI (both pyMPI or MPI4py) is usable for **clusters** only, if I am right about that "only"!
Is "Parallel Python" my only choice, or I can also happily use MPI based solutions? Which one is more promising for my needs?
**PS**. It seems none of them have very comprehensive documentations so if you know some links to other than their official websites that can help a newbie in parallel computation I will be so grateful if you would also mention them in your answer :)
---
**Edit**.
My code has two loops one inside the other, the **outer loop** cannot be parallelized as it is an iteration method (*a recursive solution*) each step depending on the values calculated within its previous step. The outer loop contains the *inner loop* alongside *3 extra equations* whose calculations depend on the whole results of the inner loop. However, the **inner loop** (which contains 9 out of 12 equations computable at each step) can be safely parallelized, all 3\*3 equations are independent w.r.t each other, only depending on the previous step. All my equations are so computationally heavy as each contains many multiple symbolic integrals. Seemingly I can parallelize both the **inner loop's 9 equations** and the **integration calculations in each of these 9 equation** separately, and also parallelize all the **integrations in other 3 equations alongside the inner loop**. You can find my code [**here**](http://ask.sagemath.org/question/1661/how-to-speed-up-a-code-containing-several-symbolic) if it can help you better understand my need, it is written inside *SageMath*. | 2012/11/29 | [
"https://Stackoverflow.com/questions/13617019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1631618/"
] | I would look in to `multiprocessing` [(doc)](http://docs.python.org/2/library/multiprocessing.html) which provides a bunch of nice tools for spawning and working with sub-processes.
To quote the documentation:
>
> multiprocessing is a package that supports spawning processes using an
> API similar to the threading module. The multiprocessing package
> offers both local and remote concurrency, effectively side-stepping
> the Global Interpreter Lock by using subprocesses instead of threads.
>
>
>
From the comments I think the `Pool` and it's `map` would serve your purposes [(doc)](http://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool).
```
def work_done_in_inner_loop(arg):
# put your work code here
pass
p = Pool(9)
for o in outer_loop:
# what ever else you do
list_of_args = [...] # what your inner loop currently loops over
res = p.map(work_done_in_inner_loop,list_of_args])
# rest of code
``` | It seems like there are a few reasonable ways to design this.
Let me refer to your jobs as the main job, the 9 intermediate jobs, and the many inner jobs the intermediate jobs can spin off. I'm assuming the intermediate jobs have a "merge" step after the inner jobs all finish, and the same for the outer job.
The simplest design is that the main job fires off the intermediate jobs and then waits for them all to finish before doings its merge step. Then intermediate jobs then fire off the inner jobs and wait for them all to finish before doing their merge steps.
This can work with a single shared queue, but you need a queue that doesn't block the worker pool while waiting, and I don't think `multiprocessing`'s `Pool` and `Queue` can do that out of the box. As soon as you've got all of your processes waiting to join their children, nothing gets done.
One way around that is to change to a continuation-passing style. If you know which one of the intermediate jobs will finish last, you can pass it the handles to the other intermediate jobs and have it join on them and do the merge, instead of the outer job. And the intermediate similarly pass off the merge to their last inner job.
The problem is that you usually have no way of knowing what's going to finish last, even without scheduling issues. So that means you need some form of either sharing (e.g., a semaphore) or message passing between the jobs to negotiate that among themselves. You can do that on top of `multiprocessing`. The only problem is that it destroys the independence of your jobs, and you're suddenly dealing with all the annoying problems of shared concurrency.
A different alternative is to have separate pools and queues for each intermediate job, and some kind of load balancing between the pools that can ensure that each core is running one active process.
Or, of course, a single pool with a more complicated implementation than `multiprocessing`'s, which does either load balancing or cooperative scheduling, so a joiner doesn't block a core.
Or a super-simple solution: Overschedule, and pay a little cost in context switching for simplicity. For example, you can run 32 workers even though you've only got 8 cores, so you've got 22 active workers and 10 waiting. Each core has 2 or 3 active workers, which will slow things down a bit, but maybe not too badly—and at least nobody's idle, and you didn't have to write any code beyond passing a different parameter to the `multiprocessing.Pool` constructor.
At any rate, `multiprocessing` is very simple, and it has almost no extra concepts that won't apply to other solutions. So it may take less time to play with it until you run into a brick wall or don't, than to try to figure out in advance whether it'll work for you. |
13,617,019 | I have a code with heavy symbolic calculations (many multiple symbolic integrals). Also I have access to both an 8-core cpu computer (with 18 GB RAM) and a small 32 cpu cluster. I prefer to remain on my professor's 8-core pc rather than to go to another professor's lab using his cluster in a more limited time, however, I'm not sure it will work on the SMP system, so I am looking for a *parallel tool* in **Python** that can be used on both **SMP** and **Clusters** and of course prefer the codes on one system to be **easily and with least effort** modifiable for use on the other system.
So far, I have found Parallel Python (PP) promising for my need, but I have recently told that MPI also does the same (pyMPI or MPI4py). I couldn't approve this as seemingly very little is discussed about this on the web, only [here](http://wiki.python.org/moin/ParallelProcessing) it is stated that MPI (both pyMPI or MPI4py) is usable for **clusters** only, if I am right about that "only"!
Is "Parallel Python" my only choice, or I can also happily use MPI based solutions? Which one is more promising for my needs?
**PS**. It seems none of them have very comprehensive documentations so if you know some links to other than their official websites that can help a newbie in parallel computation I will be so grateful if you would also mention them in your answer :)
---
**Edit**.
My code has two loops one inside the other, the **outer loop** cannot be parallelized as it is an iteration method (*a recursive solution*) each step depending on the values calculated within its previous step. The outer loop contains the *inner loop* alongside *3 extra equations* whose calculations depend on the whole results of the inner loop. However, the **inner loop** (which contains 9 out of 12 equations computable at each step) can be safely parallelized, all 3\*3 equations are independent w.r.t each other, only depending on the previous step. All my equations are so computationally heavy as each contains many multiple symbolic integrals. Seemingly I can parallelize both the **inner loop's 9 equations** and the **integration calculations in each of these 9 equation** separately, and also parallelize all the **integrations in other 3 equations alongside the inner loop**. You can find my code [**here**](http://ask.sagemath.org/question/1661/how-to-speed-up-a-code-containing-several-symbolic) if it can help you better understand my need, it is written inside *SageMath*. | 2012/11/29 | [
"https://Stackoverflow.com/questions/13617019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1631618/"
] | It seems like there are a few reasonable ways to design this.
Let me refer to your jobs as the main job, the 9 intermediate jobs, and the many inner jobs the intermediate jobs can spin off. I'm assuming the intermediate jobs have a "merge" step after the inner jobs all finish, and the same for the outer job.
The simplest design is that the main job fires off the intermediate jobs and then waits for them all to finish before doings its merge step. Then intermediate jobs then fire off the inner jobs and wait for them all to finish before doing their merge steps.
This can work with a single shared queue, but you need a queue that doesn't block the worker pool while waiting, and I don't think `multiprocessing`'s `Pool` and `Queue` can do that out of the box. As soon as you've got all of your processes waiting to join their children, nothing gets done.
One way around that is to change to a continuation-passing style. If you know which one of the intermediate jobs will finish last, you can pass it the handles to the other intermediate jobs and have it join on them and do the merge, instead of the outer job. And the intermediate similarly pass off the merge to their last inner job.
The problem is that you usually have no way of knowing what's going to finish last, even without scheduling issues. So that means you need some form of either sharing (e.g., a semaphore) or message passing between the jobs to negotiate that among themselves. You can do that on top of `multiprocessing`. The only problem is that it destroys the independence of your jobs, and you're suddenly dealing with all the annoying problems of shared concurrency.
A different alternative is to have separate pools and queues for each intermediate job, and some kind of load balancing between the pools that can ensure that each core is running one active process.
Or, of course, a single pool with a more complicated implementation than `multiprocessing`'s, which does either load balancing or cooperative scheduling, so a joiner doesn't block a core.
Or a super-simple solution: Overschedule, and pay a little cost in context switching for simplicity. For example, you can run 32 workers even though you've only got 8 cores, so you've got 22 active workers and 10 waiting. Each core has 2 or 3 active workers, which will slow things down a bit, but maybe not too badly—and at least nobody's idle, and you didn't have to write any code beyond passing a different parameter to the `multiprocessing.Pool` constructor.
At any rate, `multiprocessing` is very simple, and it has almost no extra concepts that won't apply to other solutions. So it may take less time to play with it until you run into a brick wall or don't, than to try to figure out in advance whether it'll work for you. | I recently ran into a similar problem. However, the following solution is only valid if (1) you wish to run the python script individually on a group of files, AND (2) each invocation of the script is independent of the others.
If the above applies to you, the simplest solution is to write a wrapper in bash along the lines of:
```
for a_file in $list_of_files
do
python python_script.py a_file &
done
```
The '&' will run the preceding command as a sub-process. The advantage is that bash will not wait for the python script to finish before continuing with the for loop.
You may want to place a cap on the number of processes running simultaneously, since this code will use all available resources. |
31,961,754 | I've got a python script that uses the **ansible** package to ping some remote servers. When executed manually (*python devmanager.py*) it works ok, but when the script is managed with **supervisor** it raises the following error:
```
Could not make dir /$HOME/.ansible/cp: [Errno 13] Permission denied: '/$HOME
```
The ansible command is quite simple:
```
runner = ansible.runner.Runner(
module_name='ping',
module_args='',
forks=10,
inventory=inventory
)
```
Same user in source and target systems. I've check permissions for the $HOME folder and didn't find anything weird.
Any idea what's is going on? Doesn't it know to translate the $HOME variable? | 2015/08/12 | [
"https://Stackoverflow.com/questions/31961754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/315521/"
] | You may give a try by altering the parameter "remote\_tmp" in ansible.cfg.
Default:-`$HOME/.ansible/tmp`
Update:-`/tmp/.ansible/tmp`
On this case who ever the user try to run the playbook will have enough permission to create necessary temporary files in /tmp directory. | Yes, it seems that it doesn't escape the `$HOME` variable and tries to write under `/$HOME`. |
72,815,781 | I am getting below error when using geopandas and shapely
```
AttributeError: 'DataFrame' object has no attribute 'crs'
```
Below is the code:
```
#geometry = [Point(xy) for xy in zip(complete_major_accidents['longitude'], complete_major_accidents['latitude'])]
#crs='none'
geometry = gpd.points_from_xy(complete_nonmajor_accidents.longitude, complete_nonmajor_accidents.latitude)
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
#geometries = world['geometry'].apply(lambda x: x.wkt).values
#print(geometries)
#print(tuple(geometry))
gdf = GeoDataFrame(complete_major_accidents, geometry)
gdf
ax = world[world['name'] == 'United Kingdom'].plot(figsize=(15, 15))
#print(type(ax))
gdf.plot(ax = ax, marker='o', color='red', markersize=15, edgecolor='black')
#gdf.plot(ax=world.plot(figsize=(15, 15)), marker='o', color='red', markersize=15)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/tmp/ipykernel_330/1106976374.py in <module>
12 ax = world[world['name'] == 'United Kingdom'].plot(figsize=(15, 15))
13 #print(type(ax))
---> 14 gdf.plot(ax = ax, marker='o', color='red', markersize=15, edgecolor='black')
15 #gdf.plot(ax=world.plot(figsize=(15, 15)), marker='o', color='red', markersize=15)
~/.local/lib/python3.8/site-packages/geopandas/plotting.py in __call__(self, *args, **kwargs)
961 kind = kwargs.pop("kind", "geo")
962 if kind == "geo":
--> 963 return plot_dataframe(data, *args, **kwargs)
964 if kind in self._pandas_kinds:
965 # Access pandas plots
~/.local/lib/python3.8/site-packages/geopandas/plotting.py in plot_dataframe(df, column, cmap, color, ax, cax, categorical, legend, scheme, k, vmin, vmax, markersize, figsize, legend_kwds, categories, classification_kwds, missing_kwds, aspect, **style_kwds)
674
675 if aspect == "auto":
--> 676 if df.crs and df.crs.is_geographic:
677 bounds = df.total_bounds
678 y_coord = np.mean([bounds[1], bounds[3]])
~/.local/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
5573 ):
5574 return self[name]
-> 5575 return object.__getattribute__(self, name)
5576
5577 def __setattr__(self, name: str, value) -> None:
AttributeError: 'DataFrame' object has no attribute 'crs'
``` | 2022/06/30 | [
"https://Stackoverflow.com/questions/72815781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10908274/"
] | I am finally able to resolve it by changing this below piece of code
```
gdf = GeoDataFrame(complete_major_accidents, geometry)
```
to
```
gdf = GeoDataFrame(complete_nonmajor_accidents, geometry = geometry)
``` | I got the same error after updating Geopandas from an older version. Following fix did the trick.
`self.ax = gpd.GeoDataFrame().plot(figsize=(18, 12))`
to
`self.ax = gpd.GeoDataFrame(geometry=[]).plot(figsize=(18, 12))` |
64,886,214 | I'm a new python developer and I watched a few tutorials on YouTube explaining the functions and the uses for this module, but I cannot get it to work. I installed the module via pip so I don't think that is the issue.
```
import urllib.request
x = urllib.request.urlopen('https://www.google.com')
print(x.read())
```
**Output:**
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 1342, in do\_open
h.request(req.get\_method(), req.selector, req.data, headers,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1255, in request
self.\_send\_request(method, url, body, headers, encode\_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1301, in \_send\_request
self.endheaders(body, encode\_chunked=encode\_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1250, in endheaders
self.\_send\_output(message\_body, encode\_chunked=encode\_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1010, in \_send\_output
self.send(msg)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 950, in send
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1424, in connect
self.sock = self.\_context.wrap\_socket(self.sock,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 500, in wrap\_socket
return self.sslsocket\_class.\_create(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1040, in \_create
self.do\_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1309, in do\_handshake
self.\_sslobj.do\_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE\_VERIFY\_FAILED] certificate verify failed: unable to get local issuer certificate (\_ssl.c:1122)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mike/PycharmProjects/urllib/main.py", line 8, in
x = urllib.request.urlopen('https://www.google.com')
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 214, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 517, in open
response = self.\_open(req, data)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 534, in \_open
result = self.\_call\_chain(self.handle\_open, protocol, protocol +
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 494, in \_call\_chain
result = func(\*args)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 1385, in https\_open
return self.do\_open(http.client.HTTPSConnection, req,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 1345, in do\_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE\_VERIFY\_FAILED] certificate verify failed: unable to get local issuer certificate (\_ssl.c:1122)>
Process finished with exit code 1 | 2020/11/18 | [
"https://Stackoverflow.com/questions/64886214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14558709/"
] | I gave the answer to this in the previous question you asked.You do not make any effort and do not follow the answers to the questions you ask.This is probably your homework or part of homework and you just wait for a solution.I hope you will share your works and then ask questions, this can be better for your improvement.
I am sharing my answer again because maybe it can help others and the previous question was deleted.I hope this answer works.
Please share your work before asking questions next time and follow your question and their answers otherwise you may not be able to solve your problem.
```
puzzle =["a","a","a"," ","b","b","b"]
## dont forget your input will start 0
## because you will pick an index
def move(puzzle):
move_index = int(input("enter an index for move right"))
for i in puzzle:
if move_index < len(puzzle):
if puzzle[move_index + 1] == " " and puzzle[move_index] == "a":
puzzle[move_index],puzzle[move_index+1] = puzzle[move_index +1 ],puzzle[move_index] ## if right index is free,move
return puzzle
if puzzle[move_index - 1] == " " and puzzle[move_index] == "b" :
puzzle[move_index], puzzle[move_index - 1] = puzzle[move_index - 1], puzzle[move_index]
return puzzle
if puzzle[move_index - 2] == " " and puzzle[move_index-1] == "a" and puzzle[move_index] == "b":
puzzle[move_index], puzzle[move_index - 2] = puzzle[move_index - 2], puzzle[move_index]
return puzzle
if puzzle[move_index + 2] == " " and puzzle[move_index + 1 ] == "b" and puzzle[move_index] == "a" :
puzzle[move_index], puzzle[move_index + 2] = puzzle[move_index + 2], puzzle[move_index]
return puzzle
if move_index == len(puzzle): ## you can move last element only for your conditons
puzzle.append(puzzle.pop(move_index-1)) ## switch for last and first
puzzle.insert(0, puzzle.pop())
return puzzle ## updated puzzle
else:
return puzzle
def game():
is_game_continue = int(input("Do you want continue ? (1) Yes (2) No")) ## for enter new moves
return is_game_continue
while game() == 1: ## if user want continue
## you can add other options like return value != 1
current_puzzle = move(puzzle)
print(current_puzzle)
``` | You should not use `from` as a variable since it's a reserved keyword in python.
Maybe that's what causing your problem. |
64,886,214 | I'm a new python developer and I watched a few tutorials on YouTube explaining the functions and the uses for this module, but I cannot get it to work. I installed the module via pip so I don't think that is the issue.
```
import urllib.request
x = urllib.request.urlopen('https://www.google.com')
print(x.read())
```
**Output:**
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 1342, in do\_open
h.request(req.get\_method(), req.selector, req.data, headers,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1255, in request
self.\_send\_request(method, url, body, headers, encode\_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1301, in \_send\_request
self.endheaders(body, encode\_chunked=encode\_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1250, in endheaders
self.\_send\_output(message\_body, encode\_chunked=encode\_chunked)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1010, in \_send\_output
self.send(msg)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 950, in send
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/http/client.py", line 1424, in connect
self.sock = self.\_context.wrap\_socket(self.sock,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 500, in wrap\_socket
return self.sslsocket\_class.\_create(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1040, in \_create
self.do\_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1309, in do\_handshake
self.\_sslobj.do\_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE\_VERIFY\_FAILED] certificate verify failed: unable to get local issuer certificate (\_ssl.c:1122)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mike/PycharmProjects/urllib/main.py", line 8, in
x = urllib.request.urlopen('https://www.google.com')
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 214, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 517, in open
response = self.\_open(req, data)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 534, in \_open
result = self.\_call\_chain(self.handle\_open, protocol, protocol +
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 494, in \_call\_chain
result = func(\*args)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 1385, in https\_open
return self.do\_open(http.client.HTTPSConnection, req,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/urllib/request.py", line 1345, in do\_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE\_VERIFY\_FAILED] certificate verify failed: unable to get local issuer certificate (\_ssl.c:1122)>
Process finished with exit code 1 | 2020/11/18 | [
"https://Stackoverflow.com/questions/64886214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14558709/"
] | You have all the ideas about the rules so I think you can finish the game by yourself. This answer may serve as a reference for you to put ideas together.
```
start_puzzle = ['a', 'a', 'a', ' ', 'b', 'b', 'b']
end_puzzle = ['b', 'b', 'b', ' ', 'a', 'a', 'a']
print(start_puzzle)
while start_puzzle != end_puzzle:
# -1 to get index
from_idx = int(input("Move from position: ")) - 1
to_idx = int(input("Move to position: ")) - 1
# positive step from left to right and negative step from right to left
step = to_idx - from_idx
if 0 <= from_idx < len(start_puzzle) and 0 <= to_idx < len(start_puzzle):
if start_puzzle[from_idx] == "a" and step < 0 or start_puzzle[from_idx] == "b" and step > 0:
print(f"'{start_puzzle[from_idx]}' cannot move backwards.")
elif start_puzzle[to_idx] != ' ':
print("Can only move to empty space.")
elif step > 2 or step < -2:
print("Cannot swap more than one space.")
else:
start_puzzle[from_idx], start_puzzle[to_idx] = start_puzzle[to_idx], start_puzzle[from_idx]
else:
print("Position out of range.")
print(start_puzzle)
if start_puzzle == end_puzzle:
print("You Won!!")
```
Test result:
```
['a', 'a', 'a', ' ', 'b', 'b', 'b']
Move from position: 1
Move to position: 8
Position out of range.
['a', 'a', 'a', ' ', 'b', 'b', 'b']
Move from position: 1
Move to position: 4
Cannot swap more than one space.
['a', 'a', 'a', ' ', 'b', 'b', 'b']
Move from position: 3
Move to position: 5
Can only move to empty space.
['a', 'a', 'a', ' ', 'b', 'b', 'b']
Move from position: 3
Move to position: 4
['a', 'a', ' ', 'a', 'b', 'b', 'b']
Move from position: 4
Move to position: 3
'a' cannot move backwards.
['a', 'a', ' ', 'a', 'b', 'b', 'b']
Move from position: 5
Move to position: 3
['a', 'a', 'b', 'a', ' ', 'b', 'b']
Move from position: 3
Move to position: 5
'b' cannot move backwards.
.
.
.
['b', 'b', 'b', 'a', ' ', 'a', 'a']
Move from position: 4
Move to position: 5
['b', 'b', 'b', ' ', 'a', 'a', 'a']
You Won!!
``` | You should not use `from` as a variable since it's a reserved keyword in python.
Maybe that's what causing your problem. |
31,969,540 | My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end.
I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end.
I am looking for something like `#if 0` for `cpp`.
**How can this be done?**
Here are some ideas and the reasons they are bad:
1. `sys.exit(0)`: works for `python` but not `py_compile` and `pylint`
2. put all experimental code under `def test():`: I can no longer copy/paste the code into a `python` REPL because it has non-trivial indent
3. put all experimental code between lines with `"""`: emacs no longer indents and fontifies the code properly
4. comment and uncomment the code all the time: I am too lazy (yes, this is a single key press, but I have to remember to do that!)
5. put the test code into a separate file: I want to keep the related stuff together
PS. My IDE is Emacs and my python interpreter is `pyspark`. | 2015/08/12 | [
"https://Stackoverflow.com/questions/31969540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/850781/"
] | Use `ipython` rather than `python` for your REPL It has better code completion and introspection and when you paste indented code it can automatically "de-indent" the pasted code.
Thus you can put your experimental code in a test function and then paste in parts without worrying and having to de-indent your code.
If you are pasting large blocks that can be considered individual blocks then you will need to use the `%paste` or `%cpaste` magics.
eg.
```
for i in range(3):
i *= 2
# with the following the blank line this is a complete block
print(i)
```
With a normal paste:
```
In [1]: for i in range(3):
...: i *= 2
...:
In [2]: print(i)
4
```
Using `%paste`
```
In [3]: %paste
for i in range(10):
i *= 2
print(i)
## -- End pasted text --
0
2
4
In [4]:
```
### PySpark and IPython
>
> It is also possible to launch PySpark in IPython, the enhanced Python interpreter. PySpark works with IPython 1.0.0 and later. To use IPython, set the IPYTHON variable to 1 when running bin/pyspark:[1](https://spark.apache.org/docs/0.9.0/python-programming-guide.html)
>
>
>
> ```
> $ IPYTHON=1 ./bin/pyspark
>
> ```
>
> | I suggest you use a proper version control system to keep the "real" and the "experimental" parts separated.
For example, using Git, you could only include the real code without the experimental parts in your commits (using [`add -p`](https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#Staging-Patches)), and then temporarily [`stash`](https://git-scm.com/book/en/v1/Git-Tools-Stashing) the experimental parts for running your various tools.
You could also keep the experimental parts in their own branch which you then [`rebase`](https://git-scm.com/book/en/v2/Git-Branching-Rebasing) on top of the non-experimental parts when you need them. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.