qid
int64 469
74.7M
| question
stringlengths 36
37.8k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 5
31.5k
| response_k
stringlengths 10
31.6k
|
---|---|---|---|---|---|
9,306,328 | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table on this page.
<https://docs.python.org/3/library/time.html#time.strftime>
Why? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9306328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641092/"
] | There is no such thing as a double leap second. There cannot be 62 seconds in a minute. 59, yes. 60, yes. 61, yes. 62, no.
<http://www.monkey.org/openbsd/archive2/tech/199905/msg00031.html> | Leap seconds.
It has been the case that there have been 62 seconds in a minute in the past.
It adjusts for the world spinning slower.
Part of this is down to tides. The energy for the tides comes from the rotation of the earth and moon. The result is that the world slows down.
If global warming takes place the oceans get hotter and expand. That is like a skater throwing their arms out, and the spin slows down. That hasn't taken place. The measurement of ocean levels doesn't agree with the rotation measurements. It's likely to be down to problems with the earth's surface moving, which is far larger than the sea level rise. |
35,871,791 | I currently use the docopt lib for the first time so I surely do something wrong
My script is :
```
"""prog
Usage:
prog.py (-h | --help)
prog.py (--version)
prog.py -s TAG [-t NB_NUC]
Options:
-h, --help help
--version version
-s TAG Some TAG I want.
-t NB_NUC A number of nuc.
"""
```
If I write:
python prog.py -s SMT
I get:
```
{'--help': False,
'--version': False,
'-h': False,
'-s': True,
'-t': True,
'NB_NUC': None,
'TAG': 'SMT'}
```
And it seems to be correct, but if I write :
```
python prog.py -s -t 10 -> TAG contain 10 (instead of None)
python prog.py -t 10 -s SMT -> TAG contain always 10 (instead of SMT) and NB_NUC contain SMT (instead of 10)
python prog.py -s SMT -t -> TAG contain SMT and NB_NUC contain None (and its what I expected on this way)
```
So, I tried lot a combination, but I don't understand how this is supposed to word...
What I want is TAG always contains the values which correspond with the -s argument, with None or an error if nothing is given after -s, and I don't understand why it's not the case..
Thanks for your help ! | 2016/03/08 | [
"https://Stackoverflow.com/questions/35871791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6034538/"
] | Change this
```
.module('autocompleteDemo', ['ngMaterial'])
```
to this
```
.module('myapp', ['ngMaterial'])
```
The name you specify has to match the name you put in ng-app (myApp in your case) | Seems that you missed to add the reference of `ngMaterial.js`, you need to add that right after your `angular.min.js` file file reference. Take it from [**this cdn**](https://cdnjs.com/libraries/angular-material), also add CSS with that to get styling in work. |
35,871,791 | I currently use the docopt lib for the first time so I surely do something wrong
My script is :
```
"""prog
Usage:
prog.py (-h | --help)
prog.py (--version)
prog.py -s TAG [-t NB_NUC]
Options:
-h, --help help
--version version
-s TAG Some TAG I want.
-t NB_NUC A number of nuc.
"""
```
If I write:
python prog.py -s SMT
I get:
```
{'--help': False,
'--version': False,
'-h': False,
'-s': True,
'-t': True,
'NB_NUC': None,
'TAG': 'SMT'}
```
And it seems to be correct, but if I write :
```
python prog.py -s -t 10 -> TAG contain 10 (instead of None)
python prog.py -t 10 -s SMT -> TAG contain always 10 (instead of SMT) and NB_NUC contain SMT (instead of 10)
python prog.py -s SMT -t -> TAG contain SMT and NB_NUC contain None (and its what I expected on this way)
```
So, I tried lot a combination, but I don't understand how this is supposed to word...
What I want is TAG always contains the values which correspond with the -s argument, with None or an error if nothing is given after -s, and I don't understand why it's not the case..
Thanks for your help ! | 2016/03/08 | [
"https://Stackoverflow.com/questions/35871791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6034538/"
] | You use angular material, but you don't import it. I updated your dependencies according to the [angular material getting started page](https://material.angularjs.org/1.0.5/getting-started), I created a [plunker](https://plnkr.co/edit/P3qvamZmynuQeQgy5Asm?p=preview) to verify this.
```
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<title>Shanid KV | AngularJS Dynamic Form Fields</title>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<script type="text/javascript">
angular
.module('myapp', ['ngMaterial'])
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl ($timeout, $q, $log) {
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
// list of `state` value/display objects
self.states = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
self.newState = newState;
function newState(state) {
alert("Sorry! You'll need to create a Constituion for " + state + " first!");
}
// ******************************
// Internal methods
// ******************************
/**
* Search for states... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
var results = query ? self.states.filter( createFilterFor(query) ) : self.states,
deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `states` list of key/value pairs
*/
function loadAll() {
var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
Wisconsin, Wyoming';
return allStates.split(/, +/g).map( function (state) {
return {
value: state.toLowerCase(),
display: state
};
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
}
</script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div ng-controller="DemoCtrl as ctrl" layout="column" ng-cloak>
<md-content class="md-padding">
<form ng-submit="$event.preventDefault()">
<p>Use <code>md-autocomplete</code> to search for matches from local or remote data sources.</p>
<md-autocomplete
ng-disabled="ctrl.isDisabled"
md-no-cache="ctrl.noCache"
md-selected-item="ctrl.selectedItem"
md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item-change="ctrl.selectedItemChange(item)"
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-item-text="item.display"
md-min-length="0"
placeholder="What is your favorite US state?">
<md-item-template>
<span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
No states matching "{{ctrl.searchText}}" were found.
<a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
</md-autocomplete>
<br/>
<md-checkbox ng-model="ctrl.simulateQuery">Simulate query for results?</md-checkbox>
<md-checkbox ng-model="ctrl.noCache">Disable caching of queries?</md-checkbox>
<md-checkbox ng-model="ctrl.isDisabled">Disable the input?</md-checkbox>
<p>By default, <code>md-autocomplete</code> will cache results when performing a query. After the initial call is performed, it will use the cached results to eliminate unnecessary server requests or lookup logic. This can be disabled above.</p>
</form>
</md-content>
</div>
</body>
</html>
``` | Seems that you missed to add the reference of `ngMaterial.js`, you need to add that right after your `angular.min.js` file file reference. Take it from [**this cdn**](https://cdnjs.com/libraries/angular-material), also add CSS with that to get styling in work. |
26,001,511 | Unlike Java, in python when a module is imported into another module and a module's method is called, why does the code in the body gets executed instead of only the code in the method?
Example (taken from another SO question):
### file one.py
```
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
```
### file two.py
```
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
```
and when I run this :
```
python two.py
```
I get :
```
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
```
If I want only the `func()` method of `one.py` to be executed and that's why I chose to import and then call it, what should I be doing?
Why does it get executed in the first place?
I know it gets called when its imported because of the statement `import one`. Looking for what prompted python designers to do it this way! | 2014/09/23 | [
"https://Stackoverflow.com/questions/26001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630792/"
] | It gets executed because *all* the code in the module gets executed, *including the function definition*, upon first import. If you don't want the code to be executed then put it in a main stanza. | When you import a module in Python, the whole file is executed. This creates all the functions and variables that are part of the module. It doesn't differentiate between only executing function or class statements.
I believe the general pattern for having executable code within a library is this:
```
# one.py
def func():
print "In file!"
def main():
# do stuff here
pass
if __name__=="__main__":
main()
```
You can then directly execute the file `python one.py` or you can `import one` and use `one.func()` from it. |
26,001,511 | Unlike Java, in python when a module is imported into another module and a module's method is called, why does the code in the body gets executed instead of only the code in the method?
Example (taken from another SO question):
### file one.py
```
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
```
### file two.py
```
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
```
and when I run this :
```
python two.py
```
I get :
```
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
```
If I want only the `func()` method of `one.py` to be executed and that's why I chose to import and then call it, what should I be doing?
Why does it get executed in the first place?
I know it gets called when its imported because of the statement `import one`. Looking for what prompted python designers to do it this way! | 2014/09/23 | [
"https://Stackoverflow.com/questions/26001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630792/"
] | Programming languages can have several different kinds of syntactic elements. Most languages, for example, will have statements and expressions, which are distinct. Some languages, like Java, have other syntactic elements at the top level. You cannot, for example, write some statements at the top level or in a class, but if you wanted to put a class definition at the top level or method in a class, that would be just fine.
You could, perhaps, think of Java as having a declarative part at the top level that switches to imperative (statements) once you go deeper, and then likely an expression as you go even further. But Python doesn’t really work that way. Python does have a distinction between expressions and statements, but it doesn’t really have a top-level declarative syntactic element. Perhaps you’re thinking of this:
```
def greet(name):
print("Hello, {}!".format(name))
```
…in the same way as you would in Java, in that it can only appear in a certain context. But no: in Python, a function definition is a statement, as is a class definition, as is an assignment.
Because of this design, it’s infeasible to “just import the definitions”: in order for the definitions to be created, the code to create the definitions must be run.
I urge you to think of the following case. In Python, if you want to create an enumeration (without the fancy new `enum` module), you might do something like this:
```
FOO, BAR, BAZ = range(3)
```
To the human eye, that’s probably a definition we want to exist when we import the module. But how is that fundamentally different from something like this, which you might expect to exist in `__main__`?
```
name = input("What's your name? ")
```
There really is no difference, so Python makes no attempt to try to distinguish them; when you import a module, the code is executed.
---
Bonus: Similar behavior in Java
===============================
Think about this:
```java
public class Test {
static {
System.out.println("Wait, what? Code is running without being called?");
}
public static void main(String[] args) {
System.out.println("Nothing to see here, move along now...");
}
}
``` | It gets executed because *all* the code in the module gets executed, *including the function definition*, upon first import. If you don't want the code to be executed then put it in a main stanza. |
26,001,511 | Unlike Java, in python when a module is imported into another module and a module's method is called, why does the code in the body gets executed instead of only the code in the method?
Example (taken from another SO question):
### file one.py
```
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
```
### file two.py
```
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
```
and when I run this :
```
python two.py
```
I get :
```
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
```
If I want only the `func()` method of `one.py` to be executed and that's why I chose to import and then call it, what should I be doing?
Why does it get executed in the first place?
I know it gets called when its imported because of the statement `import one`. Looking for what prompted python designers to do it this way! | 2014/09/23 | [
"https://Stackoverflow.com/questions/26001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630792/"
] | The key difference between Java and Python (in this instance) is that Java has a separate compile step -- using `javac` to create class files. Whereas, with Python this compiling is done at runtime. So when you import the module Python has to compile the entire module source code into byte code. This includes all those print statements as well as creating your functions and classes. What you're asking would be like asking `javac` to only compile part of a .java file. | It gets executed because *all* the code in the module gets executed, *including the function definition*, upon first import. If you don't want the code to be executed then put it in a main stanza. |
26,001,511 | Unlike Java, in python when a module is imported into another module and a module's method is called, why does the code in the body gets executed instead of only the code in the method?
Example (taken from another SO question):
### file one.py
```
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
```
### file two.py
```
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
```
and when I run this :
```
python two.py
```
I get :
```
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
```
If I want only the `func()` method of `one.py` to be executed and that's why I chose to import and then call it, what should I be doing?
Why does it get executed in the first place?
I know it gets called when its imported because of the statement `import one`. Looking for what prompted python designers to do it this way! | 2014/09/23 | [
"https://Stackoverflow.com/questions/26001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630792/"
] | Programming languages can have several different kinds of syntactic elements. Most languages, for example, will have statements and expressions, which are distinct. Some languages, like Java, have other syntactic elements at the top level. You cannot, for example, write some statements at the top level or in a class, but if you wanted to put a class definition at the top level or method in a class, that would be just fine.
You could, perhaps, think of Java as having a declarative part at the top level that switches to imperative (statements) once you go deeper, and then likely an expression as you go even further. But Python doesn’t really work that way. Python does have a distinction between expressions and statements, but it doesn’t really have a top-level declarative syntactic element. Perhaps you’re thinking of this:
```
def greet(name):
print("Hello, {}!".format(name))
```
…in the same way as you would in Java, in that it can only appear in a certain context. But no: in Python, a function definition is a statement, as is a class definition, as is an assignment.
Because of this design, it’s infeasible to “just import the definitions”: in order for the definitions to be created, the code to create the definitions must be run.
I urge you to think of the following case. In Python, if you want to create an enumeration (without the fancy new `enum` module), you might do something like this:
```
FOO, BAR, BAZ = range(3)
```
To the human eye, that’s probably a definition we want to exist when we import the module. But how is that fundamentally different from something like this, which you might expect to exist in `__main__`?
```
name = input("What's your name? ")
```
There really is no difference, so Python makes no attempt to try to distinguish them; when you import a module, the code is executed.
---
Bonus: Similar behavior in Java
===============================
Think about this:
```java
public class Test {
static {
System.out.println("Wait, what? Code is running without being called?");
}
public static void main(String[] args) {
System.out.println("Nothing to see here, move along now...");
}
}
``` | When you import a module in Python, the whole file is executed. This creates all the functions and variables that are part of the module. It doesn't differentiate between only executing function or class statements.
I believe the general pattern for having executable code within a library is this:
```
# one.py
def func():
print "In file!"
def main():
# do stuff here
pass
if __name__=="__main__":
main()
```
You can then directly execute the file `python one.py` or you can `import one` and use `one.func()` from it. |
26,001,511 | Unlike Java, in python when a module is imported into another module and a module's method is called, why does the code in the body gets executed instead of only the code in the method?
Example (taken from another SO question):
### file one.py
```
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
```
### file two.py
```
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
```
and when I run this :
```
python two.py
```
I get :
```
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
```
If I want only the `func()` method of `one.py` to be executed and that's why I chose to import and then call it, what should I be doing?
Why does it get executed in the first place?
I know it gets called when its imported because of the statement `import one`. Looking for what prompted python designers to do it this way! | 2014/09/23 | [
"https://Stackoverflow.com/questions/26001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630792/"
] | The key difference between Java and Python (in this instance) is that Java has a separate compile step -- using `javac` to create class files. Whereas, with Python this compiling is done at runtime. So when you import the module Python has to compile the entire module source code into byte code. This includes all those print statements as well as creating your functions and classes. What you're asking would be like asking `javac` to only compile part of a .java file. | When you import a module in Python, the whole file is executed. This creates all the functions and variables that are part of the module. It doesn't differentiate between only executing function or class statements.
I believe the general pattern for having executable code within a library is this:
```
# one.py
def func():
print "In file!"
def main():
# do stuff here
pass
if __name__=="__main__":
main()
```
You can then directly execute the file `python one.py` or you can `import one` and use `one.func()` from it. |
26,001,511 | Unlike Java, in python when a module is imported into another module and a module's method is called, why does the code in the body gets executed instead of only the code in the method?
Example (taken from another SO question):
### file one.py
```
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
```
### file two.py
```
import one
print("top-level in two.py")
one.func()
if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")
```
and when I run this :
```
python two.py
```
I get :
```
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly
```
If I want only the `func()` method of `one.py` to be executed and that's why I chose to import and then call it, what should I be doing?
Why does it get executed in the first place?
I know it gets called when its imported because of the statement `import one`. Looking for what prompted python designers to do it this way! | 2014/09/23 | [
"https://Stackoverflow.com/questions/26001511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630792/"
] | Programming languages can have several different kinds of syntactic elements. Most languages, for example, will have statements and expressions, which are distinct. Some languages, like Java, have other syntactic elements at the top level. You cannot, for example, write some statements at the top level or in a class, but if you wanted to put a class definition at the top level or method in a class, that would be just fine.
You could, perhaps, think of Java as having a declarative part at the top level that switches to imperative (statements) once you go deeper, and then likely an expression as you go even further. But Python doesn’t really work that way. Python does have a distinction between expressions and statements, but it doesn’t really have a top-level declarative syntactic element. Perhaps you’re thinking of this:
```
def greet(name):
print("Hello, {}!".format(name))
```
…in the same way as you would in Java, in that it can only appear in a certain context. But no: in Python, a function definition is a statement, as is a class definition, as is an assignment.
Because of this design, it’s infeasible to “just import the definitions”: in order for the definitions to be created, the code to create the definitions must be run.
I urge you to think of the following case. In Python, if you want to create an enumeration (without the fancy new `enum` module), you might do something like this:
```
FOO, BAR, BAZ = range(3)
```
To the human eye, that’s probably a definition we want to exist when we import the module. But how is that fundamentally different from something like this, which you might expect to exist in `__main__`?
```
name = input("What's your name? ")
```
There really is no difference, so Python makes no attempt to try to distinguish them; when you import a module, the code is executed.
---
Bonus: Similar behavior in Java
===============================
Think about this:
```java
public class Test {
static {
System.out.println("Wait, what? Code is running without being called?");
}
public static void main(String[] args) {
System.out.println("Nothing to see here, move along now...");
}
}
``` | The key difference between Java and Python (in this instance) is that Java has a separate compile step -- using `javac` to create class files. Whereas, with Python this compiling is done at runtime. So when you import the module Python has to compile the entire module source code into byte code. This includes all those print statements as well as creating your functions and classes. What you're asking would be like asking `javac` to only compile part of a .java file. |
34,030,215 | I'm trying start up a Django project.
I get this error on trying to run the manage.py:
```
(venv)dyn-160-39-161-214:proj Bren$ python manage.py
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
class Permission(models.Model):
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
new_class.add_to_class('_meta', Options(meta, **kwargs))
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
value.contribute_to_class(cls, name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 241, in __getitem__
backend = load_backend(db['ENGINE'])
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 112, in load_backend
return import_module('%s.base' % backend_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
```
I was wondering what module I should try to install.
When I use `pip install MySQLdb` I get this error:
```
Collecting MySQLdb
Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
```
When I look this up on SO and other places it seems there are lots of different mysql modules out there.
Also this is what my setup looks like for the DB (I didnt write this porject and am largely new to django and python):
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
```
...
```
}
}
```
EdBaker suggested `pip install MySQL-python`
I got this as a response:
```
Collecting MySQL-python Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python
```
Attempting to run import MySQLdb in the shell:
```
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb
```
Attempting to upgrade pip:
```
pip install pip --upgrade
```
showed pip was up to date
```
Requirement already up-to-date: pip in /Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages
``` | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848483/"
] | Clearly installing `pip install MySQL-python` is the way to go. The problem is with the location of mysql\_config. Look around here, this might help you depending on your OS: [mysql\_config not found when installing mysqldb python interface](https://stackoverflow.com/questions/7475223/mysql-config-not-found-when-installing-mysqldb-python-interface/33928783#33928783)
**Edit:**
In case the install script fails with `Command "python setup.py egg_info" failed with error code 1 in {...}`, installing libmysqlclient-dev with
```
sudo apt install libmysqlclient-dev
```
should fix the issue. Thanks to @thirupathi-thangavel. | I followed my question here [404 error when using brew to install mysql](https://stackoverflow.com/questions/34031002/404-error-when-using-brew-to-install-mysql?noredirect=1#comment55817617_34031002)
and then as fodma1 suggested went to here stackoverflow.com/a/33928783/2419215
and now it works for the most part (have another error but thats for another post)!
Thanks EdBaker and fodma1! |
34,030,215 | I'm trying start up a Django project.
I get this error on trying to run the manage.py:
```
(venv)dyn-160-39-161-214:proj Bren$ python manage.py
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
class Permission(models.Model):
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
new_class.add_to_class('_meta', Options(meta, **kwargs))
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
value.contribute_to_class(cls, name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 241, in __getitem__
backend = load_backend(db['ENGINE'])
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 112, in load_backend
return import_module('%s.base' % backend_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
```
I was wondering what module I should try to install.
When I use `pip install MySQLdb` I get this error:
```
Collecting MySQLdb
Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
```
When I look this up on SO and other places it seems there are lots of different mysql modules out there.
Also this is what my setup looks like for the DB (I didnt write this porject and am largely new to django and python):
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
```
...
```
}
}
```
EdBaker suggested `pip install MySQL-python`
I got this as a response:
```
Collecting MySQL-python Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python
```
Attempting to run import MySQLdb in the shell:
```
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb
```
Attempting to upgrade pip:
```
pip install pip --upgrade
```
showed pip was up to date
```
Requirement already up-to-date: pip in /Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages
``` | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848483/"
] | brew install mysql
Path will be shown after installation is complete, use that in below command :
```
sudo PATH=/usr/local/Cellar/mysql/bin/:$PATH pip install mysql-python
``` | I followed my question here [404 error when using brew to install mysql](https://stackoverflow.com/questions/34031002/404-error-when-using-brew-to-install-mysql?noredirect=1#comment55817617_34031002)
and then as fodma1 suggested went to here stackoverflow.com/a/33928783/2419215
and now it works for the most part (have another error but thats for another post)!
Thanks EdBaker and fodma1! |
34,030,215 | I'm trying start up a Django project.
I get this error on trying to run the manage.py:
```
(venv)dyn-160-39-161-214:proj Bren$ python manage.py
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
class Permission(models.Model):
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
new_class.add_to_class('_meta', Options(meta, **kwargs))
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
value.contribute_to_class(cls, name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 241, in __getitem__
backend = load_backend(db['ENGINE'])
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 112, in load_backend
return import_module('%s.base' % backend_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
```
I was wondering what module I should try to install.
When I use `pip install MySQLdb` I get this error:
```
Collecting MySQLdb
Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
```
When I look this up on SO and other places it seems there are lots of different mysql modules out there.
Also this is what my setup looks like for the DB (I didnt write this porject and am largely new to django and python):
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
```
...
```
}
}
```
EdBaker suggested `pip install MySQL-python`
I got this as a response:
```
Collecting MySQL-python Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python
```
Attempting to run import MySQLdb in the shell:
```
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb
```
Attempting to upgrade pip:
```
pip install pip --upgrade
```
showed pip was up to date
```
Requirement already up-to-date: pip in /Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages
``` | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848483/"
] | If the above method not working then try
>
> *mysqlclient*
>
>
>
```
pip install mysqlclient
```
>
> *I did not found the above library using **python version(3.9)*** and I installed the **mysqlclient** and it worked for fine.
>
>
> | I followed my question here [404 error when using brew to install mysql](https://stackoverflow.com/questions/34031002/404-error-when-using-brew-to-install-mysql?noredirect=1#comment55817617_34031002)
and then as fodma1 suggested went to here stackoverflow.com/a/33928783/2419215
and now it works for the most part (have another error but thats for another post)!
Thanks EdBaker and fodma1! |
34,030,215 | I'm trying start up a Django project.
I get this error on trying to run the manage.py:
```
(venv)dyn-160-39-161-214:proj Bren$ python manage.py
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
class Permission(models.Model):
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
new_class.add_to_class('_meta', Options(meta, **kwargs))
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
value.contribute_to_class(cls, name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 241, in __getitem__
backend = load_backend(db['ENGINE'])
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 112, in load_backend
return import_module('%s.base' % backend_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
```
I was wondering what module I should try to install.
When I use `pip install MySQLdb` I get this error:
```
Collecting MySQLdb
Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
```
When I look this up on SO and other places it seems there are lots of different mysql modules out there.
Also this is what my setup looks like for the DB (I didnt write this porject and am largely new to django and python):
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
```
...
```
}
}
```
EdBaker suggested `pip install MySQL-python`
I got this as a response:
```
Collecting MySQL-python Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python
```
Attempting to run import MySQLdb in the shell:
```
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb
```
Attempting to upgrade pip:
```
pip install pip --upgrade
```
showed pip was up to date
```
Requirement already up-to-date: pip in /Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages
``` | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848483/"
] | Clearly installing `pip install MySQL-python` is the way to go. The problem is with the location of mysql\_config. Look around here, this might help you depending on your OS: [mysql\_config not found when installing mysqldb python interface](https://stackoverflow.com/questions/7475223/mysql-config-not-found-when-installing-mysqldb-python-interface/33928783#33928783)
**Edit:**
In case the install script fails with `Command "python setup.py egg_info" failed with error code 1 in {...}`, installing libmysqlclient-dev with
```
sudo apt install libmysqlclient-dev
```
should fix the issue. Thanks to @thirupathi-thangavel. | brew install mysql
Path will be shown after installation is complete, use that in below command :
```
sudo PATH=/usr/local/Cellar/mysql/bin/:$PATH pip install mysql-python
``` |
34,030,215 | I'm trying start up a Django project.
I get this error on trying to run the manage.py:
```
(venv)dyn-160-39-161-214:proj Bren$ python manage.py
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute
django.setup()
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
class Permission(models.Model):
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
new_class.add_to_class('_meta', Options(meta, **kwargs))
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
value.contribute_to_class(cls, name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
return getattr(connections[DEFAULT_DB_ALIAS], item)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 241, in __getitem__
backend = load_backend(db['ENGINE'])
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 112, in load_backend
return import_module('%s.base' % backend_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
```
I was wondering what module I should try to install.
When I use `pip install MySQLdb` I get this error:
```
Collecting MySQLdb
Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
```
When I look this up on SO and other places it seems there are lots of different mysql modules out there.
Also this is what my setup looks like for the DB (I didnt write this porject and am largely new to django and python):
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
```
...
```
}
}
```
EdBaker suggested `pip install MySQL-python`
I got this as a response:
```
Collecting MySQL-python Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
sh: mysql_config: command not found
Traceback (most recent call last):
File "<string>", line 20, in <module>
File "/private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python/setup.py", line 17, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 25, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/m3/11zknyw55zxbw6zqh58rwq580000gn/T/pip-build-DC9tSL/MySQL-python
```
Attempting to run import MySQLdb in the shell:
```
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named MySQLdb
```
Attempting to upgrade pip:
```
pip install pip --upgrade
```
showed pip was up to date
```
Requirement already up-to-date: pip in /Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages
``` | 2015/12/01 | [
"https://Stackoverflow.com/questions/34030215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848483/"
] | Clearly installing `pip install MySQL-python` is the way to go. The problem is with the location of mysql\_config. Look around here, this might help you depending on your OS: [mysql\_config not found when installing mysqldb python interface](https://stackoverflow.com/questions/7475223/mysql-config-not-found-when-installing-mysqldb-python-interface/33928783#33928783)
**Edit:**
In case the install script fails with `Command "python setup.py egg_info" failed with error code 1 in {...}`, installing libmysqlclient-dev with
```
sudo apt install libmysqlclient-dev
```
should fix the issue. Thanks to @thirupathi-thangavel. | If the above method not working then try
>
> *mysqlclient*
>
>
>
```
pip install mysqlclient
```
>
> *I did not found the above library using **python version(3.9)*** and I installed the **mysqlclient** and it worked for fine.
>
>
> |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | Do a for in loop on the categories and then another for in loop for each category.
```
for (var i in categories) {
var category = categories[i];
for (var k in category) {
if (category[k].question == 'First question in category 2?') {
console.log(category[k]);
}
}
}
``` | How about this simple solution using **forEach** on each array. Hope it helps!
```js
var obj = {
"Category 1": [{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}],
"Category 2": [{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer" ]
}, {
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}]
};
for(var i in obj){
obj[i].forEach(function(x){
if(x.question === "Second question in category 2?"){
console.log(x.answers);
}
});
}
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | Do a for in loop on the categories and then another for in loop for each category.
```
for (var i in categories) {
var category = categories[i];
for (var k in category) {
if (category[k].question == 'First question in category 2?') {
console.log(category[k]);
}
}
}
``` | ```js
var questions = {
"Category 1": [
{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
},
{
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
}],
"Category 2": [
{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
},
{
"question": "Second question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
},
{
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
}]
};
for(var category in questions)
{
var filtered = $.grep(questions[category], function (e, i) {
return e.question == "Second question in category 2?";
});
if(filtered.length > 0)
{
console.log(filtered[0].answers);
}
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | You can try `for...in` loop.
```
var obj = {/* Assume that this is your object */};
for (let key in obj){ //Loops through object
for (let i = 0; i < obj[key].length; i++){ //Loops through array
if (obj[key][i].question == "Second question in category 2?"){
var answers = obj[key][i].answers; //Here's your answers in array
}
}
}
``` | Try this code:
```js
const obj = {
"Category 1": [{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}],
"Category 2": [{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 2?",
"answers": [ "first answer",
"second answer",
"third answer",
"fourth answer",
]
}, {
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}]
};
const values = Object.values(obj);
const result = values.reduce((acc, cur) => {
Array.prototype.push.apply(acc, cur);
return acc;
}, []).filter(obj => obj.question === 'Third question in category 2?');
console.log(result[0]);
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | Do a for in loop on the categories and then another for in loop for each category.
```
for (var i in categories) {
var category = categories[i];
for (var k in category) {
if (category[k].question == 'First question in category 2?') {
console.log(category[k]);
}
}
}
``` | Try this code:
```js
const obj = {
"Category 1": [{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}],
"Category 2": [{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 2?",
"answers": [ "first answer",
"second answer",
"third answer",
"fourth answer",
]
}, {
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}]
};
const values = Object.values(obj);
const result = values.reduce((acc, cur) => {
Array.prototype.push.apply(acc, cur);
return acc;
}, []).filter(obj => obj.question === 'Third question in category 2?');
console.log(result[0]);
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | You can try `for...in` loop.
```
var obj = {/* Assume that this is your object */};
for (let key in obj){ //Loops through object
for (let i = 0; i < obj[key].length; i++){ //Loops through array
if (obj[key][i].question == "Second question in category 2?"){
var answers = obj[key][i].answers; //Here's your answers in array
}
}
}
``` | How about this simple solution using **forEach** on each array. Hope it helps!
```js
var obj = {
"Category 1": [{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}],
"Category 2": [{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer" ]
}, {
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}]
};
for(var i in obj){
obj[i].forEach(function(x){
if(x.question === "Second question in category 2?"){
console.log(x.answers);
}
});
}
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | You can try `for...in` loop.
```
var obj = {/* Assume that this is your object */};
for (let key in obj){ //Loops through object
for (let i = 0; i < obj[key].length; i++){ //Loops through array
if (obj[key][i].question == "Second question in category 2?"){
var answers = obj[key][i].answers; //Here's your answers in array
}
}
}
``` | You could also use [Array.prototype.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
```js
var questions = {
"Category 1": [{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}],
"Category 2": [{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Third question in category 2?",
"answers": ["first answer - 1",
"second answer",
"third answer",
"fourth answer"
]
}]
};
function getAnswer(inputQuestion) {
var output = {};
Object.keys(questions).forEach((category) => {
questions[category].forEach((val) => {
if (val.question === inputQuestion) {
output = val.answers;
}
});
});
return output;
}
var answer = getAnswer("Third question in category 2?");
console.log(answer);
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | You can try `for...in` loop.
```
var obj = {/* Assume that this is your object */};
for (let key in obj){ //Loops through object
for (let i = 0; i < obj[key].length; i++){ //Loops through array
if (obj[key][i].question == "Second question in category 2?"){
var answers = obj[key][i].answers; //Here's your answers in array
}
}
}
``` | Do a for in loop on the categories and then another for in loop for each category.
```
for (var i in categories) {
var category = categories[i];
for (var k in category) {
if (category[k].question == 'First question in category 2?') {
console.log(category[k]);
}
}
}
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | You can try `for...in` loop.
```
var obj = {/* Assume that this is your object */};
for (let key in obj){ //Loops through object
for (let i = 0; i < obj[key].length; i++){ //Loops through array
if (obj[key][i].question == "Second question in category 2?"){
var answers = obj[key][i].answers; //Here's your answers in array
}
}
}
``` | ```js
var questions = {
"Category 1": [
{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
},
{
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
}],
"Category 2": [
{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
},
{
"question": "Second question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
},
{
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"]
}]
};
for(var category in questions)
{
var filtered = $.grep(questions[category], function (e, i) {
return e.question == "Second question in category 2?";
});
if(filtered.length > 0)
{
console.log(filtered[0].answers);
}
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | Do a for in loop on the categories and then another for in loop for each category.
```
for (var i in categories) {
var category = categories[i];
for (var k in category) {
if (category[k].question == 'First question in category 2?') {
console.log(category[k]);
}
}
}
``` | You could try something like this using for loops,
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="getAnswers"></div>
<script type="text/javascript">
var qas={
"Category 1": [{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}],
"Category 2": [{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}]
};
for(obj in qas){
var qasobj=qas[obj];
for(categ in qasobj){
console.log("getting second"+qasobj[categ].question);
if(qasobj[categ].question=="Second question in category 2?"){
console.log("You have got your answers "+qasobj[categ].answers);
document.getElementById("getAnswers").innerHTML=qasobj[categ].answers;
}
}
}
</script>
</body>
</html>
``` |
40,777,544 | I have this question I hope you could help me..
Basically I have an app where I open a file, read the word from my file and print that word by console. But I want to print "word no found" in case of no finding the word.
Here's my python :
```
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
print car[0]
print toy[0]
```
here's my text file:
>
> car red
>
>
> toy green
>
>
>
I'm getting by console this:
```
red
green
```
Working great as you can see but if I don't have the word "toy" in my file. There's a possible way to get something like this by console :
```
Red
No toy found!
```
**Thank you!** | 2016/11/24 | [
"https://Stackoverflow.com/questions/40777544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7054316/"
] | You can try `for...in` loop.
```
var obj = {/* Assume that this is your object */};
for (let key in obj){ //Loops through object
for (let i = 0; i < obj[key].length; i++){ //Loops through array
if (obj[key][i].question == "Second question in category 2?"){
var answers = obj[key][i].answers; //Here's your answers in array
}
}
}
``` | You could try something like this using for loops,
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="getAnswers"></div>
<script type="text/javascript">
var qas={
"Category 1": [{
"question": "Fist question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 1?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}],
"Category 2": [{
"question": "First question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Second question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}, {
"question": "Third question in category 2?",
"answers": ["first answer",
"second answer",
"third answer",
"fourth answer"
]
}]
};
for(obj in qas){
var qasobj=qas[obj];
for(categ in qasobj){
console.log("getting second"+qasobj[categ].question);
if(qasobj[categ].question=="Second question in category 2?"){
console.log("You have got your answers "+qasobj[categ].answers);
document.getElementById("getAnswers").innerHTML=qasobj[categ].answers;
}
}
}
</script>
</body>
</html>
``` |
23,960,243 | I have two somewhat large (~20 MB) txt files which are essentially just long strings of integers (only either 0,1,2). I would like to write a python script which iterates through the files and compares them integer by integer. At the end of the day I want the number of integers that are different and the total number of integers in the files (they should be exactly the same length). I have done some searching and it seems like difflib may be useful but I am fairly new to python and I am not sure if anything in difflib will count the differences or the number of entries.
Any help would be greatly appreciated! What I am trying right now is the following but it only looks at one entry and then terminates and I don't understand why.
```
f1 = open("file1.txt", "r")
f2 = open("file2.txt", "r")
fileOne = f1.readlines()
fileTwo = f2.readlines()
f1.close()
f2.close()
correct = 0
x = 0
total = 0
for i in fileOne:
if i != fileTwo[x]:
correct +=1
x += 1
total +=1
if total != 0:
percent = (correct / total) * 100
print "The file is %.1f %% correct!" % (percent)
print "%i out of %i symbols were correct!" % (correct, total)
``` | 2014/05/30 | [
"https://Stackoverflow.com/questions/23960243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3692250/"
] | I don't think that an exception is the correct place for logic, it should contain information about the error. A `PDOException` is useful because you know it originates from your PDO code, if you throw a `MyException` instead, you need to at least give more (useful) information.
This being set, you should read [BiVOC's comment](https://stackoverflow.com/questions/23960233/cleaning-up-code-for-a-custom-exception-class-in-php?noredirect=1#comment36912781_23960233) on your original question.
If you have [a custom exception handler](http://www.php.net/manual/en/function.set-exception-handler.php), you can then differentiate via [`instanceof`](http://php.net/manual/en/language.operators.type.php).
```
function exception_handler($exception) {
if ($exception instanceof PDOException) {
//mail
}
//always log/etc.
}
``` | What you are trying to do wont work, because nothing in the PDO code will throw your exception, unfortunately. So you are going to have to throw it yourself, like you were in the first example.
Also, the exit in the first example will never be hit. |
62,929,201 | I am creating a file and I want to write all lines of write\_line to my output.
With this could I have a new file but only with the last line of write\_log not all the lines. I think I should have a for before written log and tell to write all, but i am so new with python and need help.
I am getting name / familtname / id by SOAP response. I want to print responses which are in lines, now i just see the last line not all the lines.
```
timestamp = str(datetime.datetime.now())[:19]
file = open(CreateFile, 'w')
write_line = str(name).strip() + ';' + familyname.strip() + ';' + str(id).strip() + ';' + timestamp
file.writelines(write_line + '\n')
def CreateFile():#******************creating output log file*****
today = str(datetime.date.today()).split('-')
NowTime = str(datetime.datetime.now())[11:19:]
Nowtime_split = NowTime.split(':')
timestamp=Nowtime_split[0]+Nowtime_split[1]+Nowtime_split[2]
daystamp=today[0]+today[1]+today[2]
filename = 'log' + '_' + daystamp + '_' + timestamp + '.csv'
destfile = r'C:\Desktop' + str(filename)
file = open(destfile, 'w')
file.close()
return(destfile)
CreateFile=CreateFile()
``` | 2020/07/16 | [
"https://Stackoverflow.com/questions/62929201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13553201/"
] | Sure, split on two strings (all that consistently comes before, and all that consistently comes after) and specify that you want Split to remove the empties:
```
var r = names.Split(new[]{ "<?startname; ", "?>" }, StringSplitOptions.RemoveEmptyEntries);
```
If you take out the RemoveEmptyEntries it will give you a more clear idea of how the splitting is working, but in essence without it you'd get your names interspersed with array entries that are empty strings because split found a delimiter (the `<?...`) immediately following another (the `?>`) with an empty string between the delimiters
You can read the volumes of info about this form of split [here](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-3.1#System_String_Split_System_String___System_StringSplitOptions_) - that's a direct link to netcore3.1, you can change your version in the table of contents - this variant of Split has been available since framework2.0
---
You did also say "add to a separate list" - didn't see any code for that so I guess you will either be happy to proceed with `r` here being "a separate list" (an array actually, but probably adequately equivalent and easy to convert with LINQ's ToList() if not) or if you have another list of names (that really is a `List<string>`) then you can `thatList.AddRange(r)` it | Another Idea is to use Regex
The following regex should work :
`(?<=; )(.*?)(?=\s*\?>)` |
38,138,250 | I installed Theano 0.8.2 on Ubuntu 14.04, ran `theano.test()` and got the following error.
What would be the possible cause of this error?
>
> ======================================================================
> ERROR: test\_grad (theano.tensor.tests.test\_basic.ArctanhInplaceTester)
>
> ----------------------------------------------------------------------
>
> Traceback (most recent call last):
>
> File "/usr/local/lib/python2.7/dist-packages/theano/tensor/tests/test\_basic.py", line 483, in test\_grad
> eps=\_grad\_eps)
>
> File "/usr/local/lib/python2.7/dist-packages/theano/tests/unittest\_tools.py", line 91, in verify\_grad
>
> T.verify\_grad(op, pt, n\_tests, rng, \*args, \*\*kwargs)
>
> File "/usr/local/lib/python2.7/dist-packages/theano/gradient.py", line 1709, in verify\_grad
> abs\_tol, rel\_tol)
>
> GradientError: GradientError: numeric gradient and analytic gradient exceed tolerance:
>
> At position 4 of argument 0,
>
> abs. error = 3.537018, abs. tolerance = 0.010000
>
> rel. error = 0.013429, rel. tolerance = 0.010000
>
> Exception args:
>
> The error happened with the following inputs:, [array([[ 0.28898013, 0.98691875, -0.37341487],
>
> [-0.83661169, -0.99454761, -0.57619613]], dtype=float32)],
>
> The value of eps is:, None,
>
> The out\_type is:, None, Test arctanh\_inplace::normal: Error occurred while computing the gradient on the following inputs: [array([[ 0.28898013, 0.98691875, -0.37341487],
>
> [-0.83661169, -0.99454761, -0.57619613]], dtype=float32)]
>
>
> ======================================================================
> ERROR: test\_grad (theano.tensor.tests.test\_basic.ArctanhTester)
> ----------------------------------------------------------------------
> Traceback (most recent call last):
>
> File "/usr/local/lib/python2.7/dist-packages/theano/tensor/tests/test\_basic.py", line 483, in test\_grad
> eps=\_grad\_eps)
>
> File "/usr/local/lib/python2.7/dist-packages/theano/tests/unittest\_tools.py", line 91, in verify\_grad
> T.verify\_grad(op, pt, n\_tests, rng, \*args, \*\*kwargs)
>
> File "/usr/local/lib/python2.7/dist-packages/theano/gradient.py", line 1709, in verify\_grad
> abs\_tol, rel\_tol)
>
> GradientError: GradientError: numeric gradient and analytic gradient exceed tolerance:
>
> At position 4 of argument 0,
>
> abs. error = 3.537018, abs. tolerance = 0.010000
>
> rel. error = 0.013429, rel. tolerance = 0.010000
>
> Exception args:
>
> The error happened with the following inputs:, [array([[ 0.28898013, 0.98691875, -0.37341487],
>
> [-0.83661169, -0.99454761, -0.57619613]], dtype=float32)],
>
> The value of eps is:, None,
>
> The out\_type is:, None, Test Elemwise{arctanh,no\_inplace}::normal: Error occurred while computing the gradient on the following inputs: [array([[ 0.28898013, 0.98691875, -0.37341487],
> [-0.83661169, -0.99454761, -0.57619613]], dtype=float32)]
>
>
> ----------------------------------------------------------------------
>
> Ran 21747 tests in 7522.578s
>
>
> FAILED (SKIP=84, errors=2)
>
>
>
>
Thanks a lot. | 2016/07/01 | [
"https://Stackoverflow.com/questions/38138250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3041068/"
] | There now seems to be a way to trigger a lambda based on SQS queue message arrival:
*[AWS Lambda Adds Amazon Simple Queue Service to Supported Event Sources](https://aws.amazon.com/blogs/aws/aws-lambda-adds-amazon-simple-queue-service-to-supported-event-sources/)*
There are some things to consider, like you cannot use a FIFO SQS queue. | You can't really use long polling anyway as lambda will probably timeout before that.
You could [schedule](http://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html) your lambda to check periodically if you have a message in your queue. |
51,534,731 | So I am trying to create a form of encryption program with a GUI. Here is the code:
```
import sys
from PyQt4 import QtGui, QtCore
import os
from Crypto.Hash import SHA256
from Crypto import Random
from Crypto.Cipher import AES
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 300)
self.setWindowTitle("Encryptionprogram")
self.setWindowIcon(QtGui.QIcon('pythonicon.png'))
self.container = QtGui.QWidget()
self.setCentralWidget(self.container)
self.container_lay = QtGui.QVBoxLayout()
self.container.setLayout(self.container_lay)
extractAction = QtGui.QAction("Leave", self)
extractAction.setShortcut("Ctrl+Q")
extractAction.setStatusTip("Leave the app")
extractAction.triggered.connect(self.close_application)
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(extractAction)
#Inputs
self.Input = QtGui.QLineEdit("Filname", self)
self.Input.setFixedWidth(200)
self.Input.setFixedHeight(25)
self.Input.move(20, 200)
self.Input.setSizePolicy(QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Fixed)
self.Input2 = QtGui.QLineEdit("password", self)
self.Input2.setFixedWidth(200)
self.Input2.setFixedHeight(25)
self.Input2.move(220, 200)
self.Input2.setSizePolicy(QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Fixed)
self.home()
def home(self):
#Enter
self.enter_btn = QtGui.QPushButton("Enter")
self.container_lay.addWidget(self.enter_btn)
self.enter_btn.clicked.connect(self.run1)
self.checkBox = QtGui.QCheckBox('Krypter?', self)
self.checkBox.move(0, 60)
self.checkBox2 = QtGui.QCheckBox('Decrypt', self)
self.checkBox2.move(100, 60)
extractAction = QtGui.QAction(QtGui.QIcon('CloseIcon.png'), 'Close Program', self)
extractAction.triggered.connect(self.close_application)
self.toolBar = self.addToolBar("Extraction")
self.toolBar.addAction(extractAction)
self.show()
def enlarge_window(self, state):
if state == QtCore.Qt.Checked:
self.setGeometry(50, 50, 1250, 600)
else:
self.setGeometry(50, 50, 500, 300)
def close_application(self):
choice = QtGui.QMessageBox.question(self, 'Attention!',
"Close Program?",
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if choice == QtGui.QMessageBox.Yes:
print("Closing...")
sys.exit()
else:
pass
def closeEvent(self, event):
event.ignore()
self.close_application()
def getKey(self, password):
hasher = SHA256.new(password.encode('utf-8'))
return hasher.digest()
def run1(self):
if self.checkBox.isChecked():
Inputfilename = self.Input.text()
Inputpassword = self.Input2.text()
filename = str(Inputfilename)
password = str(Inputpassword)
print(filename, password)
self.encrypt(self.getKey(password), filename)
print("Done.")
else:
print("no work")
def encrypt(self, key, filename):
chunksize = 64 * 1024
outputFile = "(Krypteret)", filename
filesize = str(os.path.getsize(filename)).zfill(16)
IV = Random.new().read(16)
encryptor = AES.new(key, AES.MODE_CBC, IV)
with open(filename, 'rb') as infile:
with open(outputFile, 'wb') as outfile:
outfile.write(filesize.encode('utf-8'))
outfile.write(IV)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - (len(chunk) % 16))
outfile.write(encryptor.encrypt(chunk))
def decrypt(self, key, filename):
chunksize = 64 * 1024
outputFile = filename[11:]
with open(filename, 'rb') as infile:
filesize = int(infile.read(16))
IV = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, IV)
with open(outputFile, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(filesize)
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()
```
But I'm getting this error
```
Traceback (most recent call last):
File "D:/Dokumenter - HDD/Python/GUI.py", line 119, in run1
self.encrypt(self.getKey(password), filename)
File "D:/Dokumenter - HDD/Python/GUI.py", line 134, in encrypt
with open(outputFile, 'wb') as outfile:
TypeError: expected str, bytes or os.PathLike object, not tuple
Closing...
Process finished with exit code 0
```
I dont know how to fix this I have tried to find a solution not only just on the internet but i have also tried to fix it just be lokking after any potential mistakes but at this moment i have found nothing. If anyone could explain the error and/or come with a solution it would mean the world to me.
Thanks! | 2018/07/26 | [
"https://Stackoverflow.com/questions/51534731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10137836/"
] | You define outputfile as follows:
```
outputFile = "(Krypteret)", filename
```
which is a tuple, hence the error. It's not clear what you mean here; perhaps you wanted to prepend the word "(Krypteret)" to the existing filename? In which case you should do
```
outputFile = "(Krypteret)" + filename
```
(In future, please cut your code down to the minimum. The error is entirely within the `encrypt` method, you should have just posted that method.) | Or this:
```
outputFile = "(Krypteret)%s"%filename
```
Or this:
```
outputFile = "(Krypteret){}".format(filename)
```
This could not work depends on your python version:
```
outputFile = f"(Krypteret){filename}"
```
Your code doesn't work because `outputFile = "(Krypteret)", filename` returns an tuple. |
17,879,644 | If i have a list in python say
```
thing = [[20,0,1],[20,0,2],[20,1,1],[20,0],[30,1,1]]
```
I would want to have a resulting list
```
thing = [[20,1,1],[20,0,2],[30,1,1]]
```
That is if the first element is the same, remove duplicates and give priority to the number 1 in the second element. Lastly the 3rd element must also be unique to the first element.
In this [previous question](https://stackoverflow.com/questions/17827536/django-template-not-iterating-through-list) we solved a complicated method where for a transaction it details a purchased unit. I want to output other units in that course. If two transactions exist that relate to two units in one course it will display them a duplicate (or times each subsequent unit).
The aim of this question it to ensure that this duplication is stopped. Because of the complication of this solution it has resulted in a series of question. Thanks for everyone that has helped so far. | 2013/07/26 | [
"https://Stackoverflow.com/questions/17879644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725981/"
] | Read the documentation of `barplot` to understand how to specify zero space:
```
multhist(year, xlab="Count", ylab="Frequency", main="",
cex.axis=1, col=c("dark gray", "light gray"),
breaks=seq(0,1600, by=200),
space=c(0,0), beside=TRUE)
```
![enter image description here](https://i.stack.imgur.com/2VPmk.png)
Here is an example with ggplot2 and `theme_bw`:
```
library(ggplot2)
ggplot(df, aes(x=count,group=year,fill=as.factor(year))) +
geom_histogram(position="identity", alpha=0.5, breaks=seq(0,1600, by=200),right=TRUE) +
scale_fill_discrete(name="Year") +
theme_bw(base_size=20) +
xlab("values")
```
![enter image description here](https://i.stack.imgur.com/Tcrhe.png)
Or if you really want it like the plot from `multhist` (which is not as easy to interpret):
```
ggplot(df, aes(x=count,group=year,fill=as.factor(year))) +
geom_histogram(position="dodge", breaks=seq(0,1600, by=200),right=TRUE) +
scale_fill_discrete(name="Year") +
theme_bw(base_size=20) +
xlab("values") +
scale_x_continuous(breaks=seq(100,1500, by=200))
```
![enter image description here](https://i.stack.imgur.com/o17bi.png) | For superimposed histograms I prefer to use density plots. They're easier on the eyes, especially if you have thinner bins and more cases. With your data, one would get this.
```
ggplot(df, aes(x=count,group=year,fill=as.factor(year))) +
geom_density(position="identity", alpha=0.5, breaks=seq(0,1600, by=200),right=TRUE) +
scale_fill_discrete(name="Year") +
theme_bw() +
xlab("values")
```
![density plot](https://i.stack.imgur.com/dBJDN.png) |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Perhaps something more elegant would suffice?
```
[array removeObjectsInArray:[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"adID == 0"]]];
``` | ```
for(i=0; i < myArray.count; i++)
{
myClass = [myArray objectAtIndex:i];
if([myClass.adID isEqualtoString:"0"])// if it it int/NSInteger the write myClass.adID==0
{
[myArray removeObjectAtIndex:i];
i--;
}
}
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Perhaps something more elegant would suffice?
```
[array removeObjectsInArray:[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"adID == 0"]]];
``` | Use following code :
```
int count = array.count;
for(i=0;i<count;i++){
ADetail *adetail = [array objectAtIndex:i];
if(adetail.adID = 0){
[array removeObjectAtIndex:i];
i--;
}
count = array.count;
}
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Use following code :
```
int count = array.count;
for(i=0;i<count;i++){
ADetail *adetail = [array objectAtIndex:i];
if(adetail.adID = 0){
[array removeObjectAtIndex:i];
i--;
}
count = array.count;
}
``` | ```
predicate = @"adID == 0";
newArray = [theArray filterUsingPredicate:aPredicate]
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | ```
for(i=0; i < myArray.count; i++)
{
myClass = [myArray objectAtIndex:i];
if([myClass.adID isEqualtoString:"0"])// if it it int/NSInteger the write myClass.adID==0
{
[myArray removeObjectAtIndex:i];
i--;
}
}
``` | ```
predicate = @"adID == 0";
newArray = [theArray filterUsingPredicate:aPredicate]
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Using predicate
```
NSArray *filtered=[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(adId == 0)"]];
```
Using fastEnumeration:
```
NSMutableArray *newArray=[NSMutableArray new];
for(AdDetail adDetailObj in array){
if(![[adDetailObj adId] isEqualToString:@"0"]){ //if these are strings, if NSInteger then directly compare using ==
newArray[newArray.count]=adDetailObj;
}
}
```
Now `newArray` contains all objects other than `id=0` | ```
for(i=0; i < myArray.count; i++)
{
myClass = [myArray objectAtIndex:i];
if([myClass.adID isEqualtoString:"0"])// if it it int/NSInteger the write myClass.adID==0
{
[myArray removeObjectAtIndex:i];
i--;
}
}
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Using predicate
```
NSArray *filtered=[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(adId == 0)"]];
```
Using fastEnumeration:
```
NSMutableArray *newArray=[NSMutableArray new];
for(AdDetail adDetailObj in array){
if(![[adDetailObj adId] isEqualToString:@"0"]){ //if these are strings, if NSInteger then directly compare using ==
newArray[newArray.count]=adDetailObj;
}
}
```
Now `newArray` contains all objects other than `id=0` | ```
predicate = @"adID == 0";
newArray = [theArray filterUsingPredicate:aPredicate]
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Using predicate
```
NSArray *filtered=[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(adId == 0)"]];
```
Using fastEnumeration:
```
NSMutableArray *newArray=[NSMutableArray new];
for(AdDetail adDetailObj in array){
if(![[adDetailObj adId] isEqualToString:@"0"]){ //if these are strings, if NSInteger then directly compare using ==
newArray[newArray.count]=adDetailObj;
}
}
```
Now `newArray` contains all objects other than `id=0` | Use following code :
```
int count = array.count;
for(i=0;i<count;i++){
ADetail *adetail = [array objectAtIndex:i];
if(adetail.adID = 0){
[array removeObjectAtIndex:i];
i--;
}
count = array.count;
}
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Perhaps something more elegant would suffice?
```
[array removeObjectsInArray:[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"adID == 0"]]];
``` | ```
predicate = @"adID == 0";
newArray = [theArray filterUsingPredicate:aPredicate]
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | Using predicate
```
NSArray *filtered=[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(adId == 0)"]];
```
Using fastEnumeration:
```
NSMutableArray *newArray=[NSMutableArray new];
for(AdDetail adDetailObj in array){
if(![[adDetailObj adId] isEqualToString:@"0"]){ //if these are strings, if NSInteger then directly compare using ==
newArray[newArray.count]=adDetailObj;
}
}
```
Now `newArray` contains all objects other than `id=0` | ```
NSMutableArray *newArray = [NSMutableArray arrayWithArray:yourArray];
for (int i = 0; i < yourArray.count; i++)
{
AdDetail *obj = (AdDetail *)[yourArray objectAtIndex:i];
if (obj.adID == 0)
[newArray removeObjectAtIndex:i];
}
yourArray = [newArray mutableCopy];
``` |
15,783,722 | I am a bit new in python, i tried to read similar example but i cannot find my answer.
I am just trying to return two values in my generator, one is the number and the other one is the timestamp. It works fine with just the number but i cannot "print" the timestamp, can someone please help me on this?
```
import random
import datetime
mynumber = 1000
def generator():
i = 0
while 1:
yield random.randint(-1, 1)
now = datetime.datetime.now()
i = i + 1
for random_number in generator():
mynumber = mynumber + random_number
print mynumber
``` | 2013/04/03 | [
"https://Stackoverflow.com/questions/15783722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2239719/"
] | ```
NSMutableArray *newArray = [NSMutableArray arrayWithArray:yourArray];
for (int i = 0; i < yourArray.count; i++)
{
AdDetail *obj = (AdDetail *)[yourArray objectAtIndex:i];
if (obj.adID == 0)
[newArray removeObjectAtIndex:i];
}
yourArray = [newArray mutableCopy];
``` | ```
predicate = @"adID == 0";
newArray = [theArray filterUsingPredicate:aPredicate]
``` |
51,384,890 | This is the structure of my json file
```
},
"client1": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"1.1.1.1",
"2.2.2.2",
"3.3.3.3"
]
},
"client2": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"4.4.4.4",
"2.2.2.2"
]
},
```
I've seen ways to export specific parts of this json file but not everything. Basically all I want to do is search through the file using user input.
All I'm struggling with is how I actually use the user input to search and print everything under either client1 or client2 based on the input? I am sure this is only 1 or 2 lines of code but cannot figure it out. New to python. This is my code
```
data = json.load(open('clients.json'))
def client():
searchq = input('Client to export: '.capitalize())
search = ('""'+searchq+'"')
a = open('Log.json', 'a+')
a.write('Client: \n')
client()
``` | 2018/07/17 | [
"https://Stackoverflow.com/questions/51384890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10094523/"
] | If we take a look at the Ruby source code on Github, we can see that most of the kernel functionality is initialized in [`InitVM_Object`](https://github.com/ruby/ruby/blob/38e05ff3e194268fd2f38ac7c9530298e464f07b/object.c). However, `nil` is conspicuously absent, and the only clue of its existence is
```
/*
* An obsolete alias of +nil+
*/
rb_define_global_const("NIL", Qnil);
```
which, admittedly, I didn't actually know that `NIL` even worked in Ruby, but that's beside the point. Now we know that, in Ruby's C code, `Qnil` is our "nil" object. As it turns out, we can trace that back to *its* origin, in [`ruby.h`](https://github.com/ruby/ruby/blob/bcf8ce8494a6afb79196b37e856a556a649d0794/include/ruby/ruby.h). `Qnil` is not a variable; it's a `#define` pragma.
```
#define Qnil RUBY_Qnil
```
`RUBY_Qnil`, on the other hand, is defined as an enum constant.
```
enum ruby_special_consts {
RUBY_Qfalse = 0x00, /* ...0000 0000 */
RUBY_Qtrue = 0x14, /* ...0001 0100 */
RUBY_Qnil = 0x08, /* ...0000 1000 */
...
}
```
So it looks like `nil` is just a happy lie in Ruby. It's not even a real object at all; it's just a special magic number. `true` and `false` are also defined in that same enum. In fact, we can check that this is accurate in Ruby itself.
```
irb(main):009:0> false.object_id
=> 0
irb(main):010:0> true.object_id
=> 20
irb(main):011:0> nil.object_id
=> 8
```
`false`, `true`, and `nil` all have identifiers equal\* to the values we found in the enum, so this looks like it.
It's worth noting that while *nil* itself is a happy lie in the VM, the methods on `nil` are, of course, very real. The `NilClass` is defined in [`InitVM_Object`](https://github.com/ruby/ruby/blob/38e05ff3e194268fd2f38ac7c9530298e464f07b/object.c), and so are its methods. But `nil` is never *initialized*, per se.
\* It's technically possible that your values are different. The enum values listed here are protected by a `#if USE_FLONUM` block, which is set or unset depending on the size of various constants on your system. You can check out the criteria for that flag, as well as several other similar ones, in [`ruby.h`](https://github.com/ruby/ruby/blob/bcf8ce8494a6afb79196b37e856a556a649d0794/include/ruby/ruby.h). | [It's defined here](https://github.com/ruby/ruby/blob/5aa52587e86b9e2b03cad8b78307e53b777f1df2/include/ruby/ruby.h#L410-L443).
Namely, we have the lines:
```
RUBY_Qnil = 0x08
#define RUBY_Qnil ((VALUE)RUBY_Qnil)
#define Qnil RUBY_Qnil
```
This is why `nil.object_id == 8`.
`NilClass`, and its methods, are then defined [here](https://github.com/ruby/ruby/blob/38e05ff3e194268fd2f38ac7c9530298e464f07b/object.c#L4110-L4124):
```
rb_cNilClass = rb_define_class("NilClass", rb_cObject);
rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0);
rb_define_method(rb_cNilClass, "to_f", nil_to_f, 0);
rb_define_method(rb_cNilClass, "to_s", nil_to_s, 0);
rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
rb_define_method(rb_cNilClass, "&", false_and, 1);
rb_define_method(rb_cNilClass, "|", false_or, 1);
rb_define_method(rb_cNilClass, "^", false_xor, 1);
rb_define_method(rb_cNilClass, "===", rb_equal, 1);
rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
rb_undef_alloc_func(rb_cNilClass);
rb_undef_method(CLASS_OF(rb_cNilClass), "new");
```
Throughout the MRI source code, you'll then find countless references to `Qnil` |
51,384,890 | This is the structure of my json file
```
},
"client1": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"1.1.1.1",
"2.2.2.2",
"3.3.3.3"
]
},
"client2": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"4.4.4.4",
"2.2.2.2"
]
},
```
I've seen ways to export specific parts of this json file but not everything. Basically all I want to do is search through the file using user input.
All I'm struggling with is how I actually use the user input to search and print everything under either client1 or client2 based on the input? I am sure this is only 1 or 2 lines of code but cannot figure it out. New to python. This is my code
```
data = json.load(open('clients.json'))
def client():
searchq = input('Client to export: '.capitalize())
search = ('""'+searchq+'"')
a = open('Log.json', 'a+')
a.write('Client: \n')
client()
``` | 2018/07/17 | [
"https://Stackoverflow.com/questions/51384890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10094523/"
] | If we take a look at the Ruby source code on Github, we can see that most of the kernel functionality is initialized in [`InitVM_Object`](https://github.com/ruby/ruby/blob/38e05ff3e194268fd2f38ac7c9530298e464f07b/object.c). However, `nil` is conspicuously absent, and the only clue of its existence is
```
/*
* An obsolete alias of +nil+
*/
rb_define_global_const("NIL", Qnil);
```
which, admittedly, I didn't actually know that `NIL` even worked in Ruby, but that's beside the point. Now we know that, in Ruby's C code, `Qnil` is our "nil" object. As it turns out, we can trace that back to *its* origin, in [`ruby.h`](https://github.com/ruby/ruby/blob/bcf8ce8494a6afb79196b37e856a556a649d0794/include/ruby/ruby.h). `Qnil` is not a variable; it's a `#define` pragma.
```
#define Qnil RUBY_Qnil
```
`RUBY_Qnil`, on the other hand, is defined as an enum constant.
```
enum ruby_special_consts {
RUBY_Qfalse = 0x00, /* ...0000 0000 */
RUBY_Qtrue = 0x14, /* ...0001 0100 */
RUBY_Qnil = 0x08, /* ...0000 1000 */
...
}
```
So it looks like `nil` is just a happy lie in Ruby. It's not even a real object at all; it's just a special magic number. `true` and `false` are also defined in that same enum. In fact, we can check that this is accurate in Ruby itself.
```
irb(main):009:0> false.object_id
=> 0
irb(main):010:0> true.object_id
=> 20
irb(main):011:0> nil.object_id
=> 8
```
`false`, `true`, and `nil` all have identifiers equal\* to the values we found in the enum, so this looks like it.
It's worth noting that while *nil* itself is a happy lie in the VM, the methods on `nil` are, of course, very real. The `NilClass` is defined in [`InitVM_Object`](https://github.com/ruby/ruby/blob/38e05ff3e194268fd2f38ac7c9530298e464f07b/object.c), and so are its methods. But `nil` is never *initialized*, per se.
\* It's technically possible that your values are different. The enum values listed here are protected by a `#if USE_FLONUM` block, which is set or unset depending on the size of various constants on your system. You can check out the criteria for that flag, as well as several other similar ones, in [`ruby.h`](https://github.com/ruby/ruby/blob/bcf8ce8494a6afb79196b37e856a556a649d0794/include/ruby/ruby.h). | In MRI at least, nil (as well as true and false) are special constants statically created in the "C" interpreter code.
As such they are not created in the normal sense. Instead, its object id is a sort of marker for nil that is tested in the code as needed. While a bit chaotic, this would speed things up quite a bit.
```
/* special constants - i.e. non-zero and non-fixnum constants */
405 enum ruby_special_consts {
406 #if USE_FLONUM
407 RUBY_Qfalse = 0x00, /* ...0000 0000 */
408 RUBY_Qtrue = 0x14, /* ...0001 0100 */
409 RUBY_Qnil = 0x08, /* ...0000 1000 */
410 RUBY_Qundef = 0x34, /* ...0011 0100 */
411
412 RUBY_IMMEDIATE_MASK = 0x07,
413 RUBY_FIXNUM_FLAG = 0x01, /* ...xxxx xxx1 */
414 RUBY_FLONUM_MASK = 0x03,
415 RUBY_FLONUM_FLAG = 0x02, /* ...xxxx xx10 */
416 RUBY_SYMBOL_FLAG = 0x0c, /* ...0000 1100 */
417 #else
418 RUBY_Qfalse = 0, /* ...0000 0000 */
419 RUBY_Qtrue = 2, /* ...0000 0010 */
420 RUBY_Qnil = 4, /* ...0000 0100 */
421 RUBY_Qundef = 6, /* ...0000 0110 */
422
423 RUBY_IMMEDIATE_MASK = 0x03,
424 RUBY_FIXNUM_FLAG = 0x01, /* ...xxxx xxx1 */
425 RUBY_FLONUM_MASK = 0x00, /* any values ANDed with FLONUM_MASK cannot be FLONUM_FLAG */
426 RUBY_FLONUM_FLAG = 0x02,
427 RUBY_SYMBOL_FLAG = 0x0e, /* ...0000 1110 */
428 #endif
429 RUBY_SPECIAL_SHIFT = 8
430 };
``` |
51,384,890 | This is the structure of my json file
```
},
"client1": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"1.1.1.1",
"2.2.2.2",
"3.3.3.3"
]
},
"client2": {
"description": "blabla",
"contact name": "",
"contact email": "",
"third party organisation": "",
"third party contact name": "",
"third party contact email": "",
"ranges": [
"4.4.4.4",
"2.2.2.2"
]
},
```
I've seen ways to export specific parts of this json file but not everything. Basically all I want to do is search through the file using user input.
All I'm struggling with is how I actually use the user input to search and print everything under either client1 or client2 based on the input? I am sure this is only 1 or 2 lines of code but cannot figure it out. New to python. This is my code
```
data = json.load(open('clients.json'))
def client():
searchq = input('Client to export: '.capitalize())
search = ('""'+searchq+'"')
a = open('Log.json', 'a+')
a.write('Client: \n')
client()
``` | 2018/07/17 | [
"https://Stackoverflow.com/questions/51384890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10094523/"
] | In MRI at least, nil (as well as true and false) are special constants statically created in the "C" interpreter code.
As such they are not created in the normal sense. Instead, its object id is a sort of marker for nil that is tested in the code as needed. While a bit chaotic, this would speed things up quite a bit.
```
/* special constants - i.e. non-zero and non-fixnum constants */
405 enum ruby_special_consts {
406 #if USE_FLONUM
407 RUBY_Qfalse = 0x00, /* ...0000 0000 */
408 RUBY_Qtrue = 0x14, /* ...0001 0100 */
409 RUBY_Qnil = 0x08, /* ...0000 1000 */
410 RUBY_Qundef = 0x34, /* ...0011 0100 */
411
412 RUBY_IMMEDIATE_MASK = 0x07,
413 RUBY_FIXNUM_FLAG = 0x01, /* ...xxxx xxx1 */
414 RUBY_FLONUM_MASK = 0x03,
415 RUBY_FLONUM_FLAG = 0x02, /* ...xxxx xx10 */
416 RUBY_SYMBOL_FLAG = 0x0c, /* ...0000 1100 */
417 #else
418 RUBY_Qfalse = 0, /* ...0000 0000 */
419 RUBY_Qtrue = 2, /* ...0000 0010 */
420 RUBY_Qnil = 4, /* ...0000 0100 */
421 RUBY_Qundef = 6, /* ...0000 0110 */
422
423 RUBY_IMMEDIATE_MASK = 0x03,
424 RUBY_FIXNUM_FLAG = 0x01, /* ...xxxx xxx1 */
425 RUBY_FLONUM_MASK = 0x00, /* any values ANDed with FLONUM_MASK cannot be FLONUM_FLAG */
426 RUBY_FLONUM_FLAG = 0x02,
427 RUBY_SYMBOL_FLAG = 0x0e, /* ...0000 1110 */
428 #endif
429 RUBY_SPECIAL_SHIFT = 8
430 };
``` | [It's defined here](https://github.com/ruby/ruby/blob/5aa52587e86b9e2b03cad8b78307e53b777f1df2/include/ruby/ruby.h#L410-L443).
Namely, we have the lines:
```
RUBY_Qnil = 0x08
#define RUBY_Qnil ((VALUE)RUBY_Qnil)
#define Qnil RUBY_Qnil
```
This is why `nil.object_id == 8`.
`NilClass`, and its methods, are then defined [here](https://github.com/ruby/ruby/blob/38e05ff3e194268fd2f38ac7c9530298e464f07b/object.c#L4110-L4124):
```
rb_cNilClass = rb_define_class("NilClass", rb_cObject);
rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0);
rb_define_method(rb_cNilClass, "to_f", nil_to_f, 0);
rb_define_method(rb_cNilClass, "to_s", nil_to_s, 0);
rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0);
rb_define_method(rb_cNilClass, "to_h", nil_to_h, 0);
rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0);
rb_define_method(rb_cNilClass, "&", false_and, 1);
rb_define_method(rb_cNilClass, "|", false_or, 1);
rb_define_method(rb_cNilClass, "^", false_xor, 1);
rb_define_method(rb_cNilClass, "===", rb_equal, 1);
rb_define_method(rb_cNilClass, "nil?", rb_true, 0);
rb_undef_alloc_func(rb_cNilClass);
rb_undef_method(CLASS_OF(rb_cNilClass), "new");
```
Throughout the MRI source code, you'll then find countless references to `Qnil` |
12,607,241 | I am trying to install the `ScientificPython` package into a newly installed distribution of Python on a Fedora 14 x64 system. Pip finds `ScientificPython` in the repository but does not want to install it
```none
[bin]$ sudo ./python2.7 ./pip search ScientificPython
ScientificPython - Various Python modules for scientific computing
[bin]$ sudo ./python2.7 ./pip install ScientificPython
Downloading/unpacking ScientificPython
Could not find any downloads that satisfy the requirement ScientificPython
No distributions at all found for ScientificPython
Storing complete log in /tmp/tmpDLdmjy
```
Why could this happen?
Thanks! | 2012/09/26 | [
"https://Stackoverflow.com/questions/12607241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1672017/"
] | Have a look at the [ScientificPython entry on pypi](http://pypi.python.org/pypi/ScientificPython) and you will find that it only contains a link to their project page, no downloadable package or egg (which pip would need to install from). That's why pip told you `Could not find any downloads`. You will have to install by hand following their instructions.
Bottom line: if `pip search` lists a given package that doesn't necessarily mean you can `pip install` it (in most cases you fortunately can). | The package name is actually scipy, not ScientificPython
Try:
```
pip install scipy
``` |
12,607,241 | I am trying to install the `ScientificPython` package into a newly installed distribution of Python on a Fedora 14 x64 system. Pip finds `ScientificPython` in the repository but does not want to install it
```none
[bin]$ sudo ./python2.7 ./pip search ScientificPython
ScientificPython - Various Python modules for scientific computing
[bin]$ sudo ./python2.7 ./pip install ScientificPython
Downloading/unpacking ScientificPython
Could not find any downloads that satisfy the requirement ScientificPython
No distributions at all found for ScientificPython
Storing complete log in /tmp/tmpDLdmjy
```
Why could this happen?
Thanks! | 2012/09/26 | [
"https://Stackoverflow.com/questions/12607241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1672017/"
] | This may due to the unverified files in the installation package . try with the
**--allow-unverified**
>
> pip install package\_name==version --allow-unverified package\_name
>
>
>
**example**
pip install django-ajax-filtered-fields==0.5 --allow-unverified django-ajax-filtered-fields | The package name is actually scipy, not ScientificPython
Try:
```
pip install scipy
``` |
12,607,241 | I am trying to install the `ScientificPython` package into a newly installed distribution of Python on a Fedora 14 x64 system. Pip finds `ScientificPython` in the repository but does not want to install it
```none
[bin]$ sudo ./python2.7 ./pip search ScientificPython
ScientificPython - Various Python modules for scientific computing
[bin]$ sudo ./python2.7 ./pip install ScientificPython
Downloading/unpacking ScientificPython
Could not find any downloads that satisfy the requirement ScientificPython
No distributions at all found for ScientificPython
Storing complete log in /tmp/tmpDLdmjy
```
Why could this happen?
Thanks! | 2012/09/26 | [
"https://Stackoverflow.com/questions/12607241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1672017/"
] | Have a look at the [ScientificPython entry on pypi](http://pypi.python.org/pypi/ScientificPython) and you will find that it only contains a link to their project page, no downloadable package or egg (which pip would need to install from). That's why pip told you `Could not find any downloads`. You will have to install by hand following their instructions.
Bottom line: if `pip search` lists a given package that doesn't necessarily mean you can `pip install` it (in most cases you fortunately can). | This may due to the unverified files in the installation package . try with the
**--allow-unverified**
>
> pip install package\_name==version --allow-unverified package\_name
>
>
>
**example**
pip install django-ajax-filtered-fields==0.5 --allow-unverified django-ajax-filtered-fields |
66,614,260 | I have also seen the following two similar links, but they were different from mine that I will describe it in this post:
* [Apache Atlas: Http 503 Service Unavailable Error when connecting from Java Client](https://stackoverflow.com/questions/64610612/apache-atlas-http-503-service-unavailable-error-when-connecting-from-java-clien)
* [HTTP apache server Error 503 service unavailable](https://stackoverflow.com/questions/30020479/http-apache-server-error-503-service-unavailable)
I'm trying to run Apache Atlas on my local computer. So I have cloned it from the official repository.
From the *README.md* file of the repository I have entered the following two commands and it runs successfully:
1. `mvn clean install -DskipTests -X`
2. `mvn clean -DskipTests package -Pdist,embedded-hbase-solr`
[![enter image description here](https://i.stack.imgur.com/aiooj.png)](https://i.stack.imgur.com/aiooj.png)
These are the commands and changes I tried:
1. `tar xzvf apache-atlas-3.0.0-SNAPSHOT-server.tar.gz`
2. `cd apache-atlas-3.0.0-SNAPSHOT/bin/`
3. `python2.7 atlas_start.py`
After running the python script, I got this log:
```
configured for local hbase.
hbase started.
configured for local solr.
solr.xml doesn't exist in /bigdata/atlas/distro/target/apache-atlas-3.0.0-SNAPSHOT/data/solr, copying from /bigdata/atlas/distro/target/apache-atlas-3.0.0-SNAPSHOT/solr/server/solr/solr.xml
solr started.
setting up solr collections...
starting atlas on host localhost
starting atlas on port 21000
Apache Atlas Server started!!!
```
It seems that it doesn't have any problem, but whenever I want to test it with *curl*, something bad has happened?
```
curl -u admin:admin http://localhost:21000/api/atlas/v2/types/typedefs/head
```
Error:
```
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 503 Service Unavailable</title>
</head>
<body><h2>HTTP ERROR 503 Service Unavailable</h2>
<table>
<tr><th>URI:</th><td>/api/atlas/v2/types/typedefs/head</td></tr>
<tr><th>STATUS:</th><td>503</td></tr>
<tr><th>MESSAGE:</th><td>Service Unavailable</td></tr>
<tr><th>SERVLET:</th><td>-</td></tr>
</table>
<hr><a href="http://eclipse.org/jetty">Powered by Jetty:// 9.4.31.v20200723</a><hr/>
</body>
</html>
```
Here is the **application.log** file:
```
2021-03-13 17:05:37,484 INFO - [main:] ~ Loading atlas-application.properties from file:/bigdata/atlas/distro/target/apache-atlas-3.0.0-SNAPSHOT/conf/atlas-application.properties (ApplicationProperties:137)
2021-03-13 17:05:37,503 INFO - [main:] ~ Using graphdb backend 'janus' (ApplicationProperties:317)
2021-03-13 17:05:37,503 INFO - [main:] ~ Using storage backend 'hbase2' (ApplicationProperties:328)
2021-03-13 17:05:37,503 INFO - [main:] ~ Using index backend 'solr' (ApplicationProperties:339)
2021-03-13 17:05:37,515 INFO - [main:] ~ Atlas is running in MODE: PROD. (ApplicationProperties:343)
2021-03-13 17:05:37,516 INFO - [main:] ~ Setting solr-wait-searcher property 'true' (ApplicationProperties:349)
2021-03-13 17:05:37,516 INFO - [main:] ~ Setting index.search.map-name property 'false' (ApplicationProperties:353)
2021-03-13 17:05:37,516 INFO - [main:] ~ Setting atlas.graph.index.search.max-result-set-size = 150 (ApplicationProperties:363)
2021-03-13 17:05:37,517 INFO - [main:] ~ Property (set to default) atlas.graph.cache.db-cache = true (ApplicationProperties:375)
2021-03-13 17:05:37,517 INFO - [main:] ~ Property (set to default) atlas.graph.cache.db-cache-clean-wait = 20 (ApplicationProperties:375)
2021-03-13 17:05:37,517 INFO - [main:] ~ Property (set to default) atlas.graph.cache.db-cache-size = 0.5 (ApplicationProperties:375)
2021-03-13 17:05:37,517 INFO - [main:] ~ Property (set to default) atlas.graph.cache.tx-cache-size = 15000 (ApplicationProperties:375)
2021-03-13 17:05:37,518 INFO - [main:] ~ Property (set to default) atlas.graph.cache.tx-dirty-size = 120 (ApplicationProperties:375)
2021-03-13 17:05:37,535 INFO - [main:] ~
########################################################################################
Atlas Server (STARTUP)
project.name: apache-atlas
project.description: Metadata Management and Data Governance Platform over Hadoop
build.user: root
build.epoch: 1615641603895
project.version: 3.0.0-SNAPSHOT
build.version: 3.0.0-SNAPSHOT
vc.revision: 7eab2cb8d53ca4c86366e896119a1d7906ccb5b3
vc.source.url: scm:git:git://git.apache.org/atlas.git/atlas-webapp
######################################################################################## (Atlas:215)
2021-03-13 17:05:37,535 INFO - [main:] ~ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (Atlas:216)
2021-03-13 17:05:37,535 INFO - [main:] ~ Server starting with TLS ? false on port 21000 (Atlas:217)
2021-03-13 17:05:37,538 INFO - [main:] ~ <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< (Atlas:218)
2021-03-13 17:05:39,801 INFO - [main:] ~ No authentication method configured. Defaulting to simple authentication (LoginProcessor:102)
2021-03-13 17:05:40,136 WARN - [main:] ~ Unable to load native-hadoop library for your platform... using builtin-java classes where applicable (NativeCodeLoader:60)
2021-03-13 17:05:40,351 INFO - [main:] ~ Logged in user root (auth:SIMPLE) (LoginProcessor:77)
2021-03-13 17:05:41,716 INFO - [main:] ~ Not running setup per configuration atlas.server.run.setup.on.start. (SetupSteps$SetupRequired:189)
2021-03-13 17:05:43,892 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 1 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:44,989 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 2 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:46,092 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 3 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:47,194 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 4 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:48,295 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 5 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:49,397 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 6 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:50,499 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 7 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:51,601 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 8 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:52,703 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 9 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:53,805 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 10 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:54,907 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 11 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:56,009 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 12 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:57,110 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 13 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:58,212 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 14 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:05:59,313 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 15 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:00,414 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 16 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:01,517 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 17 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:02,618 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 18 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:03,720 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 19 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:04,822 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 20 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:16,941 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for get of /hbase/hbaseid, code = CONNECTIONLOSS, retries = 30, give up (ReadOnlyZKClient$ZKTask$1:196)
2021-03-13 17:06:16,958 WARN - [main:] ~ Retrieve cluster id failed (ConnectionImplementation:576)
java.util.concurrent.ExecutionException: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase/hbaseid
at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
at org.apache.hadoop.hbase.client.ConnectionImplementation.retrieveClusterId(ConnectionImplementation.java:574)
at org.apache.hadoop.hbase.client.ConnectionImplementation.<init>(ConnectionImplementation.java:307)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.apache.hadoop.hbase.client.ConnectionFactory.lambda$createConnection$0(ConnectionFactory.java:230)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/javax.security.auth.Subject.doAs(Subject.java:423)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1729)
at org.apache.hadoop.hbase.security.User$SecureHadoopUser.runAs(User.java:347)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:228)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:128)
at org.janusgraph.diskstorage.hbase2.HBaseCompat2_0.createConnection(HBaseCompat2_0.java:46)
at org.janusgraph.diskstorage.hbase2.HBaseStoreManager.<init>(HBaseStoreManager.java:314)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.janusgraph.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:58)
at org.janusgraph.diskstorage.Backend.getImplementationClass(Backend.java:440)
at org.janusgraph.diskstorage.Backend.getStorageManager(Backend.java:411)
at org.janusgraph.graphdb.configuration.builder.GraphDatabaseConfigurationBuilder.build(GraphDatabaseConfigurationBuilder.java:50)
at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:161)
at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:132)
at org.janusgraph.core.JanusGraphFactory.open(JanusGraphFactory.java:112)
at org.apache.atlas.repository.graphdb.janus.AtlasJanusGraphDatabase.initJanusGraph(AtlasJanusGraphDatabase.java:182)
at org.apache.atlas.repository.graphdb.janus.AtlasJanusGraphDatabase.getGraphInstance(AtlasJanusGraphDatabase.java:169)
at org.apache.atlas.repository.graphdb.janus.AtlasJanusGraphDatabase.getGraph(AtlasJanusGraphDatabase.java:278)
at org.apache.atlas.repository.graph.AtlasGraphProvider.getGraphInstance(AtlasGraphProvider.java:52)
at org.apache.atlas.repository.graph.AtlasGraphProvider.get(AtlasGraphProvider.java:98)
at org.apache.atlas.repository.graph.AtlasGraphProvider$$EnhancerBySpringCGLIB$$55698c0f.CGLIB$get$0(<generated>)
at org.apache.atlas.repository.graph.AtlasGraphProvider$$EnhancerBySpringCGLIB$$55698c0f$$FastClassBySpringCGLIB$$ec479fde.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at org.apache.atlas.repository.graph.AtlasGraphProvider$$EnhancerBySpringCGLIB$$55698c0f.get(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1176)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1071)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:211)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1134)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1098)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:211)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1134)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1098)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:89)
at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:102)
at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1041)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:1015)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:471)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:756)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.atlas.web.setup.KerberosAwareListener.contextInitialized(KerberosAwareListener.java:31)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:1013)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:553)
at org.eclipse.jetty.server.handler.ContextHandler.contextInitialized(ContextHandler.java:942)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:782)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:360)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1445)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1409)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:855)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:275)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:169)
at org.eclipse.jetty.server.Server.start(Server.java:408)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:110)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:97)
at org.eclipse.jetty.server.Server.doStart(Server.java:372)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.apache.atlas.web.service.EmbeddedServer.start(EmbeddedServer.java:113)
at org.apache.atlas.Atlas.main(Atlas.java:133)
Caused by: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase/hbaseid
at org.apache.zookeeper.KeeperException.create(KeeperException.java:102)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
at org.apache.hadoop.hbase.zookeeper.ReadOnlyZKClient$ZKTask$1.exec(ReadOnlyZKClient.java:198)
at org.apache.hadoop.hbase.zookeeper.ReadOnlyZKClient.run(ReadOnlyZKClient.java:342)
at java.base/java.lang.Thread.run(Thread.java:834)
2021-03-13 17:06:18,044 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for list of /hbase, code = CONNECTIONLOSS, retries = 1 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:19,144 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for list of /hbase, code = CONNECTIONLOSS, retries = 2 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:20,246 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for list of /hbase, code = CONNECTIONLOSS, retries = 3 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:21,348 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for list of /hbase, code = CONNECTIONLOSS, retries = 4 (ReadOnlyZKClient$ZKTask$1:192)
2021-03-13 17:06:22,449 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for list of /hbase, code = CONNECTIONLOSS, retries = 5 (ReadOnlyZKClient$ZKTask$1:192)
.
.
.
2021-03-13T13:58:36.264Z, RpcRetryingCaller{globalStartTime=1615643246874, pause=100, maxAttempts=16}, java.io.IOException: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase
at org.apache.hadoop.hbase.client.RpcRetryingCallerImpl.callWithRetries(RpcRetryingCallerImpl.java:145)
at org.apache.hadoop.hbase.client.HTable.get(HTable.java:383)
at org.apache.hadoop.hbase.client.HTable.get(HTable.java:357)
at org.apache.hadoop.hbase.MetaTableAccessor.getTableState(MetaTableAccessor.java:1164)
at org.apache.hadoop.hbase.MetaTableAccessor.tableExists(MetaTableAccessor.java:461)
at org.apache.hadoop.hbase.client.HBaseAdmin$6.rpcCall(HBaseAdmin.java:467)
at org.apache.hadoop.hbase.client.HBaseAdmin$6.rpcCall(HBaseAdmin.java:464)
at org.apache.hadoop.hbase.client.RpcRetryingCallable.call(RpcRetryingCallable.java:58)
at org.apache.hadoop.hbase.client.RpcRetryingCallerImpl.callWithRetries(RpcRetryingCallerImpl.java:107)
... 101 more
Caused by: java.io.IOException: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase
at org.apache.hadoop.hbase.client.ConnectionImplementation.get(ConnectionImplementation.java:2117)
at org.apache.hadoop.hbase.client.ConnectionImplementation.locateMeta(ConnectionImplementation.java:814)
at org.apache.hadoop.hbase.client.ConnectionImplementation.locateRegion(ConnectionImplementation.java:781)
at org.apache.hadoop.hbase.client.HRegionLocator.getRegionLocation(HRegionLocator.java:64)
at org.apache.hadoop.hbase.client.RegionLocator.getRegionLocation(RegionLocator.java:58)
at org.apache.hadoop.hbase.client.RegionLocator.getRegionLocation(RegionLocator.java:47)
at org.apache.hadoop.hbase.client.RegionServerCallable.prepare(RegionServerCallable.java:223)
at org.apache.hadoop.hbase.client.RpcRetryingCallerImpl.callWithRetries(RpcRetryingCallerImpl.java:105)
... 109 more
Caused by: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /hbase
at org.apache.zookeeper.KeeperException.create(KeeperException.java:102)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
at org.apache.hadoop.hbase.zookeeper.ReadOnlyZKClient$ZKTask$1.exec(ReadOnlyZKClient.java:198)
at org.apache.hadoop.hbase.zookeeper.ReadOnlyZKClient.run(ReadOnlyZKClient.java:342)
at java.base/java.lang.Thread.run(Thread.java:834)
2021-03-13 17:28:37,365 WARN - [ReadOnlyZKClient-localhost:2181@0x39acd1f1:] ~ 0x39acd1f1 to localhost:2181 failed for list of /hbase, code = CONNECTIONLOSS, retries = 1 (ReadOnlyZKClient$ZKTask$1:192)
```
Would someone help me how to install apache atlas properly?
**PS** I have also tried `2.1.0` version. Whenever I want to run it through `atlas_start.py` script, error has been occured.
```
Exception: [Errno 13] Permission denied
Traceback (most recent call last):
File "atlas_start.py", line 163, in <module>
returncode = main()
File "atlas_start.py", line 73, in main
mc.expandWebApp(atlas_home)
File "./distro/target/apache-atlas-2.1.0-bin/apache-atlas-2.1.0/bin/atlas_config.py", line 162, in expandWebApp
jar(atlasWarPath)
File "./distro/target/apache-atlas-2.1.0-bin/apache-atlas-2.1.0/bin/atlas_config.py", line 215, in jar
process = runProcess(commandline)
File "./distro/target/apache-atlas-2.1.0-bin/apache-atlas-2.1.0/bin/atlas_config.py", line 251, in runProcess
p = subprocess.Popen(commandline, stdout=stdoutFile, stderr=stderrFile, shell=shell)
File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied
``` | 2021/03/13 | [
"https://Stackoverflow.com/questions/66614260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7310077/"
] | The reason is because no matter how many times you append `board` to the list, the `board` variable will point at the same object.
Use the [`deepcopy()`](https://docs.python.org/2/library/copy.html#copy.deepcopy) method from the built-in [`copy`](https://docs.python.org/2/library/copy.html) module in the `for` loop to make copies of the object: | Your trying to append the same variable over over.
If you know for sure that `board` is a bidimensional array, you can append a list comprehension, like this:
```
l.append([array[:] for array in board])
```
If you don't know the shape of board, I suggest you use the same method as per Ann Zen's answer. |
69,860,181 | New to python-
I need to create a "while" loop that searches for the position of a certain string in a text file.
All the characters in the file have been set to integers (x = len(all)), so now I need a loop to search for the index/position of a certain string.
This is where I'm at right now:
```
string = 'found'
index = 0
while index < x:
if ????
```
Then it should print out something like
```
String found between (startIndex) and (endIndex)
``` | 2021/11/05 | [
"https://Stackoverflow.com/questions/69860181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17339907/"
] | You can use the .find() function:
```
string = "found"
x = "I found the index"
index = x.find(string)
end = index + len(string)
print(index, end)
```
2, 7 | Python has a built-in function called `index` that provides this functionality:
```py
string = "found"
with open("FILE", "r") as f:
for i,j in f.readlines():
if string in j:
foo = f.index(string)
print(f"String found at line {i+1} between ({foo}) and ({foo + len(string)})")
break
``` |
60,395,570 | im very new to python, trying to create reusable code. when i try to call the class Login and function login\_user in test\_main.py by passing all the arguments that were used under Login class, im getting an error as InvalidArgumentException: Message: invalid argument: 'using' must be a string.
test\_main.py file which runs on pytest.
Locators\_test is the class of test\_Locators.py file where i have all my xpaths
test\_Locators.py
```
class Locators_test():
loginlink_xpath = "//a[@id='login-link']"
login_email = "xxxxx"
login_password = "xxxxx"
loginemail_id = "dnn_ctr1179_Login_txtEmail"
loginpassword_id = "dnn_ctr1179_Login_txtPassword"
clicklogin_id = "dnn_ctr1179_Login_btnLogin"
```
test\_login.py
```
from Smoketest.locatorfile.test_Locators import Locators_test
class Login():
def __init__(self,driver):
self.driver = driver
def login_user(self,driver):
try:
loginButton = self.driver.find_element((By.XPATH, Locators_test.loginlink_xpath))
while loginButton.click() is True:
break
time.sleep(3)
self.driver.execute_script("window.scrollBy(0,300);")
EmailField = self.driver.find_element((By.ID, Locators_test.loginemail_id))
EmailField.send_keys(Locators_test.login_email)
PasswordField = self.driver.find_element((By.ID, Locators_test.loginpassword_id))
PasswordField.send_keys(Locators_test.login_password)
ClickLogin = self.driver.find_element((By.ID, Locators_test.clicklogin_id))
while ClickLogin.click() is True:
break
time.sleep(5)
userName = self.driver.find_element((By.XPATH, Locators_test.username_xpath))
print("Logged in as", userName.text)
except StaleElementReferenceException or ElementClickInterceptedException or TimeoutException as ex:
print(ex.message)
```
test\_main.py
```
def test_setup():
driver = webdriver.Chrome(executable_path= Locators_test.browser_path)
driver.maximize_window()
driver.delete_all_cookies()
driver.get(homePage)
driver.implicitly_wait(5)
yield
print("test complete")
def test_login(test_setup):
from Smoketest.pages.test_login import Login
lo = Login(driver)
lo.login_user(((Locators_test.loginlink_xpath,Locators_test.loginemail_id,Locators_test.login_email,Locators_test.loginpassword_id,Locators_test.login_password,Locators_test.clicklogin_id,Locators_test.username_xpath)))
```
***indentations are all fine*** | 2020/02/25 | [
"https://Stackoverflow.com/questions/60395570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12960312/"
] | I fixed it myself by removing the extra pair of parenthesis from the line
`loginButton = self.driver.find_element((By.XPATH, Locators_test.loginlink_xpath))`
Right way is
`loginButton = self.driver.find_element(By.XPATH, Locators_test.loginlink_xpath)`
ps: this applies to all the lines. | This worked for me,
```
locator = (By.XPATH, Locators_test.loginlink_xpath)
self.driver.find_element(*locator).click()
```
**Explanation:** In `*<arguments>`, all positional arguments other than the first one will be packed in a tuple, as they won't get Changed, the exact property will be reflected in the second step. |
6,892,036 | ```
"""
Saves a dir listing in a file
Usage: python listfiles.py -d dir -f filename [flags]
Arguments:
-d, --dir dir; ls of which will be saved in a file
-f, --file filename (if existing will be overwritten)
Flags:
-h, --help show this help
-v, --verbose be verbose
"""
...
def usage():
print __doc__
def main(args):
verbose = False
srcdir = filename = None
try:
opts, args = getopt.getopt(args,
'hvd:f:', ['help', 'verbose', 'dir=', 'file='])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(0)
if opt in ('-v', '--verbose'):
verbose = True
elif opt in ('-d', '--dir'):
srcdir = arg
elif opt in ('-f', '--file'):
filename = arg
if srcdir and filename:
fsock = open(filename, 'w')
write_dirlist_tosock(srcdir, fsock, verbose)
fsock.close()
else:
usage()
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[1:])
```
I am not sure if it is pythonic to use `getopt()` to also handle mandatory arguments. Would appreciate some suggestions | 2011/07/31 | [
"https://Stackoverflow.com/questions/6892036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1140524/"
] | the `getopt` module is only for those users who are already familiar with the same module in C, the python standard argument handling is [argparse](http://docs.python.org/dev/library/argparse.html). | "Mandatory Options" is a contradiction, and is not generally well supported by the various option parsing libraries; You should consider placing mandatory arguments as a positional arguments, not parsed by the option parser, this would agree with common practice much better. |
33,657,463 | I want to use unittest in python to check if a method returns object of the right class.
Every example in the web shows tests for 'type' returned.
For example, to check for `<type 'list'>` or `<type 'type'>` , we could use:
```
self.assertIsInstance(result, list)
self.assertIsInstance(result[0], tuple)
```
What I am looking for is an example to check for `<class'sqlalchemy.orm.query.Query'>`
Would appreciate any help. Thankyou. | 2015/11/11 | [
"https://Stackoverflow.com/questions/33657463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4971689/"
] | You could use `assertIsInstance()`, presumably using [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance) which is the recommended function for testing types. You could also `assertIs()` or `assertTrue()` combined with `type()` depending on the context:
```
#assert.py
import unittest
class TestType(unittest.TestCase):
def setUp(self):
self.number = 1
def test_assert_true(self):
self.assertTrue(type(self.number) is int)
def test_assert_is_instance(self):
self.assertIsInstance(self.number, int)
def test_assert_is_with_type(self):
self.assertIs(type(self.number), int)
def test_assert_is(self):
self.assertIs(self.number, int)
if __name__ == '__main__':
unittest.main()
$ python assert.py
test_assert_is (__main__.TestType) ... FAIL
test_assert_is_instance (__main__.TestType) ... ok
test_assert_is_with_type (__main__.TestType) ... ok
test_assert_true (__main__.TestType) ... ok
======================================================================
FAIL: test_assert_is (__main__.TestType)
----------------------------------------------------------------------
Traceback (most recent call last):
File "assert.py", line 19, in test_assert_is
self.assertIs(self.number, int)
AssertionError: 1 is not <type 'int'>
----------------------------------------------------------------------
Ran 4 tests in 0.000s
FAILED (failures=1)
```
The assertion error of the `test_assert_is(self)` might lead one to believe the type of 1 is not integer however it's comparing the object represented by 1 and the object that describes the type of an integer. This is most likely why `isinstance()` is preferred since it's more verbose about what it's checking and less typing is involved, so in general less error prone. | This should work:
```
self.assertIsInstance(result, sqlalchemy.orm.query.Query)
```
You need to have `import sqlalchemy` in the file. |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.
Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.
You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:
```
import Image
import numpy as np
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/4ciZO.jpg)
---
Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.
A better quality result could be made using imagemagick's `convert` command:
```
convert logo.png -background white -flatten /tmp/out.jpg
```
![enter image description here](https://i.stack.imgur.com/Qi8d0.jpg)
---
To make a nicer quality blend using numpy, you could use [alpha compositing](http://en.wikipedia.org/wiki/Alpha_compositing):
```
import Image
import numpy as np
def alpha_composite(src, dst):
'''
Return the alpha composite of src and dst.
Parameters:
src -- PIL RGBA Image object
dst -- PIL RGBA Image object
The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
'''
# http://stackoverflow.com/a/3375291/190597
# http://stackoverflow.com/a/9166671/190597
src = np.asarray(src)
dst = np.asarray(dst)
out = np.empty(src.shape, dtype = 'float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
src_a = src[alpha]/255.0
dst_a = dst[alpha]/255.0
out[alpha] = src_a+dst_a*(1-src_a)
old_setting = np.seterr(invalid = 'ignore')
out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
np.seterr(**old_setting)
out[alpha] *= 255
np.clip(out,0,255)
# astype('uint8') maps np.nan (and np.inf) to 0
out = out.astype('uint8')
out = Image.fromarray(out, 'RGBA')
return out
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/RBBhD.jpg) | ```
from PIL import Image
def fig2img ( fig ):
"""
@brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
@param fig a matplotlib figure
@return a Python Imaging Library ( PIL ) image
"""
# put the figure pixmap into a numpy array
buf = fig2data ( fig )
w, h, d = buf.shape
return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h, 4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf
def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True):
if not is_already_saved:
background = Image.new("RGB", img.size, c)
background.paste(img, mask=img.split()[3]) # 3 is the alpha channel
background.save(path, 'JPEG', quality=100)
is_already_saved = True
if if_load:
if is_already_saved:
im = Image.open(path)
return np.array(im)
else:
raise ValueError('No image to load.')
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building `RGBA -> JPG + BG` support for sorl thumbnails.
```
from PIL import Image
png = Image.open(object.logo.path)
png.load() # required for png.split()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
background.save('foo.jpg', 'JPEG', quality=80)
```
Result @80%
![enter image description here](https://i.stack.imgur.com/jaVG7.jpg)
Result @ 50%
![enter image description here](https://i.stack.imgur.com/9IsAI.jpg) | ```
from PIL import Image
def fig2img ( fig ):
"""
@brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
@param fig a matplotlib figure
@return a Python Imaging Library ( PIL ) image
"""
# put the figure pixmap into a numpy array
buf = fig2data ( fig )
w, h, d = buf.shape
return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h, 4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf
def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True):
if not is_already_saved:
background = Image.new("RGB", img.size, c)
background.paste(img, mask=img.split()[3]) # 3 is the alpha channel
background.save(path, 'JPEG', quality=100)
is_already_saved = True
if if_load:
if is_already_saved:
im = Image.open(path)
return np.array(im)
else:
raise ValueError('No image to load.')
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building `RGBA -> JPG + BG` support for sorl thumbnails.
```
from PIL import Image
png = Image.open(object.logo.path)
png.load() # required for png.split()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
background.save('foo.jpg', 'JPEG', quality=80)
```
Result @80%
![enter image description here](https://i.stack.imgur.com/jaVG7.jpg)
Result @ 50%
![enter image description here](https://i.stack.imgur.com/9IsAI.jpg) | By using [`Image.alpha_composite`](http://pillow.readthedocs.org/en/3.0.x/reference/Image.html#PIL.Image.alpha_composite), the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a `tuple index out of range` error if png has no alpha channel.
```
from PIL import Image
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255, 255, 255))
alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | It's not broken. It's doing exactly what you told it to; those pixels are black with full transparency. You will need to iterate across all pixels and convert ones with full transparency to white. | ```
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.
Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.
You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:
```
import Image
import numpy as np
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/4ciZO.jpg)
---
Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.
A better quality result could be made using imagemagick's `convert` command:
```
convert logo.png -background white -flatten /tmp/out.jpg
```
![enter image description here](https://i.stack.imgur.com/Qi8d0.jpg)
---
To make a nicer quality blend using numpy, you could use [alpha compositing](http://en.wikipedia.org/wiki/Alpha_compositing):
```
import Image
import numpy as np
def alpha_composite(src, dst):
'''
Return the alpha composite of src and dst.
Parameters:
src -- PIL RGBA Image object
dst -- PIL RGBA Image object
The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
'''
# http://stackoverflow.com/a/3375291/190597
# http://stackoverflow.com/a/9166671/190597
src = np.asarray(src)
dst = np.asarray(dst)
out = np.empty(src.shape, dtype = 'float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
src_a = src[alpha]/255.0
dst_a = dst[alpha]/255.0
out[alpha] = src_a+dst_a*(1-src_a)
old_setting = np.seterr(invalid = 'ignore')
out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
np.seterr(**old_setting)
out[alpha] *= 255
np.clip(out,0,255)
# astype('uint8') maps np.nan (and np.inf) to 0
out = out.astype('uint8')
out = Image.fromarray(out, 'RGBA')
return out
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/RBBhD.jpg) | It's not broken. It's doing exactly what you told it to; those pixels are black with full transparency. You will need to iterate across all pixels and convert ones with full transparency to white. |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | By using [`Image.alpha_composite`](http://pillow.readthedocs.org/en/3.0.x/reference/Image.html#PIL.Image.alpha_composite), the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a `tuple index out of range` error if png has no alpha channel.
```
from PIL import Image
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255, 255, 255))
alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)
``` | ```
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.
Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.
You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:
```
import Image
import numpy as np
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/4ciZO.jpg)
---
Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.
A better quality result could be made using imagemagick's `convert` command:
```
convert logo.png -background white -flatten /tmp/out.jpg
```
![enter image description here](https://i.stack.imgur.com/Qi8d0.jpg)
---
To make a nicer quality blend using numpy, you could use [alpha compositing](http://en.wikipedia.org/wiki/Alpha_compositing):
```
import Image
import numpy as np
def alpha_composite(src, dst):
'''
Return the alpha composite of src and dst.
Parameters:
src -- PIL RGBA Image object
dst -- PIL RGBA Image object
The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
'''
# http://stackoverflow.com/a/3375291/190597
# http://stackoverflow.com/a/9166671/190597
src = np.asarray(src)
dst = np.asarray(dst)
out = np.empty(src.shape, dtype = 'float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
src_a = src[alpha]/255.0
dst_a = dst[alpha]/255.0
out[alpha] = src_a+dst_a*(1-src_a)
old_setting = np.seterr(invalid = 'ignore')
out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
np.seterr(**old_setting)
out[alpha] *= 255
np.clip(out,0,255)
# astype('uint8') maps np.nan (and np.inf) to 0
out = out.astype('uint8')
out = Image.fromarray(out, 'RGBA')
return out
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/RBBhD.jpg) | ```
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | It's not broken. It's doing exactly what you told it to; those pixels are black with full transparency. You will need to iterate across all pixels and convert ones with full transparency to white. | ```
from PIL import Image
def fig2img ( fig ):
"""
@brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
@param fig a matplotlib figure
@return a Python Imaging Library ( PIL ) image
"""
# put the figure pixmap into a numpy array
buf = fig2data ( fig )
w, h, d = buf.shape
return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h, 4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf
def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True):
if not is_already_saved:
background = Image.new("RGB", img.size, c)
background.paste(img, mask=img.split()[3]) # 3 is the alpha channel
background.save(path, 'JPEG', quality=100)
is_already_saved = True
if if_load:
if is_already_saved:
im = Image.open(path)
return np.array(im)
else:
raise ValueError('No image to load.')
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | ```
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
``` | ```
from PIL import Image
def fig2img ( fig ):
"""
@brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
@param fig a matplotlib figure
@return a Python Imaging Library ( PIL ) image
"""
# put the figure pixmap into a numpy array
buf = fig2data ( fig )
w, h, d = buf.shape
return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h, 4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf
def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True):
if not is_already_saved:
background = Image.new("RGB", img.size, c)
background.paste(img, mask=img.split()[3]) # 3 is the alpha channel
background.save(path, 'JPEG', quality=100)
is_already_saved = True
if if_load:
if is_already_saved:
im = Image.open(path)
return np.array(im)
else:
raise ValueError('No image to load.')
``` |
9,166,400 | I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
### Source file
![transparent source file](https://i.stack.imgur.com/I2uNe.png)
### Code
```
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')
```
or
```
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')
```
### Result
Both ways, the resulting image looks like this:
![resulting file](https://i.stack.imgur.com/rmlPz.png)
Is there a way to fix this? I'd like to have white background where the transparent background used to be.
---
Solution
========
Thanks to the great answers, I've come up with the following function collection:
```
import Image
import numpy as np
def alpha_to_color(image, color=(255, 255, 255)):
"""Set all fully transparent pixels of an RGBA image to the specified color.
This is a very simple solution that might leave over some ugly edges, due
to semi-transparent areas. You should use alpha_composite_with color instead.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def alpha_composite(front, back):
"""Alpha composite two RGBA images.
Source: http://stackoverflow.com/a/9166671/284318
Keyword Arguments:
front -- PIL RGBA Image object
back -- PIL RGBA Image object
"""
front = np.asarray(front)
back = np.asarray(back)
result = np.empty(front.shape, dtype='float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
falpha = front[alpha] / 255.0
balpha = back[alpha] / 255.0
result[alpha] = falpha + balpha * (1 - falpha)
old_setting = np.seterr(invalid='ignore')
result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
np.seterr(**old_setting)
result[alpha] *= 255
np.clip(result, 0, 255)
# astype('uint8') maps np.nan and np.inf to 0
result = result.astype('uint8')
result = Image.fromarray(result, 'RGBA')
return result
def alpha_composite_with_color(image, color=(255, 255, 255)):
"""Alpha composite an RGBA image with a single color image of the
specified color and the same size as the original image.
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
back = Image.new('RGBA', size=image.size, color=color + (255,))
return alpha_composite(image, back)
def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
NOTE: This version is much slower than the
alpha_composite_with_color solution. Use it only if
numpy is not available.
Source: http://stackoverflow.com/a/9168169/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
def blend_value(back, front, a):
return (front * a + back * (255 - a)) / 255
def blend_rgba(back, front):
result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
return tuple(result + [255])
im = image.copy() # don't edit the reference directly
p = im.load() # load pixel array
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x, y] = blend_rgba(color + (255,), p[x, y])
return im
def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
"""Alpha composite an RGBA Image with a specified color.
Simpler, faster version than the solutions above.
Source: http://stackoverflow.com/a/9459208/284318
Keyword Arguments:
image -- PIL RGBA Image object
color -- Tuple r, g, b (default 255, 255, 255)
"""
image.load() # needed for split()
background = Image.new('RGB', image.size, color)
background.paste(image, mask=image.split()[3]) # 3 is the alpha channel
return background
```
Performance
-----------
The simple non-compositing `alpha_to_color` function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but `alpha_composite_with_color` is much faster (8.93 msec) than `pure_pil_alpha_to_color` (79.6 msec). ~~If numpy is available on your system, that's the way to go.~~ (Update: The new pure PIL version is the fastest of all mentioned solutions.)
```
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop
``` | 2012/02/06 | [
"https://Stackoverflow.com/questions/9166400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/284318/"
] | By using [`Image.alpha_composite`](http://pillow.readthedocs.org/en/3.0.x/reference/Image.html#PIL.Image.alpha_composite), the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a `tuple index out of range` error if png has no alpha channel.
```
from PIL import Image
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255, 255, 255))
alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)
``` | The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.
Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.
You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:
```
import Image
import numpy as np
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/4ciZO.jpg)
---
Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.
A better quality result could be made using imagemagick's `convert` command:
```
convert logo.png -background white -flatten /tmp/out.jpg
```
![enter image description here](https://i.stack.imgur.com/Qi8d0.jpg)
---
To make a nicer quality blend using numpy, you could use [alpha compositing](http://en.wikipedia.org/wiki/Alpha_compositing):
```
import Image
import numpy as np
def alpha_composite(src, dst):
'''
Return the alpha composite of src and dst.
Parameters:
src -- PIL RGBA Image object
dst -- PIL RGBA Image object
The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
'''
# http://stackoverflow.com/a/3375291/190597
# http://stackoverflow.com/a/9166671/190597
src = np.asarray(src)
dst = np.asarray(dst)
out = np.empty(src.shape, dtype = 'float')
alpha = np.index_exp[:, :, 3:]
rgb = np.index_exp[:, :, :3]
src_a = src[alpha]/255.0
dst_a = dst[alpha]/255.0
out[alpha] = src_a+dst_a*(1-src_a)
old_setting = np.seterr(invalid = 'ignore')
out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
np.seterr(**old_setting)
out[alpha] *= 255
np.clip(out,0,255)
# astype('uint8') maps np.nan (and np.inf) to 0
out = out.astype('uint8')
out = Image.fromarray(out, 'RGBA')
return out
FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')
```
![enter image description here](https://i.stack.imgur.com/RBBhD.jpg) |
30,077,037 | I am new to kivy. I want to switch to another screen (Signup screen) when 'signup' button is clicked on the main screen (Login screen). here is the python code:
```
import kivy
kivy.require('1.9.0')
import ConfigParser
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import Screen, ScreenManager
Window.size = (700, 550)
class LoginPage(Screen):
def switch_screen(*args):
global sm
print "i am in login and will switch to signup"
sm.current = 'signup'
class SignUp(Screen):
print "signup screen"
pass
sm = ScreenManager()
sm.add_widget(LoginPage(name="login"))
sm.add_widget(SignUp(name="signup"))
class Test(App):
icon = "C:\Users\shru\Desktop\download.jpg"
title = "Member Login"
def build(self):
return sm
if __name__ == "__main__":
Test().run()
```
Here is the .kv code
```
<LoginPage>:
canvas:
Rectangle:
source: "C:\Users\shru\Desktop\m.jpg"
size: self.size
Widget:
Button:
size: 90,35
pos: 380,200
font_size:15
background_color: (1,1,1,0.3)
text: "SignUp"
on_press: root.switch_screen()
<SignUp>:
canvas:
Rectangle:
source: "C:\Users\shru\Desktop\m.jpg"
size: self.size
Widget:
Button:
size: 90,35
pos: 380,200
font_size:15
background_color: (1,1,1,0.3)
text: "hello"
```
This on execution returns blank screen. Am I doing something wrong?
Thank you | 2015/05/06 | [
"https://Stackoverflow.com/questions/30077037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3690252/"
] | You create instances of your widget before the App is run, which is also before the kv file has been loaded, so your kv rules aren't applied and you see nothing.
Move the `sm =` etc. into the build method to fix this, the kv file is loaded before this method is run. | These changes in the code made it work:
```
sm = ScreenManager()
class Test(App):
def build(self):
sm.add_widget(LoginPage(name="login"))
sm.add_widget(SignUp(name="signup"))
return sm
if __name__ == "__main__":
Test().run()
``` |
73,102,797 | I'm using a parameter that is the timestamp in a set of tasks:
```py
default_dag_args = {'arg1': 'arg1-value',
'arg2': 'arg2-value',
'now': datetime.now()}
```
I would like that the now parameter would have the same value for all the tasks. But what happens is that it's re-executed for each function
Is there a way of doing it (executing once and using the same value through the dag)? I'm using the TaskFlow API for Airflow 2.0:
```py
@task
def python_task()
context = get_current_context()
context_dag = context['dag']
now = context_dag.default_args['now']
print now
``` | 2022/07/24 | [
"https://Stackoverflow.com/questions/73102797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6364850/"
] | I tried to set the time constant, at the start of the dag file, like:
```
TIME = datetime.now()
```
and got the context inside of the tasks with `get_current_context()` just like you did.
Sadly, I think because of running the DAG file from start, every time a task got defined in the script, time was recalculated.
One idea I have is to use XCOM's in order to save the datetime to a variable and pull it to other tasks:
My sample code is below, I think you'll get the idea.
```
from airflow.decorators import task, dag
from datetime import datetime
import time
default_arguments = {
'owner': 'admin',
# This is the beginning, for more see: https://airflow.apache.org/faq.html#what-s-the-deal-with-start-date
'start_date': datetime(2022, 5, 2)
}
@dag(
schedule_interval=None,
dag_id = "Time_Example_Dag",
default_args = default_arguments,
catchup=False,
)
def the_global_time_checker_dag():
@task
def time_set():
# To use XCOM to pass the value between tasks,
# we have to parse the datetime to a string.
now = str(datetime.now())
return now
@task
def starting_task(datetime_string):
important_number = 23
# We can use this datetime object in whatever way we like.
date_time_obj = datetime.strptime(datetime_string, '%Y-%m-%d %H:%M:%S.%f')
print(date_time_obj)
return important_number
@task
def important_task(datetime_string, number):
# Passing some time
time.sleep(10)
# Again, we are free to do whatever we want with this object.
date_time_obj = datetime.strptime(datetime_string, '%Y-%m-%d %H:%M:%S.%f')
print(date_time_obj)
print("The important number is: {}".format(number))
time_right_now = time_set()
start = starting_task(datetime_string = time_right_now)
important = important_task(datetime_string = time_right_now, number = start)
time_checker = the_global_time_checker_dag()
```
Through the logs, you can see all the datetime values are the same.
For more information about XCOM in Taskflow API, you can [check here.](https://airflow.apache.org/docs/apache-airflow/stable/tutorial_taskflow_api.html#consuming-xcoms-between-decorated-and-traditional-tasks) | When a worker gets a task instance to run, it rebuilds the whole DagBag from the Python files to get the DAG and task definition. So every time a task instance is ran, your DAG file is sourced, rerunning your DAG definition code. And that resulting DAG object is the one that the particular task instance will be defined by.
It's critical to understand that the DAG definition is not simply built once for every execution date and then persisted/reused for all TIs within that DagRun. The DAG definition is constantly being recomputed from your Python code, each TI is ran in a separate process independently and without state from other tasks. Thus, if your DAG definition includes non-deterministic results at DagBag build time - such as `datetime.now()` - every instantiation of your DAG even for the same execution date will have different values. You need to build your DAGs in a deterministic and idempotent manner.
The only way to share non-deterministic results is to store them in the DB and have your tasks fetch them, as @sezai-burak-kantarcı has pointed out. Best practice is to use task context-specific variables, like `{{ ds }}`, `{{ execution_date }}`, `{{ data_interval_start }}`, etc. These are the same for all tasks within a DAG run. You can see the template variables available here: [Airflow emplates reference](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) |
44,977,683 | So I've been working through Al Sweigart's online Automate The Boring Stuff With Python tutorials, and I've just got to the webscraping part. Here's my code with a description of what the program is supposed to do:
```
#! python3
# lucky.py - A small program that allows you to get search keywords from
# command line arguments, retrieve the search results page, and open
# a new browser tab for each result
# Steps:
# 1. Read the command line arguments from sys.argv
# 2. Fetch the search result page with the requests module
# 3. Find the links to each search result
# 4. Call the webbrowser.open() function to open the web browser
import sys, requests, bs4, webbrowser
# 1. Read the command line arguments from sys.argv
print('Googling...')
if len(sys.argv) > 1:
search = ' '.join(sys.argv[1:])
url = "https://www.google.com/#q="
for i in range(len(search.split())):
url += search.split()[i] + "+"
# 2. Fetch the search result page with the requests module
page = requests.get(url)
# 3. Find the links to each search result
soup = bs4.BeautifulSoup(page.text, 'lxml')
linkElems = soup.select('.r a')
# 4. Call the webbrowser.open() function to open the web browser
numOpen = min(5, len(linkElems))
for i in range(numOpen):
webbrowser.open("http://google.com" + linkElems[i].get('href'))
```
So the issue here is that when I check the length of linkElems, it's 0, meaning that the soup.select('.r a') command failed to aggregate the content defined under element <a> inside class=r (a class only used for search results in Google as can be seen when using the developer tools). As a result, no web pages of the search results open up in my browser.
I think the issue has something to do either with the HTML-parser not working correctly, or Google changing the way their HTML code works(?). Any insight into this issue would be greatly appreciated! | 2017/07/07 | [
"https://Stackoverflow.com/questions/44977683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5633365/"
] | Google seems to be detecting that you're a bot and not a real webbrowser with Cookies and Javascript. What they seem to be trying to do with the new results is still get web scrapers to follow the links they provide and prefix them with <https://www.google.com> so that when you then go to that URL, they can still track your movement.
You could also try to find a pattern in the link provided. For instance, when you search for 'linux', it returns the following:
```
/url?q=https://en.wikipedia.org/wiki/Linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.org/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.com/what-is-linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=d50ea51a-206b-11e8-9432-2bee635f8337
/url?q=https://www.ubuntu.com/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=dab9f6a4-206b-11e8-a999-3fc9d4576425
/search?q=linux&ie=UTF-8&prmd=ivns&source=univ&tbm=nws&tbo=u&sa=X&ved=9775308e-206b-11e8-b45f-fb72cae612a8
```
You could use a regex to grab the part between '/url?q=' and '&sa=U&ved=' as that's the URL that you probably want. Of course, that doesn't work with the 5th result that it returned because it's something special for the Google website. Again, Probably tacking <https://www.google.com> on the front of each URL returned is the safest thing to do.
Most search engines (even duckduckgo.com) are trying to track search results and clicks. If you try to avoid it they have detection code in place to block you. You may have run into this with Google telling you they've detected a large number of searches from your IP and you have to go through a CAPTCHA test to continue. | `linkElems = soup.find_all('a',href=True)` This returns all the relevant `<a>` tags and you can process the list to decide what to keep and what not to keep. |
44,977,683 | So I've been working through Al Sweigart's online Automate The Boring Stuff With Python tutorials, and I've just got to the webscraping part. Here's my code with a description of what the program is supposed to do:
```
#! python3
# lucky.py - A small program that allows you to get search keywords from
# command line arguments, retrieve the search results page, and open
# a new browser tab for each result
# Steps:
# 1. Read the command line arguments from sys.argv
# 2. Fetch the search result page with the requests module
# 3. Find the links to each search result
# 4. Call the webbrowser.open() function to open the web browser
import sys, requests, bs4, webbrowser
# 1. Read the command line arguments from sys.argv
print('Googling...')
if len(sys.argv) > 1:
search = ' '.join(sys.argv[1:])
url = "https://www.google.com/#q="
for i in range(len(search.split())):
url += search.split()[i] + "+"
# 2. Fetch the search result page with the requests module
page = requests.get(url)
# 3. Find the links to each search result
soup = bs4.BeautifulSoup(page.text, 'lxml')
linkElems = soup.select('.r a')
# 4. Call the webbrowser.open() function to open the web browser
numOpen = min(5, len(linkElems))
for i in range(numOpen):
webbrowser.open("http://google.com" + linkElems[i].get('href'))
```
So the issue here is that when I check the length of linkElems, it's 0, meaning that the soup.select('.r a') command failed to aggregate the content defined under element <a> inside class=r (a class only used for search results in Google as can be seen when using the developer tools). As a result, no web pages of the search results open up in my browser.
I think the issue has something to do either with the HTML-parser not working correctly, or Google changing the way their HTML code works(?). Any insight into this issue would be greatly appreciated! | 2017/07/07 | [
"https://Stackoverflow.com/questions/44977683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5633365/"
] | Google seems to be detecting that you're a bot and not a real webbrowser with Cookies and Javascript. What they seem to be trying to do with the new results is still get web scrapers to follow the links they provide and prefix them with <https://www.google.com> so that when you then go to that URL, they can still track your movement.
You could also try to find a pattern in the link provided. For instance, when you search for 'linux', it returns the following:
```
/url?q=https://en.wikipedia.org/wiki/Linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.org/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.com/what-is-linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=d50ea51a-206b-11e8-9432-2bee635f8337
/url?q=https://www.ubuntu.com/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=dab9f6a4-206b-11e8-a999-3fc9d4576425
/search?q=linux&ie=UTF-8&prmd=ivns&source=univ&tbm=nws&tbo=u&sa=X&ved=9775308e-206b-11e8-b45f-fb72cae612a8
```
You could use a regex to grab the part between '/url?q=' and '&sa=U&ved=' as that's the URL that you probably want. Of course, that doesn't work with the 5th result that it returned because it's something special for the Google website. Again, Probably tacking <https://www.google.com> on the front of each URL returned is the safest thing to do.
Most search engines (even duckduckgo.com) are trying to track search results and clicks. If you try to avoid it they have detection code in place to block you. You may have run into this with Google telling you they've detected a large number of searches from your IP and you have to go through a CAPTCHA test to continue. | There's no need in `phantomjs` or `selenium`. Also, query `param` is wrong: `#q=` -> `?q=`.
You can limit selected links by using `list` slicing:
```py
linkElems = soup.select('.r a')[:5]
# or
for i in soup.select('.r a')[:5]:
# other code..
```
Make sure you're using `user-agent` because default `requests` `user-agent` is [`python-requests`](https://github.com/psf/requests/blob/589c4547338b592b1fb77c65663d8aa6fbb7e38b/requests/utils.py#L808-L814) thus Google blocks a request because it knows that it's a bot and not a "real" user visit and you'll receive a different HTML with some sort of an error. `User-agent` fakes user visit by adding this information into [HTTP request headers](https://github.com/psf/requests/blob/589c4547338b592b1fb77c65663d8aa6fbb7e38b/requests/utils.py#L808-L814).
I wrote a dedicated blog about [how to reduce chance of being blocked while web scraping search engines](https://dev.to/dimitryzub/how-to-reduce-chance-being-blocked-while-web-scraping-search-engines-1o46) that cover multiple solutions.
Pass `user-agent` in request `headers`:
```py
headers = {
'User-agent':
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
requests.get('YOUR_URL', headers=headers)
```
---
Code:
```py
from bs4 import BeautifulSoup
import requests, lxml
headers = {
'User-agent':
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
params = {
"q": "samurai cop what does katana mean",
"gl": "us",
"hl": "en"
}
html = requests.get("https://www.google.com/search", headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')
for result in soup.select('.tF2Cxc')[:5]:
title = result.select_one('.DKV0Md').text
link = result.select_one('.yuRUbf a')['href']
print(title, link, sep='\n')
--------
'''
Samurai Cop - He speaks fluent Japanese - YouTube
https://www.youtube.com/watch?v=paTW3wOyIYw
Samurai Cop - What does "katana" mean? - Quotes.net
https://www.quotes.net/mquote/1060647
"It means "Japanese sword"... 2 minute review of a ... - Reddit
https://www.reddit.com/r/NewTubers/comments/47hw1g/what_does_katana_mean_it_means_japanese_sword_2/
Samurai Cop (1991) - Mathew Karedas as Joe Marshall - IMDb
https://www.imdb.com/title/tt0130236/characters/nm0360481
What does Katana mean? - Samurai Cop quotes - Subzin.com
http://www.subzin.com/quotes/Samurai+Cop/What+does+Katana+mean%3F+-+It+means+Japanese+sword
```
---
Alternatively, you can achieve the same thing by using [Google Organic Results API](https://serpapi.com/organic-results) from SerpApi. It's a paid API with a free plan.
The difference in your case is that you only need to iterate over structured JSON and get the data you want rather than making everything from scratch and maintain it over time.
Code to integrate:
```py
import os
from serpapi import GoogleSearch
params = {
"engine": "google",
"q": "samurai cop what does katana mean",
"hl": "en",
"gl": "us",
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
for result in results["organic_results"][:5]:
print(result['title'])
print(result['link'])
---------
'''
Samurai Cop - He speaks fluent Japanese - YouTube
https://www.youtube.com/watch?v=paTW3wOyIYw
Samurai Cop - What does "katana" mean? - Quotes.net
https://www.quotes.net/mquote/1060647
"It means "Japanese sword"... 2 minute review of a ... - Reddit
https://www.reddit.com/r/NewTubers/comments/47hw1g/what_does_katana_mean_it_means_japanese_sword_2/
Samurai Cop (1991) - Mathew Karedas as Joe Marshall - IMDb
https://www.imdb.com/title/tt0130236/characters/nm0360481
What does Katana mean? - Samurai Cop quotes - Subzin.com
http://www.subzin.com/quotes/Samurai+Cop/What+does+Katana+mean%3F+-+It+means+Japanese+sword
'''
```
>
> Disclaimer, I work for SerpApi.
>
>
> |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | Because this is just how Python works - keywords such as `class` and `def` are *not* declarations. Instead, they are *real live* statements which are executed. If they were not executed your module would be empty.
The idiomatic approach is:
```
# stuff to run always here such as class/def
def main():
pass
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
main()
```
It does require source control over the module being imported, however. | Put the code inside a function and it won't run until you call the function. You should have a main function in your `main.py`. with the statement:
```
if __name__ == '__main__':
main()
```
Then, if you call `python main.py` the `main()` function will run. If you import `main.py`, it will not. Also, you should probably rename `main.py` to something else for clarity's sake. |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | Due to the way Python works, it is necessary for it to run your modules when it imports them.
To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this `if`:
```
if __name__ == "__main__":
# this won't be run when imported
```
You may want to put this code in a `main()` method, so that you can either execute the file directly, or import the module and call the `main()`. For example, assume this is in the file `foo.py`.
```
def main():
print "Hello World"
if __name__ == "__main__":
main()
```
This program can be run either by going `python foo.py`, or from another Python script:
```
import foo
...
foo.main()
``` | Put the code inside a function and it won't run until you call the function. You should have a main function in your `main.py`. with the statement:
```
if __name__ == '__main__':
main()
```
Then, if you call `python main.py` the `main()` function will run. If you import `main.py`, it will not. Also, you should probably rename `main.py` to something else for clarity's sake. |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | You may write your "main.py" like this:
```
#!/usr/bin/env python
__all__=["somevar", "do_something"]
somevar=""
def do_something():
pass #blahblah
if __name__=="__main__":
do_something()
``` | A minor error that could happen (at least it happened to me), especially when distributing python scripts/functions that carry out a complete analysis, was to call the function directly at the end of the function .py file.
The only things a user needed to modify were the input files and parameters.
Doing so when you import you'll get the function running immediately. For proper behavior, you simply need to remove the inside call to the function and reserve it for the real calling file/function/portion of code |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | Because this is just how Python works - keywords such as `class` and `def` are *not* declarations. Instead, they are *real live* statements which are executed. If they were not executed your module would be empty.
The idiomatic approach is:
```
# stuff to run always here such as class/def
def main():
pass
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
main()
```
It does require source control over the module being imported, however. | Try just importing the functions needed from main.py? So,
```
from main import SomeFunction
```
It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope. |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | A minor error that could happen (at least it happened to me), especially when distributing python scripts/functions that carry out a complete analysis, was to call the function directly at the end of the function .py file.
The only things a user needed to modify were the input files and parameters.
Doing so when you import you'll get the function running immediately. For proper behavior, you simply need to remove the inside call to the function and reserve it for the real calling file/function/portion of code | Although you cannot use `import` without running the code; there is quite a swift way in which you can input your variables; by using `numpy.savez`, which stores variables as numpy arrays in a .npz file. Afterwards you can load the variables using `numpy.load`.
See a full description [in the scipy documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savez.html)
Please note this is only the case for variables and arrays of variable, and not for methods, etc. |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | Due to the way Python works, it is necessary for it to run your modules when it imports them.
To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this `if`:
```
if __name__ == "__main__":
# this won't be run when imported
```
You may want to put this code in a `main()` method, so that you can either execute the file directly, or import the module and call the `main()`. For example, assume this is in the file `foo.py`.
```
def main():
print "Hello World"
if __name__ == "__main__":
main()
```
This program can be run either by going `python foo.py`, or from another Python script:
```
import foo
...
foo.main()
``` | Use the `if __name__ == '__main__'` idiom -- `__name__` is a special variable whose value is `'__main__'` if the module is being run as a script, and the module name if it's imported. So you'd do something like
```
# imports
# class/function definitions
if __name__ == '__main__':
# code here will only run when you invoke 'python main.py'
``` |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | Because this is just how Python works - keywords such as `class` and `def` are *not* declarations. Instead, they are *real live* statements which are executed. If they were not executed your module would be empty.
The idiomatic approach is:
```
# stuff to run always here such as class/def
def main():
pass
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
main()
```
It does require source control over the module being imported, however. | There was a Python enhancement proposal [PEP 299](https://www.python.org/dev/peps/pep-0299/) which aimed to replace `if __name__ == '__main__':` idiom with `def __main__:`, but it was rejected. It's still a good read to know what to keep in mind when using `if __name__ = '__main__':`. |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | Use the `if __name__ == '__main__'` idiom -- `__name__` is a special variable whose value is `'__main__'` if the module is being run as a script, and the module name if it's imported. So you'd do something like
```
# imports
# class/function definitions
if __name__ == '__main__':
# code here will only run when you invoke 'python main.py'
``` | There was a Python enhancement proposal [PEP 299](https://www.python.org/dev/peps/pep-0299/) which aimed to replace `if __name__ == '__main__':` idiom with `def __main__:`, but it was rejected. It's still a good read to know what to keep in mind when using `if __name__ = '__main__':`. |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | There was a Python enhancement proposal [PEP 299](https://www.python.org/dev/peps/pep-0299/) which aimed to replace `if __name__ == '__main__':` idiom with `def __main__:`, but it was rejected. It's still a good read to know what to keep in mind when using `if __name__ = '__main__':`. | I did a simple test:
#test.py
```
x = 1
print("1, has it been executed?")
def t1():
print("hello")
print("2, has it been executed?")
def t2():
print("world")
print("3, has it been executed?")
def main():
print("Hello World")
print("4, has it been executed?")
print("5, has it been executed?")
print(x)
# while True:
# t2()
if x == 1:
print("6, has it been executed?")
```
#test2.py
```
import test
```
When executing or running test2.py, the running result:
```
1, has it been executed?
5, has it been executed?
1
6, has it been executed?
```
**Conclusion:** When the imported module does not add **`if __name__=="__main__":`**, the current module is run, The code in the imported module that is not in the function is executed sequentially, and the code in the function is not executed when it is not called.
in addition:
```
def main():
# Put all your code you need to execute directly when this script run directly.
pass
if __name__ == '__main__':
main()
else:
# Put functions you need to be executed only whenever imported
``` |
6,523,791 | I have a Python program I'm building that can be run in either of 2 ways: the first is to call `python main.py` which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call `python batch.py *-file-*` which will pass over all the friendly input gathering and run an entire file's worth of input through the program in a single go.
The problem is that when I run `batch.py`, it imports some variables/methods/etc from `main.py`, and when it runs this code:
```
import main
```
at the first line of the program, it immediately errors because it tries to run the code in `main.py`.
How can I stop Python from running the code contained in the `main` module which I'm importing? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6523791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367544/"
] | Put the code inside a function and it won't run until you call the function. You should have a main function in your `main.py`. with the statement:
```
if __name__ == '__main__':
main()
```
Then, if you call `python main.py` the `main()` function will run. If you import `main.py`, it will not. Also, you should probably rename `main.py` to something else for clarity's sake. | You may write your "main.py" like this:
```
#!/usr/bin/env python
__all__=["somevar", "do_something"]
somevar=""
def do_something():
pass #blahblah
if __name__=="__main__":
do_something()
``` |
73,032,143 | I have a postgres table with unique columns. I upload dataframes to the table using copy expert and psycopg2 in python. There are duplicate columns in the uploading dataframe. How can I remove the duplicate columns on the uploading dataframe and upload the dataframe?
**Postgres table:**
| email (unique) | verified | id |
| --- | --- | --- |
| jason@gmail.com | True | 1 |
| eunice@gmail.com | None | 2 |
| sam@outlook.com | True | 3 |
| riley@outlook.com | None | 4 |
List to be uploaded
| email | verified |
| --- | --- |
| jason@gmail.com | None |
| eunice@gmail.com | None |
| benita@outlook.com | None |
| james@outlook.com | None |
Expected table result:
| email (unique) | verified | id |
| --- | --- | --- |
| jason@gmail.com | True | 1 |
| eunice@gmail.com | None | 2 |
| sam@outlook.com | True | 3 |
| riley@outlook.com | None | 4 |
| benita@outlook.com | None | 5 |
| james@outlook.com | None | 6 | | 2022/07/19 | [
"https://Stackoverflow.com/questions/73032143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19415105/"
] | If you don't need to change the `$c` variable don't do it you have already set a default value in the function.
```
HelloWorld(1, 6);
function HelloWorld($a, $b = 0,$c = [],$max_text_length = 50) {
print_r([$a, $b,$c,$max_text_length]);
}
```
Result:
```
Array
(
[0] => 1 //<-- $a
[1] => 6 //<-- $b
[2] => Array //<-- $c
(
)
[3] => 50 //<-- $max_text_length
)
``` | If you are able to modify the function call, you can try this:
```
<?php echo HelloWorld($a, $b = 6, $c ?? []); ?>
```
So that if `$c` is not already defined of if it is `null`, an empty array (`[]`) will be used. If `$c` is set, it will be used. See: <https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op> |
73,669,362 | I have tried to use **subprocess.check\_output()** for getting the **ps aux** command using python but it looks like not working with the large grep string.
Can anyone have any solution?
```
subprocess.check_output('ps aux | grep "bin/scrapy" | grep "option1" | grep "option2" | grep "option3" | grep "option4" | grep "option5"' , shell =True)
``` | 2022/09/10 | [
"https://Stackoverflow.com/questions/73669362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16502801/"
] | Here's a code snippet that might help you
```bash
# capture stderr into a variable and print it
echo "capture stderr into a variable and print it"
var=$(lt -l /tmp 2>&1)
echo $var
capture stderr into a variable and print it
zsh: command not found: lt
# capture stdout into a variable and print it
echo "capture stdout into a variable and print it"
var=$(ls -l /tmp)
echo $var
# capture both stderr and stdout into a variable and print it
echo "capture both stderr and stdout into a variable and print it"
var=$(ls -l /tmp 2>&1)
echo $var
# more classic way of executing a command which I always follow is as follows. This way I am always in control of what is going on and can act accordingly
if somecommand ; then
echo "command succeeded"
else
echo "command failed"
fi
```
If you have to capture the output and stderr in different variables, then the following might help as well
```bash
## create a file using file descriptor for stdout
exec 3> stdout.txt
# create a file using file descriptor for stderr
exec 4> stderr.txt
A=$($1 /tmp 2>&4 >&3);
## close file descriptor
exec 3>&-
exec 4>&-
## open file descriptor for reading
exec 3< stdout.txt
exec 4< stderr.txt
## read from file using file descriptor
read line <&3
read line2 <&4
## close file descriptor
exec 3<&-
exec 4<&-
## print line read from file
echo "stdout: $line"
echo "stderr: $line2"
## delete file
rm stdout.txt
rm stderr.txt
```
You can try running it with the following
```bash
╰─ bash test.sh pwd
stdout: /tmp/somedir
stderr:
╰─ bash test.sh pwdd
stdout:
stderr: test.sh: line 8: pwdd: command not found
``` | As noted in a comment your use case may be better served in other scripting languages. An example: in Perl you can achieve what you want quite simple:
```
#!/usr/bin/env perl
use v5.26; # or earlier versions
use Capture::Tiny 'capture'; # library is not in core
my $cmd = 'date';
my @arg = ('-R', '-u');
my ($stdout, $stderr, $exit) = capture {
system( $cmd, @arg );
};
say "STDOUT: $stdout";
say "STDERR: $stderr";
say "EXIT: $exit";
```
I'm sure similar solutions are available in python, ruby, and all the rest. |
73,669,362 | I have tried to use **subprocess.check\_output()** for getting the **ps aux** command using python but it looks like not working with the large grep string.
Can anyone have any solution?
```
subprocess.check_output('ps aux | grep "bin/scrapy" | grep "option1" | grep "option2" | grep "option3" | grep "option4" | grep "option5"' , shell =True)
``` | 2022/09/10 | [
"https://Stackoverflow.com/questions/73669362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16502801/"
] | Here's a code snippet that might help you
```bash
# capture stderr into a variable and print it
echo "capture stderr into a variable and print it"
var=$(lt -l /tmp 2>&1)
echo $var
capture stderr into a variable and print it
zsh: command not found: lt
# capture stdout into a variable and print it
echo "capture stdout into a variable and print it"
var=$(ls -l /tmp)
echo $var
# capture both stderr and stdout into a variable and print it
echo "capture both stderr and stdout into a variable and print it"
var=$(ls -l /tmp 2>&1)
echo $var
# more classic way of executing a command which I always follow is as follows. This way I am always in control of what is going on and can act accordingly
if somecommand ; then
echo "command succeeded"
else
echo "command failed"
fi
```
If you have to capture the output and stderr in different variables, then the following might help as well
```bash
## create a file using file descriptor for stdout
exec 3> stdout.txt
# create a file using file descriptor for stderr
exec 4> stderr.txt
A=$($1 /tmp 2>&4 >&3);
## close file descriptor
exec 3>&-
exec 4>&-
## open file descriptor for reading
exec 3< stdout.txt
exec 4< stderr.txt
## read from file using file descriptor
read line <&3
read line2 <&4
## close file descriptor
exec 3<&-
exec 4<&-
## print line read from file
echo "stdout: $line"
echo "stderr: $line2"
## delete file
rm stdout.txt
rm stderr.txt
```
You can try running it with the following
```bash
╰─ bash test.sh pwd
stdout: /tmp/somedir
stderr:
╰─ bash test.sh pwdd
stdout:
stderr: test.sh: line 8: pwdd: command not found
``` | I gave it another try using [process substitution](https://stackoverflow.com/a/692407/1694803) and came up with this:
```
# command with no error
date +%b > >(read A; if [ "$A" = 'Sep' ]; then echo 'September'; fi ) 2> >(read B; if [ ! -z "$B" ]; then echo "$B"; fi >&2)
September
# command with error
date b > >(read A; if [ "$A" = 'Sep' ]; then echo 'September'; fi ) 2> >(read B; if [ ! -z "$B" ]; then echo "$B"; fi >&2)
date: invalid date “b“
# command with both at the same time should work too
```
I had no success "exporting" the variables from the subprocesses back to the original script. It might be possible though. I just couldn't figure it out.
But this gives you at least access to `stdout` and `stderr` as a variable. This means you can do whatever processing you want on them as variables. It depends on your use case if this is of any help to you. Good luck :-) |
63,100,425 | [Google Colab Runtime Selection](https://i.stack.imgur.com/m1iwV.png)
Is there way to change runtime type in Google Colab using python code instead of using GUI as shown in the image. | 2020/07/26 | [
"https://Stackoverflow.com/questions/63100425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10250530/"
] | You can read the notebook.ipynb into json string. Edit it, the overwrite it or create a new notebook file.
It may be easier to download it, edit it with a text editor, then upload and open it again.
For example, a notebook.ipynb with GPU runtime will look like this
```
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {...},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"accelerator": "GPU"
},
"cells": [...]
}
```
To change to Python 2.7, you change "name":"python2".
To change to GPU runtime, you add "accelerator": "GPU".
You can do this by hand (edit it in a text editor) or by Python (read json to dict, replace, overwrite, re-open). | You can change run time type by going
`Runtime` -> `Change run time type` -> `GPU,TPU` |
15,927,596 | I'm working on some python dicts of tuples. Each tuple containing 2 ints. The first digit in the tuple is reffered to as value and the second digit is referred to as work. I have 3 different comparators and I need to sort the dicts into descending order. This order should be determined by which comparator is called. i.e. the dict can be sorted 3 different ways. I've tried as many different ways as I could find to get this to work. I can do it without using the comparator by just breaking it up into a list and sorting by slicing the tuples but if anyone can shed some light on the syntax to sort using the comparators it would be greatly appreciated. Mine seems to be returning correctly for cmpWork but the other 2 aren't reversed.
Also it would be great if I could get the dict sorted by the tuple values.
I got a sort working with
```
sortedSubjects = sorted(tmpSubjects.iteritems(), key = operator.itemgetter(1), reverse = True)
```
but this doesn't let me slice the tuples.
First time posting noob so apologies for any mistakes.
```
def cmpValue(subInfo1, subInfo2):
return cmp(subInfo2[0] , subInfo1[0])
def cmpWork(subInfo1, subInfo2):
return cmp(subInfo1[1] , subInfo2[1])
def cmpRatio(subInfo1, subInfo2):
return cmp((float(subInfo2[0]) / subInfo2[1]) , (float(subInfo1[0]) / subInfo1[1]))
def greedyAdvisor(subjects, comparator):
tmpSubjects = subjects.copy()
sortedSubjects = sorted(tmpSubjects.values(), comparator, reverse = True)
print sortedSubjects
smallCatalog = {'6.00': (16, 8),'1.00': (7, 7),'6.01': (5, 3),'15.01': (9, 6)}
greedyAdvisor(smallCatalog, cmpRatio)
greedyAdvisor(smallCatalog, cmpValue)
greedyAdvisor(smallCatalog, cmpWork)
[(7, 7), (9, 6), (5, 3), (16, 8)]
[(5, 3), (7, 7), (9, 6), (16, 8)]
[(16, 8), (7, 7), (9, 6), (5, 3)]
```
ps
The line
```
sortedSubjects = sorted(tmpSubjects.iteritems(), key = operator.itemgetter(1), reverse = True)
```
returns
```
[('6.00', (16, 8)), ('15.01', (9, 6)), ('1.00', (7, 7)), ('6.01', (5, 3))]
```
which is almost exactly what I'm looking for except that I can't sort by the second value in the tuple and I can't sort by cmpRatio either. | 2013/04/10 | [
"https://Stackoverflow.com/questions/15927596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266053/"
] | >
> but this doesn't let me slice the tuples
>
>
>
Starting with your example:
```
sortedSubjects = sorted(tmpSubjects.iteritems(),
key=operator.itemgetter(1),
cmp=comparator, # What about specifying the comparison?
reverse=True)
``` | If you need to sort dictionary - use collections.OrderedDict
E.g., sort by 1st element of tuple
```
OrderedDict(sorted(smallCatalog.items(), key=lambda e:e[1][0]))
Out[109]: OrderedDict([('6.01', (5, 3)), ('1.00', (7, 7)), ('15.01', (9, 6)), ('6.00', (16, 8))])
``` |
9,013,354 | I apologize if this has been asked here - I've hunted around here and in the Tentative NumPy Tutorial for an answer.
I have 2 numpy arrays. The first array is similar to:
```
1 0 0 0 0
2 0 0 0 0
3 0 0 0 0
4 0 0 0 0
5 0 0 0 0
6 0 0 0 0
7 0 0 0 0
8 0 0 0 0
```
(etc... It's ~700x10 in actuality)
I then have a 2nd array similar to
```
3 1
4 18
5 2
```
(again, longer - maybe 400 or so rows)
The first column of the 2nd array is always completely contained within the first column of the first array
What I'd like to do is to insert the 2nd column of the 2nd array into that first array as part of an existing column, i.e:
array a:
```
1 0 0 0 0
2 0 0 0 0
3 1 0 0 0
4 18 0 0 0
5 2 0 0 0
6 0 0 0 0
7 0 0 0 0
8 0 0 0 0
```
(I'd be filling in each of those columns in turn, but each covers a different range within the original)
My first try was along the lines of a[b[:,0],1]=b[:,1] which puts them into the indices of b, not the values (ie, in my example above instead of filling in rows 3, 4, and 5, I filled in 2, 3, and 4). I should have realized that!
Since then, I've tried to make it work pretty inelegantly with where(), and I think I could make it work by finding the difference in the starting values of the first columns.
I'm new to python, so perhaps I'm overly optimistic - but it seems like there should be a more elegant way and I'm just missing it.
Thanks for any insights! | 2012/01/26 | [
"https://Stackoverflow.com/questions/9013354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1170478/"
] | If the numbers in the first column of `a` are in sorted order, then you could use
```
a[a[:,0].searchsorted(b[:,0]),1] = b[:,1]
```
For example:
```
import numpy as np
a = np.array([(1,0,0,0,0),
(2,0,0,0,0),
(3,0,0,0,0),
(4,0,0,0,0),
(5,0,0,0,0),
(6,0,0,0,0),
(7,0,0,0,0),
(8,0,0,0,0),
])
b = np.array([(3, 1),
(5, 18),
(7, 2)])
a[a[:,0].searchsorted(b[:,0]),1] = b[:,1]
print(a)
```
yields
```
[[ 1 0 0 0 0]
[ 2 0 0 0 0]
[ 3 1 0 0 0]
[ 4 0 0 0 0]
[ 5 18 0 0 0]
[ 6 0 0 0 0]
[ 7 2 0 0 0]
[ 8 0 0 0 0]]
```
(I changed your example a bit to show that the values in `b`'s first column do not have to be contiguous.)
---
If `a[:,0]` is not in sorted order, then you could use `np.argsort` to workaround this:
```
a = np.array( [(1,0,0,0,0),
(2,0,0,0,0),
(5,0,0,0,0),
(3,0,0,0,0),
(4,0,0,0,0),
(6,0,0,0,0),
(7,0,0,0,0),
(8,0,0,0,0),
])
b = np.array([(3, 1),
(5, 18),
(7, 2)])
perm = np.argsort(a[:,0])
a[:,1][perm[a[:,0][perm].searchsorted(b[:,0])]] = b[:,1]
print(a)
```
yields
```
[[ 1 0 0 0 0]
[ 2 0 0 0 0]
[ 5 18 0 0 0]
[ 3 1 0 0 0]
[ 4 0 0 0 0]
[ 6 0 0 0 0]
[ 7 2 0 0 0]
[ 8 0 0 0 0]]
``` | The setup:
```
a = np.arange(20).reshape(2,10).T
b = np.array([[1, 100], [3, 300], [8, 800]])
```
This will work if you don't know anything about a[:, 0] except that it is sorted.
```
index = a[:, 0].searchsorted(b[:, 0])
a[index, 1] = b[:, 1]
print a
array([[ 0, 10],
[ 1, 100],
[ 2, 12],
[ 3, 300],
[ 4, 14],
[ 5, 15],
[ 6, 16],
[ 7, 17],
[ 8, 800],
[ 9, 19]])
```
But if you know that `a[:, 0]` is a sequence of contiguous integers like your example you can do:
```
index = b[:,0] + a[0, 0]
a[index, 1] = b[:, 1]
``` |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | You can reverse a string using -1 as the step in a slice. So this works:
```
number = 2376674032
number_s = str(number)
reverse_s = number_s[::-1]
reversed = int(reverse_s)
``` | you want to reverse a number …..input it as string format , and do this:
```
number="8374783246837"
revnumber=number[::-1]
```
Done
[![enter image description here](https://i.stack.imgur.com/72nW2.png)](https://i.stack.imgur.com/72nW2.png) |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | You can reverse a string using -1 as the step in a slice. So this works:
```
number = 2376674032
number_s = str(number)
reverse_s = number_s[::-1]
reversed = int(reverse_s)
``` | ```
a = 1234
a = int("".join(reversed(str(a))))
```
This will give a = 4321
reversed functions returns an iterable object.
If we do :
```
a = list(reversed(str(a)))
```
it will return [“3”,”2″,”1″]. We have then joined it and converted into int. |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | You can reverse a string using -1 as the step in a slice. So this works:
```
number = 2376674032
number_s = str(number)
reverse_s = number_s[::-1]
reversed = int(reverse_s)
``` | ```
#here is my answer . you can do it using simple recursion
# count digits recursively
def reverse_digits(n):
# base case
if n == 0:
pass
#recursive case
else:
print(n%10,end='')
return reverse_digits(n//10)
# reverse 123
reverse_digits(123)
````````````````````````````````````````````````````
``` |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | You can reverse a string using -1 as the step in a slice. So this works:
```
number = 2376674032
number_s = str(number)
reverse_s = number_s[::-1]
reversed = int(reverse_s)
``` | To make the number an `integer` type, we have to use the `int` function, as below:
```
numbers=str(123456)
#or numbers="123456"
print((int(numbers[::-1])))
print((type(int(numbers[::-1]))))
```
output:
>
> 654321
>
> <class 'int'>
>
>
> |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | You can reverse a string using -1 as the step in a slice. So this works:
```
number = 2376674032
number_s = str(number)
reverse_s = number_s[::-1]
reversed = int(reverse_s)
``` | We can do this in a single line as well using [::-1]
print(int(str(int(input()))[::-1])) |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | you want to reverse a number …..input it as string format , and do this:
```
number="8374783246837"
revnumber=number[::-1]
```
Done
[![enter image description here](https://i.stack.imgur.com/72nW2.png)](https://i.stack.imgur.com/72nW2.png) | ```
#here is my answer . you can do it using simple recursion
# count digits recursively
def reverse_digits(n):
# base case
if n == 0:
pass
#recursive case
else:
print(n%10,end='')
return reverse_digits(n//10)
# reverse 123
reverse_digits(123)
````````````````````````````````````````````````````
``` |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | ```
a = 1234
a = int("".join(reversed(str(a))))
```
This will give a = 4321
reversed functions returns an iterable object.
If we do :
```
a = list(reversed(str(a)))
```
it will return [“3”,”2″,”1″]. We have then joined it and converted into int. | ```
#here is my answer . you can do it using simple recursion
# count digits recursively
def reverse_digits(n):
# base case
if n == 0:
pass
#recursive case
else:
print(n%10,end='')
return reverse_digits(n//10)
# reverse 123
reverse_digits(123)
````````````````````````````````````````````````````
``` |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | To make the number an `integer` type, we have to use the `int` function, as below:
```
numbers=str(123456)
#or numbers="123456"
print((int(numbers[::-1])))
print((type(int(numbers[::-1]))))
```
output:
>
> 654321
>
> <class 'int'>
>
>
> | ```
#here is my answer . you can do it using simple recursion
# count digits recursively
def reverse_digits(n):
# base case
if n == 0:
pass
#recursive case
else:
print(n%10,end='')
return reverse_digits(n//10)
# reverse 123
reverse_digits(123)
````````````````````````````````````````````````````
``` |
50,474,344 | I want to reverse digits in a number in python. Here are my two implementations.
**One:** convert the number into string and reverse each char in it
```
number = 2376674032
number_s = str(number)
index = len(number_s) - 1
str_list = []
while index > -1:
str_list.append(number_s[index])
index -= 1
result = int("".join(str_list))
print(result)
```
**Two:** using simple mathematics
```
number = 2376674032
N = 0
K = number
R = number % 10
while K > 0:
N = N*10 + R
K = K // 10
R = K % 10
result = N
print(result)
```
As I'm pretty new to python programming, so could someone help me with the following questions:
* with the first approach, will `"".join(str_list)` produce a new string with each list element? if so is a better way to concatenate strings in python(something similar to `StringBuffer` in java)
* which of the implementations is better from performance perspective? | 2018/05/22 | [
"https://Stackoverflow.com/questions/50474344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7929578/"
] | We can do this in a single line as well using [::-1]
print(int(str(int(input()))[::-1])) | ```
#here is my answer . you can do it using simple recursion
# count digits recursively
def reverse_digits(n):
# base case
if n == 0:
pass
#recursive case
else:
print(n%10,end='')
return reverse_digits(n//10)
# reverse 123
reverse_digits(123)
````````````````````````````````````````````````````
``` |
50,015,475 | I think I'm following the same online tutorial as what is mentioned in the post:
[How to convert deep learning gradient descent equation into python](https://stackoverflow.com/questions/45832369/how-to-convert-deep-learning-gradient-descent-equation-into-python)
I understand we have to calculate the cost and db but my question is why do they put axis=0 in both equations? In other words, I do not understand the axis=0, what is it used for in this calculation. What would be the result if you do the calculation without axis=0
```
import numpy as np
cost = -1*((np.sum(np.dot(Y,np.log(A))+np.dot((1-Y),(np.log(1-A))),axis=0))/m)
db = np.sum((A-Y),axis=0)/m
``` | 2018/04/25 | [
"https://Stackoverflow.com/questions/50015475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9491875/"
] | First create `Series` by shift column names, split by first whitespace and append `Date`, last filter only `Unnamed` index values and `rename` columns names:
```
s = df.columns.to_series().shift(-1).str.split(n=1).str[0] + ' Date'
s = s[s.index.str.startswith('Unnamed')]
print (s)
Unnamed: 0 233740 Date
Unnamed: 2 233160 Date
dtype: object
df = df.rename(columns=s)
print (df)
233740 Date 233740 KS Equity 233160 Date 233160 KS Equity
0 2015-12-17 10330.0 2017-08-31 10460.0
1 2015-12-18 10710.0 2017-09-01 10815.0
2 2015-12-21 10720.0 2017-09-04 10835.0
3 2015-12-22 10495.0 2017-09-05 10660.0
4 2015-12-23 10425.0 2017-09-06 10535.0
```
If need create 2 or 3 columns from all data first create `MultiIndex` by [`split`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html) and then call [`unstack`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html):
```
df.columns = df.columns.str.split(n=1, expand=True)
df = df.stack(0).reset_index(level=0, drop=True).rename_axis('val').reset_index()
print (df)
val Date KS Equity
0 233160 2017-08-31 10460.0
1 233740 2015-12-17 10330.0
2 233160 2017-09-01 10815.0
3 233740 2015-12-18 10710.0
4 233160 2017-09-04 10835.0
5 233740 2015-12-21 10720.0
6 233160 2017-09-05 10660.0
7 233740 2015-12-22 10495.0
8 233160 2017-09-06 10535.0
9 233740 2015-12-23 10425.0
```
EDIt:
Solution for multiple different headers:
```
#create dummy data
df1 = df.copy()
df1.columns = ['Unnamed: 4','233 JP Equity','Unnamed: 6','235 JP Equity']
df = df.join(df1)
print (df)
Unnamed: 0 233740 KS Equity Unnamed: 2 233160 KS Equity Unnamed: 4 \
0 2015-12-17 10330.0 2017-08-31 10460.0 2015-12-17
1 2015-12-18 10710.0 2017-09-01 10815.0 2015-12-18
2 2015-12-21 10720.0 2017-09-04 10835.0 2015-12-21
3 2015-12-22 10495.0 2017-09-05 10660.0 2015-12-22
4 2015-12-23 10425.0 2017-09-06 10535.0 2015-12-23
233 JP Equity Unnamed: 6 235 JP Equity
0 10330.0 2017-08-31 10460.0
1 10710.0 2017-09-01 10815.0
2 10720.0 2017-09-04 10835.0
3 10495.0 2017-09-05 10660.0
4 10425.0 2017-09-06 10535.0
s = df.columns.to_series().shift(-1) + ' Date'
s = s[s.index.str.startswith('Unnamed')]
print (s)
Unnamed: 0 233740 KS Equity Date
Unnamed: 2 233160 KS Equity Date
Unnamed: 4 233 JP Equity Date
Unnamed: 6 235 JP Equity Date
dtype: object
df = df.rename(columns=s)
```
In list comprehension groupby by first number, create dataetimeindex and concat together. Last reshape by `stack` and `unstack` for remove `NaN`s:
```
f = lambda x: x.split(' ',1)[1]
df = pd.concat([x.set_index(x.columns[0]).rename(columns=f) for i, x
in df.groupby(df.columns.str.split(n=1).str[0], axis=1)], 1).stack().unstack()
print (df)
JP Equity KS Equity
2015-12-17 10330.0 10330.0
2015-12-18 10710.0 10710.0
2015-12-21 10720.0 10720.0
2015-12-22 10495.0 10495.0
2015-12-23 10425.0 10425.0
2017-08-31 10460.0 10460.0
2017-09-01 10815.0 10815.0
2017-09-04 10835.0 10835.0
2017-09-05 10660.0 10660.0
2017-09-06 10535.0 10535.0
``` | If you are not happy with the automatic header generated by pandas from the first line of your file, you can skip it, tell pandas to not generate a header and provide your own.
Besides that, you can choose the columns to read in:
```
df_1 = pd.read_csv("price.csv", usecols = [0,1], skiprows=1, header=['date', 'equity'])
df_2 = pd.read_csv("price.csv", usecols = [2,3], skiprows=1, header=['date', 'equity'])
``` |
2,458,624 | Is there a way to abort a python write operation in such a way that the OS doesn't feel it's necessary to flush the unwritten data to the disc?
I'm writing data to a USB device, typically many megabytes. I'm using 4096 bytes as my block size on the write, but it appears that Linux caches up a bunch of data early on, and write it out to the USB device slowly. If at some point during the write, my user decides to cancel, I want the app to just stop writing immediately. I can see that there's a delay between when the data stops flowing from the application, and the USB activity light stops blinking. Several seconds, up to about 10 seconds typically. I find that the app is holding in the close() method, I'm assuming, waiting for the OS to finish writing the buffered data. I call flush() after every write, but that doesn't appear to have any impact on the delay. I've scoured the python docs for an answer but have found nothing. | 2010/03/16 | [
"https://Stackoverflow.com/questions/2458624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179157/"
] | It's somewhat filesystem dependent, but in some filesystems, if you delete a file before (all of) it is allocated, the IO to write the blocks will never happen. This might also be true if you truncate it so that the part which is still being written is chopped off.
Not sure that you can really abort a write if you want to still access the data. Also the kinds of filesystems that support this (e.g. xfs, ext4) are not normally used on USB sticks.
If you want to flush data to the disc, use fdatasync(). Merely flushing your IO library's buffer into the OS one will not achieve any physical flushing. | Assuming I am understanding this correct, you want to be able to 'abort' and NOT flush the data. This IS possible using a ctype and a little pokery. This is very OS dependent so I'll give you the OSX version and then what you can do to change it to Linux:
```
f = open('flibble1.txt', 'w')
f.write("hello world")
import ctypes
x = ctypes.cdll.LoadLibrary('/usr/lib/libc.dylib')
x.close(f.fileno())
try:
del f
catch IOError:
pass
```
If you change /usr/lib/libc.dylib to the libc.so.6 in /usr/lib for Linux then you should be good to go. Basically by calling close() instead of fclose(), no call to fsync() is done and nothing is flushed.
Hope that's useful. |
2,458,624 | Is there a way to abort a python write operation in such a way that the OS doesn't feel it's necessary to flush the unwritten data to the disc?
I'm writing data to a USB device, typically many megabytes. I'm using 4096 bytes as my block size on the write, but it appears that Linux caches up a bunch of data early on, and write it out to the USB device slowly. If at some point during the write, my user decides to cancel, I want the app to just stop writing immediately. I can see that there's a delay between when the data stops flowing from the application, and the USB activity light stops blinking. Several seconds, up to about 10 seconds typically. I find that the app is holding in the close() method, I'm assuming, waiting for the OS to finish writing the buffered data. I call flush() after every write, but that doesn't appear to have any impact on the delay. I've scoured the python docs for an answer but have found nothing. | 2010/03/16 | [
"https://Stackoverflow.com/questions/2458624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179157/"
] | It's somewhat filesystem dependent, but in some filesystems, if you delete a file before (all of) it is allocated, the IO to write the blocks will never happen. This might also be true if you truncate it so that the part which is still being written is chopped off.
Not sure that you can really abort a write if you want to still access the data. Also the kinds of filesystems that support this (e.g. xfs, ext4) are not normally used on USB sticks.
If you want to flush data to the disc, use fdatasync(). Merely flushing your IO library's buffer into the OS one will not achieve any physical flushing. | When you abort the write operation, trying doing `file.truncate(0);` before closing it. |
2,458,624 | Is there a way to abort a python write operation in such a way that the OS doesn't feel it's necessary to flush the unwritten data to the disc?
I'm writing data to a USB device, typically many megabytes. I'm using 4096 bytes as my block size on the write, but it appears that Linux caches up a bunch of data early on, and write it out to the USB device slowly. If at some point during the write, my user decides to cancel, I want the app to just stop writing immediately. I can see that there's a delay between when the data stops flowing from the application, and the USB activity light stops blinking. Several seconds, up to about 10 seconds typically. I find that the app is holding in the close() method, I'm assuming, waiting for the OS to finish writing the buffered data. I call flush() after every write, but that doesn't appear to have any impact on the delay. I've scoured the python docs for an answer but have found nothing. | 2010/03/16 | [
"https://Stackoverflow.com/questions/2458624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179157/"
] | Assuming I am understanding this correct, you want to be able to 'abort' and NOT flush the data. This IS possible using a ctype and a little pokery. This is very OS dependent so I'll give you the OSX version and then what you can do to change it to Linux:
```
f = open('flibble1.txt', 'w')
f.write("hello world")
import ctypes
x = ctypes.cdll.LoadLibrary('/usr/lib/libc.dylib')
x.close(f.fileno())
try:
del f
catch IOError:
pass
```
If you change /usr/lib/libc.dylib to the libc.so.6 in /usr/lib for Linux then you should be good to go. Basically by calling close() instead of fclose(), no call to fsync() is done and nothing is flushed.
Hope that's useful. | When you abort the write operation, trying doing `file.truncate(0);` before closing it. |
38,933,566 | I have a numpy array of 0's and 1's (512 x 512). I'd like to calculate the [centroid](https://en.wikipedia.org/wiki/Centroid) of the shape of 1's (they're all connected in one circular blob in the middle of the array).
```
for i in xrange(len(array[:,0])):
for j in xrange(len(array[0,:])):
if array[i,j] == 1:
x_center += i
y_center += j
count = (aorta == 1).sum()
x_center /= count
y_center /= count
```
Is there a way to speed up my calculation above? Could I use numpy.where() or something? Are there any python functions for doing this in parallel? | 2016/08/13 | [
"https://Stackoverflow.com/questions/38933566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789075/"
] | You can replace the two nested loops to get the coordinates of the center point, like so -
```
x_center, y_center = np.argwhere(array==1).sum(0)/count
``` | You could also use [`scipy.ndimage.measurements.center_of_mass`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.center_of_mass.html). |
38,933,566 | I have a numpy array of 0's and 1's (512 x 512). I'd like to calculate the [centroid](https://en.wikipedia.org/wiki/Centroid) of the shape of 1's (they're all connected in one circular blob in the middle of the array).
```
for i in xrange(len(array[:,0])):
for j in xrange(len(array[0,:])):
if array[i,j] == 1:
x_center += i
y_center += j
count = (aorta == 1).sum()
x_center /= count
y_center /= count
```
Is there a way to speed up my calculation above? Could I use numpy.where() or something? Are there any python functions for doing this in parallel? | 2016/08/13 | [
"https://Stackoverflow.com/questions/38933566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789075/"
] | You can replace the two nested loops to get the coordinates of the center point, like so -
```
x_center, y_center = np.argwhere(array==1).sum(0)/count
``` | ```
import numpy as np
x_c = 0
y_c = 0
area = array.sum()
it = np.nditer(array, flags=['multi_index'])
for i in it:
x_c = i * it.multi_index[1] + x_c
y_c = i * it.multi_index[0] + y_c
centroid = int(x_c/area), int(y_c/area)
```
Thats should be the centroid of a binary image using `numpy.nditer()` |
38,933,566 | I have a numpy array of 0's and 1's (512 x 512). I'd like to calculate the [centroid](https://en.wikipedia.org/wiki/Centroid) of the shape of 1's (they're all connected in one circular blob in the middle of the array).
```
for i in xrange(len(array[:,0])):
for j in xrange(len(array[0,:])):
if array[i,j] == 1:
x_center += i
y_center += j
count = (aorta == 1).sum()
x_center /= count
y_center /= count
```
Is there a way to speed up my calculation above? Could I use numpy.where() or something? Are there any python functions for doing this in parallel? | 2016/08/13 | [
"https://Stackoverflow.com/questions/38933566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789075/"
] | You could also use [`scipy.ndimage.measurements.center_of_mass`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.center_of_mass.html). | ```
import numpy as np
x_c = 0
y_c = 0
area = array.sum()
it = np.nditer(array, flags=['multi_index'])
for i in it:
x_c = i * it.multi_index[1] + x_c
y_c = i * it.multi_index[0] + y_c
centroid = int(x_c/area), int(y_c/area)
```
Thats should be the centroid of a binary image using `numpy.nditer()` |
33,078,764 | ```
class Class1(object):
def __init__(self, parameter1):
# action with parameter
def method1(self, parameter1):
# method actions
```
So what I want to happen is that I am able to make a `Class1` object without having loaded the `parameter1` yet and then when that has happened, I use `method1` to set `parameter1` and run actions with `method1` as `__init__` will use the results of `method1`. This is a python tutorial practice exam by the way so it has to be done this way.
EDIT:
```
>>>object1 = Class1()
>>>object1.method1(parameter1)
``` | 2015/10/12 | [
"https://Stackoverflow.com/questions/33078764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5404265/"
] | In order to allow a later initialization, you want to move all your actual initialization stuff into the method and make the parameter to the `__init__` optional. Then, if the parameter is specified, you can call the method or not.
```
class SomeClass (object):
def __init__ (self, param = None):
# do some general initialization, like initializing instance members
self.foo = 'bar'
# if the parameter is specified, call the init method
if param is not None:
self.init(param)
def init (self, param):
# do initialization stuff
```
Then, both of the following ways to create the object are equivalent:
```
x = SomeClass('param value')
y = SomeClass()
y.init('param value')
``` | If the idea is to be able to assign a value for the attribute at the method level and not in the initialization of the Class, I would suggest the following implementation:
```
class Class:
def __init__(self, parameter=None):
self.parameter=parameter
def method(self, parameter):
self.parameter = parameter
```
You can check that the attribute is certainly assigned through the method:
```
>>> c = Class1()
>>> c.method('whatever')
>>> print(c.parameter)
whatever
```
BTW in Python3 you don't need to explicitly inherit from `object` anymore, since already "[all classes inherit from object](https://docs.python.org/3/tutorial/classes.html)". |
35,271,594 | I can't install numpy for python3 via brew.
I type:
```
brew install numpy --with-python3
```
then it's OK for python2
```
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>>
```
but still not found for python3
```
Python 3.4.0 (v3.4.0:04f714765c13, Mar 15 2014, 23:02:41)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'numpy'
>>>
```
How to make it work for python3 ? | 2016/02/08 | [
"https://Stackoverflow.com/questions/35271594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681878/"
] | The correct way to install it is via:
```
pip3 install numpy
```
Obviously, you need to install python3 and pip first. I tested and works without any problem. | The problem with the Homebrew is that it sees only the system's python and the one it installed itself. So you have to first install python3 via brew and then use the --with-python3 option. |
8,425,373 | I'have a python project and I decide today put it on github.
I'm newbie with that. I see several tutorial. All work fine exept a thing I want to do:
I'm coding on my laptop in the day and on my computer I continue the work when I come back home.For now I create a repo on the laptop and I push it on my github. When I come back home on my computer I did a clone of the repo to continue working on the code. But when I push it on github again , all work fine exept I don't know how to "download" it on my laptop again to continue working in the next day.
The only things I find is to make a "cherry pick". I don't know if it's correct and how to process in this situation. | 2011/12/08 | [
"https://Stackoverflow.com/questions/8425373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967334/"
] | After you've cloned, `git pull` will update your local copy with the latest from the repository it was cloned from. See the [`git pull` section](http://schacon.github.com/git/user-manual.html#getting-updates-With-git-pull) of the manual for more information.
**Update for git gui:**
I encourage you to learn bash and the command-line interface for git, apart from being incredibly useful, it's easier to find support for them.
Looking at the "Pulling from a Remote Server" section of the git gui [tour](http://nathanj.github.com/gitguide/tour.html), it appears that pulling involves adding a remote (perhaps already done) and then selecting *Remote* -> *fetch from* -> *repository name*. | To put it on github from any computer use `push` to get it from github to any computer use `pull` |
57,976,489 | So I'm writting an application that needs to authenticate to a server using a client certificate (Mutual Authentication). The client certificate key is stored in an HSM (Gemalto's). I did the OpenSSL integration with the Luna Client but the requests module requires a file:
```py
from requests import Session
session: Session = Session()
session.cert = (
"/ssl/client.pem",
"/ssl/client.key"
)
session.verify = "/ssl/server.pem"
```
My issue is that I could not find a way to bind the private key when it's in the HSM. Here's what I tried so far with the [pycryptoki](https://github.com/gemalto/pycryptoki) library:
```py
from pycryptoki.session_management import (
c_initialize_ex,
c_open_session_ex,
login_ex,
c_logout_ex,
c_close_session_ex,
c_finalize_ex,
)
from requests import Session
c_initialize_ex()
auth_session = c_open_session_ex(0)
login_ex(auth_session, 0, "some-pass")
session: Session = Session()
session.cert = (
"/ssl/client.pem",
"rsa-private-156405640312",
)
session.verify = "/ssl/server.pem"
...
c_logout_ex(auth_session)
c_close_session_ex(auth_session)
c_finalize_ex()
```
I have opened an issue on there here a while back, I had to finish the app implementation so I put the HSM integration on the ice, but I need to make that work before going to production: <https://github.com/gemalto/pycryptoki/issues/17>
I also tried using [py-hsm](https://github.com/bentonstark/py-hsm/) but it is a low level api library, I also opened an [issue](https://github.com/bentonstark/py-hsm/issues/11#issuecomment-526778317) there with an example of my code:
```py
from pyhsm.hsmclient import HsmClient
from requests import Session
c = HsmClient(pkcs11_lib="/usr/lib/libCryptoki2_64.so")
c.open_session(slot=0)
c.login(pin="some-code")
session: Session = Session()
session.cert = "/ssl/client.pem"
c.logout()
c.close_session()
```
Anyone can provide an example of Mutual authentication with the certificate pair in an HSM? If you have something in C/C++ it would be great too, I could implement my request function and just wrap it in my python code.
Thank you in advance! | 2019/09/17 | [
"https://Stackoverflow.com/questions/57976489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431636/"
] | I have tested almost all wrappers for Python to do the same.
PyKCS11 is not really solid.
I recommend to use one of these two possibilities:
**1. PyCurl**
When you configure correctly your OpenSSL and so your cURL, the Python wrapper to cUrl can do this.
Here is a simple implementation:
```
import pycurl
from io import BytesIO
import pprint
import json
c = pycurl.Curl()
url = 'https://yourserver/endpoint'
c.setopt(pycurl.URL, url)
# set proxy-insecure
c.setopt(c.SSL_VERIFYPEER, 0)
c.setopt(c.SSL_VERIFYHOST, False)
c.setopt(c.VERBOSE, 0)
c.setopt(pycurl.SSLENGINE, 'pkcs11')
c.setopt(pycurl.SSLCERTTYPE, 'eng')
c.setopt(pycurl.SSLKEYTYPE, 'eng')
c.setopt(pycurl.SSLCERT, 'pkcs11:model=XXX;manufacturer=YYYYY;serial=ZZZZ;'
'token=AAAAA;id=BBBBBBBBB;'
'object=CCCCCC;type=cert;pin-value=pin-pin')
c.setopt(pycurl.SSLKEY, 'pkcs11:model=XXX;manufacturer=YYYYY;serial=ZZZZ;'
'token=AAAAA;id=BBBBBBBBB;'
'object=CCCCCC;type=private;pin-value=pin-pin')
# set headers
c.setopt(pycurl.HEADER, True)
# c.setopt(pycurl.USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0')
c.setopt(pycurl.HTTPHEADER, ("HEADER_TO_ADD:VALUE",))
buffer = BytesIO()
c.setopt(c.WRITEDATA, buffer)
c.perform()
# HTTP response code, e.g. 200.
print('>>> Status: %d' % c.getinfo(c.RESPONSE_CODE))
# Elapsed time for the transfer.
print('>>> Time: %f' % c.getinfo(c.TOTAL_TIME))
# getinfo must be called before close.
c.close()
body = buffer.getvalue().decode('utf-8')
print('>>> Body:\n', body)
if body.find('{') >= 0:
body = body[body.find('{'):]
dictionary = json.loads(body)
pprint.pprint(dictionary)
```
Note that the pkcs#11 URI Scheme must be compliant to the [RFC7512](https://www.rfc-editor.org/rfc/rfc7512)
It can be discovered using this command:
```
p11tool --provider=/usr/lib/libeTPkcs11.so --list-all
```
All fields including the pin must be url encoded. Use an online website to encode/decode string(pin)<->url\_encoded
**2. M2Crypto**
This is the best pkcs#11 implementation done for Python in my point of view.
It allows to override urllib2 and so requests calls thanks to the requests.Session.mount method and the requests.adapters.BaseAdapter.
I put here some code to use it with urllib2:
```
from M2Crypto import m2urllib2 as urllib2
from M2Crypto import m2, SSL, Engine
# load dynamic engine
e = Engine.load_dynamic_engine("pkcs11", "/usr/lib/x86_64-linux-gnu/engines-1.1/libpkcs11.so")
pk = Engine.Engine("pkcs11")
pk.ctrl_cmd_string("MODULE_PATH", "/usr/lib/libeTPkcs11.so")
m2.engine_init(m2.engine_by_id("pkcs11"))
pk.ctrl_cmd_string("PIN", 'pin-pin')
cert = pk.load_certificate('pkcs11:model=XXX;manufacturer=YYYYY;serial=ZZZZ;'
'token=AAAAA;id=BBBBBBBBB;'
'object=CCCCCC')
key = pk.load_private_key('pkcs11:model=XXX;manufacturer=YYYYY;serial=ZZZZ;'
'token=AAAAA;id=BBBBBBBBB;'
'object=CCCCCC', pin='pin-pin')
ssl_context = SSL.Context('tls')
ssl_context.set_cipher_list('EECDH+AESGCM:EECDH+aECDSA:EECDH+aRSA:EDH+AESGCM:EDH+aECDSA:EDH+aRSA:!SHA1:!SHA256:!SHA384:!MEDIUM:!LOW:!EXP:!aNULL:!eNULL:!PSK:!SRP:@STRENGTH')
ssl_context.set_default_verify_paths()
ssl_context.set_allow_unknown_ca(True)
SSL.Connection.postConnectionCheck = None
m2.ssl_ctx_use_x509(ssl_context.ctx, cert.x509)
m2.ssl_ctx_use_pkey_privkey(ssl_context.ctx, key.pkey)
opener = urllib2.build_opener(ssl_context)
urllib2.install_opener(opener)
url = 'https://yourserver/endpoint'
content = urllib2.urlopen(url=url).read()
# content = opener.open(url)
print(content)
```
Note that, we don't indicate type and pin in the pkcs#11 URI as for PyCurl.
The PIN is indicated as string and not url encoded when passed to load\_private\_key.
Finally, I found a good implementation for the HttpAdapter to mount on requests to do the calls.
[Here](https://github.com/cedric-dufour/scriptisms/blob/master/misc/m2requests.py) is the original implementation.
I added some lines to support the PIN code and to disable checking hostname with this:
```
M2Crypto.SSL.Connection.postConnectionCheck = None
```
And here is how to mount the adapter:
```
from requests import Session
from m2requests import M2HttpsAdapter
import pprint, json
request = Session()
m2httpsadapter = M2HttpsAdapter()
# Added by me to set a pin when loading private key
m2httpsadapter.pin = 'pin-pin'
# Need this attribute set to False else we cannot use direct IP (added by me to disable checking hostname)
m2httpsadapter.check_hostname = False
request.mount("https://", m2httpsadapter)
request.cert=('pkcs11:model=XXX;manufacturer=YYYYY;serial=ZZZZ;'
'token=AAAAA;id=BBBBBBBBB;'
'object=CCCCCC',
'pkcs11:model=XXX;manufacturer=YYYYY;serial=ZZZZ;'
'token=AAAAA;id=BBBBBBBBB;'
'object=CCCCCC')
headers = {'HEADER_TO_ADD_IF_WANTED': 'VALUE', }
r = request.get("https://yourserver/endpoint", headers=headers, verify=False)
print(r.status_code)
pprint.pprint(json.loads(r.raw.data.decode('utf-8')))
``` | A private key in an HSM can be used to sign some data, which is what you are trying to accomplish for mutual authentication. Signing some data provided by the other party proves that you control the Private Key corresponding to the certificate.
From the HSM you can get a handle to the private key and use that handle to perform private key operations without exporting the key (the whole reason for using an HSM is to prevent the content of the private key from being seen).
HSMs can expose a lot of different interfaces but PKCS#11 is by far the most common. You don't really need to use OpenSSL or to program in C/C++. Since you are using Python requests, there are some PKCS#11 Python libraries that can be used.
Please take a look at this Python PKCS11 library: <https://github.com/danni/python-pkcs11>.
You can then do things like (assuming the key is RSA)
```
import pkcs11
lib = pkcs11.lib("/usr/lib/libCryptoki2_64.so")
token = lib.get_token(token_label='DEMO')
# Open a session on our token
with token.open(user_pin='1234') as session:
# Get the key from the HSM by label
priv = session.get_key(
object_class=pkcs11.constants.ObjectClass.PRIVATE_KEY,
label='key_label')
# sign with that key using the required mechanism:
signature = priv.sign(my_to_be_signed_data, mechanism=pkcs11.Mechanism.SHA256_RSA_PKCS)
```
You do not provide many details about this mutual authentication but hopefully, this should get you on the right track. The code above retrieves the key based on a label, but this PKCS#11 library also supports finding a key in the HSM based on a lot of other properties. |